@capacms/sdk 1.0.0-next.10 → 1.0.0-next.12

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 (60) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +368 -5
  3. package/bin/capa-check-bundle.js +80 -0
  4. package/bin/capa.js +3 -3
  5. package/bin/graphql-project.js +1 -1
  6. package/dist/client.d.ts +84 -4
  7. package/dist/client.js +23 -5
  8. package/dist/esm/image/index.d.ts +69 -2
  9. package/dist/esm/image/index.js +108 -5
  10. package/dist/esm/image/shared-params.generated.d.ts +126 -2
  11. package/dist/esm/image/shared-params.generated.js +224 -5
  12. package/dist/esm/overlay/index.d.ts +4 -1
  13. package/dist/esm/overlay/index.js +382 -30
  14. package/dist/esm/overlay/live-fields.d.ts +133 -0
  15. package/dist/esm/overlay/live-fields.js +478 -0
  16. package/dist/esm/overlay/markdown.d.ts +38 -0
  17. package/dist/esm/overlay/markdown.js +536 -0
  18. package/dist/esm/overlay/protocol.d.ts +51 -5
  19. package/dist/esm/overlay/protocol.js +79 -9
  20. package/dist/image/index.d.ts +69 -2
  21. package/dist/image/index.js +109 -4
  22. package/dist/image/shared-params.generated.d.ts +126 -2
  23. package/dist/image/shared-params.generated.js +235 -6
  24. package/dist/index.d.ts +1 -1
  25. package/dist/next/attrs.d.ts +42 -1
  26. package/dist/next/attrs.js +42 -3
  27. package/dist/next/client.d.ts +48 -1
  28. package/dist/next/client.js +33 -2
  29. package/dist/next/entry-fields.d.ts +43 -2
  30. package/dist/next/graphql/request.d.ts +4 -0
  31. package/dist/next/graphql/request.js +4 -0
  32. package/dist/next/graphql/tree.js +9 -0
  33. package/dist/next/index.d.ts +4 -4
  34. package/dist/next/index.js +3 -1
  35. package/dist/nextjs/index.d.ts +91 -7
  36. package/dist/nextjs/index.js +230 -17
  37. package/dist/nextjs/write-key-guard.d.ts +117 -0
  38. package/dist/nextjs/write-key-guard.js +285 -0
  39. package/dist/overlay/index.d.ts +4 -1
  40. package/dist/overlay/index.js +399 -29
  41. package/dist/overlay/live-fields.d.ts +133 -0
  42. package/dist/overlay/live-fields.js +493 -0
  43. package/dist/overlay/markdown.d.ts +38 -0
  44. package/dist/overlay/markdown.js +539 -0
  45. package/dist/overlay/protocol.d.ts +51 -5
  46. package/dist/overlay/protocol.js +82 -9
  47. package/dist/server/browser.d.ts +1 -0
  48. package/dist/server/browser.js +20 -0
  49. package/dist/server/client.d.ts +268 -0
  50. package/dist/server/client.js +335 -0
  51. package/dist/server/errors.d.ts +60 -0
  52. package/dist/server/errors.js +120 -0
  53. package/dist/server/index.d.ts +14 -0
  54. package/dist/server/index.js +32 -0
  55. package/dist/server/key-format.d.ts +41 -0
  56. package/dist/server/key-format.js +91 -0
  57. package/dist/server/transport.d.ts +47 -0
  58. package/dist/server/transport.js +114 -0
  59. package/dist/webhooks.d.ts +8 -0
  60. package/package.json +18 -4
package/CHANGELOG.md CHANGED
@@ -2,6 +2,176 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 1.0.0-next.12
6
+
7
+ Published 2026-11-02. Releases next.1 to next.11 did not get their own headings, so the notes below cover all of them. New since 1.0.0-next.11: live preview of Rich Text, rich text, images, toggles and dates; list-item and page-less preview targets; draft links that send their token and open without draft mode; release preview.
8
+
9
+ - Live preview of Rich Text fields. The overlay takes `fields` with `kind`
10
+ `"markdown"`: a Rich Text field's value, as markdown source or as the HTML
11
+ Capa's editor writes into it. The page shows the site's own rendering of
12
+ the saved value, so the overlay finds the element by the field's tag
13
+ (`capaAttrs`) and does not look for the saved value. It renders the
14
+ markdown with its own small renderer (headings, paragraphs, emphasis,
15
+ links, lists, code, quotes and rules; the package still has no runtime
16
+ dependencies), puts the result through the same sanitizer as `"html"`, and
17
+ replaces the element's content, inside a plain wrapper it holds. A page
18
+ that tags no element for the field does not change. The sanitizer now
19
+ keeps `<hr>`. New exports from `@capacms/sdk/overlay`: `renderMarkdown` and
20
+ `richTextHtml`. An overlay that does not know a `kind` skips that field
21
+ and keeps the rest.
22
+ - Live preview of rich text, images, toggles and dates. `ready` lists
23
+ `"fields"`, and the overlay takes the admin's `fields { entryId, fields:
24
+ [{ field, kind, value, saved }] }` for `kind` `"html"`, `"image"`,
25
+ `"boolean"` and `"date"`. Each changes only what the page drew from the
26
+ saved value exactly: rich text whose content is the saved HTML (after a
27
+ sanitizer that keeps what Capa's editor makes, built node by node and put
28
+ back before a refresh), an image whose `src` or `srcset` holds the saved
29
+ URL (the site's parameters kept, http(s) only), an element tagged
30
+ `data-capa-shown-when` (shown while the value is that), text that reads
31
+ `true` or `false`, and a day printed in a format the overlay reproduces,
32
+ with its `<time datetime>`. `capaAttrs` takes `{ shownWhen }`. New exports
33
+ from `@capacms/sdk/overlay`: `acceptLiveFields`, `parseHtml`,
34
+ `sanitizeHtml`, `canonicalHtml`, `preparedHtml`, `safeHref`,
35
+ `safeImageUrl`, `swapImageUrl`, `findDateFormat`, `formatDateAs`,
36
+ `swapDatetime`, `FIELDS_MAX_FIELDS`, `FIELDS_MAX_LENGTH`, and the
37
+ `LiveField`, `LiveImage`, `LiveKind`, `HtmlElement` and `HtmlNode` types.
38
+ A `fields` message with more than 500 fields or an HTML value over 100,000
39
+ characters is refused whole. Additive: an admin sends `fields` only to an
40
+ overlay that lists it.
41
+ - One item of a list, in live preview. `capaAttrs(entry, field, { item })`
42
+ tags an item of a list field with `data-capa-item`: its index, or a path of
43
+ indexes and keys inside the field (`{ item: [2, "question"] }`). A click on
44
+ it sends `select { entryId, field, item }`, and a `highlight` that names an
45
+ item outlines the elements tagged with it, or the whole field when the page
46
+ tags no such item. The box's label names the item ("faqs › item 3").
47
+ `capaAttrs`'s third argument may be `{ item, enabled }`; a boolean does what
48
+ it did. New exports: `itemPath` and `ITEM_MAX_DEPTH` from
49
+ `@capacms/sdk/next`, `isItemPath`, `itemMatches` and `itemLabel` from
50
+ `@capacms/sdk/overlay`, and the `CapaItem` and `CapaAttrsOptions` types.
51
+ Additive: an element without an item sends the select it always did, and an
52
+ admin that sends no item gets the outline it always did.
53
+ - Shareable draft links (Capa's Share draft, `CAPA_DRAFT_LINKS`) show only
54
+ their own entry's draft. `CapaNextConfig.draftLink` sends a draft link's
55
+ token as `Capa-Draft-Link` on every REST and GraphQL read. With a
56
+ development key the read serves the linked entry's draft and every other
57
+ entry as published, entries it relates to included, and no draft at all
58
+ once the link is revoked or expires; a production key ignores it.
59
+ `preview(token, { draftLinks: true })` sends `Capa-Draft-Links: narrow`,
60
+ without which Capa answers a draft link as an invalid token, and
61
+ `PreviewClaim` gains `draftLink: true` for one. In `@capacms/sdk/nextjs`,
62
+ `createPreviewRoute` given `cookies` opens a draft link without turning
63
+ draft mode on: it keeps the token in the `capa-draft-link` cookie
64
+ (`DRAFT_LINK_COOKIE`, httpOnly, `SameSite=Lax`) until the link expires or
65
+ `maxAge` passes, whichever is first, and clears it on any other preview.
66
+ `exitPreviewRoute` clears it (`clearDraftLinkCookie`). Outside draft mode,
67
+ `getCapaClient` and `graphql()` given `headers` read with the draft key
68
+ and send it from the request's cookies, and `draftLinkToken({ headers })`
69
+ reads it for a client you build yourself. `capaHeaders()` marks a request
70
+ carrying it noindex. A site on an earlier version gets no working draft
71
+ link: its preview route lands on `?preview=expired`.
72
+ - Release preview (Capa releases, `CAPA_RELEASES`). `CapaNextConfig.release`
73
+ sends a release preview token as `Capa-Release` on every REST and GraphQL
74
+ read. With a development key the read serves what is live plus the
75
+ releases the token names, and no other draft; a production key ignores it.
76
+ `PreviewClaim` gains `kind` and `releases`: a release preview link answers
77
+ `kind: "release"` with its releases, and `entryId` and `modelId` empty.
78
+ In `@capacms/sdk/nextjs`, `createPreviewRoute` given `cookies` keeps a
79
+ release link's token in the `capa-release` cookie (`RELEASE_COOKIE`,
80
+ partitioned, one hour) and clears it on any other preview, and
81
+ `exitPreviewRoute` clears it (`clearReleaseCookie`). `getCapaClient` and
82
+ `graphql()` send it under draft mode from the request's cookies,
83
+ `draftClient` does when given `cookies`, and `releaseToken({ cookies,
84
+ draftMode })` reads it for a client you build yourself. Sites that read
85
+ through the legacy `/v2/api` are not overlaid.
86
+ - `revalidateFromWebhook` refreshes everything on `release.published` and
87
+ `release.rolled_back`, which name a release rather than its entries: the
88
+ project's tag (`t:<tenantId>`, from the envelope), `GRAPHQL_TAG` and
89
+ `MEDIA_TAG`. `release.scheduled` and `release.failed` revalidate nothing.
90
+ Each entry a release changed still sends its own event, handled as before.
91
+ A release with an end time sends `release.rolled_back` with
92
+ `reason: "ended"` when it takes itself down, and that refreshes the same
93
+ way.
94
+ - New entry point `@capacms/sdk/server`, the client for Capa's server write
95
+ API at `https://write.capacms.com`, for a `capw_` write key. Server only:
96
+ under a bundler's `browser` condition the import throws, while `node`,
97
+ `edge-light`, `workerd`, `worker` and `react-server` resolve the client.
98
+ `createWriteClient({ key, version, baseUrl? })` has a method for each
99
+ route: `me`, `entries.list`, `get`, `create`, `update` (merge), `replace`,
100
+ `publish` (now or scheduled), `unpublish` (optionally only a given
101
+ `versionId`, else 412 `version_conflict`) and `delete`, and
102
+ `scheduledActions.get`, `list` and `cancel`. It sends the key as
103
+ `Authorization: Bearer` with `Capa-Version`, a random `Idempotency-Key` on
104
+ every create (or yours), `If-Match` from `ifMatch`, and retries a 429 once
105
+ after its `Retry-After` when that is at most `maxRetryAfterSeconds` (default
106
+ 10, `0` never). It throws `CapaWriteKeyInBrowserError` where
107
+ `window` or `document` exists, `CapaWriteKeyFormatError` for a key whose
108
+ checksum is wrong before anything is sent, and `CapaWriteError` (a
109
+ `CapaError` with `status`, `code` and `hint`) for a refusal. Every request
110
+ sends `User-Agent: capacms-sdk/server` and gives up after `timeoutMs`
111
+ (default 30000) with `CapaWriteTimeoutError`. On Node it sends with
112
+ `node:https`, outside a Next.js server's cached `fetch`; elsewhere with the
113
+ global `fetch`. A redirect is never followed (`redirect_refused`), and a
114
+ plain `http` `baseUrl` is refused unless it is this machine. `isWriteKeyShaped` and
115
+ `writeKeyChecksumOk` check a value without the API. Types follow the write
116
+ API's response shapes: `{ data, meta }` with `page` on lists, `WriteEntry`
117
+ with `versions.current` and `versions.published` (its live `fields`
118
+ included), `WriteKeyInfo` with the key's `models`, `ScheduledAction`, and
119
+ `ScheduledPublish` for the `202` of a scheduled publish, which
120
+ `entries.publish` is typed to return when given `at` or `wallTime`.
121
+ - New bin `capa-check-bundle`, the required step for a Next.js site that
122
+ holds a write key: `next build && capa-check-bundle`. It exits 1, naming
123
+ the file and line, when a `capw_` key is in what a browser downloads from
124
+ the finished build: `.next/static`, and the prerendered pages under
125
+ `.next/server` (HTML, RSC payloads, static route bodies, `getStaticProps`
126
+ data), where a key a server component passes to a client component's props
127
+ ends up. It also scans `out/` when there is one, or the directories named.
128
+ Only a match whose checksum is right fails; a value only shaped like a key
129
+ is a warning.
130
+ - `@capacms/sdk/nextjs` gains `withCapaWriteKeyGuard(nextConfig)`, an earlier
131
+ check: `next build` fails when a `capw_` key is in `.next/static`. It runs
132
+ in `compiler.runAfterProductionCompile` (Next 15.4 or later), before
133
+ prerendering, and keeps a hook the config has. On an older Next it adds
134
+ nothing and warns once. Also exported:
135
+ `scanForWriteKeys`, `scanNextBuildForWriteKeys`,
136
+ `assertNoWriteKeysInBundle`, `assertNoWriteKeysInBuild` and
137
+ `CapaWriteKeyInBundleError`. Additive: nothing else changes.
138
+ - Webhook endpoints gain an optional `localeEvents` boolean, on
139
+ `WebhookEndpoint` and in `CreateWebhookEndpointInput` and
140
+ `UpdateWebhookEndpointInput`. True sends each language's saves, publishes
141
+ and unpublishes to the endpoint; they are marked by `data.localeVersionId`.
142
+ The API sends and reads the key only for a project the locales flag serves.
143
+ Additive: every endpoint without it is the one returned before.
144
+ - Image placeholders, focal points and crops, all additive. `EntryMedia`
145
+ gains optional `blurDataURL`, `averageColor`, `dominantColor`, `palette`,
146
+ `blurhash`, `focalPoint` and `crop`, which `/api/` sends only for a project
147
+ that has them; new types `MediaFocalPoint` and `MediaCrop`. `imageUrl` and
148
+ `srcSet` name a media value's focal point and crop as `fp` and `rect` in a
149
+ crop to a shape (`fit: "cover"` with a width and a height), spelled as
150
+ Capa's CDN serves them, so a moved focal point is a new URL. They take
151
+ `focalPoint` and `crop` options too, and export the `ImageFocalPoint` and
152
+ `ImageCrop` types. Every other URL, and every URL of an image without them,
153
+ is the one built before. `imagePlaceholder(image)` gives next/image's
154
+ `placeholder` and `blurDataURL` props, and `placeholderColor(image)` the
155
+ image's average or dominant colour. `toTree` keeps those keys when a
156
+ selection names them. The builders' default media fields are unchanged,
157
+ since a project without them refuses a query that selects them.
158
+ - 1.0.0-next.11. The legacy client returns the related entries `/v2/api`
159
+ sends. `listContent` returns them as `Page.relations`, the map the API sends
160
+ beside the rows: each related entry once, keyed by its id, with its fields
161
+ under `data` (`RelatedEntry`). It is `{}` at depth 0, the default, and when
162
+ an answer has no map (`structure=tree`). `getContentById` and `findOne` take
163
+ `withRelations: true` and return `{ data, id, relations, meta, cacheTags }`
164
+ from the same request, or `null`; without it they return the row as before.
165
+ A `withRelations` known only at run time (a `boolean`, or a `ReadOneOptions`
166
+ value) types the result as either shape. New types: `RelatedEntry`,
167
+ `Relations`, `FieldValue`, `OneWithRelations` and `ReadOneOptions`. `Page`
168
+ and `listContent` take the related entries' type as an optional second type
169
+ argument. Up to next.10 the map was dropped, so a
170
+ site kept the answer's body through `config.fetch` to read it; it can read
171
+ `Page.relations` instead. A `Page` built by hand, in a test, now needs
172
+ `relations: {}`. `/api/` is unchanged and has no such map: a related entry
173
+ comes back nested where the select expanded it, or with `shape: "flat"`
174
+ once in `included`.
5
175
  - Live preview shows the text being typed, in 1.0.0-next.10. The overlay's
6
176
  `ready` lists `features: ["patch"]`, and it takes the admin's `patch`
7
177
  message: the unsaved value of a plain text, number or option field, with the
package/README.md CHANGED
@@ -14,11 +14,12 @@ It runs on Node 18 or later. Its types need TypeScript 5.0 or later, with
14
14
  | Import | What it is |
15
15
  |---|---|
16
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. |
17
+ | `@capacms/sdk/nextjs` | Next.js helpers: `graphql()` in a server component, cache tags, draft and edit mode, webhook revalidation, and the build check that keeps write keys out of the bundle. |
18
18
  | `@capacms/sdk/nextjs/overlay` | The live preview overlay, as a Next.js client component. |
19
19
  | `@capacms/sdk/overlay` | The same overlay without Next. |
20
20
  | `@capacms/sdk/image` | Image URLs on Capa's CDN for any framework: `imageUrl`, `srcSet`, `sizes` and `isCapaImageUrl`. |
21
21
  | `@capacms/sdk/nextjs/image-loader` | A `next/image` loader that lets Capa's CDN resize, for `images.loaderFile`. |
22
+ | `@capacms/sdk/server` | The server write API client, `createWriteClient`, for a `capw_` write key. Server only: never in a browser. |
22
23
  | `@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
 
24
25
  ## The `/api/` client (`@capacms/sdk/next`)
@@ -374,6 +375,66 @@ declare const cover: EntryMedia | null;
374
375
  const candidates = srcSet(cover, [640, 1280, 1920], { aspectRatio: 16 / 9, fit: "cover", format: "webp" });
375
376
  ```
376
377
 
378
+ ### Focal points and crops
379
+
380
+ Where your project has focal points and crops, an editor can mark the spot
381
+ in an image that matters most, and the part of it to show, in the media
382
+ library. `/api/` then sends them on every image as `focalPoint` (`{ x, y }`)
383
+ and `crop` (`{ x, y, width, height }`), fractions of the image from 0 to 1,
384
+ or `null` where none is set.
385
+
386
+ Capa's CDN uses them for every crop to a shape, `fit: "cover"` with both a
387
+ `width` and a `height`: it cuts the crop first, then centres the shape on the
388
+ focal point as far as the crop allows. Every other request is unchanged.
389
+ `imageUrl` and `srcSet` name them in those URLs as `fp` and `rect`, so a
390
+ moved focal point gives a new URL rather than the old crop from a cache:
391
+
392
+ ```ts
393
+ import { imageUrl } from "@capacms/sdk/image";
394
+
395
+ 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 };
396
+
397
+ imageUrl(hero, { width: 400, height: 400, fit: "cover", format: "webp" });
398
+ // https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?fit=cover&format=webp&fp=0.25,0.75&height=400&width=400
399
+ ```
400
+
401
+ The `focalPoint` and `crop` options replace the media value's for one URL,
402
+ and a `crop` option applies to any resize. Both need focal points and crops
403
+ on for the project: elsewhere the CDN ignores `fp` and `rect`. An image
404
+ without them, a URL or a file key gets the same URL as before.
405
+
406
+ ### Placeholders
407
+
408
+ Where your project has image placeholders, `/api/` sends each image's
409
+ `blurDataURL` (a blurred copy 20 pixels on its long side, as a data URL),
410
+ `averageColor` and `dominantColor` (`#rrggbb`), `palette` (up to five
411
+ colours, largest first) and `blurhash`, each `null` where there is none.
412
+ `imagePlaceholder(image)` turns one into next/image's props, and
413
+ `placeholderColor(image)` gives a colour to paint the space with while the
414
+ image loads:
415
+
416
+ ```tsx
417
+ import Image from "next/image";
418
+ import { imagePlaceholder, placeholderColor } from "@capacms/sdk/image";
419
+ import type { EntryMedia } from "@capacms/sdk/next";
420
+
421
+ export function Card({ image }: { image: EntryMedia }) {
422
+ if (!image.url) return null;
423
+ return (
424
+ <div style={{ backgroundColor: placeholderColor(image) }}>
425
+ <Image src={image.url} alt={image.alt ?? ""} width={image.width ?? 1200} height={image.height ?? 800} {...imagePlaceholder(image)} />
426
+ </div>
427
+ );
428
+ }
429
+ ```
430
+
431
+ `imagePlaceholder` gives `{ placeholder: "blur", blurDataURL }` when the
432
+ image has one and `{ placeholder: "empty" }` otherwise, so it can always be
433
+ spread. The placeholders, `focalPoint` and `crop` are optional properties of
434
+ `EntryMedia`, there only for a project that has them. The GraphQL `Media`
435
+ type has them only there too, so select them only there; codegen writes them
436
+ into your types when it does.
437
+
377
438
  ### Plain HTML
378
439
 
379
440
  Build the attributes wherever the page is rendered, a server template or a
@@ -482,6 +543,9 @@ default `quality`; `capaImageLoader`, the default export of
482
543
  `@capacms/sdk/nextjs/image-loader`, sets neither, so each image keeps its own
483
544
  format. Both are also exported from `@capacms/sdk/nextjs` for server code.
484
545
 
546
+ A `src` that `imageUrl` built with `fp` and `rect` keeps them through the
547
+ loader, so its crop to a shape still centres on the focal point.
548
+
485
549
  The loader resizes only a full Capa URL, on `cdn.capacms.com` or
486
550
  `api.capacms.com` (built on the CDN host, as above). Any other `src` goes
487
551
  back unchanged: a file in `public/`, another host, or a bare name such as
@@ -1044,7 +1108,7 @@ data type, `capa.graphql<{ version: string }>(text)`.
1044
1108
  Register your documents at build time, with a development key:
1045
1109
 
1046
1110
  ```sh
1047
- CAPA_API_URL=https://api.capacms.com CAPA_DRAFT_KEY=cap_test_... capa persist --manifest persisted.json
1111
+ CAPA_API_URL=https://cdn.capacms.com CAPA_DRAFT_KEY=cap_test_... capa persist --manifest persisted.json
1048
1112
  ```
1049
1113
 
1050
1114
  Then send only their hash, with any key, including the production key your
@@ -1100,7 +1164,7 @@ Two things decide whether a document is stored:
1100
1164
  refuses a production key before it sends anything. A production key ships
1101
1165
  in your site's bundle, so it may run a document but never register one.
1102
1166
  - The host. `capa persist` sends each document to `CAPA_API_URL`, the URL
1103
- your site already reads. `https://api.capacms.com` passes every POST on to
1167
+ your site already reads. `https://cdn.capacms.com` passes every POST on to
1104
1168
  the host that stores documents. On a self-hosted stack whose read host
1105
1169
  stores nothing, set `CAPA_ADMIN_URL` to the API host your Capa admin uses;
1106
1170
  it wins over `CAPA_API_URL`. When a host stores nothing, the command says
@@ -1556,6 +1620,25 @@ The mark does not survive a spread copy or being passed to a client component,
1556
1620
  so tag in the server component that read the entry. `capaAttrs(entry, field,
1557
1621
  true)` still forces the tags on and `false` forces them off.
1558
1622
 
1623
+ Tag each item of a list with `{ item }`, its index in the list, so a click on
1624
+ the third FAQ opens the third FAQ in the editor rather than the top of the
1625
+ list field, and focusing it in the editor outlines it on the page:
1626
+
1627
+ ```tsx
1628
+ <ul>
1629
+ {page.fields.faqs.map((faq, i) => (
1630
+ <li key={i} {...capaAttrs(page, "faqs", { item: i })}>{faq.question}</li>
1631
+ ))}
1632
+ </ul>
1633
+ ```
1634
+
1635
+ `item` is an index or a path inside the field (`{ item: [i, "question"] }`)
1636
+ and adds `data-capa-item`. The options object takes `enabled` too, which does
1637
+ what the boolean does. An editor whose project does not have item targeting
1638
+ yet opens the list field as before, so the tag is safe to add now. A list of
1639
+ related entries tagged with each entry's own id (`capaAttrs(faq, "question")`)
1640
+ needs none of this: a click there already opens that entry.
1641
+
1559
1642
  **When the entry crosses to the browser as data, pass the flag.** The mark is
1560
1643
  a hidden symbol, so anything that serializes the entry drops it silently: the
1561
1644
  Next Pages Router's `getServerSideProps`, SvelteKit and Remix loaders, Nuxt's
@@ -1758,7 +1841,7 @@ the same pages, headers and cache as before.
1758
1841
 
1759
1842
  // in the fetch helper, before the existing fetch, which stays as it is
1760
1843
  if (await isDraft()) {
1761
- return fetch(`https://api.capacms.com/v2/api/${endpoint}${query}`, {
1844
+ return fetch(`https://cdn.capacms.com/v2/api/${endpoint}${query}`, {
1762
1845
  headers: { "x-api-key": process.env.CAPA_DRAFT_KEY! },
1763
1846
  cache: "no-store",
1764
1847
  }).then(parse); // the helper's existing parse
@@ -1772,7 +1855,7 @@ the same pages, headers and cache as before.
1772
1855
 
1773
1856
  2. **Add the preview and exit routes** with `createPreviewRoute({ draftMode,
1774
1857
  cookies })` and `exitPreviewRoute({ draftMode, cookies })`, as in the Quick
1775
- start. Set `CAPA_API_URL` to `https://api.capacms.com` and `CAPA_KEY` to
1858
+ start. Set `CAPA_API_URL` to `https://cdn.capacms.com` and `CAPA_KEY` to
1776
1859
  the production key the site already reads with, server-only: the routes
1777
1860
  check the editor's token with it.
1778
1861
 
@@ -1950,6 +2033,227 @@ only for the admin that said hello. Rich text, media and relations wait for
1950
2033
  the save, as before. An admin sends patches only when its project has live
1951
2034
  preview on.
1952
2035
 
2036
+ Since the release after 1.0.0-next.11 `ready` lists `"fields"` too, and the
2037
+ admin may send `fields { entryId, fields: [{ field, kind, value, saved }] }`
2038
+ for the unsaved value of HTML fields (`kind: "html"`), Rich Text fields
2039
+ (`"markdown"`, the markdown source or the HTML Capa's editor writes into
2040
+ it), images (`"image"`, a
2041
+ `{ url, alt }` or `null`), toggles (`"boolean"`, `"true"` or `"false"`) and
2042
+ dates (`"date"`, `YYYY-MM-DD` or `""`). The rule is the patch's: the overlay
2043
+ changes only what the page drew from the saved value, exactly.
2044
+
2045
+ - Rich text: an element whose content is the saved HTML gets the new HTML.
2046
+ Both are compared after the overlay's sanitizer, which keeps what Capa's
2047
+ editor makes (paragraphs, headings, lists, marks, links to http, https,
2048
+ mailto, tel or the site, http(s) images, `ql-` classes and a colour) and
2049
+ drops scripts, frames, forms, embeds, event handlers and unsafe links. A
2050
+ site that formats or sanitizes rich text its own way does not match and
2051
+ waits for the save. The new HTML is built node by node, never through
2052
+ `innerHTML`, and the site's own nodes are put back before a refresh.
2053
+ - Rich Text: your site renders the markdown its own way, so the overlay
2054
+ does not look for the saved value. The element you tag with the field
2055
+ (`capaAttrs(entry, "body")`, on the element that holds the rendered
2056
+ markdown) gets the new value, rendered by the overlay's own small markdown
2057
+ renderer (`renderMarkdown`: headings, paragraphs, emphasis, links, lists,
2058
+ code, quotes and rules) and put through the same sanitizer. A plain
2059
+ `<div>`, `<section>`, `<article>` or `<main>` that is all the element holds
2060
+ keeps its place, and the content goes inside it. A heading or paragraph
2061
+ you tag takes one paragraph of text and waits for the save with more. An
2062
+ element that is a list item, or that holds another field's tag, waits for
2063
+ the save. A page that tags no element for the field does not change.
2064
+ - Images: an `<img>` or `<source>` whose `src` or `srcset` holds the saved
2065
+ image's URL (as it is, URL-encoded as next/image sends it, or by path on
2066
+ the same host) gets the new URL in its place, so your width and format
2067
+ parameters stay. Its `alt` follows while it reads the saved alt. A removed
2068
+ image is hidden until the save. Only http(s) URLs are written.
2069
+ - Toggles: tag the element a toggle shows with
2070
+ `capaAttrs(entry, "featured", { shownWhen: true })`, and render it with
2071
+ `hidden` rather than leaving it out when the saved value hides it. The
2072
+ overlay shows it while the unsaved value is `shownWhen` and hides it
2073
+ otherwise. Text that reads `true` or `false` follows as text.
2074
+ - Dates: text that is the saved day as `2026-11-01`, as the API's ISO
2075
+ instant, or in an `Intl.DateTimeFormat` style in the page's language (in
2076
+ UTC, as a calendar day is stored) gets the new day in the same format. A
2077
+ `<time datetime>` follows. A format the overlay cannot reproduce waits for
2078
+ the save.
2079
+
2080
+ An admin sends `fields` only to an overlay that lists it, and only when its
2081
+ project has the feature on.
2082
+
2083
+ `select` carries `item` when the clicked element has a `data-capa-item`, and
2084
+ the admin may send `highlight { entryId, field, item }` to outline one item of
2085
+ a list: the overlay outlines the elements tagged with that item, or the whole
2086
+ field when the page tags no such item. An item is up to 16 segments of
2087
+ letters, digits, `_` and `-` joined with dots (`isItemPath`); anything else is
2088
+ dropped and the message kept. An older overlay ignores `item` and outlines the
2089
+ whole field.
2090
+
2091
+ ## Server writes (`@capacms/sdk/server`)
2092
+
2093
+ **Server only. Never put a write key in a browser, an app bundle or a public
2094
+ repo.** A `capw_` key writes your project's content. Read it from a
2095
+ server-only environment variable (never one starting `NEXT_PUBLIC_`) and use
2096
+ it in server code only: a route handler, a server action, a webhook, a script.
2097
+ Capa refuses a write key sent from a browser and turns the key off.
2098
+
2099
+ Mint one in the Capa admin under Developers > Keys, New server write key. It
2100
+ writes only into its own project, to the models and actions you pick, until it
2101
+ expires.
2102
+
2103
+ ```ts
2104
+ import { createWriteClient, isCapaWriteError } from "@capacms/sdk/server";
2105
+
2106
+ const capa = createWriteClient({
2107
+ key: process.env.CAPA_WRITE_KEY!, // capw_..., server only
2108
+ version: "2026-10-01",
2109
+ });
2110
+
2111
+ const { data: booking } = await capa.entries.create("bookings", {
2112
+ fields: { name: "Ana Diaz", email: "ana@example.com", clinic: { id: "4f1c..." } },
2113
+ });
2114
+
2115
+ try {
2116
+ await capa.entries.update(
2117
+ "bookings",
2118
+ booking.id,
2119
+ { fields: { confirmed: true } },
2120
+ { ifMatch: booking.versions.current.number },
2121
+ );
2122
+ } catch (error) {
2123
+ if (!isCapaWriteError(error) || error.code !== "version_conflict") throw error;
2124
+ // Someone saved it first: read it again and retry.
2125
+ }
2126
+ ```
2127
+
2128
+ The client talks to `https://write.capacms.com` (`baseUrl` changes it) and
2129
+ sends the key as `Authorization: Bearer`, with `Capa-Version` on every
2130
+ request. `version` is required. `baseUrl` must be `https`; plain `http` is
2131
+ allowed only for `localhost`, `127.0.0.1` and `[::1]`, since the key would
2132
+ otherwise cross the network in clear text.
2133
+
2134
+ | Method | Route | The key needs |
2135
+ |---|---|---|
2136
+ | `me()` | `GET /me` | any write scope |
2137
+ | `entries.list(model, { limit, after, filter })` | `GET /entries/{model}` | any write scope on the model |
2138
+ | `entries.get(model, id)` | `GET /entries/{model}/{id}` | any write scope on the model |
2139
+ | `entries.create(model, { fields, status })` | `POST /entries/{model}` | `instance:create`, and `instance:publish` for `status: "published"` |
2140
+ | `entries.update(model, id, { fields })` | `PATCH /entries/{model}/{id}` | `instance:update` |
2141
+ | `entries.replace(model, id, { fields })` | `PUT /entries/{model}/{id}` | `instance:update` |
2142
+ | `entries.publish(model, id, { at })` | `POST /entries/{model}/{id}/publish` | `instance:publish` |
2143
+ | `entries.unpublish(model, id, { versionId })` | `POST /entries/{model}/{id}/unpublish` | `instance:publish` |
2144
+ | `entries.delete(model, id)` | `DELETE /entries/{model}/{id}` | `instance:delete` |
2145
+ | `scheduledActions.get(id)`, `.list({ targetId, status, limit, after })`, `.cancel(id)` | `/scheduled-actions` | `instance:publish` |
2146
+
2147
+ Every answer is `{ data, meta }`, and a list adds `page` (`limit`,
2148
+ `hasNext`, `next`; pass `next` back as `after`). An entry is its current
2149
+ values in `fields`, with `status` `draft`, `published` or `changed` (published,
2150
+ with a newer draft), and `versions`: `current` (`id`, `number`, `status`,
2151
+ `savedAt`) and `published` (`id`, `number`, `publishedAt` and the live
2152
+ `fields`), or `null` when nothing is published. `number` is the `version`
2153
+ `/api/` reads report. Every write returns the entry, so you always learn its
2154
+ new version.
2155
+
2156
+ `entries.update` merges: a field you send replaces, `null` clears it, and a
2157
+ field you leave out is kept. `entries.replace` sets every field. Both take
2158
+ `status: "draft"`, which saves a draft and leaves the published version live,
2159
+ or `status: "published"`, which saves and publishes. `entries.publish`
2160
+ publishes now and returns the entry, or schedules it with `at` (an ISO
2161
+ instant) or `wallTime` plus `timezone` and returns `{ action, replaced, entry }`:
2162
+ the scheduled action, the pending publishes it replaced, and the entry. A
2163
+ version saved under an older version of the model is refused with 409
2164
+ `stale_model_version`. `entries.unpublish` takes the live version down; with
2165
+ `versionId` it does so only if that version is the live one, and answers 412
2166
+ `version_conflict` otherwise. `scheduledActions.list` takes `targetId`, `status`
2167
+ (one or a list of `pending`, `running`, `done`, `failed`, `cancelled`),
2168
+ `limit` (at most 200) and `after`; a `done` publish names its `resultVersionId`
2169
+ and a `failed` one its `lastError` (`code`, `message`). `filter` on `entries.list` is equality on
2170
+ scalar fields. `me()` returns the project and the key, with each model it
2171
+ reaches (`id`, `namespace`, `actions`).
2172
+
2173
+ - **Never in a browser bundle.** Under a bundler's `browser` condition (a
2174
+ `"use client"` component, a Vite or webpack browser build) the import
2175
+ itself throws when the page loads it. Server builds, Next's edge runtime
2176
+ and Cloudflare Workers resolve the real client.
2177
+ - **Before anything is sent.** `createWriteClient` throws
2178
+ `CapaWriteKeyInBrowserError` where `window` or `document` exists, and every
2179
+ call checks again. It throws `CapaWriteKeyFormatError` for a key that is not
2180
+ `capw_` and 49 letters and digits, or whose last 6 characters are not its
2181
+ checksum, so a mistyped or truncated key fails where the client is built.
2182
+ - **Retries are safe.** `entries.create` sends a random `Idempotency-Key`;
2183
+ pass `idempotencyKey` to use your own, such as your booking id, so a retry
2184
+ after a timeout never makes a second entry. Every other write takes one
2185
+ too.
2186
+ - **Conflicts.** `ifMatch` sends `If-Match` with the version you read. If the
2187
+ entry has moved on, the write is refused with 412 `version_conflict` and
2188
+ the current version in `hint`.
2189
+ - **Rate limits.** 120 writes a minute and 20 a second per key. A 429 is
2190
+ retried once after its `Retry-After`, when that is at most
2191
+ `maxRetryAfterSeconds` (10 by default, so a serverless function is not
2192
+ killed mid-wait; `0` never retries). A longer wait, or a second 429,
2193
+ throws `rate_limited` with `retryAfter` set.
2194
+ - **Errors.** A refusal throws `CapaWriteError`, with `status`, `code`,
2195
+ `hint`, `param` (`fields.<name>` for a field that failed validation) and
2196
+ `requestId`. It is a `CapaError`, so `isCapaError` is true for it too.
2197
+ - **Timeouts.** A request that gets no answer in 30 seconds throws
2198
+ `CapaWriteTimeoutError`; `timeoutMs` changes that, and `0` turns it off.
2199
+ The write may still have been applied, so retry with the same
2200
+ `idempotencyKey`. Every request sends `User-Agent: capacms-sdk/server`,
2201
+ which the key's activity records.
2202
+ - **On Node** the client sends with Node's own `https` module, not `fetch`,
2203
+ so a Next.js server's cached `fetch` never answers a read with an old
2204
+ entry version. Elsewhere (an edge runtime, Deno, a worker) it uses the
2205
+ global `fetch`. A redirect is never followed: it throws `redirect_refused`.
2206
+ If you pass your own `fetch`, it must send no `Origin`, `Sec-Fetch-Site`,
2207
+ `Sec-Fetch-Dest` or `Cookie` header, which the write host refuses as a
2208
+ browser. Node's fetch is fine: the `Sec-Fetch-Mode` it adds is not
2209
+ counted.
2210
+
2211
+ ### Keep write keys out of the bundle (Next.js)
2212
+
2213
+ Required for any Next.js site that holds a write key: run `capa-check-bundle`
2214
+ after every build, in the same script, so a key that would reach a browser
2215
+ fails the deploy.
2216
+
2217
+ ```json
2218
+ { "scripts": { "build": "next build && capa-check-bundle" } }
2219
+ ```
2220
+
2221
+ It scans what a browser downloads from the finished build: every file under
2222
+ `.next/static`, and the pages prerendering wrote under `.next/server` (HTML,
2223
+ RSC payloads, static route bodies and `getStaticProps` data), never the
2224
+ server code beside them. That covers both ways a key gets out at build time:
2225
+ a `NEXT_PUBLIC_` variable inlined into client code, and a key a server
2226
+ component passes to a client component's props on a static page. It also
2227
+ scans `out/` when there is one. Name the directories yourself for a custom
2228
+ `distDir` or another framework: `capa-check-bundle build dist`.
2229
+
2230
+ A match whose checksum is right exits 1, naming the file and line and
2231
+ printing only the key's first 12 characters. A value that is only shaped like
2232
+ a key (a placeholder in your docs) is a warning and exits 0.
2233
+
2234
+ For an earlier failure on Next 15.4 or later, also wrap your config. Then
2235
+ `next build` itself fails when a key is inlined into client code:
2236
+
2237
+ ```js
2238
+ // next.config.mjs
2239
+ import { withCapaWriteKeyGuard } from "@capacms/sdk/nextjs";
2240
+
2241
+ export default withCapaWriteKeyGuard({
2242
+ // your config
2243
+ });
2244
+ ```
2245
+
2246
+ The wrapper runs in Next's `compiler.runAfterProductionCompile` hook, with
2247
+ webpack or Turbopack, and keeps a hook your config already has. That hook
2248
+ runs before prerendering, so it cannot see a key in a prerendered page: the
2249
+ bin is still the required step. On a Next older than 15.4 the wrapper adds
2250
+ nothing and prints a warning saying so.
2251
+
2252
+ No build check can see a page rendered per request. Never pass a write key
2253
+ to a client component, and keep the code that uses it in a module that only
2254
+ the server imports. If a check fails, move that code to the server, and
2255
+ rotate the key, since a build may already have shipped it.
2256
+
1953
2257
  ## Not yet
1954
2258
 
1955
2259
  `--select-from-depth`, `capa convert-url`, GraphQL mutations, and `/api/`
@@ -1999,6 +2303,65 @@ not a UUID rather than spending a request on a certain 400. `search()` reads
1999
2303
  its hits the same way, so `SearchHit.id` is `string | null` too. `/api/` has
2000
2304
  no such collision: an entry's system keys sit beside its `fields`.
2001
2305
 
2306
+ ### Related entries: `Page.relations`
2307
+
2308
+ A read with a `depth` sends its related entries beside the rows, once each,
2309
+ keyed by entry id. Since 1.0.0-next.11 that map is `Page.relations`. On a row,
2310
+ a relation field's `value` is an id, or a list of ids, to look up in it:
2311
+
2312
+ ```ts
2313
+ import { createClient, type FieldValue } from "@capacms/sdk";
2314
+
2315
+ const capa = createClient({ baseUrl, apiKey, tenantId });
2316
+
2317
+ type Row = { data: Record<string, FieldValue> };
2318
+
2319
+ const page = await capa.listContent<Row>("home_page", { depth: 2, limit: 1 });
2320
+ const ids = (page.data[0]?.data.sections?.value ?? []) as string[];
2321
+ const sections = ids.map((id) => page.relations[id]).filter((s) => s !== undefined);
2322
+
2323
+ sections[0]?.modelType; // the related entry's model namespace
2324
+ sections[0]?.data.heading?.value; // its fields, each { type, value, sortOrder }
2325
+ ```
2326
+
2327
+ - `depth` is how many levels to follow, up to 4. The map holds every level,
2328
+ flat. At depth 0, the default, it is `{}`.
2329
+ - A related entry keeps its fields under `data` only, so its `id` is always
2330
+ the entry's UUID and its `title` the title of the version the key reads,
2331
+ whatever the model's fields are called. The API sends more columns than `RelatedEntry` names, and
2332
+ they come through as sent.
2333
+ - An id with no entry in the map is one the key cannot read: unpublished,
2334
+ for a production key, or deleted.
2335
+ - Type the related entries yourself with a second type argument:
2336
+ `listContent<Row, MyRelation>(...)`.
2337
+
2338
+ The reads of one row take `withRelations: true` and return the row with the
2339
+ map beside it, from the same request. Without it they return the row, as
2340
+ before:
2341
+
2342
+ ```ts
2343
+ import { createClient } from "@capacms/sdk";
2344
+
2345
+ const capa = createClient({ baseUrl, apiKey, tenantId });
2346
+
2347
+ const one = await capa.findOne("page", { handle: "about" }, { depth: 2, withRelations: true });
2348
+ if (one) {
2349
+ one.data; // the row findOne returns without withRelations
2350
+ one.id; // its entry id, as Page.ids reads it
2351
+ one.relations; // its related entries, as on a Page
2352
+ }
2353
+ const byId = await capa.getContentById("page", "3f6c1b4e-2a71-4d0e-9c55-8b0a1f2e7d34", { depth: 1, withRelations: true });
2354
+ ```
2355
+
2356
+ Both are `null` when there is no such row. A `withRelations` known only at
2357
+ run time, such as a draft-mode flag, types the result as either shape. A site
2358
+ that kept the answer's body through `config.fetch` to read `relations` can
2359
+ read it here instead.
2360
+
2361
+ `/api/` has no such map. A relation the select expands comes back as the
2362
+ related entry, nested where it was selected, and with `shape: "flat"` once in
2363
+ `included`. See [Flat responses](#flat-responses-each-related-entry-once).
2364
+
2002
2365
  ### Preview is a key, not a flag
2003
2366
 
2004
2367
  Capa shows unpublished content to a key whose environment is not