From 8b7f3d9a354368ac274ba877942a9033a847bb73 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 19:49:05 +0000 Subject: [PATCH] CS3: cms-sanity becomes an Orun baseline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Sanity-backed Next.js blog on Cloudflare Workers + Static Assets becomes a baseline that takes a new blog from nothing to live on stage and prod in ONE landing, built the way cirrus-baseline builds its product since baseline-v22, with what a small-site baseline contains taken from portfolio-starter-kit's baseline-v2 and the no-infra two-phase shape from hono-api (HA3) — and deployable before its owner has a Sanity project. - blueprint.yaml (the card) and repo-blueprint.yaml (the build): two phases. 01-product places every module, brands it, re-tenants it, strips the work tree, defers promotion and dev's push lanes, creates and links the repository, reconciles CLOUDFLARE_API_TOKEN (workers-deploy) and CLOUDFLARE_ACCOUNT_ID (account-id), lands one PR, and awaits the convergence and a probe of both workers.dev URLs. No wiring await: there is no infra. 02-docs is hook-only: it restores both deferrals, renders the deployment record and lands it. requires.integrations: [github, cloudflare]; nothing is asked or minted for Sanity. - Sanity is not a provider the platform brokers, so a build with no project id is the UNCONNECTED blog instead of a 500: sanity/lib/api.ts and token.ts no longer throw; sanityFetch answers the four queries from three bundled sample posts (sanity/lib/sample.ts, typed by TypeGen's results) without calling Sanity; the layout shows a "connect your Sanity project" notice; /studio renders a connect page; draft mode answers 401 with the reason. The project id and dataset are optionalSecretEnv refs (skipped while unstored), the read token an optional Worker secret; the product's README ("Connecting Sanity") and ai/context/operations.md say how an owner sets all three, redeploys, and allows the CORS origins. - The SITE_NAME seam (apps/web/app/site.ts, the template's "Blog."); the rebrand engine protects the upstream template's examples/cms-sanity links, which share the slug. The smoke reads the home page's layout and the draft-mode route's 401 (server code only the Worker answers). - .baseline/ (identity, the two task contracts, the blog's README), the bootstrap helpers, the deployment-record hook (which records whether each environment shows samples or the project's content), ai/context, docs/phases, BOOTSTRAP.md, baseline.yml and tag.yml; tooling/wire from kv-redis-starter; infra/ and packages/ discovery roots. - ci.yml plans nothing only while intent.yaml names ws_CHANGE_ME (no ORUN_CI variable) at orun v2.78.4; checks.yml runs on pull requests only and checks the committed wrangler config is the fixture render; stack-tectonic 0.19.0; .dev.vars.example ships (the ignore glob no longer swallows it). - testing/: manifest, phases (the two-phase partition and cirrus's 01-product hook chain), coverage, rebrand (the upstream link survives, an "&" and "'" name), retouch, bootstrap-defer, leak (every shipped file read for factory paths), placement (the offline bootstrap on orun's Initial commit, the product's own push-to-main plan through ci.yml's --from-ci github --event-file path with the Sanity refs optional, a --resume no-op) and e2e (both landings under Checks, every run step of the stage lane's PR plan in a staged job tree with no Sanity credentials, wrangler dev, the component's smoke verbatim and in the planned smoke step, every route including draft mode's 401). Orun-Task: CS-4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AuyckrXahuAVgdmxamUUtk --- .baseline/identity.json | 9 + .baseline/product/README.md | 142 ++++ .baseline/tasks/01-product.TaskContract.yaml | 23 + .baseline/tasks/02-docs.TaskContract.yaml | 13 + .github/workflows/baseline.yml | 136 ++++ .github/workflows/checks.yml | 24 +- .github/workflows/ci.yml | 40 +- .github/workflows/tag.yml | 97 +++ BOOTSTRAP.md | 220 ++++++ README.md | 126 ++-- ai/context/deployment.md | 7 + ai/context/operations.md | 162 +++++ apps/web/.dev.vars.example | 5 +- apps/web/.env.example | 14 +- apps/web/README.md | 326 +-------- apps/web/app/(blog)/connect-sanity.tsx | 28 + apps/web/app/(blog)/layout.tsx | 3 + .../(sanity)/studio/[[...tool]]/connect.tsx | 48 ++ .../app/(sanity)/studio/[[...tool]]/page.tsx | 6 +- apps/web/app/api/draft-mode/enable/route.ts | 22 +- apps/web/app/site.ts | 6 + apps/web/component.yaml | 31 +- apps/web/package.json | 2 +- apps/web/sanity/lib/api.ts | 36 +- apps/web/sanity/lib/demo.ts | 5 +- apps/web/sanity/lib/fetch.ts | 10 +- apps/web/sanity/lib/sample.ts | 175 +++++ apps/web/sanity/lib/token.ts | 17 +- blueprint.yaml | 143 ++++ docs/phases/01-product.md | 104 +++ docs/phases/02-docs.md | 40 ++ docs/phases/README.md | 122 ++++ hooks/render-deployment-docs.sh | 175 +++++ infra/.gitkeep | 0 intent.yaml | 53 +- packages/.gitkeep | 0 repo-blueprint.yaml | 646 ++++++++++++++++++ specs/epics/README.md | 2 +- .../epics/cms-sanity/IMPLEMENTATION-STATUS.md | 93 ++- specs/epics/cms-sanity/README.md | 9 +- specs/epics/cms-sanity/design.md | 83 ++- specs/epics/cms-sanity/epic.yaml | 9 +- specs/epics/cms-sanity/implementation-plan.md | 39 +- .../cms-sanity/risks-and-open-questions.md | 55 +- tasks/CS-1.TaskContract.yaml | 3 + tasks/CS-2.TaskContract.yaml | 3 + tasks/CS-3.TaskContract.yaml | 3 + tasks/CS-4.TaskContract.yaml | 35 + testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 177 +++++ testing/e2e.test.sh | 378 ++++++++++ testing/fixtures/acme.json | 23 + .../baseline-identity.cms-sanity.json | 9 + testing/leak.test.sh | 174 +++++ testing/lib/bootstrap.sh | 69 ++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 86 +++ testing/manifest.test.sh | 432 ++++++++++++ testing/phases.test.sh | 350 ++++++++++ testing/placement.test.sh | 326 +++++++++ testing/rebrand.test.sh | 194 ++++++ testing/retouch.test.sh | 199 ++++++ tests/web/src/site.test.ts | 16 + tests/web/src/unconnected.test.ts | 122 ++++ tests/web/tsconfig.json | 2 +- 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 | 470 +++++++++++++ tooling/rebrand/values.example.json | 8 + tooling/wire/live.mjs | 30 +- tooling/wire/render.mjs | 12 +- 73 files changed, 6672 insertions(+), 458 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 create mode 100644 apps/web/app/(blog)/connect-sanity.tsx create mode 100644 apps/web/app/(sanity)/studio/[[...tool]]/connect.tsx create mode 100644 apps/web/app/site.ts create mode 100644 apps/web/sanity/lib/sample.ts 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 infra/.gitkeep create mode 100644 packages/.gitkeep create mode 100644 repo-blueprint.yaml create mode 100644 tasks/CS-4.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.cms-sanity.json create mode 100755 testing/leak.test.sh create mode 100755 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 100644 tests/web/src/site.test.ts create mode 100644 tests/web/src/unconnected.test.ts create mode 100755 tooling/bootstrap/dev-lanes.mjs create mode 100755 tooling/bootstrap/promotion.mjs create mode 100755 tooling/bootstrap/retouch.mjs create mode 100755 tooling/bootstrap/work-tree.mjs create mode 100755 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..e48d494 --- /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 (the upstream template's own heading, `Blog.`); `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in the source links the docs carry. The upstream template's directory (`examples/cms-sanity` in Vercel's next.js repository) shares the slug and is protected from the rename.", + "slug": "cms-sanity", + "pascal": "CmsSanity", + "productName": "Blog.", + "domain": "cms-sanity.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..a6e9826 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,142 @@ +# cms-sanity + +A blog whose posts, authors and settings live in a [Sanity](https://www.sanity.io) +dataset — read over GROQ with `next-sanity`, with draft mode and live preview +through Sanity's Presentation tool, and the Sanity Studio embedded at +`/studio` — running on **Cloudflare Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare). It is +Vercel's [Blog with Sanity CMS](https://github.com/vercel/next.js/tree/canary/examples/cms-sanity) +template, ported to Workers. + +## 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 blog deploys +and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## Connecting Sanity + +The blog deploys and serves before it has a Sanity project: until its build +is given a project id it shows a few **sample posts** bundled with it, under +a notice that says so, and `/studio` explains how to connect instead of +opening a Studio with nothing behind it. To make it read your content: + +1. **Create a project** at [sanity.io/manage](https://www.sanity.io/manage) + (or `cd apps/web && pnpm run setup`, which runs `sanity init`). Note the + project id and the dataset — usually `production`. +2. **Give the build your project**, once per deployed environment. Both are + public values `next build` bakes in, stored as this repository's Orun + secrets so stage and prod can each name their own: + + ```bash + orun secrets set SANITY_PROJECT_ID --env stage # prompts for the value + orun secrets set SANITY_DATASET --env stage # optional: production when unset + orun secrets set SANITY_PROJECT_ID --env prod + orun secrets set SANITY_DATASET --env prod + ``` + + Then **redeploy the blog**: a secret is read when the blog builds, and + setting one builds nothing. Change the stamp on the last line of + `apps/web/component.yaml` (`# orun: redeploy …`) and merge; the sample + posts and the notice are gone from that deploy on. +3. **Allow the site's origins** in the project (API → CORS origins): + `https://cms-sanity-web-stage.your-workers-subdomain.workers.dev`, + `https://cms-sanity-web-prod.your-workers-subdomain.workers.dev` and any + custom domain, each **with credentials allowed** — the Studio signs in + from them. +4. **Add a read token for draft mode** (optional; published posts need + none). Create a Viewer token (API → Tokens) and store it as a Worker + secret in each environment — Cloudflare's, so deploys leave it alone: + + ```bash + pnpm --filter @app/web exec wrangler secret put SANITY_API_READ_TOKEN --name cms-sanity-web-stage + pnpm --filter @app/web exec wrangler secret put SANITY_API_READ_TOKEN --name cms-sanity-web-prod + ``` + + Without it the Studio's live preview is refused (the draft-mode route + answers 401 and says why); everything else works. + +Then write at `/studio`. Published changes show on the blog within a minute +(Sanity's API CDN cache) — no deploy. + +## What is here + +| Surface | Where | +|---|---| +| Home, `/posts/[slug]`, the draft-mode banner and action | `apps/web/app/(blog)` | +| The Studio at `/studio` | `apps/web/app/(sanity)`, `apps/web/sanity.config.ts` | +| Draft mode enable route | `apps/web/app/api/draft-mode/enable/route.ts` | +| Client, queries, `sanityFetch`, image URLs | `apps/web/sanity/lib` | +| The sample posts an unconnected blog shows | `apps/web/sanity/lib/sample.ts` | +| Schemas, Studio plugins, generated types | `apps/web/sanity/schemas`, `apps/web/sanity/plugins`, `apps/web/sanity.types.ts` | +| The blog's name until its Settings document gives one | `apps/web/app/site.ts` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.jsonc`, `component.yaml` | +| Tests | `tests/web` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm typecheck +pnpm lint +pnpm test +pnpm build # typegen + next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +That needs no Sanity project (Checks runs exactly this). With one: + +```bash +cd apps/web +cp .env.example .env.local # NEXT_PUBLIC_SANITY_PROJECT_ID, NEXT_PUBLIC_SANITY_DATASET, SANITY_API_READ_TOKEN +cd ../.. +pnpm --filter @app/web dev # http://localhost:3000, the Studio at /studio +``` + +For the Worker locally, the project id and dataset are read at build time +and the token is a Worker secret: + +```bash +cd apps/web +cp .dev.vars.example .dev.vars # SANITY_API_READ_TOKEN= +NEXT_PUBLIC_SANITY_PROJECT_ID= NEXT_PUBLIC_SANITY_DATASET= pnpm build +pnpm preview # wrangler dev over the built Worker +``` + +| Variable | Read | What it does | +|---|---|---| +| `NEXT_PUBLIC_SANITY_PROJECT_ID` | build time | The Sanity project. Deployed builds take it from the `SANITY_PROJECT_ID` secret of their environment. Unset, the blog is unconnected: sample posts and a notice. | +| `NEXT_PUBLIC_SANITY_DATASET` | build time | The dataset (`SANITY_DATASET`); `production` when unset. | +| `SANITY_API_READ_TOKEN` | request time, in the Worker | A Viewer token for draft mode and live preview. Optional. | +| `NEXT_PUBLIC_CF_BEACON_TOKEN` | build time | Optional Cloudflare Web Analytics token. Unset, no script is rendered. | + +## 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 blog builds once per +environment, with that environment's Sanity project, and deploys — to +`stage`, then to `prod` once stage has converged on the same commit; `dev` +only verifies. The Worker is `cms-sanity-web-` on your account's +workers.dev subdomain, and every deploy is smoke-tested over HTTP: the home +page must render and the draft-mode route must refuse a request without a +preview secret. `checks.yml` runs install, typecheck, lint, test and build +on every pull request. (A push to `main` runs `ci.yml` alone, which builds +and deploys.) + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare token and account id are brokered per run from the workspace's +Cloudflare connection; nothing provider-shaped is stored in the repository +or in GitHub. + +## Custom domain + +The blog answers on workers.dev from its first deploy. To serve it on your +own domain, add the domain to the Cloudflare account the blog deploys into +and attach it to the Worker (dashboard → Workers & Pages → +`cms-sanity-web-prod` → Settings → Domains & Routes → Add → Custom domain), +then add it to the Sanity project's CORS origins. Nothing in the repository +changes: the blog renders no absolute link to itself. diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..075c4ea --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,23 @@ +# Task contract template for the 01-product landing — the whole blog in one +# pull request. 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. +# +# `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 +# the deploy set and the task plane's statement of the work are one list. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The blog's repository is born and linked, the whole blog lands in one pull request, and one convergence deploys it to stage and prod — serving its sample posts until a Sanity project is connected + affects: + - web + - web-tests + doneWhen: + - repo pushed, main pinned as default, workspace linked + - main convergence green (build, deploy and smoke on stage and prod) + - the blog 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..8a781db --- /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 blog'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..1fa7ea1 --- /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 a placed tree comes up branded and carrying nothing of the factory — +# and plans the blog onto stage and prod on a merge — and that the blog it +# produces installs, builds, deploys (dry) and serves with no Sanity project +# behind it. +# +# ─── WHY THIS IS NOT IN ci.yml OR checks.yml ────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every blog built from this repository. These jobs run +# `testing/*.sh`, and `testing/` is deliberately not placed — so in a blog 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) + 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; 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 blog'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, 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-blog \ + --set "productname=Acme Blog" \ + --set productdomain=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: the plan a convergence waits on is the lane + # pin's (its optional secret refs included), 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 BLOG IT PRODUCES WORKS, WITH NO SANITY PROJECT: its one + # landing under the checks its pull request waits on, the stage lane's own + # structure check, build, 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 — the sample posts, the "connect your Sanity project" + # notice, the Studio's connect page and draft mode's refusal. Pinned at the + # product's lane version, because that is the orun the product's CI runs. + blog: + 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 blog 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..77b3f48 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 blog converged. On main the convergence builds and tests the blog +# 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..1735546 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 product built by + # an Orun bootstrap never carries the placeholder — the 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 product 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 @@ -69,8 +91,8 @@ jobs: run: needs: plan runs-on: ubuntu-latest - # A BOOTSTRAP LANDING IS CHECKED BY `plan` ALONE. Every phase of the - # baseline bootstrap lands on a branch named for its task — the provenance + # A BOOTSTRAP LANDING IS CHECKED BY `plan` ALONE. Every phase of an Orun + # bootstrap lands on a branch named for its task — the provenance # pen's `orun/-`, and the bootstrap's tasks are all `BASE-n` — # and is merged by `orun.pr/land@v1` as soon as this workflow is green. # On those pull requests `plan` above is the check: the intent, every @@ -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,7 +196,7 @@ 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 + # account id — this product has 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 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/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..c1538fb --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,220 @@ +# BOOTSTRAP — a new blog from this baseline, in one landing + +How to go from **nothing** to **a Sanity-backed Next.js blog live on stage +and prod, documented**, with ONE provider consent — and how its owner then +connects it to a Sanity project. + +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 fourteen minutes** — an estimate summed from the +phases until a bootstrap measures it: ONE landing that places the whole blog +(its pull request waits on a full Next.js build in Checks) and one +convergence that builds and deploys it to stage and prod side by side, then +the record. It is cirrus-baseline's one-landing shape (baseline-v22): no +scaffold landing of its own, no second landing for the app. + +## 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, a probe deferred for a project not yet + created, and `from: workspace`). The blog's own `ci.yml` pins its lanes + separately (v2.78.4). +- A Cloudflare account (the free plan is enough for one Worker with Static + Assets) and its **Account API token** with Workers Scripts Write (the + console's Connect recipe lists the exact permission groups). It is the ONLY + provider credential the bootstrap needs. +- **No Sanity project.** Sanity is a hosted service the platform does not + broker, so the bootstrap neither asks for nor creates one: the blog is + built, deployed and verified unconnected — it serves bundled sample posts + under a "connect your Sanity project" notice, and `/studio` says how to + connect. Its owner connects a project afterwards (§3). +- An Orun Cloud workspace for the blog — `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/cms-sanity +cd cms-sanity + +orun new --blueprint repo-blueprint.yaml \ + --out ~/blogs/acme-notes --run-hooks --resume \ + --set reponame=acme-notes --set productname="Acme Notes" \ + --set productdomain=acme.dev --set githuborg=acme-inc \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain= +``` + +**`--run-hooks` is the difference between placing files and bootstrapping a +blog.** 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 blog's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the WHOLE blog in one PR — intent, CI, tooling, identity, `apps/web` + `tests/web`; the brokered Cloudflare secrets | its PR's checks, then the convergence green (build, deploy, smoke) and the blog answering on both workers.dev URLs | +| `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 ~/blogs/acme-notes --run-hooks \ + --phase 01-product --values ~/acme-notes.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 blog is PRODUCT-ONLY: the app, 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 does ship names any of them. +That promise is a test: `testing/leak.test.sh` derives what every phase would +place and gates the set and its contents, and `testing/placement.test.sh` +gates the same rules over a placed, branded tree. + +## 2. 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/cms-sanity +cd cms-sanity +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-notes --run-hooks --resume --progress json \ + --values /work/acme-notes.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the blog'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 | + +## 3. After the blog is live: connect Sanity + +The bootstrap ends with an UNCONNECTED blog: live, smoke-tested, showing its +sample posts. Connecting it is the owner's, because no platform connection +can create a Sanity project or mint its token. The blog's README, "Connecting +Sanity", has the steps; in short, per environment: + +```bash +orun secrets set SANITY_PROJECT_ID --env stage # the project id (public) +orun secrets set SANITY_DATASET --env stage # optional; production when unset +# then redeploy apps/web: change the stamp on the last line of +# apps/web/component.yaml (`# orun: redeploy …`) and merge +pnpm --filter @app/web exec wrangler secret put SANITY_API_READ_TOKEN --name -web-stage # draft mode only +``` + +…plus each Worker URL in the Sanity project's CORS origins, with credentials +allowed. The secrets are optional references in `apps/web/component.yaml` +(`optionalSecretEnv`): until they exist, the build skips them; once they do, +the next build reads them. + +- **Build on it**: the app is `apps/web`; the content model is + `apps/web/sanity/schemas` (re-run `pnpm --filter @app/web typegen` and + commit `schema.json` and `sanity.types.ts`). Published content needs no + deploy. +- **Custom domain**: attach it to the Worker in Cloudflare and add it to the + Sanity project's CORS origins (the blog's README, "Custom domain"). There + is no domain phase: attaching a domain needs zone permissions the brokered + `workers-deploy` token does not carry. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent, and + records whether each environment reads a Sanity project yet. + +## 4. 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; 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 +bash testing/e2e.test.sh # + network for pnpm: the blog built, dry-deployed and served, no Sanity project +``` + +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 work-tree strip, 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, probe) are stood in for, a landing becoming a commit on top of +orun's `Initial commit`. + +## 5. Cutting a baseline tag (maintainers) + +Every blog 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 add (or 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 for cloudflare, 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 | +| Deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write; re-issue it, re-connect, re-run `01-product` | +| Deploy lane's build: `Symlink … points out of the filesystem root` | the composition links one lane-wide install into the job's tree (stack-tectonic ≥ 0.20.0), which Turbopack refuses. The blog pins 0.19.0 for this; keep the pin | +| The live blog says "Sample content" | expected until a Sanity project is connected (§3). Not a failure | +| Connected, but `/` answers 500 | the project id or dataset is wrong, or the dataset is private without a token. Check `orun secrets list --env ` and the project in Sanity's console; fix the secret and redeploy | +| The Studio says it cannot sign in / CORS | the Worker URL is not in the Sanity project's CORS origins with credentials allowed | +| 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 blog redeploys | +| The blog'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 | +| the convergence reported green, then `verify` got 404 from both URLs | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` runs on a push to main (`testing/coverage.test.sh` holds it); read the CI run on main for the real result | +| the convergence planned no lanes at all | the merge's push had no `before` to diff against (a first push straight onto an unborn `main`). The landing merges a pull request into orun's `Initial commit`, so its push has one; re-run the phase and its retouch marker re-plans the blog | diff --git a/README.md b/README.md index 88a1e11..6934681 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,10 @@ Vercel's [Blog with Sanity CMS](https://github.com/vercel/next.js/tree/canary/ex `next-sanity`, draft mode with live preview through the Presentation tool, Sanity TypeGen, AI Assist and Unsplash presets, and the Sanity Studio embedded at `/studio` — running on **Cloudflare Workers + Static Assets** -through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), -inside the repository conventions of the -[Cirrus baseline](https://github.com/sourceplane/cirrus-baseline). +through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), and +packaged as an **Orun baseline**: one command takes a new blog from nothing +to live on stage and prod, in its own repository, under its own name, in +ONE landing — before its owner has a Sanity project at all. The template's code is the code and Sanity stays the SaaS it is. What the port adds is the Workers build, the monorepo wrapper, a test package and @@ -15,18 +16,69 @@ the deploy contract; what it changes is what Workers force: the blog renders on request against Sanity's API CDN instead of ISR on a read-only cache, the Studio mounts client-side so it ships as static assets and not inside the Worker, and Speed Insights becomes the Cloudflare Web Analytics -beacon. See [`specs/epics/cms-sanity`](specs/epics/cms-sanity/README.md) +beacon. What the baseline adds is everything needed to make a copy of it +somebody else's — built the way +[cirrus-baseline](https://github.com/sourceplane/cirrus-baseline) builds its +product since baseline-v22: one landing, one convergence — and what makes it +deployable with no Sanity project: an unconnected build renders bundled +sample posts under a visible "connect your Sanity project" notice instead of +failing. See [`specs/epics/cms-sanity`](specs/epics/cms-sanity/README.md) for the design, the milestones and the as-built status. -## What is here +## Instantiating a blog + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/cms-sanity +cd cms-sanity +orun new --blueprint repo-blueprint.yaml --out ~/blogs/acme-notes --run-hooks --resume \ + --set reponame=acme-notes --set productname="Acme Notes" --set productdomain=acme.dev \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`cms-sanity` → Build). Two phases — `01-product` (the repository, its CI and +the whole blog in one pull request, deployed to stage and prod by one +convergence, smoke-tested) and `02-docs` (the live deployment recorded) — +each landing one pull request in the new repository. +**[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. + +The new repository receives the **blog only** — the app, its tests, its CI, +its tooling, a README of its own and its operating contract — renamed +throughout to the blog's name, repository and Cloudflare Worker. None of this +repository's machinery ships, and nothing that ships names it. + +The only provider the bootstrap asks for is Cloudflare. **Sanity is not a +provider the platform brokers**, so the blog is built without it and its +owner connects a project afterwards: two optional Orun secrets +(`SANITY_PROJECT_ID`, `SANITY_DATASET`) and a redeploy, the Worker URLs in +the project's CORS origins, and — for draft mode only — a Worker secret +`SANITY_API_READ_TOKEN`. The blog's README, "Connecting Sanity" +(`.baseline/product/README.md` here), has the steps. + +| 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 blog's README and context pack | `.baseline/product/README.md`, `ai/context/` | +| The baseline's tests: contract, leak, offline bootstrap, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + +## What is here (the blog) | Surface | Where | |---|---| -| Home, `/posts/[slug]`, the draft-mode banner and action | `apps/web/app/(blog)` | -| The Studio at `/studio` | `apps/web/app/(sanity)`, `apps/web/sanity.config.ts` | +| Home, `/posts/[slug]`, the draft-mode banner and action, the unconnected notice | `apps/web/app/(blog)` | +| The Studio at `/studio` (or, unconnected, how to connect) | `apps/web/app/(sanity)`, `apps/web/sanity.config.ts` | | Draft mode enable route | `apps/web/app/api/draft-mode/enable/route.ts` | -| Client, queries, `sanityFetch`, image URLs | `apps/web/sanity/lib` | +| Client, queries, `sanityFetch`, image URLs, the project configuration | `apps/web/sanity/lib` | +| The sample posts an unconnected blog renders | `apps/web/sanity/lib/sample.ts` | | Schemas, Studio plugins, generated types | `apps/web/sanity/schemas`, `apps/web/sanity/plugins`, `apps/web/sanity.types.ts` | +| The blog's name (the rename's seam) | `apps/web/app/site.ts` | | Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.jsonc`, `component.yaml` | | Tests | `tests/web` (vitest) | @@ -38,17 +90,17 @@ pnpm typecheck pnpm lint pnpm test pnpm build # typegen + next build + opennextjs-cloudflare build → apps/web/.open-next +pnpm --filter @app/web preview # wrangler dev over the built Worker: the sample posts, unconnected ``` -That much needs no Sanity project: the build substitutes placeholder values -for the project id, dataset and token when they are unset (`Checks` runs -exactly this). To see content you need a project: +That much needs no Sanity project (`Checks` runs exactly this). To see your +own content: ```bash cd apps/web cp .env.example .env.local pnpm run setup # sanity init: picks or creates the project and dataset, writes .env.local -# then create a Viewer token at manage.sanity.io → API → Add API token and put it in .env.local as SANITY_API_READ_TOKEN +# a Viewer token from manage.sanity.io → API → Tokens, as SANITY_API_READ_TOKEN in .env.local (draft mode only) cd ../.. pnpm --filter @app/web dev # http://localhost:3000, the Studio at /studio ``` @@ -63,52 +115,32 @@ NEXT_PUBLIC_SANITY_PROJECT_ID= NEXT_PUBLIC_SANITY_DATASET= pnpm bui pnpm preview # wrangler dev over the built Worker ``` -Variables (`apps/web/.env.example`, `apps/web/.dev.vars.example`): - | Variable | Where it is read | What it does | |---|---|---| -| `NEXT_PUBLIC_SANITY_PROJECT_ID`, `NEXT_PUBLIC_SANITY_DATASET` | build time (`next build` inlines them into the server bundle and the Studio) | The Sanity project and dataset. The Orun build exports them from the product's secrets; unset, the build uses `placeholder` for both and the Worker has no project to read from. | -| `SANITY_API_READ_TOKEN` | request time, in the Worker | A Viewer token; draft mode and live preview fetch drafts with it. A Worker secret in stage/prod, `.dev.vars` locally, `.env.local` for `next dev`. Without it every blog route answers 500 (`Missing SANITY_API_READ_TOKEN`), as upstream. | +| `NEXT_PUBLIC_SANITY_PROJECT_ID` | build time (`next build` inlines it into the server bundle and the Studio) | The Sanity project. A deployed build takes it from its environment's `SANITY_PROJECT_ID` secret, best-effort. Unset, the blog is unconnected: the sample posts under a notice, a connect page at `/studio`, draft mode refused with 401. | +| `NEXT_PUBLIC_SANITY_DATASET` | build time | The dataset (`SANITY_DATASET`); `production` when unset. | +| `SANITY_API_READ_TOKEN` | request time, in the Worker | A Viewer token; draft mode and live preview fetch drafts with it. A Worker secret in stage/prod, `.dev.vars` locally, `.env.local` for `next dev`. Optional: without it the blog renders and draft mode answers 401 with the reason. | | `NEXT_PUBLIC_CF_BEACON_TOKEN` | build time | Optional. Cloudflare Web Analytics token (dashboard → Web Analytics → add a site). Unset, no script is rendered. | -Content: open `/studio`, create a post (the home page shows an onboarding -card until one exists), publish it. The blog reads Sanity's API CDN on every -request, so a published change shows within its 60 s TTL. - ## How it maps to Vercel | Vercel | Here | |---|---| | Next.js hosting (ISR pages, route handler, server action, Studio page) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets; `/` and `/posts/[slug]` render on every request (`force-dynamic`), `/studio` is a pre-rendered shell from the static-assets cache | -| Project env vars in the dashboard | Build time: project id and dataset from Orun secrets, inlined by `next build`. Run time: the read token as a Worker secret | +| Project env vars in the dashboard | Build time: project id and dataset from optional Orun secrets, inlined by `next build`. Run time: the read token as a Worker secret | +| A missing env var fails every route | An unconnected blog: sample posts, a notice, a connect page — deployable before a Sanity project exists | | Time-based ISR (`revalidate: 60`) | Sanity's API CDN, same 60 s TTL; nothing is pre-rendered or revalidated in the Worker | | Draft mode / Presentation live preview | Unchanged (`/api/draft-mode/enable`, cookies, `VisualEditing`) | -| The Studio rendered on the server | Loaded client-side only; 10 MB of static chunks, a 1.6 MB gzip Worker | +| The Studio rendered on the server | Loaded client-side only; megabytes of static chunks, a small Worker | | Vercel Speed Insights | Cloudflare Web Analytics beacon (`app/(blog)/analytics.tsx`) | -| Deploy on push | Orun deploys `cms-sanity-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | +| Deploy on push | Orun deploys `-web-{stage,prod}` on merge to `main` and smoke-tests it (`apps/web/component.yaml`) | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed | -## Deploying +## CI -`.github/workflows/checks.yml` runs install, typecheck, lint, test and build -on every push and pull request, with no Sanity credentials. `ci.yml` is the -Orun pipeline: set `execution.state.workspace` in `intent.yaml` to this -product's workspace (`orun cloud link`), connect a Cloudflare account to it, -and set the `ORUN_CI` repository variable to `true`. A merge to `main` then -builds the app with that environment's project id and dataset and deploys -the Worker to `stage`, then `prod`. - -Three things are the product's to set once per environment: - -```bash -# Build-time values, read by apps/web/component.yaml's secretEnv at build -# (each prompts for its value) -orun secrets set SANITY_PROJECT_ID --env stage # the project id from manage.sanity.io -orun secrets set SANITY_DATASET --env stage # usually "production" - -# The Worker secret (the deploy lane does not set it) -wrangler secret put SANITY_API_READ_TOKEN --name cms-sanity-web-stage # a Viewer token -``` - -Then, in the Sanity project's settings (manage.sanity.io → API → CORS -origins), allow the Worker's origin with credentials so the embedded Studio -can talk to the dataset from `https://cms-sanity-web-prod..workers.dev/studio`. +| Workflow | What it runs | Ships to a blog | +|---|---|---| +| `checks.yml` | install, wire fixtures (and that 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; 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 blueprint read by the pinned orun, the leak gate, the offline bootstrap, the blog built, dry-deployed and served with no Sanity project | 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..4516011 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# cms-sanity — 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, whether each blog reads a Sanity project yet, and the +> secrets inventory by name. Until then, nothing here claims the blog 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..045f087 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,162 @@ +# cms-sanity — operating contract (for humans and agents) + +This is the standing guide to how this blog 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 blog without any +other source. + +## What this system is + +A blog whose content lives in [Sanity](https://www.sanity.io), served from +Cloudflare, expressed as an Orun component-native desired-state repo. + +- **`apps/web`** — Next.js built by `@opennextjs/cloudflare` into one Worker + plus Static Assets. `/` and `/posts/` render per request against + Sanity's API CDN (60 s cache); the Sanity Studio is mounted at `/studio` + and ships as static assets; `/api/draft-mode/enable` turns on draft mode + for the Studio's live preview. +- **`tests/web`** — vitest over the Sanity helpers, the draft-mode route and + the unconnected blog, verified on the `dev` rung. +- **`tooling/*`** — shared TypeScript and ESLint configuration, and the + wrangler renderer for a deployable that comes to take wiring. + +There is no infrastructure component: Sanity is a hosted service the blog +reads over HTTPS, not something this repository provisions. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and test, nothing deploys. + +## Sanity: connected, or sample posts + +The blog reads ONE Sanity project and dataset, fixed at build time (`next +build` inlines them). Until a build has a project id it is **unconnected**: +every page renders the sample posts bundled in `apps/web/sanity/lib/sample.ts` +under a "connect your Sanity project" notice, `/studio` shows how to connect +instead of a Studio, and draft mode answers 401 with the reason. Nothing +fails: an unconnected blog deploys, passes its smoke test and serves. + +To connect it, per deployed environment: + +```bash +# 1. the project and dataset (public values; the next build reads them) +orun secrets set SANITY_PROJECT_ID --env stage # prompts for the value +orun secrets set SANITY_DATASET --env stage # usually "production"; unset means production +# …and the same with --env prod + +# 2. redeploy apps/web: the values are read when it BUILDS, and setting a +# secret builds nothing. Change the stamp on the last line of +# apps/web/component.yaml (`# orun: redeploy `) and merge. + +# 3. draft mode / live preview: a Viewer token, as a Worker secret +# (Cloudflare's, not Orun's — the deploy never touches it, so it survives deploys) +pnpm --filter @app/web exec wrangler secret put SANITY_API_READ_TOKEN --name cms-sanity-web-stage +``` + +And once per project, in Sanity's management console (API → CORS origins): +add each Worker URL (`https://cms-sanity-web-.your-workers-subdomain.workers.dev`, +and any custom domain) **with credentials allowed**, or the Studio cannot +sign in from the site. + +The secrets are read best-effort (`optionalSecretEnv` in +`apps/web/component.yaml`): a key nobody has stored is skipped, never a +failed lane. A wrong project id or dataset is not caught at build: the +blog's pages then fail at request time with Sanity's error, so probe `/` +after connecting. + +## 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. `apps/web` checks its committed `wrangler.jsonc` is there, builds once per + environment with that environment's Sanity project (if any), `wrangler + deploy` ships `cms-sanity-web-`, and a smoke test fetches `/` and + requires the blog's layout, then requires `/api/draft-mode/enable` to + refuse a request without a preview secret (401) — proof the Worker's + server code answers. +4. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +5. **The convergence run is the deployment.** A green run means every + planned lane passed. Failed lanes are retried with + `gh run rerun --failed`, which resumes the same execution. + +On a pull request nothing deploys: the blog builds and dry-deploys. + +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 "blog + converged"; probe the URLs instead. +- Published content needs no deploy: the blog reads Sanity on every request, + so a published post shows within the API CDN's 60 s. +- A change to `intent.yaml`'s `environments`, or to an Orun secret, maps to + no component and redeploys nothing on its own. Land it with a change under + `apps/web`. + +## Secrets model + +- **Brokered provider secrets**: `CLOUDFLARE_API_TOKEN` (the + `workers-deploy` scope) and `CLOUDFLARE_ACCOUNT_ID` — pointers minted per + run from the workspace's Cloudflare connection. No long-lived values at + rest; nothing to rotate by hand. +- **The Sanity project**: `SANITY_PROJECT_ID` and `SANITY_DATASET` on + `stage` and `prod`, stored by the owner, read by the build. Public values, + kept as secrets so each environment can name its own. +- **The read token**: `SANITY_API_READ_TOKEN`, a Worker secret per + environment, read at request time by draft mode only. +- Inspect by NAME only: `orun secrets list --org --env stage|prod`. No + tooling in this repository prints a secret value, and no document in + `ai/context/` may contain one. + +## Verifying the system + +```bash +# the blog on each environment (also recorded, probed, in deployment.md); +# an unconnected blog carries data-sanity-notice="unconnected" +curl -s https://cms-sanity-web-stage.your-workers-subdomain.workers.dev/ | grep -o 'data-sanity-notice="[a-z]*"' +curl -s -o /dev/null -w '%{http_code}\n' https://cms-sanity-web-prod.your-workers-subdomain.workers.dev/studio +curl -s -o /dev/null -w '%{http_code}\n' https://cms-sanity-web-prod.your-workers-subdomain.workers.dev/api/draft-mode/enable # 401 + +# 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 | +|---|---| +| connect a Sanity project | "Sanity: connected, or sample posts" above | +| write, edit, publish | `/studio` on the deployed site (or `pnpm --filter @app/web dev` → `localhost:3000/studio`); no deploy needed | +| change the blog's code | edit `apps/web` (its fallback name: `apps/web/app/site.ts`), merge | +| change the content model | the schemas in `apps/web/sanity/schemas`, then `pnpm --filter @app/web typegen` and commit `schema.json` and `sanity.types.ts` with them | +| 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 | +| serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"), and add it to the Sanity project's CORS origins | +| 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 blog: add a +component under `apps/`, `infra/` or `packages/` with a `component.yaml`, +land it as a pull request, and the convergence run deploys it. A component +under `infra/` whose wiring the Worker reads is declared in `apps/web`'s +`dependsOn` (enforced on `main`), so it is applied first. diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example index 8145d0d..59e526f 100644 --- a/apps/web/.dev.vars.example +++ b/apps/web/.dev.vars.example @@ -2,6 +2,7 @@ # Copy to .dev.vars (git-ignored). In stage/prod this is a Worker secret, set # once per environment with # wrangler secret put SANITY_API_READ_TOKEN --name cms-sanity-web- -# (README → Deploying); the deploy lane does not set it. The project id and -# dataset are not here: they are inlined at build time (see .env.example). +# (README → Connecting Sanity); the deploy lane never sets or clears it. The +# project id and dataset are not here: they are inlined at build time (see +# .env.example). Optional: without it draft mode is refused with a 401. SANITY_API_READ_TOKEN= diff --git a/apps/web/.env.example b/apps/web/.env.example index 91119bf..51068c1 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1,14 +1,16 @@ # https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#using-the-sanity-cli # Copy to .env.local (git-ignored) for `next dev`. The project id and dataset # are build-time public values: `next build` inlines them into the server and -# the Studio bundles, so the build that deploys must have them (the Orun build -# exports them from the product's secrets, apps/web/component.yaml). Unset, -# the build script substitutes `placeholder` for both so the credential-free -# build in Checks still runs — the Worker then has no project to read from. +# the Studio bundles. A deployed build takes them from its environment's +# SANITY_PROJECT_ID and SANITY_DATASET secrets (README → Connecting Sanity). +# Unset, the blog is unconnected: it renders its bundled sample posts under a +# "connect your Sanity project" notice, and /studio says how to connect. NEXT_PUBLIC_SANITY_PROJECT_ID= +# Optional: production when unset. NEXT_PUBLIC_SANITY_DATASET= -# The read token (draft mode / live preview) is read at request time. Here it -# serves `next dev`; the Worker reads it as a secret — see .dev.vars.example. +# The read token (draft mode / live preview only) is read at request time. +# Here it serves `next dev`; the Worker reads it as a secret — see +# .dev.vars.example. Optional: without it draft mode is refused with a 401. SANITY_API_READ_TOKEN= # Optional. Cloudflare Web Analytics beacon token (stands in for Vercel Speed # Insights). Unset → no script is rendered. diff --git a/apps/web/README.md b/apps/web/README.md index 168a293..6b0b161 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,310 +1,30 @@ -# A statically generated blog example using Next.js and Sanity +# apps/web — the blog -![Screenshot of Sanity Studio using Presentation Tool to do Visual Editing](https://github.com/sanity-io/next.js/assets/81981/59ecd9d6-7a78-41c6-95f7-275f66fe3c9d) +A blog whose content lives in Sanity, from Vercel's +[Blog with Sanity CMS](https://github.com/vercel/next.js/tree/canary/examples/cms-sanity) +(MIT), running on Cloudflare Workers + Static Assets: -This starter is a statically generated blog that uses Next.js App Router for the frontend and [Sanity][sanity-homepage] to handle its content. It comes with a native Sanity Studio that offers features like real-time collaboration and visual editing with live updates using [Presentation][presentation]. +- Posts, authors and a Settings singleton in a Sanity dataset, read over GROQ + with `next-sanity` (`sanity/lib/queries.ts`), typed by Sanity TypeGen + (`sanity.types.ts`, regenerated by `pnpm typegen` and on every build) +- The Sanity Studio at `/studio`, loaded client-side so it ships as static + assets, with the Presentation tool's live preview through draft mode + (`/api/draft-mode/enable`), AI Assist presets and Unsplash images +- Every blog page rendered on request against Sanity's API CDN (60 s cache) +- Tailwind 4, Inter, Cloudflare Web Analytics (set `NEXT_PUBLIC_CF_BEACON_TOKEN`) -The Studio connects to Sanity Content Lake, which gives you hosted content APIs with a flexible query language, on-demand image transformations, powerful patching, and more. You can use this starter to kick-start a blog or learn these technologies. - -## Features - -- A performant, static blog with editable posts, authors, and site settings -- TypeScript setup with [Sanity TypeGen](https://www.sanity.io/docs/sanity-typegen) -- A native and customizable authoring environment, accessible on `yourblog.com/studio` -- Real-time and collaborative content editing with fine-grained revision history -- Side-by-side instant content preview that works across your whole site -- Support for block content and the most advanced custom fields capability in the industry -- Incremental Static Revalidation; no need to wait for a rebuild to publish new content -- Unsplash integration setup for easy media management -- [Sanity AI Assist preconfigured for image alt text generation](https://www.sanity.io/docs/ai-assist?utm_source=github.com&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=) -- Out of the box support for [Vercel Visual Editing](https://www.sanity.io/blog/visual-editing-sanity-vercel?utm_source=github.com&utm_medium=referral&utm_campaign=may-vercel-launch). - -## Demo - -### [https://next-blog.sanity.build](https://next-blog.sanity.build) - -## Deploy your own - -Use the Deploy Button below, you'll deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) as well as connect it to your Sanity dataset using [the Sanity Vercel Integration][integration]. - -[![Deploy with Vercel](https://vercel.com/button)][vercel-deploy] - -## How to use - -Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: - -```bash -npx create-next-app --example cms-sanity next-sanity-blog -``` - -```bash -yarn create next-app --example cms-sanity next-sanity-blog -``` +With no Sanity project id at build time the blog is **unconnected**: it +renders the sample posts in `sanity/lib/sample.ts` under a notice, and +`/studio` says how to connect. The blog's name until its Settings document +gives one is in `app/site.ts`. ```bash -pnpm create next-app --example cms-sanity next-sanity-blog +pnpm dev # typegen + next dev on http://localhost:3000 (the Studio at /studio) +pnpm build # typegen + next build + opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker +pnpm run setup # sanity init: pick or create a project and dataset, written to .env.local ``` -Whenever you edit a GROQ query you update the TypeScript types by running: - -```bash -npm run typegen -``` - -# Configuration - -- [Step 1. Set up the environment](#step-1-set-up-the-environment) - - [Reuse remote environment variables](#reuse-remote-environment-variables) - - [Using the Sanity CLI](#using-the-sanity-cli) - - [Creating a read token](#creating-a-read-token) -- [Step 2. Run Next.js locally in development mode](#step-2-run-nextjs-locally-in-development-mode) -- [Step 3. Populate content](#step-3-populate-content) -- [Step 4. Deploy to production](#step-4-deploy-to-production) -- [Next steps](#next-steps) - -## Step 1. Set up the environment - -### Reuse remote environment variables - -If you started with [deploying your own](#deploy-your-own) then you can run this to reuse the environment variables from the Vercel project and skip to the next step: - -```bash -npx vercel link -npx vercel env pull -``` - -### Using the Sanity CLI - -Copy the `.env.local.example` file to `.env.local` to get started: - -```bash -cp -i .env.local.example .env.local -``` - -Run the setup command to get setup with a Sanity project, dataset and their relevant environment variables: - -```bash -npm run setup -``` - -```bash -yarn setup -``` - -```bash -pnpm run setup -``` - -You'll be asked multiple questions, here's a sample output of what you can expect: - -```bash -Need to install the following packages: -sanity@3.30.1 -Ok to proceed? (y) y -You're setting up a new project! -We'll make sure you have an account with Sanity.io. -Press ctrl + C at any time to quit. - -Prefer web interfaces to terminals? -You can also set up best practice Sanity projects with -your favorite frontends on https://www.sanity.io/templates - -Looks like you already have a Sanity-account. Sweet! - -✔ Fetching existing projects -? Select project to use Templates [r0z1eifg] -? Select dataset to use blog-vercel -? Would you like to add configuration files for a Sanity project in this Next.js folder? No - -Detected framework Next.js, using prefix 'NEXT_PUBLIC_' -Found existing NEXT_PUBLIC_SANITY_PROJECT_ID, replacing value. -Found existing NEXT_PUBLIC_SANITY_DATASET, replacing value. -``` - -It's important that when you're asked `Would you like to add configuration files for a Sanity project in this Next.js folder?` that you answer `No` as this example is already setup with the required configuration files. - -#### Creating a read token - -This far your `.env.local` file should have values for `NEXT_PUBLIC_SANITY_PROJECT_ID` and `NEXT_PUBLIC_SANITY_DATASET`. -Before you can run the project you need to setup a read token (`SANITY_API_READ_TOKEN`), it's used for authentication when Sanity Studio is live previewing your application. - -1. Go to [manage.sanity.io](https://manage.sanity.io/) and select your project. -2. Click on the `🔌 API` tab. -3. Click on `+ Add API token`. -4. Name it "next blog live preview read token" and set `Permissions` to `Viewer` and hit `Save`. -5. Copy the token and add it to your `.env.local` file. - -```bash -SANITY_API_READ_TOKEN="" -``` - -Your `.env.local` file should look something like this: - -```bash -NEXT_PUBLIC_SANITY_PROJECT_ID="r0z1eifg" -NEXT_PUBLIC_SANITY_DATASET="blog-vercel" -SANITY_API_READ_TOKEN="sk..." -``` - -> [!CAUTION] -> Make sure to add `.env.local` to your `.gitignore` file so you don't accidentally commit it to your repository. - -## Step 2. Run Next.js locally in development mode - -```bash -npm install && npm run dev -``` - -```bash -yarn install && yarn dev -``` - -```bash -pnpm install && pnpm dev -``` - -Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions). - -## Step 3. Populate content - -Open your Sanity Studio that should be running on [http://localhost:3000/studio](http://localhost:3000/studio). - -By default you're taken to the [Presentation tool][presentation], which has a preview of the blog on the left hand side, and a list of documents on the right hand side. - -
-View screenshot ✨ - -![screenshot](https://github.com/vercel/next.js/assets/81981/07cbc580-4a03-4837-9aa4-90b632c95630) - -
- -We're all set to do some content creation! - -- Click on the **"+ Create"** button top left and select **Post** -- Type some dummy data for the **Title** -- **Generate** a **Slug** -
- Now that you have a slug you should see the post show up in the preview on the left hand side ✨ - - ![screenshot](https://github.com/vercel/next.js/assets/81981/05b74848-6ae4-442b-8995-0b7e2180aa74) - -
- -- Fill in **Content** with some dummy text -
- Or generate it with AI Assist ✨ - - If you've enabled [AI Assist][enable-ai-assist] you click on the sparkles ✨ button and generate a draft based on your title and then on **Generate sample content**. - - ![screenshot](https://github.com/vercel/next.js/assets/81981/2276d8ad-5b55-447c-befe-d53249f091e1) - -
- -- Summarize the **Content** in the **Excerpt** field -
- Or have AI Assist summarize it for you ✨ - - If you've enabled [AI Assist][enable-ai-assist] you click on the sparkles ✨ button and then on **Generate sample content**. - - ![screenshot](https://github.com/vercel/next.js/assets/81981/d24b9b37-cd88-4519-8094-f4c956102450) - -
- -- Select a **Cover Image** from [Unsplash]. -
- Unsplash is available in the **Select** dropdown ✨ - - ![screenshot](https://github.com/vercel/next.js/assets/81981/204d004d-9396-434e-8795-a8b68a2ed89b) - -
-
- Click the "Crop image" button to adjust hotspots and cropping ✨ - - ![screenshot](https://github.com/vercel/next.js/assets/81981/e905fc6e-5bab-46a7-baec-7cb08747772c) - -
-
- You can preview the results live on the left side, and additional formats on the right side ✨ - - ![screenshot](https://github.com/vercel/next.js/assets/81981/6c59eef0-d2d9-4d77-928a-98e99df4b1df) - -
- -- Customize the blog name, description and more. -
- Click "Structure" at the top center, then on "Settings" on the left hand side ✨ - - ![screenshot](https://github.com/vercel/next.js/assets/81981/14f48d83-af81-4589-900e-a7a598cc608a) - -
-
- Once you have a "Settings" document, you can customize it inside "Presentation" ✨ - - ![screenshot](https://github.com/vercel/next.js/assets/81981/e3473f7b-5e7e-46ab-8d43-cae54a4b929b) - -
- -> [!IMPORTANT] -> For each post record, you need to click **Publish** after saving for it to be visible outside Draft Mode. In production new content is using [Time-based Revalidation](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#time-based-revalidation), which means it may take up to 1 minute before changes show up. Since a stale-while-revalidate pattern is used you may need to refresh a couple of times to see the changes. - -## Step 4. Deploy to production - -> [!NOTE] -> If you already [deployed with Vercel earlier](#deploy-your-own) you can skip this step. - -To deploy your local project to Vercel, push it to [GitHub](https://docs.github.com/en/get-started/importing-your-projects-to-github/importing-source-code-to-github/adding-locally-hosted-code-to-github)/GitLab/Bitbucket and [import to Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example). - -> [!IMPORTANT] -> When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file. - -After it's deployed link your local code to the Vercel project: - -```bash -npx vercel link -``` - -> [!TIP] -> In production you can exit Draft Mode by clicking on _"Back to published"_ at the top. On [Preview deployments](https://vercel.com/docs/deployments/preview-deployments) you can [toggle Draft Mode in the Vercel Toolbar](https://vercel.com/docs/workflow-collaboration/draft-mode#enabling-draft-mode-in-the-vercel-toolbar). - -## Next steps - -- [Join the Sanity community](https://slack.sanity.io/) - -## Related examples - -- [AgilityCMS](/examples/cms-agilitycms) -- [Builder.io](/examples/cms-builder-io) -- [ButterCMS](/examples/cms-buttercms) -- [Contentful](/examples/cms-contentful) -- [Cosmic](/examples/cms-cosmic) -- [DatoCMS](/examples/cms-datocms) -- [DotCMS](/examples/cms-dotcms) -- [Drupal](/examples/cms-drupal) -- [Enterspeed](/examples/cms-enterspeed) -- [Ghost](/examples/cms-ghost) -- [GraphCMS](/examples/cms-graphcms) -- [Kontent.ai](/examples/cms-kontent-ai) -- [MakeSwift](/examples/cms-makeswift) -- [Payload](/examples/cms-payload) -- [Plasmic](/examples/cms-plasmic) -- [Prepr](/examples/cms-prepr) -- [Prismic](/examples/cms-prismic) -- [Sanity](/examples/cms-sanity) -- [Sitecore XM Cloud](/examples/cms-sitecore-xmcloud) -- [Sitefinity](/examples/cms-sitefinity) -- [Storyblok](/examples/cms-storyblok) -- [TakeShape](/examples/cms-takeshape) -- [Tina](/examples/cms-tina) -- [Umbraco](/examples/cms-umbraco) -- [Umbraco heartcore](/examples/cms-umbraco-heartcore) -- [Webiny](/examples/cms-webiny) -- [WordPress](/examples/cms-wordpress) -- [Blog Starter](/examples/blog-starter) - -[vercel-deploy]: https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fcms-sanity&repository-name=cms-sanity&project-name=cms-sanity&demo-title=Blog%20using%20Next.js%20%26%20Sanity&demo-description=Real-time%20updates%2C%20seamless%20editing%2C%20no%20rebuild%20delays.&demo-url=https%3A%2F%2Fnext-blog.sanity.build%2F&demo-image=https%3A%2F%2Fgithub.com%2Fsanity-io%2Fnext-sanity%2Fassets%2F81981%2Fb81296a9-1f53-4eec-8948-3cb51aca1259&integration-ids=oac_hb2LITYajhRQ0i4QznmKH7gx -[integration]: https://www.sanity.io/docs/vercel-integration -[`.env.local.example`]: .env.local.example -[unsplash]: https://unsplash.com -[sanity-homepage]: https://www.sanity.io?utm_source=github.com&utm_medium=referral&utm_campaign=nextjs-v3vercelstarter -[presentation]: https://www.sanity.io/docs/presentation -[enable-ai-assist]: https://www.sanity.io/plugins/ai-assist#enabling-the-ai-assist-api +How it is connected to a Sanity project and deployed — per environment, on +merge to `main` — is the repository's README and `component.yaml` beside +this file. diff --git a/apps/web/app/(blog)/connect-sanity.tsx b/apps/web/app/(blog)/connect-sanity.tsx new file mode 100644 index 0000000..96ce7b2 --- /dev/null +++ b/apps/web/app/(blog)/connect-sanity.tsx @@ -0,0 +1,28 @@ +import Link from "next/link"; + +/** + * Shown above every blog page while the build has no Sanity project id: the + * posts below it are the bundled samples (sanity/lib/sample.ts), and this says + * so, and where the steps to connect a project are. Gone once one is set. + */ +export default function ConnectSanityNotice() { + return ( +
+

+ Sample content. This blog is not connected to a Sanity + project yet.{" "} + + Connect your Sanity project + {" "} + to publish your own posts. +

+
+ ); +} diff --git a/apps/web/app/(blog)/layout.tsx b/apps/web/app/(blog)/layout.tsx index 2d0c65b..e0b3810 100644 --- a/apps/web/app/(blog)/layout.tsx +++ b/apps/web/app/(blog)/layout.tsx @@ -8,8 +8,10 @@ import { draftMode } from "next/headers"; import AlertBanner from "./alert-banner"; import { CloudflareWebAnalytics } from "./analytics"; +import ConnectSanityNotice from "./connect-sanity"; import PortableText from "./portable-text"; +import { isSanityConfigured } from "@/sanity/lib/api"; import * as demo from "@/sanity/lib/demo"; import { sanityFetch } from "@/sanity/lib/fetch"; import { settingsQuery } from "@/sanity/lib/queries"; @@ -78,6 +80,7 @@ export default async function RootLayout({
{isDraftMode && } + {!isSanityConfigured && }
{children}