@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
@@ -1,23 +1,33 @@
1
1
  /**
2
2
  * The live preview protocol, site side. Pure: no DOM, no globals, so it can be
3
- * tested under plain `node --test`.
3
+ * tested under plain `node --test`. Its one import, `./live-fields.js`, is
4
+ * pure too.
4
5
  *
5
6
  * The Capa admin frames the site and the two talk over `postMessage`. Every
6
7
  * message is a plain object `{ source, v: 1, type, ...fields }`:
7
8
  *
8
9
  * admin -> site (source "capa-admin")
9
10
  * hello {} sent on the frame's load
10
- * highlight { entryId, field: string | null } entryId "" clears
11
+ * highlight { entryId, field: string | null, item? }
12
+ * entryId "" clears. `item`: one item
13
+ * of a list field (`data-capa-item`)
11
14
  * outline { on: boolean } outline every tagged element
12
15
  * refresh {} re-render the draft
13
16
  * patch { entryId, fields: [{ field, value, saved }] }
14
17
  * unsaved text, as the editor types it
18
+ * fields { entryId, fields: [{ field, kind, value, saved }] }
19
+ * unsaved HTML and Rich Text, images,
20
+ * toggles and dates (`./live-fields.ts`).
21
+ * Sent only to an overlay whose ready
22
+ * lists "fields". A kind it does not
23
+ * know is skipped, the rest kept
15
24
  *
16
25
  * site -> admin (source "capa")
17
26
  * ready { path, entries, features } after hello, and after every navigation.
18
27
  * `features`: what this overlay can do
19
28
  * beyond v1 (`SITE_FEATURES`)
20
- * select { entryId, field } a tagged element was clicked
29
+ * select { entryId, field, item? } a tagged element was clicked. `item`:
30
+ * its `data-capa-item`, when it has one
21
31
  * hover { entryId, field } | { entryId: "", field: null }
22
32
  * visible { entryId, field } the tagged element at the centre of the
23
33
  * viewport changed (throttled, on scroll)
@@ -29,6 +39,15 @@
29
39
  * same kind of addition: an admin sends `patch` only to an overlay whose
30
40
  * `ready` lists "patch", and an older admin never reads `features`.
31
41
  *
42
+ * `item` is the same kind of addition, on two messages v1 already has. The
43
+ * site tags one item of a list (`capaAttrs(entry, "faqs", { item: 2 })`), a
44
+ * click reports it, and the editor opens that item rather than the top of
45
+ * the list. The editor sends it with a highlight only where the project has
46
+ * it on (`CAPA_PREVIEW_TARGETS`), and an overlay that does not read it
47
+ * outlines the whole field, as before. An item that is not a well-formed
48
+ * path (`isItemPath`) is dropped and the message kept: the field is still
49
+ * right.
50
+ *
32
51
  * A PATCH IS TEXT ONLY, and only where the page shows the field verbatim. The
33
52
  * overlay changes a tagged element's text while it reads exactly `saved` (the
34
53
  * value the page was rendered from) or what this page last patched it to, so
@@ -38,14 +57,29 @@
38
57
  * The admin keeps its own copy of these shapes (`apps/admin`, no dependency on
39
58
  * this package). If you change one side, change the other.
40
59
  */
60
+ import { acceptLiveFields } from "./live-fields.js";
41
61
  export const PROTOCOL_VERSION = 1;
42
62
  export const ADMIN_SOURCE = "capa-admin";
43
63
  export const SITE_SOURCE = "capa";
44
- /** What this overlay can do beyond v1, listed in its `ready`. */
45
- export const SITE_FEATURES = ["patch"];
64
+ /**
65
+ * What this overlay can do beyond v1, listed in its `ready`. `release`: this
66
+ * SDK sends a release preview's token on its reads (`Capa-Release`), so the
67
+ * admin can tell a site that shows a release from one that shows every draft.
68
+ */
69
+ export const SITE_FEATURES = ["patch", "fields", "release"];
46
70
  /** A `patch` past these is refused whole: no form has that many text fields, or that much text in one. */
47
71
  export const PATCH_MAX_FIELDS = 500;
48
72
  export const PATCH_MAX_LENGTH = 100_000;
73
+ /**
74
+ * One item of a list field, as `data-capa-item` spells it: up to 16 segments
75
+ * joined with dots, each a whole number or a key of letters, digits, `_` and
76
+ * `-` (`2`, `2.question`). `itemPath` in `@capacms/sdk/next` writes it.
77
+ */
78
+ const ITEM_PATH = /^[A-Za-z0-9_-]{1,64}(\.[A-Za-z0-9_-]{1,64}){0,15}$/;
79
+ /** Whether a value is an item path an overlay sends and an editor reads. */
80
+ export function isItemPath(value) {
81
+ return typeof value === "string" && value.length <= 1040 && ITEM_PATH.test(value);
82
+ }
49
83
  /**
50
84
  * `https://admin.example.com/` and `https://admin.example.com` are one origin,
51
85
  * and a configured value that is not a URL at all is dropped rather than
@@ -99,12 +133,17 @@ export function acceptMessage(event, allowedOrigins, parent) {
99
133
  if (typeof m.on !== "boolean")
100
134
  return null;
101
135
  return { source: ADMIN_SOURCE, v: 1, type: "outline", on: m.on };
102
- case "highlight":
136
+ case "highlight": {
103
137
  if (typeof m.entryId !== "string")
104
138
  return null;
105
139
  if (m.field !== null && typeof m.field !== "string")
106
140
  return null;
107
- return { source: ADMIN_SOURCE, v: 1, type: "highlight", entryId: m.entryId, field: m.field };
141
+ const highlight = { source: ADMIN_SOURCE, v: 1, type: "highlight", entryId: m.entryId, field: m.field };
142
+ // Optional: an item of the field, kept only when it is one (a clear has none).
143
+ if (m.entryId !== "" && m.field !== null && isItemPath(m.item))
144
+ highlight.item = m.item;
145
+ return highlight;
146
+ }
108
147
  case "patch": {
109
148
  if (typeof m.entryId !== "string" || m.entryId === "")
110
149
  return null;
@@ -125,6 +164,14 @@ export function acceptMessage(event, allowedOrigins, parent) {
125
164
  }
126
165
  return { source: ADMIN_SOURCE, v: 1, type: "patch", entryId: m.entryId, fields };
127
166
  }
167
+ case "fields": {
168
+ if (typeof m.entryId !== "string" || m.entryId === "")
169
+ return null;
170
+ const fields = acceptLiveFields(m.fields);
171
+ if (fields === null)
172
+ return null;
173
+ return { source: ADMIN_SOURCE, v: 1, type: "fields", entryId: m.entryId, fields };
174
+ }
128
175
  default:
129
176
  return null;
130
177
  }
@@ -162,8 +209,31 @@ export function readyMessage(path, entries, features) {
162
209
  ? { source: SITE_SOURCE, v: 1, type: "ready", path, entries, features: [...features] }
163
210
  : { source: SITE_SOURCE, v: 1, type: "ready", path, entries };
164
211
  }
165
- export function selectMessage(entryId, field) {
166
- return { source: SITE_SOURCE, v: 1, type: "select", entryId, field };
212
+ /** A click on a tagged element, with its list item when it names a well-formed one. */
213
+ export function selectMessage(entryId, field, item) {
214
+ return isItemPath(item)
215
+ ? { source: SITE_SOURCE, v: 1, type: "select", entryId, field, item }
216
+ : { source: SITE_SOURCE, v: 1, type: "select", entryId, field };
217
+ }
218
+ /**
219
+ * Whether an element's `data-capa-item` is the item asked for, or inside it:
220
+ * `2.question` is in item `2`. Pure, so the overlay's matching is tested
221
+ * without a DOM.
222
+ */
223
+ export function itemMatches(tagged, wanted) {
224
+ if (typeof tagged !== "string")
225
+ return false;
226
+ return tagged === wanted || tagged.startsWith(`${wanted}.`);
227
+ }
228
+ /**
229
+ * The label the overlay draws for an item: "faqs › item 3" for an index,
230
+ * which counts from one as an editor does, "faqs › question" for a key.
231
+ */
232
+ export function itemLabel(field, item) {
233
+ if (!isItemPath(item))
234
+ return field;
235
+ const parts = item.split(".").map((part) => (/^\d+$/.test(part) ? `item ${Number(part) + 1}` : part));
236
+ return `${field} › ${parts.join(" › ")}`;
167
237
  }
168
238
  export function hoverMessage(entryId, field) {
169
239
  return entryId === ""
@@ -26,14 +26,55 @@
26
26
  * Pass `enabled` to override: `true` tags an unmarked entry, `false` tags
27
27
  * nothing. Sites written before edit mode passed `isDraft` here and keep
28
28
  * working unchanged.
29
+ *
30
+ * ONE ITEM OF A LIST. `capaAttrs(entry, "faqs", { item: 2 })` tags the third
31
+ * item of the `faqs` list, so a click on it opens that item in the Capa
32
+ * editor rather than the top of the list field, and focusing the item in the
33
+ * editor outlines it on the page. `item` is the item's index, or a path of
34
+ * indexes and keys inside the field (`[2, "question"]`). It adds
35
+ * `data-capa-item`; an editor or an overlay that does not know it reads the
36
+ * element as the whole field, as before.
37
+ *
38
+ * A TOGGLE. `capaAttrs(entry, "show_banner", { shownWhen: true })` on the
39
+ * element the toggle shows lets live preview hide and show it as the editor
40
+ * flips the toggle, before the save.
29
41
  */
30
42
  export type CapaAttrs = {
31
43
  "data-capa-entry": string;
32
44
  "data-capa-field": string;
45
+ "data-capa-item"?: string;
46
+ "data-capa-shown-when"?: "true" | "false";
33
47
  } | {
34
48
  "data-capa-entry"?: undefined;
35
49
  "data-capa-field"?: undefined;
50
+ "data-capa-item"?: undefined;
51
+ "data-capa-shown-when"?: undefined;
36
52
  };
53
+ /** One item of a list field: its index, or a path of indexes and keys inside the field. */
54
+ export type CapaItem = number | string | readonly (number | string)[];
55
+ /** `capaAttrs`'s third argument, as an object. */
56
+ export interface CapaAttrsOptions {
57
+ /** Tag one item of a list field: `{ item: 2 }` is the third. */
58
+ item?: CapaItem;
59
+ /** Override edit mode, as a boolean third argument does. */
60
+ enabled?: boolean;
61
+ /**
62
+ * For an element a toggle shows: the value it is shown for. While an editor
63
+ * changes the toggle, the overlay hides the element when the unsaved value
64
+ * is not this and shows it when it is, before the save. Render the element
65
+ * with `hidden` rather than leaving it out when the saved value hides it,
66
+ * and turning the toggle on shows it at once.
67
+ */
68
+ shownWhen?: boolean;
69
+ }
70
+ /** The most segments an item path may have. Deeper than any form nests. */
71
+ export declare const ITEM_MAX_DEPTH = 16;
72
+ /**
73
+ * An item as `data-capa-item` spells it: segments joined with dots, each a
74
+ * non-negative whole number or a key of letters, digits, `_` and `-`. Null
75
+ * for anything else, and the element is then tagged as the whole field.
76
+ */
77
+ export declare function itemPath(item: CapaItem | undefined | null): string | null;
37
78
  /** `Symbol.for`, so two copies of the SDK in one bundle agree on the mark. */
38
79
  export declare const CAPA_EDIT: unique symbol;
39
80
  /** Whether an entry was read in edit mode. */
@@ -70,7 +111,7 @@ export type TaggableField<E> = unknown extends FieldsOf<E> ? E extends {
70
111
  type FieldsOf<E> = "fields" extends keyof E ? E["fields" & keyof E] : unknown;
71
112
  export declare function capaAttrs<E extends {
72
113
  id: string;
73
- }>(entry: E, field: TaggableField<E>, enabled?: boolean): CapaAttrs;
114
+ }>(entry: E, field: TaggableField<E>, options?: boolean | CapaAttrsOptions): CapaAttrs;
74
115
  /**
75
116
  * The attributes for every field of `T`, one `CapaAttrs` per field name.
76
117
  * `capa-codegen` writes `<Model>Attrs = FieldAttrs<Model>` beside each
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CAPA_EDIT = void 0;
3
+ exports.CAPA_EDIT = exports.ITEM_MAX_DEPTH = void 0;
4
+ exports.itemPath = itemPath;
4
5
  exports.isEditEntry = isEditEntry;
5
6
  exports.markEditEntries = markEditEntries;
6
7
  exports.markGraphQLEntries = markGraphQLEntries;
@@ -8,6 +9,36 @@ exports.hasGraphQLEntry = hasGraphQLEntry;
8
9
  exports.carryEditMark = carryEditMark;
9
10
  exports.capaAttrs = capaAttrs;
10
11
  exports.fieldAttrs = fieldAttrs;
12
+ /** The most segments an item path may have. Deeper than any form nests. */
13
+ exports.ITEM_MAX_DEPTH = 16;
14
+ const ITEM_KEY = /^[A-Za-z0-9_-]{1,64}$/;
15
+ /**
16
+ * An item as `data-capa-item` spells it: segments joined with dots, each a
17
+ * non-negative whole number or a key of letters, digits, `_` and `-`. Null
18
+ * for anything else, and the element is then tagged as the whole field.
19
+ */
20
+ function itemPath(item) {
21
+ if (item === undefined || item === null)
22
+ return null;
23
+ const parts = Array.isArray(item) ? item : [item];
24
+ if (parts.length === 0 || parts.length > exports.ITEM_MAX_DEPTH)
25
+ return null;
26
+ const out = [];
27
+ for (const part of parts) {
28
+ if (typeof part === "number") {
29
+ if (!Number.isSafeInteger(part) || part < 0)
30
+ return null;
31
+ out.push(String(part));
32
+ }
33
+ else if (typeof part === "string" && ITEM_KEY.test(part)) {
34
+ out.push(part);
35
+ }
36
+ else {
37
+ return null;
38
+ }
39
+ }
40
+ return out.join(".");
41
+ }
11
42
  /** `Symbol.for`, so two copies of the SDK in one bundle agree on the mark. */
12
43
  exports.CAPA_EDIT = Symbol.for("capacms.edit");
13
44
  /** Whether an entry was read in edit mode. */
@@ -100,10 +131,18 @@ function namespaceOf(entry, field) {
100
131
  const namespaces = entry[CAPA_EDIT_NAMESPACES];
101
132
  return namespaces?.[field] ?? field;
102
133
  }
103
- function capaAttrs(entry, field, enabled = isEditEntry(entry)) {
134
+ function capaAttrs(entry, field, options = isEditEntry(entry)) {
135
+ const enabled = typeof options === "boolean" ? options : (options.enabled ?? isEditEntry(entry));
104
136
  if (!enabled)
105
137
  return {};
106
- return { "data-capa-entry": entry.id, "data-capa-field": namespaceOf(entry, field) };
138
+ const attrs = { "data-capa-entry": entry.id, "data-capa-field": namespaceOf(entry, field) };
139
+ const item = typeof options === "boolean" ? null : itemPath(options.item);
140
+ if (item !== null)
141
+ attrs["data-capa-item"] = item;
142
+ if (typeof options !== "boolean" && typeof options.shownWhen === "boolean") {
143
+ attrs["data-capa-shown-when"] = options.shownWhen ? "true" : "false";
144
+ }
145
+ return attrs;
107
146
  }
108
147
  /**
109
148
  * Typed attributes for every field of one entry (M5), or of one GraphQL node:
@@ -63,6 +63,25 @@ export interface CapaNextConfig {
63
63
  * Capa lists every real URL an entry appears on. Usually set per call.
64
64
  */
65
65
  path?: string;
66
+ /**
67
+ * A draft link's token (`cap_draft_...`), sent as `Capa-Draft-Link` on every
68
+ * REST and GraphQL read. With a development key, Capa then serves that one
69
+ * entry's draft and every other entry as published, and stops serving the
70
+ * draft as soon as the link is revoked or expires. A production key ignores
71
+ * it. `@capacms/sdk/nextjs` sets it from the cookie `createPreviewRoute`
72
+ * keeps; set it yourself only for a client you build by hand.
73
+ */
74
+ draftLink?: string;
75
+ /**
76
+ * A release preview token (the `capa-release` cookie `createPreviewRoute`
77
+ * sets from a release preview link), sent as `Capa-Release`. With a
78
+ * development key, reads then serve what is live plus the releases the
79
+ * token names, and no other draft. A production key's reads ignore it.
80
+ * `@capacms/sdk/nextjs` sets it for you under draft mode (`getCapaClient`,
81
+ * `graphql`, and `draftClient` given `cookies`); `releaseToken` reads it
82
+ * for a client you build yourself.
83
+ */
84
+ release?: string;
66
85
  /** Injected for tests, non-standard runtimes, and framework fetch wrappers. */
67
86
  fetch?: typeof fetch;
68
87
  }
@@ -89,6 +108,17 @@ export interface CallOptions {
89
108
  */
90
109
  path?: string;
91
110
  }
111
+ /** What `preview()` takes beside the call options. */
112
+ export interface PreviewOptions extends CallOptions {
113
+ /**
114
+ * True only from a preview route that keeps a draft link's token and sends
115
+ * it as `draftLink` on its reads, and never turns draft mode on for one, as
116
+ * `createPreviewRoute` given `cookies` does. Sent as `Capa-Draft-Links:
117
+ * narrow`. Without it Capa answers a draft link as an invalid token, so a
118
+ * route that would turn the whole site's draft mode on never opens one.
119
+ */
120
+ draftLinks?: boolean;
121
+ }
92
122
  /**
93
123
  * One entry as `/api/entries` returns it: the system keys, and `fields`. A read
94
124
  * types `fields` from its model and select (`EntryFields`), so a relation is a
@@ -335,6 +365,12 @@ export interface PagesResource {
335
365
  }
336
366
  /** What `GET /api/preview` says a preview token names. */
337
367
  export interface PreviewClaim {
368
+ /**
369
+ * `"release"` for a release preview link, which names releases rather than
370
+ * one entry: `entryId` and `modelId` are then `""` and `namespace` null.
371
+ * Absent for one entry's preview, as before releases.
372
+ */
373
+ kind?: "entry" | "release";
338
374
  entryId: string;
339
375
  modelId: string;
340
376
  /** Null when the model has since lost its route. */
@@ -342,6 +378,17 @@ export interface PreviewClaim {
342
378
  /** Null when the path can no longer be resolved. Falls back to your routing. */
343
379
  path: string | null;
344
380
  expiresAt: string;
381
+ /**
382
+ * True for a draft link, answered only to a `preview()` call given
383
+ * `draftLinks: true`. Keep its token and send it as `draftLink`; do not turn
384
+ * draft mode on for it.
385
+ */
386
+ draftLink?: true;
387
+ /** A release preview's releases, lowest first: the later one wins where two name an entry. */
388
+ releases?: Array<{
389
+ id: string;
390
+ name: string;
391
+ }>;
345
392
  }
346
393
  /**
347
394
  * `client.graphql`: run a document, or build one from a typed selection with
@@ -404,7 +451,7 @@ export interface CapaNextClient<Q = UntypedQuery, O extends GraphQLCallOptions =
404
451
  * Takes any key the site holds, a legacy `pk_`, `sk_` or unprefixed key
405
452
  * included: Capa answers a token minted for another tenant as invalid.
406
453
  */
407
- preview(token: string, options?: CallOptions): Promise<PreviewClaim | null>;
454
+ preview(token: string, options?: PreviewOptions): Promise<PreviewClaim | null>;
408
455
  me<T = Record<string, unknown>>(options?: CallOptions): Promise<T>;
409
456
  versions<T = Record<string, unknown>>(options?: CallOptions): Promise<T>;
410
457
  graphql: GraphQLClient<Q, O>;
@@ -89,6 +89,11 @@ function resolveNextConfig(config) {
89
89
  // should surface while somebody is still writing the code. A checksum that
90
90
  // is silently dropped is a `drift` insight that never appears, which looks
91
91
  // exactly like a site that is up to date.
92
+ // The same rule: a draft link that is not a string would be sent as one,
93
+ // and serve no draft at all.
94
+ if (value.draftLink !== undefined && (typeof value.draftLink !== "string" || value.draftLink.trim() === "")) {
95
+ throw new TypeError(`@capacms/sdk/next: draftLink must be a draft link's token. Got ${JSON.stringify(value.draftLink)}.`);
96
+ }
92
97
  if (value.schemaChecksum !== undefined && value.schemaChecksum !== null) {
93
98
  if (typeof value.schemaChecksum !== "string" || !SCHEMA_CHECKSUM.test(value.schemaChecksum)) {
94
99
  throw new TypeError(`@capacms/sdk/next: schemaChecksum must be the hex checksum from your generated types, for example CAPA_SCHEMA_CHECKSUM. Got ${JSON.stringify(value.schemaChecksum)}.`);
@@ -338,7 +343,7 @@ function cacheTags(response) {
338
343
  return value.split(/\s+/).filter(Boolean);
339
344
  }
340
345
  function createRequester(config) {
341
- return async function request(path, query = new URLSearchParams(), signal, page, pagePath) {
346
+ return async function request(path, query = new URLSearchParams(), signal, page, pagePath, extra) {
342
347
  const url = new URL(config.baseUrl + path);
343
348
  query.forEach((value, key) => url.searchParams.append(key, value));
344
349
  const headers = {
@@ -359,6 +364,16 @@ function createRequester(config) {
359
364
  // still reports which schema it was generated from.
360
365
  if (config.schemaChecksum !== undefined)
361
366
  headers["Capa-Schema"] = config.schemaChecksum;
367
+ // A draft-link visit: Capa serves the linked entry's draft and nothing
368
+ // else. Absent unless set, so every other client's requests are unchanged.
369
+ if (config.draftLink !== undefined)
370
+ headers["Capa-Draft-Link"] = config.draftLink;
371
+ // A release preview (`release`): absent unless set, so every other client
372
+ // sends the requests it always sent.
373
+ if (config.release)
374
+ headers["Capa-Release"] = config.release;
375
+ if (extra)
376
+ Object.assign(headers, extra);
362
377
  const response = await config.fetchImpl(url.toString(), { method: "GET", headers, signal });
363
378
  const requestId = response.headers?.get?.("X-Request-Id") ?? "";
364
379
  const text = await response.text();
@@ -506,7 +521,23 @@ function createClient(config) {
506
521
  const query = new URLSearchParams();
507
522
  query.set("token", token);
508
523
  try {
509
- return (await request("/api/preview", query, options.signal)).body.data;
524
+ const claim = (await request("/api/preview", query, options.signal, undefined, undefined,
525
+ // Only a caller that narrows a draft link opens one (PreviewOptions).
526
+ options.draftLinks === true ? { "Capa-Draft-Links": "narrow" } : undefined)).body.data;
527
+ // A release preview names releases, not an entry: the entry keys are
528
+ // filled so a site that reads them reads a string, never undefined.
529
+ if (claim?.kind === "release") {
530
+ return {
531
+ kind: "release",
532
+ entryId: "",
533
+ modelId: "",
534
+ namespace: null,
535
+ path: claim.path ?? null,
536
+ expiresAt: claim.expiresAt,
537
+ releases: Array.isArray(claim.releases) ? claim.releases : [],
538
+ };
539
+ }
540
+ return claim;
510
541
  }
511
542
  catch (error) {
512
543
  // Invalid and expired both mean "do not enable draft mode", and a
@@ -202,6 +202,10 @@ export interface GraphQLTransport {
202
202
  version: string;
203
203
  contract?: number;
204
204
  schemaChecksum?: string;
205
+ /** A draft link's token, sent as `Capa-Draft-Link` (`CapaNextConfig.draftLink`). */
206
+ draftLink?: string;
207
+ /** A release preview token, sent as `Capa-Release` (`CapaNextConfig.release`). */
208
+ release?: string;
205
209
  fetchImpl: typeof fetch;
206
210
  }
207
211
  interface Payload {
@@ -84,6 +84,10 @@ function headersFor(transport, withBody) {
84
84
  headers["Capa-Contract"] = String(transport.contract);
85
85
  if (transport.schemaChecksum !== undefined)
86
86
  headers["Capa-Schema"] = transport.schemaChecksum;
87
+ if (transport.draftLink !== undefined)
88
+ headers["Capa-Draft-Link"] = transport.draftLink;
89
+ if (transport.release)
90
+ headers["Capa-Release"] = transport.release;
87
91
  return headers;
88
92
  }
89
93
  /** The GET form: every payload key as a query parameter, objects as JSON. */
@@ -1,5 +1,5 @@
1
1
  export { CapaError, createClient, isCapaError, LAYOUT_PAGE, resolveNextConfig, serializeSelect, } from "./client";
2
- export { CAPA_EDIT, capaAttrs, fieldAttrs, isEditEntry, markEditEntries, markGraphQLEntries } from "./attrs";
2
+ export { CAPA_EDIT, capaAttrs, fieldAttrs, isEditEntry, itemPath, ITEM_MAX_DEPTH, markEditEntries, markGraphQLEntries } from "./attrs";
3
3
  export { inflate } from "./inflate";
4
4
  export { isCapaGraphQLError } from "./errors";
5
5
  export type { CapaGraphQLError, GraphQLErrorItem } from "./errors";
@@ -25,6 +25,6 @@ export { selectionToDocument } from "./graphql/typed";
25
25
  export type { ArgsInput, CapaField, Exact, ExactSelection, NodeOf, QueryResult, QuerySelection, RuntimeSelection, Selection, SelectionError, SelectionResult, TreeLayout, treeLayout, UntypedQuery, } from "./graphql/typed";
26
26
  export type { FlatResponse, Inflated } from "./inflate";
27
27
  export type { EntryFields, EntryMedia, EntryReference, FlatFields, IncludedFields, MediaCrop, MediaFocalPoint, MissingEntry, RelationItems, } from "./entry-fields";
28
- export type { CapaAttrs, FieldAttrs, TaggableField } from "./attrs";
29
- export type { BuilderCallOptions, CallOptions, CapaNextClient, CapaNextConfig, EntriesResource, Entry, GraphQLClient, Filter, FilterOperator, FlatGetOptions, FlatListOptions, FlatPage, FlatSingle, Included, FilterScalar, FilterValue, GetOptions, ListOptions, Page, PageDetail, PageInfo, PageSummary, PagesListOptions, PagesResource, PreviewClaim, ResponseMeta, ResponseShape, Single, } from "./client";
28
+ export type { CapaAttrs, CapaAttrsOptions, CapaItem, FieldAttrs, TaggableField } from "./attrs";
29
+ export type { BuilderCallOptions, CallOptions, CapaNextClient, CapaNextConfig, EntriesResource, Entry, GraphQLClient, Filter, FilterOperator, FlatGetOptions, FlatListOptions, FlatPage, FlatSingle, Included, FilterScalar, FilterValue, GetOptions, ListOptions, Page, PageDetail, PageInfo, PageSummary, PagesListOptions, PagesResource, PreviewClaim, PreviewOptions, ResponseMeta, ResponseShape, Single, } from "./client";
30
30
  export type { ExpandedTargets, CapaRelation, CapaRelationList, RelationSelectOptions, Select, SelectItem, SelectSort, SortableSystemKey, SystemKey, } from "./select-types";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.selectionToDocument = exports.toTree = exports.selectToSelection = exports.graphqlToSelect = exports.selectToGraphQL = exports.buildGraphQLQuery = exports.CapaBuildError = exports.summarizeIntrospection = exports.gql = exports.PERSISTED_QUERY_NOT_FOUND = exports.INTROSPECTION_QUERY = exports.isCapaGraphQLError = exports.inflate = exports.markGraphQLEntries = exports.markEditEntries = exports.isEditEntry = exports.fieldAttrs = exports.capaAttrs = exports.CAPA_EDIT = exports.serializeSelect = exports.resolveNextConfig = exports.LAYOUT_PAGE = exports.isCapaError = exports.createClient = exports.CapaError = void 0;
3
+ exports.selectionToDocument = exports.toTree = exports.selectToSelection = exports.graphqlToSelect = exports.selectToGraphQL = exports.buildGraphQLQuery = exports.CapaBuildError = exports.summarizeIntrospection = exports.gql = exports.PERSISTED_QUERY_NOT_FOUND = exports.INTROSPECTION_QUERY = exports.isCapaGraphQLError = exports.inflate = exports.markGraphQLEntries = exports.markEditEntries = exports.ITEM_MAX_DEPTH = exports.itemPath = exports.isEditEntry = exports.fieldAttrs = exports.capaAttrs = exports.CAPA_EDIT = exports.serializeSelect = exports.resolveNextConfig = exports.LAYOUT_PAGE = exports.isCapaError = exports.createClient = exports.CapaError = void 0;
4
4
  var client_1 = require("./client");
5
5
  Object.defineProperty(exports, "CapaError", { enumerable: true, get: function () { return client_1.CapaError; } });
6
6
  Object.defineProperty(exports, "createClient", { enumerable: true, get: function () { return client_1.createClient; } });
@@ -13,6 +13,8 @@ Object.defineProperty(exports, "CAPA_EDIT", { enumerable: true, get: function ()
13
13
  Object.defineProperty(exports, "capaAttrs", { enumerable: true, get: function () { return attrs_1.capaAttrs; } });
14
14
  Object.defineProperty(exports, "fieldAttrs", { enumerable: true, get: function () { return attrs_1.fieldAttrs; } });
15
15
  Object.defineProperty(exports, "isEditEntry", { enumerable: true, get: function () { return attrs_1.isEditEntry; } });
16
+ Object.defineProperty(exports, "itemPath", { enumerable: true, get: function () { return attrs_1.itemPath; } });
17
+ Object.defineProperty(exports, "ITEM_MAX_DEPTH", { enumerable: true, get: function () { return attrs_1.ITEM_MAX_DEPTH; } });
16
18
  Object.defineProperty(exports, "markEditEntries", { enumerable: true, get: function () { return attrs_1.markEditEntries; } });
17
19
  Object.defineProperty(exports, "markGraphQLEntries", { enumerable: true, get: function () { return attrs_1.markGraphQLEntries; } });
18
20
  var inflate_1 = require("./inflate");