@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,625 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { configureTracer, type Span } from "../sdk/observability";
3
- import { RequestContext } from "../sdk/requestContext";
4
- import type { ResolvedSection } from "./resolve";
5
- import {
6
- getDegradedSections,
7
- isLayoutSection,
8
- layoutLoaderCacheKey,
9
- registerCacheableSections,
10
- registerLayoutSections,
11
- registerNonCriticalSections,
12
- registerSectionLoader,
13
- registerSectionLoaders,
14
- runSectionLoaders,
15
- runSingleSectionLoader,
16
- unregisterLayoutSections,
17
- } from "./sectionLoaders";
18
- import { compose, withDevice, withMobile, withSearchParam } from "./sectionMixins";
19
-
20
- const G = globalThis as any;
21
-
22
- beforeEach(() => {
23
- G.__deco.sectionLoaderRegistry.clear();
24
- G.__deco.layoutSections.clear();
25
- G.__deco.cacheableSections.clear();
26
- G.__deco.nonCriticalSections.clear();
27
- });
28
-
29
- const makeSection = (component: string, props: Record<string, unknown> = {}): ResolvedSection => ({
30
- component,
31
- props,
32
- key: component,
33
- index: 0,
34
- });
35
-
36
- describe("section degradation tracking (anti-cache-poisoning)", () => {
37
- const failing = async () => {
38
- throw new Error("VTEX down");
39
- };
40
-
41
- it("marks a critical section as degraded when its loader throws", async () => {
42
- registerSectionLoader("site/sections/ProductShelf.tsx", failing);
43
- const section = makeSection("site/sections/ProductShelf.tsx");
44
- const request = new Request("https://store.com/p");
45
-
46
- const degraded = await RequestContext.run(request, async () => {
47
- // Loader throws → section degrades to raw props (does not reject).
48
- const result = await runSingleSectionLoader(section, request);
49
- expect(result.component).toBe("site/sections/ProductShelf.tsx");
50
- return getDegradedSections();
51
- });
52
-
53
- expect(degraded).toContain("site/sections/ProductShelf.tsx");
54
- });
55
-
56
- it("does NOT mark a non-critical section as degraded", async () => {
57
- registerSectionLoader("site/sections/Decorative.tsx", failing);
58
- registerNonCriticalSections(["site/sections/Decorative.tsx"]);
59
- const section = makeSection("site/sections/Decorative.tsx");
60
- const request = new Request("https://store.com/p");
61
-
62
- const degraded = await RequestContext.run(request, async () => {
63
- await runSingleSectionLoader(section, request);
64
- return getDegradedSections();
65
- });
66
-
67
- expect(degraded).toEqual([]);
68
- });
69
-
70
- it("does NOT mark a failing LAYOUT section as degraded (avoids site-wide poisoning)", async () => {
71
- registerSectionLoader("site/sections/Header.tsx", failing);
72
- registerLayoutSections(["site/sections/Header.tsx"]);
73
- const section = makeSection("site/sections/Header.tsx");
74
- const request = new Request("https://store.com/p");
75
-
76
- const degraded = await RequestContext.run(request, async () => {
77
- await runSingleSectionLoader(section, request);
78
- return getDegradedSections();
79
- });
80
-
81
- // A flaky Header/Footer must not flip every page to X-Deco-Degraded.
82
- expect(degraded).toEqual([]);
83
- });
84
-
85
- it("does not flag a page whose loaders all succeed", async () => {
86
- registerSectionLoader("site/sections/Ok.tsx", async (p: Record<string, unknown>) => p);
87
- const section = makeSection("site/sections/Ok.tsx");
88
- const request = new Request("https://store.com/p");
89
-
90
- const degraded = await RequestContext.run(request, async () => {
91
- await runSingleSectionLoader(section, request);
92
- return getDegradedSections();
93
- });
94
-
95
- expect(degraded).toEqual([]);
96
- });
97
-
98
- it("is a no-op outside a request scope (does not throw)", async () => {
99
- registerSectionLoader("site/sections/NoScope.tsx", failing);
100
- const section = makeSection("site/sections/NoScope.tsx");
101
- const request = new Request("https://store.com/p");
102
- // No RequestContext.run wrapper — must not throw.
103
- await expect(runSingleSectionLoader(section, request)).resolves.toBeTruthy();
104
- expect(getDegradedSections()).toEqual([]);
105
- });
106
- });
107
-
108
- describe("runSingleSectionLoader — page context injection", () => {
109
- it("injects __pageUrl and __pagePath into loader props", async () => {
110
- // Two-arg signature so loader.mock.calls[0] types as [props, req].
111
- const loader = vi.fn(async (props: Record<string, unknown>, _req: Request) => props);
112
- registerSectionLoader("site/sections/SearchBanner.tsx", loader);
113
-
114
- const section = makeSection("site/sections/SearchBanner.tsx", { foo: "bar" });
115
- const request = new Request("https://store.com/lingerie?q=preto");
116
-
117
- await runSingleSectionLoader(section, request);
118
-
119
- expect(loader).toHaveBeenCalledTimes(1);
120
- const [calledProps, calledReq] = loader.mock.calls[0];
121
- expect(calledProps).toMatchObject({
122
- foo: "bar",
123
- __pageUrl: "https://store.com/lingerie?q=preto",
124
- __pagePath: "/lingerie",
125
- });
126
- expect(calledReq).toBe(request);
127
- });
128
-
129
- it("preserves existing __pageUrl / __pagePath from props (site workaround compat)", async () => {
130
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
131
- registerSectionLoader("site/sections/Custom.tsx", loader);
132
-
133
- const section = makeSection("site/sections/Custom.tsx", {
134
- __pageUrl: "https://override.example/page",
135
- __pagePath: "/override",
136
- });
137
- const request = new Request("https://store.com/real-path");
138
-
139
- await runSingleSectionLoader(section, request);
140
-
141
- const [calledProps] = loader.mock.calls[0];
142
- expect(calledProps.__pageUrl).toBe("https://override.example/page");
143
- expect(calledProps.__pagePath).toBe("/override");
144
- });
145
-
146
- it("does not throw when request.url is invalid", async () => {
147
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
148
- registerSectionLoader("site/sections/X.tsx", loader);
149
-
150
- const section = makeSection("site/sections/X.tsx", { foo: 1 });
151
- const badReq = { url: "not a url" } as unknown as Request;
152
-
153
- await expect(runSingleSectionLoader(section, badReq)).resolves.toBeDefined();
154
- expect(loader).toHaveBeenCalled();
155
- });
156
-
157
- it("returns section unchanged when no loader is registered", async () => {
158
- const section = makeSection("site/sections/NoLoader.tsx", { foo: 1 });
159
- const result = await runSingleSectionLoader(section, new Request("https://store.com/"));
160
- expect(result).toBe(section);
161
- });
162
-
163
- it("passes a 3rd-arg compat ctx (device from UA) — regular path (#305)", async () => {
164
- const loader = vi.fn(
165
- async (props: Record<string, unknown>, _req: Request, ctx?: { device?: string }) => ({
166
- ...props,
167
- seenDevice: ctx?.device,
168
- }),
169
- );
170
- registerSectionLoader("site/sections/Ctx.tsx", loader);
171
-
172
- const section = makeSection("site/sections/Ctx.tsx", {});
173
- const mobileReq = new Request("https://store.com/", {
174
- headers: { "user-agent": "iPhone Mobile Safari" },
175
- });
176
- const result = await runSingleSectionLoader(section, mobileReq);
177
-
178
- expect((result.props as Record<string, unknown>).seenDevice).toBe("mobile");
179
- });
180
-
181
- it("passes the compat ctx through layout and cacheable paths (#305)", async () => {
182
- const layoutLoader = vi.fn(
183
- async (props: Record<string, unknown>, _req: Request, ctx?: { device?: string }) => ({
184
- ...props,
185
- seenDevice: ctx?.device,
186
- }),
187
- );
188
- const cacheableLoader = vi.fn(
189
- async (props: Record<string, unknown>, _req: Request, ctx?: { device?: string }) => ({
190
- ...props,
191
- seenDevice: ctx?.device,
192
- }),
193
- );
194
- registerSectionLoader("site/sections/CtxHeader.tsx", layoutLoader);
195
- registerLayoutSections(["site/sections/CtxHeader.tsx"]);
196
- registerSectionLoader("site/sections/CtxShelf.tsx", cacheableLoader);
197
- registerCacheableSections({ "site/sections/CtxShelf.tsx": { maxAge: 60_000 } });
198
-
199
- const mobileReq = new Request("https://store.com/", {
200
- headers: { "user-agent": "iPhone Mobile Safari" },
201
- });
202
-
203
- const layoutResult = await runSingleSectionLoader(
204
- makeSection("site/sections/CtxHeader.tsx"),
205
- mobileReq,
206
- );
207
- const cacheableResult = await runSingleSectionLoader(
208
- makeSection("site/sections/CtxShelf.tsx"),
209
- mobileReq,
210
- );
211
-
212
- expect((layoutResult.props as Record<string, unknown>).seenDevice).toBe("mobile");
213
- expect((cacheableResult.props as Record<string, unknown>).seenDevice).toBe("mobile");
214
- });
215
- });
216
-
217
- describe("runSingleSectionLoader — cache keying", () => {
218
- it("cacheable sections share a cache entry across different page URLs", async () => {
219
- const loader = vi.fn(async (props: Record<string, unknown>) => ({
220
- ...props,
221
- enriched: true,
222
- }));
223
- registerSectionLoader("site/sections/Shelf.tsx", loader);
224
- registerCacheableSections({ "site/sections/Shelf.tsx": { maxAge: 60_000 } });
225
-
226
- const section = makeSection("site/sections/Shelf.tsx", { title: "Best" });
227
-
228
- await runSingleSectionLoader(section, new Request("https://store.com/page-a"));
229
- await runSingleSectionLoader(section, new Request("https://store.com/page-b"));
230
- await runSingleSectionLoader(section, new Request("https://store.com/page-c"));
231
-
232
- // Without URL-agnostic cache keys, this would be 3.
233
- expect(loader).toHaveBeenCalledTimes(1);
234
- });
235
-
236
- it("layout sections cache by component name and reuse across pages", async () => {
237
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
238
- registerSectionLoader("site/sections/Header.tsx", loader);
239
- registerLayoutSections(["site/sections/Header.tsx"]);
240
-
241
- const section = makeSection("site/sections/Header.tsx", { variant: "default" });
242
-
243
- await runSingleSectionLoader(section, new Request("https://store.com/a"));
244
- await runSingleSectionLoader(section, new Request("https://store.com/b"));
245
-
246
- expect(loader).toHaveBeenCalledTimes(1);
247
- });
248
-
249
- it("regular (non-cached) sections re-run on every request", async () => {
250
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
251
- registerSectionLoader("site/sections/Reg.tsx", loader);
252
-
253
- const section = makeSection("site/sections/Reg.tsx", {});
254
- await runSingleSectionLoader(section, new Request("https://store.com/a"));
255
- await runSingleSectionLoader(section, new Request("https://store.com/b"));
256
-
257
- expect(loader).toHaveBeenCalledTimes(2);
258
- });
259
- });
260
-
261
- // ---------------------------------------------------------------------------
262
- // Layout cache opt-out (#206)
263
- // ---------------------------------------------------------------------------
264
-
265
- describe("unregisterLayoutSections", () => {
266
- it("drops a key from the layout set so the loader re-runs per request", async () => {
267
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
268
- registerSectionLoader("site/sections/Header.tsx", loader);
269
- registerLayoutSections(["site/sections/Header.tsx"]);
270
- expect(isLayoutSection("site/sections/Header.tsx")).toBe(true);
271
-
272
- unregisterLayoutSections(["site/sections/Header.tsx"]);
273
- expect(isLayoutSection("site/sections/Header.tsx")).toBe(false);
274
-
275
- const section = makeSection("site/sections/Header.tsx", {});
276
- await runSingleSectionLoader(section, new Request("https://store.com/a"));
277
- await runSingleSectionLoader(section, new Request("https://store.com/b"));
278
-
279
- // No layout caching after unregister — loader runs per request.
280
- expect(loader).toHaveBeenCalledTimes(2);
281
- });
282
-
283
- it("is a no-op for keys that were never registered", () => {
284
- expect(() => unregisterLayoutSections(["site/sections/Never.tsx"])).not.toThrow();
285
- expect(isLayoutSection("site/sections/Never.tsx")).toBe(false);
286
- });
287
- });
288
-
289
- // ---------------------------------------------------------------------------
290
- // Dev warning: layout + request-dependent loader → cache contamination (#206)
291
- // ---------------------------------------------------------------------------
292
-
293
- describe("registerSectionLoaders — request-dependent + layout warning (#206)", () => {
294
- const originalNodeEnv = process.env.NODE_ENV;
295
- let warnSpy: ReturnType<typeof vi.spyOn>;
296
-
297
- beforeEach(() => {
298
- process.env.NODE_ENV = "development";
299
- warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
300
- });
301
-
302
- afterEach(() => {
303
- process.env.NODE_ENV = originalNodeEnv;
304
- warnSpy.mockRestore();
305
- });
306
-
307
- it("warns when a request-dependent loader is registered for a layout section", () => {
308
- registerLayoutSections(["site/sections/Header.tsx"]);
309
- registerSectionLoaders({
310
- "site/sections/Header.tsx": withDevice(),
311
- });
312
- const calls = warnSpy.mock.calls.map((c) => String(c[0]));
313
- expect(calls.some((m) => m.includes("Header.tsx"))).toBe(true);
314
- expect(calls.some((m) => m.includes("layout section"))).toBe(true);
315
- expect(calls.some((m) => m.includes("unregisterLayoutSections"))).toBe(true);
316
- });
317
-
318
- it("warns when a composed loader contains any request-dependent mixin", () => {
319
- registerLayoutSections(["site/sections/Footer.tsx"]);
320
- registerSectionLoaders({
321
- "site/sections/Footer.tsx": compose(withSearchParam(), async (props) => props),
322
- });
323
- expect(warnSpy).toHaveBeenCalled();
324
- });
325
-
326
- it("does NOT warn for a layout section whose loader is request-independent", () => {
327
- registerLayoutSections(["site/sections/Theme.tsx"]);
328
- registerSectionLoaders({
329
- "site/sections/Theme.tsx": async (props) => props,
330
- });
331
- expect(warnSpy).not.toHaveBeenCalled();
332
- });
333
-
334
- it("does NOT warn after unregisterLayoutSections drops the key", () => {
335
- registerLayoutSections(["site/sections/Header.tsx"]);
336
- unregisterLayoutSections(["site/sections/Header.tsx"]);
337
- registerSectionLoaders({
338
- "site/sections/Header.tsx": withDevice(),
339
- });
340
- expect(warnSpy).not.toHaveBeenCalled();
341
- });
342
-
343
- it("does NOT warn in production", () => {
344
- process.env.NODE_ENV = "production";
345
- registerLayoutSections(["site/sections/Header.tsx"]);
346
- registerSectionLoaders({
347
- "site/sections/Header.tsx": withMobile(),
348
- });
349
- expect(warnSpy).not.toHaveBeenCalled();
350
- });
351
- });
352
-
353
- describe("runSingleSectionLoader — error handling", () => {
354
- it("falls back to original section when loader throws", async () => {
355
- const loader = vi.fn(async () => {
356
- throw new Error("boom");
357
- });
358
- registerSectionLoader("site/sections/Boom.tsx", loader);
359
-
360
- const section = makeSection("site/sections/Boom.tsx", { x: 1 });
361
- const result = await runSingleSectionLoader(section, new Request("https://store.com/"));
362
- expect(result).toEqual(section);
363
- });
364
- });
365
-
366
- describe("runSingleSectionLoader — nested section recursion", () => {
367
- it("runs the loader of a nested section in props", async () => {
368
- const childLoader = vi.fn(async (props: Record<string, unknown>) => ({
369
- ...props,
370
- enriched: true,
371
- }));
372
- registerSectionLoader("site/sections/CategoryBanner.tsx", childLoader);
373
-
374
- // Parent has no own loader, only a nested section in props
375
- const parent = makeSection("site/sections/BackgroundWrapper.tsx", {
376
- child: {
377
- Component: "site/sections/CategoryBanner.tsx",
378
- props: { matcher: "/foo" },
379
- },
380
- });
381
-
382
- const result = await runSingleSectionLoader(parent, new Request("https://store.com/foo"));
383
-
384
- expect(childLoader).toHaveBeenCalledTimes(1);
385
- expect(result.props).toEqual({
386
- child: {
387
- Component: "site/sections/CategoryBanner.tsx",
388
- props: {
389
- matcher: "/foo",
390
- enriched: true,
391
- // page context is injected for nested sections too
392
- __pageUrl: "https://store.com/foo",
393
- __pagePath: "/foo",
394
- },
395
- },
396
- });
397
- });
398
-
399
- it("runs nested loaders in arrays (e.g. sections: Section[])", async () => {
400
- const banner = vi.fn(async (props: any) => ({ ...props, ranBanner: true }));
401
- const shelf = vi.fn(async (props: any) => ({ ...props, ranShelf: true }));
402
- registerSectionLoader("site/sections/Banner.tsx", banner);
403
- registerSectionLoader("site/sections/Shelf.tsx", shelf);
404
-
405
- const parent = makeSection("site/sections/Wrapper.tsx", {
406
- sections: [
407
- { Component: "site/sections/Banner.tsx", props: { id: 1 } },
408
- { Component: "site/sections/Shelf.tsx", props: { id: 2 } },
409
- ],
410
- });
411
-
412
- const result = await runSingleSectionLoader(parent, new Request("https://store.com/"));
413
-
414
- expect(banner).toHaveBeenCalledTimes(1);
415
- expect(shelf).toHaveBeenCalledTimes(1);
416
- const sections = (result.props as any).sections;
417
- expect(sections[0].props).toMatchObject({ id: 1, ranBanner: true });
418
- expect(sections[1].props).toMatchObject({ id: 2, ranShelf: true });
419
- });
420
-
421
- it("returns same props reference when no nested sections (zero-alloc leaf path)", async () => {
422
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
423
- registerSectionLoader("site/sections/Leaf.tsx", loader);
424
-
425
- const props = { foo: "bar" };
426
- const section = makeSection("site/sections/Leaf.tsx", props);
427
-
428
- const result = await runSingleSectionLoader(section, new Request("https://store.com/"));
429
-
430
- // Loader returned the SAME props ref → enrichNestedSections must also
431
- // return the same ref → no { ...result, props } wrapping happens
432
- expect(result.props).toMatchObject({
433
- foo: "bar",
434
- __pageUrl: "https://store.com/",
435
- __pagePath: "/",
436
- });
437
- });
438
-
439
- it("recurses into deeply nested sections (wrapper inside wrapper)", async () => {
440
- const inner = vi.fn(async (props: any) => ({ ...props, deep: true }));
441
- registerSectionLoader("site/sections/Inner.tsx", inner);
442
-
443
- const parent = makeSection("site/sections/Outer.tsx", {
444
- child: {
445
- Component: "site/sections/MidWrapper.tsx",
446
- props: {
447
- grandchild: {
448
- Component: "site/sections/Inner.tsx",
449
- props: { tag: "deep" },
450
- },
451
- },
452
- },
453
- });
454
-
455
- const result = await runSingleSectionLoader(parent, new Request("https://store.com/"));
456
-
457
- expect(inner).toHaveBeenCalledTimes(1);
458
- const grandchild = (result.props as any).child.props.grandchild;
459
- expect(grandchild.props).toMatchObject({ tag: "deep", deep: true });
460
- });
461
-
462
- it("ignores nested objects that do not look like sections", async () => {
463
- const loader = vi.fn(async (props: Record<string, unknown>) => props);
464
- registerSectionLoader("site/sections/Leaf.tsx", loader);
465
-
466
- const section = makeSection("site/sections/Leaf.tsx", {
467
- // Plain config object, not a section. Has `Component: string` but
468
- // missing the `props` field — must NOT be treated as a nested section.
469
- config: { Component: "ButtonStyle", color: "red" },
470
- });
471
-
472
- const result = await runSingleSectionLoader(section, new Request("https://store.com/"));
473
-
474
- expect(loader).toHaveBeenCalledTimes(1);
475
- expect((result.props as any).config).toEqual({
476
- Component: "ButtonStyle",
477
- color: "red",
478
- });
479
- });
480
-
481
- it("runs nested loaders even when parent has no own loader", async () => {
482
- const childLoader = vi.fn(async (props: any) => ({ ...props, ran: true }));
483
- registerSectionLoader("site/sections/Child.tsx", childLoader);
484
-
485
- // Parent has no entry in registry — but it has a nested section in props
486
- // (typical of a pure layout container that just renders children).
487
- const parent = makeSection("site/sections/UnregisteredLayout.tsx", {
488
- child: {
489
- Component: "site/sections/Child.tsx",
490
- props: { foo: "bar" },
491
- },
492
- });
493
-
494
- const result = await runSingleSectionLoader(parent, new Request("https://store.com/"));
495
-
496
- expect(childLoader).toHaveBeenCalledTimes(1);
497
- expect((result.props as any).child.props).toMatchObject({
498
- foo: "bar",
499
- ran: true,
500
- });
501
- });
502
- });
503
-
504
- describe("runSectionLoaders — batch span", () => {
505
- afterEach(() => {
506
- configureTracer({ startSpan: () => ({ end: () => {} }) });
507
- });
508
-
509
- it("emits one deco.section.loaders.batch parent with section.count", async () => {
510
- const spans: Array<{ name: string; attrs?: Record<string, unknown> }> = [];
511
- configureTracer({
512
- startSpan: (name, attrs) => {
513
- spans.push({ name, attrs });
514
- const s: Span = { end: () => {} };
515
- return s;
516
- },
517
- });
518
-
519
- registerSectionLoader("a", async (p) => p);
520
- registerSectionLoader("b", async (p) => p);
521
-
522
- await runSectionLoaders(
523
- [makeSection("a"), makeSection("b"), makeSection("c-no-loader")],
524
- new Request("https://site/"),
525
- );
526
-
527
- const batch = spans.find((s) => s.name === "deco.section.loaders.batch");
528
- expect(batch).toBeDefined();
529
- expect(batch?.attrs).toMatchObject({ "section.count": 3 });
530
-
531
- const perSection = spans.filter((s) => s.name === "deco.section.loader");
532
- expect(perSection).toHaveLength(3);
533
- });
534
- });
535
-
536
- // ---------------------------------------------------------------------------
537
- // Layout section cache — device is part of the key
538
- // ---------------------------------------------------------------------------
539
- //
540
- // This cache holds a layout section's LOADER OUTPUT, and that is where
541
- // `isMobile` is born (`ctx.device`, or a loader composed with `withDevice` /
542
- // `withMobile`). Keyed by component path alone, the first request decided the
543
- // variant for everyone for 5 minutes. Measured on a real store's PDP with
544
- // Header/Footer layout-cached: desktop first and a mobile visitor got the
545
- // desktop header (`h-[90px]`); mobile first and a desktop visitor got
546
- // `id="header-mobile-menu"`.
547
- //
548
- // NOTE: this is a DIFFERENT cache from `resolvedLayoutCache` in `cms/resolve.ts`.
549
- // That one holds the CMS prop resolution and never sees `isMobile`, so putting
550
- // the axis there (which is what decocms/blocks#528 did) does not fix this.
551
-
552
- describe("layout section cache — device axis", () => {
553
- const MOBILE = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile Safari";
554
- const TABLET = "Mozilla/5.0 (iPad; CPU OS 17_0) Safari/605";
555
- const DESKTOP = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120 Safari/537.36";
556
-
557
- // `layoutCache` is module-global with a 5-minute TTL and no exported reset, so
558
- // a shared component key would leak entries between cases.
559
- let seq = 0;
560
- const req = (ua: string) => new Request("https://store.com/p", { headers: { "user-agent": ua } });
561
-
562
- /** A layout loader that stamps what device it saw — the leak made visible. */
563
- const setupDeviceLayout = () => {
564
- seq += 1;
565
- const key = `site/sections/DeviceLayout${seq}.tsx`;
566
- let runs = 0;
567
- registerSectionLoader(key, async (props: Record<string, unknown>, request?: Request) => {
568
- runs += 1;
569
- const ua = request?.headers.get("user-agent") ?? "";
570
- return { ...props, isMobile: /iPhone|Mobile/.test(ua), ua };
571
- });
572
- registerLayoutSections([key]);
573
- return { key, runs: () => runs };
574
- };
575
-
576
- const load = async (key: string, ua: string) => {
577
- const request = req(ua);
578
- const out = await RequestContext.run(request, () =>
579
- runSingleSectionLoader(makeSection(key), request),
580
- );
581
- return out.props as { isMobile: boolean; ua: string };
582
- };
583
-
584
- it("a mobile visitor does NOT get the variant a desktop visitor cached", async () => {
585
- const { key, runs } = setupDeviceLayout();
586
-
587
- const desktop = await load(key, DESKTOP);
588
- expect(desktop.isMobile).toBe(false);
589
-
590
- const mobile = await load(key, MOBILE);
591
- // Without the axis this came back `false` — the desktop header on a phone.
592
- expect(mobile.isMobile).toBe(true);
593
- expect(runs()).toBe(2);
594
- });
595
-
596
- it("and the reverse: desktop after mobile", async () => {
597
- const { key } = setupDeviceLayout();
598
- expect((await load(key, MOBILE)).isMobile).toBe(true);
599
- expect((await load(key, DESKTOP)).isMobile).toBe(false);
600
- });
601
-
602
- it("two visitors on the same device share the entry — the cache still works", async () => {
603
- const { key, runs } = setupDeviceLayout();
604
- await load(key, DESKTOP);
605
- await load(key, DESKTOP);
606
- expect(runs()).toBe(1);
607
- });
608
-
609
- it("tablet is its own entry", async () => {
610
- const { key, runs } = setupDeviceLayout();
611
- await load(key, MOBILE);
612
- await load(key, TABLET);
613
- expect(runs()).toBe(2);
614
- });
615
-
616
- it("layoutLoaderCacheKey: three devices, three keys; no request still keys", () => {
617
- const keys = [MOBILE, TABLET, DESKTOP].map((ua) => layoutLoaderCacheKey("X", req(ua)));
618
- expect(new Set(keys).size).toBe(3);
619
- const bare = layoutLoaderCacheKey("X");
620
- expect(bare).not.toContain("undefined");
621
- // A request with no UA header must land on the same bucket as no request at
622
- // all, so a health check does not fragment the desktop entry.
623
- expect(bare).toBe(layoutLoaderCacheKey("X", new Request("https://store.com/p")));
624
- });
625
- });