@capacms/sdk 1.0.0-next.11 → 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 (46) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/README.md +246 -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/esm/overlay/index.d.ts +4 -1
  7. package/dist/esm/overlay/index.js +382 -30
  8. package/dist/esm/overlay/live-fields.d.ts +133 -0
  9. package/dist/esm/overlay/live-fields.js +478 -0
  10. package/dist/esm/overlay/markdown.d.ts +38 -0
  11. package/dist/esm/overlay/markdown.js +536 -0
  12. package/dist/esm/overlay/protocol.d.ts +51 -5
  13. package/dist/esm/overlay/protocol.js +79 -9
  14. package/dist/next/attrs.d.ts +42 -1
  15. package/dist/next/attrs.js +42 -3
  16. package/dist/next/client.d.ts +48 -1
  17. package/dist/next/client.js +33 -2
  18. package/dist/next/graphql/request.d.ts +4 -0
  19. package/dist/next/graphql/request.js +4 -0
  20. package/dist/next/index.d.ts +3 -3
  21. package/dist/next/index.js +3 -1
  22. package/dist/nextjs/index.d.ts +91 -7
  23. package/dist/nextjs/index.js +230 -17
  24. package/dist/nextjs/write-key-guard.d.ts +117 -0
  25. package/dist/nextjs/write-key-guard.js +285 -0
  26. package/dist/overlay/index.d.ts +4 -1
  27. package/dist/overlay/index.js +399 -29
  28. package/dist/overlay/live-fields.d.ts +133 -0
  29. package/dist/overlay/live-fields.js +493 -0
  30. package/dist/overlay/markdown.d.ts +38 -0
  31. package/dist/overlay/markdown.js +539 -0
  32. package/dist/overlay/protocol.d.ts +51 -5
  33. package/dist/overlay/protocol.js +82 -9
  34. package/dist/server/browser.d.ts +1 -0
  35. package/dist/server/browser.js +20 -0
  36. package/dist/server/client.d.ts +268 -0
  37. package/dist/server/client.js +335 -0
  38. package/dist/server/errors.d.ts +60 -0
  39. package/dist/server/errors.js +120 -0
  40. package/dist/server/index.d.ts +14 -0
  41. package/dist/server/index.js +32 -0
  42. package/dist/server/key-format.d.ts +41 -0
  43. package/dist/server/key-format.js +91 -0
  44. package/dist/server/transport.d.ts +47 -0
  45. package/dist/server/transport.js +114 -0
  46. package/package.json +18 -4
package/CHANGELOG.md CHANGED
@@ -2,6 +2,139 @@
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.
5
138
  - Webhook endpoints gain an optional `localeEvents` boolean, on
6
139
  `WebhookEndpoint` and in `CreateWebhookEndpointInput` and
7
140
  `UpdateWebhookEndpointInput`. True sends each language's saves, publishes
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`)
@@ -1107,7 +1108,7 @@ data type, `capa.graphql<{ version: string }>(text)`.
1107
1108
  Register your documents at build time, with a development key:
1108
1109
 
1109
1110
  ```sh
1110
- 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
1111
1112
  ```
1112
1113
 
1113
1114
  Then send only their hash, with any key, including the production key your
@@ -1163,7 +1164,7 @@ Two things decide whether a document is stored:
1163
1164
  refuses a production key before it sends anything. A production key ships
1164
1165
  in your site's bundle, so it may run a document but never register one.
1165
1166
  - 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
+ your site already reads. `https://cdn.capacms.com` passes every POST on to
1167
1168
  the host that stores documents. On a self-hosted stack whose read host
1168
1169
  stores nothing, set `CAPA_ADMIN_URL` to the API host your Capa admin uses;
1169
1170
  it wins over `CAPA_API_URL`. When a host stores nothing, the command says
@@ -1619,6 +1620,25 @@ The mark does not survive a spread copy or being passed to a client component,
1619
1620
  so tag in the server component that read the entry. `capaAttrs(entry, field,
1620
1621
  true)` still forces the tags on and `false` forces them off.
1621
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
+
1622
1642
  **When the entry crosses to the browser as data, pass the flag.** The mark is
1623
1643
  a hidden symbol, so anything that serializes the entry drops it silently: the
1624
1644
  Next Pages Router's `getServerSideProps`, SvelteKit and Remix loaders, Nuxt's
@@ -1821,7 +1841,7 @@ the same pages, headers and cache as before.
1821
1841
 
1822
1842
  // in the fetch helper, before the existing fetch, which stays as it is
1823
1843
  if (await isDraft()) {
1824
- return fetch(`https://api.capacms.com/v2/api/${endpoint}${query}`, {
1844
+ return fetch(`https://cdn.capacms.com/v2/api/${endpoint}${query}`, {
1825
1845
  headers: { "x-api-key": process.env.CAPA_DRAFT_KEY! },
1826
1846
  cache: "no-store",
1827
1847
  }).then(parse); // the helper's existing parse
@@ -1835,7 +1855,7 @@ the same pages, headers and cache as before.
1835
1855
 
1836
1856
  2. **Add the preview and exit routes** with `createPreviewRoute({ draftMode,
1837
1857
  cookies })` and `exitPreviewRoute({ draftMode, cookies })`, as in the Quick
1838
- 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
1839
1859
  the production key the site already reads with, server-only: the routes
1840
1860
  check the editor's token with it.
1841
1861
 
@@ -2013,6 +2033,227 @@ only for the admin that said hello. Rich text, media and relations wait for
2013
2033
  the save, as before. An admin sends patches only when its project has live
2014
2034
  preview on.
2015
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
+
2016
2257
  ## Not yet
2017
2258
 
2018
2259
  `--select-from-depth`, `capa convert-url`, GraphQL mutations, and `/api/`
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * capa-check-bundle — fail when a Capa server write key (capw_) is in the
4
+ * files a browser downloads.
5
+ *
6
+ * capa-check-bundle scans .next (and out, if there is one) in the current directory
7
+ * capa-check-bundle <dir>... scans each directory given (.next, build, dist, out)
8
+ *
9
+ * THE REQUIRED STEP for a Next.js site that holds a write key. Run it after the
10
+ * build, in the same script, so a key that would reach a browser fails the
11
+ * deploy:
12
+ *
13
+ * "build": "next build && capa-check-bundle"
14
+ *
15
+ * For a Next build directory (`.next`, or whatever `distDir` names) it scans
16
+ * what a browser downloads: every file under `static/`, and the pages
17
+ * prerendering wrote under `server/` (HTML, RSC payloads, static route
18
+ * bodies, `getStaticProps` data). A key passed from a server component to a
19
+ * client component's props lands there, on a static page, and nowhere in
20
+ * `static/`. `withCapaWriteKeyGuard` runs inside `next build` before
21
+ * prerendering, so it cannot see those files; this bin can. Any other
22
+ * directory (`out`, a Vite `dist`) is scanned whole.
23
+ *
24
+ * Exit 0 when no key is found, 1 with each file and line when one is, 2 when a
25
+ * directory given does not exist. Only a match whose checksum is right counts
26
+ * as a key; a value merely shaped like one is printed as a warning and exits
27
+ * 0. A key is printed as its first 12 characters only.
28
+ */
29
+ const fs = require("node:fs");
30
+ const path = require("node:path");
31
+ const {
32
+ isNextBuildDir,
33
+ scanForWriteKeys,
34
+ scanNextBuildForWriteKeys,
35
+ splitFindings,
36
+ writeKeyReport,
37
+ writeKeyShapeWarning,
38
+ } = require("../dist/nextjs/write-key-guard.js");
39
+
40
+ const USAGE = "usage: capa-check-bundle [dir ...] (default: .next, and out when it exists)";
41
+
42
+ function main(argv) {
43
+ if (argv.includes("--help") || argv.includes("-h")) {
44
+ console.log(USAGE);
45
+ return 0;
46
+ }
47
+ const unknown = argv.find((arg) => arg.startsWith("-"));
48
+ if (unknown) {
49
+ console.error(`capa-check-bundle: unknown option ${unknown}\n${USAGE}`);
50
+ return 2;
51
+ }
52
+ const explicit = argv.length > 0;
53
+ const dirs = explicit ? argv : [".next", ...(fs.existsSync("out") ? ["out"] : [])];
54
+ let found = 0;
55
+ const scanned = [];
56
+ for (const dir of dirs) {
57
+ if (!fs.existsSync(dir)) {
58
+ console.error(
59
+ explicit
60
+ ? `capa-check-bundle: ${dir} does not exist.`
61
+ : "capa-check-bundle: .next does not exist. Run it after next build, from the app's directory, or name the directory to scan.",
62
+ );
63
+ return 2;
64
+ }
65
+ const label = dir.replace(/[\\/]+$/, "");
66
+ const build = isNextBuildDir(dir);
67
+ const { keys, shaped } = splitFindings(build ? scanNextBuildForWriteKeys(dir) : scanForWriteKeys(dir));
68
+ scanned.push(build ? `${label} (static files and prerendered pages)` : label);
69
+ if (shaped.length > 0) console.error(writeKeyShapeWarning(shaped, label));
70
+ if (keys.length > 0) {
71
+ found += keys.length;
72
+ console.error(writeKeyReport(keys, label));
73
+ }
74
+ }
75
+ if (found > 0) return 1;
76
+ console.log(`capa-check-bundle: no Capa write key in ${scanned.join(", ")}.`);
77
+ return 0;
78
+ }
79
+
80
+ process.exitCode = main(process.argv.slice(2));
package/bin/capa.js CHANGED
@@ -15,10 +15,10 @@
15
15
  * literal is sent as written, so its own text is stored too, as
16
16
  * `<Name> (literal)`.
17
17
  *
18
- * CAPA_API_URL=https://api.capacms.com CAPA_DRAFT_KEY=cap_test_... capa persist [--documents src] [--manifest persisted.json]
18
+ * CAPA_API_URL=https://cdn.capacms.com CAPA_DRAFT_KEY=cap_test_... capa persist [--documents src] [--manifest persisted.json]
19
19
  *
20
20
  * Two things must hold for a document to be stored (spec 17, amendment 28).
21
- * The POST reaches the host that stores documents: api.capacms.com sends
21
+ * The POST reaches the host that stores documents: cdn.capacms.com sends
22
22
  * every POST there, and a self-hosted stack whose read host stores nothing
23
23
  * names the other host in CAPA_ADMIN_URL, which wins over CAPA_API_URL. And
24
24
  * the key is a development key, since a production key ships in site
@@ -177,7 +177,7 @@ async function persist() {
177
177
  if (declined === rows.length && rows.length) {
178
178
  console.error(
179
179
  `capa persist: ${api.baseUrl} stored nothing. A host that serves reads only runs documents but never stores one: ` +
180
- "set CAPA_ADMIN_URL to the API host your Capa admin uses (https://api.capacms.com sends every POST there), " +
180
+ "set CAPA_ADMIN_URL to the API host your Capa admin uses (https://cdn.capacms.com sends every POST there), " +
181
181
  `and make ${api.keyName} a development key.`,
182
182
  );
183
183
  }
@@ -56,7 +56,7 @@ function firstSet(env, names) {
56
56
  * Capa tool reads, with `CAPA_BASE_URL` and `CAPA_API_KEY` as aliases.
57
57
  *
58
58
  * With `admin` (for `capa persist`): the host is `CAPA_ADMIN_URL` when it is
59
- * set, else `CAPA_API_URL`. `https://api.capacms.com` sends every POST to the
59
+ * set, else `CAPA_API_URL`. `https://cdn.capacms.com` sends every POST to the
60
60
  * host that stores persisted documents, so a site's own URL registers them; a
61
61
  * self-hosted stack whose read host stores nothing names its admin host in
62
62
  * `CAPA_ADMIN_URL`. The key is the development key, `CAPA_DRAFT_KEY` as
@@ -1,5 +1,8 @@
1
- export { acceptMessage, hoverMessage, normaliseOrigins, patchedText, pickCentred, readyMessage, scrollEdge, selectMessage, textAround, visibleMessage, ADMIN_SOURCE, PATCH_MAX_FIELDS, PATCH_MAX_LENGTH, PROTOCOL_VERSION, SITE_FEATURES, SITE_SOURCE, } from "./protocol.js";
1
+ export { acceptMessage, hoverMessage, isItemPath, itemLabel, itemMatches, normaliseOrigins, patchedText, pickCentred, readyMessage, scrollEdge, selectMessage, textAround, visibleMessage, ADMIN_SOURCE, PATCH_MAX_FIELDS, PATCH_MAX_LENGTH, PROTOCOL_VERSION, SITE_FEATURES, SITE_SOURCE, } from "./protocol.js";
2
2
  export type { AdminMessage, MessageLike, PatchField, SiteMessage, TaggedBox } from "./protocol.js";
3
+ export { acceptLiveFields, canonicalHtml, findDateFormat, formatDateAs, parseHtml, preparedHtml, richTextHtml, safeHref, safeImageUrl, sanitizeHtml, swapDatetime, swapImageUrl, FIELDS_MAX_FIELDS, FIELDS_MAX_LENGTH, } from "./live-fields.js";
4
+ export { renderMarkdown } from "./markdown.js";
5
+ export type { HtmlElement, HtmlNode, LiveField, LiveImage, LiveKind } from "./live-fields.js";
3
6
  export interface OverlayOptions {
4
7
  /**
5
8
  * The Capa admin origins allowed to drive this page, for example