From 2996ff3b370bad61c1c4a45ba3b41cb44731bec3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 20:00:21 +0000 Subject: [PATCH] CM4: commerce becomes an Orun baseline, in one landing The repository is now a baseline: blueprint.yaml (the console card) and repo-blueprint.yaml (the build) take a new storefront from nothing to live on stage and prod in TWO phases, cirrus-baseline v22's one-landing shape, ported from kv-redis-starter's conversion: - 01-product places every module (root files, CI, tooling, the R2 root, the storefront, its tests), retouches, brands, re-tenants, strips the work tree, defers prod's promotion gate and dev's push lanes, confirms the lockfile, ensures and links the repository, reconciles three brokered keys - CLOUDFLARE_API_TOKEN (workers-deploy), CLOUDFLARE_R2_TOKEN (r2-data) and CLOUDFLARE_ACCOUNT_ID (account-id) - and lands it as one pull request; it then watches the merge's convergence, checks WIRING_CLOUDFLARE_R2 exists on stage and prod, and probes both URLs. - 02-docs is hook-only: restores the two deferrals, renders the deployment record from probed facts, lands it. INFRA BEFORE APP. apps/web depends on cloudflare-r2 with mode: enforced (advisory on github-pull-request), so the product's own push-to-main plan applies the bucket at lane level 0 and deploys each Worker at level 1, waiting on its own environment's apply alone. THE R2 KEY. workers-deploy grants Workers Scripts and KV and no R2, so the R2 root now binds its provider token to CLOUDFLARE_R2_TOKEN, minted from r2-data by its own reconcile hook; the card's spec.secrets mirrors it. NO THIRD-PARTY KEY ON A FRESH BUILD. Shopify is not a provider the platform brokers, so every function lib/shopify exports is now a switch: with SHOPIFY_STORE_DOMAIN set, upstream's cached Storefront API reader; unset, lib/demo - a bundled catalogue (six products with variants, collections, menus, pages, SVG images) and a cookie cart priced from it. The switch is outside "use cache", so no demo answer outlives a connected store. A /cart page renders the cart on the server; /checkout answers 200 with "Connect a payment provider to enable checkout" (or forwards to Shopify's checkout); a banner says the store is a demo. The product's README documents connecting Shopify (three Worker secrets, the webhooks). The port's latent faults, fixed: wrangler.jsonc committed as the fixture render (verify-app-structure checks it before the build); dev renders the fixture; packages/.gitkeep; Next 16's Promise params in the two image routes; the sitemap's 500 without a store. No SITE_URL: metadata, robots and the sitemap are built on the request's origin. The store's name and source link are apps/web/app/site.ts. The slug is an English word, so no shipped file spells it (or "Commerce") outside an identity form, and the leak gate holds that. Verified: the contract tests, the leak gate (v2.58.11, v2.79.0), placement with the product's own plan (v2.78.4, v2.79.0), the e2e (v2.78.4, v2.79.0: the stage lane in the staged tree, wrangler dev, the smoke, browse to a product, add it to the cart through the build's server action, check out to the payment-provider notice), orun new --status at three versions, orun validate, orun work check, terraform validate, and the repository's own Checks. Not verified: a live bootstrap, or a real Shopify store. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AuyckrXahuAVgdmxamUUtk --- .baseline/identity.json | 9 + .baseline/product/README.md | 174 +++++ .baseline/tasks/01-product.TaskContract.yaml | 27 + .baseline/tasks/02-docs.TaskContract.yaml | 13 + .github/workflows/baseline.yml | 136 ++++ .github/workflows/checks.yml | 24 +- .github/workflows/ci.yml | 38 +- .github/workflows/tag.yml | 97 +++ .gitignore | 6 +- BOOTSTRAP.md | 256 +++++++ README.md | 169 +++-- ai/context/deployment.md | 7 + ai/context/operations.md | 159 ++++ apps/web/.dev.vars.example | 11 - apps/web/.env.example | 24 +- apps/web/README.md | 104 +-- apps/web/app/[page]/opengraph-image.tsx | 12 +- apps/web/app/cart/page.tsx | 102 +++ apps/web/app/checkout/page.tsx | 75 ++ apps/web/app/layout.tsx | 40 +- apps/web/app/page.tsx | 2 +- apps/web/app/robots.ts | 11 +- .../search/[collection]/opengraph-image.tsx | 5 +- apps/web/app/site.ts | 25 + apps/web/app/sitemap.ts | 8 +- apps/web/component.yaml | 40 +- apps/web/components/cart/actions.ts | 5 +- apps/web/components/demo-banner.tsx | 21 + apps/web/components/icons/logo.tsx | 3 +- apps/web/components/layout/footer.tsx | 24 +- apps/web/components/layout/navbar/index.tsx | 3 +- apps/web/components/opengraph-image.tsx | 10 +- apps/web/components/welcome-toast.tsx | 19 +- apps/web/lib/demo/catalogue.ts | 290 ++++++++ apps/web/lib/demo/index.ts | 304 ++++++++ apps/web/lib/shopify/index.ts | 163 +++-- apps/web/lib/utils.ts | 10 +- apps/web/public/demo/bucket-tote.svg | 6 + apps/web/public/demo/cache-mug.svg | 7 + apps/web/public/demo/cloud-tee-black.svg | 4 + apps/web/public/demo/cloud-tee-white.svg | 4 + apps/web/public/demo/edge-hoodie.svg | 6 + apps/web/public/demo/origin-sticker-pack.svg | 8 + apps/web/public/demo/worker-cap.svg | 6 + apps/web/wiring.fixture.json | 3 + apps/web/wrangler.jsonc | 52 ++ apps/web/wrangler.template.jsonc | 35 +- blueprint.yaml | 151 ++++ docs/phases/01-product.md | 75 ++ docs/phases/02-docs.md | 40 ++ docs/phases/README.md | 107 +++ hooks/render-deployment-docs.sh | 189 +++++ infra/terraform/cloudflare-r2/component.yaml | 11 +- .../terraform/cloudflare-r2/terraform/main.tf | 13 +- intent.yaml | 28 +- packages/.gitkeep | 0 repo-blueprint.yaml | 677 ++++++++++++++++++ specs/epics/README.md | 2 +- specs/epics/commerce/IMPLEMENTATION-STATUS.md | 107 ++- specs/epics/commerce/README.md | 7 +- specs/epics/commerce/design.md | 107 ++- specs/epics/commerce/epic.yaml | 8 + specs/epics/commerce/implementation-plan.md | 46 +- .../commerce/risks-and-open-questions.md | 92 +++ tasks/CM-1.TaskContract.yaml | 3 + tasks/CM-2.TaskContract.yaml | 3 + tasks/CM-3.TaskContract.yaml | 3 + tasks/CM-4.TaskContract.yaml | 3 + tasks/CM-5.TaskContract.yaml | 37 + testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 177 +++++ testing/e2e.test.sh | 358 +++++++++ testing/fixtures/acme.json | 23 + .../fixtures/baseline-identity.commerce.json | 9 + testing/leak.test.sh | 203 ++++++ testing/lib/bootstrap.sh | 60 ++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 82 +++ testing/manifest.test.sh | 432 +++++++++++ testing/phases.test.sh | 351 +++++++++ testing/placement.test.sh | 360 ++++++++++ testing/rebrand.test.sh | 196 +++++ testing/retouch.test.sh | 199 +++++ testing/wire.test.sh | 188 +++++ tests/web/src/demo.test.ts | 132 ++++ tests/web/src/shopify.test.ts | 35 +- tests/web/src/site.test.ts | 37 + tests/web/src/utils.test.ts | 23 +- tooling/bootstrap/dev-lanes.mjs | 114 +++ tooling/bootstrap/promotion.mjs | 123 ++++ tooling/bootstrap/retouch.mjs | 254 +++++++ tooling/bootstrap/work-tree.mjs | 73 ++ tooling/rebrand/rebrand.mjs | 468 ++++++++++++ tooling/rebrand/values.example.json | 8 + tooling/wire/live.mjs | 30 +- tooling/wire/render.mjs | 12 +- 96 files changed, 7961 insertions(+), 391 deletions(-) create mode 100644 .baseline/identity.json create mode 100644 .baseline/product/README.md create mode 100644 .baseline/tasks/01-product.TaskContract.yaml create mode 100644 .baseline/tasks/02-docs.TaskContract.yaml create mode 100644 .github/workflows/baseline.yml create mode 100644 .github/workflows/tag.yml create mode 100644 BOOTSTRAP.md create mode 100644 ai/context/deployment.md create mode 100644 ai/context/operations.md delete mode 100644 apps/web/.dev.vars.example create mode 100644 apps/web/app/cart/page.tsx create mode 100644 apps/web/app/checkout/page.tsx create mode 100644 apps/web/app/site.ts create mode 100644 apps/web/components/demo-banner.tsx create mode 100644 apps/web/lib/demo/catalogue.ts create mode 100644 apps/web/lib/demo/index.ts create mode 100644 apps/web/public/demo/bucket-tote.svg create mode 100644 apps/web/public/demo/cache-mug.svg create mode 100644 apps/web/public/demo/cloud-tee-black.svg create mode 100644 apps/web/public/demo/cloud-tee-white.svg create mode 100644 apps/web/public/demo/edge-hoodie.svg create mode 100644 apps/web/public/demo/origin-sticker-pack.svg create mode 100644 apps/web/public/demo/worker-cap.svg create mode 100644 apps/web/wrangler.jsonc create mode 100644 blueprint.yaml create mode 100644 docs/phases/01-product.md create mode 100644 docs/phases/02-docs.md create mode 100644 docs/phases/README.md create mode 100755 hooks/render-deployment-docs.sh create mode 100644 packages/.gitkeep create mode 100644 repo-blueprint.yaml create mode 100644 tasks/CM-5.TaskContract.yaml create mode 100755 testing/bootstrap-defer.test.sh create mode 100755 testing/coverage.test.sh create mode 100755 testing/e2e.test.sh create mode 100644 testing/fixtures/acme.json create mode 100644 testing/fixtures/baseline-identity.commerce.json create mode 100755 testing/leak.test.sh create mode 100644 testing/lib/bootstrap.sh create mode 100755 testing/lib/run-hooks.py create mode 100755 testing/lib/stage-job.py create mode 100755 testing/manifest.test.sh create mode 100755 testing/phases.test.sh create mode 100755 testing/placement.test.sh create mode 100755 testing/rebrand.test.sh create mode 100755 testing/retouch.test.sh create mode 100755 testing/wire.test.sh create mode 100644 tests/web/src/demo.test.ts create mode 100644 tests/web/src/site.test.ts create mode 100755 tooling/bootstrap/dev-lanes.mjs create mode 100644 tooling/bootstrap/promotion.mjs create mode 100644 tooling/bootstrap/retouch.mjs create mode 100644 tooling/bootstrap/work-tree.mjs create mode 100644 tooling/rebrand/rebrand.mjs create mode 100644 tooling/rebrand/values.example.json diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..c393c97 --- /dev/null +++ b/.baseline/identity.json @@ -0,0 +1,9 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `productName` is the SITE_NAME seam in apps/web/app/site.ts; `slug` also names the R2 bucket names (terraform `repo`), the Worker and its self-reference binding, and the secret project — and, being an English word, it may appear NOWHERE ELSE in a shipped file (the rename would rewrite it), nor may the capitalised `pascal` form (the leftover sweep fails on it); `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in SOURCE_URL.", + "slug": "commerce", + "pascal": "Commerce", + "productName": "Next.js Commerce", + "domain": "commerce.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/.baseline/product/README.md b/.baseline/product/README.md new file mode 100644 index 0000000..7552194 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,174 @@ +# commerce + +A headless storefront — home, search, collections, product pages and a cart — +on **Cloudflare Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), built from +Vercel's open-source Next.js storefront template (MIT, `apps/web/license.md`). +The Next.js data cache lives in an **R2 bucket** that Terraform provisions per +environment, and its tag cache and revalidation queue in **Durable Objects** +the Worker itself exports. + +It is live from its first deploy with no third-party key: until you connect a +Shopify store it serves a **bundled demo catalogue** (six sample products, two +collections, menus and pages) and keeps the cart in a cookie, and checkout +says plainly that a payment provider must be connected first. + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace and the secrets inventory into +[ai/context/deployment.md](ai/context/deployment.md); how the store deploys +and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## What is here + +| Surface | Where | +|---|---| +| Home, `/search`, `/search/[collection]`, `/product/[handle]`, `/cart`, `/checkout`, `/[page]`, OG images, sitemap, robots | `apps/web/app` | +| The store's name and source link | `apps/web/app/site.ts` | +| The Shopify client (`"use cache"` readers, cart mutations, the webhook's `revalidate`) — and the switch to the demo when no store is connected | `apps/web/lib/shopify` | +| The demo catalogue and the cookie cart | `apps/web/lib/demo`, images in `apps/web/public/demo` | +| Cart (server actions, optimistic context, modal), navbar, grid, product gallery | `apps/web/components` | +| Workers build, cache bindings and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ `wrangler.jsonc`), `component.yaml` | +| The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` | +| Tests | `tests/web` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +```bash +pnpm --filter @app/web dev # http://localhost:3000, Next's dev server +pnpm --filter @app/web preview # wrangler dev over the built Worker, a local R2 bucket and local Durable Objects +``` + +With no Shopify facts in the environment both serve the demo catalogue. Make +the store yours in `apps/web/app/site.ts` (its name and the repository the +footer links to); the demo's products are `apps/web/lib/demo/catalogue.ts`. + +## Connecting Shopify + +The storefront reads one store through the Shopify Storefront API. Shopify is +not a provider the platform brokers, so you connect it yourself, once, after +the store is live: + +1. **In Shopify**, create a Storefront API access token (Settings → Apps and + sales channels → Develop apps, or the Headless channel), and set up what + the storefront reads by handle: the menus `next-js-frontend-header-menu` + and `next-js-frontend-footer-menu`, and the collections + `hidden-homepage-featured-items` (the home page's three-item grid) and + `hidden-homepage-carousel` (its carousel). Collections whose handle starts + with `hidden` never appear in search; products tagged + `nextjs-frontend-hidden` are left out of listings. +2. **Give each environment's Worker the store's three facts** as Worker + secrets. The deploy lane never sets or clears them, so this is once: + + ```bash + cd apps/web + for env in stage prod; do + wrangler secret put SHOPIFY_STORE_DOMAIN --name commerce-web-$env # your-store.myshopify.com + wrangler secret put SHOPIFY_STOREFRONT_ACCESS_TOKEN --name commerce-web-$env + wrangler secret put SHOPIFY_REVALIDATION_SECRET --name commerce-web-$env # any long random string + done + ``` + + Setting a secret publishes a new version of the Worker; its next request + reads the store. The demo banner goes, the catalogue, menus, pages and cart + are Shopify's, and nothing is rebuilt. Demo answers were never cached, so + none outlives the switch. +3. **Register Shopify's webhooks** (Settings → Notifications → Webhooks) for + `products/create`, `products/update`, `products/delete`, + `collections/create`, `collections/update` and `collections/delete`, + pointing at + `https://commerce-web-prod.your-workers-subdomain.workers.dev/api/revalidate?secret=` + (and the stage URL, if stage has a store of its own). Each delivery + revalidates the `products` or `collections` tag in the Durable Object tag + cache; the next request re-renders from Shopify. + +Product images then come from `cdn.shopify.com`, which `next.config.ts` +already allows. To use another store backend instead, replace the functions +`lib/shopify/index.ts` exports — `lib/demo` is a complete second +implementation of the same surface to copy from. + +## Checkout and payments + +The storefront never takes payment itself. With Shopify connected, "Proceed to +Checkout" sends the shopper to the cart's Shopify-hosted checkout, which takes +payment through whichever payment provider the Shopify store has enabled +(Shopify Payments or another, in the Shopify admin under Settings → +Payments). Without a store there is no payment provider: `/checkout` answers +with a notice — "Connect a payment provider to enable checkout" — the cart is +kept on the shopper's device, and nothing is charged. + +## How the cache is wired + +The Worker binds the bucket as `NEXT_INC_CACHE_R2_BUCKET` (every `"use cache"` +entry and pre-rendered page), and two Durable Objects: `NEXT_TAG_CACHE_DO_SHARDED` +(which tags were revalidated, and when) and `NEXT_CACHE_DO_QUEUE` (background +revalidation of stale routes, through the Worker's own +`WORKER_SELF_REFERENCE` binding). The bucket's name is never hand-written: +`apps/web/wrangler.template.jsonc` names it as a wiring token, and +`wrangler.jsonc` is that template rendered — from `wiring.fixture.json` for +local work and verification, and on every deploy from the document the +`cloudflare-r2` Terraform root publishes after its apply +(`WIRING_CLOUDFLARE_R2`, per environment). Edit the template, then +`pnpm run wire:fixture`; Checks fails if the committed `wrangler.jsonc` is not +the fixture render. The Durable Objects need no root: the migration in the +config creates them on the first deploy. + +## How it deploys + +Merges to `main` converge through [Orun](https://github.com/sourceplane/orun): +`.github/workflows/ci.yml` plans the changed components and runs each lane +against the workspace in `intent.yaml`. The R2 bucket applies first, then the +storefront builds with that environment's bucket name and deploys — to +`stage`, then to `prod` once stage has converged on the same commit; `dev` +only verifies. The Worker is `commerce-web-` on your account's +workers.dev subdomain, and every deploy is smoke-tested over HTTP: the home +page must answer, and `robots.txt` must name the origin it was asked on, which +only the Worker renders. `checks.yml` runs install, the fixture render, +typecheck, lint, test and build on every pull request. (A push to `main` runs +`ci.yml` alone, which applies, builds and deploys.) + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The Cloudflare +tokens and account id are brokered per run from the workspace's Cloudflare +connection — one to deploy the Worker, one with R2 access for the bucket's +apply — and the bucket names travel as Orun secrets; nothing provider-shaped +is stored in the repository or in GitHub. Shopify's facts are Worker secrets, +set once on the Workers themselves. + +## How it maps to Vercel + +| Vercel | Here | +|---|---| +| Next.js hosting (SSR, server actions, route handlers, `next/og`) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets (`ASSETS`) | +| Data Cache: `"use cache"` entries with `cacheLife("days")` | The R2 bucket bound as `NEXT_INC_CACHE_R2_BUCKET`, written at request time | +| Tag revalidation from the Shopify webhook, `updateTag` from cart actions | A sharded Durable Object tag cache consulted on every cache read | +| Stale-while-revalidate (ISR) | A Durable Object queue that re-renders stale routes through the Worker | +| `VERCEL_PROJECT_PRODUCTION_URL` | Nothing: absolute URLs are built on the request's origin (`app/site.ts`) | +| Shopify integration env vars | Worker secrets (above); the demo catalogue until they are set | +| Deploy on push | Orun applies the bucket and deploys `commerce-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | + +Partial prerendering is off: `@opennextjs/cloudflare` 1.20 cannot run Next 16's +Cache Components on workerd yet, so the storefront keeps the template's +`"use cache"` directives through `experimental.useCache` and renders every +route at request time. + +## Custom domain + +The store answers on workers.dev from its first deploy. To serve it on your +own domain, add the domain to the Cloudflare account the store deploys into +and attach it to the Worker (dashboard → Workers & Pages → +`commerce-web-prod` → Settings → Domains & Routes → Add → Custom domain), and +point Shopify's webhooks at it. Nothing in the repository changes: the store +builds its absolute links from the request it is answering. diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..84c7155 --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,27 @@ +# Task contract template for the 01-product landing. +# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to +# the key the allocator issues. It lives under `.baseline/`, not `tasks/`, +# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`), +# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge +# alone finishes this task; the main convergence is the gate the bootstrap +# watches, not one the plane observes as a PR check. +# +# The whole product in one landing. `affects` names COMPONENTS, by +# metadata.name: the phase's retouch hook reads this list to decide which +# component.yaml files get the redeploy marker, so a re-run of the phase has a +# diff and exactly these components are re-planned — the deploy set and the +# task plane's statement of the work are one list. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The product's repository is born and linked, the whole product lands in one pull request, and one convergence applies the R2 cache bucket and deploys the storefront on stage and prod + affects: + - cloudflare-r2 + - web + - web-tests + doneWhen: + - repo pushed, main pinned as default, workspace linked + - WIRING_CLOUDFLARE_R2 published on stage and prod + - main convergence green (R2 applied, then the storefront built, deployed and smoke-tested on stage and prod) + - the storefront answers on both workers.dev URLs + gates: [] diff --git a/.baseline/tasks/02-docs.TaskContract.yaml b/.baseline/tasks/02-docs.TaskContract.yaml new file mode 100644 index 0000000..d62a6e7 --- /dev/null +++ b/.baseline/tasks/02-docs.TaskContract.yaml @@ -0,0 +1,13 @@ +# Task contract template for the 02-docs landing. See 01-product's header. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The live deployment is recorded from verified facts as agent-readable state in the product's repo + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + doneWhen: + - committed deployment manifest matches probed reality + - prod waits on stage again, and dev verifies every merge to main again + gates: [] diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml new file mode 100644 index 0000000..0f32a3d --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,136 @@ +name: Baseline CI + +# THE FACTORY'S OWN LANES — this repository tested as a BASELINE: that its +# build document parses with the orun a bootstrap actually runs, that its card +# agrees with it, that every component is placed by the one product phase, +# that the R2 bucket's wiring reaches the Worker's config, that a placed +# tree comes up branded and carrying nothing of the factory — and plans the +# bucket before the Worker on a merge — and that the product it produces +# installs, builds, deploys (dry), serves, and takes a cart. +# +# ─── WHY THIS IS NOT IN ci.yml OR checks.yml ────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every site built from this repository. These jobs run +# `testing/*.sh`, and `testing/` is deliberately not placed — so in a site they +# would be steps that cannot pass, red on its very first pull request. This +# file is in the blueprint's `ignore` list, and `testing/coverage.test.sh` +# fails on any workflow that reads `testing/` and is not. + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: baseline-ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + # Tier 0. bash, python3 and git; node for the tools. No workspace install, + # no network, no credential — the job that most certainly fails a PR. + baseline-contract: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v5 + with: + node-version: 22 + # setup-node v5 turns on the pnpm cache by itself when package.json + # names a packageManager, and then fails on a runner with no pnpm. + # This job installs nothing. + package-manager-cache: false + - name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer, wire) + run: | + set -euo pipefail + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + for t in manifest phases coverage rebrand retouch bootstrap-defer wire; do + echo "── $t" + bash "testing/$t.test.sh" + done + + # Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS. + # + # Pinned at the bootstrap floor (BOOTSTRAP.md), not the site's lane pin: + # every test here reads YAML with PyYAML, which parses anything well-formed; + # only the pinned orun can say whether the document is one a bootstrap can + # run. `--status` parses it, validates every hook against the action + # registry, compiles every `when` and narration template, and writes + # nothing. Then the leak gate (what a product would carry, derived by the + # floor too), and the placement tier (the offline bootstrap: both phases + # placed and finished by the blueprint's own hooks, then the product's own + # `orun plan` for the 01-product merge — the R2 apply before the Worker's + # deploy — under the product's lane pin, below). + blueprint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.58.11 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - name: repo-blueprint.yaml, read by the pinned CLI + run: | + set -euo pipefail + orun --version + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + # Required inputs must be supplied for the document to resolve; the + # values are arbitrary and nothing is written. + orun new --blueprint repo-blueprint.yaml --status \ + --out "$(mktemp -d)" \ + --set reponame=acme-shop \ + --set "productname=Acme Shop" \ + --set productdomain=shop.acme.dev \ + --set githuborg=acme-inc + - name: the leak gate — what a product carries + run: bash testing/leak.test.sh + # The placement tier ENDS with the product's own `orun plan` — what the + # product's ci.yml runs — so it runs under the product's lane pin, not + # the bootstrap floor. v2.58.11 plans a pull request with apps/web + # waiting on the R2 plan: it does not apply a dependsOn edge's + # `modeRules`. The lane pin does (advisory on a PR, enforced on main), + # and the test refuses an orun older than the pin rather than assert + # the wrong CLI's plan. Its placements are valid under either. + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.78.4 + - name: placement — the offline bootstrap, and the product's own plan + run: | + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/placement.test.sh + + # Tier 2. THE PRODUCT IT PRODUCES WORKS: its one landing under the checks + # its pull request waits on, the stage lane's own structure check, build + # (the live wiring render included), output check and dry deploy in the tree + # orun stages, and the built Worker served and smoke-tested with the + # component's own smoke command. Pinned at the product's lane version, + # because that is the orun the product's CI runs. + site: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.78.4 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - name: e2e — the bootstrapped product builds, deploys (dry) and serves + run: | + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/e2e.test.sh diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index bd8d5df..1426539 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -1,14 +1,21 @@ name: Checks # Credential-free verification: install, render the offline wrangler fixtures, -# typecheck, lint, test and build. Runs on every push and pull request and is -# the merge gate until the product is linked to an Orun workspace, at which -# point `ci.yml` (Orun plan/run with brokered Cloudflare credentials) takes -# over — it stays gated behind the `ORUN_CI` repository variable until then. +# typecheck, lint, test and build, on every pull request, linked or not. +# `ci.yml` is the Orun pipeline beside it (plan/run with brokered Cloudflare +# credentials, deploys on merge); it plans nothing until intent.yaml names a +# workspace. +# +# PULL REQUESTS ONLY — not pushes to main. A push to main must start exactly +# one workflow, `ci.yml`, because the bootstrap's convergence watch +# (`orun.run/watch@v1` with `sha:`) takes the newest run for the merge commit +# from ANY workflow. With this one on push too, the first live bootstrap +# watched this run go green while ci.yml's deploy lanes had failed, and called +# the site converged. On main the convergence builds and tests the site +# anyway. The baseline's coverage gate holds the rule. on: - push: - branches: [main] pull_request: + workflow_dispatch: concurrency: group: checks-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} @@ -33,6 +40,11 @@ jobs: # Templated deployables render their wrangler config from the committed # fixture; an unresolved wiring token fails here, not at deploy time. - run: pnpm run wire:fixture + # …and the render is what is committed. The deploy lane checks that the + # config exists before it builds, so wrangler.jsonc is in the tree as the + # fixture render; a template edited without re-rendering fails here. + - name: the committed wrangler config is the fixture render + run: git diff --exit-code - run: pnpm typecheck - run: pnpm lint - run: pnpm test diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 027b0c4..e262a92 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,6 @@ permissions: jobs: plan: - if: ${{ vars.ORUN_CI == 'true' }} runs-on: ubuntu-latest outputs: lane-matrix: ${{ steps.matrix.outputs.lane-matrix }} @@ -33,10 +32,31 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - - uses: sourceplane/orun-action@v1.2.0 + # A TREE THAT NAMES NO WORKSPACE PLANS NOTHING. `ws_CHANGE_ME` is the + # placeholder this repository ships with until someone links it; every + # remote op of a plan here would be refused, so the job says so and + # stops green, and `run` below has no lanes to start. A site built from + # this baseline never carries the placeholder — its bootstrap writes the + # product's own workspace into intent.yaml — and a bootstrap that had no + # workspace to write leaves `ws_SET_ME`, which is NOT skipped: it fails + # here loudly rather than deploying nothing in silence. + # + # This replaced an `ORUN_CI` repository variable, which a bootstrap has + # no way to set: every site it built would have converged on nothing. + - id: linked + run: | + if grep -Eq '^[[:space:]]*workspace:[[:space:]]*ws_CHANGE_ME[[:space:]]*$' intent.yaml; then + echo "::notice title=Orun CI::intent.yaml names no Orun workspace (ws_CHANGE_ME) — nothing to plan. Link this repository (orun cloud link) and set execution.state.workspace to turn the pipeline on." + echo "linked=false" >> "$GITHUB_OUTPUT" + else + echo "linked=true" >> "$GITHUB_OUTPUT" + fi + - if: steps.linked.outputs.linked == 'true' + uses: sourceplane/orun-action@v1.2.0 with: - version: v2.78.0 - - env: + version: v2.78.4 + - if: steps.linked.outputs.linked == 'true' + env: # Surface the best-effort catalog auto-sync (execution.state.autopushCatalog). # A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes # any skip/failure visible instead of silent. @@ -57,11 +77,13 @@ jobs: # without lanes gets one per job, exactly the old matrix, and # `orun run --lane ` on it is `--job `. - id: matrix + if: steps.linked.outputs.linked == 'true' run: | echo "lane-matrix=$(jq -c 'if ((.lanes // []) | length) > 0 then [.lanes[] | {"lane": .id, "name": .name}] else [.jobs[] | {"lane": .id, "name": .checkName}] end' plan.json)" >> "$GITHUB_OUTPUT" - - uses: actions/upload-artifact@v7 + - if: steps.linked.outputs.linked == 'true' + uses: actions/upload-artifact@v7 with: name: orun-plan path: plan.json @@ -124,7 +146,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.78.0 + version: v2.78.4 # exec-id is the RUN id alone (no attempt suffix): a `gh run rerun # --failed` then RESUMES the same orun execution — jobs that succeeded in # a prior attempt stay completed, so re-run lanes' cross-job dependencies @@ -174,8 +196,8 @@ jobs: env: # GITHUB_TOKEN is the only credential CI holds — GitHub-issued and # ephemeral. Every provider credential (the Cloudflare token and - # account id — this baseline has no second provider) is an - # orun-managed secret: + # account id — there is no second provider) is an orun-managed + # secret: # brokered fresh per run from the workspace's integrations, resolved # lease-bound by the jobs that declare it (profile secretBindings or # component secretEnv), and log-redacted. Nothing provider-shaped is diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml new file mode 100644 index 0000000..c0383e3 --- /dev/null +++ b/.github/workflows/tag.yml @@ -0,0 +1,97 @@ +name: Baseline tag + +# CUTS A `baseline-vN` TAG FOR THIS REPOSITORY. +# +# A baseline tag is what the platform's registry resolves and what every +# product bootstrapped from this repository is built out of, so it is cut by a +# workflow rather than by hand: the version must look like a baseline tag, an +# existing tag is never moved, and the commit is resolved here, once. +# +# Whether a commit is fit to release is decided outside this repository, by +# whoever cuts the tag; nothing here asks for proof beyond a green `main`. + +on: + workflow_dispatch: + inputs: + version: + description: "The tag to cut, e.g. baseline-v2." + required: true + type: string + ref: + description: "Branch, tag or sha to cut it from. Defaults to main." + required: false + default: main + type: string + +concurrency: + group: baseline-tag + cancel-in-progress: false + +permissions: + contents: read + +jobs: + cut: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v6 + with: + # Full history: the ref being cut from may be any commit, and a + # shallow clone cannot resolve one it did not fetch. + fetch-depth: 0 + ref: ${{ inputs.ref }} + + - name: the version must look like a baseline tag + run: | + set -euo pipefail + # Refused here rather than by the API, because the API's error for a + # malformed ref says nothing about the convention it broke. + case "${{ inputs.version }}" in + baseline-v[0-9]*) ;; + *) echo "✕ '${{ inputs.version }}' is not a baseline-vN tag" >&2; exit 1 ;; + esac + + - name: resolve the commit + id: commit + run: | + set -euo pipefail + sha="$(git rev-parse HEAD)" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Cutting ${{ inputs.version }} from ${{ inputs.ref }} = $sha" + + - name: the tag must not already exist + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + code="$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/ref/tags/${{ inputs.version }}")" + if [ "$code" = "200" ]; then + echo "✕ ${{ inputs.version }} already exists. A baseline tag is never moved:" >&2 + echo " products resolve it, and repointing one changes what a build that" >&2 + echo " already shipped was made of. Cut the next number." >&2 + exit 1 + fi + # Anything other than 200 or 404 means the question was not answered, + # and "it probably does not exist" is not a thing to guess about a + # tag that is about to be created. + [ "$code" = "404" ] || { echo "✕ could not check for the tag (HTTP $code)" >&2; exit 1; } + + - name: cut the tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + curl -sS -X POST --fail-with-body \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/refs" \ + -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' \ + "${{ inputs.version }}" "${{ steps.commit.outputs.sha }}")" + echo "" + echo "✓ ${{ inputs.version }} → ${{ steps.commit.outputs.sha }}" + echo " Next: move the registry row in orun-cloud's infra/baselines-registry/baselines.yaml." diff --git a/.gitignore b/.gitignore index 17062c1..6657531 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,6 @@ crash.log **/.orun/runs/ **/.orun/ -# Rendered wrangler configs for wiring-templated deployables (committed as -# wrangler.template.jsonc; rendered by tooling/wire at verify/deploy time). -apps/web/wrangler.jsonc +# apps/web/wrangler.jsonc is NOT ignored: it is committed as the fixture render +# of wrangler.template.jsonc, because the deploy lane checks the config exists +# before it builds (and re-renders it for its environment in the build). diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..2c0202d --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,256 @@ +# BOOTSTRAP — a new product from this baseline, in one landing + +How to go from **nothing** to a **storefront live on stage and prod, its R2 +cache buckets applied, documented**, with ONE provider consent — and how its +owner then connects a Shopify store. + +There is one artifact: **`repo-blueprint.yaml`**. It declares what to place, +in what order, what each phase needs first, and what to say while it runs. +`orun new` is the whole runtime — the phases below are its `--phase` names, +not separate workflows. The console card the platform renders is +**`blueprint.yaml`**; it names the build document and states the inputs, the +brokered secrets and the programme, and `testing/manifest.test.sh` holds it +to what the build document does. + +Target wall-clock: **about sixteen minutes** — an estimate summed from the +phases until a bootstrap measures it: ONE landing whose pull request waits on +Checks (a full Next.js build), then one convergence — the R2 bucket applied +on stage and prod, then the storefront built with its name and deployed, +stage and prod side by side — then a short docs landing that restores the +promotion gate. + +## 0. What you need + +- GitHub org access (repository creation) and a machine with `git`, `node` + (≥ 22), `pnpm` (10.12.1), `python3` with PyYAML, `curl`, and the `orun` + CLI **≥ v2.58.11** — the floor for RUNNING the bootstrap (the phase overlay, + landings that commit per phase and wait on the PR's whole CI run, + `githubOwner` on the doctor probe, `environments` on the secrets probe, a + probe deferred for a project not yet created, and `from: workspace`). The + product's own `ci.yml` pins its lanes separately (v2.78.4), and its plans + need that pin: the floor does not apply a `dependsOn` edge's `modeRules`. +- A Cloudflare account with **R2 enabled** (R2 must be activated once in the + dashboard, even on the free plan; Durable Objects with SQLite storage are + on the free plan too) and its **Account API token** with Workers Scripts + Write, Workers KV Storage Write and **Workers R2 Storage Write** (the + console's Connect recipe lists the exact permission groups). It is the ONLY + provider credential this baseline needs, minted into two scopes: the + brokered `workers-deploy` token deploys the Worker, and the `r2-data` token + (`CLOUDFLARE_R2_TOKEN`) applies the bucket — `workers-deploy` carries no + R2. +- **No Shopify account.** The storefront goes live on its bundled demo + catalogue; Shopify is a third party the platform does not broker, so the + owner connects a store after the build (§4). +- An Orun Cloud workspace for the product — `orunWorkspace`, or the + workspace the build runs in (ORUN_WORKSPACE) when that is unset — with an + **admin-role API key** for headless runs (secret writes below admin are + masked as `not_found`). +- **The repository allow-listed in the workspace** (console → Settings → Git + repos), unless the credential can write links. `01-product`'s `link` step + stops and names the fix if it is not. + +## 1. One command: `--resume` + +The whole bootstrap, unattended. `--resume` places every phase not already +derived as done, in order, honouring each phase's barrier: + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/commerce +cd commerce + +orun new --blueprint repo-blueprint.yaml \ + --out ~/sites/acme-shop --run-hooks --resume \ + --set reponame=acme-shop --set productname="Acme Shop" \ + --set productdomain=shop.acme.dev --set githuborg=acme-inc \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain= +``` + +**`--run-hooks` is the difference between placing files and bootstrapping a +product.** Without it `orun new` writes the tree and stops: no repository, no +landing, no convergence watch, no probe. That is deliberate — it is what +makes the offline bootstrap in `testing/` possible with no workspace and no +provider. + +`--resume` is safe to re-run from anywhere, a fresh container with a fresh +`--out` included: **phase state is derived from the tree, never stored.** A +phase whose files are present but branded derives as `drifted`, and +`--resume` leaves it placed rather than reverting the product's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the WHOLE product in one PR — intent, CI, tooling, identity, the R2 root, the storefront and its tests; the brokered Cloudflare secrets (deploy, R2, account id) | its PR's checks green and merged; the convergence green (R2 applied, then the storefront built, deployed, smoke-tested); `WIRING_CLOUDFLARE_R2` on stage and prod; both workers.dev URLs answering | +| `02-docs` | `ai/context/deployment.md` from probed facts; prod's promotion gate and dev's push lanes restored | the final probe | + +```bash +orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-shop --run-hooks \ + --phase 01-product --values ~/acme-shop.values.yaml +# … then 02-docs +``` + +`02-docs` reads the identity back from `.rebrand/values.json` in the placed +tree, but the blueprint's **required** inputs — `reponame`, `productname`, +`productdomain`, `githuborg` — are validated before anything runs, so pass +them every time (a `--values` file is easier). The full guide, one page per +phase: [docs/phases/README.md](docs/phases/README.md). + +| flag | what it does | +|---|---| +| `--status` | derives and prints every phase's state and writes nothing. It parses the document, validates each hook against the action registry and compiles every template; it needs no credential and no network | +| `--phase ` | places exactly that phase; its `requires.phases` still gates | +| `--until ` | places every phase through that one and stops | + +What lands in the product is PRODUCT-ONLY: the app, its R2 root, its tests, +its CI, its tooling, its README and its two context pages. None of this +repository's machinery (`.baseline/`, the blueprints, `tooling/rebrand`, +`tooling/bootstrap`, `hooks/`, `testing/`, `docs/phases/`, `specs/`, +`tasks/`, this file) ships, and no file that ships names one of them. That +promise is a test: `testing/leak.test.sh` derives what every phase would +place and gates the set and its sources, and `testing/placement.test.sh` +gates the same rules over a placed, branded tree. + +## 2. Why one landing is safe: the plan carries the order + +The bucket must exist before the Worker that binds it: the Worker's +`wrangler.jsonc` carries the bucket's name, rendered in its build from the +wiring document the R2 root publishes after its apply, and a deploy whose +R2 binding names a bucket that does not exist is refused. That order used to +need landings of its own. It does not, because the product's plan holds it: + +- `apps/web/component.yaml` declares `dependsOn: cloudflare-r2` with + `mode: enforced`, and `modeRules` making it advisory on + `github-pull-request`. On the merge the Worker's deploy waits for its + environment's apply; on a pull request nothing deploys, so nothing waits. +- A job resolves its secrets when it STARTS, so `WIRING_CLOUDFLARE_R2_` + is there when the deploy begins. +- The landing's `await` then asks the platform that the wiring exists on + stage and prod (`orun.secrets/exists@v1`) — every later deploy reads it. + +`testing/phases.test.sh` fails if a component that reads a wiring document +does not wait for its publisher this way; `testing/placement.test.sh` plans +the product's own merge and asserts the R2 lanes run first. + +### Two Cloudflare tokens, on purpose + +`workers-deploy` grants Workers Scripts and KV write — and no R2. The R2 +root's Terraform has to list the account's buckets (`adopt.tf`) and create +one, so it authenticates with its own key, `CLOUDFLARE_R2_TOKEN`, minted from +the `r2-data` template by a second `orun.integrations/reconcile@v1` hook and +bound in `infra/terraform/cloudflare-r2/component.yaml` as the provider's +`CLOUDFLARE_API_TOKEN` (the way a D1 root binds a `d1-edit` token). The card +(`blueprint.yaml` `spec.secrets`) mirrors the hook, and +`testing/manifest.test.sh` holds the two together. + +## 3. Headless / container mode + +The blueprint's source is this repository (`sources: [{kind: dir, path: .}]`), +so the container contract is a shallow clone at a pinned tag plus two +tokens: + +```bash +export ORUN_TOKEN=… # orun auth, headless +export GITHUB_TOKEN=… # fine-grained PAT (below) + +git clone --depth 1 --branch https://github.com/sourceplane/commerce +cd commerce +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-shop --run-hooks --resume --progress json \ + --values /work/acme-shop.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the PRODUCT's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-product` creates it (or pre-create it — supported) | +| classic token caveat | a classic PAT or gh OAuth token also needs the `workflow` scope to push `.github/workflows/` | +| pinning | the clone's `--branch ` pins everything: the blueprint, its modules and its hooks' scripts all come from that one commit | + +## 4. After the product is live + +- **Connect Shopify** (the owner's step; the platform does not broker it): + three Worker secrets per environment — `SHOPIFY_STORE_DOMAIN`, + `SHOPIFY_STOREFRONT_ACCESS_TOKEN`, `SHOPIFY_REVALIDATION_SECRET`, set with + `wrangler secret put … --name -web-` — and Shopify's product + and collection webhooks pointed at `/api/revalidate?secret=…`. The + storefront switches from the demo catalogue to the store on its next + request, with no rebuild; checkout becomes Shopify's hosted checkout, which + takes payment through the store's own payment provider. The product's + README, "Connecting Shopify", has every step. +- **Change the storefront**: anything under `apps/web`; its name and source + link are `apps/web/app/site.ts`, the demo's products + `apps/web/lib/demo/catalogue.ts`. Every merge to `main` redeploys. +- **Add a binding** (D1, KV, another bucket): a Terraform root that + lease-publishes `WIRING_`, a token in `wrangler.template.jsonc`, its + fixture entry, and in `apps/web/component.yaml` the root in the build's + `--components`, the `WIRING__` secretEnv and an enforced + `dependsOn` on it. `ai/context/operations.md` in the product says the same. +- **Custom domain**: attach it to the Worker in Cloudflare (the product's + README, "Custom domain"). There is no domain phase: attaching a domain + needs zone permissions the brokered `workers-deploy` token does not carry. + Nothing in the repository changes — the storefront builds its absolute + links from the request. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent. + +## 5. Testing this baseline + +`.github/workflows/baseline.yml` runs three tiers on every pull request, and +each runs locally the same way: + +```bash +for t in manifest phases coverage rebrand retouch bootstrap-defer wire; do bash testing/$t.test.sh; done +bash testing/leak.test.sh # needs orun +bash testing/placement.test.sh # needs orun >= ci.yml's pin, node, pnpm: the offline bootstrap and the product's own plan +bash testing/e2e.test.sh # + network for pnpm: the product built in the job tree, dry-deployed and served +``` + +The offline bootstrap (`testing/lib/bootstrap.sh`) places both phases in +order and finishes each with the blueprint's OWN `run:` hooks — read out of +`repo-blueprint.yaml`, not transcribed — so the retouch marker, the rebrand, +the re-tenant, the deferrals and their restore, the lockfile and the +deployment record all run exactly as a real bootstrap runs them. Only the +platform's typed actions (task, repo, link, reconcile, land, watch, secrets, +probe) are stood in for, a landing becoming a commit. What no offline test +can do is the platform's half: the bucket applied for real (the R2 root is +held to `terraform validate`), the tokens minted, the deploy, the probes — +and a real Shopify store, which no test contacts. + +## 6. Cutting a baseline tag (maintainers) + +Every product built from this repository resolves a `baseline-vN` tag, so +the tag is cut by a workflow rather than by hand: + +```bash +gh workflow run tag.yml -f version=baseline-v1 # from main +gh workflow run tag.yml -f version=baseline-v1 -f ref= +``` + +It refuses a version that is not `baseline-v` and a tag that already +exists: a baseline tag is never moved. Then move the registry row in +orun-cloud's `infra/baselines-registry/baselines.yaml` by pull request — +after the tag exists, because the registry's sync fetches `blueprint.yaml` +at the tag and refuses the whole catalogue if it 404s. + +## Troubleshooting + +| Symptom | Cause → fix | +|---|---| +| `01-product` parks: `waiting for github for ` | the workspace's GitHub connection is to another account. Connect the App installation on `` (console → Integrations → GitHub), then `--resume` | +| `01-product` waits on the `providers` probe, then stops | Cloudflare is not connected. Connect it (console → Integrations), then re-run the phase — the probe is a wait, not a failure | +| `01-product` stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | +| Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | +| `secret-r2-data` fails `parent_grant_insufficient` | the connection's token lacks Workers R2 Storage Write; add it, re-connect, re-run `01-product` | +| R2 lane: Authentication error (10000) | the R2 root is not authenticating with `CLOUDFLARE_R2_TOKEN` (its component.yaml), or the account has not activated R2 | +| deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts write; re-issue it, re-connect, re-run `01-product` | +| R2 lane: bucket already exists (10004) | `adopt.tf` imports a bucket of the same name; restore it if removed. Two products with one `reponame` in one account share bucket names — pick another `reponame` | +| web lane fails resolving `WIRING_CLOUDFLARE_R2_` | that environment's R2 apply failed — read its lane; the web lane waits on it | +| `wiring` await stops: `WIRING_CLOUDFLARE_R2` missing on stage or prod | the convergence was green but the apply published nothing: the R2 component lost its `secretOutputs`, or its lane was not in the plan. Re-run the phase; its retouch marker re-plans the R2 root | +| Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 01-product`, `--redo 01-product`, or the console's Retry): its `retouch` hook gives the landing a diff and the R2 root and the storefront re-plan | +| The live store shows the demo banner | no Shopify store is connected — expected after a bootstrap. The product's README, "Connecting Shopify" | +| The product's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | +| A bootstrap stopped before `02-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `02-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml` | +| `✕ input "productdomain" is required` | all four required inputs must be set on every invocation, single-phase ones included | +| `unknown flag: --phase` or a parse error in the blueprint | the CLI is below the v2.58.11 floor | +| web lane `verify-app-structure` fails on `wrangler.jsonc` | the config is not committed. It is the fixture render of `wrangler.template.jsonc`: `pnpm run wire:fixture` and commit it | +| web lane `build-app`: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | +| the convergence reported green, then `verify` got 404 | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main (`checks.yml` is pull-request only) | diff --git a/README.md b/README.md index f213b68..6e79881 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,74 @@ # commerce -Vercel's [Next.js Commerce](https://github.com/vercel/commerce) — the Shopify -headless storefront: server components over the Storefront API, a -server-action cart, `"use cache"` data revalidated from Shopify webhooks — -running on **Cloudflare Workers + Static Assets** through +Vercel's [Next.js Commerce](https://github.com/vercel/commerce) — the headless +storefront: server components over a store API, a server-action cart, +`"use cache"` data revalidated from Shopify webhooks — running on **Cloudflare +Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the Next.js data cache in an **R2 bucket** provisioned by Terraform through [Orun](https://github.com/sourceplane/orun) and the tag cache and revalidation -queue in **Durable Objects** the Worker itself exports, inside the repository -conventions of the [Cirrus baseline](https://github.com/sourceplane/cirrus-baseline). - -The template's code is the code. What the port adds is the Workers build, the -cache bindings, the monorepo wrapper, a test package for the Shopify client -and the webhook, the R2 Terraform root, and the deploy contract that threads -the bucket into the Worker per environment. See +queue in **Durable Objects** the Worker itself exports — and packaged as an +**Orun baseline**: one command takes a new storefront from nothing to live on +stage and prod, in its own repository, under its own name, in ONE landing. + +A fresh build needs no third-party key: until its owner connects a Shopify +store, the storefront serves a **bundled demo catalogue** (six products, two +collections, menus, pages) with a cookie cart, and checkout answers with a +"connect a payment provider" notice rather than an error. See [`specs/epics/commerce`](specs/epics/commerce/README.md) for the design, the milestones and the as-built status. -## What is here +## Instantiating a product + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/commerce +cd commerce +orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-shop --run-hooks --resume \ + --set reponame=acme-shop --set productname="Acme Shop" --set productdomain=shop.acme.dev \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`commerce` → Build). Two phases: **`01-product`** creates the repository and +lands the whole product as ONE pull request — intent, CI, tooling, the R2 +root, the storefront and its tests — and one convergence applies the R2 +bucket on stage and prod and then deploys the storefront bound to it; +**`02-docs`** records the live deployment from probed facts. +**[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. + +The new repository receives the **product only** — the app, its R2 root, its +tests, its CI, its tooling, a README of its own and its operating contract — +renamed throughout to the product's name, repository, Cloudflare Worker and +bucket names. None of this repository's machinery ships. Its owner then +connects Shopify with three Worker secrets (the product's README, "Connecting +Shopify"); the card asks for no Shopify key, because the platform does not +broker one. + +| What makes it a baseline | Where | +|---|---| +| The console card (inputs, secrets, programme) | `blueprint.yaml` | +| The build document (modules, phases, hooks) | `repo-blueprint.yaml` | +| This tree's identity, and the bootstrap's task contracts | `.baseline/` | +| The rename engine | `tooling/rebrand/rebrand.mjs` | +| The bootstrap's helpers (deferrals, redeploy marker, work-tree strip) | `tooling/bootstrap/` | +| The deployment-record renderer | `hooks/render-deployment-docs.sh` | +| The product's README and context pack | `.baseline/product/README.md`, `ai/context/` | +| The baseline's tests: contract, wiring, leak, offline bootstrap, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + +## What is here (the product) | Surface | Where | |---|---| -| Home, `/search`, `/search/[collection]`, `/product/[handle]`, `/[page]`, OG images, sitemap, robots | `apps/web/app` | -| The Shopify client (`"use cache"` readers, cart mutations, the webhook's `revalidate`) | `apps/web/lib/shopify` | +| Home, `/search`, `/search/[collection]`, `/product/[handle]`, `/cart`, `/checkout`, `/[page]`, OG images, sitemap, robots | `apps/web/app` | +| The store's name and source link | `apps/web/app/site.ts` | +| The Shopify client (`"use cache"` readers, cart mutations, the webhook's `revalidate`) and the demo switch | `apps/web/lib/shopify` | +| The demo catalogue and the cookie cart | `apps/web/lib/demo`, `apps/web/public/demo` | | Cart (server actions, optimistic context, modal), navbar, grid, product gallery | `apps/web/components` | -| Workers build, cache bindings and deploy contract | `apps/web/next.config.ts`, `apps/web/open-next.config.ts`, `apps/web/wrangler.template.jsonc`, `apps/web/component.yaml` | +| Workers build, cache bindings and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml` | | The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` | +| The wrangler renderer | `tooling/wire` | | Tests | `tests/web` (vitest) | ## Getting started @@ -39,19 +82,15 @@ pnpm test pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next ``` -To run against a Shopify store, put its facts in `apps/web/.env.local` for -Next's dev server (see `apps/web/.env.example`) and in `apps/web/.dev.vars` -for the Worker preview (see `apps/web/.dev.vars.example`), then: - ```bash pnpm --filter @app/web dev # http://localhost:3000, Next's dev server -pnpm --filter @app/web preview # wrangler dev over the built Worker, with a local R2 bucket and local Durable Objects +pnpm --filter @app/web preview # wrangler dev over the built Worker, a local R2 bucket and local Durable Objects ``` -Without a store the storefront renders its un-configured state (no products, -no menus), exactly as upstream does before its Shopify integration is -connected; `/search`, `/[page]` and `/sitemap.xml` surface upstream's error -for a missing store. +Without Shopify facts in the environment both serve the demo catalogue. To +run against a store, put its facts in `apps/web/.env.local` for Next's dev +server and in `apps/web/.dev.vars` for the Worker preview (both from +`apps/web/.env.example`). ## How it maps to Vercel @@ -61,63 +100,39 @@ for a missing store. | Data Cache: `"use cache"` entries with `cacheLife("days")` | The R2 bucket bound as `NEXT_INC_CACHE_R2_BUCKET`, written at request time | | Tag revalidation: `revalidateTag` from the Shopify webhook, `updateTag` from cart actions | A sharded Durable Object tag cache (`NEXT_TAG_CACHE_DO_SHARDED`) consulted on every cache read | | Stale-while-revalidate (ISR) | A Durable Object queue (`NEXT_CACHE_DO_QUEUE`) that re-renders stale routes through the Worker's `WORKER_SELF_REFERENCE` binding | -| `next/image` over `cdn.shopify.com` | The Worker's own `/_next/image`: validated against `remotePatterns`, served unoptimised (no `IMAGES` binding; Shopify's CDN already sizes) | -| Project env vars in the dashboard | `COMPANY_NAME`, `SITE_NAME`, `SITE_URL` as wrangler `vars`; `SHOPIFY_STORE_DOMAIN`, `SHOPIFY_STOREFRONT_ACCESS_TOKEN`, `SHOPIFY_REVALIDATION_SECRET` as Worker secrets | -| `VERCEL_PROJECT_PRODUCTION_URL` | The `SITE_URL` var (metadata base, robots, sitemap) | -| Deploy on push | Orun deploys `commerce-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | - -Partial prerendering is off: `@opennextjs/cloudflare` 1.20 cannot run Next -16's Cache Components on workerd yet, so the storefront keeps upstream's +| `next/image` over `cdn.shopify.com` | The Worker's own `/_next/image`, validated against `remotePatterns`, served unoptimised; the demo's SVGs are static assets | +| The Shopify integration's env vars | `SHOPIFY_STORE_DOMAIN`, `SHOPIFY_STOREFRONT_ACCESS_TOKEN`, `SHOPIFY_REVALIDATION_SECRET` as Worker secrets — and, unset, the bundled demo catalogue instead of an empty store | +| `VERCEL_PROJECT_PRODUCTION_URL` | Nothing: metadata, robots and the sitemap are built on the request's origin (`app/site.ts`) | +| Deploy on push | Orun applies the bucket and deploys `-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed | + +Partial prerendering is off: `@opennextjs/cloudflare` 1.20 cannot run Next 16's +Cache Components on workerd yet, so the storefront keeps upstream's `"use cache"` directives through `experimental.useCache` and renders every -route at request time — which is what upstream's root-layout cart promise -made it do anyway. - -## Connecting Shopify +route at request time. -Follow Vercel's [Shopify integration guide](https://vercel.com/docs/integrations/ecommerce/shopify) -for the store side — a Headless (Storefront API) access token, the -`next-js-frontend-header-menu` and `next-js-frontend-footer-menu` menus, the -`hidden-homepage-featured-items` and `hidden-homepage-carousel` collections — -then give each environment's Worker the three facts as secrets (once; the -deploy lane does not set them): +## How the bucket reaches the Worker -```bash -cd apps/web -for env in stage prod; do - wrangler secret put SHOPIFY_STORE_DOMAIN --name commerce-web-$env # your-store.myshopify.com - wrangler secret put SHOPIFY_STOREFRONT_ACCESS_TOKEN --name commerce-web-$env - wrangler secret put SHOPIFY_REVALIDATION_SECRET --name commerce-web-$env # any long random string -done +``` +infra/terraform/cloudflare-r2 ──apply (r2-data token)──► orun secret WIRING_CLOUDFLARE_R2 (stage, prod) + │ (the landing's await checks it exists) + ▼ +apps/web dependsOn cloudflare-r2 (enforced on main) · secretEnv WIRING_CLOUDFLARE_R2_ + build: tooling/wire/live.mjs → wrangler.jsonc with the environment's bucket name + (dev, verify-only, renders the fixture) → next build → opennextjs-cloudflare + deploy: workers-deploy token → -web-, its Durable Objects migrated on first deploy ``` -Then register a webhook in Shopify (Settings → Notifications → Webhooks) for -`products/create`, `products/update`, `products/delete`, -`collections/create`, `collections/update` and `collections/delete`, pointing -at `https://commerce-web-prod..workers.dev/api/revalidate?secret=`. -Each delivery revalidates the `products` or `collections` tag in the Durable -Object tag cache; the next request re-renders from Shopify. Set `SITE_URL` -in `apps/web/wrangler.template.jsonc` to the public origin once you know it. - -## Deploying - -`.github/workflows/checks.yml` runs install, wire, typecheck, lint, test and -build on every push and pull request. `ci.yml` is the Orun pipeline: set -`execution.state.workspace` in `intent.yaml` to this product's workspace -(`orun cloud link`), connect Cloudflare to that workspace, and set the -`ORUN_CI` repository variable to `true`. A merge to `main` then applies the -R2 root, renders `wrangler.jsonc` from its wiring document, builds the app -and deploys the Worker to `stage`, then `prod`; the Durable Objects are -created by the migration in the wrangler config on the first deploy. - -The first deploy serves everything on demand: the build pre-renders only -`/robots.txt`, `/favicon.ico` and `/opengraph-image`, every storefront route -is dynamic, and every `"use cache"` entry is written to R2 by the first -request that needs it. Uploading the build's pre-rendered output to the -bucket is therefore optional — +`wrangler.jsonc` is committed as the fixture render of +`wrangler.template.jsonc`, because the deploy lane's `verify-app-structure` +step checks the config exists before it builds; Checks fails if the two +disagree. -```bash -pnpm --filter @app/web exec opennextjs-cloudflare populateCache remote # needs CLOUDFLARE_API_TOKEN / account, and wrangler.jsonc rendered for the target environment -``` +## CI -— and not recommended from a `Checks` build, whose `"use cache"` results are -the un-configured store's empty menus and collections. +| Workflow | What it runs | Ships to a product | +|---|---|---| +| `checks.yml` | install, wire fixtures (and the committed config is their render), typecheck, lint, test, build — every PR (not pushes: on main, `ci.yml` must be the only run a commit has, because the bootstrap's convergence watch takes the newest one) | yes | +| `ci.yml` | the Orun pipeline: `orun plan --changed`, then one job per lane; applies the R2 bucket, then deploys stage → prod on merge. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does | yes | +| `baseline.yml` | the baseline's own tiers: contract tests, the wiring path, the blueprint read by the pinned orun, the leak gate, the offline bootstrap with the product's own plan, the product built in the job tree, dry-deployed, served, browsed and added to the cart | no | +| `tag.yml` | cuts a `baseline-vN` tag (manual) | no | diff --git a/ai/context/deployment.md b/ai/context/deployment.md new file mode 100644 index 0000000..7b60298 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# commerce — live deployment manifest + +> Not rendered yet. The bootstrap's `02-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and +> their status, which store backend answered, and the secrets inventory by +> name. Until then, nothing here claims the store is live. The operating +> contract is [operations.md](operations.md). diff --git a/ai/context/operations.md b/ai/context/operations.md new file mode 100644 index 0000000..6fd3b06 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,159 @@ +# commerce — operating contract (for humans and agents) + +This is the standing guide to how this store is deployed and operated. +Instance facts (live URLs, workspace, secrets inventory) live in +[deployment.md](deployment.md), rendered from probed reality by the +bootstrap's `02-docs` phase; this file is the contract that stays true +between deployments. It is written to give an agent with repository read +access enough context to reason about and operate the store without any +other source. + +## What this system is + +A headless storefront on Cloudflare alone, expressed as an Orun +component-native desired-state repo. + +- **`infra/terraform/cloudflare-r2`** — one R2 bucket per deployed + environment (`stage`, `prod`), applied by Terraform: the storefront's + Next.js incremental cache. After each apply it publishes a wiring document + — `{r2_bucket_name}` — as the Orun secret `WIRING_CLOUDFLARE_R2` on that + environment. +- **`apps/web`** — the storefront: Next.js built by `@opennextjs/cloudflare` + into one Worker plus Static Assets. Every route renders per request. Its + data comes from a connected Shopify store or, until one is connected, from + the bundled demo catalogue (`lib/demo`), with the cart in a cookie. The + Worker binds the bucket (`NEXT_INC_CACHE_R2_BUCKET`) and exports two + Durable Objects: the tag cache and the revalidation queue. +- **`tests/web`** — the Shopify client, the demo catalogue and cart, the + webhook and the URL helpers (vitest), verified on the `dev` rung. +- **`tooling/*`** — shared TypeScript and ESLint configuration, and the + wrangler renderer that turns `wrangler.template.jsonc` plus a wiring + document into `wrangler.jsonc`. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and test, nothing deploys, and no +bucket exists for it (its build renders the committed fixture). + +## Identity and tenancy + +Every remote operation runs against ONE Orun workspace, declared in +`intent.yaml` under `execution.state.workspace` — committed, enforced, and +what CI uses. Do not remove it; headless credentials depend on it. If it +reads `ws_SET_ME`, the bootstrap had no workspace to write: set the real one +before anything else. + +## How deployment works + +1. Merge (or push) to `main`. +2. CI (`.github/workflows/ci.yml`) runs `orun plan --changed` — only + components whose files changed are planned — then runs each planned lane + with `orun run --remote-state`, authenticated by GitHub OIDC (the + exchange resolves this repository's linked workspace server-side). +3. **The bucket before the Worker.** `cloudflare-r2` applies for the + environment and publishes `WIRING_CLOUDFLARE_R2`. `apps/web` declares an + enforced `dependsOn` on it for pushes to `main`, so its deploy starts only + after that apply — and a job resolves its secrets when it starts, so the + document is there. +4. `apps/web` renders `wrangler.jsonc` from that document (the real bucket + name), builds once per environment, `wrangler deploy` ships + `commerce-web-` (the Durable Objects are created by the config's + migration on the first deploy), and a smoke test fetches `/` and + `/robots.txt` — which must name the origin it was asked on, proof the + Worker itself rendered it. +5. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +6. **The convergence run is the deployment.** A green run means every + planned lane applied. Failed lanes are retried with + `gh run rerun --failed`, which resumes the same execution. + +On a pull request nothing applies or deploys: the R2 root plans, the +storefront builds and dry-deploys, and the edges in step 3 are advisory. + +Caveats that matter: + +- A push that touches no component files plans zero lanes — that run is + green and deployed nothing. Never treat "latest run green" as "store + converged"; probe the URLs instead. +- A change to `intent.yaml`'s `environments` maps to no component and + redeploys nothing on its own. Land it with a change under `apps/web`. +- `wrangler.jsonc` is generated. Edit `wrangler.template.jsonc` and run + `pnpm run wire:fixture`; Checks fails when the two disagree. + +## The store backend + +- **No store connected** (no `SHOPIFY_STORE_DOMAIN` secret on the Worker): + every reader answers from `lib/demo`, the cart is the `demo-cart` cookie + (variant ids and quantities; prices always re-read from the catalogue), a + banner says the store is a demo, and `/checkout` answers 200 with "Connect + a payment provider to enable checkout". Nothing is cached for the demo. +- **Shopify connected**: the three Worker secrets `SHOPIFY_STORE_DOMAIN`, + `SHOPIFY_STOREFRONT_ACCESS_TOKEN`, `SHOPIFY_REVALIDATION_SECRET` (the + README's "Connecting Shopify"). Readers go to the Storefront API and are + cached in R2 (`"use cache"`, tagged `products` / `collections`); Shopify's + webhooks hit `/api/revalidate?secret=…` to revalidate a tag; checkout is + Shopify's hosted checkout, which takes payment through the store's own + payment provider. The switch is per request: setting or deleting the + secrets changes the backend without a redeploy. + +## Secrets model + +- **Brokered provider secrets**: `CLOUDFLARE_API_TOKEN` (the + `workers-deploy` scope: Workers Scripts and KV Storage write) deploys the + Worker; `CLOUDFLARE_R2_TOKEN` (the `r2-data` scope: R2 Storage write) is + what the R2 root's Terraform authenticates with, because the deploy token + carries no R2; `CLOUDFLARE_ACCOUNT_ID` is the connection fact both bind. + Minted per run from the workspace's Cloudflare connection — no long-lived + values at rest, nothing to rotate by hand. +- **Wiring**: `WIRING_CLOUDFLARE_R2` on `stage` and `prod`, written by the R2 + root's apply (lease-published), read by the Worker's build as + `WIRING_CLOUDFLARE_R2_`. It holds the bucket name, not a credential. +- **Store secrets**: Shopify's three facts are Worker secrets on + `commerce-web-`, set by the owner with `wrangler secret put`; the + pipeline never reads or writes them. +- Inspect by NAME only: `orun secrets list --org --project` and + `--env stage|prod`; `wrangler secret list --name commerce-web-`. No + tooling in this repository prints a secret value, and no document in + `ai/context/` may contain one. + +## Verifying the system + +```bash +# the storefront on each environment (also recorded, probed, in deployment.md); +# robots.txt names the origin the Worker was asked on +curl -s https://commerce-web-stage.your-workers-subdomain.workers.dev/robots.txt | grep -i '^Host:' +curl -s -o /dev/null -w '%{http_code}\n' https://commerce-web-prod.your-workers-subdomain.workers.dev/ +# which backend answers: the demo banner is on every page until a store is connected +curl -s https://commerce-web-prod.your-workers-subdomain.workers.dev/ | grep -c data-demo-banner + +# the wiring the deploys read, and workspace readiness +orun secrets list --org --env stage && orun secrets list --org --env prod +orun integrations list --org --json && orun cloud check --org +``` + +## Common operations + +| task | how | +|---|---| +| change the storefront | edit `apps/web` (its name and source link: `apps/web/app/site.ts`), merge | +| connect Shopify | the README's "Connecting Shopify": three Worker secrets per environment and the webhooks; no merge needed | +| change the demo catalogue | `apps/web/lib/demo/catalogue.ts` and its images in `apps/web/public/demo`, merge | +| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | +| redeploy without a change | edit the last line of `apps/web/component.yaml` (`# orun: redeploy `) and merge — it is a deploy trigger, nothing reads it | +| empty the data cache | revalidate through the webhook route (a `products/update` or `collections/update` topic), or delete the bucket's `incremental-cache/` objects | +| add a binding (D1, KV, another bucket) | a Terraform root under `infra/terraform/` that publishes `WIRING_`, a token in `wrangler.template.jsonc`, its fixture entry, the root in the build's `--components`, the `WIRING__` secretEnv and an enforced `dependsOn` on it in `apps/web/component.yaml` | +| serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"); nothing in the repository changes | +| add a runtime secret | `wrangler secret put --name commerce-web-` for the Worker; `orun secrets set --org --env ` for a lane | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `02-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 02-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +Structural changes follow the same contract that deployed the store: add a +component under `apps/`, `infra/` or `packages/` with a `component.yaml`, +land it as a pull request, and the convergence run applies it. A different +store backend is a replacement for the functions `lib/shopify/index.ts` +exports; `lib/demo` implements the same surface. diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example deleted file mode 100644 index 4d803f1..0000000 --- a/apps/web/.dev.vars.example +++ /dev/null @@ -1,11 +0,0 @@ -# Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`. -# Copy to .dev.vars (git-ignored). In stage/prod these are Worker secrets, set -# once per environment with `wrangler secret put --name commerce-web-` -# (README → Deploying); the deploy lane does not set them. Left unset, the -# storefront renders without products ("Shopify not configured"), as upstream -# does before its integration is connected. -SHOPIFY_STORE_DOMAIN="your-store.myshopify.com" -SHOPIFY_STOREFRONT_ACCESS_TOKEN="" -SHOPIFY_REVALIDATION_SECRET="" -# Which Next .env files the Worker loads at start (defaults to production). -# NEXTJS_ENV=development diff --git a/apps/web/.env.example b/apps/web/.env.example index 5331778..d49f9da 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1,10 +1,16 @@ -# Local development (`pnpm --filter @app/web dev`). Copy to .env.local -# (git-ignored). The Worker reads COMPANY_NAME, SITE_NAME and SITE_URL as -# wrangler vars (wrangler.template.jsonc) and the SHOPIFY_* values as Worker -# secrets (.dev.vars.example). -COMPANY_NAME="Vercel Inc." -SITE_NAME="Next.js Commerce" -SITE_URL="http://localhost:3000" -SHOPIFY_REVALIDATION_SECRET="" +# Local development. Every value is optional: with no Shopify store the +# storefront serves its bundled demo catalogue (lib/demo) and keeps the cart +# in a cookie. The store's name is apps/web/app/site.ts, and its origin is +# the request's own. +# +# Next's dev server (`pnpm dev`) → copy to .env.local +# the Worker preview (`pnpm preview`) → copy to .dev.vars +# +# Both are git-ignored. On the deployed Workers the SHOPIFY_* values are +# Worker secrets, set once per environment with +# `wrangler secret put --name commerce-web-` (the repository's +# README, "Connecting Shopify"); the deploy lane never sets them. +COMPANY_NAME="" +SHOPIFY_STORE_DOMAIN="" SHOPIFY_STOREFRONT_ACCESS_TOKEN="" -SHOPIFY_STORE_DOMAIN="[your-shopify-store-subdomain].myshopify.com" +SHOPIFY_REVALIDATION_SECRET="" diff --git a/apps/web/README.md b/apps/web/README.md index ea48c93..e45e4a5 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,75 +1,43 @@ -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fcommerce&project-name=commerce&repo-name=commerce&demo-title=Next.js%20Commerce&demo-url=https%3A%2F%2Fdemo.vercel.store&demo-image=https%3A%2F%2Fbigcommerce-demo-asset-ksvtgfvnd.vercel.app%2Fbigcommerce.png&products=%255B%257B%2522type%2522%253A%2522integration%2522%252C%2522protocol%2522%253A%2522other%2522%252C%2522productSlug%2522%253A%2522shopify%2522%252C%2522integrationSlug%2522%253A%2522shopify%2522%257D%255D&env=COMPANY_NAME,SITE_NAME) - -# Next.js Commerce - -A high-performance, server-rendered Next.js App Router ecommerce application. - -This template uses React Server Components, Server Actions, `Suspense`, `useOptimistic`, and more. - -

- -> Note: Looking for Next.js Commerce v1? View the [code](https://github.com/vercel/commerce/tree/v1), [demo](https://commerce-v1.vercel.store), and [release notes](https://github.com/vercel/commerce/releases/tag/v1). - -## Providers - -Vercel will only be actively maintaining a Shopify version [as outlined in our vision and strategy for Next.js Commerce](https://github.com/vercel/commerce/pull/966). - -Vercel is happy to partner and work with any commerce provider to help them get a similar template up and running and listed below. Alternative providers should be able to fork this repository and swap out the `lib/shopify` file with their own implementation while leaving the rest of the template mostly unchanged. - -- Shopify (this repository) -- [BigCommerce](https://github.com/bigcommerce/nextjs-commerce) ([Demo](https://next-commerce-v2.vercel.app/)) -- [Ecwid by Lightspeed](https://github.com/Ecwid/ecwid-nextjs-commerce/) ([Demo](https://ecwid-nextjs-commerce.vercel.app/)) -- [Geins](https://github.com/geins-io/vercel-nextjs-commerce) ([Demo](https://geins-nextjs-commerce-starter.vercel.app/)) -- [Medusa](https://github.com/medusajs/vercel-commerce) ([Demo](https://medusa-nextjs-commerce.vercel.app/)) -- [Prodigy Commerce](https://github.com/prodigycommerce/nextjs-commerce) ([Demo](https://prodigy-nextjs-commerce.vercel.app/)) -- [Saleor](https://github.com/saleor/nextjs-commerce) ([Demo](https://saleor-commerce.vercel.app/)) -- [Shopware](https://github.com/shopwareLabs/vercel-commerce) ([Demo](https://shopware-vercel-commerce-react.vercel.app/)) -- [Swell](https://github.com/swellstores/verswell-commerce) ([Demo](https://verswell-commerce.vercel.app/)) -- [Umbraco](https://github.com/umbraco/Umbraco.VercelCommerce.Demo) ([Demo](https://vercel-commerce-demo.umbraco.com/)) -- [Wix](https://github.com/wix/headless-templates/tree/main/nextjs/commerce) ([Demo](https://wix-nextjs-commerce.vercel.app/)) -- [Fourthwall](https://github.com/FourthwallHQ/vercel-commerce) ([Demo](https://vercel-storefront.fourthwall.app/)) - -> Note: Providers, if you are looking to use similar products for your demo, you can [download these assets](https://drive.google.com/file/d/1q_bKerjrwZgHwCw0ovfUMW6He9VtepO_/view?usp=sharing). - -## Integrations - -Integrations enable upgraded or additional functionality for Next.js Commerce - -- [Orama](https://github.com/oramasearch/nextjs-commerce) ([Demo](https://vercel-commerce.oramasearch.com/)) - - - Upgrades search to include typeahead with dynamic re-rendering, vector-based similarity search, and JS-based configuration. - - Search runs entirely in the browser for smaller catalogs or on a CDN for larger. - -- [React Bricks](https://github.com/ReactBricks/nextjs-commerce-rb) ([Demo](https://nextjs-commerce.reactbricks.com/)) - - Edit pages, product details, and footer content visually using [React Bricks](https://www.reactbricks.com) visual headless CMS. - -## Running locally - -You will need to use the environment variables [defined in `.env.example`](.env.example) to run Next.js Commerce. It's recommended you use [Vercel Environment Variables](https://vercel.com/docs/concepts/projects/environment-variables) for this, but a `.env` file is all that is necessary. - -> Note: You should not commit your `.env` file or it will expose secrets that will allow others to control your Shopify store. - -1. Install Vercel CLI: `npm i -g vercel` -2. Link local instance with Vercel and GitHub accounts (creates `.vercel` directory): `vercel link` -3. Download your environment variables: `vercel env pull` +# apps/web — the storefront + +Vercel's open-source Next.js storefront template (MIT, `license.md`) on +Cloudflare Workers + Static Assets: server components over a store API, a +server-action cart with optimistic updates, `"use cache"` data revalidated by +tag. The template's pages and components are kept; what this app adds is the +Workers build, the cache bindings, a demo catalogue for a store that is not +connected yet, and a cart page and a checkout notice. + +- `app/` — the routes: home, `/search`, `/search/[collection]`, + `/product/[handle]`, `/cart`, `/checkout`, `/[page]`, the Open Graph images, + `robots.txt`, `sitemap.xml`, and `/api/revalidate` (Shopify's webhooks) +- `app/site.ts` — the store's name, the repository its footer links to, and + the request origin every absolute URL is built on +- `lib/shopify/` — the Storefront API client; each exported reader and cart + operation answers from `lib/demo` instead while no store is connected + (`SHOPIFY_STORE_DOMAIN` unset) +- `lib/demo/` — the bundled catalogue (`catalogue.ts`) and a cookie cart; + its images are `public/demo/*.svg` +- `components/` — cart (server actions, optimistic context, modal), navbar, + grid, product gallery, the demo banner ```bash -pnpm install -pnpm dev +pnpm dev # next dev on http://localhost:3000 +pnpm build # next build + opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker: a local R2 bucket, local Durable Objects ``` -Your app should now be running on [localhost:3000](http://localhost:3000/). - -
- Expand if you work at Vercel and want to run locally and / or contribute +The cache's bucket is not hand-written. `wrangler.template.jsonc` names it as +a wiring token; `wrangler.jsonc` is that template rendered from +`wiring.fixture.json` (placeholder names, for local work and verification), +and every deploy renders it again from the name the `cloudflare-r2` Terraform +root published for the environment (`component.yaml`'s `buildCommand`). -1. Run `vc link`. -1. Select the `Vercel Solutions` scope. -1. Connect to the existing `commerce-shopify` project. -1. Run `vc env pull` to get environment variables. -1. Run `pnpm dev` to ensure everything is working correctly. -
+## Store backend -## Vercel, Next.js Commerce, and Shopify Integration Guide +| `SHOPIFY_STORE_DOMAIN` | catalogue, menus, pages | cart | checkout | +|---|---|---|---| +| unset (a fresh deploy) | `lib/demo`, never cached | the `demo-cart` cookie, priced from the catalogue | `/checkout`: "Connect a payment provider to enable checkout" | +| set | the Storefront API, cached in R2 (`"use cache"`), revalidated by webhook | a Shopify cart (`cartId` cookie) | Shopify's hosted checkout | -You can use this comprehensive [integration guide](https://vercel.com/docs/integrations/ecommerce/shopify) with step-by-step instructions on how to configure Shopify as a headless CMS using Next.js Commerce as your headless Shopify storefront on Vercel. +Connecting a store is three Worker secrets and Shopify's webhooks — the +repository's README, "Connecting Shopify". diff --git a/apps/web/app/[page]/opengraph-image.tsx b/apps/web/app/[page]/opengraph-image.tsx index 5f11d80..2b7fbc5 100644 --- a/apps/web/app/[page]/opengraph-image.tsx +++ b/apps/web/app/[page]/opengraph-image.tsx @@ -1,9 +1,15 @@ import OpengraphImage from "components/opengraph-image"; import { getPage } from "lib/shopify"; -export default async function Image({ params }: { params: { page: string } }) { - const page = await getPage(params.page); - const title = page.seo?.title || page.title; +// Next 16 passes an image route's params as a Promise (upstream reads them +// synchronously, which made every page's image a 500). +export default async function Image({ + params, +}: { + params: Promise<{ page: string }>; +}) { + const page = await getPage((await params).page); + const title = page?.seo?.title || page?.title; return await OpengraphImage({ title }); } diff --git a/apps/web/app/cart/page.tsx b/apps/web/app/cart/page.tsx new file mode 100644 index 0000000..ce746a1 --- /dev/null +++ b/apps/web/app/cart/page.tsx @@ -0,0 +1,102 @@ +import { redirectToCheckout } from "components/cart/actions"; +import Footer from "components/layout/footer"; +import Price from "components/price"; +import { DEFAULT_OPTION } from "lib/constants"; +import { getCart } from "lib/shopify"; +import type { Metadata } from "next"; +import Image from "next/image"; +import Link from "next/link"; + +export const metadata: Metadata = { + title: "Your cart", + robots: { index: false }, +}; + +// The cart as a page, rendered on the server from the same getCart() the +// cart modal reads — so it works without JavaScript, and is a stable URL for +// "view your cart". Checkout is a plain form post to the same server action +// the modal uses. +export default async function CartPage() { + const cart = await getCart(); + const lines = cart?.lines ?? []; + + return ( + <> +
+

Your cart

+ {lines.length === 0 ? ( +

+ Your cart is empty.{" "} + + Browse the store + + . +

+ ) : ( + <> +
    + {lines.map((item) => ( +
  • +
    + { +
    +
    + + {item.merchandise.product.title} + + {item.merchandise.title !== DEFAULT_OPTION ? ( + + {item.merchandise.title} + + ) : null} + + Quantity {item.quantity} + +
    + +
  • + ))} +
+
+

Total

+ +
+
+ +
+ + )} +
+