@decocms/tanstack 8.5.1 → 8.6.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.
Files changed (76) hide show
  1. package/README.md +35 -8
  2. package/dist/assignments.d.ts +31 -0
  3. package/dist/assignments.d.ts.map +1 -0
  4. package/dist/assignments.js +61 -0
  5. package/dist/assignments.js.map +1 -0
  6. package/dist/draft.d.ts +9 -6
  7. package/dist/draft.d.ts.map +1 -1
  8. package/dist/draft.js +10 -7
  9. package/dist/draft.js.map +1 -1
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/scope/server.d.ts +1 -1
  15. package/dist/scope/server.d.ts.map +1 -1
  16. package/dist/server/index.d.ts +35 -8
  17. package/dist/server/index.d.ts.map +1 -1
  18. package/dist/server/index.js +41 -9
  19. package/dist/server/index.js.map +1 -1
  20. package/dist/shared.d.ts +5 -5
  21. package/dist/shared.js +5 -5
  22. package/dist/start/index.d.ts +3 -3
  23. package/dist/start/index.js +3 -3
  24. package/dist/visitor.d.ts +14 -0
  25. package/dist/visitor.d.ts.map +1 -0
  26. package/dist/visitor.js +14 -0
  27. package/dist/visitor.js.map +1 -0
  28. package/dist/worker/assignments.d.ts +44 -0
  29. package/dist/worker/assignments.d.ts.map +1 -0
  30. package/dist/worker/assignments.js +114 -0
  31. package/dist/worker/assignments.js.map +1 -0
  32. package/dist/worker/cache.d.ts +33 -0
  33. package/dist/worker/cache.d.ts.map +1 -0
  34. package/dist/worker/cache.js +41 -0
  35. package/dist/worker/cache.js.map +1 -0
  36. package/dist/worker/cookies.d.ts +1 -5
  37. package/dist/worker/cookies.d.ts.map +1 -1
  38. package/dist/worker/cookies.js +1 -26
  39. package/dist/worker/cookies.js.map +1 -1
  40. package/dist/worker/drafts.d.ts +27 -48
  41. package/dist/worker/drafts.d.ts.map +1 -1
  42. package/dist/worker/drafts.js +33 -88
  43. package/dist/worker/drafts.js.map +1 -1
  44. package/dist/worker/index.d.ts +77 -51
  45. package/dist/worker/index.d.ts.map +1 -1
  46. package/dist/worker/index.js +141 -360
  47. package/dist/worker/index.js.map +1 -1
  48. package/dist/worker/segment.d.ts +7 -6
  49. package/dist/worker/segment.d.ts.map +1 -1
  50. package/dist/worker/segment.js +6 -5
  51. package/dist/worker/segment.js.map +1 -1
  52. package/dist/worker/serverFn.d.ts +12 -0
  53. package/dist/worker/serverFn.d.ts.map +1 -0
  54. package/dist/worker/serverFn.js +44 -0
  55. package/dist/worker/serverFn.js.map +1 -0
  56. package/package.json +3 -3
  57. package/src/assignments.ts +77 -0
  58. package/src/draft.ts +10 -7
  59. package/src/index.ts +3 -1
  60. package/src/scope/server.ts +1 -1
  61. package/src/server/index.ts +51 -12
  62. package/src/shared.ts +5 -5
  63. package/src/start/index.ts +3 -3
  64. package/src/visitor.ts +14 -0
  65. package/src/worker/assignments.ts +146 -0
  66. package/src/worker/cache.ts +57 -0
  67. package/src/worker/cookies.ts +1 -27
  68. package/src/worker/drafts.ts +38 -98
  69. package/src/worker/index.ts +213 -425
  70. package/src/worker/segment.ts +7 -7
  71. package/src/worker/serverFn.ts +36 -0
  72. package/dist/worker/cacheProfiles.d.ts +0 -43
  73. package/dist/worker/cacheProfiles.d.ts.map +0 -1
  74. package/dist/worker/cacheProfiles.js +0 -162
  75. package/dist/worker/cacheProfiles.js.map +0 -1
  76. package/src/worker/cacheProfiles.ts +0 -180
@@ -5,51 +5,67 @@
5
5
  *
6
6
  * - `/deco/_liveness` answers `OK`; v7's admin paths (`/deco/*`, `/live/*`,
7
7
  * `/.decofile`) answer 404.
8
- * - Drafts: the host allowlist (`./drafts.ts`), the draft cookie, the
9
- * `x-deco-draft` request header the page reads, and on the response
10
- * `no-store`, `Vary: Cookie` and `noindex`. Only a real draft skips the cache.
8
+ * - Versions: the host allowlist (`./drafts.ts`) for a Studio link's version
9
+ * (a draft, or a published release by its commit SHA, with the preview's
10
+ * moment and switched tests and campaigns), the draft cookie, the
11
+ * `x-deco-version` request header the page reads, and on the response
12
+ * `no-store`, `Vary: Cookie` and `noindex`.
11
13
  * - The CMS redirects, before any route.
12
- * - An edge cache (the Cloudflare Cache API) keyed by URL, device, the site's
13
- * segment parts and `<build>.<content revision>`, with stale-while-revalidate
14
- * and stale-if-error; logged-in, private and degraded responses never stored.
15
- * - CDN caching of client-side navigation data whose `__cseg` token checks out;
16
- * every other response tells the CDN `no-store`, at one exit.
14
+ * - No page cache: caching is the site's (`pageCache`, the README's
15
+ * worker-entry recipe), with the helpers it needs exported here
16
+ * (`assignmentsKey`, `cacheVersion`, `isCacheable`, …).
17
+ * The worker calls `pageCache` only for a request `isCacheable` accepts,
18
+ * never for a preview, and adds the visitor's cookie after it, so a stored
19
+ * copy never carries one. A page request with `Authorization` is never
20
+ * handed to it and answers `private, no-cache, no-store`. A response with no
21
+ * `CDN-Cache-Control` tells the CDN `no-store`, at one exit.
17
22
  * - Security headers and `frame-ancestors` for Studio; immutable fingerprinted
18
23
  * assets; one `Set-Cookie` per cookie; `x-page-status`.
24
+ * - The visitor: on a page or server-function request, `readVisitor` from
25
+ * `@decocms/blocks/experiments` (the `deco_segment` cookie, or a new
26
+ * visitor), handed to the app on `x-deco-visitor`; the cookie is sent on a
27
+ * first visit only, never from a preview.
28
+ * - What the request's content gives it, decided once per request: each test
29
+ * and campaign on or off (`readAssignments`: `cms.client({ visitor,
30
+ * version, date, experiments, campaigns })` with the visitor and the Studio
31
+ * link's version, moment and switched tests and campaigns), handed to the
32
+ * site's `pageCache` (`page.assignments`, for its key) and to the app on
33
+ * `x-deco-assignments` (`contentClient` builds
34
+ * `cms.client({ version, experiments, campaigns })` from it, deciding
35
+ * nothing again).
19
36
  * - `http.server.request.duration` for every request, to the CMS's telemetry
20
37
  * (`recordServerRequest` from `@decocms/blocks/metrics`), labelled with the route's template, the
21
- * method, the status class, the cache decision and the device; nothing
22
- * when the CMS has no telemetry.
38
+ * method, the status class, the cache decision (the `X-Cache` the site's
39
+ * `pageCache` answered with) and the device; nothing when the CMS has no
40
+ * telemetry.
23
41
  */
24
42
  import { type CMS, matchRoute, type Redirect, type Route } from "@decocms/blocks";
43
+ import { readVisitor, serializeVisitor, type Visitor } from "@decocms/blocks/experiments";
25
44
  import { recordServerRequest } from "@decocms/blocks/metrics";
26
45
  import { runInScope } from "@decocms/tanstack/scope";
27
- import { DRAFT_HEADER, draftResponseHeaders } from "../draft.ts";
28
- import { CSEG_PARAM, DEGRADED_HEADER, PAGE_STATUS_HEADER } from "../shared.ts";
29
- import {
30
- type CacheProfileName,
31
- type CacheProfileOverrides,
32
- cacheControl,
33
- canonicalizeServerFnPayload,
34
- isServerFnPath,
35
- PRIVATE_NO_CACHE,
36
- profileOf,
37
- resolveProfiles,
38
- } from "./cacheProfiles.ts";
39
- import { dedupeSetCookies, hasOnlySafeCookies, withoutSafeCookies } from "./cookies.ts";
40
- import { decideDraft, type PreviewPolicy } from "./drafts.ts";
46
+ import { ASSIGNMENTS_HEADER, serializeAssignments } from "../assignments.ts";
47
+ import { draftResponseHeaders, VERSION_HEADER } from "../draft.ts";
48
+ import { PAGE_STATUS_HEADER } from "../shared.ts";
49
+ import { VISITOR_HEADER } from "../visitor.ts";
50
+ import { type RequestAssignments, readAssignments } from "./assignments.ts";
51
+ import { isCacheable } from "./cache.ts";
52
+ import { dedupeSetCookies } from "./cookies.ts";
53
+ import { type DraftDecision, decideDraft } from "./drafts.ts";
41
54
  import { type CspOptions, htmlSecurityHeaders } from "./security.ts";
42
- import { DEVICES, detectDevice, type Segment, segmentKey, segmentToken } from "./segment.ts";
43
-
44
- export type {
45
- CacheProfile,
46
- CacheProfileName,
47
- CacheProfileOverrides,
48
- CacheWindow,
49
- } from "./cacheProfiles.ts";
50
- export { DEFAULT_CACHE_PROFILES } from "./cacheProfiles.ts";
55
+ import { type Device, detectDevice } from "./segment.ts";
56
+ import { isServerFnPath } from "./serverFn.ts";
57
+
58
+ export { CSEG_PARAM, DEGRADED_HEADER } from "../shared.ts";
59
+ export {
60
+ assignmentsKey,
61
+ liveAssignmentKeys,
62
+ type RequestAssignments,
63
+ readAssignments,
64
+ } from "./assignments.ts";
65
+ export { cacheVersion, isCacheable, requestVersion } from "./cache.ts";
51
66
  export type { CspOptions } from "./security.ts";
52
- export type { Device, Segment } from "./segment.ts";
67
+ export { type Device, detectDevice, type Segment, segmentKey, segmentToken } from "./segment.ts";
68
+ export { isServerFnPath, serverFnPagePath } from "./serverFn.ts";
53
69
 
54
70
  /** The part of Cloudflare's `ExecutionContext` the worker uses. */
55
71
  export interface ExecutionContextLike {
@@ -65,58 +81,62 @@ export interface ServerEntry {
65
81
  fetch(request: Request, env?: any, ctx?: any): Response | Promise<Response>;
66
82
  }
67
83
 
68
- /** What the edge cache did with a request (`X-Cache`). */
69
- export type CacheDecision = "HIT" | "STALE-HIT" | "STALE-ERROR" | "MISS" | "BYPASS";
70
-
71
- /** One page or server-function request, for `onCache`. */
72
- export interface CacheEvent {
73
- /** The page type (cache profile) the URL maps to. */
74
- profile: CacheProfileName;
75
- decision: CacheDecision;
76
- /** Milliseconds from the request to the response's headers. */
77
- ms: number;
78
- status: number;
84
+ /**
85
+ * A page or server-function request the site's `pageCache` may answer from
86
+ * its own cache: always one `isCacheable` accepts (a GET of the current
87
+ * release, never a preview).
88
+ */
89
+ export interface PageRequest<Env = unknown> {
90
+ /** The request as the app gets it: the visitor and the assignments on their headers. */
91
+ request: Request;
92
+ url: URL;
93
+ /** The visitor the worker read (`readVisitor`). */
94
+ visitor: Visitor;
95
+ /**
96
+ * Each test and campaign on or off for this request, as the worker decided
97
+ * them and the page renders them: key the cache on `assignmentsKey(page.assignments)`.
98
+ */
99
+ assignments: RequestAssignments;
100
+ /** The request's device class, from its user agent. */
101
+ device: Device;
102
+ env: Env;
103
+ ctx: ExecutionContextLike;
104
+ /**
105
+ * Renders the page: the app's response, with `x-page-status` applied and
106
+ * without the visitor's cookie (the worker adds it to whatever `pageCache`
107
+ * answers). `csegToken` is the `__cseg` token `DecoDocument` publishes and
108
+ * `decoServerFnFetch` sends back on the page's navigation data.
109
+ */
110
+ render(scope?: { csegToken?: string }): Promise<Response>;
79
111
  }
80
112
 
113
+ /**
114
+ * The site's page cache: answers a page from its own cache, or calls
115
+ * `page.render()`. Set `X-Cache` (`HIT`, `STALE-HIT`, `STALE-ERROR`, `MISS`)
116
+ * on the answer and the request's metric counts it.
117
+ */
118
+ export type PageCache<Env = unknown> = (page: PageRequest<Env>) => Promise<Response>;
119
+
81
120
  export interface DecoWorkerOptions<Env = unknown> {
82
121
  serverEntry: ServerEntry;
83
- /** The site's CMS: drafts, the content revision in the cache key, CMS redirects. */
122
+ /** The site's CMS: drafts, the CMS redirects, the page templates of the request metric. */
84
123
  cms: CMS;
85
- /** The site's name: `<site>.deco.site` and `<site>.deco-cx.workers.dev` may preview drafts. */
86
- site: string;
87
- /** The build's id, in every cache key: the commit sha (`decoTanstack()` defines `__BUILD_HASH__`). */
88
- buildHash: string;
89
- /** Local development (`import.meta.env.DEV`): no edge cache, `no-cache` pages, loopback may frame the site. */
124
+ /** Local development (`import.meta.env.DEV`): `pageCache` is never called, loopback may frame the site. */
90
125
  dev?: boolean;
91
126
  /** The site's Content-Security-Policy. Studio's `frame-ancestors` is always added. */
92
127
  csp?: CspOptions;
93
128
  /**
94
- * More cache-key parts for a request (a region, a sales channel, an A/B
95
- * cohort), merged over `{ device }` (`mobile`, `tablet` or `desktop`; return
96
- * your own `device` to merge classes). Return `"private"` for a request that
97
- * must never share a cached response (a signed-in shopper).
129
+ * The site's own page cache (the example worker entry the README links), called for
130
+ * every page and server-function request `isCacheable` accepts. Without
131
+ * it nothing is cached: every request renders.
98
132
  */
99
- segment?: (request: Request) => Record<string, string | undefined> | "private";
100
- /** Changes to the default cache profiles (`DEFAULT_CACHE_PROFILES`). */
101
- cacheProfiles?: CacheProfileOverrides;
102
- /** Cookies a cached response may set (stripped from the stored copy). Default: `_deco_bucket`. */
103
- safeCookies?: readonly string[];
104
- /** Turns on `POST /_cache/purge` with `Authorization: Bearer <token>`. */
105
- purgeToken?: (env: Env) => string | undefined;
133
+ pageCache?: PageCache<Env>;
106
134
  /**
107
135
  * `Link: rel=preload` hints on every HTML response the app renders. A
108
136
  * `routes` response carries none: it is another origin's page (a proxied
109
137
  * checkout, an A/B test's other site), and these are this app's assets.
110
138
  */
111
139
  preload?: { styles?: readonly string[]; fonts?: readonly string[] };
112
- /**
113
- * v7's `DECO_ALLOWED_PREVIEW_HOSTS`: replaces the site's declared preview
114
- * hosts (the `CMS` block's), exact hosts with their port
115
- * (`["localhost:5173"]` for local development); the site's Deco hosts stay
116
- * allowed. `"none"` turns draft previews off on every host. Without it and
117
- * without hosts in the `CMS` block, drafts preview only on the Deco hosts.
118
- */
119
- previewHosts?: readonly string[] | "none";
120
140
  /**
121
141
  * The escape hatch, after the CMS redirects and before anything else: answer
122
142
  * a request yourself (a commerce proxy, a sitemap, an A/B route) or return
@@ -129,8 +149,6 @@ export interface DecoWorkerOptions<Env = unknown> {
129
149
  env: Env,
130
150
  ctx: ExecutionContextLike,
131
151
  ) => Response | null | undefined | Promise<Response | null | undefined>;
132
- /** Called once per page or server-function request (D3: no exporter is built in). */
133
- onCache?: (event: CacheEvent) => void;
134
152
  }
135
153
 
136
154
  export interface DecoWorker<Env> {
@@ -140,37 +158,12 @@ export interface DecoWorker<Env> {
140
158
  const LIVENESS_PATH = "/deco/_liveness";
141
159
  /** v7's admin protocol paths: v8 sites serve none of them. */
142
160
  const REMOVED_ADMIN_PATHS = ["/deco/", "/live/", "/.decofile"];
143
- const PURGE_PATH = "/_cache/purge";
144
161
  const BYPASS_PATHS = ["/_build"];
145
162
  const STATIC_PATHS = ["/fonts/"];
146
163
  const FINGERPRINTED_ASSET_RE = /(?:\/_build)?\/assets\/.*-[a-zA-Z0-9_-]{8,}\.\w+$/;
147
- /** Query parameters that never change a page, left out of its cache key (v7's list). */
148
- const TRACKING_PARAMS = new Set([
149
- "utm_source",
150
- "utm_medium",
151
- "utm_campaign",
152
- "utm_term",
153
- "utm_content",
154
- "utmi_campaign",
155
- "utmi_page",
156
- "utmi_part",
157
- "fbclid",
158
- "gclid",
159
- "gclsrc",
160
- "dclid",
161
- "msclkid",
162
- "twclid",
163
- "li_fat_id",
164
- "mc_cid",
165
- "mc_eid",
166
- "ttclid",
167
- "srsltid",
168
- ]);
169
- const DEFAULT_SAFE_COOKIES = ["_deco_bucket"];
170
- const STORED_AT = "X-Deco-Stored-At";
171
- const DECISIONS = new Set<string>(["HIT", "STALE-HIT", "STALE-ERROR", "MISS", "BYPASS"]);
164
+ const PRIVATE_NO_CACHE = "private, no-cache, no-store, must-revalidate";
172
165
  /** Paths the worker (or TanStack Start) serves under a fixed template, for `http.route`. */
173
- const FIXED_ROUTES = [LIVENESS_PATH, PURGE_PATH];
166
+ const FIXED_ROUTES = [LIVENESS_PATH];
174
167
  const PREFIX_ROUTES = ["/_serverFn/", "/_server/", "/_build/", "/assets/", "/fonts/"];
175
168
 
176
169
  /** The template of a path the worker knows without the content, or `null`. */
@@ -188,18 +181,18 @@ function fixedRoute(pathname: string): string | null {
188
181
  const REDIRECT_ROUTE = "redirect";
189
182
 
190
183
  /**
191
- * The cache label of `http.server.request.duration`: the worker's own
192
- * decision. A response that never went through the edge cache (no cache
193
- * profile: a redirect, the site's `routes`, an asset) is `BYPASS` whatever
194
- * `X-Cache` an upstream put on it.
184
+ * The cache label of `http.server.request.duration`: `DRAFT` for a preview,
185
+ * otherwise what the site's `pageCache` said in `X-Cache`. A response that
186
+ * never went through it (a redirect, the site's `routes`, an asset, a page
187
+ * without a `pageCache`) is `BYPASS` whatever `X-Cache` an upstream put on it.
195
188
  */
196
189
  function cacheLabel(
197
190
  response: Response,
198
191
  draft: boolean,
199
- served: { profile?: unknown } | undefined,
192
+ served: { cached?: true } | undefined,
200
193
  ): "HIT" | "MISS" | "BYPASS" | "DRAFT" {
201
194
  if (draft) return "DRAFT";
202
- if (!served?.profile) return "BYPASS";
195
+ if (!served?.cached) return "BYPASS";
203
196
  const xCache = response.headers.get("X-Cache");
204
197
  if (xCache === "HIT" || xCache === "STALE-HIT" || xCache === "STALE-ERROR") return "HIT";
205
198
  return xCache === "MISS" ? "MISS" : "BYPASS";
@@ -207,12 +200,6 @@ function cacheLabel(
207
200
 
208
201
  const isHtml = (r: Response) => (r.headers.get("content-type") ?? "").includes("text/html");
209
202
 
210
- function edgeCache(): Cache | null {
211
- return typeof caches !== "undefined"
212
- ? ((caches as unknown as { default?: Cache }).default ?? null)
213
- : null;
214
- }
215
-
216
203
  /** The origin's response with the page's own status (`x-page-status`) applied. */
217
204
  function withPageStatus(response: Response): Response {
218
205
  const status = Number(response.headers.get(PAGE_STATUS_HEADER));
@@ -222,14 +209,6 @@ function withPageStatus(response: Response): Response {
222
209
  return new Response(response.body, { status, headers });
223
210
  }
224
211
 
225
- function isPrivateResponse(response: Response): boolean {
226
- return /\b(private|no-store)\b/i.test(response.headers.get("cache-control") ?? "");
227
- }
228
-
229
- function isDegraded(response: Response): boolean {
230
- return response.headers.get(DEGRADED_HEADER) === "true";
231
- }
232
-
233
212
  /** Adds `value` to the response's `Vary`, keeping what the origin listed. */
234
213
  function appendVary(headers: Headers, value: string): void {
235
214
  const current = headers.get("vary");
@@ -243,114 +222,15 @@ function mutable(response: Response): Response {
243
222
  return new Response(response.body, response);
244
223
  }
245
224
 
246
- function bypass(response: Response, reason: string, cacheControlValue?: string): Response {
247
- const out = mutable(response);
248
- if (cacheControlValue) {
249
- out.headers.set("Cache-Control", cacheControlValue);
250
- out.headers.delete("CDN-Cache-Control");
251
- }
252
- out.headers.set("X-Cache", "BYPASS");
253
- out.headers.set("X-Cache-Reason", reason);
254
- return out;
255
- }
256
-
257
225
  export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>): DecoWorker<Env> {
258
226
  const { cms, serverEntry } = options;
259
227
  const dev = options.dev === true;
260
- const profiles = resolveProfiles(options.cacheProfiles);
261
- const safeCookies = new Set(options.safeCookies ?? DEFAULT_SAFE_COOKIES);
262
228
  const securityHeaders = htmlSecurityHeaders(options.csp, dev);
263
- const policy: PreviewPolicy = { site: options.site, previewHosts: options.previewHosts };
264
229
  const preloadLinks = [
265
230
  ...(options.preload?.styles ?? []).map((href) => `<${href}>; rel=preload; as=style`),
266
231
  ...(options.preload?.fonts ?? []).map((href) => `<${href}>; rel=preload; as=font; crossorigin`),
267
232
  ];
268
233
 
269
- /** `<build>.<revision>`: a published release gets new entries at once; the build alone when the revision can't be read. */
270
- async function cacheVersion(): Promise<string> {
271
- let revision = "";
272
- try {
273
- revision = await cms.forRelease().revision();
274
- } catch {
275
- // The content didn't load: key on the build only.
276
- }
277
- return [options.buildHash, revision].filter(Boolean).join(".");
278
- }
279
-
280
- function segmentOf(request: Request): Segment | "private" {
281
- const base = { device: detectDevice(request.headers.get("user-agent") ?? "") };
282
- const extra = options.segment?.(request);
283
- if (extra === "private") return "private";
284
- const out: Record<string, string> = { ...base };
285
- for (const [k, v] of Object.entries(extra ?? {})) {
286
- if (v === undefined || v === "") delete out[k];
287
- else out[k] = v;
288
- }
289
- return out;
290
- }
291
-
292
- function cacheKey(url: URL, request: Request, version: string, segment: Segment): Request {
293
- const key = new URL(url);
294
- for (const name of [...key.searchParams.keys()]) {
295
- if (TRACKING_PARAMS.has(name.toLowerCase())) key.searchParams.delete(name);
296
- }
297
- key.searchParams.delete(CSEG_PARAM);
298
- const serverFn = isServerFnPath(key.pathname);
299
- if (serverFn) {
300
- const payload = key.searchParams.get("payload");
301
- if (payload) key.searchParams.set("payload", canonicalizeServerFnPayload(payload));
302
- }
303
- if (version) key.searchParams.set("__v", version);
304
- // Programmatic fetches (no navigation) get their own entries, as in v7.
305
- if (!serverFn && request.headers.get("sec-fetch-dest") === "empty") {
306
- key.searchParams.set("__fetch", "1");
307
- }
308
- key.searchParams.set("__seg", segmentKey(segment));
309
- return new Request(key.toString(), { method: "GET" });
310
- }
311
-
312
- async function purge(request: Request, env: Env): Promise<Response> {
313
- const token = options.purgeToken?.(env);
314
- if (!token || request.headers.get("Authorization") !== `Bearer ${token}`) {
315
- return new Response("Unauthorized", { status: 401 });
316
- }
317
- let body: { paths?: unknown; segments?: unknown };
318
- try {
319
- body = await request.json();
320
- } catch {
321
- return new Response("Invalid JSON body", { status: 400 });
322
- }
323
- const paths = Array.isArray(body.paths)
324
- ? body.paths.filter((p): p is string => typeof p === "string" && p.startsWith("/"))
325
- : [];
326
- if (paths.length === 0) {
327
- return new Response('Body must include "paths": ["/", "/page"]', { status: 400 });
328
- }
329
- // Each segment to drop: the devices by default; a site with more parts lists its own.
330
- const segments: Segment[] = Array.isArray(body.segments)
331
- ? body.segments.filter((s): s is Segment => !!s && typeof s === "object")
332
- : DEVICES.map((device) => ({ device }));
333
- const cache = edgeCache();
334
- if (!cache) return Response.json({ purged: [], total: 0, note: "Cache API unavailable" });
335
- const origin = new URL(request.url).origin;
336
- // The current version's entries: older versions' keys are no longer looked up.
337
- const version = await cacheVersion();
338
- const purged: string[] = [];
339
- for (const path of paths) {
340
- for (const segment of segments) {
341
- for (const programmatic of [false, true]) {
342
- const url = new URL(path, origin);
343
- const headers = programmatic ? { "sec-fetch-dest": "empty" } : undefined;
344
- const key = cacheKey(url, new Request(url, { headers }), version, segment);
345
- if (await cache.delete(key)) {
346
- purged.push(`${path} (${segmentKey(segment)}${programmatic ? ", fetch" : ""})`);
347
- }
348
- }
349
- }
350
- }
351
- return Response.json({ purged, total: purged.length });
352
- }
353
-
354
234
  // The release's redirects, read once per revision (a draft's are read each time).
355
235
  let releaseRedirects: { revision: string; list: Promise<Redirect[]> } | undefined;
356
236
 
@@ -359,8 +239,8 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
359
239
  const [list] = await client.list<Redirect>("redirect");
360
240
  return list ?? [];
361
241
  };
362
- if (pointer) return read(cms.forDraft(pointer));
363
- const client = cms.forRelease();
242
+ if (pointer) return read(cms.client({ version: pointer }));
243
+ const client = cms.client();
364
244
  const revision = await client.revision();
365
245
  if (releaseRedirects?.revision !== revision) {
366
246
  releaseRedirects = { revision, list: read(client) };
@@ -447,19 +327,56 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
447
327
 
448
328
  interface Served {
449
329
  response: Response;
450
- profile?: CacheProfileName;
330
+ /** Answered by the site's `pageCache`: its `X-Cache` labels the metric. */
331
+ cached?: true;
451
332
  /** Answered by the site's `routes`: not this app's page, so no `preload` hints. */
452
333
  routed?: true;
453
334
  /** A CMS redirect. */
454
335
  redirect?: true;
336
+ /** The visitor's `deco_segment` cookie, on a first visit to the live site. */
337
+ visitorCookie?: string;
338
+ }
339
+
340
+ /**
341
+ * What a page or server-function request reads, decided once: the visitor
342
+ * (`readVisitor`: the `deco_segment` cookie, or a new visitor) on
343
+ * `x-deco-visitor`, each test and campaign on or off for it and the
344
+ * request's version (`readAssignments`) on `x-deco-assignments`, and the
345
+ * cookie to send when the visitor had no id. A preview (a draft, or an old
346
+ * release) sends no cookie: Studio is not a visitor.
347
+ */
348
+ async function withDecisions(
349
+ request: Request,
350
+ draft: DraftDecision,
351
+ ): Promise<{
352
+ request: Request;
353
+ visitor: Visitor | null;
354
+ assignments?: RequestAssignments;
355
+ visitorCookie?: string;
356
+ }> {
357
+ // TanStack Start's own build files render no content.
358
+ if (BYPASS_PATHS.some((p) => new URL(request.url).pathname.startsWith(p))) {
359
+ return { request, visitor: null };
360
+ }
361
+ const { visitor, cookie } = readVisitor(request);
362
+ const assignments = await readAssignments(cms, { visitor, ...draft.version });
363
+ const headers = new Headers(request.headers);
364
+ headers.set(VISITOR_HEADER, serializeVisitor(visitor));
365
+ headers.set(ASSIGNMENTS_HEADER, serializeAssignments(assignments));
366
+ const forwarded = new Request(request, { headers });
367
+ if (cookie === null || draft.version !== null) {
368
+ return { request: forwarded, visitor, assignments };
369
+ }
370
+ return { request: forwarded, visitor, assignments, visitorCookie: cookie };
455
371
  }
456
372
 
457
373
  async function handle(
458
374
  request: Request,
459
375
  env: Env,
460
376
  ctx: ExecutionContextLike,
461
- draft: string | null,
377
+ decision: DraftDecision,
462
378
  ): Promise<Served> {
379
+ const draft = decision.version?.version ?? null;
463
380
  const url = new URL(request.url);
464
381
  const method = request.method;
465
382
  const readOnly = method === "GET" || method === "HEAD";
@@ -470,7 +387,6 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
470
387
  headers: {
471
388
  "Content-Type": "text/plain",
472
389
  "Cache-Control": PRIVATE_NO_CACHE,
473
- "X-Cache": "BYPASS",
474
390
  },
475
391
  }),
476
392
  };
@@ -479,13 +395,10 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
479
395
  return {
480
396
  response: new Response("Not Found", {
481
397
  status: 404,
482
- headers: { "Cache-Control": PRIVATE_NO_CACHE, "X-Cache": "BYPASS" },
398
+ headers: { "Cache-Control": PRIVATE_NO_CACHE },
483
399
  }),
484
400
  };
485
401
  }
486
- if (url.pathname === PURGE_PATH && method === "POST")
487
- return { response: await purge(request, env) };
488
-
489
402
  const asset =
490
403
  FINGERPRINTED_ASSET_RE.test(url.pathname) ||
491
404
  STATIC_PATHS.some((p) => url.pathname.startsWith(p));
@@ -515,222 +428,111 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
515
428
  return { response: resp };
516
429
  }
517
430
 
518
- const profileName = profileOf(url);
519
- const profile = profiles[profileName];
520
- const segment = segmentOf(request);
521
- const cacheable =
522
- method === "GET" &&
523
- !dev &&
524
- draft === null &&
525
- segment !== "private" &&
526
- !request.headers.has("authorization") &&
527
- !BYPASS_PATHS.some((p) => url.pathname.startsWith(p));
528
- const version = cacheable ? await cacheVersion() : "";
529
- const token = cacheable ? segmentToken(segment as Segment, version) : null;
530
- const origin = async (): Promise<Response> =>
431
+ const visited = await withDecisions(request, decision);
432
+ const served = await page(
433
+ visited.request,
434
+ env,
435
+ ctx,
436
+ draft,
437
+ url,
438
+ visited.visitor,
439
+ visited.assignments,
440
+ );
441
+ return visited.visitorCookie === undefined
442
+ ? served
443
+ : { ...served, visitorCookie: visited.visitorCookie };
444
+ }
445
+
446
+ /** A page or server-function request: the site's `pageCache` when it may cache it, else the app. */
447
+ async function page(
448
+ request: Request,
449
+ env: Env,
450
+ ctx: ExecutionContextLike,
451
+ draft: string | null,
452
+ url: URL,
453
+ visitor: Visitor | null,
454
+ assignments: RequestAssignments | undefined,
455
+ ): Promise<Served> {
456
+ const render = async (scope?: { csegToken?: string }): Promise<Response> =>
531
457
  withPageStatus(
532
- await runInScope({ csegToken: token ?? undefined, draft: draft ?? undefined }, () =>
458
+ await runInScope({ csegToken: scope?.csegToken, draft: draft ?? undefined }, () =>
533
459
  serverEntry.fetch(request, env, ctx),
534
460
  ),
535
461
  );
536
462
 
537
- if (!cacheable) {
538
- const resp = await origin();
539
- if (draft !== null) {
540
- const out = bypass(resp, "draft");
541
- for (const [k, v] of Object.entries(draftResponseHeaders(draft))) {
542
- if (k.toLowerCase() !== "vary") out.headers.set(k, v);
543
- else appendVary(out.headers, v);
544
- }
545
- return { response: out, profile: profileName };
546
- }
547
- if (method !== "GET") return { response: bypass(resp, "method"), profile: profileName };
548
- if (
549
- segment === "private" ||
550
- request.headers.has("authorization") ||
551
- !profile.isPublic ||
552
- isPrivateResponse(resp) ||
553
- !hasOnlySafeCookies(resp, safeCookies)
554
- ) {
555
- return { response: bypass(resp, "private", PRIVATE_NO_CACHE), profile: profileName };
556
- }
557
- // `vite dev` (and the `/_build` paths): the browser revalidates every time.
558
- return {
559
- response: bypass(resp, dev ? "dev" : "path", dev ? "no-cache" : undefined),
560
- profile: profileName,
561
- };
562
- }
563
-
564
- const seg = segment as Segment;
565
- const key = cacheKey(url, request, version, seg);
566
- const cache = edgeCache();
567
- const edge = profile.edge;
568
- const cdnPublic =
569
- token !== null &&
570
- profile.isPublic &&
571
- edge.fresh > 0 &&
572
- isServerFnPath(url.pathname) &&
573
- url.searchParams.get(CSEG_PARAM) === token;
574
-
575
- const dress = (
576
- resp: Response,
577
- decision: CacheDecision,
578
- extra?: Record<string, string>,
579
- ): Response => {
580
- const out = mutable(resp);
581
- // Cloudflare's Cache API adds its own status to a matched response.
582
- out.headers.delete("cf-cache-status");
583
- out.headers.delete(STORED_AT);
584
- out.headers.set("Cache-Control", cacheControl(profile));
585
- out.headers.set("Vary", "Accept-Encoding");
586
- // The CDN may keep only navigation data whose URL carries this segment's token.
587
- out.headers.set(
588
- "CDN-Cache-Control",
589
- cdnPublic ? `public, max-age=${edge.fresh}` : "no-store",
590
- );
591
- out.headers.set("X-Cache", decision);
592
- out.headers.set("X-Cache-Profile", profileName);
593
- out.headers.set("X-Cache-Segment", segmentKey(seg));
594
- if (version) out.headers.set("X-Cache-Version", version);
595
- for (const [k, v] of Object.entries(extra ?? {})) out.headers.set(k, v);
596
- return out;
597
- };
598
-
599
- const storable = (resp: Response) =>
600
- resp.status === 200 &&
601
- !isDegraded(resp) &&
602
- !isPrivateResponse(resp) &&
603
- hasOnlySafeCookies(resp, safeCookies);
604
-
605
- const store = (resp: Response) => {
606
- if (!cache) return;
607
- const ttl = edge.fresh + Math.max(edge.swr, edge.sie);
608
- const copy = resp.headers.has("set-cookie")
609
- ? withoutSafeCookies(resp, safeCookies)
610
- : resp.clone();
611
- copy.headers.set("Cache-Control", `public, max-age=${ttl}`);
612
- copy.headers.set(STORED_AT, String(Date.now()));
613
- copy.headers.delete("CDN-Cache-Control");
614
- ctx.waitUntil(cache.put(key, copy).catch(() => {}));
615
- };
616
-
617
- const ageOf = (resp: Response) => {
618
- const storedAt = Number(resp.headers.get(STORED_AT) || "0");
619
- return storedAt > 0 ? (Date.now() - storedAt) / 1000 : Number.POSITIVE_INFINITY;
620
- };
621
-
622
- let cached: Response | undefined;
623
- if (cache && profile.isPublic && edge.fresh > 0) {
624
- try {
625
- cached = (await cache.match(key)) ?? undefined;
626
- } catch {
627
- // Cache API unavailable: a miss.
628
- }
629
- }
630
-
631
- if (cached) {
632
- const age = ageOf(cached);
633
- if (age < edge.fresh) return { response: dress(cached, "HIT"), profile: profileName };
634
- if (age < edge.fresh + edge.swr) {
635
- ctx.waitUntil(
636
- origin()
637
- .then((fresh) => {
638
- if (storable(fresh)) store(fresh);
639
- })
640
- .catch(() => {}),
641
- );
642
- return {
643
- response: dress(cached, "STALE-HIT", { "X-Cache-Age": String(Math.round(age)) }),
644
- profile: profileName,
645
- };
646
- }
647
- }
648
-
649
- const staleOnError = (reason: string, status?: number): Response | null => {
650
- if (!cached || edge.sie <= 0) return null;
651
- const age = ageOf(cached);
652
- if (age >= edge.fresh + edge.sie) return null;
653
- return dress(cached, "STALE-ERROR", {
654
- "X-Cache-Age": String(Math.round(age)),
655
- "X-Cache-Reason": reason,
656
- ...(status ? { "X-Cache-Origin-Status": String(status) } : {}),
657
- });
658
- };
659
-
660
- let resp: Response;
661
- try {
662
- resp = await origin();
663
- } catch (error) {
664
- const stale = staleOnError("origin-error");
665
- if (stale) return { response: stale, profile: profileName };
666
- throw error;
667
- }
668
-
669
- if (resp.status !== 200) {
670
- if (resp.status >= 500 || resp.status === 429) {
671
- const stale = staleOnError("origin-status", resp.status);
672
- if (stale) return { response: stale, profile: profileName };
463
+ if (draft !== null) {
464
+ const out = mutable(await render());
465
+ for (const [k, v] of Object.entries(draftResponseHeaders(draft))) {
466
+ if (k.toLowerCase() !== "vary") out.headers.set(k, v);
467
+ else appendVary(out.headers, v);
673
468
  }
674
- return { response: bypass(resp, `status:${resp.status}`), profile: profileName };
675
- }
676
- if (isDegraded(resp)) {
677
- const stale = staleOnError("degraded");
678
- if (stale) return { response: stale, profile: profileName };
679
- return { response: bypass(resp, "degraded", PRIVATE_NO_CACHE), profile: profileName };
469
+ return { response: out };
680
470
  }
681
- if (isPrivateResponse(resp) || !hasOnlySafeCookies(resp, safeCookies)) {
682
- return { response: bypass(resp, "private-response", PRIVATE_NO_CACHE), profile: profileName };
471
+ // A signed request's page is that caller's: no shared cache may keep it,
472
+ // whatever the app said (RFC 9111 lets one store a `public` answer to it).
473
+ if (request.headers.has("authorization")) {
474
+ const out = mutable(await render());
475
+ out.headers.set("Cache-Control", PRIVATE_NO_CACHE);
476
+ return { response: out };
683
477
  }
684
- if (!profile.isPublic || edge.fresh === 0) {
685
- return {
686
- response: bypass(resp, `profile:${profileName}`, PRIVATE_NO_CACHE),
687
- profile: profileName,
688
- };
478
+ if (
479
+ !options.pageCache ||
480
+ visitor === null ||
481
+ assignments === undefined ||
482
+ !isCacheable(request, { version: draft, dev })
483
+ ) {
484
+ return { response: await render() };
689
485
  }
690
- store(resp);
691
- return { response: dress(resp, "MISS"), profile: profileName };
486
+ const response = await options.pageCache({
487
+ request,
488
+ url,
489
+ visitor,
490
+ assignments,
491
+ device: detectDevice(request.headers.get("user-agent") ?? ""),
492
+ env,
493
+ ctx,
494
+ render,
495
+ });
496
+ return { response, cached: true };
692
497
  }
693
498
 
694
499
  async function serve(
695
500
  incoming: Request,
696
501
  env: Env,
697
502
  ctx: ExecutionContextLike,
698
- started: number,
699
503
  ): Promise<{ response: Response; served: Served; draft: boolean }> {
700
- let decision: { pointer: string | null; setCookie: string | null } = {
701
- pointer: null,
702
- setCookie: null,
703
- };
504
+ let decision: DraftDecision = { version: null, setCookie: null };
704
505
  try {
705
- decision = await decideDraft(cms, incoming, policy);
506
+ decision = await decideDraft(cms, incoming);
706
507
  } catch {
707
508
  // The settings didn't load: the request gets the release.
708
509
  }
709
- // The page reads the draft from this header; a copy from outside never counts.
510
+ // The page reads the version, the visitor and the assignments from these
511
+ // headers; a copy from outside never counts.
710
512
  let request = incoming;
711
- if (incoming.headers.has(DRAFT_HEADER) || decision.pointer !== null) {
513
+ const own = [VERSION_HEADER, VISITOR_HEADER, ASSIGNMENTS_HEADER];
514
+ if (own.some((name) => incoming.headers.has(name)) || decision.version !== null) {
712
515
  const headers = new Headers(incoming.headers);
713
- headers.delete(DRAFT_HEADER);
714
- if (decision.pointer !== null) headers.set(DRAFT_HEADER, decision.pointer);
516
+ for (const name of own) headers.delete(name);
517
+ if (decision.version !== null) headers.set(VERSION_HEADER, decision.version.version);
715
518
  request = new Request(incoming, { headers });
716
519
  }
717
520
 
718
- const served = await handle(request, env, ctx, decision.pointer);
719
- const draft = decision.pointer !== null;
521
+ const served = await handle(request, env, ctx, decision);
522
+ const draft = decision.version !== null;
720
523
  let response = served.response;
721
524
  // A WebSocket upgrade passes through untouched.
722
525
  if (response.status === 101) return { response, served, draft };
723
526
  response = mutable(response);
724
527
 
725
- // CDN-Cache-Control is decided here, at the single exit: a response the
726
- // worker didn't cache, or that no branch gave one, tells the CDN no-store.
727
- if (
728
- response.headers.get("X-Cache") === "BYPASS" ||
729
- !response.headers.has("CDN-Cache-Control")
730
- ) {
528
+ // CDN-Cache-Control is decided here, at the single exit: a response that
529
+ // names none (the app's, the site's cache's or a route's) tells the CDN
530
+ // no-store, so only what the site chose to share is kept in front of it.
531
+ if (!response.headers.has("CDN-Cache-Control")) {
731
532
  response.headers.set("CDN-Cache-Control", "no-store");
732
533
  }
733
534
  if (decision.setCookie) response.headers.append("Set-Cookie", decision.setCookie);
535
+ if (served.visitorCookie) response.headers.append("Set-Cookie", served.visitorCookie);
734
536
  dedupeSetCookies(response);
735
537
  if (isHtml(response)) {
736
538
  for (const [k, v] of Object.entries(securityHeaders)) {
@@ -741,29 +543,15 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
741
543
  }
742
544
  }
743
545
 
744
- if (served.profile && options.onCache) {
745
- const xCache = response.headers.get("X-Cache") ?? "BYPASS";
746
- try {
747
- options.onCache({
748
- profile: served.profile,
749
- decision: (DECISIONS.has(xCache) ? xCache : "BYPASS") as CacheDecision,
750
- ms: Date.now() - started,
751
- status: response.status,
752
- });
753
- } catch {
754
- // A metrics hook never breaks a response.
755
- }
756
- }
757
546
  return { response, served, draft };
758
547
  }
759
548
 
760
549
  return {
761
550
  async fetch(incoming, env, ctx) {
762
- const started = Date.now();
763
551
  const clock = performance.now();
764
552
  let result: Awaited<ReturnType<typeof serve>>;
765
553
  try {
766
- result = await serve(incoming, env, ctx, started);
554
+ result = await serve(incoming, env, ctx);
767
555
  } catch (error) {
768
556
  // The runtime answers a thrown request with a 500.
769
557
  measure(incoming, ctx, (performance.now() - clock) / 1000, 500, "BYPASS", undefined);