@decocms/tanstack 8.0.0 → 8.4.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 (150) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +86 -31
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -44
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/cms/kvBlockSource.test.ts +0 -82
  109. package/src/cms/kvBlockSource.ts +0 -68
  110. package/src/daemon/auth.ts +0 -204
  111. package/src/daemon/fs.ts +0 -238
  112. package/src/daemon/index.ts +0 -8
  113. package/src/daemon/middleware.ts +0 -156
  114. package/src/daemon/tunnel.ts +0 -129
  115. package/src/daemon/volumes.ts +0 -366
  116. package/src/daemon/watch.ts +0 -272
  117. package/src/hooks/DecoPageRenderer.tsx +0 -688
  118. package/src/hooks/DecoRootLayout.tsx +0 -111
  119. package/src/hooks/NavigationProgress.tsx +0 -21
  120. package/src/hooks/PreviewProviders.tsx +0 -26
  121. package/src/hooks/StableOutlet.tsx +0 -30
  122. package/src/hooks/index.ts +0 -9
  123. package/src/routes/adminRoutes.test.ts +0 -99
  124. package/src/routes/adminRoutes.ts +0 -153
  125. package/src/routes/cmsRoute.test.ts +0 -100
  126. package/src/routes/cmsRoute.ts +0 -944
  127. package/src/routes/components.tsx +0 -57
  128. package/src/routes/index.ts +0 -24
  129. package/src/routes/pageUrl.test.ts +0 -70
  130. package/src/routes/pageUrl.ts +0 -54
  131. package/src/routes/withSiteGlobals.test.ts +0 -206
  132. package/src/routes/withSiteGlobals.ts +0 -222
  133. package/src/sdk/cookiePassthrough.ts +0 -58
  134. package/src/sdk/createInvoke.ts +0 -77
  135. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  136. package/src/sdk/deferredSectionLoader.ts +0 -46
  137. package/src/sdk/kvHydration.test.ts +0 -215
  138. package/src/sdk/kvHydration.ts +0 -193
  139. package/src/sdk/outboundHeaders.test.ts +0 -113
  140. package/src/sdk/outboundHeaders.ts +0 -81
  141. package/src/sdk/router.ts +0 -92
  142. package/src/sdk/useHydrated.ts +0 -19
  143. package/src/sdk/workerEntry.test.ts +0 -495
  144. package/src/sdk/workerEntry.ts +0 -2307
  145. package/src/setupFastDeploy.ts +0 -13
  146. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  147. package/src/vite/plugin.js +0 -850
  148. package/src/vite/plugin.test.js +0 -113
  149. package/src/vite/plugin.test.ts +0 -52
  150. package/tsconfig.json +0 -7
@@ -1,2307 +0,0 @@
1
- /**
2
- * Factory for creating a cache-aware Cloudflare Worker entry.
3
- *
4
- * Wraps a TanStack Start server entry with:
5
- * - Cloudflare Cache API integration (edge caching)
6
- * - Device-specific cache keys (mobile/desktop split)
7
- * - Per-URL cache profile detection via detectCacheProfile()
8
- * - Immutable caching for fingerprinted static assets
9
- * - Cache purge API endpoint
10
- * - Protection against accidental caching of private/search paths
11
- *
12
- * @example
13
- * ```ts
14
- * // src/worker-entry.ts
15
- * import handler, { createServerEntry } from "@tanstack/react-start/server-entry";
16
- * import { createDecoWorkerEntry } from "@decocms/start/sdk/workerEntry";
17
- *
18
- * const serverEntry = createServerEntry({
19
- * async fetch(request) {
20
- * return await handler.fetch(request);
21
- * },
22
- * });
23
- *
24
- * export default createDecoWorkerEntry(serverEntry);
25
- * ```
26
- */
27
-
28
- import {
29
- getRevision,
30
- isBot,
31
- loadBlocks,
32
- type MatcherContext,
33
- onChange,
34
- resolveDecoPage,
35
- runSectionLoaders,
36
- runSingleSectionLoader,
37
- } from "@decocms/blocks/cms";
38
- import { DECO_MATCHERS_OVERRIDE_PARAM } from "@decocms/blocks/matchers/override";
39
- import { clearLoaderCache } from "@decocms/blocks/sdk/cachedLoader";
40
- import {
41
- type CacheProfileName,
42
- cacheHeaders,
43
- canonicalizeServerFnPayloadForCacheKey,
44
- detectCacheProfile,
45
- edgeCacheConfig,
46
- getCacheProfile,
47
- serverFnPagePath,
48
- } from "@decocms/blocks/sdk/cacheHeaders";
49
- import { isDevMode } from "@decocms/blocks/sdk/env";
50
- import { parseSegmentCookie, SEGMENT_COOKIE, segmentCacheToken } from "@decocms/blocks/sdk/flags";
51
- import {
52
- getActiveSpan,
53
- logRequest,
54
- recordCacheMetric,
55
- recordRequestMetric,
56
- setSpanAttribute,
57
- withTracing,
58
- } from "@decocms/blocks/sdk/observability";
59
- import {
60
- _setDebugSampled,
61
- _setRequestTraceContext,
62
- instrumentWorker,
63
- type OtelOptions,
64
- } from "@decocms/blocks/sdk/otel";
65
- import { setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
66
- import { parseTraceparent } from "@decocms/blocks/sdk/otelHttpTracer";
67
- import { loadRedirects, matchRedirect, type RedirectMap } from "@decocms/blocks/sdk/redirects";
68
- import { RequestContext } from "@decocms/blocks/sdk/requestContext";
69
- import { cleanPathForCacheKey } from "@decocms/blocks/sdk/urlUtils";
70
- import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
71
- import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
72
- import { buildHtmlShell } from "@decocms/blocks-admin/sdk/htmlShell";
73
- import { getAppMiddleware } from "@decocms/blocks-admin/sdk/setupApps";
74
- import { ensureBlocksHydrated, maybePollRevision } from "./kvHydration";
75
- import { DECO_POWERED_BY, installDefaultUserAgent } from "./outboundHeaders";
76
-
77
- /**
78
- * Build-time identifier injected by `decoVitePlugin()` (see
79
- * `src/vite/plugin.js`). Falls back to `undefined` if the consuming site
80
- * isn't using the plugin or the symbol wasn't `define`d at bundle time.
81
- *
82
- * The runtime `env.BUILD_HASH` (when explicitly set, e.g. via
83
- * `wrangler deploy --var BUILD_HASH:foo`) takes precedence — see
84
- * `getBuildHash()` below.
85
- */
86
- declare const __DECO_BUILD_HASH__: string | undefined;
87
-
88
- /**
89
- * The five canonical cache-decision strings stamped on the `X-Cache`
90
- * response header (and on the `decision` label of `cache_*_total`
91
- * metrics). Used by the request-metric label enrichment to keep label
92
- * cardinality bounded — anything else (e.g. an upstream proxy that sets
93
- * its own `X-Cache: random-text`) is dropped from the label.
94
- */
95
- type CacheDecisionString = "HIT" | "STALE-HIT" | "STALE-ERROR" | "MISS" | "BYPASS";
96
-
97
- function isCacheDecision(value: string | null): value is CacheDecisionString {
98
- return (
99
- value === "HIT" ||
100
- value === "STALE-HIT" ||
101
- value === "STALE-ERROR" ||
102
- value === "MISS" ||
103
- value === "BYPASS"
104
- );
105
- }
106
-
107
- /**
108
- * Append Link preload headers for CSS and fonts so the browser starts
109
- * fetching them before parsing HTML. Only applied to HTML responses.
110
- */
111
- function appendResourceHints(resp: Response): void {
112
- const ct = resp.headers.get("content-type");
113
- if (!ct || !ct.includes("text/html")) return;
114
- const { cssHref, fontHrefs } = getRenderShellConfig();
115
- if (cssHref) {
116
- resp.headers.append("Link", `<${cssHref}>; rel=preload; as=style`);
117
- }
118
- for (const href of fontHrefs) {
119
- resp.headers.append("Link", `<${href}>; rel=preload; as=font; crossorigin`);
120
- }
121
- }
122
-
123
- // ---------------------------------------------------------------------------
124
- // Types
125
- // ---------------------------------------------------------------------------
126
-
127
- /**
128
- * Minimal ExecutionContext interface compatible with Cloudflare Workers.
129
- * Defined here so blocks doesn't need @cloudflare/workers-types.
130
- */
131
- interface WorkerExecutionContext {
132
- waitUntil(promise: Promise<unknown>): void;
133
- passThroughOnException(): void;
134
- }
135
-
136
- interface ServerEntry {
137
- fetch(
138
- request: Request,
139
- env: Record<string, unknown>,
140
- ctx: WorkerExecutionContext,
141
- ): Response | Promise<Response>;
142
- }
143
-
144
- /**
145
- * Segment dimensions used to differentiate cache entries.
146
- *
147
- * The workerEntry calls `buildSegment` (if provided) to extract these
148
- * from the request. Two requests with the same SegmentKey share a
149
- * cache entry; different segments get different cached responses.
150
- */
151
- export interface SegmentKey {
152
- /**
153
- * Device class derived from the request User-Agent.
154
- *
155
- * Accepts the full `Device` union (`"mobile" | "desktop" | "tablet"`) so
156
- * that callers can pass `detectDevice(...)` directly without manual
157
- * narrowing. Sites that want to share cache entries between mobile and
158
- * tablet can collapse the value at the call site (e.g.
159
- * `device === "tablet" ? "mobile" : device`).
160
- */
161
- device: Device;
162
- /** Whether the user is logged in (e.g., has a valid auth cookie). */
163
- loggedIn?: boolean;
164
- /** Commerce sales channel / price list. */
165
- salesChannel?: string;
166
- /**
167
- * VTEX region ID for regionalized pricing/availability.
168
- * When present, cache entries are segmented per region.
169
- * Sites without regionalization should omit this field
170
- * to avoid unnecessary cache fragmentation.
171
- */
172
- regionId?: string;
173
- /** Sorted list of active A/B flag names for cache cohort splitting. */
174
- flags?: string[];
175
- /**
176
- * Custom cache dimensions beyond the known fields above (e.g. a
177
- * store/CEP-based delivery selector). `hashSegment` serializes these
178
- * automatically — unlike the known fields, there's no dedicated shorthand
179
- * key, so don't reuse a name already declared above.
180
- */
181
- [customField: string]: string | boolean | string[] | undefined;
182
- }
183
-
184
- /**
185
- * Admin route handlers injected by the site's worker-entry.ts.
186
- * Kept as a runtime option so the imports only exist in the SSR entry
187
- * (not pulled into the client Vite build).
188
- */
189
- export interface AdminHandlers {
190
- handleMeta: (request: Request) => Response;
191
- handleDecofileRead: () => Response;
192
- handleDecofileReload: (request: Request) => Response | Promise<Response>;
193
- handleRender: (request: Request) => Response | Promise<Response>;
194
- corsHeaders: (request: Request) => Record<string, string>;
195
- }
196
-
197
- export interface DecoWorkerEntryOptions {
198
- /**
199
- * Admin route handlers (/live/_meta, /.decofile, /live/previews).
200
- * Pass the handlers from `@decocms/start/admin` here.
201
- * If not provided, admin routes are not handled.
202
- */
203
- admin?: AdminHandlers;
204
-
205
- /**
206
- * Override the default cache profile detection.
207
- * Return `null` to fall through to the built-in detector.
208
- */
209
- detectProfile?: (url: URL) => CacheProfileName | null;
210
-
211
- /**
212
- * Whether to create device-specific cache keys (mobile vs desktop).
213
- * Useful when server-rendered HTML differs by device.
214
- * @default true
215
- */
216
- deviceSpecificKeys?: boolean;
217
-
218
- /**
219
- * Build a full segment key from the incoming request.
220
- *
221
- * When provided, the segment key replaces the simple device-only
222
- * cache key with a richer key that differentiates by login state,
223
- * sales channel, and A/B flags.
224
- *
225
- * Logged-in segments (`loggedIn: true`) automatically bypass the
226
- * cache (the response is fetched fresh every time).
227
- *
228
- * @example
229
- * ```ts
230
- * import { extractVtexContext } from "@decocms/apps/vtex/middleware";
231
- *
232
- * createDecoWorkerEntry(serverEntry, {
233
- * buildSegment: (request) => {
234
- * const vtx = extractVtexContext(request);
235
- * return {
236
- * device: /mobile|android|iphone/i.test(request.headers.get("user-agent") ?? "") ? "mobile" : "desktop",
237
- * loggedIn: vtx.isLoggedIn,
238
- * salesChannel: vtx.salesChannel,
239
- * // Include regionId only if the site uses VTEX regionalization.
240
- * // When present, cache entries split by region; omit it for
241
- * // non-regionalized sites to maximize cache sharing.
242
- * regionId: vtx.regionId ?? undefined,
243
- * };
244
- * },
245
- * });
246
- * ```
247
- */
248
- buildSegment?: (request: Request) => SegmentKey;
249
-
250
- /**
251
- * Environment variable name holding the cache purge token.
252
- * Set to `false` to disable the purge endpoint.
253
- * @default "PURGE_TOKEN"
254
- */
255
- purgeTokenEnv?: string | false;
256
-
257
- /**
258
- * Paths that should always bypass the edge cache, even if the
259
- * profile detector would otherwise cache them.
260
- * Defaults include `/_build`, `/deco/`, `/live/`, `/.decofile`.
261
- */
262
- bypassPaths?: string[];
263
-
264
- /**
265
- * Additional paths (beyond the defaults) that should bypass caching.
266
- * Merged with the default bypass paths.
267
- */
268
- extraBypassPaths?: string[];
269
-
270
- /**
271
- * Custom HTML shell for the `/live/previews` iframe page.
272
- * If not provided, a shell is generated from the render config
273
- * (theme, CSS, fonts) set via setRenderShell().
274
- */
275
- previewShell?: string;
276
-
277
- /**
278
- * Regex for detecting fingerprinted static assets (content-hashed filenames).
279
- * Matched paths get `immutable, max-age=31536000`.
280
- * @default /\/_build\/assets\/.*-[a-zA-Z0-9]{8,}\.\w+$/
281
- */
282
- fingerprintedAssetPattern?: RegExp;
283
-
284
- /**
285
- * Whether to strip UTM and tracking params from cache keys.
286
- * Two requests differing only in utm_source, fbclid, etc.
287
- * will share the same cache entry.
288
- * @default true
289
- */
290
- stripTrackingParams?: boolean;
291
-
292
- /**
293
- * Optional proxy handler for commerce backend routes
294
- * (checkout, account, API, login, etc.).
295
- *
296
- * Called early in the request pipeline — after admin routes and cache
297
- * purge, but before static assets and edge cache logic. This ensures
298
- * proxy requests never hit TanStack Start or the React SSR pipeline.
299
- *
300
- * Return a `Response` to proxy the request, or `null` to let the
301
- * normal TanStack Start flow handle it.
302
- *
303
- * @example
304
- * ```ts
305
- * import { shouldProxyToVtex, proxyToVtex } from "@decocms/apps/vtex/utils/proxy";
306
- *
307
- * createDecoWorkerEntry(serverEntry, {
308
- * proxyHandler: (request, url) => {
309
- * if (shouldProxyToVtex(url.pathname)) {
310
- * return proxyToVtex(request);
311
- * }
312
- * return null;
313
- * },
314
- * });
315
- * ```
316
- */
317
- proxyHandler?: (request: Request, url: URL) => Promise<Response | null> | Response | null;
318
-
319
- /**
320
- * Environment variable name holding a build version string.
321
- * The value is appended to every cache key so each deploy gets its own
322
- * cache namespace — old entries become orphaned and expire naturally,
323
- * preventing stale HTML that references old CSS/JS fingerprinted filenames.
324
- *
325
- * Set to `false` to disable. When the env var is missing or empty,
326
- * cache keys remain unversioned (backward-compatible).
327
- *
328
- * @default "BUILD_HASH"
329
- *
330
- * @example
331
- * ```yaml
332
- * # CI: pass git hash to wrangler
333
- * - run: npx wrangler deploy --var BUILD_HASH:$(git rev-parse --short HEAD)
334
- * ```
335
- */
336
- cacheVersionEnv?: string | false;
337
-
338
- /**
339
- * Security headers appended to every SSR response (HTML pages).
340
- * Pass `false` to disable entirely.
341
- *
342
- * Default headers: X-Content-Type-Options, Referrer-Policy,
343
- * Permissions-Policy, X-XSS-Protection, HSTS, Cross-Origin-Opener-Policy,
344
- * and a `Content-Security-Policy: frame-ancestors` directive that lets the
345
- * deco admin/studio embed the storefront (see DEFAULT_FRAME_ANCESTORS_CSP).
346
- *
347
- * Custom entries are merged with defaults (custom values take precedence) —
348
- * pass `Content-Security-Policy` here to override the default frame-ancestors.
349
- *
350
- * @default DEFAULT_SECURITY_HEADERS
351
- */
352
- securityHeaders?: Record<string, string> | false;
353
-
354
- /**
355
- * Content Security Policy directives (report-only by default).
356
- * Pass an array of directive strings which are joined with "; ".
357
- * Pass `false` to omit CSP entirely.
358
- *
359
- * @example
360
- * ```ts
361
- * csp: [
362
- * "default-src 'self'",
363
- * "script-src 'self' 'unsafe-inline' https://www.googletagmanager.com",
364
- * "img-src 'self' data: https:",
365
- * ]
366
- * ```
367
- */
368
- csp?: string[] | false;
369
-
370
- /**
371
- * Automatically inject Cloudflare geo data (country, region, city)
372
- * as internal cookies on every request so location matchers can read
373
- * them from MatcherContext.cookies. The cookies are only visible
374
- * within the Worker — they are never sent to the browser.
375
- *
376
- * @default true
377
- */
378
- autoInjectGeoCookies?: boolean;
379
-
380
- /**
381
- * Controls how Cloudflare geo data is folded into edge cache keys.
382
- *
383
- * - `"auto"` (default): inspects the loaded decofile on every `setBlocks()`
384
- * call (startup + fast-deploy swaps). If any block is configured with
385
- * `website/matchers/location.ts`, geo keying is activated at `"region"`
386
- * granularity (country+state); otherwise it is set to `"off"`. `"region"`
387
- * covers VTEX regionalization and most geo matchers without city-level
388
- * fragmentation. Sites that need city precision should set `"city"`
389
- * explicitly. No manual configuration needed for the common case.
390
- * - `"city"`: full `country|region|city` key — maximum isolation for sites
391
- * with city-level location matchers.
392
- * - `"region"`: `country|region` — good for region/state matchers (e.g.
393
- * VTEX regionalization), avoids city-level fragmentation.
394
- * - `"country"`: country only.
395
- * - `"off"`: no `__cf_geo` param is added and the automatic `regionId`
396
- * backfill from CF geo is disabled. Use for single-catalog storefronts
397
- * that do not vary content by location — recovers the full edge HIT rate.
398
- *
399
- * @default "auto"
400
- */
401
- geoCacheKey?: "auto" | "off" | "country" | "region" | "city";
402
-
403
- /**
404
- * Cookie names considered "safe" for caching — these are public/anonymous
405
- * cookies that do not carry per-user session or auth data.
406
- *
407
- * When a response contains ONLY safe cookies, it is still eligible for
408
- * Cache API storage. The safe cookies are stripped from the cached copy
409
- * but kept on the response served to the current user.
410
- *
411
- * If the response contains ANY cookie NOT in this list, the response
412
- * bypasses caching entirely (existing behavior).
413
- *
414
- * @default DEFAULT_SAFE_COOKIES (vtex_is_session, vtex_is_anonymous, vtex_segment, _deco_bucket)
415
- *
416
- * @example
417
- * ```ts
418
- * createDecoWorkerEntry(serverEntry, {
419
- * safeCookies: [
420
- * ...DEFAULT_SAFE_COOKIES,
421
- * "my_custom_analytics_cookie",
422
- * ],
423
- * });
424
- * ```
425
- */
426
- safeCookies?: string[];
427
-
428
- /**
429
- * Additional static paths (beyond fingerprinted assets) that should
430
- * receive long-lived immutable cache headers.
431
- *
432
- * Useful for non-fingerprinted resources like fonts that live at
433
- * stable URLs (e.g., `/fonts/Lato-Regular.woff2`).
434
- *
435
- * @default ["/fonts/"]
436
- *
437
- * @example
438
- * ```ts
439
- * createDecoWorkerEntry(serverEntry, {
440
- * staticPaths: ["/fonts/", "/static/", "/images/icons/"],
441
- * });
442
- * ```
443
- */
444
- staticPaths?: string[];
445
-
446
- /**
447
- * CDN-Cache-Control header strategy.
448
- *
449
- * - `"no-store"` (default): CDN never caches; every request invokes the Worker.
450
- * Correct when segment-based cache keys differ from the original URL.
451
- * - `"match-profile"`: Set CDN-Cache-Control to a short TTL matching the
452
- * profile's edge.fresh value. Only safe when you are NOT using segment-based
453
- * cache keys (i.e., no `buildSegment` and `deviceSpecificKeys: false`).
454
- * - A function: Return a CDN-Cache-Control value per profile, or `null` for no-store.
455
- *
456
- * @default "no-store"
457
- */
458
- cdnCacheControl?: "no-store" | "match-profile" | ((profile: CacheProfileName) => string | null);
459
- /**
460
- * Auto-instrumentation via `instrumentWorker` is enabled by default. The
461
- * framework wraps the returned handler so that, when OTel env vars
462
- * (`DECO_OTEL_*_ENDPOINT`, `DECO_OTEL_TRACES_SAMPLING_RATE`,
463
- * `DECO_OTEL_LOGS_MIN_LEVEL`) are set on the Worker's `env`, telemetry
464
- * starts flowing without the site having to touch its worker entry.
465
- *
466
- * - Pass an `OtelOptions` object to override defaults (serviceName,
467
- * sampling, custom env var names, etc.).
468
- * - Pass `false` to disable framework-side instrumentation entirely
469
- * (e.g., when the site applies its own `instrumentWorker` wrap or
470
- * uses a custom transport).
471
- *
472
- * When the OTel endpoint env vars are absent the wrap is effectively a
473
- * no-op — no buffers, no flushes, no network calls.
474
- */
475
- observability?: OtelOptions | false;
476
-
477
- /**
478
- * Default `User-Agent` for OUTBOUND `fetch` calls (loaders, commerce
479
- * APIs, proxies). Cloudflare Workers sends no User-Agent at all, and
480
- * UA-less requests are blocked by common WAF setups (Cloudflare managed
481
- * rules / Bot Fight Mode) on partner origins. The old Deno runtime
482
- * implicitly sent `Deno/x.y.z` on every outbound request, so this
483
- * restores pre-migration behavior with an identifiable value.
484
- *
485
- * Applied only when the caller didn't set a User-Agent — app-specific
486
- * UAs always win.
487
- *
488
- * - Pass a string to override the value (e.g. to match a partner's
489
- * existing WAF allowlist during migration).
490
- * - Pass `false` to leave `globalThis.fetch` untouched.
491
- *
492
- * @default `Deco/<version> (+https://deco.cx)` — see DECO_USER_AGENT.
493
- */
494
- outboundUserAgent?: string | false;
495
- }
496
-
497
- // ---------------------------------------------------------------------------
498
- // Constants
499
- // ---------------------------------------------------------------------------
500
-
501
- const PREVIEW_SHELL_SCRIPT = `(function() {
502
- if (window.__DECO_LIVE_CONTROLS__) return;
503
- window.__DECO_LIVE_CONTROLS__ = true;
504
- addEventListener("message", function(event) {
505
- var data = event.data;
506
- if (!data || typeof data !== "object") return;
507
- switch (data.type) {
508
- case "editor::inject":
509
- if (data.args && data.args.script) {
510
- try { eval(data.args.script); } catch(e) { console.error("[deco] inject error:", e); }
511
- }
512
- break;
513
- }
514
- });
515
- })();`;
516
-
517
- function buildPreviewShell(): string {
518
- return buildHtmlShell({ script: PREVIEW_SHELL_SCRIPT });
519
- }
520
-
521
- // ---------------------------------------------------------------------------
522
- // Cloudflare geo cookie injection
523
- // ---------------------------------------------------------------------------
524
-
525
- /**
526
- * Inject Cloudflare geo data as cookies so matchers (location.ts) can
527
- * read them from MatcherContext.cookies without relying on request.cf.
528
- *
529
- * Call this on the incoming request before passing it to the worker entry.
530
- * Only needed in production Cloudflare Workers where `request.cf` is populated.
531
- *
532
- * @example
533
- * ```ts
534
- * export default {
535
- * async fetch(request, env, ctx) {
536
- * return handler.fetch(injectGeoCookies(request), env, ctx);
537
- * }
538
- * };
539
- * ```
540
- */
541
- /**
542
- * Returns `true` when the decofile contains at least one block whose
543
- * `__resolveType` is `website/matchers/location.ts`. Used by
544
- * `geoCacheKey: "auto"` to decide whether geo cache key fragmentation
545
- * should be active.
546
- *
547
- * Matches only resolver-type references (not arbitrary string values) to
548
- * avoid false positives from content/label fields that happen to mention
549
- * the path.
550
- */
551
- export function detectLocationMatcher(blocks: Record<string, unknown>): boolean {
552
- return JSON.stringify(blocks).includes('"__resolveType":"website/matchers/location.ts"');
553
- }
554
-
555
- /**
556
- * Build the `__cf_geo` cache-key fragment from Cloudflare's `request.cf`
557
- * object at the requested granularity.
558
- *
559
- * Returns `undefined` when `granularity` is `"off"`, `cf` is absent, or no
560
- * relevant fields are present.
561
- *
562
- * @example
563
- * buildGeoCacheParam({ country: "BR", region: "São Paulo", city: "SP" }, "region")
564
- * // → "BR|São Paulo"
565
- */
566
- export function buildGeoCacheParam(
567
- cf: Record<string, string> | undefined,
568
- granularity: "off" | "country" | "region" | "city",
569
- ): string | undefined {
570
- if (granularity === "off" || !cf) return undefined;
571
- const parts: string[] = [];
572
- if (cf.country) parts.push(cf.country);
573
- if (granularity !== "country" && cf.region) parts.push(cf.region);
574
- if (granularity === "city" && cf.city) parts.push(cf.city);
575
- return parts.length ? parts.join("|") : undefined;
576
- }
577
-
578
- export function injectGeoCookies(request: Request): Request {
579
- const cf = (request as unknown as { cf?: Record<string, string> }).cf;
580
- if (!cf) return request;
581
-
582
- const parts: string[] = [];
583
- if (cf.region) parts.push(`__cf_geo_region=${encodeURIComponent(cf.region)}`);
584
- if (cf.country) parts.push(`__cf_geo_country=${encodeURIComponent(cf.country)}`);
585
- if (cf.city) parts.push(`__cf_geo_city=${encodeURIComponent(cf.city)}`);
586
- if (cf.latitude) parts.push(`__cf_geo_lat=${encodeURIComponent(cf.latitude)}`);
587
- if (cf.longitude) parts.push(`__cf_geo_lng=${encodeURIComponent(cf.longitude)}`);
588
- if (cf.regionCode) parts.push(`__cf_geo_region_code=${encodeURIComponent(cf.regionCode)}`);
589
-
590
- if (!parts.length) return request;
591
-
592
- const existing = request.headers.get("cookie") ?? "";
593
- const combined = existing ? `${existing}; ${parts.join("; ")}` : parts.join("; ");
594
-
595
- // Strip CF geo headers that carry non-ASCII values (cf-region: "São Paulo",
596
- // cf-ipcity: "Brasília", etc.) before building the new Request. The geo
597
- // data is preserved in the __cf_geo_* cookies we just built, so callers
598
- // downstream lose no information.
599
- //
600
- // Without this strip, the Workers runtime emits a warning on every
601
- // request because the new Request inherits these UTF-8 headers from the
602
- // inbound request:
603
- //
604
- // "A header value for "cf-region" contains non-ASCII characters: "..."
605
- //
606
- // and the warning is logged once per non-ASCII header — for a Brazilian
607
- // storefront with cities/states full of accents that means ~2 warns per
608
- // request × every request that hits the worker.
609
- const headers = new Headers();
610
- for (const [key, value] of request.headers.entries()) {
611
- const lk = key.toLowerCase();
612
- if (lk === "cf-region" || lk === "cf-ipcity") continue;
613
- headers.set(key, value);
614
- }
615
- headers.set("cookie", combined);
616
-
617
- // Mirror the ASCII-safe geo fields from request.cf into headers so matchers
618
- // that read `request.headers.get("cf-region-code")` (parity with the
619
- // upstream deco-cx/apps location matcher) still work even if the inbound
620
- // request didn't carry them. Non-ASCII fields (region name, city) stay in
621
- // the cookies above — putting them in headers would re-trigger the
622
- // non-ASCII warning we strip on the loop above.
623
- if (cf.country && !headers.has("cf-ipcountry")) headers.set("cf-ipcountry", cf.country);
624
- if (cf.regionCode && !headers.has("cf-region-code")) headers.set("cf-region-code", cf.regionCode);
625
- if (cf.latitude && !headers.has("cf-iplatitude")) headers.set("cf-iplatitude", cf.latitude);
626
- if (cf.longitude && !headers.has("cf-iplongitude")) headers.set("cf-iplongitude", cf.longitude);
627
-
628
- return new Request(request, { headers });
629
- }
630
-
631
- const ONE_YEAR = 31536000;
632
-
633
- /**
634
- * Sensible security headers for any production storefront.
635
- *
636
- * Framing protection is handled by a default `Content-Security-Policy:
637
- * frame-ancestors` directive (see DEFAULT_FRAME_ANCESTORS_CSP), NOT
638
- * `X-Frame-Options`. CSP level 3 `frame-ancestors` supersedes X-Frame-Options
639
- * in every modern browser, and — unlike the all-or-nothing SAMEORIGIN value —
640
- * it can allow the deco admin/studio to embed the storefront for live preview
641
- * while still blocking arbitrary third-party framing (clickjacking).
642
- *
643
- * Full CSP (script-src etc.) is intentionally not included here — it's
644
- * site-specific (third-party script domains) and passed via the `csp` option.
645
- */
646
- export const DEFAULT_SECURITY_HEADERS: Record<string, string> = {
647
- "X-Content-Type-Options": "nosniff",
648
- "Referrer-Policy": "strict-origin-when-cross-origin",
649
- "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
650
- "X-XSS-Protection": "1; mode=block",
651
- "Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
652
- "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
653
- };
654
-
655
- /**
656
- * Origins allowed to embed the storefront in an iframe. These are the deco
657
- * studio surfaces that render the live-preview iframe, plus `'self'` so the
658
- * storefront can frame itself.
659
- *
660
- * A site can widen this by passing its own
661
- * `securityHeaders["Content-Security-Policy"]`, or drop framing protection
662
- * entirely with `securityHeaders: false`.
663
- */
664
- export const DECO_ADMIN_FRAME_ANCESTORS: string[] = [
665
- "'self'",
666
- "https://studio.decocms.com",
667
- "https://*.deco.studio",
668
- ];
669
-
670
- /**
671
- * Default enforcement CSP shipped on every SSR HTML response. Only the
672
- * `frame-ancestors` directive is enforced by default; the full site CSP
673
- * (passed via the `csp` option) is emitted report-only.
674
- */
675
- export const DEFAULT_FRAME_ANCESTORS_CSP = `frame-ancestors ${DECO_ADMIN_FRAME_ANCESTORS.join(" ")}`;
676
-
677
- const DEFAULT_BYPASS_PATHS = ["/_build", "/deco/", "/live/", "/.decofile"];
678
-
679
- /**
680
- * Cookie names that are safe for caching — they carry anonymous/public
681
- * segment data, not per-user auth tokens.
682
- *
683
- * VTEX Intelligent Search sets `vtex_is_session` and `vtex_is_anonymous`
684
- * on every response. `vtex_segment` encodes the sales channel.
685
- * `_deco_bucket` is the A/B test cohort cookie.
686
- */
687
- export const DEFAULT_SAFE_COOKIES: string[] = [
688
- "vtex_is_session",
689
- "vtex_is_anonymous",
690
- "vtex_segment",
691
- "_deco_bucket",
692
- ];
693
-
694
- const DEFAULT_STATIC_PATHS = ["/fonts/"];
695
-
696
- /**
697
- * Parse Set-Cookie header values and return cookie names.
698
- */
699
- function parseCookieNames(response: Response): string[] {
700
- const names: string[] = [];
701
- // getSetCookie() returns individual Set-Cookie values (available in Workers runtime)
702
- const setCookies = (response.headers as any).getSetCookie?.() as string[] | undefined;
703
- if (setCookies) {
704
- for (const sc of setCookies) {
705
- const eqIdx = sc.indexOf("=");
706
- if (eqIdx > 0) names.push(sc.slice(0, eqIdx).trim());
707
- }
708
- } else {
709
- // Fallback: parse from combined header (less reliable but covers edge cases)
710
- const combined = response.headers.get("set-cookie") ?? "";
711
- for (const part of combined.split(",")) {
712
- const eqIdx = part.indexOf("=");
713
- if (eqIdx > 0) {
714
- const name = part.slice(0, eqIdx).trim();
715
- // Skip attributes like "Expires=..." that appear after semicolons
716
- if (!name.includes(";") && name.length > 0) names.push(name);
717
- }
718
- }
719
- }
720
- return names;
721
- }
722
-
723
- /**
724
- * Check if ALL cookies in a response are in the safe list.
725
- * Returns true if the response has no cookies or only safe cookies.
726
- */
727
- function hasOnlySafeCookies(response: Response, safeCookieSet: Set<string>): boolean {
728
- if (!response.headers.has("set-cookie")) return true;
729
- const names = parseCookieNames(response);
730
- if (names.length === 0) return true;
731
- return names.every((name) => safeCookieSet.has(name));
732
- }
733
-
734
- /**
735
- * Clone a response, stripping Set-Cookie headers that match the safe list.
736
- * Uses response.clone() to preserve the original body for the served response.
737
- * The returned copy is intended for cache storage only.
738
- */
739
- function stripSafeCookiesForCache(response: Response, safeCookieSet: Set<string>): Response {
740
- const clone = response.clone();
741
- const setCookies = (response.headers as any).getSetCookie?.() as string[] | undefined;
742
- if (!setCookies || setCookies.length === 0) return clone;
743
-
744
- // Remove all Set-Cookie headers, then re-add only unsafe ones
745
- clone.headers.delete("set-cookie");
746
- for (const sc of setCookies) {
747
- const eqIdx = sc.indexOf("=");
748
- const name = eqIdx > 0 ? sc.slice(0, eqIdx).trim() : "";
749
- if (name && !safeCookieSet.has(name)) {
750
- clone.headers.append("set-cookie", sc);
751
- }
752
- }
753
- return clone;
754
- }
755
-
756
- /**
757
- * Deduplicate Set-Cookie headers — keep only the LAST occurrence of
758
- * each cookie name. Multiple layers (VTEX middleware, invoke handlers,
759
- * etc.) may independently append the same cookie.
760
- */
761
- function deduplicateSetCookies(response: Response): void {
762
- const setCookies = (response.headers as any).getSetCookie?.() as string[] | undefined;
763
- if (!setCookies || setCookies.length <= 1) return;
764
-
765
- // Build map: cookie name → last Set-Cookie value
766
- const seen = new Map<string, string>();
767
- for (const sc of setCookies) {
768
- const eqIdx = sc.indexOf("=");
769
- const name = eqIdx > 0 ? sc.slice(0, eqIdx).trim() : sc;
770
- seen.set(name, sc);
771
- }
772
-
773
- // If no duplicates, nothing to do
774
- if (seen.size === setCookies.length) return;
775
-
776
- response.headers.delete("set-cookie");
777
- for (const sc of seen.values()) {
778
- response.headers.append("set-cookie", sc);
779
- }
780
- }
781
-
782
- const FINGERPRINTED_ASSET_RE = /(?:\/_build)?\/assets\/.*-[a-zA-Z0-9_-]{8,}\.\w+$/;
783
-
784
- // ---------------------------------------------------------------------------
785
- // Auto geo-key detection (module-level singleton)
786
- // ---------------------------------------------------------------------------
787
- // Registered once so that multiple createDecoWorkerEntry calls in the same
788
- // isolate (e.g. integration tests) don't accumulate listeners. Uses "region"
789
- // (country+state) as the auto granularity — covers VTEX regionalization and
790
- // most geo matchers without the city-level fragmentation (~hundreds of buckets).
791
- // Sites that need city precision should set geoCacheKey: "city" explicitly.
792
-
793
- let _autoGeoKey: "off" | "region" = "off";
794
- let _autoGeoListenerInstalled = false;
795
-
796
- function installAutoGeoListener(): void {
797
- if (_autoGeoListenerInstalled) return;
798
- _autoGeoListenerInstalled = true;
799
- const update = (blocks: Record<string, unknown>) => {
800
- _autoGeoKey = detectLocationMatcher(blocks) ? "region" : "off";
801
- };
802
- onChange(update);
803
- update(loadBlocks());
804
- }
805
-
806
- const IMMUTABLE_HEADERS: Record<string, string> = {
807
- "Cache-Control": `public, max-age=${ONE_YEAR}, immutable`,
808
- Vary: "Accept-Encoding",
809
- };
810
-
811
- /** SHA-256 hex hash of a string — used for POST body cache keys. */
812
- async function hashText(text: string): Promise<string> {
813
- const data = new TextEncoder().encode(text);
814
- const buf = await crypto.subtle.digest("SHA-256", data);
815
- return Array.from(new Uint8Array(buf))
816
- .map((b) => b.toString(16).padStart(2, "0"))
817
- .join("");
818
- }
819
-
820
- // ---------------------------------------------------------------------------
821
- // CMS redirect cache — keyed by revision so cross-bundle setBlocks() calls
822
- // (Vite server-function split) are detected via globalThis.__deco.revision.
823
- // ---------------------------------------------------------------------------
824
-
825
- let _redirectMap: RedirectMap | null = null;
826
- let _redirectMapRevision: string | null = null;
827
-
828
- // ---------------------------------------------------------------------------
829
- // Factory
830
- // ---------------------------------------------------------------------------
831
-
832
- /**
833
- * Creates a Cloudflare Worker fetch handler that wraps a TanStack Start
834
- * server entry with intelligent edge caching.
835
- */
836
- export function createDecoWorkerEntry(
837
- serverEntry: ServerEntry,
838
- options: DecoWorkerEntryOptions = {},
839
- ): {
840
- fetch(
841
- request: Request,
842
- env: Record<string, unknown>,
843
- ctx: WorkerExecutionContext,
844
- ): Promise<Response>;
845
- } {
846
- const {
847
- admin,
848
- detectProfile: customDetect,
849
- deviceSpecificKeys = true,
850
- buildSegment: rawBuildSegment,
851
- purgeTokenEnv = "PURGE_TOKEN",
852
- bypassPaths,
853
- extraBypassPaths = [],
854
- fingerprintedAssetPattern = FINGERPRINTED_ASSET_RE,
855
- stripTrackingParams: shouldStripTracking = true,
856
- previewShell: customPreviewShell,
857
- cacheVersionEnv = "BUILD_HASH",
858
- securityHeaders: securityHeadersOpt,
859
- csp: cspOpt,
860
- autoInjectGeoCookies: geoOpt = true,
861
- geoCacheKey: geoCacheKeyOpt = "auto",
862
- safeCookies: safeCookiesOpt = DEFAULT_SAFE_COOKIES,
863
- staticPaths: staticPathsOpt = DEFAULT_STATIC_PATHS,
864
- cdnCacheControl: cdnCacheControlOpt = "no-store",
865
- observability: observabilityOpt,
866
- outboundUserAgent: outboundUserAgentOpt,
867
- } = options;
868
-
869
- // Patch global fetch once so every outbound request — apps calling
870
- // `fetch` directly, RequestContext.fetch, instrumentedFetch — carries a
871
- // User-Agent. Workers sends none by default, which WAFs on partner
872
- // origins read as bot traffic. Set-if-absent: callers that set their
873
- // own UA are untouched.
874
- if (outboundUserAgentOpt !== false) {
875
- installDefaultUserAgent(outboundUserAgentOpt);
876
- }
877
-
878
- // When geoCacheKey is "auto", install the module-level listener that watches
879
- // the decofile for website/matchers/location.ts. The listener is registered
880
- // only once regardless of how many times this factory is called, so there is
881
- // no listener accumulation in tests or dynamic worker-composition scenarios.
882
- if (geoCacheKeyOpt === "auto") {
883
- installAutoGeoListener();
884
- }
885
-
886
- /** Resolve the effective geo granularity for the current request. */
887
- function effectiveGeoKey(): "off" | "country" | "region" | "city" {
888
- return geoCacheKeyOpt === "auto" ? _autoGeoKey : geoCacheKeyOpt;
889
- }
890
-
891
- // Backfill `regionId` from Cloudflare geo when the consumer's buildSegment
892
- // doesn't set one. Without this, sites using website/matchers/location.ts
893
- // get a single cached response per device that leaks across regions: the
894
- // first visitor's resolved variant gets served to everyone. With this,
895
- // existing sites get region-segmented cache "for free" on bump — no
896
- // worker-entry.ts edit required.
897
- function readRegionFromRequest(request: Request): string | undefined {
898
- // Trust the Cloudflare-injected `request.cf` first — it can't be spoofed
899
- // by clients. Fall back to the `cf-region-code` header for environments
900
- // that surface geo only via headers (e.g. tests, non-CF proxies).
901
- const cf = (request as unknown as { cf?: { regionCode?: string } }).cf;
902
- if (cf?.regionCode) return cf.regionCode;
903
- const fromHeader = request.headers.get("cf-region-code");
904
- return fromHeader || undefined;
905
- }
906
-
907
- const buildSegment = rawBuildSegment
908
- ? (request: Request): SegmentKey => {
909
- const seg = rawBuildSegment(request);
910
- if (seg.regionId) return seg;
911
- if (effectiveGeoKey() === "off") return seg;
912
- const region = readRegionFromRequest(request);
913
- return region ? { ...seg, regionId: region } : seg;
914
- }
915
- : undefined;
916
-
917
- const safeCookieSet = new Set(safeCookiesOpt);
918
-
919
- // Build the final security headers map (merged defaults + custom + CSP)
920
- const secHeaders: Record<string, string> | null = (() => {
921
- if (securityHeadersOpt === false) return null;
922
- const base = { ...DEFAULT_SECURITY_HEADERS };
923
- // Ship an enforcement `frame-ancestors` CSP by default so the deco
924
- // admin/studio can embed the storefront for live preview without every
925
- // site copy-pasting the directive into its worker entry. A site can
926
- // override the whole header via securityHeaders["Content-Security-Policy"]
927
- // (the merge loop below wins) or disable all security headers with `false`.
928
- base["Content-Security-Policy"] = DEFAULT_FRAME_ANCESTORS_CSP;
929
- if (securityHeadersOpt) {
930
- for (const [k, v] of Object.entries(securityHeadersOpt)) base[k] = v;
931
- }
932
- if (cspOpt && cspOpt.length > 0) {
933
- base["Content-Security-Policy-Report-Only"] = cspOpt.join("; ");
934
- }
935
- return base;
936
- })();
937
-
938
- function applySecurityHeaders(resp: Response): Response {
939
- if (!secHeaders) return resp;
940
- const ct = resp.headers.get("content-type") ?? "";
941
- if (!ct.includes("text/html")) return resp;
942
- const out = new Response(resp.body, resp);
943
- for (const [k, v] of Object.entries(secHeaders)) {
944
- if (!out.headers.has(k)) out.headers.set(k, v);
945
- }
946
- return out;
947
- }
948
-
949
- const allBypassPaths = [...(bypassPaths ?? DEFAULT_BYPASS_PATHS), ...extraBypassPaths];
950
-
951
- // -- Helpers ----------------------------------------------------------------
952
-
953
- function isBypassPath(pathname: string): boolean {
954
- return allBypassPaths.some((bp) => pathname.startsWith(bp));
955
- }
956
-
957
- function isStaticAsset(pathname: string): boolean {
958
- if (fingerprintedAssetPattern.test(pathname)) return true;
959
- // Non-fingerprinted static paths (e.g., /fonts/)
960
- return staticPathsOpt.some((sp) => pathname.startsWith(sp));
961
- }
962
-
963
- function isCacheable(request: Request, url: URL): boolean {
964
- if (request.method !== "GET") return false;
965
- if (isBypassPath(url.pathname)) return false;
966
- if (url.searchParams.has("__deco_draft")) return false;
967
- if (url.searchParams.has("__deco_preview")) return false;
968
- if (url.searchParams.has("pathTemplate")) return false;
969
- // Forced matcher results must never be served from (or stored in) the
970
- // shared edge cache.
971
- if (url.searchParams.has(DECO_MATCHERS_OVERRIDE_PARAM)) return false;
972
- if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) return false;
973
- return true;
974
- }
975
-
976
- function getProfile(url: URL): CacheProfileName {
977
- // For TanStack GET server-fn requests, resolve the page path embedded in
978
- // the payload so the data request inherits the PAGE's profile (product /
979
- // search / static) instead of the generic "listing" derived from the
980
- // `/_serverFn/...` pathname. This is what makes SPA-navigation data
981
- // requests cache as long as their HTML documents (e.g. PDP 5min) and hit
982
- // the edge like full reloads do. Falls back to the request URL when no
983
- // embedded path is found.
984
- const pagePath = serverFnPagePath(url);
985
- const target = pagePath ? new URL(pagePath, url.origin) : url;
986
- if (customDetect) {
987
- const custom = customDetect(target);
988
- if (custom !== null) return custom;
989
- }
990
- return detectCacheProfile(target);
991
- }
992
-
993
- const KNOWN_SEGMENT_FIELDS = new Set([
994
- "device",
995
- "loggedIn",
996
- "salesChannel",
997
- "regionId",
998
- "flags",
999
- ]);
1000
-
1001
- function hashSegment(seg: SegmentKey): string {
1002
- const parts: string[] = [seg.device];
1003
- if (seg.loggedIn) parts.push("auth");
1004
- if (seg.salesChannel) parts.push(`sc=${seg.salesChannel}`);
1005
- if (seg.regionId) parts.push(`r=${seg.regionId}`);
1006
- if (seg.flags?.length) parts.push(`f=${seg.flags.sort().join(",")}`);
1007
- // Custom dimensions (anything beyond the known fields above) are
1008
- // serialized generically so they aren't silently dropped from the
1009
- // cache key — see #284.
1010
- const customKeys = Object.keys(seg)
1011
- .filter((k) => !KNOWN_SEGMENT_FIELDS.has(k) && seg[k] !== undefined)
1012
- .sort();
1013
- for (const k of customKeys) {
1014
- const v = seg[k];
1015
- if (v === "" || v === false || (Array.isArray(v) && v.length === 0)) {
1016
- continue;
1017
- }
1018
- const serialized = Array.isArray(v) ? [...v].sort().join(",") : v === true ? "" : String(v);
1019
- parts.push(serialized ? `${k}=${serialized}` : k);
1020
- }
1021
- return parts.join("|");
1022
- }
1023
-
1024
- /**
1025
- * Resolve the per-deploy cache-key version with this priority:
1026
- * 1. `env[cacheVersionEnv]` — explicit override (e.g. `wrangler
1027
- * deploy --var BUILD_HASH:foo`). Wins so callers can always
1028
- * force a specific value.
1029
- * 2. `__DECO_BUILD_HASH__` — build-time constant injected by
1030
- * `decoVitePlugin()` from WORKERS_CI_COMMIT_SHA / git rev-parse.
1031
- * This is the production path on Cloudflare Workers Builds.
1032
- * 3. Empty string — versioning disabled (legacy pre-plugin sites).
1033
- */
1034
- function getBuildHash(env: Record<string, unknown>): string {
1035
- if (cacheVersionEnv === false) return "";
1036
- const fromEnv = (env[cacheVersionEnv] as string) || "";
1037
- if (fromEnv) return fromEnv;
1038
- return typeof __DECO_BUILD_HASH__ !== "undefined" ? __DECO_BUILD_HASH__ : "";
1039
- }
1040
-
1041
- function readRequestCookie(request: Request, name: string): string | undefined {
1042
- for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
1043
- const idx = pair.indexOf("=");
1044
- if (idx <= 0) continue;
1045
- if (pair.slice(0, idx).trim() !== name) continue;
1046
- const raw = pair.slice(idx + 1).trim();
1047
- // Decode once so this matches TanStack's getCookies() used during SSR
1048
- // (see cms/resolve.ts) — otherwise the worker's cache key and the render
1049
- // could disagree on the cohort. The deco_segment value is raw base64 (no
1050
- // percent-escapes), so decoding is a no-op for it and safe in general.
1051
- try {
1052
- return decodeURIComponent(raw);
1053
- } catch {
1054
- return raw;
1055
- }
1056
- }
1057
- return undefined;
1058
- }
1059
-
1060
- function buildCacheKey(
1061
- request: Request,
1062
- env: Record<string, unknown>,
1063
- ): { key: Request; segment?: SegmentKey } {
1064
- const url = new URL(request.url);
1065
-
1066
- if (shouldStripTracking) {
1067
- const cleanPath = cleanPathForCacheKey(url.toString());
1068
- const cleanUrl = new URL(cleanPath, url.origin);
1069
- url.search = cleanUrl.search;
1070
- }
1071
-
1072
- // For GET server-fn requests (SPA navigation data), the page being loaded
1073
- // is encoded in the `payload` arg. Canonicalize it and strip variant params
1074
- // (skuId/idsku) that the loader ignores — otherwise `/p?skuId=X` and `/p`
1075
- // get distinct keys and every variant-carrying PDP→PDP nav MISSes, even
1076
- // though the resolved response is identical. Keeps PLP filter params intact.
1077
- if (url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/")) {
1078
- const payload = url.searchParams.get("payload");
1079
- if (payload) {
1080
- url.searchParams.set("payload", canonicalizeServerFnPayloadForCacheKey(payload));
1081
- }
1082
- }
1083
-
1084
- const version = getBuildHash(env);
1085
- if (version) {
1086
- url.searchParams.set("__v", version);
1087
- }
1088
-
1089
- // Include CF geo data in cache key so location matcher results don't leak
1090
- // across different geos. Granularity is controlled by `geoCacheKey`:
1091
- // "city" (default) → country|region|city, "region" → country|region,
1092
- // "country" → country only, "off" → omitted entirely.
1093
- const geoParam = buildGeoCacheParam(
1094
- (request as unknown as { cf?: Record<string, string> }).cf,
1095
- effectiveGeoKey(),
1096
- );
1097
- if (geoParam) url.searchParams.set("__cf_geo", geoParam);
1098
-
1099
- // Bots render every section eagerly (shouldDeferSection short-circuits in
1100
- // resolve.ts), producing a ~10x larger HTML payload (all eager-section
1101
- // props serialized into the SSR hydration blob). Key bots into a SEPARATE
1102
- // bucket so a crawler / Lighthouse / PageSpeed request can never poison the
1103
- // shared human cache entry (and vice-versa). This MUST use the same `isBot`
1104
- // predicate that gates shouldDeferSection — keying off a different bot
1105
- // regex (e.g. requestContext's BOT_RE, which misses Lighthouse/Semrush)
1106
- // would let the key and render decisions diverge and re-introduce poisoning.
1107
- if (isBot(request.headers.get("user-agent") ?? undefined)) {
1108
- url.searchParams.set("__bot", "1");
1109
- }
1110
-
1111
- // Programmatic, non-navigation fetches (the PLP "Ver mais"/load-more AJAX,
1112
- // embeds, server-to-server) read the static SSR HTML and can't run the
1113
- // client-side deferred-section resolution, so the origin renders every
1114
- // section eagerly for them (isProgrammaticFetch in cms/resolve.ts) — the
1115
- // same ~10x larger payload as bots. Key them into a SEPARATE `__fetch=1`
1116
- // bucket so a fetch-triggered eager response never poisons the navigation
1117
- // (deferred) entry, and vice-versa. MUST use the same `Sec-Fetch-Dest:
1118
- // empty` signal as isProgrammaticFetch so the key and render decisions can't
1119
- // diverge. `/_serverFn` (SPA-nav data) is excluded: it has its own keying
1120
- // and stays eager via isClientNavigation, not this bucket.
1121
- const secFetchDest = request.headers.get("sec-fetch-dest");
1122
- const isServerFnPath =
1123
- url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/");
1124
- if (!isServerFnPath && secFetchDest === "empty") {
1125
- url.searchParams.set("__fetch", "1");
1126
- }
1127
-
1128
- // A/B cohort split: fold the sticky `deco_segment` cookie into the cache
1129
- // key so each variant keeps its own cached HTML. The cookie carries the
1130
- // traffic fingerprint (see sdk/flags.ts), so a `traffic` change lands
1131
- // cohorts in fresh buckets. Empty for non-A/B visitors (no cookie) → they
1132
- // keep sharing one entry. A freshly-assigned visitor sets the cookie on the
1133
- // response, which is not a "safe" cookie, so that one response bypasses the
1134
- // cache and never poisons the shared entry.
1135
- const flagToken = segmentCacheToken(
1136
- parseSegmentCookie(readRequestCookie(request, SEGMENT_COOKIE)),
1137
- );
1138
- if (flagToken) {
1139
- url.searchParams.set("__abf", flagToken);
1140
- }
1141
-
1142
- if (buildSegment) {
1143
- const segment = buildSegment(request);
1144
- url.searchParams.set("__seg", hashSegment(segment));
1145
- return { key: new Request(url.toString(), { method: "GET" }), segment };
1146
- }
1147
-
1148
- if (deviceSpecificKeys) {
1149
- const device = isMobileUA(request.headers.get("user-agent") ?? "") ? "mobile" : "desktop";
1150
- url.searchParams.set("__cf_device", device);
1151
- }
1152
-
1153
- return { key: new Request(url.toString(), { method: "GET" }) };
1154
- }
1155
-
1156
- // -- Purge handler ----------------------------------------------------------
1157
-
1158
- interface PurgeRequestBody {
1159
- paths?: string[];
1160
- countries?: string[];
1161
- /** Sales channels to include in segment combos. Defaults to ["1"]. */
1162
- salesChannels?: string[];
1163
- /** Region IDs to include in segment combos. Each ID generates additional entries. */
1164
- regionIds?: string[];
1165
- }
1166
-
1167
- function buildPurgeSegments(body: PurgeRequestBody): SegmentKey[] {
1168
- const devices: Array<"mobile" | "desktop"> = ["mobile", "desktop"];
1169
- const channels = body.salesChannels ?? ["1"];
1170
- const regions: Array<string | undefined> = [undefined, ...(body.regionIds ?? [])];
1171
-
1172
- const segments: SegmentKey[] = [];
1173
- for (const device of devices) {
1174
- for (const salesChannel of channels) {
1175
- for (const regionId of regions) {
1176
- segments.push({ device, salesChannel, regionId });
1177
- }
1178
- }
1179
- segments.push({ device });
1180
- }
1181
- return segments;
1182
- }
1183
-
1184
- // Constant-time string compare — avoids a byte-wise timing side-channel on the
1185
- // purge token. Length is not secret here, so a fast length-mismatch reject is fine.
1186
- function timingSafeEqualStr(a: string, b: string): boolean {
1187
- if (a.length !== b.length) return false;
1188
- let diff = 0;
1189
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1190
- return diff === 0;
1191
- }
1192
-
1193
- // Shared auth for the cache purge endpoints. Returns a Response when the request
1194
- // is unauthorized or purge is disabled, or null when authorized. Single source
1195
- // of truth so /_cache/purge and /_cache/purge-loaders can't drift.
1196
- function authorizePurge(request: Request, env: Record<string, unknown>): Response | null {
1197
- if (purgeTokenEnv === false) {
1198
- return new Response("Purge disabled", { status: 404 });
1199
- }
1200
- const token = (env[purgeTokenEnv] as string) || "";
1201
- const auth = request.headers.get("Authorization") ?? "";
1202
- if (!token || !timingSafeEqualStr(auth, `Bearer ${token}`)) {
1203
- return new Response("Unauthorized", { status: 401 });
1204
- }
1205
- return null;
1206
- }
1207
-
1208
- async function handlePurge(request: Request, env: Record<string, unknown>): Promise<Response> {
1209
- const denied = authorizePurge(request, env);
1210
- if (denied) return denied;
1211
-
1212
- let body: PurgeRequestBody;
1213
- try {
1214
- body = await request.json();
1215
- } catch {
1216
- return new Response("Invalid JSON body", { status: 400 });
1217
- }
1218
-
1219
- const paths = body.paths;
1220
- if (!Array.isArray(paths) || paths.length === 0) {
1221
- return new Response('Body must include "paths": ["/", "/page"]', { status: 400 });
1222
- }
1223
-
1224
- const geoVariants = body.countries ?? [];
1225
-
1226
- const cache = isDevMode()
1227
- ? null
1228
- : typeof caches !== "undefined"
1229
- ? ((caches as unknown as { default?: Cache }).default ?? null)
1230
- : null;
1231
-
1232
- if (!cache) {
1233
- return Response.json({ purged: [], total: 0, note: "Cache API unavailable" });
1234
- }
1235
-
1236
- const baseUrl = new URL(request.url).origin;
1237
- const purged: string[] = [];
1238
-
1239
- const geoKeys: (string | null)[] = [null, ...geoVariants];
1240
-
1241
- // Bots (`__bot=1`) and programmatic fetches (`__fetch=1`) are each keyed
1242
- // into a separate bucket (see buildCacheKey), so purge every combination.
1243
- // The param-set order below MUST mirror buildCacheKey exactly (__v,
1244
- // __cf_geo, __bot, __fetch, then __seg/__cf_device) so the purge key
1245
- // byte-matches the stored key.
1246
- const botVariants = [false, true] as const;
1247
- const fetchVariants = [false, true] as const;
1248
-
1249
- for (const p of paths) {
1250
- if (buildSegment) {
1251
- const segments = buildPurgeSegments(body);
1252
- for (const seg of segments) {
1253
- for (const cc of geoKeys) {
1254
- for (const bot of botVariants) {
1255
- for (const fetchReq of fetchVariants) {
1256
- const url = new URL(p, baseUrl);
1257
- const purgeVersion = getBuildHash(env);
1258
- if (purgeVersion) url.searchParams.set("__v", purgeVersion);
1259
- if (cc) url.searchParams.set("__cf_geo", cc);
1260
- if (bot) url.searchParams.set("__bot", "1");
1261
- if (fetchReq) url.searchParams.set("__fetch", "1");
1262
- url.searchParams.set("__seg", hashSegment(seg));
1263
- const key = new Request(url.toString(), { method: "GET" });
1264
- try {
1265
- if (await cache.delete(key)) {
1266
- const tags = [
1267
- hashSegment(seg),
1268
- cc,
1269
- bot ? "bot" : null,
1270
- fetchReq ? "fetch" : null,
1271
- ]
1272
- .filter(Boolean)
1273
- .join(", ");
1274
- purged.push(`${p} (${tags})`);
1275
- }
1276
- } catch {
1277
- /* ignore */
1278
- }
1279
- }
1280
- }
1281
- }
1282
- }
1283
- } else {
1284
- const devices = deviceSpecificKeys ? (["mobile", "desktop"] as const) : ([null] as const);
1285
-
1286
- for (const device of devices) {
1287
- for (const cc of geoKeys) {
1288
- for (const bot of botVariants) {
1289
- for (const fetchReq of fetchVariants) {
1290
- const url = new URL(p, baseUrl);
1291
- const purgeVersion = getBuildHash(env);
1292
- if (purgeVersion) url.searchParams.set("__v", purgeVersion);
1293
- if (cc) url.searchParams.set("__cf_geo", cc);
1294
- if (bot) url.searchParams.set("__bot", "1");
1295
- if (fetchReq) url.searchParams.set("__fetch", "1");
1296
- if (device) url.searchParams.set("__cf_device", device);
1297
- const key = new Request(url.toString(), { method: "GET" });
1298
- try {
1299
- if (await cache.delete(key)) {
1300
- const parts = [device, cc, bot ? "bot" : null, fetchReq ? "fetch" : null]
1301
- .filter(Boolean)
1302
- .join(", ");
1303
- purged.push(parts ? `${p} (${parts})` : p);
1304
- }
1305
- } catch {
1306
- /* ignore */
1307
- }
1308
- }
1309
- }
1310
- }
1311
- }
1312
- }
1313
- }
1314
-
1315
- return Response.json({ purged, total: purged.length });
1316
- }
1317
-
1318
- // Purge the in-memory loader/commerce cache for THIS isolate. Same auth as
1319
- // handlePurge (Bearer `purgeTokenEnv`). Per-isolate by nature — the isolate
1320
- // that serves this request clears its cache; other live isolates keep theirs
1321
- // until they're recycled or hit too. For a guaranteed global flush, redeploy
1322
- // (loader cache keys are build-hash versioned).
1323
- async function handlePurgeLoaders(
1324
- request: Request,
1325
- env: Record<string, unknown>,
1326
- ): Promise<Response> {
1327
- const denied = authorizePurge(request, env);
1328
- if (denied) return denied;
1329
- clearLoaderCache();
1330
- return Response.json({ cleared: true, scope: "isolate" });
1331
- }
1332
-
1333
- // -- Admin route handler ---------------------------------------------------
1334
-
1335
- const ADMIN_NO_CACHE: Record<string, string> = {
1336
- "Cache-Control": "no-store, no-cache, must-revalidate",
1337
- "CDN-Cache-Control": "no-store",
1338
- "Surrogate-Control": "no-store",
1339
- };
1340
-
1341
- function addCors(response: Response, request: Request): Response {
1342
- if (!admin) return response;
1343
- const cors = admin.corsHeaders(request);
1344
- const resp = new Response(response.body, {
1345
- status: response.status,
1346
- statusText: response.statusText,
1347
- headers: new Headers(response.headers),
1348
- });
1349
- for (const [k, v] of Object.entries({ ...cors, ...ADMIN_NO_CACHE })) {
1350
- resp.headers.set(k, v);
1351
- }
1352
- return resp;
1353
- }
1354
-
1355
- async function tryAdminRoute(request: Request): Promise<Response | null> {
1356
- if (!admin) return null;
1357
-
1358
- const url = new URL(request.url);
1359
- const { pathname } = url;
1360
- const method = request.method;
1361
-
1362
- if (pathname === "/live/_meta") {
1363
- if (method === "OPTIONS") {
1364
- return new Response(null, {
1365
- status: 204,
1366
- headers: { ...admin.corsHeaders(request), ...ADMIN_NO_CACHE },
1367
- });
1368
- }
1369
- const resp = await withTracing("deco.admin.meta", async () => admin.handleMeta(request));
1370
- return addCors(resp, request);
1371
- }
1372
-
1373
- if (pathname === "/.decofile") {
1374
- if (method === "OPTIONS") {
1375
- return new Response(null, {
1376
- status: 204,
1377
- headers: { ...admin.corsHeaders(request), ...ADMIN_NO_CACHE },
1378
- });
1379
- }
1380
- if (method === "POST") {
1381
- const resp = await withTracing("deco.admin.decofile.reload", () =>
1382
- Promise.resolve(admin.handleDecofileReload(request)),
1383
- );
1384
- return addCors(resp, request);
1385
- }
1386
- const resp = await withTracing("deco.admin.decofile.read", async () =>
1387
- admin.handleDecofileRead(),
1388
- );
1389
- return addCors(resp, request);
1390
- }
1391
-
1392
- if (pathname === "/deco/_liveness") {
1393
- return new Response("OK", {
1394
- status: 200,
1395
- headers: { "Content-Type": "text/plain", ...ADMIN_NO_CACHE },
1396
- });
1397
- }
1398
-
1399
- if ((pathname === "/live/previews" || pathname === "/live/previews/") && method === "GET") {
1400
- const shell = customPreviewShell ?? buildPreviewShell();
1401
- return new Response(shell, {
1402
- status: 200,
1403
- headers: {
1404
- "Content-Type": "text/html; charset=utf-8",
1405
- ...admin.corsHeaders(request),
1406
- ...ADMIN_NO_CACHE,
1407
- },
1408
- });
1409
- }
1410
-
1411
- if (pathname.startsWith("/live/previews/") && pathname !== "/live/previews/") {
1412
- if (method === "OPTIONS") {
1413
- return new Response(null, {
1414
- status: 204,
1415
- headers: { ...admin.corsHeaders(request), ...ADMIN_NO_CACHE },
1416
- });
1417
- }
1418
- const pathComponent = pathname.slice("/live/previews/".length);
1419
- const resp = await withTracing(
1420
- "deco.admin.render",
1421
- () => Promise.resolve(admin.handleRender(request)),
1422
- { "cms.component": pathComponent || "(page)" },
1423
- );
1424
- return addCors(resp, request);
1425
- }
1426
-
1427
- return null;
1428
- }
1429
-
1430
- // -- Main fetch handler -----------------------------------------------------
1431
-
1432
- const handler = {
1433
- async fetch(
1434
- request: Request,
1435
- env: Record<string, unknown>,
1436
- ctx: WorkerExecutionContext,
1437
- ): Promise<Response> {
1438
- const startedAt = performance.now();
1439
- const reqUrl = new URL(request.url);
1440
- const method = request.method;
1441
-
1442
- // Inject CF geo data as cookies for location matchers (before anything reads cookies)
1443
- if (geoOpt) {
1444
- request = injectGeoCookies(request);
1445
- }
1446
-
1447
- // Captured inside the withTracing scope so the outer post-response
1448
- // path (response headers, metric labels, log attrs) can stamp the
1449
- // trace ID without re-entering AsyncLocalStorage. The closure
1450
- // captures whatever the framework span saw; if the bridge tracer
1451
- // is a no-op, both stay empty strings and the header writes below
1452
- // become no-ops.
1453
- const identity = { requestId: "", traceId: "" };
1454
-
1455
- // Wrap the entire request in a RequestContext so that all code
1456
- // in the call stack (loaders, invoke handlers, vtexFetchWithCookies)
1457
- // can access the request and write response headers.
1458
- const response = await RequestContext.run(request, async () => {
1459
- // Stash env so request-scoped adapters (Workers Analytics Engine,
1460
- // future binding-driven destinations) can resolve their bindings
1461
- // via getRuntimeEnv() in sdk/otelAdapters.ts.
1462
- setRuntimeEnv(env);
1463
-
1464
- // RequestContext.run already resolved request.id from the
1465
- // inbound headers (precedence: x-request-id → cf-ray → UUID).
1466
- // Lift it into the closure so the response-write path below has
1467
- // access without going back through ALS.
1468
- identity.requestId = RequestContext.requestId ?? "";
1469
-
1470
- // W3C tracecontext propagation — parse the inbound `traceparent`
1471
- // header so the OTLP trace exporter creates root spans under
1472
- // the caller's trace ID. No-op when the header is absent or
1473
- // malformed; the exporter falls back to a fresh trace ID.
1474
- const incomingTraceparent = request.headers.get("traceparent");
1475
- const remoteTrace = parseTraceparent(incomingTraceparent);
1476
- if (remoteTrace) _setRequestTraceContext(remoteTrace);
1477
-
1478
- // Debug sampling: ?__d=<any> forces this request to be fully sampled
1479
- // regardless of headSamplingRate. Lets operators trace a specific
1480
- // production request without changing global sampling rates.
1481
- if (new URL(request.url).searchParams.has("__d")) _setDebugSampled();
1482
-
1483
- // Wrap inner handler in a single root span carrying our normalized
1484
- // path/method attributes. The framework span flows BOTH ways:
1485
- // - via the OTLP direct-POST tracer (when DECO_OTEL_TRACES_ENDPOINT
1486
- // is set) → ClickHouse `otel_traces`,
1487
- // - via the @opentelemetry/api bridge → CF Workers Observability
1488
- // when `observability.traces.enabled = true` in wrangler.jsonc.
1489
- // See `configureTracerStack` in `otel.ts` for the composition.
1490
- return withTracing(
1491
- "deco.http.request",
1492
- async () => {
1493
- // Stamp identity on the root span so every child span +
1494
- // every log emitted under the same active span carries
1495
- // them. Done inside the span scope so getActiveSpan()
1496
- // returns the right span. Cheap no-op for any of these
1497
- // when no tracer is configured.
1498
- if (identity.requestId) {
1499
- setSpanAttribute("request.id", identity.requestId);
1500
- }
1501
- const spanCtx = getActiveSpan()?.spanContext?.();
1502
- if (spanCtx?.traceId) {
1503
- identity.traceId = spanCtx.traceId;
1504
- }
1505
-
1506
- // Run app middleware (injects app state into RequestContext.bag,
1507
- // runs registered middleware like VTEX cookie forwarding).
1508
- const appMw = getAppMiddleware();
1509
- const innerResponse = appMw
1510
- ? await appMw(request, () => handleRequest(request, env, ctx))
1511
- : await handleRequest(request, env, ctx);
1512
-
1513
- // Access log at debug — no-op in prod (default warn minLevel),
1514
- // visible in dev with DECO_OTEL_LOGS_MIN_LEVEL=debug.
1515
- // Must run inside the span so getSpan() returns the active root
1516
- // span and trace_id is stamped on the log record.
1517
- try {
1518
- logRequest(request, innerResponse.status, performance.now() - startedAt, {
1519
- ...(identity.requestId ? { "request.id": identity.requestId } : {}),
1520
- ...(identity.traceId ? { "trace.id": identity.traceId } : {}),
1521
- });
1522
- } catch {
1523
- /* swallow — observability must never fail the request */
1524
- }
1525
-
1526
- return innerResponse;
1527
- },
1528
- {
1529
- "http.method": method,
1530
- "url.path": reqUrl.pathname,
1531
- },
1532
- );
1533
- });
1534
-
1535
- // Deduplicate Set-Cookie headers — multiple layers (VTEX middleware,
1536
- // invoke handlers, etc.) may independently append the same cookie.
1537
- deduplicateSetCookies(response);
1538
-
1539
- let finalResponse = applySecurityHeaders(response);
1540
-
1541
- // Echo request.id + trace.id back to the client / tail worker.
1542
- // The CF tail worker reads these headers off the response to
1543
- // stamp `request.id` / `trace.id` on tail rows — they're the
1544
- // join key against direct-POST logs/metrics (which carry the
1545
- // same values via the logger + span attributes).
1546
- //
1547
- // Headers are written defensively: if a downstream component
1548
- // already set them (e.g. a proxy upstream), the existing value
1549
- // wins. That's intentional — a load-balancer-supplied request.id
1550
- // is more useful for cross-system correlation than ours.
1551
- if (identity.requestId || identity.traceId) {
1552
- // applySecurityHeaders may return either the original Response
1553
- // (HTML path, fresh Headers) or the same Response (non-HTML
1554
- // path). Either way Response.headers is mutable on Workers, so
1555
- // we can set on it directly.
1556
- if (identity.requestId && !finalResponse.headers.has("x-request-id")) {
1557
- try {
1558
- finalResponse.headers.set("x-request-id", identity.requestId);
1559
- } catch {
1560
- // Some intermediaries seal response headers (e.g. cached
1561
- // responses replayed from the Cache API). Fall back to
1562
- // building a new Response.
1563
- const headers = new Headers(finalResponse.headers);
1564
- if (identity.requestId) headers.set("x-request-id", identity.requestId);
1565
- if (identity.traceId) headers.set("x-trace-id", identity.traceId);
1566
- finalResponse = new Response(finalResponse.body, {
1567
- status: finalResponse.status,
1568
- statusText: finalResponse.statusText,
1569
- headers,
1570
- });
1571
- }
1572
- }
1573
- if (identity.traceId && !finalResponse.headers.has("x-trace-id")) {
1574
- try {
1575
- finalResponse.headers.set("x-trace-id", identity.traceId);
1576
- } catch {
1577
- /* see above — sealed header case already handled */
1578
- }
1579
- }
1580
- }
1581
-
1582
- // Old-runtime parity: deco-cx/deco stamped `x-powered-by: deco@<ver>`
1583
- // on every response (utils/http.ts defaultHeaders); partner-side logs
1584
- // and ops tooling use it to identify deco traffic. Set-if-absent so
1585
- // an upstream origin's own value wins.
1586
- if (!finalResponse.headers.has("x-powered-by")) {
1587
- try {
1588
- finalResponse.headers.set("x-powered-by", DECO_POWERED_BY);
1589
- } catch {
1590
- /* sealed headers (cached replay) — identification is best-effort */
1591
- }
1592
- }
1593
-
1594
- // Metrics + structured request log. Done after security headers so
1595
- // the recorded status reflects what the client actually receives.
1596
- // Both calls are no-ops when no meter / logger is configured.
1597
- const durationMs = performance.now() - startedAt;
1598
- try {
1599
- // Phase 2 / D-11 canonical labels — lift the cache decision +
1600
- // profile + region off the response we just built so dashboards
1601
- // can answer "cache hit rate per route" from
1602
- // `http.server.request.duration` alone, no join to a cache counter
1603
- // required.
1604
- const xCacheRaw = finalResponse.headers.get("X-Cache");
1605
- const cacheDecision = isCacheDecision(xCacheRaw) ? xCacheRaw : undefined;
1606
- const colo = (request as unknown as { cf?: { colo?: string } }).cf?.colo;
1607
- // NOTE: `request.id` and `trace.id` are intentionally NOT stamped
1608
- // on the metric. They are per-request identifiers and would
1609
- // collapse aggregation (every request → its own histogram data
1610
- // point). They are stamped on the span; use traces for
1611
- // request-level correlation.
1612
- recordRequestMetric(method, reqUrl.pathname, finalResponse.status, durationMs, {
1613
- ...(cacheDecision ? { cache_decision: cacheDecision } : {}),
1614
- ...(cacheDecision ? { cache_layer: "edge" as const } : {}),
1615
- ...(typeof colo === "string" && colo.length > 0 ? { region: colo } : {}),
1616
- });
1617
- } catch {
1618
- /* swallow — observability must never fail the request */
1619
- }
1620
- return finalResponse;
1621
- },
1622
- };
1623
-
1624
- // Auto-instrument with `instrumentWorker` unless explicitly opted out.
1625
- // When `observabilityOpt === false` the site is taking control of its own
1626
- // OTel wiring; otherwise the framework wraps the handler so that, when
1627
- // `DECO_OTEL_*_ENDPOINT` env vars are configured, telemetry flows
1628
- // without any change to the site's worker-entry. When the env vars are
1629
- // absent the wrap is a no-op (no exporters created, no flush calls).
1630
- return observabilityOpt === false
1631
- ? handler
1632
- : instrumentWorker(handler, (observabilityOpt as OtelOptions | undefined) ?? {});
1633
-
1634
- async function handleRequest(
1635
- request: Request,
1636
- env: Record<string, unknown>,
1637
- ctx: WorkerExecutionContext,
1638
- ): Promise<Response> {
1639
- const url = new URL(request.url);
1640
-
1641
- // Fast-deploy: hydrate the in-memory decofile from KV on the first request
1642
- // per isolate (awaited, ~10-30ms once), then opportunistically poll for
1643
- // content changes (non-blocking, via ctx.waitUntil). No-op unless the
1644
- // DECO_KV binding is present — non-migrated sites are unaffected. Runs
1645
- // before admin routes so /.decofile reads reflect KV too.
1646
- await ensureBlocksHydrated(env, ctx);
1647
- maybePollRevision(env, ctx);
1648
-
1649
- // Admin routes (/_meta, /.decofile, /live/previews) — always handled first
1650
- const adminResponse = await tryAdminRoute(request);
1651
- if (adminResponse) return adminResponse;
1652
-
1653
- // Purge endpoint
1654
- if (url.pathname === "/_cache/purge" && request.method === "POST") {
1655
- return handlePurge(request, env);
1656
- }
1657
-
1658
- // Loader/commerce cache purge (in-memory, this isolate only). Escape hatch
1659
- // to invalidate loader results immediately after an out-of-band upstream
1660
- // change (e.g. a Magento catalog sync) without waiting out the TTL. A
1661
- // redeploy is the global lever — loader cache keys are build-hash versioned.
1662
- if (url.pathname === "/_cache/purge-loaders" && request.method === "POST") {
1663
- return handlePurgeLoaders(request, env);
1664
- }
1665
-
1666
- // CMS redirects (website/loaders/redirect.ts blocks) — checked before
1667
- // ?asJson and commerce proxy so every request path respects redirects.
1668
- // Revision-keyed so cross-bundle setBlocks() calls are detected even when
1669
- // onChange listeners don't fire across Vite split-bundle module instances.
1670
- const currentRevision = getRevision();
1671
- if (_redirectMapRevision !== currentRevision) {
1672
- _redirectMap = loadRedirects(loadBlocks());
1673
- _redirectMapRevision = currentRevision;
1674
- }
1675
- const cmsRedirect = matchRedirect(url.pathname, _redirectMap!);
1676
- if (cmsRedirect) {
1677
- return new Response(null, {
1678
- status: cmsRedirect.status,
1679
- headers: { Location: encodeURI(cmsRedirect.to) },
1680
- });
1681
- }
1682
-
1683
- // ?asJson — return resolved page data as JSON (legacy deco compat)
1684
- if (url.searchParams.has("asJson") && request.method === "GET") {
1685
- const basePath = url.pathname;
1686
- const cookies: Record<string, string> = {};
1687
- for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
1688
- const [k, ...v] = pair.split("=");
1689
- if (k?.trim()) cookies[k.trim()] = v.join("=").trim();
1690
- }
1691
- const matcherCtx: MatcherContext = {
1692
- userAgent: request.headers.get("user-agent") ?? "",
1693
- url: url.toString(),
1694
- path: basePath,
1695
- cookies,
1696
- request,
1697
- };
1698
- const page = await resolveDecoPage(basePath, matcherCtx);
1699
- if (!page) {
1700
- return Response.json(null, {
1701
- status: 404,
1702
- headers: { "Access-Control-Allow-Origin": "*" },
1703
- });
1704
- }
1705
- const enrichedSections = await runSectionLoaders(page.resolvedSections, request);
1706
-
1707
- // Run SEO section loader if registered
1708
- let seoResult = page.seoSection;
1709
- if (seoResult) {
1710
- try {
1711
- seoResult = await runSingleSectionLoader(seoResult, request);
1712
- } catch {
1713
- // use unloaded seoSection
1714
- }
1715
- }
1716
-
1717
- // Merge site-wide SEO defaults into seo props
1718
- const blocks = loadBlocks();
1719
- const site = blocks["Site"] as Record<string, unknown> | undefined;
1720
- const fullSiteSeo = (site?.seo as Record<string, unknown>) ?? {};
1721
-
1722
- // When SeoV2 loader ran, use its output as base (preserves key order)
1723
- // and only fill in missing fields from the site-wide SEO config.
1724
- const loaderProps = seoResult?.props ?? {};
1725
- const seoProps: Record<string, unknown> = { ...loaderProps };
1726
- for (const [k, v] of Object.entries(fullSiteSeo)) {
1727
- if (!(k in seoProps)) seoProps[k] = v;
1728
- }
1729
- // Strip internal template fields
1730
- delete seoProps.titleTemplate;
1731
- delete seoProps.descriptionTemplate;
1732
-
1733
- // Build resolveChain statically to match legacy deco-cx/deco format.
1734
- type FieldResolver = { type: string; value: string | number };
1735
- const rawKey = page.blockKey ?? `pages-${page.name}`;
1736
- const encodedKey = rawKey.replace(
1737
- /^(pages-)(.+)$/,
1738
- (_m, prefix, rest) => prefix + encodeURIComponent(rest),
1739
- );
1740
- const pageChain: FieldResolver[] = [
1741
- { type: "resolver", value: "website/handlers/fresh.ts" },
1742
- { type: "prop", value: "page" },
1743
- { type: "resolver", value: "resolved" },
1744
- { type: "resolvable", value: encodedKey },
1745
- { type: "resolver", value: "website/pages/Page.tsx" },
1746
- ];
1747
-
1748
- const seoChain: FieldResolver[] = [
1749
- ...pageChain,
1750
- { type: "prop", value: "seo" },
1751
- { type: "resolver", value: seoResult?.component ?? "website/sections/Seo/SeoV2.tsx" },
1752
- ];
1753
-
1754
- const result = {
1755
- props: {
1756
- name: page.name,
1757
- path: page.path,
1758
- seo: {
1759
- props: seoProps,
1760
- metadata: {
1761
- resolveChain: seoChain,
1762
- component: seoResult?.component ?? "website/sections/Seo/SeoV2.tsx",
1763
- },
1764
- },
1765
- sections: enrichedSections.map((s, i) => ({
1766
- props: s.props,
1767
- metadata: {
1768
- resolveChain: [
1769
- ...pageChain,
1770
- { type: "prop", value: "sections" },
1771
- { type: "prop", value: String(i) },
1772
- { type: "resolver", value: s.component },
1773
- ],
1774
- component: s.component,
1775
- },
1776
- })),
1777
- devMode: false,
1778
- unindexedDomain: false,
1779
- },
1780
- metadata: {
1781
- resolveChain: pageChain,
1782
- component: "website/pages/Page.tsx",
1783
- },
1784
- };
1785
- return Response.json(result, {
1786
- headers: {
1787
- "Access-Control-Allow-Origin": "*",
1788
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
1789
- "Access-Control-Allow-Methods": "GET, OPTIONS",
1790
- },
1791
- });
1792
- }
1793
-
1794
- // Commerce proxy (checkout, account, API, etc.)
1795
- if (options.proxyHandler) {
1796
- const proxyResponse = await options.proxyHandler(request, url);
1797
- if (proxyResponse) return proxyResponse;
1798
- }
1799
-
1800
- // Static fingerprinted assets — serve from origin with immutable headers
1801
- if (isStaticAsset(url.pathname)) {
1802
- const origin = await serverEntry.fetch(request, env, ctx);
1803
- if (origin.status === 200) {
1804
- const ct = origin.headers.get("content-type") ?? "";
1805
- if (ct.includes("text/html")) {
1806
- return new Response("Not Found", { status: 404 });
1807
- }
1808
- const resp = new Response(origin.body, origin);
1809
- for (const [k, v] of Object.entries(IMMUTABLE_HEADERS)) {
1810
- resp.headers.set(k, v);
1811
- }
1812
- return resp;
1813
- }
1814
- return origin;
1815
- }
1816
-
1817
- // -----------------------------------------------------------------
1818
- // POST _serverFn — edge-cacheable using body-hash as cache key.
1819
- // These carry public CMS section data (shelves, deferred sections)
1820
- // that benefits from edge caching despite being POST requests.
1821
- // -----------------------------------------------------------------
1822
- if (
1823
- request.method === "POST" &&
1824
- (url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/"))
1825
- ) {
1826
- const serverFnCache = isDevMode()
1827
- ? null
1828
- : typeof caches !== "undefined"
1829
- ? ((caches as unknown as { default?: Cache }).default ?? null)
1830
- : null;
1831
-
1832
- // Build segment once — used for logged-in check and cache key
1833
- const sfnSegment = buildSegment ? buildSegment(request) : undefined;
1834
-
1835
- // Logged-in users always bypass — personalized content must not leak
1836
- if (sfnSegment?.loggedIn) {
1837
- const origin = await serverEntry.fetch(request, env, ctx);
1838
- const resp = new Response(origin.body, origin);
1839
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
1840
- resp.headers.set("X-Cache", "BYPASS");
1841
- resp.headers.set("X-Cache-Reason", "logged-in");
1842
- return resp;
1843
- }
1844
-
1845
- // Matcher overrides via header don't vary the body-hash cache key —
1846
- // bypass so forced variants are neither stored nor served from cache.
1847
- // (QS overrides travel inside the payload's pageUrl, so they already
1848
- // produce a distinct body hash.)
1849
- if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) {
1850
- const origin = await serverEntry.fetch(request, env, ctx);
1851
- const resp = new Response(origin.body, origin);
1852
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
1853
- resp.headers.set("X-Cache", "BYPASS");
1854
- resp.headers.set("X-Cache-Reason", "matchers-override");
1855
- return resp;
1856
- }
1857
-
1858
- // Clone request before consuming body — the clone goes to origin
1859
- // untouched so TanStack Start internals (cookie passthrough, etc.)
1860
- // work correctly. We only read the body for the cache key hash.
1861
- const originClone = request.clone();
1862
- const body = await request.text();
1863
- const bodyHash = await hashText(body);
1864
-
1865
- // Build a synthetic GET cache key from the URL + body hash + segment
1866
- // Includes device, salesChannel, regionId, flags — so users in
1867
- // different regions or channels get separate cache entries.
1868
- const cacheKeyUrl = new URL(request.url);
1869
- cacheKeyUrl.searchParams.set("__body", bodyHash);
1870
- const sfnVersion = getBuildHash(env);
1871
- if (sfnVersion) cacheKeyUrl.searchParams.set("__v", sfnVersion);
1872
- if (sfnSegment) {
1873
- cacheKeyUrl.searchParams.set("__seg", hashSegment(sfnSegment));
1874
- } else if (deviceSpecificKeys) {
1875
- const device = isMobileUA(request.headers.get("user-agent") ?? "") ? "mobile" : "desktop";
1876
- cacheKeyUrl.searchParams.set("__cf_device", device);
1877
- }
1878
- // Include CF geo data so location-based content doesn't leak across geos.
1879
- // Uses the same effectiveGeoKey() as the GET path so geoCacheKey config
1880
- // is respected consistently for both HTML and server-fn responses.
1881
- const sfnGeoParam = buildGeoCacheParam(
1882
- (request as unknown as { cf?: Record<string, string> }).cf,
1883
- effectiveGeoKey(),
1884
- );
1885
- if (sfnGeoParam) cacheKeyUrl.searchParams.set("__cf_geo", sfnGeoParam);
1886
- const sfnCacheKey = new Request(cacheKeyUrl.toString(), { method: "GET" });
1887
-
1888
- // Use "listing" profile for server function responses
1889
- const sfnProfile: CacheProfileName = "listing";
1890
- const sfnEdge = edgeCacheConfig(sfnProfile);
1891
-
1892
- // Check edge cache
1893
- let sfnCached: Response | undefined;
1894
- if (serverFnCache) {
1895
- try {
1896
- sfnCached = await withTracing(
1897
- "deco.cache.lookup",
1898
- async () => (await serverFnCache.match(sfnCacheKey)) ?? undefined,
1899
- { "cache.profile": sfnProfile, "cache.kind": "serverFn" },
1900
- );
1901
- } catch {
1902
- /* Cache API unavailable */
1903
- }
1904
- }
1905
-
1906
- if (sfnCached && sfnEdge.fresh > 0) {
1907
- const storedAt = Number(sfnCached.headers.get("X-Deco-Stored-At") || "0");
1908
- const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
1909
-
1910
- if (ageSec < sfnEdge.fresh) {
1911
- recordCacheMetric(true, sfnProfile, "HIT", "edge");
1912
- const out = new Response(sfnCached.body, sfnCached);
1913
- const hdrs = cacheHeaders(sfnProfile);
1914
- for (const [k, v] of Object.entries(hdrs)) out.headers.set(k, v);
1915
- out.headers.set("X-Cache", "HIT");
1916
- out.headers.set("X-Cache-Profile", sfnProfile);
1917
- return out;
1918
- }
1919
-
1920
- if (ageSec < sfnEdge.fresh + sfnEdge.swr) {
1921
- recordCacheMetric(true, sfnProfile, "STALE-HIT", "edge");
1922
- // Stale-while-revalidate: serve stale, refresh in background
1923
- ctx.waitUntil(
1924
- (async () => {
1925
- try {
1926
- const bgReq = new Request(request, { body, method: "POST" });
1927
- const bgOrigin = await serverEntry.fetch(bgReq, env, ctx);
1928
- if (
1929
- bgOrigin.status === 200 &&
1930
- bgOrigin.headers.get("X-Deco-Cacheable") === "true" &&
1931
- !bgOrigin.headers.has("set-cookie") &&
1932
- serverFnCache
1933
- ) {
1934
- const ttl = sfnEdge.fresh + Math.max(sfnEdge.swr, sfnEdge.sie);
1935
- const toStore = bgOrigin.clone();
1936
- toStore.headers.set("Cache-Control", `public, max-age=${ttl}`);
1937
- toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
1938
- toStore.headers.delete("CDN-Cache-Control");
1939
- toStore.headers.delete("X-Deco-Cacheable");
1940
- await serverFnCache.put(sfnCacheKey, toStore);
1941
- }
1942
- } catch {
1943
- /* background revalidation failed */
1944
- }
1945
- })(),
1946
- );
1947
- const out = new Response(sfnCached.body, sfnCached);
1948
- const hdrs = cacheHeaders(sfnProfile);
1949
- for (const [k, v] of Object.entries(hdrs)) out.headers.set(k, v);
1950
- out.headers.set("X-Cache", "STALE-HIT");
1951
- out.headers.set("X-Cache-Profile", sfnProfile);
1952
- out.headers.set("X-Cache-Age", String(Math.round(ageSec)));
1953
- return out;
1954
- }
1955
- }
1956
-
1957
- // Cache MISS — fetch origin with the body we already read
1958
- recordCacheMetric(false, sfnProfile, "MISS", "edge");
1959
- const origin = await serverEntry.fetch(originClone, env, ctx);
1960
-
1961
- // Only cache responses explicitly marked as cacheable by the handler
1962
- // (loadDeferredSection sets X-Deco-Cacheable: true). Checkout actions,
1963
- // invoke mutations, and other server functions are passed through.
1964
- const isCacheableResponse =
1965
- origin.headers.get("X-Deco-Cacheable") === "true" &&
1966
- !origin.headers.has("set-cookie") &&
1967
- origin.status === 200;
1968
-
1969
- if (!isCacheableResponse) {
1970
- const resp = new Response(origin.body, origin);
1971
- resp.headers.delete("X-Deco-Cacheable");
1972
- resp.headers.set("X-Cache", "BYPASS");
1973
- resp.headers.set(
1974
- "X-Cache-Reason",
1975
- origin.headers.has("set-cookie") ? "set-cookie" : "not-cacheable",
1976
- );
1977
- return resp;
1978
- }
1979
-
1980
- // Store in edge cache
1981
- if (serverFnCache) {
1982
- try {
1983
- const ttl = sfnEdge.fresh + Math.max(sfnEdge.swr, sfnEdge.sie);
1984
- const toStore = origin.clone();
1985
- toStore.headers.set("Cache-Control", `public, max-age=${ttl}`);
1986
- toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
1987
- toStore.headers.delete("CDN-Cache-Control");
1988
- toStore.headers.delete("X-Deco-Cacheable");
1989
- ctx.waitUntil(
1990
- withTracing("deco.cache.store", () => serverFnCache.put(sfnCacheKey, toStore), {
1991
- "cache.profile": sfnProfile,
1992
- "cache.kind": "serverFn",
1993
- }),
1994
- );
1995
- } catch {
1996
- /* Cache API unavailable */
1997
- }
1998
- }
1999
-
2000
- const resp = new Response(origin.body, origin);
2001
- resp.headers.delete("X-Deco-Cacheable");
2002
- const hdrs = cacheHeaders(sfnProfile);
2003
- for (const [k, v] of Object.entries(hdrs)) resp.headers.set(k, v);
2004
- resp.headers.set("X-Cache", "MISS");
2005
- resp.headers.set("X-Cache-Profile", sfnProfile);
2006
- return resp;
2007
- }
2008
-
2009
- // Non-cacheable requests — pass through but protect against accidental caching
2010
- if (!isCacheable(request, url)) {
2011
- const origin = await serverEntry.fetch(request, env, ctx);
2012
- const profile = getProfile(url);
2013
-
2014
- if (profile === "private" || profile === "none" || profile === "cart") {
2015
- const resp = new Response(origin.body, origin);
2016
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
2017
- resp.headers.delete("CDN-Cache-Control");
2018
- resp.headers.set("X-Cache", "BYPASS");
2019
- resp.headers.set("X-Cache-Reason", `non-cacheable:${profile}`);
2020
- return resp;
2021
- }
2022
-
2023
- const resp = new Response(origin.body, origin);
2024
-
2025
- // Responses with private Set-Cookie headers carry per-user tokens —
2026
- // never expose them with public cache headers.
2027
- // Safe/public cookies (e.g., vtex_is_session) are allowed through.
2028
- if (origin.headers.has("set-cookie") && !hasOnlySafeCookies(origin, safeCookieSet)) {
2029
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
2030
- resp.headers.delete("CDN-Cache-Control");
2031
- resp.headers.set("X-Cache", "BYPASS");
2032
- resp.headers.set("X-Cache-Reason", "private-set-cookie");
2033
- return resp;
2034
- }
2035
-
2036
- // Set cache headers from the detected profile so the response
2037
- // is explicit about cacheability (avoids ambiguous empty header).
2038
- const hdrsNc = cacheHeaders(profile);
2039
- for (const [k, v] of Object.entries(hdrsNc)) resp.headers.set(k, v);
2040
-
2041
- const reason = request.method !== "GET" ? `method:${request.method}` : "bypass-path";
2042
- resp.headers.set("X-Cache", "BYPASS");
2043
- resp.headers.set("X-Cache-Profile", profile);
2044
- resp.headers.set("X-Cache-Reason", reason);
2045
- return resp;
2046
- }
2047
-
2048
- // Cacheable request — build segment-aware cache key
2049
- const { key: cacheKey, segment } = buildCacheKey(request, env);
2050
-
2051
- // Logged-in users always bypass the cache (personalized content)
2052
- if (segment?.loggedIn) {
2053
- const origin = await serverEntry.fetch(request, env, ctx);
2054
- const resp = new Response(origin.body, origin);
2055
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
2056
- resp.headers.set("X-Cache", "BYPASS");
2057
- resp.headers.set("X-Cache-Reason", "logged-in");
2058
- return resp;
2059
- }
2060
-
2061
- // Check Cache API — disabled in local dev to avoid stale responses
2062
- const cache = isDevMode()
2063
- ? null
2064
- : typeof caches !== "undefined"
2065
- ? ((caches as unknown as { default?: Cache }).default ?? null)
2066
- : null;
2067
-
2068
- const profile = getProfile(url);
2069
- const edgeConfig = edgeCacheConfig(profile);
2070
-
2071
- // Helper: dress a response with proper client-facing headers
2072
- function dressResponse(
2073
- resp: Response,
2074
- xCache: string,
2075
- extra?: Record<string, string>,
2076
- ): Response {
2077
- const out = new Response(resp.body, resp);
2078
- const hdrs = cacheHeaders(profile);
2079
- for (const [k, v] of Object.entries(hdrs)) out.headers.set(k, v);
2080
-
2081
- // CDN-Cache-Control: controls Cloudflare's automatic CDN layer
2082
- // (separate from Cache API which the worker manages directly).
2083
- if (cdnCacheControlOpt === "no-store") {
2084
- out.headers.set("CDN-Cache-Control", "no-store");
2085
- } else if (cdnCacheControlOpt === "match-profile") {
2086
- if (edgeConfig.isPublic && edgeConfig.fresh > 0) {
2087
- out.headers.set("CDN-Cache-Control", `public, max-age=${edgeConfig.fresh}`);
2088
- } else {
2089
- out.headers.set("CDN-Cache-Control", "no-store");
2090
- }
2091
- } else if (typeof cdnCacheControlOpt === "function") {
2092
- const val = cdnCacheControlOpt(profile);
2093
- out.headers.set("CDN-Cache-Control", val ?? "no-store");
2094
- }
2095
-
2096
- out.headers.set("X-Cache", xCache);
2097
- out.headers.set("X-Cache-Profile", profile);
2098
- if (segment) out.headers.set("X-Cache-Segment", hashSegment(segment));
2099
- const headerVersion = getBuildHash(env);
2100
- if (headerVersion) out.headers.set("X-Cache-Version", headerVersion);
2101
- if (extra) for (const [k, v] of Object.entries(extra)) out.headers.set(k, v);
2102
- appendResourceHints(out);
2103
- return out;
2104
- }
2105
-
2106
- // Helper: store a response in Cache API with the full retention window
2107
- function storeInCache(resp: Response) {
2108
- if (!cache) return;
2109
- try {
2110
- const storageTtl = edgeConfig.fresh + Math.max(edgeConfig.swr, edgeConfig.sie);
2111
- const toStore = resp.clone();
2112
- toStore.headers.set("Cache-Control", `public, max-age=${storageTtl}`);
2113
- toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
2114
- toStore.headers.delete("CDN-Cache-Control");
2115
- ctx.waitUntil(
2116
- withTracing("deco.cache.store", () => cache.put(cacheKey, toStore), {
2117
- "cache.profile": profile,
2118
- "cache.kind": "html",
2119
- }),
2120
- );
2121
- } catch {
2122
- // Cache API unavailable
2123
- }
2124
- }
2125
-
2126
- // Helper: background revalidation (fetch origin, store result)
2127
- function revalidateInBackground() {
2128
- ctx.waitUntil(
2129
- Promise.resolve(serverEntry.fetch(request, env, ctx))
2130
- .then((origin) => {
2131
- // Never overwrite a good entry with a degraded 200 (a critical
2132
- // section failed) — that would poison the cache. Leave the stale
2133
- // entry in place until a healthy revalidation succeeds.
2134
- if (origin.status === 200 && origin.headers.get("X-Deco-Degraded") !== "true") {
2135
- // Only cache if response has no cookies or only safe cookies.
2136
- // Strip safe cookies from the cached copy.
2137
- if (hasOnlySafeCookies(origin, safeCookieSet)) {
2138
- const cleanOrigin = origin.headers.has("set-cookie")
2139
- ? stripSafeCookiesForCache(origin, safeCookieSet)
2140
- : origin;
2141
- storeInCache(cleanOrigin);
2142
- }
2143
- }
2144
- })
2145
- .catch(() => {
2146
- // Background revalidation failed — stale entry stays until SIE expires
2147
- }),
2148
- );
2149
- }
2150
-
2151
- // --- Edge cache check with SWR + SIE ---
2152
- let cached: Response | undefined;
2153
- if (cache) {
2154
- try {
2155
- cached = await withTracing(
2156
- "deco.cache.lookup",
2157
- async () => (await cache.match(cacheKey)) ?? undefined,
2158
- { "cache.profile": profile, "cache.kind": "html" },
2159
- );
2160
- } catch {
2161
- // Cache API unavailable
2162
- }
2163
- }
2164
-
2165
- if (cached && edgeConfig.isPublic && edgeConfig.fresh > 0) {
2166
- const storedAtStr = cached.headers.get("X-Deco-Stored-At");
2167
- const storedAt = storedAtStr ? Number(storedAtStr) : 0;
2168
- const ageMs = storedAt > 0 ? Date.now() - storedAt : Infinity;
2169
- const ageSec = ageMs / 1000;
2170
-
2171
- if (ageSec < edgeConfig.fresh) {
2172
- // FRESH HIT — serve immediately
2173
- recordCacheMetric(true, profile, "HIT", "edge");
2174
- return dressResponse(cached, "HIT");
2175
- }
2176
-
2177
- if (ageSec < edgeConfig.fresh + edgeConfig.swr) {
2178
- // STALE-HIT within SWR window — serve stale, revalidate in background
2179
- recordCacheMetric(true, profile, "STALE-HIT", "edge");
2180
- revalidateInBackground();
2181
- return dressResponse(cached, "STALE-HIT", { "X-Cache-Age": String(Math.round(ageSec)) });
2182
- }
2183
-
2184
- // Past SWR window but still in cache (within SIE window) — keep reference
2185
- // for potential error fallback below
2186
- }
2187
-
2188
- // Cache MISS or past SWR window — fetch from origin
2189
- recordCacheMetric(false, profile, "MISS", "edge");
2190
- let origin: Response;
2191
- try {
2192
- origin = await serverEntry.fetch(request, env, ctx);
2193
- } catch (err) {
2194
- // Origin fetch threw — SIE fallback if we have a stale entry
2195
- if (cached && edgeConfig.sie > 0) {
2196
- const storedAtStr = cached.headers.get("X-Deco-Stored-At");
2197
- const storedAt = storedAtStr ? Number(storedAtStr) : 0;
2198
- const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
2199
- if (ageSec < edgeConfig.fresh + edgeConfig.sie) {
2200
- console.warn(
2201
- `[edge-cache] Origin threw, serving stale (age=${Math.round(ageSec)}s, sie=${edgeConfig.sie}s)`,
2202
- );
2203
- recordCacheMetric(true, profile, "STALE-ERROR", "edge");
2204
- return dressResponse(cached, "STALE-ERROR", {
2205
- "X-Cache-Age": String(Math.round(ageSec)),
2206
- });
2207
- }
2208
- }
2209
- throw err;
2210
- }
2211
-
2212
- if (origin.status !== 200) {
2213
- // Non-200 origin — SIE fallback on 5xx/429
2214
- if (origin.status >= 500 || origin.status === 429) {
2215
- if (cached && edgeConfig.sie > 0) {
2216
- const storedAtStr = cached.headers.get("X-Deco-Stored-At");
2217
- const storedAt = storedAtStr ? Number(storedAtStr) : 0;
2218
- const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
2219
- if (ageSec < edgeConfig.fresh + edgeConfig.sie) {
2220
- console.warn(
2221
- `[edge-cache] Origin ${origin.status}, serving stale (age=${Math.round(ageSec)}s)`,
2222
- );
2223
- recordCacheMetric(true, profile, "STALE-ERROR", "edge");
2224
- return dressResponse(cached, "STALE-ERROR", {
2225
- "X-Cache-Age": String(Math.round(ageSec)),
2226
- "X-Cache-Origin-Status": String(origin.status),
2227
- });
2228
- }
2229
- }
2230
- }
2231
- const resp = new Response(origin.body, origin);
2232
- resp.headers.set("X-Cache", "BYPASS");
2233
- resp.headers.set("X-Cache-Reason", `status:${origin.status}`);
2234
- appendResourceHints(resp);
2235
- return resp;
2236
- }
2237
-
2238
- // Responses with private Set-Cookie headers must never be cached —
2239
- // they carry per-user session/auth tokens that would leak to other users.
2240
- // Safe/public cookies (IS session, segment, etc.) are stripped from the
2241
- // cached copy but kept on the response served to the current user.
2242
- if (origin.headers.has("set-cookie") && !hasOnlySafeCookies(origin, safeCookieSet)) {
2243
- const resp = new Response(origin.body, origin);
2244
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
2245
- resp.headers.delete("CDN-Cache-Control");
2246
- resp.headers.set("X-Cache", "BYPASS");
2247
- resp.headers.set("X-Cache-Reason", "private-set-cookie");
2248
- appendResourceHints(resp);
2249
- return resp;
2250
- }
2251
-
2252
- // Degraded origin — a critical section loader failed, so this 200 carries
2253
- // raw/empty data (e.g. an empty product shelf during a VTEX outage). Treat
2254
- // it like a 5xx for caching: prefer a warm stale entry (STALE-ERROR) and
2255
- // NEVER store it. Without this, the broken page would be cached as healthy
2256
- // for the full retention window and stale-if-error would never fire —
2257
- // turning a seconds-long blip into hours of empty pages.
2258
- if (origin.headers.get("X-Deco-Degraded") === "true") {
2259
- if (cached && edgeConfig.sie > 0) {
2260
- const storedAtStr = cached.headers.get("X-Deco-Stored-At");
2261
- const storedAt = storedAtStr ? Number(storedAtStr) : 0;
2262
- const ageSec = storedAt > 0 ? (Date.now() - storedAt) / 1000 : Infinity;
2263
- if (ageSec < edgeConfig.fresh + edgeConfig.sie) {
2264
- console.warn(
2265
- `[edge-cache] Origin degraded, serving stale (age=${Math.round(ageSec)}s, sie=${edgeConfig.sie}s)`,
2266
- );
2267
- recordCacheMetric(true, profile, "STALE-ERROR", "edge");
2268
- return dressResponse(cached, "STALE-ERROR", {
2269
- "X-Cache-Age": String(Math.round(ageSec)),
2270
- "X-Cache-Reason": "degraded",
2271
- });
2272
- }
2273
- }
2274
- // Cold cache — serve the degraded page but never persist it.
2275
- const resp = new Response(origin.body, origin);
2276
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
2277
- resp.headers.delete("CDN-Cache-Control");
2278
- resp.headers.set("X-Cache", "BYPASS");
2279
- resp.headers.set("X-Cache-Reason", "degraded");
2280
- appendResourceHints(resp);
2281
- return resp;
2282
- }
2283
-
2284
- const profileConfig = getCacheProfile(profile);
2285
-
2286
- if (!profileConfig.isPublic || profileConfig.edge.fresh === 0) {
2287
- const resp = new Response(origin.body, origin);
2288
- resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
2289
- resp.headers.set("X-Cache", "BYPASS");
2290
- resp.headers.set("X-Cache-Reason", `profile:${profile}`);
2291
- appendResourceHints(resp);
2292
- return resp;
2293
- }
2294
-
2295
- // Clone for cache BEFORE dressResponse consumes the body stream.
2296
- // dressResponse() calls new Response(resp.body, resp) which locks
2297
- // the ReadableStream. Calling clone() on a locked body corrupts
2298
- // the stream in Workers runtime, causing Error 1101.
2299
- // Strip safe cookies from the cached copy so they don't leak
2300
- // to other users, but the current user still gets them.
2301
- const cacheOrigin = origin.headers.has("set-cookie")
2302
- ? stripSafeCookiesForCache(origin, safeCookieSet)
2303
- : origin;
2304
- storeInCache(cacheOrigin);
2305
- return dressResponse(origin, "MISS");
2306
- }
2307
- }