@decocms/tanstack 8.1.0-next.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 (177) 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 +85 -37
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -61
  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/__conformance__/observability.test.ts +0 -221
  109. package/src/cms/kvBlockSource.test.ts +0 -82
  110. package/src/cms/kvBlockSource.ts +0 -68
  111. package/src/daemon/auth.ts +0 -204
  112. package/src/daemon/fs.ts +0 -238
  113. package/src/daemon/index.ts +0 -8
  114. package/src/daemon/middleware.ts +0 -156
  115. package/src/daemon/tunnel.ts +0 -129
  116. package/src/daemon/volumes.ts +0 -366
  117. package/src/daemon/watch.ts +0 -272
  118. package/src/hooks/CdnSegmentMarker.tsx +0 -38
  119. package/src/hooks/DecoPageRenderer.tsx +0 -750
  120. package/src/hooks/DecoRootLayout.tsx +0 -192
  121. package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
  122. package/src/hooks/DraftPreviewIndicator.tsx +0 -64
  123. package/src/hooks/NavigationProgress.test.tsx +0 -58
  124. package/src/hooks/NavigationProgress.tsx +0 -63
  125. package/src/hooks/PreviewProviders.test.tsx +0 -42
  126. package/src/hooks/PreviewProviders.tsx +0 -45
  127. package/src/hooks/StableOutlet.tsx +0 -30
  128. package/src/hooks/deferredObserverTiming.test.tsx +0 -91
  129. package/src/hooks/index.ts +0 -10
  130. package/src/routes/adminRoutes.test.ts +0 -99
  131. package/src/routes/adminRoutes.ts +0 -153
  132. package/src/routes/cmsRoute.test.ts +0 -267
  133. package/src/routes/cmsRoute.ts +0 -1053
  134. package/src/routes/components.tsx +0 -57
  135. package/src/routes/index.ts +0 -24
  136. package/src/routes/pageUrl.test.ts +0 -70
  137. package/src/routes/pageUrl.ts +0 -55
  138. package/src/routes/withSiteGlobals.test.ts +0 -243
  139. package/src/routes/withSiteGlobals.ts +0 -243
  140. package/src/sdk/backgroundTasks.test.ts +0 -68
  141. package/src/sdk/backgroundTasks.ts +0 -38
  142. package/src/sdk/cdnSegment.test.ts +0 -67
  143. package/src/sdk/cdnSegment.ts +0 -71
  144. package/src/sdk/cookiePassthrough.ts +0 -58
  145. package/src/sdk/createInvoke.ts +0 -77
  146. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  147. package/src/sdk/deferredSectionLoader.ts +0 -46
  148. package/src/sdk/draft.test.ts +0 -341
  149. package/src/sdk/draft.ts +0 -277
  150. package/src/sdk/draftShared.ts +0 -16
  151. package/src/sdk/kvHydration.test.ts +0 -371
  152. package/src/sdk/kvHydration.ts +0 -263
  153. package/src/sdk/kvRedirects.test.ts +0 -132
  154. package/src/sdk/kvRedirects.ts +0 -125
  155. package/src/sdk/outboundHeaders.test.ts +0 -113
  156. package/src/sdk/outboundHeaders.ts +0 -81
  157. package/src/sdk/router.ts +0 -101
  158. package/src/sdk/serverFnFetch.ts +0 -59
  159. package/src/sdk/speculationRules.test.ts +0 -82
  160. package/src/sdk/speculationRules.ts +0 -136
  161. package/src/sdk/startEntry.ts +0 -31
  162. package/src/sdk/useHydrated.ts +0 -19
  163. package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
  164. package/src/sdk/workerEntry.test.ts +0 -1033
  165. package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
  166. package/src/sdk/workerEntry.ts +0 -3154
  167. package/src/setupFastDeploy.ts +0 -13
  168. package/src/v8/__conformance__/delivery.test.ts +0 -100
  169. package/src/v8/binding.ts +0 -70
  170. package/src/v8/kvLoader.bundle.test.ts +0 -42
  171. package/src/v8/kvLoader.test.ts +0 -74
  172. package/src/v8/kvLoader.ts +0 -43
  173. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  174. package/src/vite/plugin.js +0 -1022
  175. package/src/vite/plugin.test.js +0 -238
  176. package/src/vite/plugin.test.ts +0 -176
  177. package/tsconfig.json +0 -7
@@ -1,263 +0,0 @@
1
- /**
2
- * Fast-deploy KV hydration — the runtime read path.
3
- *
4
- * Bridges a Cloudflare KV namespace to the in-memory decofile so CMS content
5
- * edits propagate WITHOUT a `wrangler deploy`. Two entry points, both called
6
- * from `workerEntry.ts`:
7
- *
8
- * - `ensureBlocksHydrated(env, ctx)` — on the FIRST request per isolate, load
9
- * the whole snapshot from KV and swap it in via `setBlocks()`. Awaited, so it
10
- * adds one ~10-30ms cold-start hit per isolate but guarantees fresh content
11
- * (the bundled `blocks.gen` snapshot is frozen at the last code deploy).
12
- *
13
- * - `maybePollRevision(env, ctx)` — on EVERY request, opportunistically (gated
14
- * to once per `POLL_INTERVAL_MS`) probe `index:revision` via `ctx.waitUntil`
15
- * so it never blocks the response; reload + swap when it changed.
16
- *
17
- * Everything is a no-op unless fast-deploy is enabled (`isFastDeployEnabled`),
18
- * so non-migrated sites behave exactly as before.
19
- *
20
- * Why whole-snapshot swap (not per-block async): the resolver reads
21
- * `loadBlocks()` synchronously in dozens of places. Loading the entire decofile
22
- * once and swapping the map keeps that hot path synchronous — KV is touched
23
- * only on cold start and during the throttled poll. Mirrors the
24
- * `DecofileProvider` pattern from the deco-cx/deco Fresh runtime.
25
- */
26
-
27
- import { DEPLOYMENT_ID_ENV, getDeploymentId, getRevision, setBlocks } from "@decocms/blocks/cms";
28
- import { KVBlockSource } from "../cms/kvBlockSource";
29
- import type { KVNamespace } from "@decocms/blocks/cms";
30
- import { setSpanAttribute } from "@decocms/blocks/sdk/observability";
31
-
32
- /** How often (ms) an isolate re-probes its `index:revision:<id>`. */
33
- export const POLL_INTERVAL_MS = 10_000;
34
-
35
- /** KV binding name expected on the Worker `env`. */
36
- export const KV_BINDING = "DECO_KV";
37
-
38
- /** Opt-in env var — set to "1" (or "true") to enable fast-deploy. The DECO_KV
39
- * binding must also be present. */
40
- export const FAST_DEPLOY_ENV = "DECO_FAST_DEPLOY";
41
-
42
- // Deployment-id resolution lives in `@decocms/blocks/cms` (next to the key
43
- // builders it feeds) so the runtime read path and the admin write-through
44
- // resolve it identically. Re-exported for the existing call sites/tests.
45
- export { getDeploymentId };
46
-
47
- // globalThis-backed state so all Vite server-function split-module copies share
48
- // the same hydration flags (same pattern as `loader.ts`).
49
- const G = globalThis as unknown as {
50
- __deco?: {
51
- kvHydrated?: boolean;
52
- kvHydration?: Promise<void> | null;
53
- kvLastPolledAt?: number;
54
- };
55
- };
56
- if (!G.__deco) G.__deco = {};
57
-
58
- /** Minimal Cloudflare ExecutionContext shape (matches workerEntry.ts). */
59
- interface ExecutionContextLike {
60
- waitUntil(promise: Promise<unknown>): void;
61
- }
62
-
63
- type Env = Record<string, unknown>;
64
-
65
- function getKV(env: Env): KVNamespace | null {
66
- const binding = env[KV_BINDING];
67
- // Duck-type the binding: a real KVNamespace has get/put. Guards against a
68
- // string/secret accidentally named DECO_KV.
69
- if (binding && typeof (binding as KVNamespace).get === "function") {
70
- return binding as KVNamespace;
71
- }
72
- return null;
73
- }
74
-
75
- /**
76
- * Fast-deploy is active only when BOTH hold: `DECO_FAST_DEPLOY` is set to "1"
77
- * (or "true") — an explicit, per-site opt-in — AND the `DECO_KV` binding is
78
- * present. Either missing ⇒ bundled-snapshot behavior, identical to
79
- * pre-fast-deploy. Requiring the explicit flag means simply binding a KV
80
- * namespace can't silently flip a site onto the KV read/write path.
81
- */
82
- export function isFastDeployEnabled(env: Env): boolean {
83
- const flag = env[FAST_DEPLOY_ENV];
84
- if (flag !== "1" && flag !== "true") return false;
85
- return getKV(env) !== null;
86
- }
87
-
88
- /**
89
- * Resolve the KV namespace for the write-through path, or `null` when
90
- * fast-deploy is disabled. Shared by `decofile.ts` so the enablement rule
91
- * lives in exactly one place.
92
- */
93
- export function getFastDeployKV(env: Env): KVNamespace | null {
94
- if (!isFastDeployEnabled(env)) return null;
95
- return getKV(env);
96
- }
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
- /**
105
- * Does this bundle ship no decofile of its own?
106
- *
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.
111
- *
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.
121
- */
122
- function bundleHasNoDecofile(): boolean {
123
- return typeof __DECO_BLOCKS_STUBBED__ !== "undefined" && __DECO_BLOCKS_STUBBED__ === true;
124
- }
125
-
126
- /**
127
- * Cold-start hydration. Awaits the KV snapshot once per isolate and swaps it
128
- * into the in-memory block map. Concurrent first requests share a single
129
- * in-flight load.
130
- *
131
- * On failure (KV outage, bad JSON, snapshot not seeded) the behavior depends on
132
- * whether a bundled snapshot exists:
133
- *
134
- * - Bundled present (default): warn, serve bundled, mark hydration done —
135
- * `maybePollRevision` recovers once KV is reachable again.
136
- * - Bundled stubbed out (`fastDeploy`): throw. There is no content to serve, so
137
- * a 5xx is the only honest answer; hydration is left unlatched so the next
138
- * request retries instead of pinning the isolate to an empty decofile.
139
- */
140
- export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Promise<void> {
141
- if (!isFastDeployEnabled(env)) {
142
- // A stubbed bundle with fast-deploy off would serve an empty 200 the edge caches.
143
- return bundleHasNoDecofile()
144
- ? Promise.reject(
145
- new Error(
146
- `[CMS/KV] this bundle ships no decofile but fast-deploy is off (set ${FAST_DEPLOY_ENV}=1 and bind DECO_KV)`,
147
- ),
148
- )
149
- : Promise.resolve();
150
- }
151
- if (G.__deco!.kvHydrated) return Promise.resolve();
152
- if (G.__deco!.kvHydration) return G.__deco!.kvHydration;
153
-
154
- const kv = getKV(env);
155
- if (!kv) return Promise.resolve();
156
-
157
- // No resolvable deployment id ⇒ keep the bundled snapshot (this build's own
158
- // content). Never read another deployment's key.
159
- const deploymentId = getDeploymentId(env);
160
- if (!deploymentId) {
161
- if (bundleHasNoDecofile()) {
162
- return Promise.reject(
163
- new Error(
164
- `[CMS/KV] no deployment id (set ${DEPLOYMENT_ID_ENV}) and this bundle ships no decofile`,
165
- ),
166
- );
167
- }
168
- setSpanAttribute("deco.block.source", "bundled");
169
- G.__deco!.kvHydrated = true;
170
- return Promise.resolve();
171
- }
172
-
173
- const load = (async () => {
174
- // Held rather than rethrown inline so the `finally` below can decide
175
- // whether to latch — latching on a fatal path would serve an empty
176
- // decofile for the isolate's entire life.
177
- let fatal: Error | null = null;
178
- try {
179
- const snapshot = await new KVBlockSource(kv, deploymentId).loadSnapshot();
180
- // An empty snapshot is treated as a failure, not a success: with no
181
- // bundled decofile it would otherwise latch and serve exactly the empty,
182
- // edge-cached site this guard exists to prevent. A site legitimately has
183
- // blocks; `{}` means the seed wrote nothing.
184
- const empty = !snapshot || Object.keys(snapshot.blocks).length === 0;
185
- if (!empty) {
186
- setBlocks(snapshot!.blocks);
187
- setSpanAttribute("deco.block.source", "kv");
188
- } else if (!bundleHasNoDecofile()) {
189
- setSpanAttribute("deco.block.source", "bundled");
190
- } else {
191
- fatal = new Error(
192
- `[CMS/KV] decofile:${deploymentId} ${snapshot ? "is empty" : "not found"} and this ` +
193
- `bundle ships no decofile — seed it before activating this version`,
194
- );
195
- }
196
- } catch (e) {
197
- if (!bundleHasNoDecofile()) {
198
- // Non-fatal: serve the bundled snapshot. The poll loop recovers later.
199
- console.warn("[CMS/KV] cold-start hydration failed, using bundled snapshot:", e);
200
- setSpanAttribute("deco.block.source", "bundled");
201
- } else {
202
- fatal = e instanceof Error ? e : new Error(String(e));
203
- }
204
- } finally {
205
- G.__deco!.kvHydrated = !fatal;
206
- G.__deco!.kvHydration = null;
207
- }
208
- if (fatal) throw fatal;
209
- })();
210
-
211
- G.__deco!.kvHydration = load;
212
- return load;
213
- }
214
-
215
- /**
216
- * Opportunistic revision poll. Throttled to once per `POLL_INTERVAL_MS` and run
217
- * through `ctx.waitUntil` so it never adds latency to the response. Reloads the
218
- * snapshot and swaps it in when KV's revision differs from the in-memory one.
219
- */
220
- export function maybePollRevision(env: Env, ctx?: ExecutionContextLike): void {
221
- if (!isFastDeployEnabled(env)) return;
222
- if (!G.__deco!.kvHydrated) return; // wait until cold-start hydration finished
223
-
224
- const now = Date.now();
225
- if (now - (G.__deco!.kvLastPolledAt ?? 0) < POLL_INTERVAL_MS) return;
226
- G.__deco!.kvLastPolledAt = now;
227
-
228
- const kv = getKV(env);
229
- if (!kv) return;
230
-
231
- const deploymentId = getDeploymentId(env);
232
- if (!deploymentId) return; // bundled-only; nothing to poll
233
-
234
- const poll = pollRevisionOnce(kv, deploymentId);
235
- // Prefer waitUntil so the work outlives the response; fall back to a
236
- // fire-and-forget promise (dev / tests) with its rejection swallowed.
237
- if (ctx?.waitUntil) ctx.waitUntil(poll);
238
- else void poll.catch(() => {});
239
- }
240
-
241
- async function pollRevisionOnce(kv: KVNamespace, deploymentId: string): Promise<void> {
242
- try {
243
- const source = new KVBlockSource(kv, deploymentId);
244
- const remoteRevision = await source.getRevision();
245
- if (!remoteRevision || remoteRevision === getRevision()) return;
246
-
247
- const snapshot = await source.loadSnapshot();
248
- if (snapshot) {
249
- setBlocks(snapshot.blocks);
250
- console.info(`[CMS/KV] decofile refreshed → revision ${snapshot.revision}`);
251
- }
252
- } catch (e) {
253
- // Swallow — a failed poll must never affect the request. Next tick retries.
254
- console.warn("[CMS/KV] revision poll failed:", e);
255
- }
256
- }
257
-
258
- /** Test-only: reset the isolate-level hydration flags. */
259
- export function __resetKvHydrationStateForTests(): void {
260
- G.__deco!.kvHydrated = false;
261
- G.__deco!.kvHydration = null;
262
- G.__deco!.kvLastPolledAt = 0;
263
- }
@@ -1,132 +0,0 @@
1
- import {
2
- loadRedirects,
3
- matchExactRedirect,
4
- matchPatternRedirect,
5
- } from "@decocms/blocks/sdk/redirects";
6
- import { beforeEach, describe, expect, it, vi } from "vitest";
7
- import { clearRedirectCache, lookupExactRedirect } from "./kvRedirects";
8
-
9
- /** Minimal KV binding that records every read. */
10
- function makeKV(values: Record<string, string> = {}) {
11
- const get = vi.fn((key: string) => Promise.resolve(values[key] ?? null));
12
- return { get, put: vi.fn(), delete: vi.fn() };
13
- }
14
-
15
- const ID = "sha-abc";
16
- const enabled = (kv: unknown) => ({
17
- DECO_FAST_DEPLOY: "1",
18
- DECO_KV: kv,
19
- DECO_DEPLOYMENT_ID: ID,
20
- });
21
-
22
- beforeEach(() => {
23
- clearRedirectCache();
24
- vi.useRealTimers();
25
- });
26
-
27
- describe("lookupExactRedirect", () => {
28
- it("reads redirect:<id>:<path> and returns the rule", async () => {
29
- const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new","status":301}' });
30
- await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toEqual({
31
- from: "/old",
32
- to: "/new",
33
- status: 301,
34
- });
35
- });
36
-
37
- it("returns null for a missing key", async () => {
38
- await expect(lookupExactRedirect(enabled(makeKV()), "/nope")).resolves.toBeNull();
39
- });
40
-
41
- it("caches a HIT so the same path costs one KV read", async () => {
42
- const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new","status":302}' });
43
- await lookupExactRedirect(enabled(kv), "/old");
44
- await lookupExactRedirect(enabled(kv), "/old");
45
- expect(kv.get).toHaveBeenCalledTimes(1);
46
- });
47
-
48
- it("caches a MISS too — that is the common case on every request", async () => {
49
- const kv = makeKV();
50
- await lookupExactRedirect(enabled(kv), "/nope");
51
- await lookupExactRedirect(enabled(kv), "/nope");
52
- expect(kv.get).toHaveBeenCalledTimes(1);
53
- });
54
-
55
- it("re-reads after the TTL, which is how a redirect edit propagates", async () => {
56
- // The rules live outside the decofile, so a redirect-only sync leaves the
57
- // revision identical and the poller has nothing to react to. The TTL is
58
- // the only propagation path.
59
- const kv = makeKV();
60
- await lookupExactRedirect(enabled(kv), "/soon");
61
- vi.useFakeTimers();
62
- vi.setSystemTime(Date.now() + 61_000);
63
- await lookupExactRedirect(enabled(kv), "/soon");
64
- expect(kv.get).toHaveBeenCalledTimes(2);
65
- });
66
-
67
- it("is inert when fast-deploy is off", async () => {
68
- const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new","status":301}' });
69
- const env = { DECO_KV: kv, DECO_DEPLOYMENT_ID: ID }; // no DECO_FAST_DEPLOY
70
- await expect(lookupExactRedirect(env, "/old")).resolves.toBeNull();
71
- expect(kv.get).not.toHaveBeenCalled();
72
- });
73
-
74
- it("never reads another deployment's keys when the id is unresolvable", async () => {
75
- const kv = makeKV();
76
- await lookupExactRedirect({ DECO_FAST_DEPLOY: "1", DECO_KV: kv }, "/old");
77
- expect(kv.get).not.toHaveBeenCalled();
78
- });
79
-
80
- it("treats a KV failure as no-redirect, never a throw", async () => {
81
- // A KV outage must not 5xx a page that would otherwise render fine.
82
- const kv = { get: vi.fn(() => Promise.reject(new Error("KV down"))) };
83
- await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toBeNull();
84
- });
85
-
86
- it("treats a malformed value as no-redirect", async () => {
87
- const kv = makeKV({ [`redirect:${ID}:/old`]: "not json" });
88
- await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toBeNull();
89
- });
90
-
91
- it("defaults an unknown status to 302 rather than inventing a permanent redirect", async () => {
92
- const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new"}' });
93
- await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toMatchObject({ status: 302 });
94
- });
95
- });
96
-
97
- describe("precedence: exact (KV) over glob (memory)", () => {
98
- it("an exact rule in KV wins over a glob still in the decofile", async () => {
99
- // This is why matchRedirect was split in two. Doing "matchRedirect, then
100
- // KV" would return /store/sale here, inverting the precedence every
101
- // non-fast-deploy path has.
102
- const map = loadRedirects({
103
- r: {
104
- __resolveType: "website/loaders/redirects.ts",
105
- redirects: [{ from: "/shop/*", to: "/store/*" }],
106
- },
107
- });
108
- const kv = makeKV({ [`redirect:${ID}:/shop/sale`]: '{"to":"/promo","status":301}' });
109
-
110
- const hit =
111
- matchExactRedirect("/shop/sale", map) ??
112
- (await lookupExactRedirect(enabled(kv), "/shop/sale")) ??
113
- matchPatternRedirect("/shop/sale", map);
114
-
115
- expect(hit).toMatchObject({ to: "/promo", status: 301 });
116
- });
117
-
118
- it("falls through to the glob when KV has no exact rule", async () => {
119
- const map = loadRedirects({
120
- r: {
121
- __resolveType: "website/loaders/redirects.ts",
122
- redirects: [{ from: "/shop/*", to: "/store/*" }],
123
- },
124
- });
125
- const hit =
126
- matchExactRedirect("/shop/other", map) ??
127
- (await lookupExactRedirect(enabled(makeKV()), "/shop/other")) ??
128
- matchPatternRedirect("/shop/other", map);
129
-
130
- expect(hit).toMatchObject({ to: "/store/other" });
131
- });
132
- });
@@ -1,125 +0,0 @@
1
- /**
2
- * Request-time lookup for KV-keyed exact redirects.
3
- *
4
- * A bulk-migration site can carry tens of thousands of rules. Inside the
5
- * decofile they are resident in every isolate twice — the parsed snapshot graph
6
- * and the `RedirectMap` built from it — for data consulted at most once per
7
- * request and usually matching nothing. `splitExactRedirects` moves them to one
8
- * `redirect:<deployment-id>:<path>` key each at sync time, so the list is never
9
- * loaded and this looks up only the path actually being requested.
10
- *
11
- * Globs stay in the decofile and in memory: they must be scanned in order
12
- * against the path, so they can never be a key lookup. There are tens of them.
13
- *
14
- * Inert unless fast-deploy is on — without a `DECO_KV` binding there is nowhere
15
- * to look, and the rules are still in the decofile where `matchRedirect` finds
16
- * them. Same on-or-off switch as the rest of fast-deploy, so a site can't end
17
- * up with redirects in neither place.
18
- */
19
-
20
- import { getDeploymentId, redirectKey, type StoredRedirect } from "@decocms/blocks/cms";
21
- import type { Redirect } from "@decocms/blocks/sdk/redirects";
22
- import { getFastDeployKV } from "./kvHydration";
23
-
24
- /**
25
- * How long a lookup (hit OR miss) is trusted inside one isolate.
26
- *
27
- * Deliberately a TTL rather than the decofile revision: the rules now live in
28
- * their own keys, so a redirect-only content sync leaves the decofile byte
29
- * identical and the revision poller sees nothing to react to. The TTL is the
30
- * propagation delay for a redirect edit.
31
- *
32
- * Ceiling: if that delay ever needs to be near-zero, the upgrade is a
33
- * `index:redirects-revision:<id>` key polled next to `index:revision:<id>` —
34
- * not a shorter TTL, which just multiplies KV reads.
35
- */
36
- const TTL_MS = 60_000;
37
-
38
- /** Bounded so a crawler walking unique URLs cannot grow the isolate unbounded —
39
- * the whole point of this module is to stop holding an unbounded list. */
40
- const MAX_ENTRIES = 2_000;
41
-
42
- interface CacheEntry {
43
- value: StoredRedirect | null;
44
- expiresAt: number;
45
- }
46
-
47
- // globalThis-backed so every Vite server-function split-module copy shares one
48
- // cache (same reason as `loader.ts` and `kvHydration.ts`).
49
- const G = globalThis as unknown as { __decoRedirectCache?: Map<string, CacheEntry> };
50
- function cache(): Map<string, CacheEntry> {
51
- G.__decoRedirectCache ??= new Map();
52
- return G.__decoRedirectCache;
53
- }
54
-
55
- /** Insertion-ordered LRU touch + evict. */
56
- function remember(key: string, value: StoredRedirect | null): void {
57
- const c = cache();
58
- c.delete(key);
59
- c.set(key, { value, expiresAt: Date.now() + TTL_MS });
60
- while (c.size > MAX_ENTRIES) c.delete(c.keys().next().value!);
61
- }
62
-
63
- /** Cached entry, or `undefined` when absent/expired. */
64
- function peek(key: string): CacheEntry | undefined {
65
- const c = cache();
66
- const entry = c.get(key);
67
- if (!entry) return undefined;
68
- if (Date.now() >= entry.expiresAt) {
69
- c.delete(key);
70
- return undefined;
71
- }
72
- c.delete(key);
73
- c.set(key, entry);
74
- return entry;
75
- }
76
-
77
- /** Test seam — the cache is process-global, so suites must be able to reset it. */
78
- export function clearRedirectCache(): void {
79
- G.__decoRedirectCache = new Map();
80
- }
81
-
82
- /**
83
- * Look up one exact redirect for `normalizedPath` (already through
84
- * `normalizePath` — the key contract).
85
- *
86
- * Returns `null` for "no redirect", including every case where the lookup
87
- * cannot run (fast-deploy off, no deployment id, KV error). A KV failure must
88
- * not 5xx a page that would otherwise render: the worst outcome is the request
89
- * proceeds and the URL serves its normal response.
90
- */
91
- export async function lookupExactRedirect(
92
- env: Record<string, unknown>,
93
- normalizedPath: string,
94
- ): Promise<Redirect | null> {
95
- const kv = getFastDeployKV(env);
96
- if (!kv) return null;
97
-
98
- const deploymentId = getDeploymentId(env);
99
- if (!deploymentId) return null;
100
-
101
- const key = redirectKey(deploymentId, normalizedPath);
102
- const cached = peek(key);
103
- const stored = cached !== undefined ? cached.value : await read(kv, key);
104
- if (cached === undefined) remember(key, stored);
105
- if (!stored) return null;
106
-
107
- return { from: normalizedPath, to: stored.to, status: stored.status };
108
- }
109
-
110
- async function read(
111
- kv: { get(key: string): Promise<string | null> },
112
- key: string,
113
- ): Promise<StoredRedirect | null> {
114
- try {
115
- const raw = await kv.get(key);
116
- if (raw === null) return null;
117
- const parsed = JSON.parse(raw) as StoredRedirect;
118
- // A malformed value is a miss, not a throw — never let bad data in one key
119
- // take down every request for that path.
120
- if (!parsed || typeof parsed.to !== "string") return null;
121
- return { to: parsed.to, status: parsed.status === 301 ? 301 : 302 };
122
- } catch {
123
- return null;
124
- }
125
- }
@@ -1,113 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- _uninstallDefaultUserAgentForTests,
4
- DECO_POWERED_BY,
5
- DECO_USER_AGENT,
6
- installDefaultUserAgent,
7
- } from "./outboundHeaders";
8
-
9
- /** Headers the wrapped baseFetch would put on the wire for a given call. */
10
- function wireHeaders(call: readonly [RequestInfo | URL, RequestInit?]): Headers {
11
- const [input, init] = call;
12
- if (init?.headers !== undefined) return new Headers(init.headers);
13
- if (input instanceof Request) return new Headers(input.headers);
14
- return new Headers();
15
- }
16
-
17
- describe("installDefaultUserAgent", () => {
18
- const realFetch = globalThis.fetch;
19
-
20
- afterEach(() => {
21
- _uninstallDefaultUserAgentForTests();
22
- globalThis.fetch = realFetch;
23
- vi.restoreAllMocks();
24
- });
25
-
26
- function install(userAgent?: string) {
27
- const baseFetch = vi.fn(
28
- async (_input: RequestInfo | URL, _init?: RequestInit) => new Response("ok"),
29
- );
30
- globalThis.fetch = baseFetch as unknown as typeof fetch;
31
- installDefaultUserAgent(userAgent);
32
- return baseFetch;
33
- }
34
-
35
- it("sets the default UA on a bare string fetch", async () => {
36
- const baseFetch = install();
37
- await fetch("https://api.example.com/products");
38
-
39
- const headers = wireHeaders(baseFetch.mock.calls[0]);
40
- expect(headers.get("user-agent")).toBe(DECO_USER_AGENT);
41
- });
42
-
43
- it("keeps the caller's UA from init.headers", async () => {
44
- const baseFetch = install();
45
- await fetch("https://api.example.com/", {
46
- headers: { "user-agent": "deco-aws-app/1.0" },
47
- });
48
-
49
- // Untouched call: init passed through verbatim.
50
- expect(baseFetch.mock.calls[0][1]).toEqual({
51
- headers: { "user-agent": "deco-aws-app/1.0" },
52
- });
53
- });
54
-
55
- it("keeps the UA of a Request input", async () => {
56
- const baseFetch = install();
57
- const req = new Request("https://api.example.com/", {
58
- headers: { "User-Agent": "decocx/1.0" },
59
- });
60
- await fetch(req);
61
-
62
- expect(baseFetch.mock.calls[0][0]).toBe(req);
63
- expect(baseFetch.mock.calls[0][1]).toBeUndefined();
64
- });
65
-
66
- it("preserves a Request's other headers when injecting the UA", async () => {
67
- const baseFetch = install();
68
- await fetch(
69
- new Request("https://api.example.com/", {
70
- headers: { accept: "application/json", "x-api-key": "k" },
71
- }),
72
- );
73
-
74
- const headers = wireHeaders(baseFetch.mock.calls[0]);
75
- expect(headers.get("user-agent")).toBe(DECO_USER_AGENT);
76
- expect(headers.get("accept")).toBe("application/json");
77
- expect(headers.get("x-api-key")).toBe("k");
78
- });
79
-
80
- it("preserves non-header init members (method, body, signal)", async () => {
81
- const baseFetch = install();
82
- const controller = new AbortController();
83
- await fetch("https://api.example.com/", {
84
- method: "POST",
85
- body: "{}",
86
- signal: controller.signal,
87
- });
88
-
89
- const init = baseFetch.mock.calls[0][1]!;
90
- expect(init.method).toBe("POST");
91
- expect(init.body).toBe("{}");
92
- expect(init.signal).toBe(controller.signal);
93
- expect(new Headers(init.headers).get("user-agent")).toBe(DECO_USER_AGENT);
94
- });
95
-
96
- it("honors a custom UA value", async () => {
97
- const baseFetch = install("MyStore-Migration/1.0");
98
- await fetch("https://api.example.com/");
99
-
100
- expect(wireHeaders(baseFetch.mock.calls[0]).get("user-agent")).toBe("MyStore-Migration/1.0");
101
- });
102
-
103
- it("is idempotent — a second install does not re-wrap", () => {
104
- install();
105
- const wrapped = globalThis.fetch;
106
- installDefaultUserAgent();
107
- expect(globalThis.fetch).toBe(wrapped);
108
- });
109
-
110
- it("exposes the old-runtime-parity x-powered-by value", () => {
111
- expect(DECO_POWERED_BY).toMatch(/^deco@\d+\.\d+\.\d+/);
112
- });
113
- });