@decocms/tanstack 7.64.2 → 7.65.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.
@@ -24,13 +24,7 @@
24
24
  * `DecofileProvider` pattern from the deco-cx/deco Fresh runtime.
25
25
  */
26
26
 
27
- import {
28
- DEPLOYMENT_ID_ENV,
29
- getDeploymentId,
30
- getRevision,
31
- loadBlocks,
32
- setBlocks,
33
- } from "@decocms/blocks/cms";
27
+ import { DEPLOYMENT_ID_ENV, getDeploymentId, getRevision, setBlocks } from "@decocms/blocks/cms";
34
28
  import { KVBlockSource } from "../cms/kvBlockSource";
35
29
  import type { KVNamespace } from "@decocms/blocks/cms";
36
30
  import { setSpanAttribute } from "@decocms/blocks/sdk/observability";
@@ -101,21 +95,32 @@ export function getFastDeployKV(env: Env): KVNamespace | null {
101
95
  return getKV(env);
102
96
  }
103
97
 
98
+ // Build-time constant injected by `decoVitePlugin({ fastDeploy: true })`: true
99
+ // when `blocks.gen` was stubbed out of THIS server bundle. Declared with a
100
+ // `typeof` guard so it's inert wherever the define isn't applied (this
101
+ // package's own tsc output, the Next.js build, tests).
102
+ declare const __DECO_BLOCKS_STUBBED__: boolean | undefined;
103
+
104
104
  /**
105
- * Is there a bundled snapshot to fall back on?
105
+ * Does this bundle ship no decofile of its own?
106
106
  *
107
- * `decoVitePlugin({ fastDeploy: true })` stubs `blocks.gen` out of the server
108
- * bundle to avoid holding the decofile twice (see the option's docs). That
109
- * makes KV the ONLY source of content, so the "warn and serve bundled"
110
- * recovery below would actually serve an EMPTY site — 200s with no pages,
111
- * which then get edge-cached and outlive the KV failure that caused them.
107
+ * When true, KV is the ONLY source of content, so the "warn and serve bundled"
108
+ * recovery below would serve an EMPTY site — 200s with no pages, which then get
109
+ * edge-cached and outlive the KV failure that caused them. Those cases fail
110
+ * loudly instead.
112
111
  *
113
- * Checking the in-memory map rather than a build-time flag keeps this honest
114
- * in both configurations, and means sites that still bundle their decofile
115
- * (the default) behave exactly as before.
112
+ * This is deliberately a BUILD-time answer rather than "is the in-memory map
113
+ * empty". The runtime check is not equivalent in three ways:
114
+ * - `loadBlocks()` composes request-scoped draft/preview overrides, and
115
+ * `bindRequestDraft` runs before hydration — a draft-preview first request
116
+ * would make a stubbed bundle look populated, latch, and then serve the
117
+ * empty base decofile for the isolate's life.
118
+ * - A legitimately-empty decofile (new site, missing `blocks.gen.json`) would
119
+ * look stubbed, turning a previously-warning default site into 5xx.
120
+ * - An empty snapshot in KV can't be distinguished from a healthy one.
116
121
  */
117
- function hasBundledFallback(): boolean {
118
- return Object.keys(loadBlocks()).length > 0;
122
+ function bundleHasNoDecofile(): boolean {
123
+ return typeof __DECO_BLOCKS_STUBBED__ !== "undefined" && __DECO_BLOCKS_STUBBED__ === true;
119
124
  }
120
125
 
121
126
  /**
@@ -144,10 +149,10 @@ export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Pro
144
149
  // content). Never read another deployment's key.
145
150
  const deploymentId = getDeploymentId(env);
146
151
  if (!deploymentId) {
147
- if (!hasBundledFallback()) {
152
+ if (bundleHasNoDecofile()) {
148
153
  return Promise.reject(
149
154
  new Error(
150
- `[CMS/KV] no deployment id (set ${DEPLOYMENT_ID_ENV}) and no bundled snapshot to fall back on`,
155
+ `[CMS/KV] no deployment id (set ${DEPLOYMENT_ID_ENV}) and this bundle ships no decofile`,
151
156
  ),
152
157
  );
153
158
  }
@@ -163,19 +168,24 @@ export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Pro
163
168
  let fatal: Error | null = null;
164
169
  try {
165
170
  const snapshot = await new KVBlockSource(kv, deploymentId).loadSnapshot();
166
- if (snapshot) {
167
- setBlocks(snapshot.blocks);
171
+ // An empty snapshot is treated as a failure, not a success: with no
172
+ // bundled decofile it would otherwise latch and serve exactly the empty,
173
+ // edge-cached site this guard exists to prevent. A site legitimately has
174
+ // blocks; `{}` means the seed wrote nothing.
175
+ const empty = !snapshot || Object.keys(snapshot.blocks).length === 0;
176
+ if (!empty) {
177
+ setBlocks(snapshot!.blocks);
168
178
  setSpanAttribute("deco.block.source", "kv");
169
- } else if (hasBundledFallback()) {
179
+ } else if (!bundleHasNoDecofile()) {
170
180
  setSpanAttribute("deco.block.source", "bundled");
171
181
  } else {
172
182
  fatal = new Error(
173
- `[CMS/KV] decofile:${deploymentId} not found and no bundled snapshot to fall back on — ` +
174
- `seed it before activating this version`,
183
+ `[CMS/KV] decofile:${deploymentId} ${snapshot ? "is empty" : "not found"} and this ` +
184
+ `bundle ships no decofile — seed it before activating this version`,
175
185
  );
176
186
  }
177
187
  } catch (e) {
178
- if (hasBundledFallback()) {
188
+ if (!bundleHasNoDecofile()) {
179
189
  // Non-fatal: serve the bundled snapshot. The poll loop recovers later.
180
190
  console.warn("[CMS/KV] cold-start hydration failed, using bundled snapshot:", e);
181
191
  setSpanAttribute("deco.block.source", "bundled");
package/src/sdk/router.ts CHANGED
@@ -6,61 +6,63 @@
6
6
  * filter URLs like `?filter.brand=Nike&filter.brand=Adidas` which must
7
7
  * round-trip correctly through the router's search system.
8
8
  */
9
- import { createRouter as createTanStackRouter } from "@tanstack/react-router";
9
+
10
+ import { getRequestNonce } from "@decocms/blocks/sdk/nonce";
10
11
  import type {
11
- SearchSerializer,
12
- SearchParser,
13
- AnyRoute,
14
- TrailingSlashOption,
12
+ AnyRoute,
13
+ SearchParser,
14
+ SearchSerializer,
15
+ TrailingSlashOption,
15
16
  } from "@tanstack/react-router";
17
+ import { createRouter as createTanStackRouter } from "@tanstack/react-router";
16
18
 
17
19
  export const decoParseSearch: SearchParser = (searchStr) => {
18
- const str = searchStr.startsWith("?") ? searchStr.slice(1) : searchStr;
19
- if (!str) return {};
20
+ const str = searchStr.startsWith("?") ? searchStr.slice(1) : searchStr;
21
+ if (!str) return {};
20
22
 
21
- const params = new URLSearchParams(str);
22
- const result: Record<string, string | string[]> = {};
23
+ const params = new URLSearchParams(str);
24
+ const result: Record<string, string | string[]> = {};
23
25
 
24
- for (const key of new Set(params.keys())) {
25
- const values = params.getAll(key);
26
- result[key] = values.length === 1 ? values[0] : values;
27
- }
28
- return result;
26
+ for (const key of new Set(params.keys())) {
27
+ const values = params.getAll(key);
28
+ result[key] = values.length === 1 ? values[0] : values;
29
+ }
30
+ return result;
29
31
  };
30
32
 
31
33
  export const decoStringifySearch: SearchSerializer = (search) => {
32
- const params = new URLSearchParams();
33
- for (const [key, value] of Object.entries(search)) {
34
- if (value === undefined || value === null || value === "") continue;
35
- if (Array.isArray(value)) {
36
- for (const v of value) params.append(key, String(v));
37
- } else {
38
- params.append(key, String(value));
39
- }
40
- }
41
- const str = params.toString();
42
- return str ? `?${str}` : "";
34
+ const params = new URLSearchParams();
35
+ for (const [key, value] of Object.entries(search)) {
36
+ if (value === undefined || value === null || value === "") continue;
37
+ if (Array.isArray(value)) {
38
+ for (const v of value) params.append(key, String(v));
39
+ } else {
40
+ params.append(key, String(value));
41
+ }
42
+ }
43
+ const str = params.toString();
44
+ return str ? `?${str}` : "";
43
45
  };
44
46
 
45
47
  export interface CreateDecoRouterOptions {
46
- routeTree: AnyRoute;
47
- scrollRestoration?: boolean;
48
- defaultPreload?: "intent" | "viewport" | "render" | false;
49
- trailingSlash?: TrailingSlashOption;
50
- /**
51
- * Router context — passed to all route loaders/components via routeContext.
52
- * Commonly used for { queryClient } per TanStack Query integration docs.
53
- */
54
- context?: Record<string, unknown>;
55
- /**
56
- * Non-DOM provider component to wrap the entire router.
57
- * Per TanStack docs, only non-DOM-rendering components (providers) should
58
- * be used — anything else causes hydration errors.
59
- *
60
- * Example: QueryClientProvider wrapping
61
- * Wrap: ({ children }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>
62
- */
63
- Wrap?: (props: { children: any }) => any;
48
+ routeTree: AnyRoute;
49
+ scrollRestoration?: boolean;
50
+ defaultPreload?: "intent" | "viewport" | "render" | false;
51
+ trailingSlash?: TrailingSlashOption;
52
+ /**
53
+ * Router context — passed to all route loaders/components via routeContext.
54
+ * Commonly used for { queryClient } per TanStack Query integration docs.
55
+ */
56
+ context?: Record<string, unknown>;
57
+ /**
58
+ * Non-DOM provider component to wrap the entire router.
59
+ * Per TanStack docs, only non-DOM-rendering components (providers) should
60
+ * be used — anything else causes hydration errors.
61
+ *
62
+ * Example: QueryClientProvider wrapping
63
+ * Wrap: ({ children }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>
64
+ */
65
+ Wrap?: (props: { children: any }) => any;
64
66
  }
65
67
 
66
68
  /**
@@ -70,23 +72,30 @@ export interface CreateDecoRouterOptions {
70
72
  * - Preload on intent
71
73
  */
72
74
  export function createDecoRouter(options: CreateDecoRouterOptions) {
73
- const {
74
- routeTree,
75
- scrollRestoration = true,
76
- defaultPreload = "intent",
77
- trailingSlash,
78
- context,
79
- Wrap,
80
- } = options;
75
+ const {
76
+ routeTree,
77
+ scrollRestoration = true,
78
+ defaultPreload = "intent",
79
+ trailingSlash,
80
+ context,
81
+ Wrap,
82
+ } = options;
83
+
84
+ // On the server, `getRouter()` runs per request inside `RequestContext.run`,
85
+ // so this reads the request's CSP nonce (enforce mode) — `ScriptOnce` and
86
+ // TanStack's own hydration scripts read `router.options.ssr.nonce` and stamp
87
+ // it. `undefined` in report-only mode and on the client, where it's a no-op.
88
+ const nonce = getRequestNonce();
81
89
 
82
- return createTanStackRouter({
83
- routeTree,
84
- scrollRestoration,
85
- defaultPreload,
86
- trailingSlash,
87
- context: context as any,
88
- Wrap,
89
- parseSearch: decoParseSearch,
90
- stringifySearch: decoStringifySearch,
91
- });
90
+ return createTanStackRouter({
91
+ routeTree,
92
+ scrollRestoration,
93
+ defaultPreload,
94
+ trailingSlash,
95
+ context: context as any,
96
+ Wrap,
97
+ parseSearch: decoParseSearch,
98
+ stringifySearch: decoStringifySearch,
99
+ ...(nonce ? { ssr: { nonce } } : {}),
100
+ });
92
101
  }