@capacms/sdk 1.0.0-next.1 → 1.0.0-next.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +487 -0
  2. package/README.md +1810 -183
  3. package/bin/capa-codegen.js +192 -5
  4. package/bin/capa.js +235 -0
  5. package/bin/graphql-project.js +142 -0
  6. package/bin/project-env.js +58 -0
  7. package/dist/client.d.ts +89 -4
  8. package/dist/client.js +40 -5
  9. package/dist/codegen.d.ts +55 -0
  10. package/dist/codegen.js +320 -39
  11. package/dist/config.d.ts +5 -36
  12. package/dist/config.js +47 -1
  13. package/dist/esm/image/index.d.ts +187 -0
  14. package/dist/esm/image/index.js +353 -0
  15. package/dist/esm/image/shared-params.generated.d.ts +314 -0
  16. package/dist/esm/image/shared-params.generated.js +680 -0
  17. package/dist/esm/nextjs/image-loader.d.ts +60 -0
  18. package/dist/esm/nextjs/image-loader.js +67 -0
  19. package/dist/esm/nextjs/overlay.d.ts +30 -0
  20. package/dist/esm/nextjs/overlay.js +75 -0
  21. package/dist/esm/overlay/index.d.ts +32 -0
  22. package/dist/esm/overlay/index.js +576 -0
  23. package/dist/esm/overlay/protocol.d.ts +187 -0
  24. package/dist/esm/overlay/protocol.js +240 -0
  25. package/dist/esm/package.json +4 -0
  26. package/dist/graphql-codegen.d.ts +117 -0
  27. package/dist/graphql-codegen.js +705 -0
  28. package/dist/http.js +1 -1
  29. package/dist/image/index.d.ts +187 -0
  30. package/dist/image/index.js +362 -0
  31. package/dist/image/shared-params.generated.d.ts +314 -0
  32. package/dist/image/shared-params.generated.js +700 -0
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +2 -1
  35. package/dist/next/attrs.d.ts +84 -10
  36. package/dist/next/attrs.js +119 -2
  37. package/dist/next/client.d.ts +176 -32
  38. package/dist/next/client.js +212 -90
  39. package/dist/next/entry-fields.d.ts +203 -0
  40. package/dist/next/entry-fields.js +2 -0
  41. package/dist/next/errors.d.ts +136 -0
  42. package/dist/next/errors.js +214 -0
  43. package/dist/next/field-names.d.ts +37 -0
  44. package/dist/next/field-names.js +145 -0
  45. package/dist/next/graphql/build.d.ts +27 -0
  46. package/dist/next/graphql/build.js +98 -0
  47. package/dist/next/graphql/documents.d.ts +67 -0
  48. package/dist/next/graphql/documents.js +35 -0
  49. package/dist/next/graphql/edit-mode.d.ts +16 -0
  50. package/dist/next/graphql/edit-mode.js +93 -0
  51. package/dist/next/graphql/filter-values.d.ts +34 -0
  52. package/dist/next/graphql/filter-values.js +96 -0
  53. package/dist/next/graphql/introspection.d.ts +89 -0
  54. package/dist/next/graphql/introspection.js +102 -0
  55. package/dist/next/graphql/plan.d.ts +115 -0
  56. package/dist/next/graphql/plan.js +531 -0
  57. package/dist/next/graphql/request.d.ts +228 -0
  58. package/dist/next/graphql/request.js +283 -0
  59. package/dist/next/graphql/rest.d.ts +66 -0
  60. package/dist/next/graphql/rest.js +502 -0
  61. package/dist/next/graphql/selection.d.ts +55 -0
  62. package/dist/next/graphql/selection.js +212 -0
  63. package/dist/next/graphql/sha256.d.ts +13 -0
  64. package/dist/next/graphql/sha256.js +86 -0
  65. package/dist/next/graphql/summary.d.ts +83 -0
  66. package/dist/next/graphql/summary.js +151 -0
  67. package/dist/next/graphql/tree-layout.d.ts +36 -0
  68. package/dist/next/graphql/tree-layout.js +20 -0
  69. package/dist/next/graphql/tree.d.ts +171 -0
  70. package/dist/next/graphql/tree.js +258 -0
  71. package/dist/next/graphql/typed.d.ts +261 -0
  72. package/dist/next/graphql/typed.js +146 -0
  73. package/dist/next/index.d.ts +30 -5
  74. package/dist/next/index.js +32 -1
  75. package/dist/next/inflate.d.ts +51 -0
  76. package/dist/next/inflate.js +243 -0
  77. package/dist/next/key-family.d.ts +31 -0
  78. package/dist/next/key-family.js +66 -0
  79. package/dist/next/select-types.d.ts +58 -5
  80. package/dist/next/system-keys.d.ts +27 -0
  81. package/dist/next/system-keys.js +42 -0
  82. package/dist/nextjs/image-loader.d.ts +60 -0
  83. package/dist/nextjs/image-loader.js +71 -0
  84. package/dist/nextjs/index.d.ts +484 -5
  85. package/dist/nextjs/index.js +688 -6
  86. package/dist/nextjs/overlay.d.ts +30 -0
  87. package/dist/nextjs/overlay.js +78 -0
  88. package/dist/overlay/index.d.ts +14 -2
  89. package/dist/overlay/index.js +282 -43
  90. package/dist/overlay/protocol.d.ts +98 -2
  91. package/dist/overlay/protocol.js +151 -4
  92. package/dist/webhooks.d.ts +8 -0
  93. package/package.json +63 -15
package/README.md CHANGED
@@ -1,21 +1,36 @@
1
1
  # @capacms/sdk
2
2
 
3
- ## The `/api/` client (`@capacms/sdk/next`)
4
-
5
- Install the SDK from the `next` dist tag:
3
+ The TypeScript SDK for Capa's content API: REST and GraphQL reads typed from
4
+ your models, Next.js caching and live preview, and codegen. The API reference
5
+ is at https://docs.capacms.com/api.
6
6
 
7
7
  ```sh
8
8
  pnpm add @capacms/sdk@next
9
9
  ```
10
10
 
11
+ It runs on Node 18 or later. Its types need TypeScript 5.0 or later, with
12
+ `strict` on or off.
13
+
14
+ | Import | What it is |
15
+ |---|---|
16
+ | `@capacms/sdk/next` | The client for `/api/`: entries, GraphQL, pages and preview. It takes a `cap_` key, or the legacy key a site already holds for reads. Start here. |
17
+ | `@capacms/sdk/nextjs` | Next.js helpers: `graphql()` in a server component, cache tags, draft and edit mode, webhook revalidation. |
18
+ | `@capacms/sdk/nextjs/overlay` | The live preview overlay, as a Next.js client component. |
19
+ | `@capacms/sdk/overlay` | The same overlay without Next. |
20
+ | `@capacms/sdk/image` | Image URLs on Capa's CDN for any framework: `imageUrl`, `srcSet`, `sizes` and `isCapaImageUrl`. |
21
+ | `@capacms/sdk/nextjs/image-loader` | A `next/image` loader that lets Capa's CDN resize, for `images.loaderFile`. |
22
+ | `@capacms/sdk` | The legacy `/v2/api` client, which takes a legacy key and a tenant id and refuses a `cap_` key, and the webhook signature check. |
23
+
24
+ ## The `/api/` client (`@capacms/sdk/next`)
25
+
11
26
  Create one client per key and pin the platform version in code:
12
27
 
13
28
  ```ts
14
29
  import { createClient, CapaError } from "@capacms/sdk/next";
15
30
 
16
31
  const capa = createClient({
17
- baseUrl: process.env.CAPA_BASE_URL!,
18
- apiKey: process.env.CAPA_API_KEY!, // cap_live_... or cap_test_...
32
+ baseUrl: process.env.CAPA_API_URL!,
33
+ apiKey: process.env.CAPA_KEY!, // cap_live_..., cap_test_..., or the legacy key your site has
19
34
  version: "2026-10-01",
20
35
  contract: 1,
21
36
  });
@@ -23,7 +38,32 @@ const capa = createClient({
23
38
 
24
39
  The `/api/` client sends `x-api-key`, `Capa-Version`, optional
25
40
  `Capa-Contract`, and `Accept: application/json`. It never sends
26
- `X-Tenant-Key`; the tenant comes from the `cap_` key.
41
+ `X-Tenant-Key`; the tenant comes from the key.
42
+
43
+ ### Keys
44
+
45
+ A `cap_` key is the key for `/api/`: scoped, and stored hashed. `cap_live_`
46
+ reads published content, `cap_test_` drafts too. Mint one in the Capa admin
47
+ under Developers > Keys.
48
+
49
+ The legacy key your site already holds works too, for every read: a `pk_`
50
+ or `sk_` key, or an older key with no prefix, since every key but `cap_` is
51
+ a legacy key to the API. That covers `entries`, `graphql`,
52
+ `graphqlSchema`, `pages`, `me`, `versions` and `preview`: a site checks an
53
+ editor's preview link with the key it already holds, and Capa refuses a link
54
+ made for another project. The first client built with one prints a warning
55
+ once per process, naming the `cap_` key to mint. Draft reads through the SDK
56
+ keep their rule and take a `cap_` key only: `draftClient`'s `draft` config,
57
+ and `CAPA_DRAFT_KEY` for `getCapaClient` and `graphql()`, throw a `TypeError`
58
+ for a legacy key before any request. An `apiKey` that is not a string is
59
+ refused where the client is built.
60
+
61
+ `CAPA_API_URL` and `CAPA_KEY` are the names every Capa tool reads: the
62
+ `/nextjs` helpers, `capa-codegen` and Capa's MCP server, so one `.env` serves
63
+ them all. `capa persist` registers with the development key in
64
+ `CAPA_DRAFT_KEY`, since only a development key stores a document (see
65
+ Persisted queries). `CAPA_BASE_URL` and `CAPA_API_KEY` still work as
66
+ aliases; when both are set, the first pair wins.
27
67
 
28
68
  ### Entries
29
69
 
@@ -53,8 +93,8 @@ const one = await capa.entries.get("articles", "entry-id", {
53
93
  });
54
94
  ```
55
95
 
56
- `select` may be the grammar string from `docs/api/entries.md` or the object
57
- form above. Lists return `{ data, page, meta, cacheTags }`; singles return
96
+ `select` may be the grammar string the API reference describes
97
+ (https://docs.capacms.com/api/entries) or the object form above. Lists return `{ data, page, meta, cacheTags }`; singles return
58
98
  `{ data, meta, cacheTags }`. `cacheTags` is parsed from the `Surrogate-Key`
59
99
  header. `get()` returns `null` for `404 entry_not_found` and throws every other
60
100
  error.
@@ -64,7 +104,7 @@ Filters use the `/api/` operators:
64
104
  ```ts
65
105
  await capa.entries.list("articles", {
66
106
  filter: {
67
- id: { in: ["a", "b"] },
107
+ id: { in: ["00000000-0000-4000-8000-000000000021", "00000000-0000-4000-8000-000000000022"] },
68
108
  views: { gte: 10 },
69
109
  tags: { hasAny: ["news", "launch"] },
70
110
  },
@@ -75,6 +115,102 @@ await capa.entries.list("articles", {
75
115
  Unknown filter operators throw a local `TypeError` before any request is sent.
76
116
  Per-call `{ signal }` is forwarded to `fetch`.
77
117
 
118
+ #### Typed reads
119
+
120
+ `capa-codegen` writes an interface per model (see Codegen). Pass it, and the
121
+ select's own type, and `fields` is typed as the API returns it:
122
+
123
+ ```ts
124
+ import type { Articles, ArticlesSelect } from "./capa-types"; // written by capa-codegen
125
+
126
+ const select = [
127
+ "title",
128
+ { author: ["name"] },
129
+ { coauthors: { select: ["name"], limit: 3 } },
130
+ ] as const satisfies ArticlesSelect;
131
+
132
+ const typed = await capa.entries.list<Articles, typeof select>("articles", { select });
133
+
134
+ for (const article of typed.data) {
135
+ const { title, author, coauthors } = article.fields;
136
+ if (author && "fields" in author) console.log(title, author.fields.name);
137
+ for (const coauthor of coauthors.items) {
138
+ if ("fields" in coauthor) console.log(coauthor.fields.name);
139
+ }
140
+ article.fields.body; // compile error: the select does not name it
141
+ }
142
+ ```
143
+
144
+ - A relation the select expands is the related entry, with its own `fields`,
145
+ or `{ id, model, missing: true }` when that entry was deleted, is
146
+ unpublished for a production key, or is in a model the key cannot read.
147
+ `"fields" in author` tells them apart.
148
+ - A relation the select names without expanding it (`"author"`, or every
149
+ relation under `*`) is a reference, `{ id, model }`.
150
+ - A relation list is `{ items, pageInfo }`, expanded or not.
151
+ - Media is `{ id, url, alt, type, width, height }`.
152
+ - A field the select names is always there, and `null` when it was never
153
+ filled, as the API writes it. `title?: string` in the model reads as
154
+ `string | null`.
155
+ - A field the select does not name is not there, so reading it does not
156
+ compile.
157
+
158
+ Without `typeof select`, or with a select written as a string, every field is
159
+ typed, and each relation as whichever of the three it may be. `get` and
160
+ `iterate` take the same two types, and `EntryFields<Articles, typeof select>`
161
+ names the type of `fields`.
162
+
163
+ ### Flat responses: each related entry once
164
+
165
+ By default an expanded relation is nested where you selected it, so twenty
166
+ articles by one author carry that author twenty times. Pass `shape: "flat"` and
167
+ every relation comes back as a `{ id, model }` reference, with each expanded
168
+ entry once in `included`, keyed by model namespace and then id:
169
+
170
+ ```ts
171
+ const select = ["title", { author: ["name"] }] as const satisfies Select<Article>;
172
+ const flat = await capa.entries.list<Article, typeof select>("articles", {
173
+ select,
174
+ shape: "flat",
175
+ });
176
+
177
+ flat.data[0].fields.author; // { id: "…", model: "authors" }
178
+ flat.included.authors[authorId].fields; // { name: "Ada Vale" }, typed from Author
179
+ ```
180
+
181
+ `included` is typed by the select: the union of the entry types it expands, at
182
+ any depth, each field of which may be absent, since an entry holds what every
183
+ path that reached it selected. A relation in `data` or in `included` is a
184
+ reference. A select written as a plain string types `included` as
185
+ `Record<string, unknown>`. `get` takes `shape: "flat"` the same way.
186
+ `iterate` reads the tree shape only.
187
+
188
+ `inflate` turns a flat result back into the tree result, deep-equal to what the
189
+ same request without `shape` returns:
190
+
191
+ ```ts
192
+ import { inflate } from "@capacms/sdk/next";
193
+
194
+ const tree = inflate(flat); // { data, page, meta, cacheTags }, typed as the tree read
195
+ ```
196
+
197
+ - It walks the select the request sent. A result from this client carries it
198
+ (`flat.select`); for a body you fetched yourself, pass it:
199
+ `inflate(body, "title,author(name)")`.
200
+ - `$tags`, `$createdAt` and the other `$` names in the select are the system
201
+ keys, as the API reads them, so `select=$tags,tags` on a model with its own
202
+ `tags` field comes back with both.
203
+ - It returns copies. The same author under twenty articles is twenty equal,
204
+ independent objects, as when a tree body is parsed. The input is not changed.
205
+ - Cycles end where the select ends: `a` related to `b` related to `a` is
206
+ inflated to the depth you wrote and no further.
207
+ - An entry reached by two paths holds the union of what they selected, and one
208
+ value per field. If two paths expand the same array relation with different
209
+ `limit` or `sort`, the first one wins, and `inflate` cannot tell them apart.
210
+ Every other request round-trips exactly.
211
+ - In edit mode, included entries are marked, and so is every copy `inflate`
212
+ makes of them.
213
+
78
214
  ### Errors
79
215
 
80
216
  ```ts
@@ -105,7 +241,11 @@ const capa = createClient({ baseUrl, apiKey, version: "2026-10-01", fetch: fetch
105
241
  ```
106
242
 
107
243
  `withCache` merges `{ next: { tags, revalidate } }` into every fetch call.
108
- `tagsFor` builds Capa surrogate keys: `m:`, `e:`, `k:`, and `t:`.
244
+ `tagsFor` builds Capa surrogate keys: `m:`, `e:`, `k:`, and `t:`, by id, and
245
+ `tagsFor({ namespace: "articles" })` builds `capa:model:articles`, the tag
246
+ for a GraphQL read (see GraphQL), and `capa:media`. `revalidateFromWebhook`
247
+ revalidates all of them for the entry and model a webhook names, and for a
248
+ media event, the file's `f:` key and `capa:media`.
109
249
 
110
250
  Webhook revalidation pairs with the existing signature verifier:
111
251
 
@@ -139,19 +279,1045 @@ SDK never imports `next/*`:
139
279
  ```ts
140
280
  import { draftMode } from "next/headers";
141
281
  import { draftClient } from "@capacms/sdk/nextjs";
282
+ import type { CapaQuery } from "./capa-graphql"; // written by capa-codegen --graphql
142
283
 
143
- const capa = await draftClient({
284
+ const capa = await draftClient<CapaQuery>({
144
285
  production,
145
286
  draft,
146
287
  isDraft: async () => (await draftMode()).isEnabled,
147
288
  });
148
289
  ```
149
290
 
291
+ `CapaQuery` types the GraphQL builder on the client it returns, as it does
292
+ for `createClient<CapaQuery>`; `getCapaClient<CapaQuery>` and
293
+ `getPublishedClient<CapaQuery>` take it the same way. Without it each helper
294
+ returns an untyped client. `getCapaClient` sends its GraphQL reads as it
295
+ sends its REST reads, which Next does not keep, unless a call gives `tags` or
296
+ `revalidate`; then it keeps them in Next's data cache as `graphql()` does
297
+ (see The typed builder).
298
+
299
+ ## Images
300
+
301
+ Capa serves every upload from its CDN at
302
+ `https://cdn.capacms.com/files/<key>`, and resizes it from the query string.
303
+ `@capacms/sdk/image` builds those URLs for any framework:
304
+
305
+ ```ts
306
+ import { imageUrl, srcSet, sizes } from "@capacms/sdk/image";
307
+
308
+ const hero = { id: "f1", url: "https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg", alt: "Terrace", type: "image", width: 2400, height: 1600 };
309
+
310
+ imageUrl(hero, { width: 1200, format: "webp" });
311
+ // https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?format=webp&width=1200
312
+
313
+ srcSet(hero, [640, 960, 1280, 1920], { format: "webp" });
314
+ // ...?format=webp&width=640 640w, ...?format=webp&width=960 960w, ...
315
+
316
+ sizes({ 768: "50vw", 1280: "33vw" });
317
+ // (min-width: 1280px) 33vw, (min-width: 768px) 50vw, 100vw
318
+ ```
319
+
320
+ `imageUrl(image, options)` and `srcSet(image, widths, options)` take a media
321
+ value as `/api/` returns it (`{ id, url, alt, type, width, height }`), the
322
+ legacy client's `CapaImage`, a CDN URL, or a file key such as
323
+ `sunns_1790971326210_d54fed020806.jpg`.
324
+
325
+ | Option | Values | Default, left out of the URL |
326
+ |---|---|---|
327
+ | `width`, `height` | CSS pixels, whole numbers | the image's own size |
328
+ | `fit` | `inside`, `cover` (crop), `contain` (pad), when both `width` and `height` are given | `inside` |
329
+ | `quality` | 1 to 100 | 80; 60 with `format: "avif"`. Kept in the URL with `avif` and `auto` |
330
+ | `dpr` | 1 to 3; the image is `width × dpr` pixels wide | 1 |
331
+ | `blur` | 1 to 256: a blurred placeholder that many pixels square | none |
332
+ | `format` | `webp`, `avif`, `jpeg`, `png`, `auto` | the image's own format |
333
+
334
+ What the helpers do for you:
335
+
336
+ - **Every URL is already in the order and spelling Capa's CDN serves.** Capa
337
+ answers any other spelling of the same query with a 301, which costs the
338
+ first view of each image a round trip. Defaults are left out, as the CDN
339
+ leaves them out.
340
+ - **Nothing is enlarged.** When the image's own `width` (and, for a box,
341
+ `height`) is known, a request for more pixels than it has is brought down
342
+ to its size, keeping the requested shape. A media value from `/api/` has
343
+ both. `srcSet` lists one candidate at the image's own width in place of the
344
+ wider ones.
345
+ - **`format=auto` is sent only when you pass it.** Note that the CDN
346
+ currently returns JPEG for `format=auto` whatever the browser accepts. Use
347
+ `format: "webp"` until that is fixed.
348
+ - **Anything that is not a Capa image comes back unchanged:** another host's
349
+ URL, a path on your own site, or a media value whose `type` is not
350
+ `image`. `isCapaImageUrl(src)` says which is which.
351
+ - **An older upload's `https://api.capacms.com/files/...` URL is built on
352
+ `cdn.capacms.com`.** It is the same file: the CDN fetches from that host,
353
+ which has no cache in front of it. On the CDN a resized copy is made once
354
+ and cached at the edge.
355
+ - **No image gives `undefined`.** `imageUrl` returns `undefined` for `null`,
356
+ or for a media value whose `url` is null or empty (the legacy API sends an
357
+ unset image as `{ url: "" }`), so for a media value its type is
358
+ `string | undefined`; for a string it is `string`. `srcSet` returns
359
+ `undefined` whenever it has nothing to resize. Either can go straight into
360
+ a `src` or `srcSet` prop.
361
+ - An option the CDN would refuse with a 400 (a width that is not a whole
362
+ number, `quality: 120`, more than 4096 pixels on an edge) throws a
363
+ `TypeError` naming the option.
364
+
365
+ For a crop at a fixed shape, `srcSet` takes `aspectRatio` (width over height)
366
+ in place of `height`:
367
+
368
+ ```ts
369
+ import { srcSet } from "@capacms/sdk/image";
370
+ import type { EntryMedia } from "@capacms/sdk/next";
371
+
372
+ declare const cover: EntryMedia | null;
373
+
374
+ const candidates = srcSet(cover, [640, 1280, 1920], { aspectRatio: 16 / 9, fit: "cover", format: "webp" });
375
+ ```
376
+
377
+ ### Focal points and crops
378
+
379
+ Where your project has focal points and crops, an editor can mark the spot
380
+ in an image that matters most, and the part of it to show, in the media
381
+ library. `/api/` then sends them on every image as `focalPoint` (`{ x, y }`)
382
+ and `crop` (`{ x, y, width, height }`), fractions of the image from 0 to 1,
383
+ or `null` where none is set.
384
+
385
+ Capa's CDN uses them for every crop to a shape, `fit: "cover"` with both a
386
+ `width` and a `height`: it cuts the crop first, then centres the shape on the
387
+ focal point as far as the crop allows. Every other request is unchanged.
388
+ `imageUrl` and `srcSet` name them in those URLs as `fp` and `rect`, so a
389
+ moved focal point gives a new URL rather than the old crop from a cache:
390
+
391
+ ```ts
392
+ import { imageUrl } from "@capacms/sdk/image";
393
+
394
+ const hero = { id: "f1", url: "https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg", alt: "Terrace", type: "image", width: 2400, height: 1600, focalPoint: { x: 0.25, y: 0.75 }, crop: null };
395
+
396
+ imageUrl(hero, { width: 400, height: 400, fit: "cover", format: "webp" });
397
+ // https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?fit=cover&format=webp&fp=0.25,0.75&height=400&width=400
398
+ ```
399
+
400
+ The `focalPoint` and `crop` options replace the media value's for one URL,
401
+ and a `crop` option applies to any resize. Both need focal points and crops
402
+ on for the project: elsewhere the CDN ignores `fp` and `rect`. An image
403
+ without them, a URL or a file key gets the same URL as before.
404
+
405
+ ### Placeholders
406
+
407
+ Where your project has image placeholders, `/api/` sends each image's
408
+ `blurDataURL` (a blurred copy 20 pixels on its long side, as a data URL),
409
+ `averageColor` and `dominantColor` (`#rrggbb`), `palette` (up to five
410
+ colours, largest first) and `blurhash`, each `null` where there is none.
411
+ `imagePlaceholder(image)` turns one into next/image's props, and
412
+ `placeholderColor(image)` gives a colour to paint the space with while the
413
+ image loads:
414
+
415
+ ```tsx
416
+ import Image from "next/image";
417
+ import { imagePlaceholder, placeholderColor } from "@capacms/sdk/image";
418
+ import type { EntryMedia } from "@capacms/sdk/next";
419
+
420
+ export function Card({ image }: { image: EntryMedia }) {
421
+ if (!image.url) return null;
422
+ return (
423
+ <div style={{ backgroundColor: placeholderColor(image) }}>
424
+ <Image src={image.url} alt={image.alt ?? ""} width={image.width ?? 1200} height={image.height ?? 800} {...imagePlaceholder(image)} />
425
+ </div>
426
+ );
427
+ }
428
+ ```
429
+
430
+ `imagePlaceholder` gives `{ placeholder: "blur", blurDataURL }` when the
431
+ image has one and `{ placeholder: "empty" }` otherwise, so it can always be
432
+ spread. The placeholders, `focalPoint` and `crop` are optional properties of
433
+ `EntryMedia`, there only for a project that has them. The GraphQL `Media`
434
+ type has them only there too, so select them only there; codegen writes them
435
+ into your types when it does.
436
+
437
+ ### Plain HTML
438
+
439
+ Build the attributes wherever the page is rendered, a server template or a
440
+ build script:
441
+
442
+ ```ts
443
+ import { imageUrl, srcSet, sizes } from "@capacms/sdk/image";
444
+ import type { EntryMedia } from "@capacms/sdk/next";
445
+
446
+ const attr = (value: unknown) => String(value ?? "").replace(/&/g, "&amp;").replace(/"/g, "&quot;");
447
+
448
+ function picture(image: EntryMedia): string {
449
+ return `<img
450
+ src="${attr(imageUrl(image, { width: 1280, format: "webp" }))}"
451
+ srcset="${attr(srcSet(image, [480, 800, 1280, 1920], { format: "webp" }))}"
452
+ sizes="${sizes({ 1024: "50vw" })}"
453
+ width="${attr(image.width)}" height="${attr(image.height)}"
454
+ alt="${attr(image.alt)}" loading="lazy">`;
455
+ }
456
+ ```
457
+
458
+ In the browser the result is an ordinary responsive image:
459
+
460
+ ```html
461
+ <img
462
+ src="https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?format=webp&width=1280"
463
+ srcset="https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?format=webp&width=480 480w, https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?format=webp&width=800 800w, https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?format=webp&width=1280 1280w, https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?format=webp&width=1920 1920w"
464
+ sizes="(min-width: 1024px) 50vw, 100vw"
465
+ width="2400" height="1600" alt="Terrace" loading="lazy">
466
+ ```
467
+
468
+ `@capacms/sdk/image` is an ES module for bundlers and CommonJS for
469
+ `require`, and carries no other part of the SDK, so it adds little to a
470
+ browser bundle.
471
+
472
+ ### React
473
+
474
+ ```tsx
475
+ import { imageUrl, srcSet, sizes } from "@capacms/sdk/image";
476
+ import type { EntryMedia } from "@capacms/sdk/next";
477
+
478
+ export function Hero({ image }: { image: EntryMedia | null }) {
479
+ if (!image?.url) return null;
480
+ return (
481
+ <img
482
+ src={imageUrl(image, { width: 1280, format: "webp" })}
483
+ srcSet={srcSet(image, [640, 960, 1280, 1920], { format: "webp" })}
484
+ sizes={sizes({ 1024: "50vw" })}
485
+ width={image.width ?? undefined}
486
+ height={image.height ?? undefined}
487
+ alt={image.alt ?? ""}
488
+ />
489
+ );
490
+ }
491
+ ```
492
+
493
+ A blurred placeholder is one more URL: `imageUrl(image, { blur: 20, format: "webp" })`
494
+ is a few hundred bytes to show while the full image loads.
495
+
496
+ ### Next.js: let Capa resize for next/image
497
+
498
+ `next/image` sends every image through Next's optimizer unless a loader says
499
+ otherwise, and on Vercel that optimizer is billed by use. A custom loader hands the
500
+ resizing to Capa's CDN instead. Add a loader file:
501
+
502
+ ```ts
503
+ // capa-image-loader.ts (or .js)
504
+ "use client";
505
+ import { createCapaImageLoader } from "@capacms/sdk/nextjs/image-loader";
506
+
507
+ export default createCapaImageLoader({ format: "webp" });
508
+ ```
509
+
510
+ and name it in `next.config`:
511
+
512
+ ```js
513
+ // next.config.mjs
514
+ export default {
515
+ images: {
516
+ loader: "custom",
517
+ loaderFile: "./capa-image-loader.ts",
518
+ },
519
+ };
520
+ ```
521
+
522
+ Then use `<Image>` as usual, with the media value's `url`. Mark any other
523
+ image `unoptimized`, since the loader leaves it as it is and Next warns in
524
+ development that the loader ignores its width:
525
+
526
+ ```tsx
527
+ import Image from "next/image";
528
+ import { isCapaImageUrl } from "@capacms/sdk/image";
529
+ import type { EntryMedia } from "@capacms/sdk/next";
530
+
531
+ export function Cover({ image }: { image: EntryMedia }) {
532
+ const src = image.url ?? "/placeholder.jpg";
533
+ return <Image src={src} unoptimized={!isCapaImageUrl(src)} alt={image.alt ?? ""} width={image.width ?? 1200} height={image.height ?? 800} sizes="(min-width: 1024px) 50vw, 100vw" />;
534
+ }
535
+ ```
536
+
537
+ Next lists a URL per width it wants, and the loader turns each into a Capa
538
+ URL in canonical order: `?format=webp&width=640`, `?format=webp&width=750`,
539
+ and so on. An `<Image>`'s `quality` prop becomes `quality`; without one,
540
+ Capa's default of 80 applies. `createCapaImageLoader` takes `format` and a
541
+ default `quality`; `capaImageLoader`, the default export of
542
+ `@capacms/sdk/nextjs/image-loader`, sets neither, so each image keeps its own
543
+ format. Both are also exported from `@capacms/sdk/nextjs` for server code.
544
+
545
+ A `src` that `imageUrl` built with `fp` and `rect` keeps them through the
546
+ loader, so its crop to a shape still centres on the focal point.
547
+
548
+ The loader resizes only a full Capa URL, on `cdn.capacms.com` or
549
+ `api.capacms.com` (built on the CDN host, as above). Any other `src` goes
550
+ back unchanged: a file in `public/`, another host, or a bare name such as
551
+ `logo.png`, which is your site's file and not a Capa key.
552
+
553
+ The loader never throws, because a throw fails the render of the whole page.
554
+ A `src` or prop the CDN would refuse, such as a src carrying `dpr=2` at a
555
+ width of 3840 (past the 4096-pixel edge) or `quality={0}`, gets the `src`
556
+ back unchanged. A width past 4096 pixels asks for 4096. The loader only sees
557
+ the `src` string, so it cannot know the image's own width: keep
558
+ `deviceSizes` to the widths your layout uses.
559
+
560
+ The loader file needs its own entry, `@capacms/sdk/nextjs/image-loader`,
561
+ because Next runs the loader in the browser on every page with an image, and
562
+ that entry holds the image rules and nothing else.
563
+
564
+ ## GraphQL
565
+
566
+ `/api/graphql` reads the same content as `/api/entries`, with the same key,
567
+ version, limits and error codes. The schema is built for your key: it has
568
+ exactly the models the key can read. The API reference is at
569
+ https://docs.capacms.com/api/graphql.
570
+
571
+ ### In a Next.js server component
572
+
573
+ ```tsx
574
+ // app/blog/page.tsx
575
+ import { draftMode, headers } from "next/headers";
576
+ import { capaAttrs } from "@capacms/sdk/next";
577
+ import { graphql, tagsFor } from "@capacms/sdk/nextjs";
578
+ import { BlogIndexModels } from "./capa-graphql"; // written by capa-codegen --graphql
579
+
580
+ const BLOG_INDEX = `#graphql
581
+ query BlogIndex($first: Int) {
582
+ articles(first: $first, sort: [publishedAt_DESC]) {
583
+ nodes { id model title author { name } }
584
+ }
585
+ }
586
+ `;
587
+
588
+ export default async function Blog() {
589
+ const { data } = await graphql(BLOG_INDEX, { first: 5 }, {
590
+ draftMode,
591
+ headers,
592
+ tags: tagsFor({ namespace: BlogIndexModels }), // articles, and authors for author { name }
593
+ revalidate: 60,
594
+ });
595
+ return (
596
+ <ul>
597
+ {data?.articles?.nodes.map((a) => <li key={a.id} {...capaAttrs(a, "title")}>{a.title}</li>)}
598
+ </ul>
599
+ );
600
+ }
601
+ ```
602
+
603
+ `data` and the variables are typed from the document itself, with no cast,
604
+ once `capa-codegen --graphql` has read it (see Typed documents). Until then
605
+ the call does not compile, and the error says to run it, so a document edited
606
+ since the last run is never silently untyped.
607
+
608
+ Given `tags` or `revalidate`, `graphql()` keeps a published read in Next's
609
+ data cache, through Next's own `unstable_cache`, under the tags you give.
610
+ Given neither, it keeps nothing: the read is sent as a REST read is, and the
611
+ page shows a publish on its next render. `BlogIndexModels` lists the models
612
+ the query reads, which codegen writes beside its types: `articles`, and
613
+ `authors` for `author { name }`. It changes when the query does, so a model
614
+ the query starts reading is never left out. `tagsFor({ namespace })` makes
615
+ one tag per model (`capa:model:articles`), and `capa:media`. The webhook
616
+ route above calls `revalidateFromWebhook`, which revalidates a model's tag
617
+ whenever an entry of the model is published, unpublished or deleted, so the
618
+ page shows the change on the next request. Editing a file in the media
619
+ library, its alt text say, changes no entry, so it revalidates `capa:media`
620
+ instead, and every read tagged by its models shows the new text. How long a
621
+ read is kept:
622
+
623
+ - With neither `tags` nor `revalidate`, not at all: every render reads the
624
+ API, as `entries.list` does, so a site with no webhook route still shows a
625
+ publish on the next request.
626
+ - With `tags` and no `revalidate`, until one of its tags is revalidated.
627
+ With the webhook route, that is until the next publish of a model it reads.
628
+ - With `revalidate: 60`, also at most 60 seconds, so a missed webhook costs
629
+ a minute of stale content at most.
630
+ - With `revalidate: 0`, not at all.
631
+
632
+ A read with a `revalidate` and no `tags` is tagged `capa:graphql`
633
+ (`GRAPHQL_TAG`), which `revalidateFromWebhook` revalidates on every content
634
+ change, so it is never stale after a publish; tag it with its models to
635
+ refresh the page only when one of them changes.
636
+
637
+ A read that answered with `errors` is never kept: a root field that timed
638
+ out is shown once and read again on the next request. Next's fetch cache is
639
+ not used for a GraphQL read, since it keeps every 200 and a GraphQL error is
640
+ a 200, and in Next 15 it keeps nothing without a `revalidate`. A draft and an
641
+ edit-mode page are read uncached. Outside a Next request, in a script or a
642
+ test, the read is simply sent. `unstable_cache` is an option only to supply
643
+ another implementation.
644
+
645
+ `draftMode` and `headers` work out draft and edit mode as `getCapaClient`
646
+ does. Under draft mode the read uses `CAPA_DRAFT_KEY`, a `cap_` key, and
647
+ bypasses the cache.
648
+ In edit mode (draft mode, or the editor's Published view) each entry that
649
+ selected `id` and `model` is marked, so `capaAttrs(node, field)` makes it
650
+ clickable in the Capa editor (see Live preview); a visitor's page carries no
651
+ tags. Leave both out for a page with no preview.
652
+
653
+ `graphql()` reads `CAPA_API_URL`, `CAPA_KEY` and `CAPA_API_VERSION` like the
654
+ other helpers, and a setting you pass in `config` (`baseUrl`, `apiKey`,
655
+ `version`, `fetch`) is used instead of its variable, so a full `config`
656
+ needs no env at all. A published read is a GET, which the CDN and the API
657
+ also cache for the published key; a document too long for a URL goes as a
658
+ POST, which only Next's data cache keeps (see How reads are sent and cached).
659
+ The result's `cacheTags`
660
+ holds the API's `Surrogate-Key` for a GET (`m:<modelId>`, `e:<entryId>`), for
661
+ purging a CDN of your own. `draft: true` or `false` decides draft mode
662
+ yourself. Pass `persisted: true` once your documents are stored with
663
+ `capa persist` (see Persisted queries).
664
+
665
+ ### In a Node script
666
+
667
+ ```ts
668
+ import { createClient, isCapaError } from "@capacms/sdk/next";
669
+
670
+ const capa = createClient({
671
+ baseUrl: process.env.CAPA_API_URL!,
672
+ apiKey: process.env.CAPA_KEY!,
673
+ version: "2026-10-01",
674
+ });
675
+
676
+ const POPULAR = `#graphql
677
+ query Popular { articles(first: 5, filter: { views: { gte: 10 } }) { nodes { id title } } }
678
+ `;
679
+
680
+ const { data, errors, extensions } = await capa.graphql(POPULAR);
681
+
682
+ for (const error of errors) console.warn(error.code, error.message, error.hint, error.path);
683
+ console.log(data?.articles?.nodes, extensions.cost?.actualQueryCost);
684
+ ```
685
+
686
+ For a string codegen has not read, such as one built at run time, pass the
687
+ data type yourself: `capa.graphql<{ version: string }>("{ version }")`.
688
+
689
+ `capa.graphql(document, variables?, options?)` resolves once the API has run
690
+ the document, even when `errors` is not empty: the root fields that worked
691
+ still carry data, a root field that failed is `null` (which is why every list
692
+ root is nullable in the schema and in generated types), and each error is a
693
+ `CapaGraphQLError`.
694
+
695
+ A `CapaGraphQLError` is a plain object: the spec's `message`, `locations`,
696
+ `path` and `extensions`, with `code`, `hint`, `docs`, `param` and `type`
697
+ lifted out of `extensions`. So `Response.json(result)` in a route handler, and
698
+ a server component passing `errors` to a client component, keep every field.
699
+ `isCapaGraphQLError(value)` checks one by its shape, so it holds after JSON.
700
+
701
+ A request the API refuses as a whole throws `CapaError`, whose
702
+ `graphqlErrors` holds every error the API sent: a document that does not
703
+ parse or validate, a variable of the wrong type, a query over a budget, a
704
+ filter the planner refuses. Its body has `errors` and no `data`. GraphQL over
705
+ HTTP sends that refusal as a 200 on `application/json`, which this client
706
+ asks for, and as a 4xx on `application/graphql-response+json`; either way the
707
+ `CapaError` is the same, with `status` 400. Other refusals keep their own
708
+ status: the key (401), the plan (402), the origin (403), the contract (404),
709
+ a mutation (405) and the rate (429).
710
+
711
+ The API runs 4 reads at once per project, GraphQL documents and
712
+ `/api/entries` reads counted together, and at most 3 of them for one client
713
+ of a key, so one busy visitor never holds every slot. Up to 64 more per
714
+ client and 256 per key wait for a slot. Past that it answers 429 with
715
+ `Retry-After`. The client waits that long, plus up to 250 ms, and sends the
716
+ request again, up to 3 times, so a page that reads many things at once from
717
+ one key slows down instead of failing. `retries: 0` throws the first 429
718
+ instead, and `retries: n` allows n repeats. A 429 that is thrown carries
719
+ `retryAfter`, in seconds. A `Retry-After` over 30 seconds is thrown at once
720
+ rather than waited out, and `signal` ends a wait early. `entries.list` and
721
+ `entries.get` share these limits and throw their 429 with `retryAfter`
722
+ rather than repeat it. When an API machine is full of other projects' reads,
723
+ it answers 503 `service_unavailable` with `Retry-After`, which is thrown.
724
+
725
+ Where GraphQL is switched off (`CAPA_API_GRAPHQL=off`), the `CapaError`
726
+ says "This Capa deployment does not serve GraphQL." and its `hint` says to
727
+ read with `entries.list` or `entries.get` meanwhile. Options:
728
+ `operationName`, `method`, `persisted: true`, `retries`, and `signal`.
729
+
730
+ `extensions.cost` is the query's cost as Shopify's APIs report it, in
731
+ entries. `requestedQueryCost` is the most the document can read: every list at
732
+ its full `first` (25 at a root and 100 nested when you give none), capped at
733
+ 5,000, plus 500 for each scan. `actualQueryCost` is what it did read, plus 500
734
+ for each scan that ran. The 5,000 limit is checked before the document runs,
735
+ on a tighter figure: a nested list with no `first` counts 10 for each entry
736
+ above it, not 100, so `{ articles(first: 1) { nodes { coauthors { nodes { name } } } } }`
737
+ passes as 11 entries and requests 101. That figure is `budget.counted`, and
738
+ the limit is `budget.limit`, on every response: it is the number to watch,
739
+ since a document is refused exactly when `counted` passes `limit`, and a
740
+ refusal states it. There is no per-key budget, so there is no
741
+ `throttleStatus`.
742
+
743
+ A document that uses a deprecated field, argument or enum value gets one
744
+ `{ coordinate, reason }` for each in `extensions.deprecations`, such as
745
+ `{ "coordinate": "Articles._folder", "reason": "Read folder instead." }`.
746
+ `capa-codegen --graphql` warns about the same uses before you ship.
747
+
748
+ A scan reads entries the answer does not hold. Each of these is one:
749
+
750
+ - a `totalCount`;
751
+ - a filter or sort through a relation;
752
+ - a root field that filters or sorts by its model's own fields, once however
753
+ many such conditions it has, so
754
+ `articles(first: 10, filter: { featured: { eq: true } })` requests 510;
755
+ - each `contains`, `startsWith`, `endsWith` or `ne` condition past the first;
756
+ - a relation list sorted with `sort`.
757
+
758
+ Filters on `id`, `createdAt`, `updatedAt`, `publishedAt` and `_tags`, and a
759
+ relation's `eq`, are served by an index and cost nothing. The API reference
760
+ has every rule: https://docs.capacms.com/api/graphql#cost.
761
+
762
+ A development key's reads, such as the draft client's, also carry
763
+ `extensions.capa`. Its `cost` breaks the cost down against every limit
764
+ (depth, root fields, connections, nodes, fields) and counts the `scans`. Its
765
+ `rest` names the REST request each root field was answered with. A production
766
+ key's reads leave `extensions.capa` out, which keeps a cached page's answer
767
+ small.
768
+
769
+ #### How reads are sent and cached
770
+
771
+ A read is a GET whenever its URL fits the API's limit of 8,192 bytes (path
772
+ and query string), and a POST when it does not; a long document is never
773
+ refused for its length. `method: "POST"` always sends a POST, and
774
+ `method: "GET"` sends a GET that fits and a POST that does not.
775
+
776
+ | Request | Cached by the API and the CDN |
777
+ |---|---|
778
+ | GET with a production key, no errors | yes: `public, max-age=60`, purged by the entries it read (`cacheTags`) |
779
+ | GET with a development key | no (`no-store`): drafts move |
780
+ | any response with `errors` | no (`no-store`) |
781
+ | GET selecting `me`, `__schema` or `__type` | no (`no-store`) |
782
+ | POST | never |
783
+
784
+ So a document too long for a GET is not cached. Keep it cacheable with
785
+ persisted queries: `persisted: true` sends only the hash by GET (see
786
+ Persisted queries). `graphqlSchema()` reads the introspection by POST, since
787
+ it is never cached. The admin host serves GraphQL by POST only and answers a
788
+ GET as a path it does not serve; a read that did not ask for GET is then
789
+ repeated as a POST, and that host is read by POST for five minutes. A
790
+ `method: "GET"` read there throws "This Capa host does not serve GraphQL by
791
+ GET." In Next.js, `graphql()` from `/nextjs` adds Next's data cache on top
792
+ when a read gives `tags` or `revalidate`, for a published read with no
793
+ errors, a POST included: kept under its `tags` until one is revalidated, or
794
+ for `revalidate` seconds when you give it, and never for a draft.
795
+
796
+ ### The typed builder
797
+
798
+ Write the query as an object and get the result typed from exactly what you
799
+ selected, without writing GraphQL text:
800
+
801
+ ```ts
802
+ import { createClient } from "@capacms/sdk/next";
803
+ import type { CapaQuery } from "./capa-graphql"; // written by capa-codegen --graphql
804
+
805
+ const capa = createClient<CapaQuery>({ baseUrl, apiKey, version: "2026-10-01" });
806
+
807
+ const { data } = await capa.graphql.query({
808
+ articles: {
809
+ args: { first: 5, sort: ["publishedAt_DESC"], filter: { featured: { eq: true } } },
810
+ nodes: { title: true, author: { name: true } },
811
+ },
812
+ });
813
+
814
+ data?.articles?.nodes[0].author?.name; // string | null
815
+ data?.articles?.nodes[0].body; // compile error: not selected
816
+ ```
817
+
818
+ `true` selects a scalar, an object selects fields of a relation or a
819
+ connection, and `args` sits beside the fields of anything that takes
820
+ arguments. A misspelled field, argument, filter field or operator fails to
821
+ compile, even beside a correct one, and so does an argument of the wrong type,
822
+ a sort value that is not in the enum, or a required argument left out
823
+ (`article` without `args: { id }`). The compiler's error names the key and
824
+ where it was written: `titel: true` under `articles.nodes` fails with
825
+ `Type 'true' is not assignable to type 'true & SelectionError<"titel is not a
826
+ field of articles.nodes">'`. A `Date` in `args` is sent as its ISO text.
827
+ Without `CapaQuery` the builder still runs, untyped.
828
+ `selectionToDocument(selection)` returns the text it sends.
829
+
830
+ `query()` takes the options `capa.graphql` takes, except `persisted`. Its
831
+ document is printed when it runs, so `capa persist` never stored it, and it
832
+ is already a GET that the API and the CDN cache. To persist a read, write it
833
+ as a `#graphql` literal (see Persisted queries).
834
+
835
+ In a Next.js server component, read through `getCapaClient`. A read that
836
+ names tags is kept in Next's data cache under them:
837
+
838
+ ```tsx
839
+ // app/blog/page.tsx
840
+ import { draftMode, headers } from "next/headers";
841
+ import { getCapaClient, tagsFor } from "@capacms/sdk/nextjs";
842
+ import type { CapaQuery } from "./capa-graphql";
843
+
844
+ export default async function Blog() {
845
+ const capa = await getCapaClient<CapaQuery>({ draftMode, headers });
846
+ const { data } = await capa.graphql.query(
847
+ { articles: { args: { first: 5, sort: ["publishedAt_DESC"] }, nodes: { id: true, title: true } } },
848
+ { tags: tagsFor({ namespace: "articles" }), revalidate: 60 },
849
+ );
850
+ return <ul>{data?.articles?.nodes.map((a) => <li key={a.id}>{a.title}</li>)}</ul>;
851
+ }
852
+ ```
853
+
854
+ `tags` and `revalidate` work as they do for `graphql()` (see In a Next.js
855
+ server component). A read is kept until a publish of a model its tags name,
856
+ a read with errors is never kept, and a draft or an edit-mode page is read
857
+ uncached. A read with neither is not kept, as the client's REST reads are
858
+ not. `capa.graphql(document)` on the same client takes them too.
859
+
860
+ Read one field twice in one request with an alias: any other key, with
861
+ `__aliasFor` naming the field it reads. A home page's featured and latest
862
+ articles are one request:
863
+
864
+ ```ts
865
+ const { data: home } = await capa.graphql.query({
866
+ articles: { args: { first: 3, filter: { featured: { eq: true } } }, nodes: { id: true, title: true } },
867
+ latest: { __aliasFor: "articles", args: { first: 5, sort: ["publishedAt_DESC"] }, nodes: { id: true, title: true } },
868
+ });
869
+
870
+ home?.latest?.nodes[0].title; // string | null, typed as articles is
871
+ ```
872
+
873
+ The alias is checked as the field it names, arguments and fields included,
874
+ and sent as `latest: articles(...)`. A scalar is aliased with `__aliasFor`
875
+ alone: `{ headline: { __aliasFor: "title" } }`.
876
+
877
+ #### Typing a component's props
878
+
879
+ `NodeOf` names one entry of a builder read, so a component that renders it
880
+ takes exactly what the selection reads, and the two cannot drift:
881
+
882
+ ```tsx
883
+ import type { NodeOf } from "@capacms/sdk/next";
884
+ import type { CapaQuery } from "./capa-graphql";
885
+
886
+ const teasers = {
887
+ articles: { args: { first: 5 }, nodes: { id: true, title: true, author: { name: true } } },
888
+ } as const;
889
+
890
+ // { id: string; title: string | null; author: { name: string | null } | null }
891
+ type Teaser = NodeOf<CapaQuery, typeof teasers, "articles">;
892
+
893
+ function Card({ article }: { article: Teaser }) {
894
+ return <li>{article.title} by {article.author?.name}</li>;
895
+ }
896
+
897
+ const { data } = await capa.graphql.query(teasers);
898
+ const cards = data?.articles?.nodes.map((article) => <Card key={article.id} article={article} />);
899
+ ```
900
+
901
+ It is a node of a list root, the entry of a single root (`article`), or the
902
+ node of an alias (`NodeOf<CapaQuery, typeof home, "latest">`).
903
+ `QueryResult<CapaQuery, typeof teasers>` is the type of `data` as a whole.
904
+
905
+ #### The same data in REST's shape
906
+
907
+ The builder returns GraphQL's shape, because that is what its types describe:
908
+ `articles.nodes[0].author.name`. Code written against `/api/entries` reads
909
+ entries instead: `data[0].fields.author.fields.name`. `toTree` converts one to
910
+ the other:
911
+
912
+ ```ts
913
+ import { toTree } from "@capacms/sdk/next";
914
+ import { capaTreeLayout } from "./capa-graphql"; // written by capa-codegen --graphql
915
+
916
+ const selection = {
917
+ articles: {
918
+ args: { first: 5, sort: ["publishedAt_DESC"] },
919
+ nodes: { id: true, status: true, title: true, author: { id: true, status: true, name: true } },
920
+ },
921
+ } as const;
922
+ const { data } = await capa.graphql.query(selection);
923
+ const { articles } = toTree(data, selection, capaTreeLayout);
924
+ articles?.map((entry) => entry.fields.title); // each a string | null, as entries.list types it
925
+ // deep-equal to (await capa.entries.list("articles", { select: "title,author(name)", sort: ["-publishedAt"], limit: 5 })).data
926
+ ```
927
+
928
+ `capaTreeLayout` is what `toTree` reads of your schema (each model's root
929
+ fields, and which fields are renamed, relations, ids or media), written by
930
+ codegen beside the types, so the conversion reads nothing from the API.
931
+ Without codegen, pass the key's schema instead. That is one introspection
932
+ request, so read it once and reuse it:
933
+
934
+ ```ts
935
+ import { toTree } from "@capacms/sdk/next";
936
+
937
+ const schema = await capa.graphqlSchema(); // one request: read it once, reuse it
938
+ const selection = { articles: { args: { first: 5 }, nodes: { id: true, status: true, title: true } } } as const;
939
+ const { data } = await capa.graphql.query(selection);
940
+ const { articles } = toTree(data, selection, schema); // the same tree as with capaTreeLayout
941
+ ```
942
+
943
+ A selection kept in a variable is declared `as const`, so each `true` and
944
+ each `sort` value keeps its exact type and the result is typed exactly.
945
+
946
+ Each model root field becomes its REST `data`, typed from the selection: a
947
+ list root as an array of entries, a single root as one entry or `null`, and
948
+ `null` for a root that failed (its error is in `errors`). System fields sit beside `fields`
949
+ (`_version` as `version`), every other field sits under `fields` by its
950
+ namespace (`hero_image` as `hero-image`), every entry carries its `model`
951
+ from the schema, whether you selected it or not, a relation list becomes
952
+ `{ items, pageInfo }` (`{ items }` when you did not select its `pageInfo`), a
953
+ relation into a model the key cannot read is
954
+ `{ id, model }` as REST writes it unexpanded (a list of them is
955
+ `{ items, pageInfo }`), and a media value keeps REST's public shape and key
956
+ order, `{ id, url, alt, type, width, height }`, as far as you selected it (a
957
+ list of media is an array of those).
958
+
959
+ The result is deep-equal to the REST response for the same read when the
960
+ selection names the rest of what REST always returns: `id` and `status` on
961
+ every entry, `pageInfo { hasNextPage endCursor }` on each relation list, and
962
+ all six media fields. Its type is then assignable to the entry
963
+ `entries.list<Articles, typeof select>` returns for the same read, so a
964
+ function written for the REST read takes it unchanged. With a typed client,
965
+ a selection without `id` and `status` does not compile. Three things differ by design, because GraphQL
966
+ does not carry what REST says there:
967
+
968
+ - A missing single relation (deleted, or a draft the key cannot see) is `null`
969
+ in GraphQL and `{ id, model, missing: true }` in REST.
970
+ - A missing item of a relation list is left out in GraphQL, so `items` is
971
+ shorter. REST keeps its slot as `{ id, model, missing: true }`.
972
+ - A value that does not fit its field's type is `null` in GraphQL and the raw
973
+ value in REST.
974
+
975
+ Page a list with the GraphQL result's own `pageInfo`; `version`, `me`
976
+ and `entry` are not model roots, and `toTree` refuses them. A root alias
977
+ (`latest: { __aliasFor: "articles", ... }`) becomes the REST data of the field
978
+ it names, under its own key. An alias below a root has no REST equivalent,
979
+ since REST reads each field once, so `toTree` refuses it too.
980
+
981
+ ### Typed documents
982
+
983
+ ```json
984
+ {
985
+ "scripts": {
986
+ "dev": "capa-codegen --graphql --watch --out src/capa-graphql.ts & next dev",
987
+ "prebuild": "capa-codegen --graphql --out src/capa-graphql.ts"
988
+ }
989
+ }
990
+ ```
991
+
992
+ `capa-codegen` reads `CAPA_API_URL` and `CAPA_KEY` from your shell, else from
993
+ `.env.local` and `.env` as `next dev` reads them, so a Next.js site needs no
994
+ extra setup. `--watch` keeps running and writes the module again whenever a
995
+ document changes, and when the key's schema does (it reads the schema again
996
+ every minute). A document with a problem is printed with its file and line,
997
+ and the last good module stays in place.
998
+
999
+ Write a document where you use it, marked in one of three ways, and codegen
1000
+ types it by its text:
1001
+
1002
+ ```ts
1003
+ import { createClient, gql } from "@capacms/sdk/next";
1004
+
1005
+ const LATEST = `#graphql
1006
+ query Latest($first: Int) { articles(first: $first) { nodes { id title } } }
1007
+ `;
1008
+ const ONE = /* capa */ `query One($id: ID!) { article(id: $id) { title views } }`;
1009
+ const VERSION = gql(`query Version { version }`);
1010
+
1011
+ const { data } = await capa.graphql(LATEST, { first: 10 });
1012
+ data?.articles?.nodes[0].title; // string | null
1013
+ await capa.graphql(LATEST, { first: "10" }); // compile error
1014
+ await capa.graphql(ONE); // compile error: id is required
1015
+ ```
1016
+
1017
+ The generated file adds each literal's text to `CapaDocuments` with
1018
+ `declare module "@capacms/sdk/next"`, and `client.graphql` and `graphql()`
1019
+ from `/nextjs` look the text up, so nothing is imported from it. Keep the
1020
+ generated file inside your tsconfig's `include`. A literal is sent exactly as
1021
+ written, so it holds one operation and every fragment it spreads, written
1022
+ inside it or spread in with `${}` (see Fragments); codegen says so, with the
1023
+ file and line, when it does not. A literal of fragments only is a fragment
1024
+ source for others.
1025
+
1026
+ Codegen also reads every `.graphql` file and every gql`...` tagged template
1027
+ under `src` (or `--documents dir1,dir2`). A tagged template is a plain string
1028
+ to TypeScript, so for those, and for `.graphql` files, import the
1029
+ `<Name>Document` codegen writes for every named operation:
1030
+
1031
+ ```ts
1032
+ // src/queries/articles.graphql
1033
+ // query ArticlesPage($first: Int) { articles(first: $first) { nodes { id title } } }
1034
+
1035
+ import { ArticlesPageDocument } from "./capa-graphql";
1036
+
1037
+ const { data } = await capa.graphql(ArticlesPageDocument, { first: 10 });
1038
+ data?.articles?.nodes[0].title; // string | null
1039
+ await capa.graphql(ArticlesPageDocument, { first: "10" }); // compile error
1040
+ ```
1041
+
1042
+ #### Fragments
1043
+
1044
+ ```ts
1045
+ import type { ArticleTeaserFragment } from "./capa-graphql";
1046
+
1047
+ const ARTICLE_TEASER = `#graphql
1048
+ fragment ArticleTeaser on Articles { id title }
1049
+ `;
1050
+
1051
+ const TEASERS = `#graphql
1052
+ query Teasers($first: Int) { articles(first: $first) { nodes { ...ArticleTeaser } } }
1053
+ ${ARTICLE_TEASER}
1054
+ ` as const;
1055
+
1056
+ function teaser(props: ArticleTeaserFragment) {
1057
+ return props.title;
1058
+ }
1059
+
1060
+ const { data } = await capa.graphql(TEASERS, { first: 3 });
1061
+ data?.articles?.nodes.map(teaser);
1062
+ ```
1063
+
1064
+ Write a fragment in a `#graphql` literal of its own and spread it into a
1065
+ query with `${NAME}`, as Hydrogen does. Codegen reads the query with the
1066
+ fragment's text in place, which is exactly the text the program sends, so the
1067
+ query is typed and persisted like any other literal. End the query's template
1068
+ with `as const`: TypeScript keeps the text of a template with `${}` only
1069
+ then, and codegen says so when it is missing. A `${}` that names anything
1070
+ else is text only known at run time, which codegen skips and names.
1071
+
1072
+ Codegen writes a `<Name>Fragment` type for every fragment, from a literal or
1073
+ a `.graphql` file, for a component that takes the fragment's data as props:
1074
+ the nodes of any query that spreads the fragment fit it.
1075
+
1076
+ The generated file also holds the schema's types, `CapaQuery` for the typed
1077
+ builder, `capaTreeLayout` for `toTree`, and `<Name>Models` beside each
1078
+ operation: the models it reads, for its cache tags (see In a Next.js server
1079
+ component). That is each model whose entries it selects, and each model a
1080
+ filter or sort reaches through a relation. A filter or sort passed as a
1081
+ variable counts every model its type can reach, and `entry(id:)` counts every
1082
+ model, since either can read any of them.
1083
+
1084
+ Codegen names, with its file and line, every template it does not read that
1085
+ looks like a query, and says what to change: one left unmarked, graphql`...`
1086
+ (from `/nextjs` that is a request, not a tag), and one with a `${}` that names
1087
+ no literal of the project, whose text is only known at run time.
1088
+
1089
+ A field the key cannot read is a codegen error with its file and line, so a
1090
+ model change fails CI instead of production. A field, argument, filter
1091
+ operator or sort value a later `Capa-Version` phases out is `@deprecated` in
1092
+ the generated types, so your editor strikes it through, and codegen prints
1093
+ each use with its file, line and the reason, while still writing the module.
1094
+ `--check` exits 2 when the committed file is stale. `--save-schema
1095
+ capa-schema.json` writes the schema it read, and `--schema capa-schema.json`
1096
+ reads it back instead of calling the API, for CI without a key. Codegen needs
1097
+ `graphql` installed in your project (`pnpm add -D graphql`); nothing else in
1098
+ the SDK does.
1099
+
1100
+ A literal codegen has not read yet, new or edited since the last run, does
1101
+ not compile: the error says `run capa-codegen --graphql`. Text built at run
1102
+ time is a plain `string` and stays untyped, and so does a call that names its
1103
+ data type, `capa.graphql<{ version: string }>(text)`.
1104
+
1105
+ ### Persisted queries
1106
+
1107
+ Register your documents at build time, with a development key:
1108
+
1109
+ ```sh
1110
+ CAPA_API_URL=https://api.capacms.com CAPA_DRAFT_KEY=cap_test_... capa persist --manifest persisted.json
1111
+ ```
1112
+
1113
+ Then send only their hash, with any key, including the production key your
1114
+ site ships:
1115
+
1116
+ ```ts
1117
+ import { ArticlesPageDocument } from "./capa-graphql";
1118
+
1119
+ const { data } = await capa.graphql(ArticlesPageDocument, { first: 10 }, { persisted: true });
1120
+ ```
1121
+
1122
+ With `persisted: true` the client sends the document's sha256 as one small
1123
+ GET, which the CDN and the API cache for a production key, and the document
1124
+ never travels. Variables too long for a GET URL (8,192 bytes) go with the hash
1125
+ in a POST instead, which works the same way but is not cached. `capa persist` prints `<sha256> <operation> stored, pinned` per
1126
+ operation, hashing the same text `capa-codegen --graphql` exports, so run
1127
+ both from the same documents. A document written as a literal is stored
1128
+ twice, as its `<Name>Document` text and as written (`<Name> (literal)`),
1129
+ since a call with the literal sends that text.
1130
+
1131
+ `capa persist` registers every document with `Capa-Persist: pin`. The API
1132
+ drops unpinned documents first when a project's store is full, so the
1133
+ documents developers register while trying queries in the Explorer or a
1134
+ draft preview never push your site's documents out. A document the API
1135
+ stores without its pin is reported as `stored, not pinned` and the command
1136
+ exits 3, since it is exposed to exactly that. `--manifest` writes each
1137
+ operation's `sha256`, `stored` and `pinned`.
1138
+
1139
+ Name the build too, so a run of preview deploys never pushes production's
1140
+ documents out:
1141
+
1142
+ ```sh
1143
+ capa persist --release "$GIT_COMMIT" --env production
1144
+ ```
1145
+
1146
+ That sends `Capa-Persist: pin; release=<commit>; env=production`. A project
1147
+ keeps up to 2,000 documents and 16 MiB, and when it is full the API keeps
1148
+ the pins of the latest 3 production releases first, then what a production
1149
+ key ran in the last 30 days, then other pins, such as a preview build's.
1150
+ On Vercel and Netlify the command reads both from the build
1151
+ (`VERCEL_GIT_COMMIT_SHA` and `VERCEL_ENV`, or `COMMIT_REF` and `CONTEXT`),
1152
+ so there is nothing to pass. Elsewhere, pass the flags or set `CAPA_RELEASE`
1153
+ and `CAPA_RELEASE_ENV`. A release is 1 to 64 letters, digits, dots, dashes
1154
+ or underscores, such as a commit or a deploy id, and an environment is a
1155
+ lowercase name such as `production` or `preview`. The two go together, and
1156
+ the command checks them before it sends anything. The manifest records them
1157
+ as `release` and `env`.
1158
+
1159
+ Two things decide whether a document is stored:
1160
+
1161
+ - The key. `capa persist` reads the development key from `CAPA_DRAFT_KEY`,
1162
+ the name `/nextjs` reads for drafts (`CAPA_KEY` when that is unset), and
1163
+ refuses a production key before it sends anything. A production key ships
1164
+ in your site's bundle, so it may run a document but never register one.
1165
+ - The host. `capa persist` sends each document to `CAPA_API_URL`, the URL
1166
+ your site already reads. `https://api.capacms.com` passes every POST on to
1167
+ the host that stores documents. On a self-hosted stack whose read host
1168
+ stores nothing, set `CAPA_ADMIN_URL` to the API host your Capa admin uses;
1169
+ it wins over `CAPA_API_URL`. When a host stores nothing, the command says
1170
+ so and names the variable to set.
1171
+
1172
+ When a hash is not stored yet, a production client still gets its data, with
1173
+ no error: the API answers the GET with `PersistedQueryNotFound`, the client
1174
+ sends one POST carrying the document and the hash, and the API runs it and
1175
+ answers `extensions.persistedQuery.registered: false`. The client then
1176
+ remembers that hash for five minutes and sends POST straight away, so a
1177
+ missing registration costs one extra GET per five minutes rather than one per
1178
+ call. `registered: false` on a production read is how to spot a document
1179
+ `capa persist` did not register. `graphql()` from `/nextjs` is not persisted
1180
+ by default for the same reason: until `capa persist` has run, every hash
1181
+ misses.
1182
+
1183
+ A builder read (`capa.graphql.query`) cannot be persisted, and
1184
+ `persisted: true` there throws a `TypeError` before any request. Its
1185
+ document is printed when it runs, so `capa persist` never sees it, and a
1186
+ production key never stores one. It is already a cacheable GET.
1187
+
1188
+ ### A REST select as a builder read, and back
1189
+
1190
+ `selectToSelection` turns a REST read into a typed builder selection, which
1191
+ `client.graphql.query` runs and `toTree` turns into that read's `data`.
1192
+ `graphqlToSelect` gives a builder selection's REST request, as it gives a
1193
+ tool spec's:
1194
+
1195
+ ```ts
1196
+ import { graphqlToSelect, selectToSelection, toTree } from "@capacms/sdk/next";
1197
+
1198
+ const schema = await capa.graphqlSchema();
1199
+ const selection = selectToSelection(schema, "articles", "title,author(name)", { sort: ["-views"], limit: 5 });
1200
+ const { data } = await capa.graphql.query(selection);
1201
+ const { articles } = toTree(data, selection, schema);
1202
+ // deep-equal to (await capa.entries.list("articles", { select: "title,author(name)", sort: ["-views"], limit: 5 })).data
1203
+
1204
+ graphqlToSelect(schema, { articles: { args: { first: 5 }, nodes: { title: true, author: { name: true } } } }).url;
1205
+ // "/api/entries/articles?select=title,author(name)&limit=5"
1206
+ ```
1207
+
1208
+ The selection names what `toTree` needs to answer what REST answers: `id`,
1209
+ `model` and `status` on every entry, `pageInfo` on every relation list, and
1210
+ all six media fields. Its fields are known only when it runs, so its data and
1211
+ its tree are untyped, with a typed client too. It takes what `selectToGraphQL`
1212
+ takes and refuses what it refuses. A relation the select names bare, which
1213
+ REST returns unexpanded as `{ id, model }`, is read expanded to its id, the
1214
+ REST read `author(id)`, because GraphQL reads a relation to a model the key
1215
+ can read as an entry. `graphqlToSelect` reads a selection's one model root
1216
+ field, and throws `CapaBuildError` for any other root (`version`, `entry`),
1217
+ and for a relation list read from a cursor in a list read, which have no REST
1218
+ request here. `last` with no `before`, or with `before: null` as Relay and
1219
+ Apollo send it, reads the end of the list: REST's `before=end`.
1220
+
1221
+ ### The tool spec: build a query for an explorer or an assistant
1222
+
1223
+ Tools that build queries (the admin's Explorer, the MCP server) share one
1224
+ plain format, the tool spec: `{ model, fields, first, sort, filter }`. The SDK
1225
+ reads the key's schema once and writes GraphQL from it in Capa's canonical
1226
+ format, and moves between it and a REST read:
1227
+
1228
+ ```ts
1229
+ import { buildGraphQLQuery, graphqlToSelect, selectToGraphQL } from "@capacms/sdk/next";
1230
+
1231
+ const schema = await capa.graphqlSchema(); // models, fields, filters, sorts, from one request
1232
+
1233
+ const spec = { model: "articles", fields: ["title", { field: "author", fields: ["name"] }], sort: ["views_DESC"], first: 5 };
1234
+ const { query, variables } = buildGraphQLQuery(schema, spec);
1235
+ graphqlToSelect(schema, spec).url;
1236
+ // "/api/entries/articles?select=title,author(name)&sort=-views&limit=5"
1237
+
1238
+ selectToGraphQL(schema, "articles", "title,author(name)", { sort: ["-views"], limit: 5 });
1239
+ // the same tool spec, from a REST read
1240
+ ```
1241
+
1242
+ The tool spec is not the typed builder's selection: `client.graphql.query`
1243
+ and `toTree` take the selection, which `selectToSelection` writes.
1244
+
1245
+ `graphqlToSelect` writes the REST twin exactly as the API writes it in
1246
+ `extensions.capa.rest`: the filter as `where` JSON, the root's default page
1247
+ size left out, a relation list's `first` written as `limit:` whenever you give
1248
+ it (100 included, since REST counts a limit you write in full and one you
1249
+ leave out as 10), and a system key a field of the model shadows written with `$`
1250
+ (`_tags` beside a field called `tags` is `select=$tags,tags`; `createdAt_DESC`
1251
+ beside a field called `createdAt` is `sort=-$createdAt`). That includes a
1252
+ field GraphQL leaves out because its name collides with another's, which the
1253
+ type's description lists as `Not exposed:` and the schema summary as
1254
+ `notExposed`: beside a hidden field called `id`, `id_DESC` is `sort=-$id`.
1255
+ `selectToGraphQL` reads `$` names back, and refuses a REST name for a hidden
1256
+ field, which GraphQL cannot read. It selects what the REST read returns: a
1257
+ media value with all six of its fields (`id url alt type width height`), and
1258
+ `*`, or no select, as everything: the system keys `createdAt`, `updatedAt`,
1259
+ `publishedAt`, `version`, `folder` and `tags`, every field, and each relation
1260
+ list as a connection of ids (`coauthors { nodes { id } }`), the page of
1261
+ references REST returns. A reference to an entry the key cannot see is the
1262
+ one difference left: REST shows it as `{ id, model, missing: true }`, and
1263
+ GraphQL reads it as `null`, or leaves it out of a list. `buildGraphQLQuery`
1264
+ with no `fields` keeps its own shorter default, media as `id url alt`. Both helpers send each filter value as the type its
1265
+ filter input declares, since GraphQL refuses any other: `"10"` for a number
1266
+ field becomes `10`, and `has: "true"` on a list of true/false values becomes
1267
+ `true`, which its `BooleanListFilter` takes. A name the schema does not have,
1268
+ or a key a relation's spec does not take (`frist` for `first`, at any depth),
1269
+ throws `CapaBuildError` with `didYouMean`, before anything is sent. A `where`
1270
+ on `$tags` ports to GraphQL's `_tags` filter:
1271
+
1272
+ ```ts
1273
+ import { selectToGraphQL } from "@capacms/sdk/next";
1274
+
1275
+ const schema = await capa.graphqlSchema();
1276
+ selectToGraphQL(schema, "articles", "title", { where: { $tags: { has: "news" } } });
1277
+ // { model: "articles", fields: ["title"], filter: { _tags: { has: "news" } } }
1278
+ ```
1279
+
1280
+ A model GraphQL leaves out, because its type name would collide with
1281
+ another's (`twin_a` and `twin-a`), is listed in the summary's `restOnly`.
1282
+ Asked for one, the builder throws `CapaBuildError` naming its REST read
1283
+ (`twin_a is readable over REST only: GET /api/entries/twin_a.`) and why,
1284
+ with no `didYouMean`: `entries.list("twin_a")` reads it.
1285
+
1286
+ Two REST reads have no GraphQL twin and throw too: a `where` on `$version`,
1287
+ `$folder`, `$model` or `$status` (GraphQL filters `id`, `createdAt`,
1288
+ `updatedAt`, `publishedAt` and `_tags`), and a filter hop through a relation
1289
+ the key cannot read (REST answers it `unknown_field`).
1290
+
1291
+ A tool spec pages as a REST read does: `first` with `after` reads the page after a
1292
+ cursor, and `first` with `before` the entries just before one. GraphQL writes
1293
+ the second as `last` with `before`, and the API refuses `first` there, so
1294
+ `{ first: 25, before }` prints `articles(last: $last, before: $before)`, and
1295
+ a tool spec with both `after` and `before` throws, as the API refuses it.
1296
+ `before: "end"` reads the last entries of the list, REST's `before=end`:
1297
+ `{ first: 5, before: "end" }` prints `articles(last: $last)`, and the list's
1298
+ `startCursor` pages back from there. `after: "end"` throws, since `end` is not
1299
+ a cursor.
1300
+ A read of one entry also pages a relation list from its cursor, as REST's
1301
+ `coauthors(name,after:…)` does: `{ field: "coauthors", fields: ["name"],
1302
+ after }` in a spec with `mode: "single"`, or `args: { after }` on the list in
1303
+ a selection. A list read throws for it, as the API refuses it there
1304
+ (`after: applies to a single entry`). `sort` takes one value or a list, at
1305
+ the root as on a relation list.
1306
+
1307
+ A spec written as REST writes a read throws, and says what to write instead:
1308
+ `"author.name"` or `"author(name)"` in `fields` is
1309
+ `{ field: "author", fields: ["name"] }`, `"*"` is `fields` left out, and a
1310
+ sort `"-publishedAt"` is `"publishedAt_DESC"` (in `didYouMean` too).
1311
+ Relations nest up to 4 deep below the root entry, which with the root is the
1312
+ API's 5 levels of entries; a fifth throws `CapaBuildError` and names the field
1313
+ to select without fields, for its id.
1314
+
150
1315
  ## Typed select and codegen
151
1316
 
152
1317
  `Select<T>` is exported from `@capacms/sdk/next`. `capa-codegen` keeps the legacy
153
1318
  `/v2/schema/types` shape for schemas without relations. When a schema has
154
- relations, codegen wraps them in branded helpers:
1319
+ relations, codegen wraps them in branded helpers, which describe the model;
1320
+ a read's `fields` is typed from them as the API returns it (see Typed reads):
155
1321
 
156
1322
  ```ts
157
1323
  export type CapaRelation<T> = T & { readonly __capaRelation: "one"; readonly __capaRelationTarget: T };
@@ -167,7 +1333,31 @@ export type ArticleSelect = import("@capacms/sdk/next").Select<Article>;
167
1333
  ```
168
1334
 
169
1335
  Those brands let TypeScript tell scalar fields from relation fields, so misspelled
170
- fields and invalid nested selects fail in consumer typechecks.
1336
+ fields and invalid nested selects fail in consumer typechecks. A relation named
1337
+ alone (`"author"`) is read as a reference.
1338
+
1339
+ Every name is written so the module parses, whatever the namespace holds. A
1340
+ field that is not an identifier is quoted (`"am/pm_indicator"?: string;`,
1341
+ read as `fields["am/pm_indicator"]`), and a model whose name is not one is
1342
+ named as GraphQL names it: `2024_events` is `_2024Events`, with
1343
+ `_2024EventsSelect` beside it. Two models whose names give one interface name,
1344
+ such as `twin_a` and `twin-a`, are each named from the whole namespace instead:
1345
+ `Model_twin_a` and `Model_twin$2da`, each character that is not a letter, digit
1346
+ or `_` written as `$` and its hex code. An enum's values are written as stored,
1347
+ a quote or a backslash included.
1348
+
1349
+ A select names a field by its namespace as saved, whatever it holds:
1350
+ `["price.usd", { "at.place": ["zip.code"] }]`. The client writes a name holding
1351
+ `,` `(` `)` `:` `.` `"` `*` `[` `]` or a space, or starting with `-`, quoted, as
1352
+ REST's grammar reads it: `select="price.usd","at.place"("zip.code")`. A string
1353
+ select, `sort` and `where` take REST's own text, so write such a name quoted
1354
+ there yourself: `sort: ['-"price.usd"']`.
1355
+
1356
+ A select also takes the entry's system keys by their `$` names, which mean the
1357
+ system key even on a model with a field of the same plain name
1358
+ (`SystemKey`): `["title", "$tags", { coauthors: { select: ["name"], sort: "-$createdAt" } }]`.
1359
+ A `$` name that is no system key fails to compile. A field whose namespace
1360
+ starts with `$` cannot be named, so `select: "*"` is how to read it.
171
1361
 
172
1362
  ## Pages and preview
173
1363
 
@@ -192,6 +1382,15 @@ const capa = createClient({ baseUrl, apiKey, version: "2026-10-01" });
192
1382
  const posts = await capa.entries.list("articles", { page: routeOf(import.meta.url) });
193
1383
  ```
194
1384
 
1385
+ Send `path` beside it, the concrete path being rendered, and Capa can list the
1386
+ real URLs an entry appears on, not only the route patterns:
1387
+
1388
+ ```ts
1389
+ await capa.entries.list("articles", { page: "/blog/[slug]", path: `/blog/${slug}` });
1390
+ ```
1391
+
1392
+ `path` goes out as `Capa-Path`, only when `page` is also set.
1393
+
195
1394
  `routeOf` turns a Next route file into the page string: `/blog/[slug]`. It
196
1395
  drops route groups `(marketing)`, parallel slots `@modal`, the leaf file name
197
1396
  and the extension. Write the string out by hand if you prefer; `routeOf` exists
@@ -199,6 +1398,19 @@ so that moving a folder cannot silently split one page's telemetry in two. Set
199
1398
  `page` on the config instead when a client serves exactly one page; a value on
200
1399
  the call wins over one on the config.
201
1400
 
1401
+ A layout is not a page. `app/layout.tsx` (and any nested `layout.*` or
1402
+ `template.*`) renders around every page below it, and Next does not tell it
1403
+ which one, so its reads cannot be charged to the page being rendered. `routeOf`
1404
+ returns `"(layout)"` for these files, exported as `LAYOUT_PAGE`, and a read that
1405
+ names it sends no `Capa-Page` header at all, even when the client was created
1406
+ with a `page`. So a Site singleton or a nav read in your root layout is simply
1407
+ not attributed, instead of making `/` look as if it read everything:
1408
+
1409
+ ```ts
1410
+ // In app/layout.tsx: same call as in a page, and no page is recorded.
1411
+ const site = await capa.entries.list("site", { page: routeOf(import.meta.url) });
1412
+ ```
1413
+
202
1414
  A malformed value throws a `TypeError`. Capa itself ignores a header it cannot
203
1415
  store, because a mangled page identity must never take a blog down, so the SDK
204
1416
  is the place a typo surfaces.
@@ -252,7 +1464,7 @@ exactly like a site that is up to date.
252
1464
 
253
1465
  `capa.pages.get(page)` carries an `insights` array: suggestions drawn from that
254
1466
  page's own reads, computed by Capa so that this SDK, the Capa admin and
255
- `@capa/mcp` all read one answer.
1467
+ Capa's MCP server all read one answer.
256
1468
 
257
1469
  ```ts
258
1470
  const detail = await capa.pages.get("/blog/[slug]");
@@ -328,45 +1540,202 @@ editor sees the path without a link to open it.
328
1540
 
329
1541
  ## Live preview
330
1542
 
1543
+ ### Quick start (Next.js)
1544
+
1545
+ Preview needs `@capacms/sdk` 1.0.0-next.8 or later. The `latest` tag is
1546
+ older and has no `capaHeaders`, so install the `next` tag:
1547
+
1548
+ ```sh
1549
+ pnpm add @capacms/sdk@next
1550
+ ```
1551
+
1552
+ Set `CAPA_API_URL`, `CAPA_KEY` (`cap_live_`, or the legacy key your site
1553
+ holds) and `CAPA_DRAFT_KEY` (`cap_test_`). Draft reads through the SDK take a
1554
+ `cap_` key only (see Keys). Then:
1555
+
1556
+ ```ts
1557
+ // middleware.ts
1558
+ import { NextResponse } from "next/server";
1559
+ import { capaMiddleware } from "@capacms/sdk/nextjs";
1560
+ export const middleware = capaMiddleware({ NextResponse });
1561
+
1562
+ // app/api/capa/preview/route.ts (and exit/route.ts with exitPreviewRoute)
1563
+ import { cookies, draftMode } from "next/headers";
1564
+ import { createPreviewRoute } from "@capacms/sdk/nextjs";
1565
+ export const GET = createPreviewRoute({ draftMode, cookies });
1566
+
1567
+ // next.config.mjs
1568
+ import { capaHeaders } from "@capacms/sdk/nextjs";
1569
+ export default { async headers() { return capaHeaders(); } };
1570
+
1571
+ // in a page: getCapaClient({ draftMode, headers }), then <h1 {...fieldAttrs(post).title}>
1572
+ // in the root layout: const edit = await editMode({ draftMode, headers }) from @capacms/sdk/nextjs,
1573
+ // then {edit ? <CapaOverlay adminOrigins={[...]} /> : null} from @capacms/sdk/nextjs/overlay
1574
+ ```
1575
+
1576
+ In Capa, set the project's preview URL to your site, and editors can click
1577
+ your page. The sections below explain each piece.
1578
+
331
1579
  The Capa editor can show your site beside the form: focus a field and its spot
332
1580
  on the page is outlined, click the page and the editor jumps to the field, save
333
- and the draft re-renders in place. It needs three things on your side. A
334
- complete, runnable example is `examples/sdk-demo` in this repository.
1581
+ and the draft re-renders in place. Where live preview is on, the text being
1582
+ typed shows on the page before the save (see the protocol below). It needs three things on your side.
1583
+
1584
+ ### 1. Turn on edit mode and tag what an editor can click
335
1585
 
336
- ### 1. Tag what an editor can click
1586
+ Edit mode is on when Next draft mode is on, or when the request carries a
1587
+ `capa-edit` token the Capa editor's Published view sends. Work it out once per
1588
+ request and build the client with it:
1589
+
1590
+ ```ts
1591
+ // lib/capa.ts
1592
+ import { draftMode, headers } from "next/headers";
1593
+ import { createClient } from "@capacms/sdk/next";
1594
+ import { editMode } from "@capacms/sdk/nextjs";
1595
+
1596
+ export async function capa() {
1597
+ const draft = (await draftMode()).isEnabled;
1598
+ return createClient({
1599
+ baseUrl, version: "2026-10-01",
1600
+ apiKey: draft ? process.env.CAPA_DRAFT_KEY! : process.env.CAPA_KEY!,
1601
+ editMode: await editMode({ draftMode, headers }),
1602
+ });
1603
+ }
1604
+ ```
337
1605
 
338
- `capaAttrs(entry, field, enabled)` from `@capacms/sdk/next` returns the two
339
- attributes the overlay looks for. `field` is the field's namespace, which is its
340
- key in `entry.fields`, and it autocompletes when the entry is typed. Pass the
341
- draft flag as `enabled` so a published page ships no entry ids.
1606
+ Then tag fields with `capaAttrs(entry, field)` from `@capacms/sdk/next`. `field`
1607
+ is the field's namespace, its key in `entry.fields`, and it autocompletes when
1608
+ the entry is typed. There is no flag to pass: an entry read by an edit-mode
1609
+ client carries a hidden mark (related entries too), and `capaAttrs` tags only
1610
+ marked entries. A visitor's page therefore ships no `data-capa-` attributes.
342
1611
 
343
1612
  ```tsx
344
1613
  import { capaAttrs } from "@capacms/sdk/next";
345
1614
 
346
- <h1 {...capaAttrs(article, "title", isDraft)}>{article.fields.title}</h1>
1615
+ <h1 {...capaAttrs(article, "title")}>{article.fields.title}</h1>
347
1616
  ```
348
1617
 
349
- ### 2. Start the overlay in draft mode
1618
+ The mark does not survive a spread copy or being passed to a client component,
1619
+ so tag in the server component that read the entry. `capaAttrs(entry, field,
1620
+ true)` still forces the tags on and `false` forces them off.
1621
+
1622
+ **When the entry crosses to the browser as data, pass the flag.** The mark is
1623
+ a hidden symbol, so anything that serializes the entry drops it silently: the
1624
+ Next Pages Router's `getServerSideProps`, SvelteKit and Remix loaders, Nuxt's
1625
+ payload, or your own JSON endpoint. The page then shows the draft with no
1626
+ `data-capa-` tags, and the editor has nothing to point at. Nothing errors. Send
1627
+ the draft or edit state alongside the entry and hand it to `capaAttrs`:
350
1628
 
351
1629
  ```tsx
352
- // app/capa-overlay.tsx
353
- "use client";
354
- import { useEffect } from "react";
355
- import { useRouter } from "next/navigation";
356
- import { startOverlay } from "@capacms/sdk/overlay";
357
-
358
- export function CapaOverlay({ adminOrigins }: { adminOrigins: string[] }) {
359
- const router = useRouter();
360
- useEffect(() => startOverlay({ adminOrigins, onRefresh: () => router.refresh() }), [adminOrigins, router]);
361
- return null;
1630
+ // pages/articles/[id].tsx on the Pages Router. A +page.server.ts load or
1631
+ // useAsyncData on the server hands over the flag the same way.
1632
+ import type { Entry } from "@capacms/sdk/next";
1633
+ import type { Articles } from "./capa-types";
1634
+
1635
+ export async function getServerSideProps({ draftMode = false }) {
1636
+ const entry = (await capa.entries.get<Articles>("articles", "entry-id"))!.data;
1637
+ return { props: { entry, edit: draftMode } };
1638
+ }
1639
+
1640
+ // in the component
1641
+ export default function Page({ entry, edit }: { entry: Entry<Articles>; edit: boolean }) {
1642
+ return <h1 {...capaAttrs(entry, "title", edit)}>{entry.fields.title}</h1>;
1643
+ }
1644
+ ```
1645
+
1646
+ Or re-mark the entries where they arrive with `markEditEntries(data)` when the
1647
+ page is in edit mode.
1648
+
1649
+ GraphQL reads are marked the same way, from `getCapaClient`, an edit-mode
1650
+ `createClient` or `graphql()` given `{ draftMode, headers }`. A node is an
1651
+ entry when it selected `id` and `model`, and `field` is the field as you
1652
+ selected it:
1653
+
1654
+ ```tsx
1655
+ const { data } = await capa.graphql.query({ articles: { nodes: { id: true, model: true, title: true } } });
1656
+ <h1 {...capaAttrs(data!.articles!.nodes[0], "title")}>{data!.articles!.nodes[0].title}</h1>
1657
+ ```
1658
+
1659
+ A field GraphQL renamed (`hero_image` for `hero-image`) is tagged by its
1660
+ namespace, which the editor knows it by: in edit mode the client reads the
1661
+ names of the key's types and fields once a minute to know which fields those
1662
+ are. That read starts beside the page's read, so the page waits for the
1663
+ slower of the two, and a document that never says `model` reads no names.
1664
+ With a typed client, tagging a node that did not select `model` does not
1665
+ compile.
1666
+ `toTree` keeps the mark, so its entries tag like REST entries, by namespace.
1667
+
1668
+ To accept `capa-edit`, verify it in middleware. The token is checked with Capa,
1669
+ any forged `x-capa-edit` header is removed, and edit-mode responses are marked
1670
+ `private, no-store`:
1671
+
1672
+ ```ts
1673
+ // middleware.ts
1674
+ import { NextResponse, type NextRequest } from "next/server";
1675
+ import { resolveEditRequest } from "@capacms/sdk/nextjs";
1676
+
1677
+ export async function middleware(request: NextRequest) {
1678
+ const edit = await resolveEditRequest(request, publishedClient());
1679
+ const response = NextResponse.next({ request: { headers: edit.headers } });
1680
+ if (edit.cacheControl) response.headers.set("Cache-Control", edit.cacheControl);
1681
+ if (edit.robotsTag) response.headers.set("X-Robots-Tag", edit.robotsTag);
1682
+ return response;
362
1683
  }
363
1684
  ```
364
1685
 
365
- Render it from your root layout only when `(await draftMode()).isEnabled`.
1686
+ ### 2. Start the overlay in edit mode
1687
+
1688
+ ```tsx
1689
+ // app/layout.tsx
1690
+ import { CapaOverlay } from "@capacms/sdk/nextjs/overlay";
1691
+
1692
+ {edit ? <CapaOverlay adminOrigins={["https://app.capacms.com"]} /> : null}
1693
+ ```
1694
+
1695
+ `@capacms/sdk/nextjs/overlay` is a client component and needs `react` and
1696
+ `next`. Without Next, call `startOverlay({ adminOrigins, onRefresh })` from
1697
+ `@capacms/sdk/overlay` in your own effect.
1698
+
1699
+ Render it from your root layout only in edit mode
1700
+ (`await editMode({ draftMode, headers })`), so it never runs for a visitor.
1701
+ Imported this way, its code still sits in the layout's chunk, which every
1702
+ visitor downloads. To keep it out, load it lazily from a small client
1703
+ component, as step 5 of "Add preview to a live site without changing it"
1704
+ shows. Both overlay entry points reach a bundler as ES modules, so loading
1705
+ the overlay leaves the rest of a visitor's chunks as they were.
1706
+
366
1707
  `startOverlay` returns a disposer and is safe to call twice. Outside a frame it
367
1708
  does nothing at all, and inside one it only listens to a parent window at one of
368
- `adminOrigins`. Without `onRefresh` a save reloads the page; the scroll position
369
- is kept either way.
1709
+ `adminOrigins`.
1710
+
1711
+ **Clicks inside the editor's frame.** A click on a tagged element selects its
1712
+ field in the editor. A ⌘-click (Ctrl-click on Windows and Linux) on a tagged
1713
+ element that is a link, or sits inside one, follows the link inside the frame
1714
+ instead, so an editor can move between pages. The hover label says so over a
1715
+ link. A link with no tag on or around it navigates as usual.
1716
+
1717
+ **After a save.** `<CapaOverlay />` re-renders the draft in place with
1718
+ `router.refresh()` and keeps the scroll position.
1719
+
1720
+ - The refresh runs in a React transition. While it is pending, the overlay
1721
+ makes a no-op state update every 300 ms. Under React 19.2 and Next 15.5, a
1722
+ draft refresh can otherwise stay suspended after its whole response has
1723
+ arrived, when the page sits inside a Suspense boundary that is already on
1724
+ screen (a root `loading.tsx` makes one), and show nothing until some other
1725
+ state update.
1726
+ - A refresh that has not landed after `refreshTimeoutMs` (10 seconds) reloads
1727
+ the page instead, which comes back to the same scroll position.
1728
+ - `refresh="reload"` reloads the page on every save, for a site that prefers
1729
+ it:
1730
+
1731
+ ```tsx
1732
+ <CapaOverlay adminOrigins={["https://app.capacms.com"]} refresh="reload" />
1733
+ ```
1734
+
1735
+ With `startOverlay`, `onRefresh` may return a promise that settles once the new
1736
+ draft is on screen. The overlay waits for it up to `refreshTimeoutMs`, and
1737
+ reloads if it rejects or is still pending. Without `onRefresh` every save
1738
+ reloads. The scroll position is kept every way.
370
1739
 
371
1740
  ### 3. Accept the preview link on any page
372
1741
 
@@ -397,46 +1766,274 @@ export function middleware(request: NextRequest) {
397
1766
  `/api/draft` is the route handler shown under "Open a draft in your own site"
398
1767
  above, reading `token` and `path`.
399
1768
 
400
- **Cookies in a frame.** The editor frames your site from another site, and a
401
- browser only sends a cookie into a cross-site frame when it is
402
- `SameSite=None; Secure`. Next sets the draft-mode cookie that way in a
403
- production build. `next dev` sets it `SameSite=Lax`, so re-set it as
404
- `SameSite=None; Secure` in your draft route while developing (browsers accept
405
- `Secure` on `http://localhost`). Safari's third-party cookie blocking can still
406
- drop it, which is why every preview load carries a fresh token and step 3
407
- honours it on any page.
1769
+ **Cookies in a frame.** The editor frames your site from another site. A
1770
+ browser sends a cookie into a cross-site frame only when it is
1771
+ `SameSite=None; Secure`, and Safari 26.2 and later only when it is
1772
+ `Partitioned` too. Next sets the draft-mode cookie with neither `Partitioned`
1773
+ nor `Max-Age`, so it is dropped in Safari's frame and, everywhere else, opens
1774
+ every draft on the site until the browser closes. Pass Next's `cookies` to
1775
+ `createPreviewRoute` and `exitPreviewRoute` and they re-set it as
1776
+ `HttpOnly; Secure; SameSite=None; Partitioned; Path=/; Max-Age=3600`, and
1777
+ delete it the same way. `maxAge` changes the hour. In your own route, call
1778
+ `frameDraftCookie(cookies)` after `enable()` and `clearDraftCookie(cookies)`
1779
+ after `disable()`. A browser that drops the cookie still gets a fresh token on
1780
+ every preview load, which step 3 honours on any page.
1781
+
1782
+ Leave `redirect` out of both routes. Each then answers with its own 307,
1783
+ marked `X-Robots-Tag: noindex, nofollow`, `Referrer-Policy: no-referrer` (the
1784
+ token is in the URL) and `Cache-Control: private, no-store`. Next's
1785
+ `redirect()` cannot carry headers, so passing it keeps the old redirect.
1786
+
1787
+ **Mark drafts, and let Capa frame them.** `capaHeaders()` returns rules for
1788
+ `next.config`'s `headers()` that send `X-Robots-Tag: noindex, nofollow` and
1789
+ `Content-Security-Policy: frame-ancestors 'self' https://app.capacms.com` on a
1790
+ request carrying the draft cookie or a `capa-preview`, `capa-edit` or
1791
+ `capa-view` query, and on nothing else. A visitor's response, cached or not,
1792
+ is unchanged. Pass `adminOrigins` to name another admin, such as one running
1793
+ locally, and pass the same list to `createPreviewRoute`. A browser applies
1794
+ every CSP it is sent, so if your site sends its own `frame-ancestors` or
1795
+ `X-Frame-Options`, leave them off draft responses with
1796
+ `missing: [{ type: "cookie", key: DRAFT_COOKIE }]` on that rule.
1797
+ `capaMiddleware` marks its edit-mode responses noindex too, and
1798
+ `resolveEditRequest` returns the value as `robotsTag`.
1799
+
1800
+ ### Add preview to a live site without changing it
1801
+
1802
+ A live Next.js site that reads Capa with its own code keeps that code. Preview
1803
+ adds a branch that only draft mode switches on, and draft mode is off for
1804
+ every visitor, at build time and during ISR. Reading
1805
+ `(await draftMode()).isEnabled` leaves a static page static, so a visitor gets
1806
+ the same pages, headers and cache as before.
1807
+
1808
+ 1. **Read drafts in draft mode.** In the helper that fetches from Capa, before
1809
+ the existing fetch, read the same URL with a draft key and no cache. The
1810
+ data has the same shape, so every page renders unchanged.
1811
+
1812
+ ```ts
1813
+ // lib/capa-draft.ts
1814
+ import "server-only";
1815
+ import { draftMode } from "next/headers";
1816
+
1817
+ export async function isDraft(): Promise<boolean> {
1818
+ // draftMode() throws outside a request (generateStaticParams, some build steps).
1819
+ try { return (await draftMode()).isEnabled; } catch { return false; }
1820
+ }
1821
+
1822
+ // in the fetch helper, before the existing fetch, which stays as it is
1823
+ if (await isDraft()) {
1824
+ return fetch(`https://api.capacms.com/v2/api/${endpoint}${query}`, {
1825
+ headers: { "x-api-key": process.env.CAPA_DRAFT_KEY! },
1826
+ cache: "no-store",
1827
+ }).then(parse); // the helper's existing parse
1828
+ }
1829
+ ```
1830
+
1831
+ The draft key is any key of yours whose environment is not `production`
1832
+ (see Preview is a key, not a flag). Keep it server-only, never in a
1833
+ `NEXT_PUBLIC_` variable, and keep the branch in a `server-only` module: a
1834
+ helper a client component also imports would bundle it.
1835
+
1836
+ 2. **Add the preview and exit routes** with `createPreviewRoute({ draftMode,
1837
+ cookies })` and `exitPreviewRoute({ draftMode, cookies })`, as in the Quick
1838
+ start. Set `CAPA_API_URL` to `https://api.capacms.com` and `CAPA_KEY` to
1839
+ the production key the site already reads with, server-only: the routes
1840
+ check the editor's token with it.
1841
+
1842
+ 3. **Add the middleware behind a matcher**, so a visitor's request never runs
1843
+ it. Next reads `config` from the file itself, so write the matcher out:
1844
+
1845
+ ```ts
1846
+ // middleware.ts (proxy.ts on Next 16)
1847
+ import { NextResponse } from "next/server";
1848
+ import { capaMiddleware } from "@capacms/sdk/nextjs";
1849
+
1850
+ export const middleware = capaMiddleware({ NextResponse });
1851
+ export const config = {
1852
+ matcher: [
1853
+ { source: "/:path*", has: [{ type: "query", key: "capa-preview" }] },
1854
+ { source: "/:path*", has: [{ type: "query", key: "capa-edit" }] },
1855
+ { source: "/:path*", has: [{ type: "query", key: "capa-view" }] },
1856
+ { source: "/:path*", has: [{ type: "cookie", key: "__prerender_bypass" }] },
1857
+ ],
1858
+ };
1859
+ ```
1860
+
1861
+ 4. **Add `capaHeaders()`** to `next.config`'s `headers()`, as in the Quick
1862
+ start: drafts are marked noindex and only the Capa admin can frame them.
1863
+
1864
+ 5. **Start the overlay and tag fields in draft mode.** Load the overlay
1865
+ lazily from a small client component, so its code is not in a chunk a
1866
+ visitor downloads, and render that component from the root layout in
1867
+ draft mode only:
1868
+
1869
+ ```tsx
1870
+ // components/capa-preview.tsx
1871
+ "use client";
1872
+ import { lazy, Suspense } from "react";
1873
+
1874
+ const CapaOverlay = lazy(() =>
1875
+ import("@capacms/sdk/nextjs/overlay").then((m) => ({ default: m.CapaOverlay })),
1876
+ );
1877
+
1878
+ export default function CapaPreview({ adminOrigins }: { adminOrigins: string[] }) {
1879
+ return (
1880
+ <Suspense fallback={null}>
1881
+ <CapaOverlay adminOrigins={adminOrigins} />
1882
+ </Suspense>
1883
+ );
1884
+ }
1885
+
1886
+ // app/layout.tsx
1887
+ const draft = await isDraft();
1888
+ {draft ? <CapaPreview adminOrigins={["https://app.capacms.com"]} /> : null}
1889
+ ```
1890
+
1891
+ Tag an editable field with `{...capaAttrs({ id: entry.id }, "title", draft)}`.
1892
+ With `draft` false it returns `{}`, so a visitor's HTML gains no
1893
+ attribute. The field is its key in the entry, which is its namespace.
1894
+
1895
+ 6. **Route handlers that set their own `Cache-Control`** must send
1896
+ `private, no-store` in draft mode. Otherwise a CDN keeps a draft fetched by
1897
+ the editor's browser and serves it to everyone.
1898
+
1899
+ Do not call `editMode()`, `getCapaClient()` or `resolveEditRequest()` from a
1900
+ static or ISR page or layout. Each reads `headers()`, which makes every route
1901
+ that calls it dynamic: the HTML stays the same, but the site loses ISR and
1902
+ renders every view. `isDraft()` above is the static-safe check. The editor's
1903
+ Published view then shows the static page without the overlay.
1904
+
1905
+ In Capa, set the project's preview URL to the site's production origin, and
1906
+ give each model with a page a route pattern, or Preview has no link to open.
1907
+
1908
+ ### A save that shows nothing: a page transition that freezes the route
1909
+
1910
+ A site that animates page changes with framer-motion often wraps each page in
1911
+ a `FrozenRoute`, which pins Next's `LayoutRouterContext` so the page that is
1912
+ leaving keeps its content while it animates out:
1913
+
1914
+ ```tsx
1915
+ "use client";
1916
+
1917
+ import { useContext, useRef } from "react";
1918
+ import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime";
1919
+
1920
+ const FrozenRoute = ({ children }: { children: React.ReactNode }) => {
1921
+ const context = useContext(LayoutRouterContext);
1922
+ const frozen = useRef(context).current;
1923
+
1924
+ return (
1925
+ <LayoutRouterContext.Provider value={frozen}>
1926
+ {children}
1927
+ </LayoutRouterContext.Provider>
1928
+ );
1929
+ };
1930
+
1931
+ export default FrozenRoute;
1932
+ ```
1933
+
1934
+ The pinned context keeps the page as the frame first drew it. After a save,
1935
+ `router.refresh()` fetches the draft and nothing on screen changes, and no
1936
+ overlay setting can reach inside the freeze. Skip it in draft mode only. Give
1937
+ the page-transition wrapper a `live` prop:
1938
+
1939
+ ```tsx
1940
+ "use client";
1941
+
1942
+ import { usePathname } from "next/navigation";
1943
+ import { AnimatePresence, motion } from "framer-motion";
1944
+ import FrozenRoute from "./frozen-route";
1945
+
1946
+ const PageAnimatePresence = ({
1947
+ children,
1948
+ live,
1949
+ }: {
1950
+ children: React.ReactNode;
1951
+ /** Capa preview (draft mode only): no freeze, so an editor's save shows in place. */
1952
+ live?: boolean;
1953
+ }) => {
1954
+ const pathname = usePathname();
1955
+
1956
+ return (
1957
+ <AnimatePresence mode="wait">
1958
+ <motion.div className="flex flex-col flex-grow" key={pathname}>
1959
+ {live ? children : <FrozenRoute>{children}</FrozenRoute>}
1960
+ </motion.div>
1961
+ </AnimatePresence>
1962
+ );
1963
+ };
1964
+
1965
+ export default PageAnimatePresence;
1966
+ ```
1967
+
1968
+ and pass it from the root layout as a conditional spread, so a visitor's
1969
+ props, and the RSC payload that carries them, are exactly what they were:
1970
+
1971
+ ```tsx
1972
+ // app/layout.tsx
1973
+ const draft = await isDraft();
1974
+
1975
+ <PageAnimatePresence {...(draft ? { live: true } : {})}>
1976
+ {children}
1977
+ </PageAnimatePresence>
1978
+ ```
408
1979
 
409
- **Let Capa frame the site.** Send
410
- `Content-Security-Policy: frame-ancestors 'self' https://app.capacms.com` (your
411
- admin origin) so the editor can frame the site and nothing else can.
1980
+ Writing `live={draft}` instead would send `live: false` to every visitor.
1981
+ To find the freeze, search the site for `LayoutRouterContext`.
412
1982
 
413
1983
  ### The protocol
414
1984
 
415
- Every message is `{ source, v: 1, type, ...fields }`. The admin sends
1985
+ Every message is `{ source, v: 1, type, ...fields }`. `source` is
1986
+ `capa-admin` on the admin's messages and `capa` on the site's. The admin sends
416
1987
  `hello`, `highlight { entryId, field }` (`entryId: ""` clears), `outline { on }`
417
1988
  and `refresh`. The site answers `ready { path, entries }` after every hello and
418
1989
  every navigation, `select { entryId, field }` on a click, and `hover`.
419
1990
  `acceptMessage(event, allowedOrigins, parent)` is the site's filter, exported
420
1991
  for your own tests.
421
1992
 
1993
+ The site also sends `visible { entryId, field }` while the page scrolls (at
1994
+ most every 150ms, and only when it changes): the tagged element at the centre
1995
+ of the viewport, chosen by `pickCentred`. At the very top of a page, where a
1996
+ heading can never reach the centre, it is the topmost visible element instead,
1997
+ and at the very bottom the bottommost. The editor's "Follow the page" scrolls
1998
+ the form to that field. An overlay older than 1.0.0-next.2 never sends it, and
1999
+ the editor then does not follow.
2000
+
2001
+ Following a link with ⌘-click sends no message of its own: the page the link
2002
+ leads to answers with `ready`, as after any navigation, so an editor of any
2003
+ version follows along.
2004
+
2005
+ Since 1.0.0-next.10 `ready` also lists `features: ["patch"]`, and the admin
2006
+ may send `patch { entryId, fields: [{ field, value, saved }] }` while an
2007
+ editor types: the unsaved text of plain text, number and option fields, and
2008
+ the saved value the page was rendered from. The overlay puts `value` into a
2009
+ tagged element's one text node while that text reads `saved` or what it last
2010
+ patched it to, so a field your site formats (a price, a date, Markdown) is
2011
+ left alone until the save re-renders it. It writes text, never markup, and
2012
+ only for the admin that said hello. Rich text, media and relations wait for
2013
+ the save, as before. An admin sends patches only when its project has live
2014
+ preview on.
2015
+
422
2016
  ## Not yet
423
2017
 
424
- `--select-from-depth`, `capa convert-url`, `capa persist`, GraphQL, and `/api/`
2018
+ `--select-from-depth`, `capa convert-url`, GraphQL mutations, and `/api/`
425
2019
  writes are not in this release.
426
2020
 
427
2021
  ## The legacy `/v2/api` client
428
2022
 
429
- A read client for Capa, plus two arrangement writes (`workspaces`,
430
- `models.setLayout`) and `capa-codegen`, a command that pulls a tenant's
431
- generated TypeScript so content is typed at the call site.
2023
+ `@capacms/sdk` is the client for sites that read `/v2/api` today. It takes a
2024
+ legacy key (`pk_`, `sk_` or unprefixed) and the tenant's id, and refuses a
2025
+ `cap_` key where it is built, since `/v2` answers one as an invalid key: a
2026
+ `cap_` key reads `/api/`, with `createClient` from `@capacms/sdk/next`.
2027
+ Besides reads, it schedules publishes, arranges the admin's workspaces and
2028
+ entry layouts, and manages webhook endpoints.
432
2029
 
433
2030
  ```ts
434
2031
  import { createClient } from "@capacms/sdk";
435
2032
  import type { BlogPost } from "./capa-types"; // written by capa-codegen
436
2033
 
437
2034
  const capa = createClient({
438
- baseUrl: process.env.CAPA_BASE_URL!,
439
- apiKey: process.env.CAPA_API_KEY!,
2035
+ baseUrl: process.env.CAPA_API_URL!,
2036
+ apiKey: process.env.CAPA_KEY!, // a pk_ key, not a cap_ key
440
2037
  tenantId: process.env.CAPA_TENANT_ID!,
441
2038
  });
442
2039
 
@@ -444,80 +2041,90 @@ const page = await capa.listContent<BlogPost>("blog_post", { limit: 10 });
444
2041
  const one = await capa.findOne<BlogPost>("blog_post", { handle: "hello" });
445
2042
  ```
446
2043
 
447
- ## Codegen
2044
+ ### An entry's id: read `Page.ids`
448
2045
 
449
- ```
450
- CAPA_BASE_URL=... CAPA_API_KEY=... CAPA_TENANT_ID=... capa-codegen --out src/capa-types.ts
2046
+ A `/v2/api` row puts the model's own fields at its top level, so a model
2047
+ with a field named `id` replaces the entry's id in the row, and the same goes
2048
+ for `title` and `tags`. Many models have one: every Shopify model names a
2049
+ field `id`. So read `Page.ids`, not `row.id`:
2050
+
2051
+ ```ts
2052
+ const page = await capa.listContent("shopify_page");
2053
+ page.ids[0] // the entry's UUID when the row has one to give
2054
+ page.data[0].id // the model's OWN id field whenever one exists
451
2055
  ```
452
2056
 
453
- Exit codes: `0` wrote or already current, `1` failed, `2` `--check` found a diff.
454
- `--check` is the CI mode — it fails when the committed file is stale.
2057
+ `Page.ids` is `string | null` per row, in the order of `data`: `null` means
2058
+ the model shadows `id` and the row carries nothing else to read the entry's
2059
+ id from. `instanceIdOf(row)` reads one row the same way, and prefers an
2060
+ `instanceId` when a row carries one. `getContentById` throws for an id that is
2061
+ not a UUID rather than spending a request on a certain 400. `search()` reads
2062
+ its hits the same way, so `SearchHit.id` is `string | null` too. `/api/` has
2063
+ no such collision: an entry's system keys sit beside its `fields`.
455
2064
 
456
- **Commit the output.** Not generated at install (needs credentials during
457
- `npm install`, which breaks CI images and Docker builds) and not at build time
458
- (makes every build network-dependent, and a Capa outage a build outage). A
459
- committed file is also what makes the feature useful: "a model changed, so the
460
- build fails" only helps if a human can see *what* changed, and a committed file
461
- turns that into a reviewable diff instead of a wall of `tsc` errors.
2065
+ ### Related entries: `Page.relations`
462
2066
 
463
- Re-running when nothing changed costs **one conditional request returning 0
464
- bytes** — see below.
2067
+ A read with a `depth` sends its related entries beside the rows, once each,
2068
+ keyed by entry id. Since 1.0.0-next.11 that map is `Page.relations`. On a row,
2069
+ a relation field's `value` is an id, or a list of ids, to look up in it:
465
2070
 
466
- ## Three server-side rough edges, handled here
2071
+ ```ts
2072
+ import { createClient, type FieldValue } from "@capacms/sdk";
467
2073
 
468
- The API is mid-port to a byte-parity bar, so changing a customer-facing response
469
- costs a signed exception. None of these is worth one, because each can be
470
- handled on this side.
2074
+ const capa = createClient({ baseUrl, apiKey, tenantId });
471
2075
 
472
- **1. `/v2/schema/types` has no ETag,** so it cannot be revalidated. `/v2/schema`
473
- *does* — it returns a `checksum` and honours `If-None-Match` with a 304, and that
474
- checksum is `sha256({models, relations})`, exactly what the types are generated
475
- from. So codegen gates on it and fetches types only when the schema moved.
2076
+ type Row = { data: Record<string, FieldValue> };
476
2077
 
477
- **2. The generator orders models by display name,** while interfaces are *named*
478
- from the namespace (`blogs_home_section` → `BlogsHomeSection`). Renaming a
479
- model's display name therefore reorders the whole file without changing a single
480
- type — a false "your types changed" in the exact mechanism this feature rests
481
- on. `normalizeTypes` re-sorts by interface name, so the committed file is stable
482
- under renames.
2078
+ const page = await capa.listContent<Row>("home_page", { depth: 2, limit: 1 });
2079
+ const ids = (page.data[0]?.data.sections?.value ?? []) as string[];
2080
+ const sections = ids.map((id) => page.relations[id]).filter((s) => s !== undefined);
483
2081
 
484
- **3. A model field named `id` overwrites the instance id** (#4628). Rows are
485
- built as `{...instance, ...formatInstanceData(instance)}` (`routes/v2/api.ts`).
486
- Hoisted fields are spread second, so `id`, `title` and `tags` are overwritten.
487
- In one ordinary tenant, 20 of 20 models shadow `title` and 7 of 20 shadow `id`.
2082
+ sections[0]?.modelType; // the related entry's model namespace
2083
+ sections[0]?.data.heading?.value; // its fields, each { type, value, sortOrder }
2084
+ ```
488
2085
 
489
- A server-side fix for this shipped briefly as #4628 (`instanceId` appended to
490
- every public row) and was reverted on 2026-09-20 under the public-surface
491
- freeze: `/v2/api`, `/v3/api`, the `/v1` public reads and `/files` answer the
492
- bytes the legacy API answers, and a row key that resolves the shadowing is
493
- planned for the next API version. **So a row from today's server carries no
494
- `instanceId`, and `row.id` may be a content value.**
2086
+ - `depth` is how many levels to follow, up to 4. The map holds every level,
2087
+ flat. At depth 0, the default, it is `{}`.
2088
+ - A related entry keeps its fields under `data` only, so its `id` is always
2089
+ the entry's UUID and its `title` the title of the version the key reads,
2090
+ whatever the model's fields are called. The API sends more columns than `RelatedEntry` names, and
2091
+ they come through as sent.
2092
+ - An id with no entry in the map is one the key cannot read: unpublished,
2093
+ for a production key, or deleted.
2094
+ - Type the related entries yourself with a second type argument:
2095
+ `listContent<Row, MyRelation>(...)`.
2096
+
2097
+ The reads of one row take `withRelations: true` and return the row with the
2098
+ map beside it, from the same request. Without it they return the row, as
2099
+ before:
495
2100
 
496
- The client already handles both: `instanceIdOf` prefers `instanceId` when a row
497
- has one and falls back to `id` when that is a UUID, so nothing here changes when
498
- the next version starts sending it.
2101
+ ```ts
2102
+ import { createClient } from "@capacms/sdk";
499
2103
 
500
- So **read `Page.ids`, not `row.id`**:
2104
+ const capa = createClient({ baseUrl, apiKey, tenantId });
501
2105
 
502
- ```ts
503
- const page = await capa.listContent("shopify_page");
504
- page.ids[0] // the instance UUID when the row has one to give
505
- page.data[0].id // the model's OWN id field whenever one exists
2106
+ const one = await capa.findOne("page", { handle: "about" }, { depth: 2, withRelations: true });
2107
+ if (one) {
2108
+ one.data; // the row findOne returns without withRelations
2109
+ one.id; // its entry id, as Page.ids reads it
2110
+ one.relations; // its related entries, as on a Page
2111
+ }
2112
+ const byId = await capa.getContentById("page", "3f6c1b4e-2a71-4d0e-9c55-8b0a1f2e7d34", { depth: 1, withRelations: true });
506
2113
  ```
507
2114
 
508
- `Page.ids` is `string | null` per row: `null` means the model shadows `id` and
509
- the server sent nothing else to read it from, which is the state of every server
510
- today. `getContentById` throws on a non-UUID rather than spending a request on a
511
- guaranteed 400.
2115
+ Both are `null` when there is no such row. A `withRelations` known only at
2116
+ run time, such as a draft-mode flag, types the result as either shape. A site
2117
+ that kept the answer's body through `config.fetch` to read `relations` can
2118
+ read it here instead.
512
2119
 
513
- `search()` is the same story. `/v2/api/search?extended=true` hoists fields the
514
- same way, so `SearchHit.id` is read through the same `instanceIdOf` and has the
515
- same `string | null` type.
2120
+ `/api/` has no such map. A relation the select expands comes back as the
2121
+ related entry, nested where it was selected, and with `shape: "flat"` once in
2122
+ `included`. See [Flat responses](#flat-responses-each-related-entry-once).
516
2123
 
517
- ## Preview is a key, not a flag
2124
+ ### Preview is a key, not a flag
518
2125
 
519
- Capa gates unpublished content on the API key's `environment` column, not on
520
- anything in the request (`routes/v2/api.ts:203`). There is no `?preview=true`, so
2126
+ Capa shows unpublished content to a key whose environment is not
2127
+ `production`, whatever the request says. There is no `?preview=true`, so
521
2128
  preview is a second client:
522
2129
 
523
2130
  ```ts
@@ -525,67 +2132,91 @@ const capa = createClient({ ...cfg, apiKey: PUBLISHED_KEY });
525
2132
  const preview = createClient({ ...cfg, apiKey: PREVIEW_KEY });
526
2133
  ```
527
2134
 
528
- The comparison is exact and case-sensitive against a free-text column, so **any**
529
- environment that is not literally `production` returns drafts — including a typo
530
- like `Production`. And a client cannot find out which it holds: `apiKeyEnvironment`
531
- is consumed internally and returned by no endpoint, so a site handed a `draft`
532
- key serves unpublished content publicly with no way to detect it.
533
-
534
- ## Not included
2135
+ The comparison is exact and case-sensitive, so **any** environment that is
2136
+ not literally `production` returns drafts, a typo like `Production`
2137
+ included. And a `/v2` client cannot find out which it holds: no `/v2`
2138
+ endpoint reports a key's environment, so a site handed a `draft` key serves
2139
+ unpublished content publicly with no way to detect it. `/api/` reports it:
2140
+ `capa.me()` on `@capacms/sdk/next` answers the key's `environment`.
535
2141
 
536
- **Caching.** Every framework does it differently and owning it means
537
- reimplementing all of them badly. Plain `fetch` returning plain data lets Next's
538
- fetch cache and React Router loaders work natively. What the host cannot know is
539
- which surrogate keys a response carries, so those are surfaced as
540
- `Page.cacheTags` for CDN purging.
2142
+ ### Codegen
541
2143
 
542
- **`getBySlug`.** Capa has no slug convention — the field is `handle` on
543
- `shopify_page`, `product_handle` on `judge_me_review`, `bloghandle` on
544
- `shopify_article`, and nothing marks one as *the* slug. `findOne(ns, {handle})`
545
- is explicit instead. A slug marker belongs on the model, in Capa.
546
-
547
- **Content writes.** `/v2/agent/model-instances` exists and an API key reaches
548
- it, so an SDK that can silently publish a draft is now technically possible.
549
- That wants a deliberate surface of its own rather than another method quietly
550
- added to the client, so it is absent rather than half-built. The one exception
551
- is `scheduledActions`, below, and the exception is narrow on purpose: a schedule
552
- is a request that leaves a row you can read, show and cancel. Publishing *now*
553
- leaves the caller holding the only copy of what happened.
2144
+ ```sh
2145
+ CAPA_API_URL=... CAPA_KEY=pk_... CAPA_TENANT_ID=... capa-codegen --out src/capa-types.ts
2146
+ ```
554
2147
 
555
- This section used to say the SDK could not write at all, because `verifyApiKey`
556
- guarded five route files carrying 15 GETs and no write verb. That stopped being
557
- true with the agent surface (`#383`) and `tenant_api_keys.permission` becoming a
558
- real control (`#4646`). Two things write today, and both touch arrangement
559
- rather than content:
2148
+ Without `--graphql`, `capa-codegen` reads the legacy `/v2` schema, which
2149
+ takes a `pk_` key and `CAPA_TENANT_ID`. A `cap_` key, which `/v2` refuses,
2150
+ writes the same interfaces from the key's GraphQL schema, with no tenant id,
2151
+ and so does `--schema <file>`, a schema `capa-codegen --graphql --save-schema`
2152
+ wrote. GraphQL does not say three things, so those types say less: every
2153
+ field is optional, an enum is a `string`, and a field GraphQL leaves out is
2154
+ `unknown`. There is no `CAPA_SCHEMA_CHECKSUM`, since that is the `/v2`
2155
+ schema's checksum. Where the API does not serve GraphQL, use a `pk_` key. It
2156
+ reads `.env.local` and `.env` too, as `next dev` does.
2157
+
2158
+ Exit codes: `0` wrote or already current, `1` failed, `2` `--check` found a
2159
+ diff. `--check` is the CI mode: it fails when the committed file is stale.
2160
+
2161
+ **Commit the output.** Generating at install needs credentials during
2162
+ `npm install`, which breaks CI images and Docker builds, and generating at
2163
+ build time makes every build depend on the network. A committed file also
2164
+ turns "a model changed, so the build fails" into a reviewable diff instead of
2165
+ a wall of `tsc` errors.
2166
+
2167
+ With a `pk_` key, re-running when nothing changed costs one conditional
2168
+ request that returns no body: codegen stamps the `/v2` schema's checksum in
2169
+ the file and fetches the types only when the schema moved. With `--graphql`,
2170
+ a `cap_` key or `--schema` there is no checksum, so every run reads the whole
2171
+ schema again: one full introspection request, or the file. Models are written
2172
+ in the order of their interface names, so renaming a model's display name
2173
+ does not reorder the file.
2174
+
2175
+ ### What it leaves out
2176
+
2177
+ **Caching.** Every framework caches differently, so the client returns plain
2178
+ data from plain `fetch`, and Next's fetch cache and React Router loaders work
2179
+ with it as they are. What your host cannot know is which surrogate keys a
2180
+ response carries, so `Page.cacheTags` holds them for purging a CDN.
2181
+
2182
+ **`getBySlug`.** Capa has no slug convention: the field is `handle` on
2183
+ `shopify_page`, `product_handle` on `judge_me_review` and `bloghandle` on
2184
+ `shopify_article`, and nothing marks one as the slug. `findOne(ns, { handle })`
2185
+ says which.
2186
+
2187
+ **Content writes.** The client writes no entry content. It schedules
2188
+ publishes (`scheduledActions`, below), a request that leaves a row you can
2189
+ read, show and cancel, and it writes arrangement, which touches no entry:
560
2190
 
561
2191
  ```ts
562
- await capa.workspaces.apply(id, { tree }); // the admin rail (0h, 0t)
563
- await capa.models.setLayout(id, layout); // the entry editor (0m)
2192
+ await capa.workspaces.apply(id, { tree }); // the admin's left rail
2193
+ await capa.models.setLayout(id, layout); // the entry editor
564
2194
  await capa.models.setLayout(id, null); // back to the linear editor
565
2195
  ```
566
2196
 
567
- Reading has two shapes. `models.getLayout(id)` is the document or null;
568
- `models.getLayoutInfo(id)` is the same read with the model's `embedByDefault`
569
- beside it, which is what decides a relation field with no `display` on its
570
- layout node (section 0m.8, and it applies in linear mode too):
2197
+ ### Workspaces and entry layouts
2198
+
2199
+ Reading a layout has two shapes. `models.getLayout(id)` is the document or
2200
+ null; `models.getLayoutInfo(id)` is the same read with the model's
2201
+ `embedByDefault` beside it, which decides how a relation field with no
2202
+ `display` renders, in linear mode too:
571
2203
 
572
2204
  ```ts
573
2205
  const { layout, embedByDefault } = await capa.models.getLayoutInfo(id);
574
2206
  ```
575
2207
 
576
- A workspace `tree` is a flat `WorkspaceDocNode[]` since 0t: one list of folders
577
- the customer named, each holding any mix of `{model}`, `{instance}`,
578
- `{media_folder}` and further folders. The 0h shape, `{ model, content, media }`,
579
- is still accepted for one release and lands in folders called Models, Content
580
- and Media.
2208
+ A workspace `tree` is a flat `WorkspaceDocNode[]`: one list of folders you
2209
+ named, each holding any mix of `{model}`, `{instance}`, `{media_folder}` and
2210
+ further folders. The older shape, `{ model, content, media }`, is still
2211
+ accepted and lands in folders called Models, Content and Media.
581
2212
 
582
2213
  `workspaces.*` needs a key with `write`; `models.setLayout` needs one with
583
- `agent`, because it writes a MODEL and that is the gate every other model write
584
- asks for. `models.getLayout` needs only `read`. A refused document comes back as
585
- `CapaError` carrying the API's own `{ error, path }`, where `path` names the
586
- node to fix. `apps/api/LAYOUT.md` has the rules and a worked example.
2214
+ `agent`, because it writes a model and that is the permission every model
2215
+ write asks for. `models.getLayout` needs only `read`. A refused document comes
2216
+ back as `CapaError` carrying the API's own `{ error, path }`, where `path`
2217
+ names the node to fix.
587
2218
 
588
- ## Scheduling a publish
2219
+ ### Scheduling a publish
589
2220
 
590
2221
  ```ts
591
2222
  const { batchId, resolved, actions, replaced } = await capa.scheduledActions.create({
@@ -596,10 +2227,9 @@ const { batchId, resolved, actions, replaced } = await capa.scheduledActions.cre
596
2227
  });
597
2228
  ```
598
2229
 
599
- **Instance targets only, from a key.** A `{ type: "model" }` target needs the
600
- `model:publish` permission, and no API key bundle carries it in phase 1, so the
601
- server answers 403 whatever the key. Scheduling a schema publish is an admin
602
- session job until a bundle grants it.
2230
+ **Entry targets only, from a key.** A `{ type: "model" }` target needs the
2231
+ `model:publish` permission, which no API key carries, so the server answers
2232
+ 403 whatever the key. Scheduling a model publish is done in the Capa admin.
603
2233
 
604
2234
  **Send a wall clock and a zone, not an instant.** `wallTime` carrying a `Z` or a
605
2235
  `+02:00` is refused, here and by the server, because the two together are the
@@ -647,18 +2277,17 @@ right now and `cancel` answers 409 `already_running`. `resultVersionId` on a
647
2277
  `done` row is the version that went live.
648
2278
 
649
2279
  Reading needs a `read` key; every write here needs `instance:publish`, which the
650
- `write`, `delete` and `agent` bundles carry. A refusal is a `CapaError` with the
651
- API's own `{ error, code }`. The operator's side of all of this, including what
652
- to do when an action fails at 3am, is `docs/PUBLISHING.md`.
2280
+ `write`, `delete` and `agent` keys carry. A refusal is a `CapaError` with the
2281
+ API's own `{ error, code }`.
653
2282
 
654
- ## Webhooks
2283
+ ### Webhooks
655
2284
 
656
2285
  Two halves that do not need each other. The verifier is clientless, so a
657
2286
  receiver imports one function and nothing else. The resource manages endpoints,
658
2287
  and it is the only thing in this SDK that needs a session token rather than an
659
2288
  API key.
660
2289
 
661
- ### Verifying a delivery
2290
+ #### Verifying a delivery
662
2291
 
663
2292
  ```ts
664
2293
  import { verifyWebhookSignature } from "@capacms/sdk";
@@ -697,12 +2326,12 @@ During the 24 hours after a rotation Capa sends two `v1=` entries, the new
697
2326
  secret first. Either one verifies, so a receiver can be updated any time inside
698
2327
  that window without dropping a request.
699
2328
 
700
- ### Managing endpoints
2329
+ #### Managing endpoints
701
2330
 
702
2331
  ```ts
703
2332
  const capa = createClient({
704
- baseUrl: process.env.CAPA_BASE_URL!,
705
- apiKey: process.env.CAPA_API_KEY!,
2333
+ baseUrl: process.env.CAPA_API_URL!,
2334
+ apiKey: process.env.CAPA_KEY!,
706
2335
  tenantId: process.env.CAPA_TENANT_ID!,
707
2336
  accessToken: sessionJwt, // from POST /v2/user/login
708
2337
  });
@@ -717,19 +2346,20 @@ const { secret, ...endpoint } = await capa.webhooks.endpoints.create({
717
2346
 
718
2347
  `createClient` still needs `apiKey` and `tenantId` to construct at all, so a
719
2348
  script that only ever calls `webhooks.*` has to pass something non-empty for
720
- both. Any placeholder will do, because no webhook call reads either one.
2349
+ both. Any legacy-looking placeholder will do, because no webhook call reads
2350
+ either one.
721
2351
 
722
2352
  **The tenant comes from the session, not from `tenantId`.** These routes read
723
2353
  the current tenant off the logged-in user's token, so the `tenantId` you passed
724
2354
  to `createClient` is ignored for every `webhooks.*` call: a client built with one
725
2355
  `tenantId` operates on whatever tenant that user is currently on.
726
2356
 
727
- **`accessToken`, not `apiKey`.** The webhook routes have no API key mount at
728
- all (publishing spec D8): a key that can add an endpoint can forward every
729
- content change in the tenant to a URL of its choosing, and a key is a string in
730
- a config file nobody rotates. So these routes want a logged-in person, and every
731
- `webhooks.*` method throws `@capacms/sdk: webhooks need accessToken; API keys
732
- cannot manage endpoints.` before sending anything when the token is absent.
2357
+ **`accessToken`, not `apiKey`.** The webhook routes take no API key at all: a
2358
+ key that can add an endpoint can forward every content change in the project
2359
+ to a URL of its choosing, and a key is a string in a config file nobody
2360
+ rotates. So these routes want a logged-in person, and every `webhooks.*`
2361
+ method throws `@capacms/sdk: webhooks need accessToken; API keys cannot manage
2362
+ endpoints.` before sending anything when the token is absent.
733
2363
 
734
2364
  The rest of the resource:
735
2365
 
@@ -752,9 +2382,9 @@ await capa.webhooks.deliveries.redeliver(deliveryId); // same event id
752
2382
  ```
753
2383
 
754
2384
  `test` answers `{ eventId }`, and that value is an **opaque request id**: the
755
- event that actually arrives carries a different `id` (`evt_` plus the outbox row
756
- id), so there is nothing to correlate on. Read `deliveries(id)` and take the
757
- newest `webhook.test` row to see what the test did.
2385
+ event that actually arrives carries a different `id` (`evt_` plus another
2386
+ id), so there is nothing to correlate on. Read `deliveries(id)` and take the newest
2387
+ `webhook.test` row to see what the test did.
758
2388
 
759
2389
  `resume` without `backfill` is deliberately a two-step: it enables the endpoint
760
2390
  and tells you how many events it missed, so you can show a person
@@ -762,10 +2392,7 @@ and tells you how many events it missed, so you can show a person
762
2392
  Call it again with `{ backfill: true, since }` if they say yes.
763
2393
 
764
2394
  Reads need `webhook:read`, writes need the `webhook:*` write actions, and
765
- `revealSecret` needs `secret:reveal`, which no role bundle holds: it is an owner
766
- or an explicit override, and every call leaves an audit row whether it was
767
- allowed or denied. A server without `CAPA_SECRET_KEY` set answers `503` with
768
- code `webhooks_not_configured` to every write while reads keep working.
769
-
770
- The operator's side of all of this, including the retry ladder, auto-pause, the
771
- SSRF rules and how to run a receiver locally, is `docs/WEBHOOKS.md`.
2395
+ `revealSecret` needs `secret:reveal`, which no role holds by default: it is an
2396
+ owner or an explicit grant, and every call leaves an audit row whether it was
2397
+ allowed or denied. A server without webhook secrets configured answers `503`
2398
+ with code `webhooks_not_configured` to every write while reads keep working.