@decocms/tanstack 8.5.2 → 8.7.0
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/README.md +35 -8
- package/dist/assignments.d.ts +31 -0
- package/dist/assignments.d.ts.map +1 -0
- package/dist/assignments.js +61 -0
- package/dist/assignments.js.map +1 -0
- package/dist/draft.d.ts +28 -9
- package/dist/draft.d.ts.map +1 -1
- package/dist/draft.js +30 -11
- package/dist/draft.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/react/DecoDocument.d.ts.map +1 -1
- package/dist/react/DecoDocument.js +4 -4
- package/dist/react/DecoDocument.js.map +1 -1
- package/dist/react/pageValues.d.ts +3 -0
- package/dist/react/pageValues.d.ts.map +1 -1
- package/dist/react/pageValues.js +13 -4
- package/dist/react/pageValues.js.map +1 -1
- package/dist/scope/server.d.ts +6 -1
- package/dist/scope/server.d.ts.map +1 -1
- package/dist/scope/server.js.map +1 -1
- package/dist/server/index.d.ts +37 -8
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +45 -9
- package/dist/server/index.js.map +1 -1
- package/dist/shared.d.ts +5 -5
- package/dist/shared.js +5 -5
- package/dist/start/index.d.ts +3 -3
- package/dist/start/index.js +3 -3
- package/dist/visitor.d.ts +14 -0
- package/dist/visitor.d.ts.map +1 -0
- package/dist/visitor.js +14 -0
- package/dist/visitor.js.map +1 -0
- package/dist/worker/assignments.d.ts +44 -0
- package/dist/worker/assignments.d.ts.map +1 -0
- package/dist/worker/assignments.js +114 -0
- package/dist/worker/assignments.js.map +1 -0
- package/dist/worker/cache.d.ts +35 -0
- package/dist/worker/cache.d.ts.map +1 -0
- package/dist/worker/cache.js +45 -0
- package/dist/worker/cache.js.map +1 -0
- package/dist/worker/cookies.d.ts +1 -5
- package/dist/worker/cookies.d.ts.map +1 -1
- package/dist/worker/cookies.js +1 -26
- package/dist/worker/cookies.js.map +1 -1
- package/dist/worker/drafts.d.ts +54 -46
- package/dist/worker/drafts.d.ts.map +1 -1
- package/dist/worker/drafts.js +88 -88
- package/dist/worker/drafts.js.map +1 -1
- package/dist/worker/index.d.ts +82 -51
- package/dist/worker/index.d.ts.map +1 -1
- package/dist/worker/index.js +197 -372
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/segment.d.ts +7 -6
- package/dist/worker/segment.d.ts.map +1 -1
- package/dist/worker/segment.js +6 -5
- package/dist/worker/segment.js.map +1 -1
- package/dist/worker/serverFn.d.ts +12 -0
- package/dist/worker/serverFn.d.ts.map +1 -0
- package/dist/worker/serverFn.js +44 -0
- package/dist/worker/serverFn.js.map +1 -0
- package/package.json +3 -3
- package/src/assignments.ts +77 -0
- package/src/draft.ts +34 -11
- package/src/index.ts +3 -1
- package/src/react/DecoDocument.tsx +20 -4
- package/src/react/pageValues.ts +12 -4
- package/src/scope/server.ts +6 -1
- package/src/server/index.ts +57 -12
- package/src/shared.ts +5 -5
- package/src/start/index.ts +3 -3
- package/src/visitor.ts +14 -0
- package/src/worker/assignments.ts +146 -0
- package/src/worker/cache.ts +61 -0
- package/src/worker/cookies.ts +1 -27
- package/src/worker/drafts.ts +113 -98
- package/src/worker/index.ts +276 -436
- package/src/worker/segment.ts +7 -7
- package/src/worker/serverFn.ts +36 -0
- package/dist/worker/cacheProfiles.d.ts +0 -43
- package/dist/worker/cacheProfiles.d.ts.map +0 -1
- package/dist/worker/cacheProfiles.js +0 -162
- package/dist/worker/cacheProfiles.js.map +0 -1
- package/src/worker/cacheProfiles.ts +0 -180
package/src/start/index.ts
CHANGED
|
@@ -17,9 +17,9 @@ function publishedToken(): string | null {
|
|
|
17
17
|
/**
|
|
18
18
|
* `fetch` for server-function calls: adds the CDN segment token the page
|
|
19
19
|
* published (`__cseg`), so the CDN can cache client-side navigation data. The
|
|
20
|
-
* token is a hint: the
|
|
21
|
-
*
|
|
22
|
-
* a plain `fetch`.
|
|
20
|
+
* token is a hint: the site's page cache (the example worker entry the README links)
|
|
21
|
+
* recomputes it from the request and lets the CDN keep the response only when
|
|
22
|
+
* they match. With no token on the page, a plain `fetch`.
|
|
23
23
|
*/
|
|
24
24
|
export const decoServerFnFetch: typeof fetch = (input, init) => {
|
|
25
25
|
// TanStack's server-function fetcher passes the URL as a string; anything else goes through as is.
|
package/src/visitor.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the worker hands the app the visitor: the request header it sets on a
|
|
3
|
+
* page or server-function request once it read the visitor (`readVisitor`
|
|
4
|
+
* from `@decocms/blocks/experiments`, a new one on a first visit). The worker
|
|
5
|
+
* writes it (`./worker/index.ts`); the app reads it (`contentClient` from
|
|
6
|
+
* `@decocms/tanstack/server`). No imports, no state: safe in every bundle.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The request header carrying the visitor, in its stored form (the
|
|
11
|
+
* `deco_segment` cookie's value, `serializeVisitor`). The worker removes any
|
|
12
|
+
* copy that arrives from outside, so a client can't send one itself.
|
|
13
|
+
*/
|
|
14
|
+
export const VISITOR_HEADER = "x-deco-visitor";
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A request's assignments (what its content gives it), decided once by the
|
|
3
|
+
* worker: the version it reads (a Studio link's draft or release SHA), each
|
|
4
|
+
* test of the saved `experiments` block on or off for its visitor and each
|
|
5
|
+
* campaign of the saved `campaigns` block running or not at its date, with a
|
|
6
|
+
* preview's switched tests and campaigns on top. The worker hands them to the
|
|
7
|
+
* page (`x-deco-assignments`) and to the site's `pageCache`
|
|
8
|
+
* (`page.assignments`), whose key carries them (`assignmentsKey`). Two
|
|
9
|
+
* requests with the same assignments render the same content, so they share
|
|
10
|
+
* a cache entry; the visitor id itself is never in the key, or every visitor
|
|
11
|
+
* would miss.
|
|
12
|
+
*
|
|
13
|
+
* Blocks decides (`cms.client({ visitor, version, … })`); this only reads
|
|
14
|
+
* the answers. A site without either block has no assignments and keys as
|
|
15
|
+
* before.
|
|
16
|
+
*/
|
|
17
|
+
import type { ClientOptions, CMS } from "@decocms/blocks";
|
|
18
|
+
import type { Assignments } from "@decocms/blocks/experiments";
|
|
19
|
+
import type { DecidedAssignments } from "../assignments.ts";
|
|
20
|
+
|
|
21
|
+
export interface RequestAssignments extends DecidedAssignments {
|
|
22
|
+
/** The version read, `null` for the current release. */
|
|
23
|
+
version: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const EXPERIMENTS = { block: "experiments", type: "split-traffic" } as const;
|
|
27
|
+
const CAMPAIGNS = { block: "campaigns", type: "calendar" } as const;
|
|
28
|
+
|
|
29
|
+
type Reader = ReturnType<CMS["client"]>;
|
|
30
|
+
|
|
31
|
+
/** Plain code-unit order, the same on every server and locale. */
|
|
32
|
+
const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
|
|
33
|
+
|
|
34
|
+
const record = (): Assignments => Object.create(null) as Assignments;
|
|
35
|
+
|
|
36
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
37
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Whether the content saves a block of `type`: listing never fails on a
|
|
42
|
+
* missing block, so a site without tests or campaigns reports no error.
|
|
43
|
+
*/
|
|
44
|
+
async function saves(client: Reader, type: string): Promise<boolean> {
|
|
45
|
+
const [list] = await client.list(type);
|
|
46
|
+
return (list?.length ?? 0) > 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The saved `block` resolved, each name `true` or `false`; none when it is missing. */
|
|
50
|
+
async function decided(
|
|
51
|
+
client: Reader,
|
|
52
|
+
spec: { block: string; type: string },
|
|
53
|
+
): Promise<Assignments> {
|
|
54
|
+
const out = record();
|
|
55
|
+
try {
|
|
56
|
+
if (!(await saves(client, spec.type))) return out;
|
|
57
|
+
const [value] = await client.resolve<unknown>(spec.block);
|
|
58
|
+
if (!isRecord(value)) return out;
|
|
59
|
+
for (const name of Object.keys(value).sort(byCodeUnit)) out[name] = value[name] === true;
|
|
60
|
+
} catch {
|
|
61
|
+
// Content that doesn't load gives no assignments.
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The assignments of one request: `cms.client(options)` (the version, the
|
|
68
|
+
* visitor, the date and a preview's switched tests and campaigns, as
|
|
69
|
+
* `cms.readVersion` reads them) resolving `experiments` and `campaigns`.
|
|
70
|
+
* Missing blocks (or content that doesn't load) give none, never an error.
|
|
71
|
+
*/
|
|
72
|
+
export async function readAssignments(
|
|
73
|
+
cms: Pick<CMS, "client">,
|
|
74
|
+
options: ClientOptions,
|
|
75
|
+
): Promise<RequestAssignments> {
|
|
76
|
+
const version = typeof options.version === "string" ? options.version : null;
|
|
77
|
+
let client: Reader;
|
|
78
|
+
try {
|
|
79
|
+
client = cms.client(options);
|
|
80
|
+
} catch {
|
|
81
|
+
return { version, experiments: record(), campaigns: record() };
|
|
82
|
+
}
|
|
83
|
+
const [experiments, campaigns] = await Promise.all([
|
|
84
|
+
decided(client, EXPERIMENTS),
|
|
85
|
+
decided(client, CAMPAIGNS),
|
|
86
|
+
]);
|
|
87
|
+
return { version, experiments, campaigns };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Every assignments key a live request can carry now, for a site's purge: each
|
|
92
|
+
* subset of the tests in the saved `experiments` block on (the empty one
|
|
93
|
+
* included), with the campaigns running now and with none. Previews are
|
|
94
|
+
* never cached, so no version. A site without either block has one: `""`.
|
|
95
|
+
*/
|
|
96
|
+
export async function liveAssignmentKeys(cms: Pick<CMS, "client">): Promise<string[]> {
|
|
97
|
+
let client: Reader;
|
|
98
|
+
try {
|
|
99
|
+
client = cms.client();
|
|
100
|
+
} catch {
|
|
101
|
+
return [""];
|
|
102
|
+
}
|
|
103
|
+
const [saved, campaigns] = await Promise.all([
|
|
104
|
+
decided(client, EXPERIMENTS),
|
|
105
|
+
decided(client, CAMPAIGNS),
|
|
106
|
+
]);
|
|
107
|
+
const tests = Object.keys(saved);
|
|
108
|
+
const running = Object.keys(campaigns).some((name) => campaigns[name] === true);
|
|
109
|
+
const campaignSets = running ? [campaigns, record()] : [record()];
|
|
110
|
+
const keys: string[] = [];
|
|
111
|
+
// Subsets by bitmask, tests in sorted order: 2^tests of them.
|
|
112
|
+
for (let mask = 0; mask < 2 ** tests.length; mask++) {
|
|
113
|
+
const experiments = record();
|
|
114
|
+
tests.forEach((name, i) => {
|
|
115
|
+
experiments[name] = Math.floor(mask / 2 ** i) % 2 === 1;
|
|
116
|
+
});
|
|
117
|
+
for (const set of campaignSets) {
|
|
118
|
+
keys.push(assignmentsKey({ version: null, experiments, campaigns: set }));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return keys;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The names that are on, sorted. */
|
|
125
|
+
function onNames(assignments: Readonly<Assignments>): string[] {
|
|
126
|
+
return Object.keys(assignments)
|
|
127
|
+
.filter((name) => assignments[name] === true)
|
|
128
|
+
.sort(byCodeUnit);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The assignments as one stable string for a cache key:
|
|
133
|
+
* `v=<version>|x=<tests on>|c=<campaigns running>`, names sorted and
|
|
134
|
+
* URL-encoded, empty parts left out; `""` for none. The names that are off
|
|
135
|
+
* aren't in it: within one content revision they are the rest.
|
|
136
|
+
*/
|
|
137
|
+
export function assignmentsKey(assignments: RequestAssignments): string {
|
|
138
|
+
const list = (names: string[]) => names.map(encodeURIComponent).join(",");
|
|
139
|
+
const parts: string[] = [];
|
|
140
|
+
if (assignments.version) parts.push(`v=${encodeURIComponent(assignments.version)}`);
|
|
141
|
+
const tests = onNames(assignments.experiments);
|
|
142
|
+
const campaigns = onNames(assignments.campaigns);
|
|
143
|
+
if (tests.length) parts.push(`x=${list(tests)}`);
|
|
144
|
+
if (campaigns.length) parts.push(`c=${list(campaigns)}`);
|
|
145
|
+
return parts.join("|");
|
|
146
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a site needs to build its own page cache in front of the worker (the
|
|
3
|
+
* README's worker-entry recipe): whether a request may be cached at all, the
|
|
4
|
+
* version every key carries, and the version (draft or old release) a request
|
|
5
|
+
* renders. The worker caches nothing itself.
|
|
6
|
+
*/
|
|
7
|
+
import type { CMS } from "@decocms/blocks";
|
|
8
|
+
import { VERSION_HEADER } from "../draft.ts";
|
|
9
|
+
import { hasDraftSignal } from "./drafts.ts";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Whether a request may be served from or stored in a shared cache at all:
|
|
13
|
+
* a GET of the current release (`version` `null`: never a preview, a draft
|
|
14
|
+
* or an old release), carrying no draft signal at all (no `?__draft=`, `off`
|
|
15
|
+
* included, and no draft cookie: a preview always renders), outside local
|
|
16
|
+
* development, without `Authorization`, and not one of TanStack Start's own
|
|
17
|
+
* `/_build` files. The worker calls a
|
|
18
|
+
* site's `pageCache` only for these.
|
|
19
|
+
*/
|
|
20
|
+
export function isCacheable(
|
|
21
|
+
request: Pick<Request, "method" | "url" | "headers">,
|
|
22
|
+
inputs: { version: string | null; dev?: boolean },
|
|
23
|
+
): boolean {
|
|
24
|
+
return (
|
|
25
|
+
request.method === "GET" &&
|
|
26
|
+
inputs.version === null &&
|
|
27
|
+
inputs.dev !== true &&
|
|
28
|
+
!request.headers.has("authorization") &&
|
|
29
|
+
!hasDraftSignal(request) &&
|
|
30
|
+
!new URL(request.url).pathname.startsWith("/_build")
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `<build>.<content revision>`, for every cache key: a new build or a
|
|
36
|
+
* published release gets new entries at once. The build alone when the
|
|
37
|
+
* revision can't be read.
|
|
38
|
+
*/
|
|
39
|
+
export async function cacheVersion(
|
|
40
|
+
cms: Pick<CMS, "forRelease">,
|
|
41
|
+
buildHash: string,
|
|
42
|
+
): Promise<string> {
|
|
43
|
+
let revision = "";
|
|
44
|
+
try {
|
|
45
|
+
revision = await cms.forRelease().revision();
|
|
46
|
+
} catch {
|
|
47
|
+
// The content didn't load: key on the build only.
|
|
48
|
+
}
|
|
49
|
+
return [buildHash, revision].filter(Boolean).join(".");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The version a request renders as the worker decided it (a Studio link's
|
|
54
|
+
* draft pointer or release SHA, after the host allowlist), from the
|
|
55
|
+
* `x-deco-version` header it sets; `null` for the current release. For the
|
|
56
|
+
* request a `routes` handler or `pageCache` gets: the worker removes any copy
|
|
57
|
+
* that arrives from outside.
|
|
58
|
+
*/
|
|
59
|
+
export function requestVersion(request: Pick<Request, "headers">): string | null {
|
|
60
|
+
return request.headers.get(VERSION_HEADER) || null;
|
|
61
|
+
}
|
package/src/worker/cookies.ts
CHANGED
|
@@ -1,30 +1,4 @@
|
|
|
1
|
-
/** Set-Cookie handling:
|
|
2
|
-
|
|
3
|
-
function cookieName(setCookie: string): string {
|
|
4
|
-
const eq = setCookie.indexOf("=");
|
|
5
|
-
return eq > 0 ? setCookie.slice(0, eq).trim() : "";
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
/** Whether every cookie the response sets is one a shared (cached) response may set. */
|
|
9
|
-
export function hasOnlySafeCookies(response: Response, safe: ReadonlySet<string>): boolean {
|
|
10
|
-
return response.headers.getSetCookie().every((c) => {
|
|
11
|
-
const name = cookieName(c);
|
|
12
|
-
return name === "" || safe.has(name);
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/** A copy for the cache without the safe cookies; the visitor still gets them. */
|
|
17
|
-
export function withoutSafeCookies(response: Response, safe: ReadonlySet<string>): Response {
|
|
18
|
-
const copy = response.clone();
|
|
19
|
-
const cookies = response.headers.getSetCookie();
|
|
20
|
-
if (cookies.length === 0) return copy;
|
|
21
|
-
copy.headers.delete("set-cookie");
|
|
22
|
-
for (const c of cookies) {
|
|
23
|
-
const name = cookieName(c);
|
|
24
|
-
if (name && !safe.has(name)) copy.headers.append("set-cookie", c);
|
|
25
|
-
}
|
|
26
|
-
return copy;
|
|
27
|
-
}
|
|
1
|
+
/** Set-Cookie handling: one header per cookie. */
|
|
28
2
|
|
|
29
3
|
/**
|
|
30
4
|
* A Set-Cookie's identity: name + Domain + Path, the way the browser keys its
|
package/src/worker/drafts.ts
CHANGED
|
@@ -1,84 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Which hosts may render drafts:
|
|
3
|
-
*
|
|
4
|
-
* `
|
|
5
|
-
* `
|
|
6
|
-
*
|
|
7
|
-
* - The site's own preview hosts: the ones it declares, in the `CMS` block or
|
|
8
|
-
* as `createCMS({ preview: { hosts } })` (matched as `cms.draftPointer`
|
|
9
|
-
* matches them). A site that declares none has none, as in v7: blocks'
|
|
10
|
-
* own default (every host) doesn't count as a declaration.
|
|
11
|
-
* - The hosts Deco runs the site on, named after the site and always added:
|
|
12
|
-
* `<site>.deco.site` and `<site>.deco-cx.workers.dev`, exact.
|
|
13
|
-
* - `previewHosts: [...]` replaces the site's own list (the inferred hosts are
|
|
14
|
-
* still added); `previewHosts: "none"` turns previews off on every host.
|
|
15
|
-
*
|
|
16
|
-
* Hosts compare exactly, lowercased, port included (`localhost:5173`).
|
|
2
|
+
* Which hosts may render drafts: the ones the CMS allows (`cms.readVersion`):
|
|
3
|
+
* the addresses Studio writes into the current release's metadata, plus
|
|
4
|
+
* `createCMS`'s `preview.hosts`; every host while the site has published no
|
|
5
|
+
* list, or with no `site` and no `preview.hosts`. The site declares nothing
|
|
6
|
+
* here (PO 2026-10-22).
|
|
17
7
|
*
|
|
18
8
|
* The draft itself is the capability: a host check only bounds where a draft
|
|
19
9
|
* link works. A request the check refuses gets the release, never an error.
|
|
10
|
+
*
|
|
11
|
+
* What a link carries is a version, as `cms.readVersion` reads it: a draft
|
|
12
|
+
* pointer, or a published release's commit SHA (Studio's "Preview this
|
|
13
|
+
* version"), with the preview's moment and switched tests and campaigns
|
|
14
|
+
* (`__at`, `__test`, `__campaign`; `parseVersion` from `@decocms/blocks`).
|
|
15
|
+
* Both pass the same host check: a visitor on the live site never picks a
|
|
16
|
+
* version.
|
|
20
17
|
*/
|
|
21
|
-
import { type CMS, parseDraftPointer } from "@decocms/blocks";
|
|
18
|
+
import { type CMS, parseDraftPointer, parseVersion, type RequestVersion } from "@decocms/blocks";
|
|
22
19
|
import { DRAFT_COOKIE, DRAFT_PARAM } from "../draft.ts";
|
|
23
20
|
|
|
24
|
-
export interface PreviewPolicy {
|
|
25
|
-
/** The site's name: `<site>.deco.site` and `<site>.deco-cx.workers.dev` may preview. */
|
|
26
|
-
site?: string;
|
|
27
|
-
/** Replaces the `CMS` block's preview hosts; `"none"` turns previews off everywhere. */
|
|
28
|
-
previewHosts?: readonly string[] | "none";
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** The hosts Deco runs `site` on, which may always preview (unless previews are off). */
|
|
32
|
-
export function inferredPreviewHosts(site: string | undefined): string[] {
|
|
33
|
-
const s = (site ?? "").trim().toLowerCase();
|
|
34
|
-
return s ? [`${s}.deco.site`, `${s}.deco-cx.workers.dev`] : [];
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Whether `host` may preview without asking the CMS: `true` (an override or
|
|
39
|
-
* inferred host), `false` (previews off, or the override leaves it out), or
|
|
40
|
-
* `"cms"` when only the site's declared preview hosts can say (none declared:
|
|
41
|
-
* `false`, see {@link declaresPreviewHosts}).
|
|
42
|
-
*/
|
|
43
|
-
export function previewHostDecision(host: string, policy: PreviewPolicy): boolean | "cms" {
|
|
44
|
-
const override =
|
|
45
|
-
policy.previewHosts === "none"
|
|
46
|
-
? ["none"]
|
|
47
|
-
: (policy.previewHosts ?? []).map((h) => h.trim().toLowerCase()).filter(Boolean);
|
|
48
|
-
if (override.includes("none")) return false;
|
|
49
|
-
const h = host.trim().toLowerCase();
|
|
50
|
-
if (h === "") return false;
|
|
51
|
-
if (inferredPreviewHosts(policy.site).includes(h)) return true;
|
|
52
|
-
if (policy.previewHosts !== undefined) return override.includes(h);
|
|
53
|
-
return "cms";
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Whether the site declares its own preview hosts: in the `CMS` block, or as
|
|
58
|
-
* `createCMS`'s `preview.hosts`. When it declares none, `cms.settings()`
|
|
59
|
-
* reports blocks' default, every host (`["*"]`), which v7 never had: there,
|
|
60
|
-
* a site without a list previewed only on its Deco hosts. The saved `CMS`
|
|
61
|
-
* block tells an explicit `["*"]` from that default.
|
|
62
|
-
*/
|
|
63
|
-
export async function declaresPreviewHosts(
|
|
64
|
-
cms: Pick<CMS, "settings" | "forRelease">,
|
|
65
|
-
): Promise<boolean> {
|
|
66
|
-
const { hosts } = (await cms.settings()).preview;
|
|
67
|
-
if (hosts.length !== 1 || hosts[0] !== "*") return true;
|
|
68
|
-
try {
|
|
69
|
-
const [block] = await cms.forRelease().resolve<unknown>("CMS", { run: false });
|
|
70
|
-
const preview = isRecord(block) ? block.preview : undefined;
|
|
71
|
-
return isRecord(preview) && ("hosts" in preview || "__resolveType" in preview);
|
|
72
|
-
} catch {
|
|
73
|
-
return false;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
78
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
21
|
const DRAFT_OFF = "off";
|
|
22
|
+
/** A draft pointer's version that names no draft: the release, nothing fetched. */
|
|
23
|
+
const LOCAL_VERSION = "local";
|
|
82
24
|
|
|
83
25
|
function draftParam(url: URL): string | null {
|
|
84
26
|
return url.searchParams.get(DRAFT_PARAM);
|
|
@@ -99,16 +41,35 @@ function readCookie(header: string | null, name: string): string | null {
|
|
|
99
41
|
}
|
|
100
42
|
|
|
101
43
|
/**
|
|
102
|
-
*
|
|
103
|
-
* first, then the draft cookie; `null` for `?__draft=off` and
|
|
104
|
-
* that doesn't parse.
|
|
44
|
+
* What a request's Studio link asks for, as `@decocms/blocks` reads it:
|
|
45
|
+
* `?__draft=` first, then the draft cookie; `null` for `?__draft=off` and
|
|
46
|
+
* for a value that doesn't parse.
|
|
105
47
|
*/
|
|
106
|
-
export function
|
|
48
|
+
export function readDraftVersion(request: Request): RequestVersion | null {
|
|
107
49
|
const param = draftParam(new URL(request.url));
|
|
108
50
|
if (param === DRAFT_OFF) return null;
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
return
|
|
51
|
+
const fromLink = param ? parseVersion(param) : null;
|
|
52
|
+
if (fromLink !== null) return fromLink;
|
|
53
|
+
return parseVersion(readCookie(request.headers.get("cookie"), DRAFT_COOKIE));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Whether a request carries a draft signal at all: `?__draft=` with any value
|
|
58
|
+
* (`off` and a value that doesn't parse too) or the draft cookie. Such a
|
|
59
|
+
* request is a preview: it never goes through a page cache and its response
|
|
60
|
+
* is never cached (`draftResponseHeaders`), whatever the host check decides.
|
|
61
|
+
*/
|
|
62
|
+
export function hasDraftSignal(request: Pick<Request, "url" | "headers">): boolean {
|
|
63
|
+
return (
|
|
64
|
+
draftParam(new URL(request.url)) !== null ||
|
|
65
|
+
readCookie(request.headers.get("cookie"), DRAFT_COOKIE) !== null
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Whether a version names a saved draft (a pointer, not a release's SHA and not `local`). */
|
|
70
|
+
function namesDraft(version: string): boolean {
|
|
71
|
+
const parsed = parseDraftPointer(version);
|
|
72
|
+
return parsed !== null && parsed.version !== LOCAL_VERSION;
|
|
112
73
|
}
|
|
113
74
|
|
|
114
75
|
function serializeCookie(value: string, extra: string[]): string {
|
|
@@ -125,33 +86,87 @@ function serializeCookie(value: string, extra: string[]): string {
|
|
|
125
86
|
}
|
|
126
87
|
|
|
127
88
|
export interface DraftDecision {
|
|
128
|
-
/**
|
|
129
|
-
|
|
130
|
-
|
|
89
|
+
/**
|
|
90
|
+
* What this request's Studio link asks for, after the host check: the
|
|
91
|
+
* version (a draft pointer, or a release's commit SHA) and the preview's
|
|
92
|
+
* moment and switched tests and campaigns, in the shape of
|
|
93
|
+
* `cms.client()`'s options; `null` for the current release.
|
|
94
|
+
*/
|
|
95
|
+
version: RequestVersion | null;
|
|
96
|
+
/**
|
|
97
|
+
* The `Set-Cookie` the response carries: storing a link's version (the
|
|
98
|
+
* worker sends it only with a response below 500), or ending a preview.
|
|
99
|
+
*/
|
|
131
100
|
setCookie: string | null;
|
|
101
|
+
/**
|
|
102
|
+
* The link named a draft that can't be read (deleted, or its host
|
|
103
|
+
* failing): the request renders the release, the cookie is expired when
|
|
104
|
+
* the draft is gone (a failure that may pass leaves it), and the page says so calmly (`DraftBadge`'s `unavailable`), never a 500.
|
|
105
|
+
*/
|
|
106
|
+
unavailable?: true;
|
|
107
|
+
/**
|
|
108
|
+
* The release check made for this draft request (`cms.checkRelease()`):
|
|
109
|
+
* the host check, the read below and the page's draft reads all wait for
|
|
110
|
+
* it, so the request reads `latest.json` once.
|
|
111
|
+
*/
|
|
112
|
+
releaseCheck?: string;
|
|
132
113
|
}
|
|
133
114
|
|
|
134
|
-
/**
|
|
115
|
+
/**
|
|
116
|
+
* The version a request renders, and the cookie its response sets. A draft
|
|
117
|
+
* request first checks for the latest release, once (`cms.checkRelease()`),
|
|
118
|
+
* and the host check and every draft read share that check. A draft
|
|
119
|
+
* pointer is read once before the page renders (`forDraft(...).revision()`,
|
|
120
|
+
* the same read the page makes, shared while in flight): a draft that can't
|
|
121
|
+
* be read gives the release and `unavailable`, never an error page.
|
|
122
|
+
*/
|
|
135
123
|
export async function decideDraft(
|
|
136
|
-
cms: Pick<CMS, "
|
|
124
|
+
cms: Pick<CMS, "readVersion" | "forDraft" | "checkRelease">,
|
|
137
125
|
request: Request,
|
|
138
|
-
policy: PreviewPolicy,
|
|
139
126
|
): Promise<DraftDecision> {
|
|
140
127
|
const url = new URL(request.url);
|
|
141
128
|
const param = draftParam(url);
|
|
142
129
|
// Ending a preview is allowed on any host, so a cookie set earlier always goes.
|
|
143
|
-
if (param === DRAFT_OFF) return {
|
|
144
|
-
const
|
|
145
|
-
if (
|
|
146
|
-
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if (
|
|
152
|
-
|
|
130
|
+
if (param === DRAFT_OFF) return { version: null, setCookie: expiredCookie() };
|
|
131
|
+
const version = readDraftVersion(request);
|
|
132
|
+
if (version === null) return { version: null, setCookie: null };
|
|
133
|
+
// One release check per draft request, shared below and by the page.
|
|
134
|
+
const releaseCheck = namesDraft(version.version) ? await cms.checkRelease() : undefined;
|
|
135
|
+
if ((await cms.readVersion(request, { releaseCheck })) === null) {
|
|
136
|
+
return { version: null, setCookie: null };
|
|
137
|
+
}
|
|
138
|
+
if (releaseCheck !== undefined) {
|
|
139
|
+
try {
|
|
140
|
+
await cms.forDraft(version.version, { releaseCheck }).revision();
|
|
141
|
+
} catch (error) {
|
|
142
|
+
// Gone (deleted): the preview ends. Any other failure (the drafts' host
|
|
143
|
+
// down, a timeout) leaves the cookie alone, so the next request tries again.
|
|
144
|
+
const setCookie = isDraftGone(error) ? expiredCookie() : null;
|
|
145
|
+
return { version: null, setCookie, unavailable: true };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// The link's own value goes in the cookie, its preview parameters with it.
|
|
149
|
+
const fromLink = param !== null && parseVersion(param) !== null;
|
|
153
150
|
return {
|
|
154
|
-
|
|
155
|
-
setCookie: fromLink ? serializeCookie(encodeURIComponent(
|
|
151
|
+
version,
|
|
152
|
+
setCookie: fromLink ? serializeCookie(encodeURIComponent(param), []) : null,
|
|
153
|
+
...(releaseCheck === undefined ? {} : { releaseCheck }),
|
|
156
154
|
};
|
|
157
155
|
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Whether a draft read failed because the drafts' host no longer has the
|
|
159
|
+
* draft (`404`/`410`), as opposed to a failure that may pass (a `5xx`, a
|
|
160
|
+
* timeout, a network error). Reads the error and its causes.
|
|
161
|
+
*/
|
|
162
|
+
function isDraftGone(error: unknown): boolean {
|
|
163
|
+
for (let e = error, depth = 0; e instanceof Error && depth < 5; e = e.cause, depth++) {
|
|
164
|
+
if (/draft changes: HTTP (404|410)\b/.test(e.message)) return true;
|
|
165
|
+
}
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The `Set-Cookie` that ends a preview. */
|
|
170
|
+
function expiredCookie(): string {
|
|
171
|
+
return serializeCookie("", ["Max-Age=0"]);
|
|
172
|
+
}
|