@decocms/blocks 8.0.0 → 8.1.0-next.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 (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. package/tsconfig.json +0 -7
@@ -1,326 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- getStableBucket,
4
- proxyToFallback,
5
- type SiteConfig,
6
- tagBucket,
7
- type WorkerHandler,
8
- withABTesting,
9
- } from "./abTesting";
10
-
11
- // ---------------------------------------------------------------------------
12
- // Test helpers
13
- // ---------------------------------------------------------------------------
14
-
15
- const REAL_HOST = "www.bagaggio.com.br";
16
- const FALLBACK_HOST = "lojabagaggio.deco.site";
17
-
18
- function makeUrl(path = "/x"): URL {
19
- return new URL(`https://${REAL_HOST}${path}`);
20
- }
21
-
22
- function makeFakeKv(value: SiteConfig | null) {
23
- return {
24
- get: vi.fn(async () => value),
25
- };
26
- }
27
-
28
- function makeCtx() {
29
- return {
30
- waitUntil: vi.fn(),
31
- passThroughOnException: vi.fn(),
32
- };
33
- }
34
-
35
- // ---------------------------------------------------------------------------
36
- // proxyToFallback
37
- // ---------------------------------------------------------------------------
38
-
39
- describe("proxyToFallback", () => {
40
- let fetchSpy: ReturnType<typeof vi.fn>;
41
-
42
- beforeEach(() => {
43
- fetchSpy = vi.fn();
44
- vi.stubGlobal("fetch", fetchSpy);
45
- });
46
-
47
- afterEach(() => {
48
- vi.unstubAllGlobals();
49
- });
50
-
51
- it("always sets redirect:'manual' to avoid replaying streamed bodies on 3xx", async () => {
52
- fetchSpy.mockResolvedValue(new Response("ok", { status: 200 }));
53
-
54
- const request = new Request(`https://${REAL_HOST}/foo`, {
55
- method: "POST",
56
- body: "payload",
57
- });
58
- await proxyToFallback(request, makeUrl("/foo"), FALLBACK_HOST);
59
-
60
- expect(fetchSpy).toHaveBeenCalledTimes(1);
61
- const [, init] = fetchSpy.mock.calls[0];
62
- expect(init.redirect).toBe("manual");
63
- });
64
-
65
- it("strips hop-by-hop headers + host before forwarding", async () => {
66
- fetchSpy.mockResolvedValue(new Response(null, { status: 204 }));
67
-
68
- const request = new Request(`https://${REAL_HOST}/foo`, {
69
- method: "GET",
70
- headers: {
71
- host: REAL_HOST,
72
- connection: "keep-alive",
73
- "keep-alive": "timeout=5",
74
- "transfer-encoding": "chunked",
75
- upgrade: "websocket",
76
- "proxy-authorization": "Bearer x",
77
- "x-real-ip": "1.2.3.4",
78
- cookie: "session=abc",
79
- },
80
- });
81
- await proxyToFallback(request, makeUrl("/foo"), FALLBACK_HOST);
82
-
83
- const [, init] = fetchSpy.mock.calls[0];
84
- const fwd = init.headers as Headers;
85
- expect(fwd.get("host")).toBeNull();
86
- expect(fwd.get("connection")).toBeNull();
87
- expect(fwd.get("keep-alive")).toBeNull();
88
- expect(fwd.get("transfer-encoding")).toBeNull();
89
- expect(fwd.get("upgrade")).toBeNull();
90
- expect(fwd.get("proxy-authorization")).toBeNull();
91
- // Non-hop-by-hop headers are preserved.
92
- expect(fwd.get("x-real-ip")).toBe("1.2.3.4");
93
- expect(fwd.get("cookie")).toBe("session=abc");
94
- expect(fwd.get("x-forwarded-host")).toBe(REAL_HOST);
95
- });
96
-
97
- it("forwards a 302 from the upstream without following it, rewriting Location", async () => {
98
- fetchSpy.mockResolvedValue(
99
- new Response(null, {
100
- status: 302,
101
- headers: { location: `https://${FALLBACK_HOST}/landing` },
102
- }),
103
- );
104
-
105
- const request = new Request(`https://${REAL_HOST}/go`, {
106
- method: "POST",
107
- body: "irrelevant",
108
- });
109
- const res = await proxyToFallback(request, makeUrl("/go"), FALLBACK_HOST);
110
-
111
- expect(res.status).toBe(302);
112
- expect(res.headers.get("location")).toBe(`https://${REAL_HOST}/landing`);
113
- });
114
-
115
- it("does NOT consume the response body on 3xx (passes it through as stream)", async () => {
116
- // The text-rewrite block must skip non-2xx so streamed/binary 3xx bodies
117
- // aren't needlessly drained — that was a latent bug paired with the
118
- // redirect:"manual" fix.
119
- const upstream = new Response("redirect-body", {
120
- status: 301,
121
- headers: {
122
- "content-type": "text/html",
123
- location: `https://${FALLBACK_HOST}/elsewhere`,
124
- },
125
- });
126
- const textSpy = vi.spyOn(upstream, "text");
127
- fetchSpy.mockResolvedValue(upstream);
128
-
129
- const request = new Request(`https://${REAL_HOST}/r`, { method: "GET" });
130
- const res = await proxyToFallback(request, makeUrl("/r"), FALLBACK_HOST);
131
-
132
- expect(textSpy).not.toHaveBeenCalled();
133
- expect(res.status).toBe(301);
134
- expect(res.headers.get("location")).toBe(`https://${REAL_HOST}/elsewhere`);
135
- });
136
-
137
- it("rewrites the hostname in 2xx text bodies (Fresh partial URLs)", async () => {
138
- fetchSpy.mockResolvedValue(
139
- new Response(`<a href="https://${FALLBACK_HOST}/produto">veja</a>`, {
140
- status: 200,
141
- headers: { "content-type": "text/html" },
142
- }),
143
- );
144
-
145
- const request = new Request(`https://${REAL_HOST}/p`, { method: "GET" });
146
- const res = await proxyToFallback(request, makeUrl("/p"), FALLBACK_HOST);
147
- const body = await res.text();
148
-
149
- expect(body).toBe(`<a href="https://${REAL_HOST}/produto">veja</a>`);
150
- });
151
-
152
- it("does NOT call .text() on 2xx binary responses (image/png passes as stream)", async () => {
153
- const binary = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a]);
154
- const upstream = new Response(binary, {
155
- status: 200,
156
- headers: { "content-type": "image/png" },
157
- });
158
- const textSpy = vi.spyOn(upstream, "text");
159
- fetchSpy.mockResolvedValue(upstream);
160
-
161
- const request = new Request(`https://${REAL_HOST}/img.png`, {
162
- method: "GET",
163
- });
164
- const res = await proxyToFallback(request, makeUrl("/img.png"), FALLBACK_HOST);
165
-
166
- expect(textSpy).not.toHaveBeenCalled();
167
- expect(res.headers.get("content-type")).toBe("image/png");
168
- const bytes = new Uint8Array(await res.arrayBuffer());
169
- expect(Array.from(bytes)).toEqual(Array.from(binary));
170
- });
171
-
172
- it("rewrites Set-Cookie Domain from fallback origin to real hostname", async () => {
173
- const headers = new Headers({ "content-type": "application/json" });
174
- headers.append("set-cookie", `vtex_segment=abc; Domain=.${FALLBACK_HOST}; Path=/`);
175
- fetchSpy.mockResolvedValue(new Response("{}", { status: 200, headers }));
176
-
177
- const request = new Request(`https://${REAL_HOST}/api`, { method: "GET" });
178
- const res = await proxyToFallback(request, makeUrl("/api"), FALLBACK_HOST);
179
-
180
- const cookies = res.headers.getSetCookie?.() ?? [];
181
- expect(cookies).toHaveLength(1);
182
- expect(cookies[0]).toContain(`Domain=.${REAL_HOST}`);
183
- expect(cookies[0]).not.toContain(FALLBACK_HOST);
184
- });
185
- });
186
-
187
- // ---------------------------------------------------------------------------
188
- // withABTesting — clone defense
189
- // ---------------------------------------------------------------------------
190
-
191
- describe("withABTesting — outer-catch defense", () => {
192
- let fetchSpy: ReturnType<typeof vi.fn>;
193
-
194
- beforeEach(() => {
195
- fetchSpy = vi.fn();
196
- vi.stubGlobal("fetch", fetchSpy);
197
- });
198
-
199
- afterEach(() => {
200
- vi.unstubAllGlobals();
201
- });
202
-
203
- it("recovers via inner handler with body intact when fallback proxy throws", async () => {
204
- // Simulate the legacy bug: the first fetch (fallback proxy) blows up
205
- // *after* the body would have been consumed. The outer catch must be
206
- // able to read request.body when calling handler.fetch, so withABTesting
207
- // tees the request with request.clone() before handing it to the proxy.
208
- fetchSpy.mockRejectedValue(new Error("upstream exploded"));
209
-
210
- const handler: WorkerHandler = {
211
- fetch: vi.fn(async (req) => {
212
- const body = await req.text();
213
- return new Response(`handler saw: ${body}`, { status: 200 });
214
- }),
215
- };
216
-
217
- const kv = makeFakeKv({
218
- workerName: "test",
219
- fallbackOrigin: FALLBACK_HOST,
220
- abTest: { ratio: 0 }, // ratio 0 → always fallback bucket
221
- });
222
-
223
- const wrapped = withABTesting(handler, { kvBinding: "KV" });
224
- const request = new Request(`https://${REAL_HOST}/recover`, {
225
- method: "POST",
226
- body: "payload",
227
- });
228
- const res = await wrapped.fetch(
229
- request,
230
- { KV: kv } as unknown as Record<string, unknown>,
231
- makeCtx(),
232
- );
233
-
234
- expect(res.status).toBe(200);
235
- expect(await res.text()).toBe("handler saw: payload");
236
- expect(handler.fetch).toHaveBeenCalledTimes(1);
237
- });
238
- });
239
-
240
- // ---------------------------------------------------------------------------
241
- // Ratio-fingerprinted cookie
242
- // ---------------------------------------------------------------------------
243
-
244
- describe("getStableBucket — ratio fingerprint", () => {
245
- it("honors the cookie when its ratio fingerprint matches the current ratio", () => {
246
- const request = new Request(`https://${REAL_HOST}/`, {
247
- headers: { cookie: "_deco_bucket=fallback:50", "cf-connecting-ip": "1.2.3.4" },
248
- });
249
- expect(getStableBucket(request, 0.5, makeUrl("/"))).toBe("fallback");
250
- });
251
-
252
- it("ignores the cookie when the KV ratio has changed (fingerprint mismatch)", () => {
253
- // Cookie remembers an old 50/50 assignment. Operator bumped to 100/0 in
254
- // KV → cookie is no longer authoritative; bucket must be recomputed
255
- // against the new threshold (here: 1.0 → always "worker").
256
- const request = new Request(`https://${REAL_HOST}/`, {
257
- headers: { cookie: "_deco_bucket=fallback:50", "cf-connecting-ip": "1.2.3.4" },
258
- });
259
- expect(getStableBucket(request, 1.0, makeUrl("/"))).toBe("worker");
260
- });
261
-
262
- it("ignores legacy unix-timestamp cookies and re-evaluates against current ratio", () => {
263
- // Pre-fingerprint cookies (bucket:unixTs) parse to null and fall through
264
- // to the hash. Ratio=0 forces "fallback" regardless of IP.
265
- const request = new Request(`https://${REAL_HOST}/`, {
266
- headers: {
267
- cookie: "_deco_bucket=worker:1711540800",
268
- "cf-connecting-ip": "1.2.3.4",
269
- },
270
- });
271
- expect(getStableBucket(request, 0, makeUrl("/"))).toBe("fallback");
272
- });
273
-
274
- it("query param override beats the cookie even when fingerprint matches", () => {
275
- const request = new Request(`https://${REAL_HOST}/?_deco_bucket=worker`, {
276
- headers: { cookie: "_deco_bucket=fallback:50" },
277
- });
278
- expect(
279
- getStableBucket(
280
- request,
281
- 0.5,
282
- new URL(`https://${REAL_HOST}/?_deco_bucket=worker`),
283
- ),
284
- ).toBe("worker");
285
- });
286
- });
287
-
288
- describe("tagBucket — ratio fingerprint", () => {
289
- it("writes the cookie with the current ratio fingerprint when none exists", () => {
290
- const request = new Request(`https://${REAL_HOST}/`);
291
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.7);
292
- const setCookie = res.headers.get("set-cookie") ?? "";
293
- expect(setCookie).toContain("_deco_bucket=worker:70");
294
- expect(setCookie).toContain(`Domain=${REAL_HOST}`);
295
- expect(setCookie).toContain("SameSite=Lax");
296
- });
297
-
298
- it("rewrites the cookie when the ratio changes (cookie fingerprint stale)", () => {
299
- const request = new Request(`https://${REAL_HOST}/`, {
300
- headers: { cookie: "_deco_bucket=worker:30" },
301
- });
302
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.7);
303
- const setCookie = res.headers.get("set-cookie") ?? "";
304
- expect(setCookie).toContain("_deco_bucket=worker:70");
305
- });
306
-
307
- it("does NOT rewrite the cookie when bucket and ratio still match", () => {
308
- const request = new Request(`https://${REAL_HOST}/`, {
309
- headers: { cookie: "_deco_bucket=worker:50" },
310
- });
311
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.5);
312
- expect(res.headers.get("set-cookie")).toBeNull();
313
- });
314
-
315
- it("rounds the ratio to an integer percent (0.501 → 50)", () => {
316
- const request = new Request(`https://${REAL_HOST}/`);
317
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.501);
318
- expect(res.headers.get("set-cookie")).toContain("_deco_bucket=worker:50");
319
- });
320
-
321
- it("defaults Max-Age to 1 year (cookie expiry is no longer the invalidation mechanism)", () => {
322
- const request = new Request(`https://${REAL_HOST}/`);
323
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.5);
324
- expect(res.headers.get("set-cookie")).toContain(`Max-Age=${60 * 60 * 24 * 365}`);
325
- });
326
- });
@@ -1,115 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- canonicalizeServerFnPayloadForCacheKey,
4
- detectCacheProfile,
5
- serverFnPagePath,
6
- } from "./cacheHeaders";
7
-
8
- const sfn = (payload: unknown): URL => {
9
- const u = new URL("https://store.com/_serverFn/abc123");
10
- if (payload !== undefined) u.searchParams.set("payload", JSON.stringify(payload));
11
- return u;
12
- };
13
-
14
- describe("serverFnPagePath — extract page path from GET server-fn payload", () => {
15
- it("returns null for a non-server-fn URL", () => {
16
- expect(serverFnPagePath(new URL("https://store.com/escolar/p"))).toBeNull();
17
- });
18
-
19
- it("returns null when there is no payload", () => {
20
- expect(serverFnPagePath(new URL("https://store.com/_serverFn/abc"))).toBeNull();
21
- });
22
-
23
- it("extracts the page path from TanStack's serialized envelope", () => {
24
- // Shape observed from a real loadCmsPage preload request.
25
- const payload = {
26
- t: {
27
- t: 10,
28
- i: 0,
29
- p: { k: ["data"], v: [{ t: 1, s: "/mochila-executiva-preta/p" }] },
30
- o: 0,
31
- },
32
- f: 63,
33
- m: [],
34
- };
35
- expect(serverFnPagePath(sfn(payload))).toBe("/mochila-executiva-preta/p");
36
- });
37
-
38
- it("extracts the page path from the simple { data } form", () => {
39
- expect(serverFnPagePath(sfn({ data: "/c/shoes" }))).toBe("/c/shoes");
40
- });
41
-
42
- it("returns null on malformed payload (fails safe)", () => {
43
- const u = new URL("https://store.com/_serverFn/abc");
44
- u.searchParams.set("payload", "{not json");
45
- expect(serverFnPagePath(u)).toBeNull();
46
- });
47
-
48
- it("ignores protocol-relative-looking values (//) and finds none", () => {
49
- expect(serverFnPagePath(sfn({ data: "//cdn.example.com/x" }))).toBeNull();
50
- });
51
-
52
- it("lets the server-fn response inherit the page's cache profile", () => {
53
- // The whole point: a PDP data request should profile as "product" (5min),
54
- // not the "listing" (60s) it would get from the /_serverFn pathname.
55
- const pdp = serverFnPagePath(sfn({ data: "/bolsa-preta/p" }));
56
- expect(pdp).toBe("/bolsa-preta/p");
57
- expect(detectCacheProfile(pdp!)).toBe("product");
58
-
59
- const home = serverFnPagePath(sfn({ data: "/" }));
60
- expect(detectCacheProfile(home!)).toBe("static");
61
- });
62
- });
63
-
64
- describe("canonicalizeServerFnPayloadForCacheKey — variant-param cache key", () => {
65
- // The real envelope shape observed from a loadCmsPage preload.
66
- const envelope = (path: string) =>
67
- JSON.stringify({
68
- t: { t: 10, i: 0, p: { k: ["data"], v: [{ t: 1, s: path }] }, o: 0 },
69
- f: 63,
70
- m: [],
71
- });
72
-
73
- it("strips skuId so a variant URL keys the same as the canonical path", () => {
74
- const withSku = canonicalizeServerFnPayloadForCacheKey(
75
- envelope("/mala-preta/p?skuId=148940"),
76
- );
77
- const canonical = canonicalizeServerFnPayloadForCacheKey(envelope("/mala-preta/p"));
78
- expect(withSku).toBe(canonical);
79
- });
80
-
81
- it("strips idsku as well", () => {
82
- const a = canonicalizeServerFnPayloadForCacheKey(envelope("/x/p?idsku=99"));
83
- const b = canonicalizeServerFnPayloadForCacheKey(envelope("/x/p"));
84
- expect(a).toBe(b);
85
- });
86
-
87
- it("keeps PLP filter/search params (they DO change the response)", () => {
88
- const filtered = canonicalizeServerFnPayloadForCacheKey(
89
- envelope("/c/shoes?filter.size=40"),
90
- );
91
- const plain = canonicalizeServerFnPayloadForCacheKey(envelope("/c/shoes"));
92
- expect(filtered).not.toBe(plain);
93
- expect(filtered).toContain("filter.size=40");
94
- });
95
-
96
- it("keeps a non-ignored param while dropping skuId", () => {
97
- const out = canonicalizeServerFnPayloadForCacheKey(
98
- envelope("/c/shoes?q=boot&skuId=1"),
99
- );
100
- expect(out).toContain("q=boot");
101
- expect(out).not.toContain("skuId");
102
- });
103
-
104
- it("canonicalizes equivalent payloads to byte-identical strings", () => {
105
- // Even with no ignored param, both must round-trip to the same string so
106
- // the cache key is stable regardless of incidental serialization diffs.
107
- const a = canonicalizeServerFnPayloadForCacheKey(envelope("/a/p"));
108
- const b = canonicalizeServerFnPayloadForCacheKey(envelope("/a/p"));
109
- expect(a).toBe(b);
110
- });
111
-
112
- it("returns the original string on malformed payload (fail-safe)", () => {
113
- expect(canonicalizeServerFnPayloadForCacheKey("{not json")).toBe("{not json");
114
- });
115
- });
@@ -1,122 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { clearLoaderCache, createCachedLoader, getLoaderCacheStats } from "./cachedLoader";
3
-
4
- describe("createCachedLoader", () => {
5
- beforeEach(() => {
6
- clearLoaderCache();
7
- });
8
- afterEach(() => {
9
- clearLoaderCache();
10
- vi.restoreAllMocks();
11
- });
12
-
13
- it("serves a fresh entry from cache (MISS then HIT) within maxAge", async () => {
14
- const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
15
- const cached = createCachedLoader("t/basic", loaderFn, {
16
- policy: "stale-while-revalidate",
17
- maxAge: 60_000,
18
- });
19
-
20
- await cached({ id: 1 }); // MISS
21
- await cached({ id: 1 }); // HIT — same key, within maxAge
22
-
23
- expect(loaderFn).toHaveBeenCalledTimes(1);
24
- expect(getLoaderCacheStats().entries).toBe(1);
25
- });
26
-
27
- it("distinct props produce distinct entries", async () => {
28
- const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
29
- const cached = createCachedLoader("t/props", loaderFn, {
30
- policy: "stale-while-revalidate",
31
- maxAge: 60_000,
32
- });
33
-
34
- await cached({ id: 1 });
35
- await cached({ id: 2 });
36
-
37
- expect(loaderFn).toHaveBeenCalledTimes(2);
38
- expect(getLoaderCacheStats().entries).toBe(2);
39
- });
40
-
41
- it("clearLoaderCache() empties the cache so the next call is a MISS", async () => {
42
- const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
43
- const cached = createCachedLoader("t/bust", loaderFn, {
44
- policy: "stale-while-revalidate",
45
- maxAge: 60_000,
46
- });
47
-
48
- await cached({ id: 1 }); // MISS
49
- await cached({ id: 1 }); // HIT
50
- expect(loaderFn).toHaveBeenCalledTimes(1);
51
-
52
- clearLoaderCache();
53
- expect(getLoaderCacheStats().entries).toBe(0);
54
-
55
- await cached({ id: 1 }); // MISS again — cache was cleared
56
- expect(loaderFn).toHaveBeenCalledTimes(2);
57
- });
58
-
59
- it("a purge during an in-flight loader does not repopulate the cleared entry", async () => {
60
- // Loader we can resolve manually, to hold it "in flight" across the purge.
61
- let release!: (v: { v: number }) => void;
62
- const loaderFn = vi.fn(
63
- () =>
64
- new Promise<{ v: number }>((res) => {
65
- release = res;
66
- }),
67
- );
68
- const cached = createCachedLoader("t/race", loaderFn, {
69
- policy: "stale-while-revalidate",
70
- maxAge: 60_000,
71
- });
72
-
73
- const inflight = cached({ id: 1 }); // MISS — loader now pending
74
- clearLoaderCache(); // purge lands while the loader is in flight
75
- release({ v: 99 }); // loader resolves with pre-purge data
76
- await expect(inflight).resolves.toEqual({ v: 99 }); // caller still gets its value
77
-
78
- // ...but the raced result must NOT have been written back to the cache.
79
- expect(getLoaderCacheStats().entries).toBe(0);
80
- });
81
-
82
- it("warns once per loader name when maxAge is very long", async () => {
83
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
84
- const loaderFn = vi.fn(async () => ({}));
85
-
86
- // > 10 min → warns
87
- createCachedLoader("t/long-a", loaderFn, {
88
- policy: "stale-while-revalidate",
89
- maxAge: 3_600_000,
90
- });
91
- // same name again → deduped, no second warning
92
- createCachedLoader("t/long-a", loaderFn, {
93
- policy: "stale-while-revalidate",
94
- maxAge: 3_600_000,
95
- });
96
- // short maxAge → no warning
97
- createCachedLoader("t/short", loaderFn, {
98
- policy: "stale-while-revalidate",
99
- maxAge: 60_000,
100
- });
101
-
102
- const longWarnings = warn.mock.calls.filter(
103
- (c) => typeof c[0] === "string" && c[0].includes("t/long-a"),
104
- );
105
- const shortWarnings = warn.mock.calls.filter(
106
- (c) => typeof c[0] === "string" && c[0].includes("t/short"),
107
- );
108
- expect(longWarnings).toHaveLength(1);
109
- expect(shortWarnings).toHaveLength(0);
110
- });
111
-
112
- it("no-store policy bypasses the cache entirely", async () => {
113
- const loaderFn = vi.fn(async () => ({}));
114
- const cached = createCachedLoader("t/nostore", loaderFn, { policy: "no-store" });
115
-
116
- await cached({});
117
- await cached({});
118
-
119
- expect(loaderFn).toHaveBeenCalledTimes(2);
120
- expect(getLoaderCacheStats().entries).toBe(0);
121
- });
122
- });