@decocms/blocks 7.71.6 → 8.0.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 (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
@@ -1,381 +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.acme.com.br";
16
- const FALLBACK_HOST = "lojaacme.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("streams the hostname rewrite instead of buffering the body", async () => {
52
- fetchSpy.mockResolvedValue(
53
- new Response(`<a href="https://${FALLBACK_HOST}/x">go</a>`, {
54
- status: 200,
55
- headers: { "content-type": "text/html", "content-length": "999" },
56
- }),
57
- );
58
-
59
- const res = await proxyToFallback(
60
- new Request(`https://${REAL_HOST}/foo`),
61
- makeUrl("/foo"),
62
- FALLBACK_HOST,
63
- );
64
-
65
- await expect(res.text()).resolves.toBe(`<a href="https://${REAL_HOST}/x">go</a>`);
66
- // The rewrite changes the body length, so the upstream content-length is a
67
- // lie and a streamed body has none to state.
68
- expect(res.headers.get("content-length")).toBeNull();
69
- });
70
-
71
- it("still rewrites when content-encoding is retained (workerd keeps the header but yields decoded bytes)", async () => {
72
- fetchSpy.mockResolvedValue(
73
- new Response(`see ${FALLBACK_HOST}`, {
74
- status: 200,
75
- headers: { "content-type": "text/html", "content-encoding": "gzip" },
76
- }),
77
- );
78
-
79
- const res = await proxyToFallback(
80
- new Request(`https://${REAL_HOST}/foo`),
81
- makeUrl("/foo"),
82
- FALLBACK_HOST,
83
- );
84
-
85
- await expect(res.text()).resolves.toBe(`see ${REAL_HOST}`);
86
- expect(res.headers.get("content-encoding")).toBe("gzip");
87
- });
88
-
89
- it("leaves a non-2xx body alone", async () => {
90
- fetchSpy.mockResolvedValue(
91
- new Response(`moved to ${FALLBACK_HOST}`, {
92
- status: 302,
93
- headers: { "content-type": "text/html" },
94
- }),
95
- );
96
-
97
- const res = await proxyToFallback(
98
- new Request(`https://${REAL_HOST}/foo`),
99
- makeUrl("/foo"),
100
- FALLBACK_HOST,
101
- );
102
-
103
- await expect(res.text()).resolves.toBe(`moved to ${FALLBACK_HOST}`);
104
- });
105
-
106
- it("always sets redirect:'manual' to avoid replaying streamed bodies on 3xx", async () => {
107
- fetchSpy.mockResolvedValue(new Response("ok", { status: 200 }));
108
-
109
- const request = new Request(`https://${REAL_HOST}/foo`, {
110
- method: "POST",
111
- body: "payload",
112
- });
113
- await proxyToFallback(request, makeUrl("/foo"), FALLBACK_HOST);
114
-
115
- expect(fetchSpy).toHaveBeenCalledTimes(1);
116
- const [, init] = fetchSpy.mock.calls[0];
117
- expect(init.redirect).toBe("manual");
118
- });
119
-
120
- it("strips hop-by-hop headers + host before forwarding", async () => {
121
- fetchSpy.mockResolvedValue(new Response(null, { status: 204 }));
122
-
123
- const request = new Request(`https://${REAL_HOST}/foo`, {
124
- method: "GET",
125
- headers: {
126
- host: REAL_HOST,
127
- connection: "keep-alive",
128
- "keep-alive": "timeout=5",
129
- "transfer-encoding": "chunked",
130
- upgrade: "websocket",
131
- "proxy-authorization": "Bearer x",
132
- "x-real-ip": "1.2.3.4",
133
- cookie: "session=abc",
134
- },
135
- });
136
- await proxyToFallback(request, makeUrl("/foo"), FALLBACK_HOST);
137
-
138
- const [, init] = fetchSpy.mock.calls[0];
139
- const fwd = init.headers as Headers;
140
- expect(fwd.get("host")).toBeNull();
141
- expect(fwd.get("connection")).toBeNull();
142
- expect(fwd.get("keep-alive")).toBeNull();
143
- expect(fwd.get("transfer-encoding")).toBeNull();
144
- expect(fwd.get("upgrade")).toBeNull();
145
- expect(fwd.get("proxy-authorization")).toBeNull();
146
- // Non-hop-by-hop headers are preserved.
147
- expect(fwd.get("x-real-ip")).toBe("1.2.3.4");
148
- expect(fwd.get("cookie")).toBe("session=abc");
149
- expect(fwd.get("x-forwarded-host")).toBe(REAL_HOST);
150
- });
151
-
152
- it("forwards a 302 from the upstream without following it, rewriting Location", async () => {
153
- fetchSpy.mockResolvedValue(
154
- new Response(null, {
155
- status: 302,
156
- headers: { location: `https://${FALLBACK_HOST}/landing` },
157
- }),
158
- );
159
-
160
- const request = new Request(`https://${REAL_HOST}/go`, {
161
- method: "POST",
162
- body: "irrelevant",
163
- });
164
- const res = await proxyToFallback(request, makeUrl("/go"), FALLBACK_HOST);
165
-
166
- expect(res.status).toBe(302);
167
- expect(res.headers.get("location")).toBe(`https://${REAL_HOST}/landing`);
168
- });
169
-
170
- it("does NOT consume the response body on 3xx (passes it through as stream)", async () => {
171
- // The text-rewrite block must skip non-2xx so streamed/binary 3xx bodies
172
- // aren't needlessly drained — that was a latent bug paired with the
173
- // redirect:"manual" fix.
174
- const upstream = new Response("redirect-body", {
175
- status: 301,
176
- headers: {
177
- "content-type": "text/html",
178
- location: `https://${FALLBACK_HOST}/elsewhere`,
179
- },
180
- });
181
- const textSpy = vi.spyOn(upstream, "text");
182
- fetchSpy.mockResolvedValue(upstream);
183
-
184
- const request = new Request(`https://${REAL_HOST}/r`, { method: "GET" });
185
- const res = await proxyToFallback(request, makeUrl("/r"), FALLBACK_HOST);
186
-
187
- expect(textSpy).not.toHaveBeenCalled();
188
- expect(res.status).toBe(301);
189
- expect(res.headers.get("location")).toBe(`https://${REAL_HOST}/elsewhere`);
190
- });
191
-
192
- it("rewrites the hostname in 2xx text bodies (Fresh partial URLs)", async () => {
193
- fetchSpy.mockResolvedValue(
194
- new Response(`<a href="https://${FALLBACK_HOST}/produto">veja</a>`, {
195
- status: 200,
196
- headers: { "content-type": "text/html" },
197
- }),
198
- );
199
-
200
- const request = new Request(`https://${REAL_HOST}/p`, { method: "GET" });
201
- const res = await proxyToFallback(request, makeUrl("/p"), FALLBACK_HOST);
202
- const body = await res.text();
203
-
204
- expect(body).toBe(`<a href="https://${REAL_HOST}/produto">veja</a>`);
205
- });
206
-
207
- it("does NOT call .text() on 2xx binary responses (image/png passes as stream)", async () => {
208
- const binary = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a]);
209
- const upstream = new Response(binary, {
210
- status: 200,
211
- headers: { "content-type": "image/png" },
212
- });
213
- const textSpy = vi.spyOn(upstream, "text");
214
- fetchSpy.mockResolvedValue(upstream);
215
-
216
- const request = new Request(`https://${REAL_HOST}/img.png`, {
217
- method: "GET",
218
- });
219
- const res = await proxyToFallback(request, makeUrl("/img.png"), FALLBACK_HOST);
220
-
221
- expect(textSpy).not.toHaveBeenCalled();
222
- expect(res.headers.get("content-type")).toBe("image/png");
223
- const bytes = new Uint8Array(await res.arrayBuffer());
224
- expect(Array.from(bytes)).toEqual(Array.from(binary));
225
- });
226
-
227
- it("rewrites Set-Cookie Domain from fallback origin to real hostname", async () => {
228
- const headers = new Headers({ "content-type": "application/json" });
229
- headers.append("set-cookie", `vtex_segment=abc; Domain=.${FALLBACK_HOST}; Path=/`);
230
- fetchSpy.mockResolvedValue(new Response("{}", { status: 200, headers }));
231
-
232
- const request = new Request(`https://${REAL_HOST}/api`, { method: "GET" });
233
- const res = await proxyToFallback(request, makeUrl("/api"), FALLBACK_HOST);
234
-
235
- const cookies = res.headers.getSetCookie?.() ?? [];
236
- expect(cookies).toHaveLength(1);
237
- expect(cookies[0]).toContain(`Domain=.${REAL_HOST}`);
238
- expect(cookies[0]).not.toContain(FALLBACK_HOST);
239
- });
240
- });
241
-
242
- // ---------------------------------------------------------------------------
243
- // withABTesting — clone defense
244
- // ---------------------------------------------------------------------------
245
-
246
- describe("withABTesting — outer-catch defense", () => {
247
- let fetchSpy: ReturnType<typeof vi.fn>;
248
-
249
- beforeEach(() => {
250
- fetchSpy = vi.fn();
251
- vi.stubGlobal("fetch", fetchSpy);
252
- });
253
-
254
- afterEach(() => {
255
- vi.unstubAllGlobals();
256
- });
257
-
258
- it("recovers via inner handler with body intact when fallback proxy throws", async () => {
259
- // Simulate the legacy bug: the first fetch (fallback proxy) blows up
260
- // *after* the body would have been consumed. The outer catch must be
261
- // able to read request.body when calling handler.fetch, so withABTesting
262
- // tees the request with request.clone() before handing it to the proxy.
263
- fetchSpy.mockRejectedValue(new Error("upstream exploded"));
264
-
265
- const handler: WorkerHandler = {
266
- fetch: vi.fn(async (req) => {
267
- const body = await req.text();
268
- return new Response(`handler saw: ${body}`, { status: 200 });
269
- }),
270
- };
271
-
272
- const kv = makeFakeKv({
273
- workerName: "test",
274
- fallbackOrigin: FALLBACK_HOST,
275
- abTest: { ratio: 0 }, // ratio 0 → always fallback bucket
276
- });
277
-
278
- const wrapped = withABTesting(handler, { kvBinding: "KV" });
279
- const request = new Request(`https://${REAL_HOST}/recover`, {
280
- method: "POST",
281
- body: "payload",
282
- });
283
- const res = await wrapped.fetch(
284
- request,
285
- { KV: kv } as unknown as Record<string, unknown>,
286
- makeCtx(),
287
- );
288
-
289
- expect(res.status).toBe(200);
290
- expect(await res.text()).toBe("handler saw: payload");
291
- expect(handler.fetch).toHaveBeenCalledTimes(1);
292
- });
293
- });
294
-
295
- // ---------------------------------------------------------------------------
296
- // Ratio-fingerprinted cookie
297
- // ---------------------------------------------------------------------------
298
-
299
- describe("getStableBucket — ratio fingerprint", () => {
300
- it("honors the cookie when its ratio fingerprint matches the current ratio", () => {
301
- const request = new Request(`https://${REAL_HOST}/`, {
302
- headers: { cookie: "_deco_bucket=fallback:50", "cf-connecting-ip": "1.2.3.4" },
303
- });
304
- expect(getStableBucket(request, 0.5, makeUrl("/"))).toBe("fallback");
305
- });
306
-
307
- it("ignores the cookie when the KV ratio has changed (fingerprint mismatch)", () => {
308
- // Cookie remembers an old 50/50 assignment. Operator bumped to 100/0 in
309
- // KV → cookie is no longer authoritative; bucket must be recomputed
310
- // against the new threshold (here: 1.0 → always "worker").
311
- const request = new Request(`https://${REAL_HOST}/`, {
312
- headers: { cookie: "_deco_bucket=fallback:50", "cf-connecting-ip": "1.2.3.4" },
313
- });
314
- expect(getStableBucket(request, 1.0, makeUrl("/"))).toBe("worker");
315
- });
316
-
317
- it("ignores legacy unix-timestamp cookies and re-evaluates against current ratio", () => {
318
- // Pre-fingerprint cookies (bucket:unixTs) parse to null and fall through
319
- // to the hash. Ratio=0 forces "fallback" regardless of IP.
320
- const request = new Request(`https://${REAL_HOST}/`, {
321
- headers: {
322
- cookie: "_deco_bucket=worker:1711540800",
323
- "cf-connecting-ip": "1.2.3.4",
324
- },
325
- });
326
- expect(getStableBucket(request, 0, makeUrl("/"))).toBe("fallback");
327
- });
328
-
329
- it("query param override beats the cookie even when fingerprint matches", () => {
330
- const request = new Request(`https://${REAL_HOST}/?_deco_bucket=worker`, {
331
- headers: { cookie: "_deco_bucket=fallback:50" },
332
- });
333
- expect(
334
- getStableBucket(
335
- request,
336
- 0.5,
337
- new URL(`https://${REAL_HOST}/?_deco_bucket=worker`),
338
- ),
339
- ).toBe("worker");
340
- });
341
- });
342
-
343
- describe("tagBucket — ratio fingerprint", () => {
344
- it("writes the cookie with the current ratio fingerprint when none exists", () => {
345
- const request = new Request(`https://${REAL_HOST}/`);
346
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.7);
347
- const setCookie = res.headers.get("set-cookie") ?? "";
348
- expect(setCookie).toContain("_deco_bucket=worker:70");
349
- expect(setCookie).toContain(`Domain=${REAL_HOST}`);
350
- expect(setCookie).toContain("SameSite=Lax");
351
- });
352
-
353
- it("rewrites the cookie when the ratio changes (cookie fingerprint stale)", () => {
354
- const request = new Request(`https://${REAL_HOST}/`, {
355
- headers: { cookie: "_deco_bucket=worker:30" },
356
- });
357
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.7);
358
- const setCookie = res.headers.get("set-cookie") ?? "";
359
- expect(setCookie).toContain("_deco_bucket=worker:70");
360
- });
361
-
362
- it("does NOT rewrite the cookie when bucket and ratio still match", () => {
363
- const request = new Request(`https://${REAL_HOST}/`, {
364
- headers: { cookie: "_deco_bucket=worker:50" },
365
- });
366
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.5);
367
- expect(res.headers.get("set-cookie")).toBeNull();
368
- });
369
-
370
- it("rounds the ratio to an integer percent (0.501 → 50)", () => {
371
- const request = new Request(`https://${REAL_HOST}/`);
372
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.501);
373
- expect(res.headers.get("set-cookie")).toContain("_deco_bucket=worker:50");
374
- });
375
-
376
- it("defaults Max-Age to 1 year (cookie expiry is no longer the invalidation mechanism)", () => {
377
- const request = new Request(`https://${REAL_HOST}/`);
378
- const res = tagBucket(new Response("ok"), "worker", REAL_HOST, request, 0.5);
379
- expect(res.headers.get("set-cookie")).toContain(`Max-Age=${60 * 60 * 24 * 365}`);
380
- });
381
- });
@@ -1,258 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- canonicalizeServerFnPayloadForCacheKey,
4
- payloadHasTrackingParams,
5
- detectCacheProfile,
6
- getCacheProfile,
7
- registerCachePattern,
8
- registerPrivatePaths,
9
- serverFnPagePath,
10
- setCacheProfile,
11
- } from "./cacheHeaders";
12
-
13
- const sfn = (payload: unknown): URL => {
14
- const u = new URL("https://store.com/_serverFn/abc123");
15
- if (payload !== undefined) u.searchParams.set("payload", JSON.stringify(payload));
16
- return u;
17
- };
18
-
19
- describe("serverFnPagePath — extract page path from GET server-fn payload", () => {
20
- it("returns null for a non-server-fn URL", () => {
21
- expect(serverFnPagePath(new URL("https://store.com/escolar/p"))).toBeNull();
22
- });
23
-
24
- it("returns null when there is no payload", () => {
25
- expect(serverFnPagePath(new URL("https://store.com/_serverFn/abc"))).toBeNull();
26
- });
27
-
28
- it("extracts the page path from TanStack's serialized envelope", () => {
29
- // Shape observed from a real loadCmsPage preload request.
30
- const payload = {
31
- t: {
32
- t: 10,
33
- i: 0,
34
- p: { k: ["data"], v: [{ t: 1, s: "/mochila-executiva-preta/p" }] },
35
- o: 0,
36
- },
37
- f: 63,
38
- m: [],
39
- };
40
- expect(serverFnPagePath(sfn(payload))).toBe("/mochila-executiva-preta/p");
41
- });
42
-
43
- it("extracts the page path from the simple { data } form", () => {
44
- expect(serverFnPagePath(sfn({ data: "/c/shoes" }))).toBe("/c/shoes");
45
- });
46
-
47
- it("returns null on malformed payload (fails safe)", () => {
48
- const u = new URL("https://store.com/_serverFn/abc");
49
- u.searchParams.set("payload", "{not json");
50
- expect(serverFnPagePath(u)).toBeNull();
51
- });
52
-
53
- it("ignores protocol-relative-looking values (//) and finds none", () => {
54
- expect(serverFnPagePath(sfn({ data: "//cdn.example.com/x" }))).toBeNull();
55
- });
56
-
57
- it("lets the server-fn response inherit the page's cache profile", () => {
58
- // The whole point: a PDP data request should profile as "product" (5min),
59
- // not the "listing" (60s) it would get from the /_serverFn pathname.
60
- const pdp = serverFnPagePath(sfn({ data: "/bolsa-preta/p" }));
61
- expect(pdp).toBe("/bolsa-preta/p");
62
- expect(detectCacheProfile(pdp!)).toBe("product");
63
-
64
- const home = serverFnPagePath(sfn({ data: "/" }));
65
- expect(detectCacheProfile(home!)).toBe("static");
66
- });
67
- });
68
-
69
- describe("canonicalizeServerFnPayloadForCacheKey — variant-param cache key", () => {
70
- // The real envelope shape observed from a loadCmsPage preload.
71
- const envelope = (path: string) =>
72
- JSON.stringify({
73
- t: { t: 10, i: 0, p: { k: ["data"], v: [{ t: 1, s: path }] }, o: 0 },
74
- f: 63,
75
- m: [],
76
- });
77
-
78
- it("strips skuId so a variant URL keys the same as the canonical path", () => {
79
- const withSku = canonicalizeServerFnPayloadForCacheKey(
80
- envelope("/mala-preta/p?skuId=148940"),
81
- );
82
- const canonical = canonicalizeServerFnPayloadForCacheKey(envelope("/mala-preta/p"));
83
- expect(withSku).toBe(canonical);
84
- });
85
-
86
- it("strips idsku as well", () => {
87
- const a = canonicalizeServerFnPayloadForCacheKey(envelope("/x/p?idsku=99"));
88
- const b = canonicalizeServerFnPayloadForCacheKey(envelope("/x/p"));
89
- expect(a).toBe(b);
90
- });
91
-
92
- it("strips tracking params — paid traffic shares the canonical entry", () => {
93
- const paid = canonicalizeServerFnPayloadForCacheKey(
94
- envelope("/aneis?filter.color=ouro&utm_source=google&gclid=abc&srsltid=xyz"),
95
- );
96
- const canonical = canonicalizeServerFnPayloadForCacheKey(
97
- envelope("/aneis?filter.color=ouro"),
98
- );
99
- expect(paid).toBe(canonical);
100
- });
101
-
102
- it("canonicalizes absolute URLs too, not just paths", () => {
103
- // Sites embed one in the payload (the deferred-section `pageUrl` is built
104
- // with `new URL(...)`), and the old guard skipped anything not starting
105
- // with "/" — so not even skuId was stripped there.
106
- const messy = canonicalizeServerFnPayloadForCacheKey(
107
- envelope("https://store.com/mala-preta/p?skuId=148940&utm_source=ads"),
108
- );
109
- const canonical = canonicalizeServerFnPayloadForCacheKey(
110
- envelope("https://store.com/mala-preta/p"),
111
- );
112
- expect(messy).toBe(canonical);
113
- });
114
-
115
- it("leaves non-URL strings alone", () => {
116
- const a = canonicalizeServerFnPayloadForCacheKey(envelope("mala preta ?utm_source=x"));
117
- expect(a).toBe(canonicalizeServerFnPayloadForCacheKey(envelope("mala preta ?utm_source=x")));
118
- expect(a).toContain("utm_source");
119
- });
120
-
121
- it("keeps PLP filter/search params (they DO change the response)", () => {
122
- const filtered = canonicalizeServerFnPayloadForCacheKey(
123
- envelope("/c/shoes?filter.size=40"),
124
- );
125
- const plain = canonicalizeServerFnPayloadForCacheKey(envelope("/c/shoes"));
126
- expect(filtered).not.toBe(plain);
127
- expect(filtered).toContain("filter.size=40");
128
- });
129
-
130
- it("keeps a non-ignored param while dropping skuId", () => {
131
- const out = canonicalizeServerFnPayloadForCacheKey(
132
- envelope("/c/shoes?q=boot&skuId=1"),
133
- );
134
- expect(out).toContain("q=boot");
135
- expect(out).not.toContain("skuId");
136
- });
137
-
138
- it("canonicalizes equivalent payloads to byte-identical strings", () => {
139
- // Even with no ignored param, both must round-trip to the same string so
140
- // the cache key is stable regardless of incidental serialization diffs.
141
- const a = canonicalizeServerFnPayloadForCacheKey(envelope("/a/p"));
142
- const b = canonicalizeServerFnPayloadForCacheKey(envelope("/a/p"));
143
- expect(a).toBe(b);
144
- });
145
-
146
- it("returns the original string on malformed payload (fail-safe)", () => {
147
- expect(canonicalizeServerFnPayloadForCacheKey("{not json")).toBe("{not json");
148
- });
149
- });
150
-
151
- describe("detectCacheProfile — private areas", () => {
152
- it.each([
153
- "/checkout",
154
- "/checkout/cart",
155
- "/cart",
156
- "/carrinho",
157
- "/minha-conta",
158
- "/meus-pedidos",
159
- "/login",
160
- "/myaccount",
161
- ])("keeps the existing private route %s private", (path) => {
162
- expect(detectCacheProfile(path)).toBe("private");
163
- });
164
-
165
- it.each([
166
- // Every one of these used to fall through to the cacheable `listing`
167
- // default. `/listadedesejos` is the one that bit a live store.
168
- "/listadedesejos",
169
- "/lista-de-desejos",
170
- "/wishlist",
171
- "/favoritos",
172
- "/orders",
173
- "/order-placed",
174
- "/profile",
175
- "/perfil",
176
- "/logout",
177
- "/sair",
178
- "/cadastro",
179
- "/signup",
180
- "/register",
181
- "/assinaturas",
182
- "/trocas",
183
- "/devolucao",
184
- ])("treats %s as private", (path) => {
185
- expect(detectCacheProfile(path)).toBe("private");
186
- });
187
-
188
- it("matches case-insensitively", () => {
189
- expect(detectCacheProfile("/Checkout")).toBe("private");
190
- expect(detectCacheProfile("/MINHA-CONTA")).toBe("private");
191
- });
192
-
193
- it("matches behind a locale prefix", () => {
194
- expect(detectCacheProfile("/pt/checkout")).toBe("private");
195
- expect(detectCacheProfile("/pt-br/minha-conta")).toBe("private");
196
- });
197
-
198
- it("does not swallow public routes that merely start with two letters", () => {
199
- expect(detectCacheProfile("/pt/tenis")).toBe("listing");
200
- expect(detectCacheProfile("/carteiras")).toBe("listing");
201
- expect(detectCacheProfile("/cartoes-presente")).toBe("listing");
202
- });
203
-
204
- it("registerPrivatePaths adds site-specific private routes", () => {
205
- expect(detectCacheProfile("/clube-vip")).toBe("listing");
206
- registerPrivatePaths(["/clube-vip", "sem-barra"]);
207
- expect(detectCacheProfile("/clube-vip")).toBe("private");
208
- expect(detectCacheProfile("/clube-vip/beneficios")).toBe("private");
209
- expect(detectCacheProfile("/sem-barra")).toBe("private");
210
- // prefix match must respect segment boundaries
211
- expect(detectCacheProfile("/clube-vip-publico")).toBe("listing");
212
- });
213
- });
214
-
215
- describe("cache configuration can tighten, not loosen", () => {
216
- it("refuses to make a non-public profile public", () => {
217
- setCacheProfile("private", { isPublic: true });
218
- expect(getCacheProfile("private").isPublic).toBe(false);
219
- });
220
-
221
- it("still allows ordinary tuning of a private profile", () => {
222
- setCacheProfile("private", { loader: { fresh: 1_000 } });
223
- expect(getCacheProfile("private").loader.fresh).toBe(1_000);
224
- expect(getCacheProfile("private").isPublic).toBe(false);
225
- });
226
-
227
- it("a custom pattern cannot make a private path public", () => {
228
- // A catch-all site pattern used to win over the built-in private check,
229
- // because custom patterns are evaluated first.
230
- registerCachePattern({ test: () => true, profile: "static" });
231
- expect(detectCacheProfile("/checkout")).toBe("private");
232
- // ...but it still applies everywhere else.
233
- expect(detectCacheProfile("/tenis")).toBe("static");
234
- });
235
- });
236
-
237
- describe("payloadHasTrackingParams", () => {
238
- const p = (v: unknown) => JSON.stringify(v);
239
-
240
- it("finds a tracking param in an embedded absolute URL", () => {
241
- expect(payloadHasTrackingParams(p({ data: { pageUrl: "https://x.test/p?gclid=1" } }))).toBe(
242
- true,
243
- );
244
- });
245
-
246
- it("finds a tracking param in an embedded route path", () => {
247
- expect(payloadHasTrackingParams(p(["/produtos?utm_source=ads&page=2"]))).toBe(true);
248
- });
249
-
250
- it("ignores real params and plain strings", () => {
251
- expect(payloadHasTrackingParams(p({ pageUrl: "/produtos?sort=price:asc&page=2" }))).toBe(false);
252
- expect(payloadHasTrackingParams(p({ label: "gclid=1 in a sentence" }))).toBe(false);
253
- });
254
-
255
- it("is fail-safe on malformed payloads", () => {
256
- expect(payloadHasTrackingParams("not json {")).toBe(false);
257
- });
258
- });