@capacms/sdk 1.0.0-next.15 → 1.0.0-next.17

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,59 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 1.0.0-next.17
6
+
7
+ Published 2026-11-25. New since 1.0.0-next.16: `search()` reads Site search through the new `siteSearchKey` option, since `/v2/api/search` answers 410 on every key. Each refusal throws with the steps to fix it.
8
+
9
+ - `search()` reads Site search. It called `/v2/api/search`, which answers
10
+ 410 on every key since 2026-10-30. It now calls `GET /v2/site-search`
11
+ with the project's site search key, passed to `createClient` as the new
12
+ `siteSearchKey` option (a `capss_` key from Settings > Search > Site
13
+ keys). That key is the only credential sent there: no `apiKey` and no
14
+ `X-Tenant-Key`.
15
+ - Without `siteSearchKey`, `search()` throws before sending anything, with
16
+ the steps to get one. A project without Site search (404), a refused key
17
+ (401) and a project whose first index is not built yet (503
18
+ `search_not_ready`) each throw a `CapaError` whose message says what to
19
+ do. Any other refusal keeps the API's own words.
20
+ - `SearchHit` keeps its four fields. `model` is now always a `string`
21
+ (it was optional) and `title` a `string` (it was `unknown`). `id` and
22
+ `namespace` stay `string | null` so code that checks for `null` still
23
+ compiles, but Site search sends both on every hit, and `id` is always
24
+ the entry's instance id: a model with its own `id` field no longer
25
+ hides it.
26
+ - What `search()` finds changed. Site search holds the published version
27
+ of the models and fields the project picked in Settings > Search. It used
28
+ to be every model marked searchable.
29
+ - `limit` is 1 to 50 (default 20), where it was up to 500, and `page`
30
+ starts at 1. A limit outside that range, a page below 1, or a page that
31
+ starts past 1,000 hits throws a `RangeError` before any request, since
32
+ Site search would cut the offset to 1,000 and answer the wrong page.
33
+ - `SearchOptions` is exported, the type of `search()`'s options.
34
+ - `CapaError` takes an optional fourth argument, its message.
35
+
36
+ ## 1.0.0-next.16
37
+
38
+ Published 2026-11-18. New since 1.0.0-next.15: a shared draft link that does not open lands on `?preview=link-ended`, so a site can word it for someone with no Capa account; `draftLinkVisit({ headers })` tells a page whether a draft-link visit's link is still live, for a "Draft preview" bar; and `preview()` takes `checkOnly`.
39
+
40
+ - A shared draft link that does not open (revoked, expired, changed, made
41
+ up, or a preview route not given `cookies`) now lands on
42
+ `?preview=link-ended`, exported as `DRAFT_LINK_ENDED`, instead of the
43
+ editor's `?preview=expired`. The person holding a draft link has no Capa
44
+ account, so a site can word the answer for them. An editor's preview
45
+ token that does not open still lands on `?preview=expired`. A site that
46
+ shows a banner only for `expired` shows none for a dead draft link until
47
+ it handles `link-ended`.
48
+ - `draftLinkVisit({ headers })`, new in `@capacms/sdk/nextjs`, tells a page
49
+ whether its request is a visit of a draft link and whether the link is
50
+ still live: `null`, or `{ status: "active", path, expiresAt }`,
51
+ `{ status: "ended" }` or `{ status: "unknown" }`. It checks the token with
52
+ Capa once, as the preview route does, with the published key, and never
53
+ throws. Use it for a "Draft preview" bar on a draft-link visit.
54
+ - `preview(token, { checkOnly: true })` sends `Capa-Draft-Link-Check: 1`,
55
+ which changes nothing in the answer. `draftLinkVisit` sets it, so Capa's
56
+ logs tell a page asking about a link from the link being opened.
57
+
5
58
  ## 1.0.0-next.15
6
59
 
7
60
  Published 2026-11-17. New since 1.0.0-next.14: `capa-codegen --shape api` (or `{ shape: "api" }` in code), an opt-in mode that writes types as `/api/` returns them: fields that can be null say so, required fields are no longer optional, enums are their options with a pk_ key, and media carry their real fields. Without the flag the output is byte for byte what it was.
package/README.md CHANGED
@@ -2027,6 +2027,53 @@ every CSP it is sent, so if your site sends its own `frame-ancestors` or
2027
2027
  `capaMiddleware` marks its edit-mode responses noindex too, and
2028
2028
  `resolveEditRequest` returns the value as `robotsTag`.
2029
2029
 
2030
+ ### Shared draft links
2031
+
2032
+ An editor can share a draft with someone who has no Capa account (Share draft
2033
+ in the preview pane). The link is `<preview base URL><path>?capa-preview=cap_draft_...`,
2034
+ and the same middleware and `createPreviewRoute({ draftMode, cookies })` open
2035
+ it. The route never turns draft mode on for it: it keeps the token in the
2036
+ `capa-draft-link` cookie for at most an hour, and lands on the page with the
2037
+ token gone from the address. That visit's reads through `getCapaClient` and
2038
+ `graphql()`, given `headers`, show the linked entry's draft and every other
2039
+ entry as published.
2040
+
2041
+ The person holding the link is not an editor, so word what they see for them:
2042
+
2043
+ - A draft link that does not open (revoked, expired, changed, or a route not
2044
+ given `cookies`) lands on `?preview=link-ended` (`DRAFT_LINK_ENDED`), never
2045
+ on the editor's `?preview=expired`. Capa answers every dead link the same
2046
+ way, so say it once: "This preview link is no longer active. Ask the person
2047
+ who shared it for a new one."
2048
+ - `draftLinkVisit({ headers })` says whether this request is a visit, and
2049
+ whether its link is still live: `null` with no visit, or `active` (with the
2050
+ page it opens and when it ends), `ended` or `unknown`. It asks Capa once.
2051
+
2052
+ ```tsx
2053
+ // app/layout.tsx
2054
+ import { draftMode, headers } from "next/headers";
2055
+ import { draftLinkVisit } from "@capacms/sdk/nextjs";
2056
+
2057
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
2058
+ const draft = (await draftMode()).isEnabled;
2059
+ const visit = draft ? null : await draftLinkVisit({ headers });
2060
+ // visit?.status === "active": "Draft preview. You are seeing unpublished changes."
2061
+ // visit?.status === "ended": "This preview link is no longer active."
2062
+ // ...render the bar and {children}
2063
+ }
2064
+ ```
2065
+
2066
+ Next keeps a layout as the visitor moves between pages, so a bar the root
2067
+ layout draws keeps the state it read on the first page. To show a revoke on
2068
+ the next page, as the content does, ask again after each page change: a
2069
+ route handler that returns `draftLinkVisit({ headers })`, fetched by the bar
2070
+ when the path changes, or a server component in each page.
2071
+
2072
+ Show the visitor a bar while a visit is active, as the editor's preview
2073
+ does, or they may take an unpublished page for the live one. Tell them to
2074
+ forward the link they were sent: the address bar holds the page's own
2075
+ address once the link opens, and that address is the published page.
2076
+
2030
2077
  ### Add preview to a live site without changing it
2031
2078
 
2032
2079
  A live Next.js site that reads Capa with its own code keeps that code. Preview
@@ -2518,9 +2565,9 @@ page.data[0].id // the model's OWN id field whenever one exists
2518
2565
  the model shadows `id` and the row carries nothing else to read the entry's
2519
2566
  id from. `instanceIdOf(row)` reads one row the same way, and prefers an
2520
2567
  `instanceId` when a row carries one. `getContentById` throws for an id that is
2521
- not a UUID rather than spending a request on a certain 400. `search()` reads
2522
- its hits the same way, so `SearchHit.id` is `string | null` too. `/api/` has
2523
- no such collision: an entry's system keys sit beside its `fields`.
2568
+ not a UUID rather than spending a request on a certain 400. `search()` has
2569
+ no such problem: Site search sends the instance id on every hit. `/api/` has
2570
+ no such collision either: an entry's system keys sit beside its `fields`.
2524
2571
 
2525
2572
  ### Related entries: `Page.relations`
2526
2573
 
@@ -2581,6 +2628,39 @@ read it here instead.
2581
2628
  related entry, nested where it was selected, and with `shape: "flat"` once in
2582
2629
  `included`. See [Flat responses](#flat-responses-each-related-entry-once).
2583
2630
 
2631
+ ### Search
2632
+
2633
+ `search()` reads Site search, `GET /v2/site-search`. `/v2/api/search`
2634
+ answers 410 on every key since 2026-10-30. Site search takes a key of its
2635
+ own, so pass the project's site search key as `siteSearchKey`:
2636
+
2637
+ ```ts
2638
+ const capa = createClient({
2639
+ baseUrl: process.env.CAPA_API_URL!,
2640
+ apiKey: process.env.CAPA_KEY!,
2641
+ tenantId: process.env.CAPA_TENANT_ID!,
2642
+ siteSearchKey: process.env.CAPA_SITE_SEARCH_KEY, // capss_...
2643
+ });
2644
+
2645
+ const hits = await capa.search("kitchen", { namespace: "articles", limit: 10, page: 1 });
2646
+ // [{ id, namespace, model, title }]
2647
+ ```
2648
+
2649
+ To get the key, turn on Site search for the project in the Capa admin,
2650
+ Settings > Search. It is in pilot, so ask Capa to turn it on if that page is
2651
+ missing. Pick the models and fields to search, then make a key there under
2652
+ Site keys. It starts `capss_`, reads nothing but Site search, and goes only
2653
+ to that route: the legacy key in `apiKey` is not sent there.
2654
+
2655
+ Site search holds the published version of the models and fields the project
2656
+ picked. `limit` is 1 to 50 (default 20) and `page` starts at 1. A page that
2657
+ starts past 1,000 hits throws, since Site search reads no further.
2658
+
2659
+ `search()` throws with the fix when it cannot search. With no
2660
+ `siteSearchKey` it throws before sending anything. A project without Site
2661
+ search (404), a refused key (401) and a project whose first index is not
2662
+ built yet (503) each throw a `CapaError` whose message says what to do.
2663
+
2584
2664
  ### Preview is a key, not a flag
2585
2665
 
2586
2666
  Capa shows unpublished content to a key whose environment is not
package/dist/client.d.ts CHANGED
@@ -131,11 +131,12 @@ export interface CapaClient {
131
131
  }): Promise<T | null>;
132
132
  /** A `ReadOneOptions` value, or a `withRelations` known only at run time: either shape. */
133
133
  findOne<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, where: Record<string, string | number | boolean>, options?: ReadOneOptions): Promise<T | OneWithRelations<T, R> | null>;
134
- search(q: string, options?: {
135
- namespace?: string;
136
- limit?: number;
137
- page?: number;
138
- }): Promise<SearchHit[]>;
134
+ /**
135
+ * Full-text search over the project's published content, through Site
136
+ * search (`GET /v2/site-search`). Needs `siteSearchKey` in the config, and
137
+ * Site search turned on for the project; it throws with the fix otherwise.
138
+ */
139
+ search(q: string, options?: SearchOptions): Promise<SearchHit[]>;
139
140
  /** Saved arrangements of the Capa admin's left rail. ADMIN_UI_OVERHAUL 0h. */
140
141
  workspaces: WorkspacesResource;
141
142
  /** Model schema reads, and the entry-editor layout. ADMIN_UI_OVERHAUL 0m. */
@@ -456,17 +457,30 @@ export interface ScheduledActionsResource {
456
457
  /** Creates a NEW pending row; the failed one keeps its history. */
457
458
  retry(id: string): Promise<ScheduledAction>;
458
459
  }
460
+ export interface SearchOptions {
461
+ /** One model's namespace. Omit to search every model in the project's Site search setup. */
462
+ namespace?: string;
463
+ /** Hits per page, 1 to 50. Default 20. */
464
+ limit?: number;
465
+ /** 1-based page number. Site search reads at most 1,000 hits in, so `(page - 1) * limit` is at most 1000. */
466
+ page?: number;
467
+ }
468
+ /**
469
+ * One Site search hit, as `search()` returns it. Since 1.0.0-next.17 it comes
470
+ * from `/v2/site-search`.
471
+ */
459
472
  export interface SearchHit {
460
473
  /**
461
- * The instance UUID, via `instanceIdOf`. `null` means the server sent no
462
- * usable id: an extended search row hoists the model's own fields the same
463
- * way a content row does, so a model with a field named `id` shadows it, and
464
- * a server older than #4628 sends no `instanceId` beside it.
474
+ * The entry's instance id, a UUID. Site search sends it on every hit. The
475
+ * type keeps `null`, as before, so code that checks for it still compiles.
465
476
  */
466
477
  id: string | null;
478
+ /** The model's namespace. Always sent; `null` stays in the type for the same reason as `id`. */
467
479
  namespace: string | null;
468
- model?: string;
469
- title: unknown;
480
+ /** The model's name, as the admin shows it. */
481
+ model: string;
482
+ /** The entry's title as plain text, `""` when it has none. */
483
+ title: string;
470
484
  }
471
485
  /**
472
486
  * The Capa instance id for a row.
package/dist/client.js CHANGED
@@ -21,6 +21,35 @@ const config_1 = require("./config");
21
21
  const http_1 = require("./http");
22
22
  const key_family_1 = require("./next/key-family");
23
23
  const webhooks_1 = require("./webhooks");
24
+ /** Site search's own limits (packages/search/src/tenant/query.ts). */
25
+ const SITE_SEARCH_MAX_LIMIT = 50;
26
+ const SITE_SEARCH_MAX_OFFSET = 1000;
27
+ const SITE_SEARCH_PATH = "/v2/site-search";
28
+ const SITE_SEARCH_SETUP = "Turn on Site search for the project in the Capa admin (Settings > Search; while Site search is in pilot, " +
29
+ "ask Capa to turn it on if that page is missing), make a site search key there under Site keys " +
30
+ "(it starts capss_), and pass it to createClient as siteSearchKey.";
31
+ /** What a Site search refusal means for a `search()` caller, or null to keep the API's own words. */
32
+ function siteSearchRefusal(status, text) {
33
+ let code;
34
+ try {
35
+ code = JSON.parse(text)?.code;
36
+ }
37
+ catch {
38
+ code = undefined;
39
+ }
40
+ if (status === 401) {
41
+ return ("@capacms/sdk: Site search refused siteSearchKey: it was revoked, or it is not this project's capss_ key. " +
42
+ "Make a new one in the Capa admin under Settings > Search > Site keys and pass it as siteSearchKey.");
43
+ }
44
+ // The route answers an unknown path's 404 to a project Site search is not on for.
45
+ if (status === 404)
46
+ return `@capacms/sdk: Site search is not turned on for this project, so search() has nothing to read. ${SITE_SEARCH_SETUP}`;
47
+ if (status === 503 && code === "search_not_ready") {
48
+ return ("@capacms/sdk: Site search is on for this project but has no index yet. In the Capa admin, pick the models " +
49
+ "to search in Settings > Search, save, and wait for the first build to finish.");
50
+ }
51
+ return null;
52
+ }
24
53
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
25
54
  /**
26
55
  * The Capa instance id for a row.
@@ -50,10 +79,6 @@ function instanceIdOf(row) {
50
79
  const id = r?.id;
51
80
  return typeof id === "string" && UUID_RE.test(id) ? id : null;
52
81
  }
53
- /** Capa wraps most values as `{type, value, sortOrder}` — including `title`. */
54
- const unwrap = (v) => v && typeof v === "object" && !Array.isArray(v) && "value" in v
55
- ? v.value
56
- : v ?? null;
57
82
  function contentQuery(options = {}) {
58
83
  const q = {
59
84
  limit: options.limit,
@@ -137,35 +162,59 @@ function createClient(config) {
137
162
  },
138
163
  async search(q, options = {}) {
139
164
  const text = String(q ?? "").trim();
140
- // The server answers an absent `q` with 500 carrying `Cannot read
141
- // properties of undefined (reading 'trim')` — the parameter is trimmed
142
- // before it is checked. #4627 made it a 400 and the public-surface freeze
143
- // put the 500 back on 2026-09-20, so this guard is what a caller actually
144
- // gets: a named error, at no request cost, on every server.
165
+ // Site search answers an empty q with every entry it holds, which is not
166
+ // a search. Refused here, as it always was, at no request cost.
145
167
  if (!text)
146
168
  throw new Error("@capacms/sdk: search(q) requires a non-empty query.");
147
- const { body } = await (0, http_1.getJson)(resolved, "/v2/api/search", {
148
- q: text,
149
- modelNamespace: options.namespace,
150
- size: options.limit ?? 20,
151
- page: options.page,
152
- // The default (non-extended) branch answers {id, title} and says
153
- // nothing about which model a hit belongs to, so the namespace has to
154
- // be bought with a hydration round trip. #4627 briefly added it to the
155
- // default row; the public-surface freeze reverted that on 2026-09-20.
156
- extended: true,
157
- depth: 0,
169
+ // `/v2/api/search` answers 410 on every key since 2026-10-30. Site search
170
+ // is the search Capa serves now, and it takes its own key: the legacy
171
+ // key in `apiKey` is not sent there.
172
+ const key = String(resolved.siteSearchKey ?? "").trim();
173
+ if (!key)
174
+ throw new Error(`@capacms/sdk: search() reads Site search, which needs its own key. ${SITE_SEARCH_SETUP}`);
175
+ const limit = options.limit ?? 20;
176
+ if (!Number.isInteger(limit) || limit < 1 || limit > SITE_SEARCH_MAX_LIMIT) {
177
+ throw new RangeError(`@capacms/sdk: search() takes a limit from 1 to ${SITE_SEARCH_MAX_LIMIT}; got ${options.limit}.`);
178
+ }
179
+ const page = options.page ?? 1;
180
+ if (!Number.isInteger(page) || page < 1)
181
+ throw new RangeError(`@capacms/sdk: search() takes a page from 1; got ${options.page}.`);
182
+ // The server cuts a larger offset to 1000 without saying so, which
183
+ // would answer the wrong page.
184
+ const offset = (page - 1) * limit;
185
+ if (offset > SITE_SEARCH_MAX_OFFSET) {
186
+ throw new RangeError(`@capacms/sdk: Site search reads at most ${SITE_SEARCH_MAX_OFFSET} hits in; page ${page} of ${limit} starts at ${offset}.`);
187
+ }
188
+ const url = new URL(resolved.baseUrl + SITE_SEARCH_PATH);
189
+ url.searchParams.set("q", text);
190
+ url.searchParams.set("limit", String(limit));
191
+ if (offset)
192
+ url.searchParams.set("offset", String(offset));
193
+ if (options.namespace)
194
+ url.searchParams.set("filter[model]", options.namespace);
195
+ // Only the site search key, as the admin's copyable widget sends it: no
196
+ // X-Tenant-Key, since the key names the project.
197
+ const res = await resolved.fetchImpl(url.toString(), {
198
+ method: "GET",
199
+ headers: { "x-api-key": key, Accept: "application/json" },
158
200
  });
159
- return (body.data ?? []).map((row) => ({
160
- // instanceIdOf, not row.id. `/v2/api/search?extended=true` hoists the
161
- // model's own fields exactly as `/v2/api/:ns` does, so a model with a
162
- // field named `id` shadows the id here too; #4628 now sends
163
- // `instanceId` on these rows as well. `null` means an old server AND a
164
- // shadowing model, the same as `Page.ids`.
165
- id: instanceIdOf(row),
166
- namespace: row.dataModel?.namespace ?? row.modelNamespace ?? null,
167
- model: row.dataModel?.modelName ?? undefined,
168
- title: unwrap(row.title),
201
+ const body = await res.text();
202
+ if (!res.ok) {
203
+ const message = siteSearchRefusal(res.status, body);
204
+ throw new http_1.CapaError(res.status, SITE_SEARCH_PATH, body, message ?? undefined);
205
+ }
206
+ let answer;
207
+ try {
208
+ answer = JSON.parse(body);
209
+ }
210
+ catch {
211
+ throw new http_1.CapaError(res.status, SITE_SEARCH_PATH, `response was not JSON: ${body.slice(0, 200)}`);
212
+ }
213
+ return (answer.hits ?? []).map((hit) => ({
214
+ id: typeof hit.id === "string" ? hit.id : null,
215
+ namespace: typeof hit.model === "string" ? hit.model : null,
216
+ model: String(hit.modelName ?? ""),
217
+ title: typeof hit.title === "string" ? hit.title : "",
169
218
  }));
170
219
  },
171
220
  /**
package/dist/config.d.ts CHANGED
@@ -19,6 +19,16 @@ export interface CapaConfig {
19
19
  * this field and keeps using `apiKey`.
20
20
  */
21
21
  accessToken?: string;
22
+ /**
23
+ * The project's site search key (`capss_`), for `search()` only.
24
+ *
25
+ * `search()` reads Site search, `GET /v2/site-search`, because
26
+ * `/v2/api/search` answers 410 on every key since 2026-10-30. Site search
27
+ * takes a key of its own: make one in the Capa admin under Settings >
28
+ * Search > Site keys, once Site search is on for the project. Without it,
29
+ * `search()` throws before it sends anything. No other method reads it.
30
+ */
31
+ siteSearchKey?: string;
22
32
  /** Injected in tests; defaults to the global fetch. */
23
33
  fetch?: typeof fetch;
24
34
  }
package/dist/http.d.ts CHANGED
@@ -2,7 +2,8 @@ import type { ResolvedConfig } from "./config";
2
2
  export declare class CapaError extends Error {
3
3
  readonly status: number;
4
4
  readonly path: string;
5
- constructor(status: number, path: string, body: string);
5
+ /** `message` replaces the default one, for an answer the SDK can explain better than its body does. */
6
+ constructor(status: number, path: string, body: string, message?: string);
6
7
  }
7
8
  export type Query = Record<string, string | number | boolean | undefined | null>;
8
9
  /**
package/dist/http.js CHANGED
@@ -9,8 +9,9 @@ exports.writeJson = writeJson;
9
9
  class CapaError extends Error {
10
10
  status;
11
11
  path;
12
- constructor(status, path, body) {
13
- super(`Capa API ${status} on ${path}${body ? `: ${body.slice(0, 200)}` : ""}`);
12
+ /** `message` replaces the default one, for an answer the SDK can explain better than its body does. */
13
+ constructor(status, path, body, message) {
14
+ super(message ?? `Capa API ${status} on ${path}${body ? `: ${body.slice(0, 200)}` : ""}`);
14
15
  this.name = "CapaError";
15
16
  this.status = status;
16
17
  this.path = path;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createClient, instanceIdOf } from "./client";
2
- export type { CapaClient, CreateScheduledActionsInput, CreateScheduledActionsResult, FieldValue, LayoutCard, LayoutDisplay, LayoutField, LayoutInline, LayoutWidth, ListOptions, ListScheduledActionsOptions, ModelLayout, ModelLayoutInfo, ModelsResource, OneWithRelations, Page, ReadOneOptions, RelatedEntry, Relations, ResolvedScheduleTime, ScheduledAction, ScheduledActionsPage, ScheduledActionsResource, ScheduledActionStatus, ScheduledActionTarget, SearchHit, WorkspaceApplyResult, WorkspaceChanges, WorkspaceDocNode, WorkspaceDocument, WorkspaceSummary, WorkspaceTemplate, WorkspaceTreeDocument, WorkspacesResource, } from "./client";
2
+ export type { CapaClient, CreateScheduledActionsInput, CreateScheduledActionsResult, FieldValue, LayoutCard, LayoutDisplay, LayoutField, LayoutInline, LayoutWidth, ListOptions, ListScheduledActionsOptions, ModelLayout, ModelLayoutInfo, ModelsResource, OneWithRelations, Page, ReadOneOptions, RelatedEntry, Relations, ResolvedScheduleTime, ScheduledAction, ScheduledActionsPage, ScheduledActionsResource, ScheduledActionStatus, ScheduledActionTarget, SearchHit, SearchOptions, WorkspaceApplyResult, WorkspaceChanges, WorkspaceDocNode, WorkspaceDocument, WorkspaceSummary, WorkspaceTemplate, WorkspaceTreeDocument, WorkspacesResource, } from "./client";
3
3
  export type { CapaConfig } from "./config";
4
4
  export { CapaError } from "./http";
5
5
  export { WEBHOOKS_NEED_ACCESS_TOKEN } from "./webhooks";
@@ -118,6 +118,13 @@ export interface PreviewOptions extends CallOptions {
118
118
  * route that would turn the whole site's draft mode on never opens one.
119
119
  */
120
120
  draftLinks?: boolean;
121
+ /**
122
+ * True when the call only asks whether a draft-link visit's link is still
123
+ * live, as `draftLinkVisit` does, rather than opening it. Sent as
124
+ * `Capa-Draft-Link-Check: 1`. It changes nothing in the answer: Capa's logs
125
+ * then tell a page that asked about a link from a link being opened.
126
+ */
127
+ checkOnly?: boolean;
121
128
  }
122
129
  /**
123
130
  * One entry as `/api/entries` returns it: the system keys, and `fields`. A read
@@ -542,7 +542,12 @@ function createClient(config) {
542
542
  try {
543
543
  const claim = (await request("/api/preview", query, options.signal, undefined, undefined,
544
544
  // Only a caller that narrows a draft link opens one (PreviewOptions).
545
- options.draftLinks === true ? { "Capa-Draft-Links": "narrow" } : undefined)).body.data;
545
+ options.draftLinks === true || options.checkOnly === true
546
+ ? {
547
+ ...(options.draftLinks === true ? { "Capa-Draft-Links": "narrow" } : {}),
548
+ ...(options.checkOnly === true ? { "Capa-Draft-Link-Check": "1" } : {}),
549
+ }
550
+ : undefined)).body.data;
546
551
  // A release preview names releases, not an entry: the entry keys are
547
552
  // filled so a site that reads them reads a string, never undefined.
548
553
  // A link to a release that is done since carries its banner, for the
@@ -194,6 +194,55 @@ export declare function editMode(input: {
194
194
  export declare function draftLinkToken(input: {
195
195
  headers: () => HeaderReader | Promise<HeaderReader>;
196
196
  }): Promise<string | null>;
197
+ /**
198
+ * The `?preview=` value `createPreviewRoute` lands a DRAFT LINK on when it does
199
+ * not open: revoked, expired, changed, made up, another site's, or a route not
200
+ * given `cookies`. Capa gives one answer for all of them, so a site cannot tell
201
+ * them apart either. An editor's preview token that does not open still lands
202
+ * on `?preview=expired`. The person holding a draft link has no Capa account,
203
+ * so word it for them, for example "This preview link is no longer active. Ask
204
+ * the person who shared it for a new one."
205
+ */
206
+ export declare const DRAFT_LINK_ENDED = "link-ended";
207
+ /**
208
+ * What a draft-link visit is now, from `draftLinkVisit`:
209
+ *
210
+ * - `active`: the link still opens. `path` is the page it opens, or null when
211
+ * Capa can no longer resolve one; `expiresAt` is when the link itself ends.
212
+ * - `ended`: the link no longer opens (revoked, expired, its entry deleted).
213
+ * The visit's reads already show what is published.
214
+ * - `unknown`: Capa could not be asked. Show nothing rather than guess.
215
+ */
216
+ export type DraftLinkVisit = {
217
+ status: "active";
218
+ path: string | null;
219
+ expiresAt: string;
220
+ } | {
221
+ status: "ended";
222
+ } | {
223
+ status: "unknown";
224
+ };
225
+ /**
226
+ * Whether this request is a visit of a draft link, and whether that link is
227
+ * still live: null with no draft-link cookie, otherwise its state, asked of
228
+ * Capa (`preview()` with `draftLinks` and `checkOnly`, one request). For a
229
+ * banner that tells the visitor they are looking at an unpublished draft, in
230
+ * a server component or a route handler:
231
+ *
232
+ * import { draftMode, headers } from "next/headers";
233
+ * const visit = (await draftMode()).isEnabled ? null : await draftLinkVisit({ headers });
234
+ * // visit?.status === "active": "Draft preview. You are seeing unpublished changes."
235
+ * // visit?.status === "ended": "This preview link is no longer active."
236
+ *
237
+ * Under draft mode the reads are the editor's, so ask only outside it. The
238
+ * token is checked with the published key (`CAPA_KEY`), as
239
+ * `createPreviewRoute` checks it, unless `client` gives another. It never
240
+ * throws: Capa unreachable, no key, or `headers` throwing is `unknown`.
241
+ */
242
+ export declare function draftLinkVisit(input: {
243
+ headers: () => HeaderReader | Promise<HeaderReader>;
244
+ client?: () => Pick<CapaNextClient, "preview">;
245
+ }): Promise<DraftLinkVisit | null>;
197
246
  export interface EditRequest {
198
247
  /** True when the page must render in edit mode. */
199
248
  edit: boolean;
@@ -521,7 +570,8 @@ export declare function clearDraftLinkCookie(cookies: CookiesFn): Promise<void>;
521
570
  *
522
571
  * Checks the token with Capa (the site never holds the signing key), turns
523
572
  * draft mode on and lands on the entry's page. A bad or expired token lands on
524
- * the page without draft mode and `?preview=expired`; Capa unreachable gives
573
+ * the page without draft mode and `?preview=expired`, or `?preview=link-ended`
574
+ * for a draft link (`DRAFT_LINK_ENDED`); Capa unreachable gives
525
575
  * `?preview=unavailable`. The token is checked with any key the site holds,
526
576
  * its legacy key included (`getPublishedClient`, from `CAPA_KEY`).
527
577
  *
@@ -540,8 +590,10 @@ export declare function clearDraftLinkCookie(cookies: CookiesFn): Promise<void>;
540
590
  * mode the browser had, and lands on the linked page. `onEnable` does not run
541
591
  * for it. That visit's reads through `getCapaClient` and `graphql()` show the
542
592
  * linked entry's draft and every other entry as published, and stop showing
543
- * the draft once the link is revoked or expires. Without `cookies`, Capa
544
- * answers a draft link as an expired token.
593
+ * the draft once the link is revoked or expires. A draft link that does not
594
+ * open lands on `?preview=link-ended` (`DRAFT_LINK_ENDED`), never on the
595
+ * editor's `expired`. Without `cookies`, Capa answers every draft link that
596
+ * way. `draftLinkVisit` tells a page whether the visit's link is still live.
545
597
  *
546
598
  * With no `redirect`, the route answers
547
599
  * with its own 307, marked `X-Robots-Tag: noindex, nofollow`,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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;
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.DRAFT_LINK_ENDED = 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;
@@ -11,6 +11,7 @@ exports.preview = preview;
11
11
  exports.pagesFor = pagesFor;
12
12
  exports.editMode = editMode;
13
13
  exports.draftLinkToken = draftLinkToken;
14
+ exports.draftLinkVisit = draftLinkVisit;
14
15
  exports.resolveEditRequest = resolveEditRequest;
15
16
  exports.getPublishedClient = getPublishedClient;
16
17
  exports.getCapaClient = getCapaClient;
@@ -406,6 +407,48 @@ function draftLinkIn(headers) {
406
407
  async function draftLinkToken(input) {
407
408
  return draftLinkIn(await input.headers());
408
409
  }
410
+ /**
411
+ * The `?preview=` value `createPreviewRoute` lands a DRAFT LINK on when it does
412
+ * not open: revoked, expired, changed, made up, another site's, or a route not
413
+ * given `cookies`. Capa gives one answer for all of them, so a site cannot tell
414
+ * them apart either. An editor's preview token that does not open still lands
415
+ * on `?preview=expired`. The person holding a draft link has no Capa account,
416
+ * so word it for them, for example "This preview link is no longer active. Ask
417
+ * the person who shared it for a new one."
418
+ */
419
+ exports.DRAFT_LINK_ENDED = "link-ended";
420
+ /**
421
+ * Whether this request is a visit of a draft link, and whether that link is
422
+ * still live: null with no draft-link cookie, otherwise its state, asked of
423
+ * Capa (`preview()` with `draftLinks` and `checkOnly`, one request). For a
424
+ * banner that tells the visitor they are looking at an unpublished draft, in
425
+ * a server component or a route handler:
426
+ *
427
+ * import { draftMode, headers } from "next/headers";
428
+ * const visit = (await draftMode()).isEnabled ? null : await draftLinkVisit({ headers });
429
+ * // visit?.status === "active": "Draft preview. You are seeing unpublished changes."
430
+ * // visit?.status === "ended": "This preview link is no longer active."
431
+ *
432
+ * Under draft mode the reads are the editor's, so ask only outside it. The
433
+ * token is checked with the published key (`CAPA_KEY`), as
434
+ * `createPreviewRoute` checks it, unless `client` gives another. It never
435
+ * throws: Capa unreachable, no key, or `headers` throwing is `unknown`.
436
+ */
437
+ async function draftLinkVisit(input) {
438
+ let claim;
439
+ try {
440
+ const token = draftLinkIn(await input.headers());
441
+ if (token === null)
442
+ return null;
443
+ claim = await (input.client ?? getPublishedClient)().preview(token, { draftLinks: true, checkOnly: true });
444
+ }
445
+ catch {
446
+ return { status: "unknown" };
447
+ }
448
+ if (claim === null || claim.draftLink !== true)
449
+ return { status: "ended" };
450
+ return { status: "active", path: claim.path ?? null, expiresAt: claim.expiresAt };
451
+ }
409
452
  /** The settings with the draft link added, when there is one. */
410
453
  function withDraftLink(settings, link) {
411
454
  return link === null ? settings : { ...settings, draftLink: link };
@@ -943,7 +986,8 @@ function routeRedirect(location, headers) {
943
986
  *
944
987
  * Checks the token with Capa (the site never holds the signing key), turns
945
988
  * draft mode on and lands on the entry's page. A bad or expired token lands on
946
- * the page without draft mode and `?preview=expired`; Capa unreachable gives
989
+ * the page without draft mode and `?preview=expired`, or `?preview=link-ended`
990
+ * for a draft link (`DRAFT_LINK_ENDED`); Capa unreachable gives
947
991
  * `?preview=unavailable`. The token is checked with any key the site holds,
948
992
  * its legacy key included (`getPublishedClient`, from `CAPA_KEY`).
949
993
  *
@@ -962,8 +1006,10 @@ function routeRedirect(location, headers) {
962
1006
  * mode the browser had, and lands on the linked page. `onEnable` does not run
963
1007
  * for it. That visit's reads through `getCapaClient` and `graphql()` show the
964
1008
  * linked entry's draft and every other entry as published, and stop showing
965
- * the draft once the link is revoked or expires. Without `cookies`, Capa
966
- * answers a draft link as an expired token.
1009
+ * the draft once the link is revoked or expires. A draft link that does not
1010
+ * open lands on `?preview=link-ended` (`DRAFT_LINK_ENDED`), never on the
1011
+ * editor's `expired`. Without `cookies`, Capa answers every draft link that
1012
+ * way. `draftLinkVisit` tells a page whether the visit's link is still live.
967
1013
  *
968
1014
  * With no `redirect`, the route answers
969
1015
  * with its own 307, marked `X-Robots-Tag: noindex, nofollow`,
@@ -1011,7 +1057,11 @@ function createPreviewRoute(input) {
1011
1057
  await clearDraftLinkCookie(input.cookies);
1012
1058
  await clearReleaseCookie(input.cookies);
1013
1059
  }
1014
- return go(`${path}?preview=${failed ? "unavailable" : "expired"}`);
1060
+ // A draft link's holder has no Capa account: the site words its answer
1061
+ // for them (DRAFT_LINK_ENDED). Known by the token's shape, since Capa
1062
+ // answers a dead link exactly as it answers a forged one.
1063
+ const ended = isLink || token.startsWith(DRAFT_LINK_PREFIX) ? exports.DRAFT_LINK_ENDED : "expired";
1064
+ return go(`${path}?preview=${failed ? "unavailable" : ended}`);
1015
1065
  }
1016
1066
  if (isLink) {
1017
1067
  // The link's own page, and no draft mode: the visit's reads send the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capacms/sdk",
3
- "version": "1.0.0-next.15",
3
+ "version": "1.0.0-next.17",
4
4
  "description": "The TypeScript SDK for Capa's content API: REST and GraphQL reads typed from your models, Next.js caching and live preview, and codegen.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://docs.capacms.com/api",