@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
@@ -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. */
@@ -108,6 +108,12 @@ function relationList(schema, target, selection, value) {
108
108
  }
109
109
  return out;
110
110
  }
111
+ /**
112
+ * The keys REST adds after `height` where a project has them (an image's
113
+ * placeholders, its focal point and crop), in REST's order. The builder never
114
+ * selects them on its own; a selection that names them gets them back here.
115
+ */
116
+ const MEDIA_OPTIONAL_FIELDS = ["blurDataURL", "averageColor", "dominantColor", "palette", "blurhash", "focalPoint", "crop"];
111
117
  /** One media value with its keys in REST's order: `{ id, url, alt, type, width, height }`, as far as selected. */
112
118
  function mediaTree(value) {
113
119
  if (!isObject(value))
@@ -116,6 +122,9 @@ function mediaTree(value) {
116
122
  for (const key of plan_1.MEDIA_FIELDS)
117
123
  if (key in value)
118
124
  out[key] = value[key];
125
+ for (const key of MEDIA_OPTIONAL_FIELDS)
126
+ if (key in value)
127
+ out[key] = value[key];
119
128
  return out;
120
129
  }
121
130
  /** A relation GraphQL types as an id holds one when it is a non-empty string, as REST reads a stored reference. */
@@ -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";
@@ -24,7 +24,7 @@ export type { CapaTreeLayout, TreeLayoutField, TreeLayoutModel } from "./graphql
24
24
  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
- export type { EntryFields, EntryMedia, EntryReference, FlatFields, IncludedFields, 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";
27
+ export type { EntryFields, EntryMedia, EntryReference, FlatFields, IncludedFields, MediaCrop, MediaFocalPoint, MissingEntry, RelationItems, } from "./entry-fields";
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");
@@ -45,6 +45,8 @@ export declare function tagsFor(input: {
45
45
  }): string[];
46
46
  export interface WebhookPayload {
47
47
  type?: unknown;
48
+ /** The envelope's project, read for a release's events (`t:<tenantId>`). */
49
+ tenantId?: unknown;
48
50
  data?: {
49
51
  instanceId?: unknown;
50
52
  modelId?: unknown;
@@ -68,6 +70,15 @@ export interface WebhookPayload {
68
70
  * visibility changed, or the file went) revalidates the file's own key
69
71
  * (`f:<fileId>`, as REST's `Surrogate-Key` names it) and `MEDIA_TAG`, which
70
72
  * every read tagged by namespace carries, since it may show that file.
73
+ *
74
+ * A release (`release.published`, `release.rolled_back`) changed many
75
+ * entries in one transaction and names none of them, so everything goes:
76
+ * the project's tag (`t:<tenantId>`, from the envelope's `tenantId`),
77
+ * `GRAPHQL_TAG`, and `MEDIA_TAG`, which every read tagged by namespace
78
+ * carries. Each of its entries also sends its own event, which this handles
79
+ * as above, so a site subscribed to both refreshes either way. A release
80
+ * with a time range takes itself down at its end with `release.rolled_back`
81
+ * and `reason: "ended"`, which refreshes the same way, whatever the reason.
71
82
  */
72
83
  export declare function revalidateFromWebhook(input: {
73
84
  payload: WebhookPayload;
@@ -84,6 +95,12 @@ export declare function draftClient<Q = UntypedQuery>(input: {
84
95
  production: CapaNextConfig;
85
96
  draft: CapaNextConfig;
86
97
  isDraft: () => boolean | Promise<boolean>;
98
+ /**
99
+ * Next's `cookies`. Given, a release preview's token (the `capa-release`
100
+ * cookie) is sent with the draft client's reads, so the page shows what is
101
+ * live plus the release. Left out, the draft client reads every draft.
102
+ */
103
+ cookies?: CookiesFn;
87
104
  }): Promise<CapaNextClient<Q>>;
88
105
  export declare function routeOf(file: string): string;
89
106
  /**
@@ -106,6 +123,8 @@ export { gql, LAYOUT_PAGE };
106
123
  export type { PreviewClaim };
107
124
  export { capaImageLoader, createCapaImageLoader } from "./image-loader";
108
125
  export type { CapaImageLoader, CapaImageLoaderOptions, CapaImageLoaderProps } from "./image-loader";
126
+ export { assertNoWriteKeysInBuild, assertNoWriteKeysInBundle, CapaWriteKeyInBundleError, scanForWriteKeys, scanNextBuildForWriteKeys, withCapaWriteKeyGuard, } from "./write-key-guard";
127
+ export type { GuardableNextConfig, ScanOptions, WarnFn, WriteKeyFinding, WriteKeyGuardOptions } from "./write-key-guard";
109
128
  /**
110
129
  * The query parameter that turns edit mode on for one request without draft
111
130
  * content: `?capa-edit=<token>`, where the token is a Capa preview token. The
@@ -125,6 +144,14 @@ export declare const VIEW_PARAM = "capa-view";
125
144
  export declare const EDIT_HEADER = "x-capa-edit";
126
145
  /** The cookie Next's `draftMode().enable()` sets. */
127
146
  export declare const DRAFT_COOKIE = "__prerender_bypass";
147
+ /**
148
+ * The cookie `createPreviewRoute` keeps a draft link's token in. A draft link
149
+ * never turns draft mode on. A request that carries this cookie is a visit of
150
+ * the link: `getCapaClient` and `graphql()` read with the draft key and send
151
+ * the token as `Capa-Draft-Link`, and Capa serves the linked entry's draft
152
+ * and every other entry as published, until the link is revoked or expires.
153
+ */
154
+ export declare const DRAFT_LINK_COOKIE = "capa-draft-link";
128
155
  /** What every edit-mode response must send: never cached, never shared. */
129
156
  export declare const EDIT_CACHE_CONTROL = "private, no-store";
130
157
  interface HeaderReader {
@@ -151,6 +178,22 @@ export declare function editMode(input: {
151
178
  }>;
152
179
  headers: () => HeaderReader | Promise<HeaderReader>;
153
180
  }): Promise<boolean>;
181
+ /**
182
+ * The draft link this request is a visit of: the token `createPreviewRoute`
183
+ * kept in `DRAFT_LINK_COOKIE`, or null. `getCapaClient` and `graphql()` use
184
+ * it on their own. For a client you build yourself, outside draft mode:
185
+ *
186
+ * import { headers } from "next/headers";
187
+ * const link = await draftLinkToken({ headers });
188
+ * const client = link ? createClient({ ...draftConfig, draftLink: link }) : createClient(publishedConfig);
189
+ *
190
+ * With the draft key and `draftLink`, Capa serves the linked entry's draft
191
+ * and nothing else. Under draft mode the reads are the editor's, every draft,
192
+ * and this is not needed.
193
+ */
194
+ export declare function draftLinkToken(input: {
195
+ headers: () => HeaderReader | Promise<HeaderReader>;
196
+ }): Promise<string | null>;
154
197
  export interface EditRequest {
155
198
  /** True when the page must render in edit mode. */
156
199
  edit: boolean;
@@ -268,7 +311,9 @@ export interface NextGraphQLOptions extends NextCacheOptions {
268
311
  headers?: () => HeaderReader | Promise<HeaderReader>;
269
312
  /**
270
313
  * Read drafts with `CAPA_DRAFT_KEY`, uncached. Worked out from `draftMode`
271
- * when that is passed; set it to decide yourself.
314
+ * when that is passed; set it to decide yourself. Left out, outside draft
315
+ * mode, a request carrying a draft link (`DRAFT_LINK_COOKIE`, read through
316
+ * `headers`) reads the linked entry's draft and nothing else.
272
317
  */
273
318
  draft?: boolean;
274
319
  /** Overrides for the env-derived client (base URL, key, version, edit mode, fetch). Each one given is not read from env. */
@@ -338,6 +383,24 @@ export declare const CAPA_ADMIN_ORIGIN = "https://app.capacms.com";
338
383
  export declare const DRAFT_ROBOTS_TAG = "noindex, nofollow";
339
384
  /** How long the draft cookie lasts, in seconds: one hour, as a preview token does. */
340
385
  export declare const DRAFT_COOKIE_MAX_AGE = 3600;
386
+ /**
387
+ * The cookie a release preview's token lives in. `createPreviewRoute` sets it
388
+ * (partitioned, one hour, like the draft cookie) when the link names releases,
389
+ * and clears it on any other preview; `exitPreviewRoute` clears it. Read
390
+ * only under draft mode, and sent as `Capa-Release`.
391
+ */
392
+ export declare const RELEASE_COOKIE = "capa-release";
393
+ /**
394
+ * The release preview's token for this request, or undefined: under draft
395
+ * mode, the `capa-release` cookie. For a site that builds its own client:
396
+ *
397
+ * import { cookies, draftMode } from "next/headers";
398
+ * const client = createClient({ ..., release: await releaseToken({ cookies, draftMode }) });
399
+ */
400
+ export declare function releaseToken(input: {
401
+ cookies: CookiesFn;
402
+ draftMode: DraftModeFn;
403
+ }): Promise<string | undefined>;
341
404
  /**
342
405
  * `frame-ancestors 'self' <origins>`, the CSP directive that lets the Capa
343
406
  * editor frame a draft and nothing else frame it. Each origin is a scheme and
@@ -374,9 +437,10 @@ export interface NextHeaderRule {
374
437
  * import { capaHeaders } from "@capacms/sdk/nextjs";
375
438
  * export default { async headers() { return [...capaHeaders()]; } };
376
439
  *
377
- * A rule matches a request carrying the draft cookie, or a `capa-preview`,
378
- * `capa-edit` or `capa-view` query. A visitor's request carries none of
379
- * them, so its response, cached or not, is exactly what it was. Next checks
440
+ * A rule matches a request carrying the draft cookie or a draft link's
441
+ * cookie, or a `capa-preview`, `capa-edit` or `capa-view` query. A visitor's
442
+ * request carries none of them, so its response, cached or not, is exactly
443
+ * what it was. Next checks
380
444
  * the cookie by name, not by value, so a forged cookie only adds these
381
445
  * headers to the forger's own response.
382
446
  *
@@ -398,7 +462,7 @@ export interface DraftCookieJar {
398
462
  path: string;
399
463
  httpOnly: boolean;
400
464
  secure: boolean;
401
- sameSite: "none";
465
+ sameSite: "none" | "lax";
402
466
  partitioned: boolean;
403
467
  maxAge?: number;
404
468
  expires?: Date;
@@ -427,6 +491,14 @@ export declare function frameDraftCookie(cookies: CookiesFn, options?: {
427
491
  * `frameDraftCookie`, ends when the browser closes, as it always did.
428
492
  */
429
493
  export declare function clearDraftCookie(cookies: CookiesFn): Promise<void>;
494
+ /** Delete the release preview's cookie (`RELEASE_COOKIE`), partitioned as it was set. Nothing when there is none. */
495
+ export declare function clearReleaseCookie(cookies: CookiesFn): Promise<void>;
496
+ /**
497
+ * Delete the draft link's cookie `createPreviewRoute` kept, when the request
498
+ * carries one. `createPreviewRoute` calls it on any other answer and
499
+ * `exitPreviewRoute` on exit, given `cookies`.
500
+ */
501
+ export declare function clearDraftLinkCookie(cookies: CookiesFn): Promise<void>;
430
502
  /**
431
503
  * `app/api/capa/preview/route.ts`:
432
504
  *
@@ -440,7 +512,19 @@ export declare function clearDraftCookie(cookies: CookiesFn): Promise<void>;
440
512
  * its legacy key included (`getPublishedClient`, from `CAPA_KEY`).
441
513
  *
442
514
  * Given `cookies`, the draft cookie is re-set by `frameDraftCookie`: one hour,
443
- * and sent inside the editor's frame. With no `redirect`, the route answers
515
+ * and sent inside the editor's frame.
516
+ *
517
+ * A DRAFT LINK (Share draft in Capa) opens only given `cookies`, and never
518
+ * turns draft mode on. The route tells Capa it narrows (`preview()` with
519
+ * `draftLinks`), keeps the token in `DRAFT_LINK_COOKIE` until the link
520
+ * expires or `maxAge` seconds pass, whichever is first, turns off any draft
521
+ * mode the browser had, and lands on the linked page. `onEnable` does not run
522
+ * for it. That visit's reads through `getCapaClient` and `graphql()` show the
523
+ * linked entry's draft and every other entry as published, and stop showing
524
+ * the draft once the link is revoked or expires. Without `cookies`, Capa
525
+ * answers a draft link as an expired token.
526
+ *
527
+ * With no `redirect`, the route answers
444
528
  * with its own 307, marked `X-Robots-Tag: noindex, nofollow`,
445
529
  * `Referrer-Policy: no-referrer` (the token is in the URL),
446
530
  * `Cache-Control: private, no-store` and the editor's `frame-ancestors`.
@@ -468,7 +552,7 @@ export declare function createPreviewRoute(input: {
468
552
  * export const GET = exitPreviewRoute({ draftMode, cookies });
469
553
  *
470
554
  * Turns draft mode off and lands on `?path=`. Given `cookies`, the framed
471
- * cookie `createPreviewRoute` set is deleted too. With no `redirect`, the route
555
+ * cookie `createPreviewRoute` set is deleted too, and a draft link's cookie. With no `redirect`, the route
472
556
  * answers with its own 307, marked noindex and never cached.
473
557
  */
474
558
  export declare function exitPreviewRoute(input: {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DRAFT_COOKIE_MAX_AGE = exports.DRAFT_ROBOTS_TAG = exports.CAPA_ADMIN_ORIGIN = exports.DEFAULT_API_VERSION = exports.CAPA_ENV_ALIASES = exports.CAPA_ENV = exports.EDIT_CACHE_CONTROL = exports.DRAFT_COOKIE = exports.EDIT_HEADER = exports.VIEW_PARAM = exports.PREVIEW_PARAM = exports.EDIT_PARAM = exports.createCapaImageLoader = exports.capaImageLoader = exports.LAYOUT_PAGE = exports.gql = exports.MEDIA_TAG = exports.GRAPHQL_TAG = void 0;
3
+ exports.RELEASE_COOKIE = exports.DRAFT_COOKIE_MAX_AGE = exports.DRAFT_ROBOTS_TAG = exports.CAPA_ADMIN_ORIGIN = exports.DEFAULT_API_VERSION = exports.CAPA_ENV_ALIASES = exports.CAPA_ENV = exports.EDIT_CACHE_CONTROL = exports.DRAFT_LINK_COOKIE = exports.DRAFT_COOKIE = exports.EDIT_HEADER = exports.VIEW_PARAM = exports.PREVIEW_PARAM = exports.EDIT_PARAM = exports.withCapaWriteKeyGuard = exports.scanNextBuildForWriteKeys = exports.scanForWriteKeys = exports.CapaWriteKeyInBundleError = exports.assertNoWriteKeysInBundle = exports.assertNoWriteKeysInBuild = exports.createCapaImageLoader = exports.capaImageLoader = exports.LAYOUT_PAGE = exports.gql = exports.MEDIA_TAG = exports.GRAPHQL_TAG = void 0;
4
4
  exports.withCache = withCache;
5
5
  exports.modelTag = modelTag;
6
6
  exports.tagsFor = tagsFor;
@@ -10,16 +10,20 @@ exports.routeOf = routeOf;
10
10
  exports.preview = preview;
11
11
  exports.pagesFor = pagesFor;
12
12
  exports.editMode = editMode;
13
+ exports.draftLinkToken = draftLinkToken;
13
14
  exports.resolveEditRequest = resolveEditRequest;
14
15
  exports.getPublishedClient = getPublishedClient;
15
16
  exports.getCapaClient = getCapaClient;
16
17
  exports.graphql = graphql;
17
18
  exports.safeSitePath = safeSitePath;
19
+ exports.releaseToken = releaseToken;
18
20
  exports.frameAncestors = frameAncestors;
19
21
  exports.draftHeaders = draftHeaders;
20
22
  exports.capaHeaders = capaHeaders;
21
23
  exports.frameDraftCookie = frameDraftCookie;
22
24
  exports.clearDraftCookie = clearDraftCookie;
25
+ exports.clearReleaseCookie = clearReleaseCookie;
26
+ exports.clearDraftLinkCookie = clearDraftLinkCookie;
23
27
  exports.createPreviewRoute = createPreviewRoute;
24
28
  exports.exitPreviewRoute = exitPreviewRoute;
25
29
  exports.capaMiddleware = capaMiddleware;
@@ -104,6 +108,15 @@ function tagsFor(input) {
104
108
  * visibility changed, or the file went) revalidates the file's own key
105
109
  * (`f:<fileId>`, as REST's `Surrogate-Key` names it) and `MEDIA_TAG`, which
106
110
  * every read tagged by namespace carries, since it may show that file.
111
+ *
112
+ * A release (`release.published`, `release.rolled_back`) changed many
113
+ * entries in one transaction and names none of them, so everything goes:
114
+ * the project's tag (`t:<tenantId>`, from the envelope's `tenantId`),
115
+ * `GRAPHQL_TAG`, and `MEDIA_TAG`, which every read tagged by namespace
116
+ * carries. Each of its entries also sends its own event, which this handles
117
+ * as above, so a site subscribed to both refreshes either way. A release
118
+ * with a time range takes itself down at its end with `release.rolled_back`
119
+ * and `reason: "ended"`, which refreshes the same way, whatever the reason.
107
120
  */
108
121
  async function revalidateFromWebhook(input) {
109
122
  const data = input.payload?.data ?? input.payload;
@@ -116,7 +129,15 @@ async function revalidateFromWebhook(input) {
116
129
  const namespace = data?.modelNamespace ?? data?.namespace;
117
130
  if (typeof namespace === "string" && namespace)
118
131
  tags.push(modelTag(namespace));
119
- const media = typeof input.payload?.type === "string" && input.payload.type.startsWith("media.");
132
+ const type = typeof input.payload?.type === "string" ? input.payload.type : "";
133
+ if (type === "release.published" || type === "release.rolled_back") {
134
+ const tenantId = input.payload?.tenantId;
135
+ const all = [...(typeof tenantId === "string" && tenantId ? [`t:${tenantId}`] : []), exports.GRAPHQL_TAG, exports.MEDIA_TAG];
136
+ for (const tag of all)
137
+ await input.revalidateTag(tag);
138
+ return all;
139
+ }
140
+ const media = type.startsWith("media.");
120
141
  if (media) {
121
142
  if (typeof data?.fileId === "string" && data.fileId)
122
143
  tags.push(`f:${data.fileId}`);
@@ -140,7 +161,8 @@ async function draftClient(input) {
140
161
  if (!(await input.isDraft()))
141
162
  return (0, next_1.createClient)(input.production);
142
163
  (0, key_family_1.requireDraftKey)(input.draft?.apiKey, "the draft config");
143
- return (0, next_1.createClient)(input.draft);
164
+ const release = input.draft.release ?? (input.cookies ? (await input.cookies()).get(exports.RELEASE_COOKIE)?.value || undefined : undefined);
165
+ return (0, next_1.createClient)(release ? { ...input.draft, release } : input.draft);
144
166
  }
145
167
  // ------------------------------------------------------------------ pages ---
146
168
  /**
@@ -286,6 +308,14 @@ function pagesFor(client) {
286
308
  var image_loader_1 = require("./image-loader");
287
309
  Object.defineProperty(exports, "capaImageLoader", { enumerable: true, get: function () { return image_loader_1.capaImageLoader; } });
288
310
  Object.defineProperty(exports, "createCapaImageLoader", { enumerable: true, get: function () { return image_loader_1.createCapaImageLoader; } });
311
+ // Fail `next build` when a capw_ server write key is in a browser bundle.
312
+ var write_key_guard_1 = require("./write-key-guard");
313
+ Object.defineProperty(exports, "assertNoWriteKeysInBuild", { enumerable: true, get: function () { return write_key_guard_1.assertNoWriteKeysInBuild; } });
314
+ Object.defineProperty(exports, "assertNoWriteKeysInBundle", { enumerable: true, get: function () { return write_key_guard_1.assertNoWriteKeysInBundle; } });
315
+ Object.defineProperty(exports, "CapaWriteKeyInBundleError", { enumerable: true, get: function () { return write_key_guard_1.CapaWriteKeyInBundleError; } });
316
+ Object.defineProperty(exports, "scanForWriteKeys", { enumerable: true, get: function () { return write_key_guard_1.scanForWriteKeys; } });
317
+ Object.defineProperty(exports, "scanNextBuildForWriteKeys", { enumerable: true, get: function () { return write_key_guard_1.scanNextBuildForWriteKeys; } });
318
+ Object.defineProperty(exports, "withCapaWriteKeyGuard", { enumerable: true, get: function () { return write_key_guard_1.withCapaWriteKeyGuard; } });
289
319
  // -------------------------------------------------------------- edit mode ---
290
320
  /**
291
321
  * The query parameter that turns edit mode on for one request without draft
@@ -306,6 +336,23 @@ exports.VIEW_PARAM = "capa-view";
306
336
  exports.EDIT_HEADER = "x-capa-edit";
307
337
  /** The cookie Next's `draftMode().enable()` sets. */
308
338
  exports.DRAFT_COOKIE = "__prerender_bypass";
339
+ /**
340
+ * The cookie `createPreviewRoute` keeps a draft link's token in. A draft link
341
+ * never turns draft mode on. A request that carries this cookie is a visit of
342
+ * the link: `getCapaClient` and `graphql()` read with the draft key and send
343
+ * the token as `Capa-Draft-Link`, and Capa serves the linked entry's draft
344
+ * and every other entry as published, until the link is revoked or expires.
345
+ */
346
+ exports.DRAFT_LINK_COOKIE = "capa-draft-link";
347
+ /** What every draft link's token starts with. */
348
+ const DRAFT_LINK_PREFIX = "cap_draft_";
349
+ /**
350
+ * A draft link's token: the prefix and 32 random bytes, base64url. COPIED
351
+ * from `apps/api/src/draft-links/token.ts`, since this package has no runtime
352
+ * dependencies. A cookie of any other shape is no draft link, and the request
353
+ * reads published content.
354
+ */
355
+ const DRAFT_LINK_TOKEN = /^cap_draft_[A-Za-z0-9_-]{43}$/;
309
356
  /** What every edit-mode response must send: never cached, never shared. */
310
357
  exports.EDIT_CACHE_CONTROL = "private, no-store";
311
358
  /**
@@ -329,6 +376,40 @@ async function editMode(input) {
329
376
  function verifiedEdit(headers) {
330
377
  return headers.get(exports.EDIT_HEADER) === "1";
331
378
  }
379
+ /** One cookie's value from a `Cookie` header, or null. */
380
+ function cookieIn(header, name) {
381
+ for (const part of (header ?? "").split(/;\s*/)) {
382
+ const eq = part.indexOf("=");
383
+ if (eq > 0 && part.slice(0, eq).trim() === name)
384
+ return part.slice(eq + 1).trim();
385
+ }
386
+ return null;
387
+ }
388
+ /** The draft link `DRAFT_LINK_COOKIE` holds on this request, or null. */
389
+ function draftLinkIn(headers) {
390
+ const value = cookieIn(headers.get("cookie"), exports.DRAFT_LINK_COOKIE);
391
+ return value !== null && DRAFT_LINK_TOKEN.test(value) ? value : null;
392
+ }
393
+ /**
394
+ * The draft link this request is a visit of: the token `createPreviewRoute`
395
+ * kept in `DRAFT_LINK_COOKIE`, or null. `getCapaClient` and `graphql()` use
396
+ * it on their own. For a client you build yourself, outside draft mode:
397
+ *
398
+ * import { headers } from "next/headers";
399
+ * const link = await draftLinkToken({ headers });
400
+ * const client = link ? createClient({ ...draftConfig, draftLink: link }) : createClient(publishedConfig);
401
+ *
402
+ * With the draft key and `draftLink`, Capa serves the linked entry's draft
403
+ * and nothing else. Under draft mode the reads are the editor's, every draft,
404
+ * and this is not needed.
405
+ */
406
+ async function draftLinkToken(input) {
407
+ return draftLinkIn(await input.headers());
408
+ }
409
+ /** The settings with the draft link added, when there is one. */
410
+ function withDraftLink(settings, link) {
411
+ return link === null ? settings : { ...settings, draftLink: link };
412
+ }
332
413
  /**
333
414
  * The middleware half of edit mode.
334
415
  *
@@ -455,9 +536,15 @@ function getPublishedClient(overrides = {}) {
455
536
  async function getCapaClient(input) {
456
537
  const draft = (await input.draftMode()).isEnabled === true;
457
538
  const edit = await editMode({ draftMode: input.draftMode, headers: input.headers });
458
- const settings = modeConfig(input.config, draft);
539
+ // A draft-link visit (DRAFT_LINK_COOKIE): the draft key, sending the token,
540
+ // so Capa serves the linked entry's draft and nothing else. Never under
541
+ // draft mode, which is the editor's and reads every draft. A release
542
+ // preview's token (`withRelease`) is read only under draft mode.
543
+ const reader = await input.headers();
544
+ const link = draft ? null : draftLinkIn(reader);
545
+ const settings = withDraftLink(withRelease(modeConfig(input.config, draft || link !== null), draft ? reader : null), link);
459
546
  const client = (0, next_1.createClient)({ editMode: edit, ...settings });
460
- const read = { draft, edit, settings, given: input.unstable_cache };
547
+ const read = { draft: draft || link !== null, edit, settings, given: input.unstable_cache };
461
548
  const graphql = (0, client_1.graphqlClient)((document, variables, options = {}) => {
462
549
  const { tags, revalidate, ...call } = options;
463
550
  return readInNext(read, document, variables, call, { tags, revalidate });
@@ -512,8 +599,13 @@ async function cacheKeyOf(settings, document, variables, call) {
512
599
  async function graphql(document, variables, options = {}) {
513
600
  const { tags, revalidate, draft: draftOption, draftMode, headers, config, unstable_cache: given, ...call } = options;
514
601
  const draft = draftOption ?? (draftMode ? (await draftMode()).isEnabled === true : false);
515
- const edit = draft || (headers ? verifiedEdit(await headers()) : false);
516
- const read = { draft, edit, settings: modeConfig(config, draft), given };
602
+ const reader = headers ? await headers() : null;
603
+ const edit = draft || (reader ? verifiedEdit(reader) : false);
604
+ // A draft-link visit, as `getCapaClient` works it out. A `draft` given
605
+ // decides alone.
606
+ const link = draftOption === undefined && !draft && reader ? draftLinkIn(reader) : null;
607
+ const settings = withDraftLink(withRelease(modeConfig(config, draft || link !== null), draft ? reader : null), link);
608
+ const read = { draft: draft || link !== null, edit, settings, given };
517
609
  return readInNext(read, document, variables, call, { tags, revalidate });
518
610
  }
519
611
  /**
@@ -598,6 +690,48 @@ exports.CAPA_ADMIN_ORIGIN = "https://app.capacms.com";
598
690
  exports.DRAFT_ROBOTS_TAG = "noindex, nofollow";
599
691
  /** How long the draft cookie lasts, in seconds: one hour, as a preview token does. */
600
692
  exports.DRAFT_COOKIE_MAX_AGE = 3600;
693
+ /**
694
+ * The cookie a release preview's token lives in. `createPreviewRoute` sets it
695
+ * (partitioned, one hour, like the draft cookie) when the link names releases,
696
+ * and clears it on any other preview; `exitPreviewRoute` clears it. Read
697
+ * only under draft mode, and sent as `Capa-Release`.
698
+ */
699
+ exports.RELEASE_COOKIE = "capa-release";
700
+ /** One cookie's value out of a `Cookie` header, or undefined. */
701
+ function cookieValue(header, name) {
702
+ for (const part of (header ?? "").split(/;\s*/)) {
703
+ const at = part.indexOf("=");
704
+ if (at > 0 && part.slice(0, at) === name) {
705
+ const raw = part.slice(at + 1);
706
+ try {
707
+ return decodeURIComponent(raw) || undefined;
708
+ }
709
+ catch {
710
+ return raw || undefined;
711
+ }
712
+ }
713
+ }
714
+ return undefined;
715
+ }
716
+ /** The settings with the release preview's token from the request, under draft mode only. */
717
+ function withRelease(settings, headers) {
718
+ if (!headers || settings.release !== undefined)
719
+ return settings;
720
+ const release = cookieValue(headers.get("cookie"), exports.RELEASE_COOKIE);
721
+ return release ? { ...settings, release } : settings;
722
+ }
723
+ /**
724
+ * The release preview's token for this request, or undefined: under draft
725
+ * mode, the `capa-release` cookie. For a site that builds its own client:
726
+ *
727
+ * import { cookies, draftMode } from "next/headers";
728
+ * const client = createClient({ ..., release: await releaseToken({ cookies, draftMode }) });
729
+ */
730
+ async function releaseToken(input) {
731
+ if ((await input.draftMode()).isEnabled !== true)
732
+ return undefined;
733
+ return (await input.cookies()).get(exports.RELEASE_COOKIE)?.value || undefined;
734
+ }
601
735
  /**
602
736
  * `frame-ancestors 'self' <origins>`, the CSP directive that lets the Capa
603
737
  * editor frame a draft and nothing else frame it. Each origin is a scheme and
@@ -650,9 +784,10 @@ function draftHeaders(options = {}) {
650
784
  * import { capaHeaders } from "@capacms/sdk/nextjs";
651
785
  * export default { async headers() { return [...capaHeaders()]; } };
652
786
  *
653
- * A rule matches a request carrying the draft cookie, or a `capa-preview`,
654
- * `capa-edit` or `capa-view` query. A visitor's request carries none of
655
- * them, so its response, cached or not, is exactly what it was. Next checks
787
+ * A rule matches a request carrying the draft cookie or a draft link's
788
+ * cookie, or a `capa-preview`, `capa-edit` or `capa-view` query. A visitor's
789
+ * request carries none of them, so its response, cached or not, is exactly
790
+ * what it was. Next checks
656
791
  * the cookie by name, not by value, so a forged cookie only adds these
657
792
  * headers to the forger's own response.
658
793
  *
@@ -664,6 +799,7 @@ function capaHeaders(options = {}) {
664
799
  const headers = () => Object.entries(draftHeaders(options)).map(([key, value]) => ({ key, value }));
665
800
  const conditions = [
666
801
  { type: "cookie", key: exports.DRAFT_COOKIE },
802
+ { type: "cookie", key: exports.DRAFT_LINK_COOKIE },
667
803
  { type: "query", key: exports.PREVIEW_PARAM },
668
804
  { type: "query", key: exports.EDIT_PARAM },
669
805
  { type: "query", key: exports.VIEW_PARAM },
@@ -707,6 +843,42 @@ async function frameDraftCookie(cookies, options = {}) {
707
843
  async function clearDraftCookie(cookies) {
708
844
  (await cookies()).set({ name: exports.DRAFT_COOKIE, value: "", ...FRAMED, expires: new Date(0) });
709
845
  }
846
+ /** Delete the release preview's cookie (`RELEASE_COOKIE`), partitioned as it was set. Nothing when there is none. */
847
+ async function clearReleaseCookie(cookies) {
848
+ const jar = await cookies();
849
+ if (!jar.get(exports.RELEASE_COOKIE))
850
+ return;
851
+ jar.set({ name: exports.RELEASE_COOKIE, value: "", ...FRAMED, expires: new Date(0) });
852
+ }
853
+ /**
854
+ * A draft link's cookie. Opened at the top level, never inside the editor's
855
+ * frame, so it is `SameSite=Lax` and not partitioned. `HttpOnly`: the page's
856
+ * own scripts never see the token.
857
+ */
858
+ const DRAFT_LINK_ATTRS = { path: "/", httpOnly: true, secure: true, sameSite: "lax", partitioned: false };
859
+ /**
860
+ * Keep a draft link's token for the visit. It ends at the link's expiry or
861
+ * after `maxAge` seconds, whichever comes first. False, and nothing kept,
862
+ * when the link has already expired.
863
+ */
864
+ async function keepDraftLink(cookies, token, expiresAt, maxAge) {
865
+ const left = Math.floor((Date.parse(expiresAt) - Date.now()) / 1000);
866
+ if (!Number.isFinite(left) || left <= 0)
867
+ return false;
868
+ (await cookies()).set({ name: exports.DRAFT_LINK_COOKIE, value: token, ...DRAFT_LINK_ATTRS, maxAge: Math.min(left, maxAge) });
869
+ return true;
870
+ }
871
+ /**
872
+ * Delete the draft link's cookie `createPreviewRoute` kept, when the request
873
+ * carries one. `createPreviewRoute` calls it on any other answer and
874
+ * `exitPreviewRoute` on exit, given `cookies`.
875
+ */
876
+ async function clearDraftLinkCookie(cookies) {
877
+ const jar = await cookies();
878
+ if (!jar.get(exports.DRAFT_LINK_COOKIE)?.value)
879
+ return;
880
+ jar.set({ name: exports.DRAFT_LINK_COOKIE, value: "", ...DRAFT_LINK_ATTRS, expires: new Date(0) });
881
+ }
710
882
  /**
711
883
  * The preview and exit routes' own redirect. Next's `redirect()` throws and
712
884
  * answers for the route, so it cannot carry headers; this one is a plain
@@ -732,7 +904,19 @@ function routeRedirect(location, headers) {
732
904
  * its legacy key included (`getPublishedClient`, from `CAPA_KEY`).
733
905
  *
734
906
  * Given `cookies`, the draft cookie is re-set by `frameDraftCookie`: one hour,
735
- * and sent inside the editor's frame. With no `redirect`, the route answers
907
+ * and sent inside the editor's frame.
908
+ *
909
+ * A DRAFT LINK (Share draft in Capa) opens only given `cookies`, and never
910
+ * turns draft mode on. The route tells Capa it narrows (`preview()` with
911
+ * `draftLinks`), keeps the token in `DRAFT_LINK_COOKIE` until the link
912
+ * expires or `maxAge` seconds pass, whichever is first, turns off any draft
913
+ * mode the browser had, and lands on the linked page. `onEnable` does not run
914
+ * for it. That visit's reads through `getCapaClient` and `graphql()` show the
915
+ * linked entry's draft and every other entry as published, and stop showing
916
+ * the draft once the link is revoked or expires. Without `cookies`, Capa
917
+ * answers a draft link as an expired token.
918
+ *
919
+ * With no `redirect`, the route answers
736
920
  * with its own 307, marked `X-Robots-Tag: noindex, nofollow`,
737
921
  * `Referrer-Policy: no-referrer` (the token is in the URL),
738
922
  * `Cache-Control: private, no-store` and the editor's `frame-ancestors`.
@@ -754,21 +938,47 @@ function createPreviewRoute(input) {
754
938
  let claim = null;
755
939
  let failed = false;
756
940
  try {
757
- claim = await (input.client ?? getPublishedClient)().preview(token);
941
+ // Given cookies, the route can keep a draft link's token, so it says it
942
+ // narrows one. Without them Capa answers a draft link as invalid.
943
+ claim = await (input.client ?? getPublishedClient)().preview(token, input.cookies ? { draftLinks: true } : undefined);
758
944
  }
759
945
  catch {
760
946
  failed = true;
761
947
  }
762
948
  const draft = await input.draftMode();
763
- if (!claim) {
949
+ // Either sign is enough, so a draft link never reaches `enable()`.
950
+ const isLink = claim !== null && (claim.draftLink === true || token.startsWith(DRAFT_LINK_PREFIX));
951
+ const kept = isLink && input.cookies ? await keepDraftLink(input.cookies, token, claim.expiresAt, maxAge) : false;
952
+ if (!claim || (isLink && !kept)) {
764
953
  draft.disable?.();
765
- if (input.cookies)
954
+ if (input.cookies) {
766
955
  await clearDraftCookie(input.cookies);
956
+ await clearDraftLinkCookie(input.cookies);
957
+ await clearReleaseCookie(input.cookies);
958
+ }
767
959
  return go(`${path}?preview=${failed ? "unavailable" : "expired"}`);
768
960
  }
961
+ if (isLink) {
962
+ // The link's own page, and no draft mode: the visit's reads send the
963
+ // kept token, and Capa serves the linked entry's draft alone.
964
+ draft.disable?.();
965
+ await clearDraftCookie(input.cookies);
966
+ await clearReleaseCookie(input.cookies);
967
+ return go(safeSitePath(claim.path ?? path));
968
+ }
769
969
  draft.enable?.();
770
- if (input.cookies)
970
+ if (input.cookies) {
771
971
  await frameDraftCookie(input.cookies, { maxAge });
972
+ await clearDraftLinkCookie(input.cookies);
973
+ // A release preview keeps its token for the reads (`Capa-Release`); any
974
+ // other preview clears one left from before, so it shows every draft.
975
+ if (claim.kind === "release" && (claim.releases?.length ?? 0) > 0) {
976
+ (await input.cookies()).set({ name: exports.RELEASE_COOKIE, value: token, ...FRAMED, maxAge });
977
+ }
978
+ else {
979
+ await clearReleaseCookie(input.cookies);
980
+ }
981
+ }
772
982
  await input.onEnable?.();
773
983
  return go(safeSitePath(claim.path ?? path));
774
984
  };
@@ -780,14 +990,17 @@ function createPreviewRoute(input) {
780
990
  * export const GET = exitPreviewRoute({ draftMode, cookies });
781
991
  *
782
992
  * Turns draft mode off and lands on `?path=`. Given `cookies`, the framed
783
- * cookie `createPreviewRoute` set is deleted too. With no `redirect`, the route
993
+ * cookie `createPreviewRoute` set is deleted too, and a draft link's cookie. With no `redirect`, the route
784
994
  * answers with its own 307, marked noindex and never cached.
785
995
  */
786
996
  function exitPreviewRoute(input) {
787
997
  return async (request) => {
788
998
  (await input.draftMode()).disable?.();
789
- if (input.cookies)
999
+ if (input.cookies) {
790
1000
  await clearDraftCookie(input.cookies);
1001
+ await clearDraftLinkCookie(input.cookies);
1002
+ await clearReleaseCookie(input.cookies);
1003
+ }
791
1004
  const location = safeSitePath(new URL(request.url).searchParams.get("path"));
792
1005
  if (input.redirect)
793
1006
  return input.redirect(location);