@decocms/tanstack 7.63.0 → 7.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.63.0",
3
+ "version": "7.64.0",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -27,9 +27,9 @@
27
27
  "lint:unused": "knip"
28
28
  },
29
29
  "dependencies": {
30
- "@decocms/blocks": "7.63.0",
31
- "@decocms/blocks-admin": "7.63.0",
32
- "@decocms/blocks-cli": "7.63.0",
30
+ "@decocms/blocks": "7.64.0",
31
+ "@decocms/blocks-admin": "7.64.0",
32
+ "@decocms/blocks-cli": "7.64.0",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
35
  "ws": "^8.18.0"
@@ -27,6 +27,7 @@
27
27
 
28
28
  import type { MatcherContext, ResolvedSection } from "@decocms/blocks/cms";
29
29
  import { loadBlocks, onChange, resolvePageSections } from "@decocms/blocks/cms";
30
+ import { createCacheStore, getCacheStorageContext } from "@decocms/blocks/sdk/cacheStorage";
30
31
 
31
32
  // ---------------------------------------------------------------------------
32
33
  // Types
@@ -79,7 +80,7 @@ const cacheTtlMs = DEFAULT_CACHE_TTL_MS;
79
80
  // every other route (e.g. a /section-only alert winning on "/"). Caching a
80
81
  // resolvedSections array per path preserves the original 5-minute SWR behavior
81
82
  // while keeping each route's matcher evaluation correct.
82
- const cache = new Map<string, CacheEntry>();
83
+ const cache = createCacheStore<CacheEntry>("site-globals");
83
84
  const inflight = new Map<string, Promise<CacheEntry>>();
84
85
 
85
86
  onChange(() => {
@@ -105,7 +106,7 @@ function gatherSectionRefs(site: SiteBlock): SiteGlobalRef[] {
105
106
  const EMPTY_ENTRY: CacheEntry = {
106
107
  resolvedSections: [],
107
108
  rawRefs: [],
108
- expiresAt: Number.POSITIVE_INFINITY, // empty entries don't need refresh
109
+ expiresAt: 0,
109
110
  };
110
111
 
111
112
  /**
@@ -125,9 +126,11 @@ export async function resolveSiteGlobals(matcherCtx?: MatcherContext): Promise<{
125
126
  // Path/date/segment matchers inside site-global sections (e.g. a multivariate
126
127
  // `Alert` gated by a pathname matcher) must evaluate against the actual
127
128
  // request, and the result is cached per path so routes don't share variants.
128
- const cacheKey = matcherCtx?.path ?? "";
129
+ const cacheKey = cache.key(matcherCtx?.path ?? "");
129
130
  const now = Date.now();
130
- const cached = cache.get(cacheKey);
131
+ const cached = getCacheStorageContext()?.storage
132
+ ? await cache.read(cacheKey)
133
+ : cache.get(cacheKey);
131
134
  if (cached && cached.expiresAt > now) return cached;
132
135
  const inflightEntry = inflight.get(cacheKey);
133
136
  if (inflightEntry) return inflightEntry;
@@ -137,14 +140,16 @@ export async function resolveSiteGlobals(matcherCtx?: MatcherContext): Promise<{
137
140
  // Cache the empty result so subsequent requests don't re-walk the
138
141
  // block registry. `onChange` invalidation still applies — if a Site
139
142
  // block appears later, the listener clears `cache` and we re-check.
140
- cache.set(cacheKey, EMPTY_ENTRY);
141
- return EMPTY_ENTRY;
143
+ const empty = { ...EMPTY_ENTRY, expiresAt: Date.now() + cacheTtlMs };
144
+ cache.set(cacheKey, empty, empty.expiresAt);
145
+ return empty;
142
146
  }
143
147
 
144
148
  const rawRefs = gatherSectionRefs(site);
145
149
  if (rawRefs.length === 0) {
146
- cache.set(cacheKey, EMPTY_ENTRY);
147
- return EMPTY_ENTRY;
150
+ const empty = { ...EMPTY_ENTRY, expiresAt: Date.now() + cacheTtlMs };
151
+ cache.set(cacheKey, empty, empty.expiresAt);
152
+ return empty;
148
153
  }
149
154
 
150
155
  const p = (async () => {
@@ -155,7 +160,7 @@ export async function resolveSiteGlobals(matcherCtx?: MatcherContext): Promise<{
155
160
  rawRefs,
156
161
  expiresAt: Date.now() + cacheTtlMs,
157
162
  };
158
- cache.set(cacheKey, entry);
163
+ cache.set(cacheKey, entry, entry.expiresAt);
159
164
  return entry;
160
165
  } catch (err) {
161
166
  console.error("[site-globals] failed to resolve:", err);
@@ -183,7 +188,10 @@ export async function resolveSiteGlobals(matcherCtx?: MatcherContext): Promise<{
183
188
  * both in `site.global` and in a page's section list, which would otherwise
184
189
  * render twice.
185
190
  */
186
- export function dedupeGlobals(globals: ResolvedSection[], existing: ResolvedSection[]): ResolvedSection[] {
191
+ export function dedupeGlobals(
192
+ globals: ResolvedSection[],
193
+ existing: ResolvedSection[],
194
+ ): ResolvedSection[] {
187
195
  if (globals.length === 0) return [];
188
196
  const seenComponents = new Set<string>();
189
197
  for (const s of existing) {
@@ -0,0 +1,147 @@
1
+ // @vitest-environment node
2
+
3
+ import { setBlocks } from "@decocms/blocks/cms";
4
+ import { clearLoaderCache, createCachedLoader } from "@decocms/blocks/sdk/cachedLoader";
5
+ import {
6
+ type CacheKVNamespace,
7
+ createKVCacheStorage,
8
+ getCacheStorageContext,
9
+ } from "@decocms/blocks/sdk/cacheStorage";
10
+ import { beforeEach, describe, expect, it, vi } from "vitest";
11
+ import { createDecoWorkerEntry } from "./workerEntry";
12
+
13
+ function makeKV(): CacheKVNamespace {
14
+ const values = new Map<string, string>();
15
+ return {
16
+ get: async (key) => values.get(key) ?? null,
17
+ put: async (key, value) => {
18
+ values.set(key, value);
19
+ },
20
+ delete: async (key) => {
21
+ values.delete(key);
22
+ },
23
+ };
24
+ }
25
+ const jobs: Promise<unknown>[] = [];
26
+ const ctx = { waitUntil: (work: Promise<unknown>) => jobs.push(work), passThroughOnException() {} };
27
+ async function flush() {
28
+ while (jobs.length) await Promise.all(jobs.splice(0));
29
+ }
30
+ const request = (path = "/", headers: Record<string, string> = {}) =>
31
+ new Request(`https://shop.test${path}`, {
32
+ headers: { accept: "text/html", ...headers },
33
+ });
34
+ const env = () => ({ CACHE: makeKV(), BUILD_HASH: "build-A", PURGE_TOKEN: "test-token" });
35
+ const options = {
36
+ observability: false as const,
37
+ outboundUserAgent: false as const,
38
+ geoCacheKey: "off" as const,
39
+ buildSegment: (req: Request) => ({
40
+ device: "desktop" as const,
41
+ loggedIn: req.headers.has("authorization"),
42
+ }),
43
+ cacheStorage: (bindings: Record<string, unknown>) =>
44
+ createKVCacheStorage(bindings.CACHE as CacheKVNamespace),
45
+ };
46
+ beforeEach(() => {
47
+ clearLoaderCache();
48
+ setBlocks({});
49
+ });
50
+
51
+ describe("worker cache storage injection", () => {
52
+ it("uses the injected KV for HTML, with no global Cache API, across worker instances", async () => {
53
+ const origin = {
54
+ fetch: vi.fn(async () => new Response("page", { headers: { "content-type": "text/html" } })),
55
+ };
56
+ const bindings = env();
57
+ const first = createDecoWorkerEntry(origin, options);
58
+ expect((await first.fetch(request(), bindings, ctx)).headers.get("x-cache")).toBe("MISS");
59
+ await flush();
60
+ const second = createDecoWorkerEntry(origin, options);
61
+ const hit = await second.fetch(request(), bindings, ctx);
62
+ expect(hit.headers.get("x-cache")).toBe("HIT");
63
+ expect(await hit.text()).toBe("page");
64
+ expect(origin.fetch).toHaveBeenCalledTimes(1);
65
+ const changed = await second.fetch(request(), { ...bindings, BUILD_HASH: "build-B" }, ctx);
66
+ expect(changed.headers.get("x-cache")).toBe("MISS");
67
+ await flush();
68
+ });
69
+
70
+ it("uses the same adapter for loader results and isolates authenticated requests", async () => {
71
+ const upstream = vi.fn(async () => ({ n: upstream.mock.calls.length }));
72
+ const loader = createCachedLoader("worker-cache-test", upstream, {
73
+ policy: "no-cache",
74
+ maxAge: 60_000,
75
+ });
76
+ const origin = {
77
+ fetch: vi.fn(async () => {
78
+ expect(getCacheStorageContext()).toBeDefined();
79
+ return Response.json(await loader({}), { headers: { "cache-control": "no-store" } });
80
+ }),
81
+ };
82
+ const worker = createDecoWorkerEntry(origin, options);
83
+ const bindings = env();
84
+ await worker.fetch(request("/one"), bindings, ctx);
85
+ await flush();
86
+ clearLoaderCache();
87
+ await worker.fetch(request("/two"), bindings, ctx);
88
+ expect(upstream).toHaveBeenCalledTimes(1);
89
+ await worker.fetch(request("/two", { authorization: "Bearer private" }), bindings, ctx);
90
+ expect(upstream).toHaveBeenCalledTimes(2);
91
+ await flush();
92
+ });
93
+
94
+ it("stores public server-function POSTs by body and excludes unmarked responses", async () => {
95
+ const origin = {
96
+ fetch: vi.fn(
97
+ async (req: Request) =>
98
+ new Response(await req.text(), {
99
+ headers: { "X-Deco-Cacheable": "true", "content-type": "application/json" },
100
+ }),
101
+ ),
102
+ };
103
+ const worker = createDecoWorkerEntry(origin, options);
104
+ const bindings = env();
105
+ const post = (body: string) =>
106
+ new Request("https://shop.test/_serverFn/public", { method: "POST", body });
107
+ expect((await worker.fetch(post('"first"'), bindings, ctx)).headers.get("x-cache")).toBe(
108
+ "MISS",
109
+ );
110
+ await flush();
111
+ const hit = await worker.fetch(post('"first"'), bindings, ctx);
112
+ expect(hit.headers.get("x-cache")).toBe("HIT");
113
+ expect(await hit.text()).toBe('"first"');
114
+ expect((await worker.fetch(post('"second"'), bindings, ctx)).headers.get("x-cache")).toBe(
115
+ "MISS",
116
+ );
117
+ await flush();
118
+ expect(origin.fetch).toHaveBeenCalledTimes(2);
119
+ const unmarked = createDecoWorkerEntry({ fetch: async () => new Response("private") }, options);
120
+ expect((await unmarked.fetch(post('"third"'), bindings, ctx)).headers.get("x-cache")).toBe(
121
+ "BYPASS",
122
+ );
123
+ });
124
+
125
+ it("purges HTML through the configured adapter", async () => {
126
+ const worker = createDecoWorkerEntry(
127
+ { fetch: async () => new Response("page", { headers: { "content-type": "text/html" } }) },
128
+ options,
129
+ );
130
+ const bindings = env();
131
+ await worker.fetch(request(), bindings, ctx);
132
+ await flush();
133
+ expect((await worker.fetch(request(), bindings, ctx)).headers.get("x-cache")).toBe("HIT");
134
+ const purge = await worker.fetch(
135
+ new Request("https://shop.test/_cache/purge", {
136
+ method: "POST",
137
+ headers: { authorization: "Bearer test-token" },
138
+ body: JSON.stringify({ paths: ["/"] }),
139
+ }),
140
+ bindings,
141
+ ctx,
142
+ );
143
+ expect(purge.status).toBe(200);
144
+ expect((await worker.fetch(request(), bindings, ctx)).headers.get("x-cache")).toBe("MISS");
145
+ await flush();
146
+ });
147
+ });
@@ -25,6 +25,14 @@
25
25
  * ```
26
26
  */
27
27
 
28
+ import {
29
+ bindCacheStorage,
30
+ type CacheStorage,
31
+ createWebCacheStorage,
32
+ getCacheStorageContext,
33
+ } from "@decocms/blocks/sdk/cacheStorage";
34
+ import { createResponseCache } from "@decocms/blocks/sdk/responseCache";
35
+
28
36
  import {
29
37
  getRevision,
30
38
  getSectionOptions,
@@ -41,7 +49,6 @@ import {
41
49
  } from "@decocms/blocks/cms";
42
50
  import { DECO_MATCHERS_OVERRIDE_PARAM } from "@decocms/blocks/matchers/override";
43
51
  import { clearLoaderCache } from "@decocms/blocks/sdk/cachedLoader";
44
- import { djb2Hex } from "@decocms/blocks/sdk/djb2";
45
52
  import {
46
53
  type CacheProfileName,
47
54
  cacheHeaders,
@@ -51,9 +58,9 @@ import {
51
58
  getCacheProfile,
52
59
  serverFnPagePath,
53
60
  } from "@decocms/blocks/sdk/cacheHeaders";
61
+ import { djb2Hex } from "@decocms/blocks/sdk/djb2";
54
62
  import { isDevMode } from "@decocms/blocks/sdk/env";
55
63
  import { parseSegmentCookie, SEGMENT_COOKIE, segmentCacheToken } from "@decocms/blocks/sdk/flags";
56
- import { CSEG_BAG_KEY, CSEG_PARAM, segmentToken } from "./cdnSegment";
57
64
  import {
58
65
  getActiveSpan,
59
66
  logRequest,
@@ -74,11 +81,11 @@ import { loadRedirects, matchRedirect, type RedirectMap } from "@decocms/blocks/
74
81
  import { RequestContext } from "@decocms/blocks/sdk/requestContext";
75
82
  import { cleanPathForCacheKey } from "@decocms/blocks/sdk/urlUtils";
76
83
  import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
77
- import { reconfigureAppsOnce } from "@decocms/blocks-admin/apps/autoconfig";
78
84
  import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
85
+ import { reconfigureAppsOnce } from "@decocms/blocks-admin/apps/autoconfig";
79
86
  import { buildHtmlShell } from "@decocms/blocks-admin/sdk/htmlShell";
80
87
  import { getAppMiddleware } from "@decocms/blocks-admin/sdk/setupApps";
81
- import { setSpeculationRules, type SpeculationRulesConfig } from "./speculationRules";
88
+ import { CSEG_BAG_KEY, CSEG_PARAM, segmentToken } from "./cdnSegment";
82
89
  import {
83
90
  applyDraftCookieAndHeaders,
84
91
  bindRequestDraft,
@@ -90,6 +97,7 @@ import {
90
97
  } from "./draft";
91
98
  import { ensureBlocksHydrated, maybePollRevision } from "./kvHydration";
92
99
  import { DECO_POWERED_BY, installDefaultUserAgent } from "./outboundHeaders";
100
+ import { type SpeculationRulesConfig, setSpeculationRules } from "./speculationRules";
93
101
 
94
102
  /**
95
103
  * Build-time identifier injected by `decoVitePlugin()` (see
@@ -212,6 +220,11 @@ export interface AdminHandlers {
212
220
  }
213
221
 
214
222
  export interface DecoWorkerEntryOptions {
223
+ /** Choose storage once per request using the app's runtime bindings. Null disables shared storage.
224
+ * Omit to retain Web Cache API response caching and memory-only data caches.
225
+ */
226
+ cacheStorage?: (env: Record<string, unknown>, request: Request) => CacheStorage | null;
227
+
215
228
  /**
216
229
  * Admin route handlers (/live/_meta, /.decofile, /live/previews).
217
230
  * Pass the handlers from `@decocms/start/admin` here.
@@ -1162,13 +1175,7 @@ export function createDecoWorkerEntry(
1162
1175
  return detectCacheProfile(target);
1163
1176
  }
1164
1177
 
1165
- const KNOWN_SEGMENT_FIELDS = new Set([
1166
- "device",
1167
- "loggedIn",
1168
- "salesChannel",
1169
- "regionId",
1170
- "flags",
1171
- ]);
1178
+ const KNOWN_SEGMENT_FIELDS = new Set(["device", "loggedIn", "salesChannel", "regionId", "flags"]);
1172
1179
 
1173
1180
  function hashSegment(seg: SegmentKey): string {
1174
1181
  const parts: string[] = [seg.device];
@@ -1480,14 +1487,10 @@ export function createDecoWorkerEntry(
1480
1487
 
1481
1488
  const geoVariants = body.countries ?? [];
1482
1489
 
1483
- const cache = isDevMode()
1484
- ? null
1485
- : typeof caches !== "undefined"
1486
- ? ((caches as unknown as { default?: Cache }).default ?? null)
1487
- : null;
1490
+ const cache = responseCache(request, env);
1488
1491
 
1489
1492
  if (!cache) {
1490
- return Response.json({ purged: [], total: 0, note: "Cache API unavailable" });
1493
+ return Response.json({ purged: [], total: 0, note: "Cache storage unavailable" });
1491
1494
  }
1492
1495
 
1493
1496
  const baseUrl = new URL(request.url).origin;
@@ -1584,7 +1587,42 @@ export function createDecoWorkerEntry(
1584
1587
  const denied = authorizePurge(request, env);
1585
1588
  if (denied) return denied;
1586
1589
  clearLoaderCache();
1587
- return Response.json({ cleared: true, scope: "isolate" });
1590
+ return Response.json({
1591
+ cleared: true,
1592
+ scope: "isolate",
1593
+ ...(options.cacheStorage
1594
+ ? { sharedStorage: "Entries expire by TTL; this endpoint clears memory only." }
1595
+ : {}),
1596
+ });
1597
+ }
1598
+
1599
+ function responseCache(request: Request, env: Record<string, unknown>) {
1600
+ if (isDevMode()) return null;
1601
+ const context = getCacheStorageContext();
1602
+ if (context?.disabled && new URL(request.url).pathname !== "/_cache/purge") return null;
1603
+ let storage = context?.storage;
1604
+ // Purge is authenticated before this helper runs, and needs storage even though
1605
+ // ordinary Authorization-bearing requests bypass every shared cache.
1606
+ if (options.cacheStorage && new URL(request.url).pathname === "/_cache/purge") {
1607
+ try {
1608
+ storage = options.cacheStorage(env, request);
1609
+ } catch {
1610
+ return null;
1611
+ }
1612
+ }
1613
+ if (!options.cacheStorage) {
1614
+ const native =
1615
+ typeof caches !== "undefined"
1616
+ ? (caches as unknown as { default?: Cache }).default
1617
+ : undefined;
1618
+ storage = native ? createWebCacheStorage(native, new URL(request.url).origin) : null;
1619
+ }
1620
+ return storage
1621
+ ? createResponseCache(
1622
+ storage,
1623
+ JSON.stringify([new URL(request.url).origin, getBuildHash(env), getRevision()]),
1624
+ )
1625
+ : null;
1588
1626
  }
1589
1627
 
1590
1628
  // -- Admin route handler ---------------------------------------------------
@@ -1970,6 +2008,46 @@ export function createDecoWorkerEntry(
1970
2008
  await ensureBlocksHydrated(env, ctx);
1971
2009
  maybePollRevision(env, ctx);
1972
2010
 
2011
+ {
2012
+ const segment = buildSegment?.(request);
2013
+ const privateRequest =
2014
+ requestCarriesDraft(request, url) ||
2015
+ segment?.loggedIn === true ||
2016
+ request.headers.has("authorization") ||
2017
+ url.searchParams.has("__deco_preview") ||
2018
+ url.searchParams.has(DECO_MATCHERS_OVERRIDE_PARAM) ||
2019
+ request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM) ||
2020
+ url.pathname.startsWith("/live/previews") ||
2021
+ url.pathname.startsWith("/deco/render");
2022
+ let storage: CacheStorage | null = null;
2023
+ try {
2024
+ storage =
2025
+ privateRequest || isDevMode() ? null : (options.cacheStorage?.(env, request) ?? null);
2026
+ } catch {
2027
+ /* Missing storage is a cache miss, never a storefront failure. */
2028
+ }
2029
+ bindCacheStorage({
2030
+ storage,
2031
+ disabled: privateRequest || isDevMode(),
2032
+ scope: JSON.stringify([
2033
+ new URL(request.url).origin,
2034
+ getBuildHash(env),
2035
+ getRevision(),
2036
+ segment
2037
+ ? hashSegment(segment)
2038
+ : isMobileUA(request.headers.get("user-agent") ?? "")
2039
+ ? "mobile"
2040
+ : "desktop",
2041
+ buildGeoCacheParam(
2042
+ (request as unknown as { cf?: Record<string, string> }).cf,
2043
+ effectiveGeoKey(),
2044
+ ),
2045
+ privateRequest ? crypto.randomUUID() : null,
2046
+ ]),
2047
+ waitUntil: (work) => ctx.waitUntil(work),
2048
+ });
2049
+ }
2050
+
1973
2051
  // Admin routes (/_meta, /.decofile, /live/previews) — always handled first
1974
2052
  const adminResponse = await tryAdminRoute(request);
1975
2053
  if (adminResponse) return adminResponse;
@@ -2143,11 +2221,7 @@ export function createDecoWorkerEntry(
2143
2221
  }
2144
2222
 
2145
2223
  // ?asJson — return resolved page data as JSON (legacy deco compat)
2146
- if (
2147
- options.asJson !== false &&
2148
- url.searchParams.has("asJson") &&
2149
- request.method === "GET"
2150
- ) {
2224
+ if (options.asJson !== false && url.searchParams.has("asJson") && request.method === "GET") {
2151
2225
  const basePath = url.pathname;
2152
2226
  const cookies: Record<string, string> = {};
2153
2227
  for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
@@ -2289,11 +2363,7 @@ export function createDecoWorkerEntry(
2289
2363
  request.method === "POST" &&
2290
2364
  (url.pathname.startsWith("/_serverFn/") || url.pathname.startsWith("/_server/"))
2291
2365
  ) {
2292
- const serverFnCache = isDevMode()
2293
- ? null
2294
- : typeof caches !== "undefined"
2295
- ? ((caches as unknown as { default?: Cache }).default ?? null)
2296
- : null;
2366
+ const serverFnCache = responseCache(request, env);
2297
2367
 
2298
2368
  // Draft preview: a drafted SPA navigation fetches its section data via
2299
2369
  // this POST, carrying the draft cookie. The draft is already bound to the
@@ -2539,11 +2609,7 @@ export function createDecoWorkerEntry(
2539
2609
  }
2540
2610
 
2541
2611
  // Check Cache API — disabled in local dev to avoid stale responses
2542
- const cache = isDevMode()
2543
- ? null
2544
- : typeof caches !== "undefined"
2545
- ? ((caches as unknown as { default?: Cache }).default ?? null)
2546
- : null;
2612
+ const cache = responseCache(request, env);
2547
2613
 
2548
2614
  const profile = getProfile(url);
2549
2615
  const edgeConfig = edgeCacheConfig(profile);