@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,980 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
-
3
- // Mock dependencies before importing the module under test
4
- vi.mock("./sectionLoaders", () => ({
5
- isLayoutSection: () => false,
6
- runSingleSectionLoader: vi.fn(async (section: any) => section),
7
- }));
8
-
9
- vi.mock("../sdk/normalizeUrls", () => ({
10
- normalizeUrlsInObject: vi.fn(<T>(x: T) => x),
11
- }));
12
-
13
- vi.mock("./loader", () => ({
14
- findPageByPath: vi.fn(),
15
- loadBlocks: vi.fn(() => ({})),
16
- }));
17
-
18
- vi.mock("./registry", () => ({
19
- getSection: vi.fn(),
20
- getOnBeforeResolveProps: vi.fn(),
21
- }));
22
-
23
- import { normalizeUrlsInObject } from "../sdk/normalizeUrls";
24
- import { findPageByPath } from "./loader";
25
- import { getSection } from "./registry";
26
- import type { AsyncRenderingConfig, DeferredSection } from "./resolve";
27
- import {
28
- clearCommerceLoaders,
29
- DEFAULT_FOLD_THRESHOLD,
30
- extractSeoFromProps,
31
- getAsyncRenderingConfig,
32
- isEagerRequest,
33
- registerCommerceLoader,
34
- registerEagerSections,
35
- registerNeverDeferSections,
36
- resolveDecoPage,
37
- resolveDeferredSectionFull,
38
- resolvePageSeoBlock,
39
- resolveSectionsList,
40
- resolveValue,
41
- setAsyncRenderingConfig,
42
- shouldDeferSection,
43
- WELL_KNOWN_TYPES,
44
- } from "./resolve";
45
- import { runSingleSectionLoader } from "./sectionLoaders";
46
-
47
- describe("resolveDeferredSectionFull", () => {
48
- it("resolves a deferred section and preserves index", async () => {
49
- const ds: DeferredSection = {
50
- component: "site/sections/ProductShelf.tsx",
51
- key: "site/sections/ProductShelf.tsx",
52
- index: 5,
53
- propsHash: "test",
54
- rawProps: { title: "Best Sellers" },
55
- };
56
-
57
- const request = new Request("https://store.com/");
58
-
59
- // resolveDeferredSection depends on ensureInitialized() and CMS internals.
60
- // Since we can't easily mock the full resolution pipeline, we test that
61
- // the function composes correctly by verifying it calls the right deps.
62
- // A full integration test would require a running CMS context.
63
-
64
- // For now, verify the function signature is correct and types align
65
- expect(typeof resolveDeferredSectionFull).toBe("function");
66
- expect(resolveDeferredSectionFull.length).toBe(4); // ds, pagePath, request, matcherCtx?
67
- });
68
-
69
- it("runSingleSectionLoader is called with enriched section", async () => {
70
- // Verify the mock is correctly set up
71
- const mockSection = {
72
- component: "test",
73
- props: { title: "hi" },
74
- key: "test",
75
- index: 3,
76
- };
77
- const request = new Request("https://store.com/");
78
-
79
- const result = await (runSingleSectionLoader as any)(mockSection, request);
80
- expect(result).toEqual(mockSection);
81
- });
82
-
83
- it("normalizeUrlsInObject is used for output normalization", () => {
84
- const input = { url: "https://store.com/image.jpg" };
85
- const result = (normalizeUrlsInObject as any)(input);
86
- expect(result).toEqual(input); // mock passes through
87
- });
88
- });
89
-
90
- // ---------------------------------------------------------------------------
91
- // resolveSectionsList — page-level variant wrapper support
92
- // ---------------------------------------------------------------------------
93
-
94
- describe("resolveSectionsList", () => {
95
- const makeRctx = (matcherCtx = {}) => ({
96
- routeParams: {},
97
- matcherCtx,
98
- memo: new Map(),
99
- depth: 0,
100
- });
101
-
102
- it("returns array as-is when value is already an array", async () => {
103
- const sections = [{ __resolveType: "section-A" }, { __resolveType: "section-B" }];
104
- const result = await resolveSectionsList(sections, makeRctx());
105
- expect(result).toEqual(sections);
106
- });
107
-
108
- it("returns empty array for null/undefined/non-object", async () => {
109
- expect(await resolveSectionsList(null, makeRctx())).toEqual([]);
110
- expect(await resolveSectionsList(undefined, makeRctx())).toEqual([]);
111
- expect(await resolveSectionsList("string", makeRctx())).toEqual([]);
112
- expect(await resolveSectionsList(42, makeRctx())).toEqual([]);
113
- });
114
-
115
- it("resolves page-level variant wrapper without __resolveType", async () => {
116
- // Simulates CMS admin wrapping all sections in a device variant
117
- // Rule has no __resolveType → evaluateMatcher returns true (match-all)
118
- const sectionsArray = [
119
- { __resolveType: "Header - 01" },
120
- { __resolveType: "site/sections/Account/PersonalData.tsx" },
121
- { __resolveType: "Footer - 01" },
122
- ];
123
-
124
- const variantWrapper = {
125
- variants: [
126
- {
127
- rule: { mobile: true, tablet: true, desktop: true },
128
- value: sectionsArray,
129
- },
130
- ],
131
- };
132
-
133
- const result = await resolveSectionsList(variantWrapper, makeRctx());
134
- expect(result).toEqual(sectionsArray);
135
- });
136
-
137
- it("returns empty when no variant matches in page-level wrapper", async () => {
138
- // All variants have __resolveType in rule → evaluateMatcher returns false
139
- // (unregistered matcher defaults to false)
140
- const variantWrapper = {
141
- variants: [
142
- {
143
- rule: { __resolveType: "website/matchers/device.ts", mobile: true },
144
- value: [{ __resolveType: "MobileOnly" }],
145
- },
146
- ],
147
- };
148
-
149
- const result = await resolveSectionsList(variantWrapper, makeRctx());
150
- expect(result).toEqual([]);
151
- });
152
-
153
- it("picks first matching variant in page-level wrapper", async () => {
154
- const desktopSections = [{ __resolveType: "DesktopLayout" }];
155
- const mobileSections = [{ __resolveType: "MobileLayout" }];
156
-
157
- const variantWrapper = {
158
- variants: [
159
- {
160
- // No __resolveType → evaluateMatcher returns true (first match wins)
161
- rule: { desktop: true },
162
- value: desktopSections,
163
- },
164
- {
165
- rule: { mobile: true },
166
- value: mobileSections,
167
- },
168
- ],
169
- };
170
-
171
- const result = await resolveSectionsList(variantWrapper, makeRctx());
172
- expect(result).toEqual(desktopSections);
173
- });
174
-
175
- it("returns empty for object without __resolveType and without variants", async () => {
176
- const result = await resolveSectionsList({ someKey: "value" }, makeRctx());
177
- expect(result).toEqual([]);
178
- });
179
-
180
- it("respects max depth limit (20)", async () => {
181
- // Build 21 levels of nested variant wrappers to exceed MAX_RESOLVE_DEPTH=20
182
- let wrapper: any = [{ __resolveType: "deep" }];
183
- for (let i = 0; i < 21; i++) {
184
- wrapper = { variants: [{ rule: {}, value: wrapper }] };
185
- }
186
- const result = await resolveSectionsList(wrapper, makeRctx());
187
- expect(result).toEqual([]);
188
- });
189
- });
190
-
191
- // ---------------------------------------------------------------------------
192
- // Commerce loader auto-injects URL query params as top-level props
193
- // ---------------------------------------------------------------------------
194
- //
195
- // Regression guard for Google Shopping deep links (and any direct entry
196
- // with `?skuId=…`, `?q=…`, etc.): the apps-start canonical commerce
197
- // loaders read `props.skuId` to pre-select a variant. The framework
198
- // injects URL search params into `resolvedProps` at the commerce-loader
199
- // call site so loaders see them on direct navigation. CMS-configured
200
- // props win over URL params (URL is a fallback, not an override).
201
-
202
- describe("commerce loader auto-injects URL search params as props", () => {
203
- const KEY = "site/loaders/__test/queryInjectLoader";
204
-
205
- beforeEach(() => {
206
- clearCommerceLoaders();
207
- });
208
-
209
- afterEach(() => {
210
- clearCommerceLoaders();
211
- });
212
-
213
- it("populates props.skuId from ?skuId= when CMS does not set it", async () => {
214
- const calls: Array<Record<string, unknown>> = [];
215
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
216
- calls.push({ ...props });
217
- return null;
218
- });
219
-
220
- await resolveValue({ __resolveType: KEY, slug: "sabonete" }, undefined, {
221
- url: "https://store.com/produto/sabonete/p?skuId=12345&size=M",
222
- path: "/produto/sabonete/p",
223
- });
224
-
225
- expect(calls).toHaveLength(1);
226
- expect(calls[0]).toMatchObject({
227
- slug: "sabonete",
228
- skuId: "12345",
229
- size: "M",
230
- __pagePath: "/produto/sabonete/p",
231
- __pageUrl: "https://store.com/produto/sabonete/p?skuId=12345&size=M",
232
- });
233
- });
234
-
235
- it("does NOT override a CMS-configured prop with a URL param of the same name", async () => {
236
- const calls: Array<Record<string, unknown>> = [];
237
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
238
- calls.push({ ...props });
239
- return null;
240
- });
241
-
242
- await resolveValue({ __resolveType: KEY, skuId: "cms-locked-sku" }, undefined, {
243
- url: "https://store.com/p?skuId=url-value",
244
- path: "/p",
245
- });
246
-
247
- expect(calls[0]?.skuId).toBe("cms-locked-sku");
248
- });
249
-
250
- it("decodes URL-encoded values", async () => {
251
- const calls: Array<Record<string, unknown>> = [];
252
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
253
- calls.push({ ...props });
254
- return null;
255
- });
256
-
257
- await resolveValue({ __resolveType: KEY }, undefined, {
258
- url: "https://store.com/?q=preto%20azul",
259
- path: "/",
260
- });
261
-
262
- expect(calls[0]?.q).toBe("preto azul");
263
- });
264
-
265
- it("is a no-op when matcherCtx.url is missing", async () => {
266
- const calls: Array<Record<string, unknown>> = [];
267
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
268
- calls.push({ ...props });
269
- return null;
270
- });
271
-
272
- await resolveValue({ __resolveType: KEY, slug: "abc" }, undefined, {});
273
-
274
- expect(calls[0]).toEqual({ slug: "abc" });
275
- expect(calls[0]?.__pageUrl).toBeUndefined();
276
- });
277
-
278
- it("warns and skips injection when matcherCtx.url is malformed", async () => {
279
- const calls: Array<Record<string, unknown>> = [];
280
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
281
- calls.push({ ...props });
282
- return null;
283
- });
284
-
285
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
286
- try {
287
- await expect(
288
- resolveValue({ __resolveType: KEY, slug: "abc" }, undefined, {
289
- url: "not a url",
290
- path: "/",
291
- }),
292
- ).resolves.not.toThrow();
293
-
294
- // Loader still ran with __pageUrl set, but no query params were
295
- // injected and the warning surfaced the upstream bug.
296
- expect(calls[0]).toMatchObject({ slug: "abc", __pageUrl: "not a url" });
297
- expect(Object.keys(calls[0] ?? {}).sort()).toEqual(
298
- ["__pagePath", "__pageUrl", "slug"].sort(),
299
- );
300
- const warnings = warnSpy.mock.calls.map((c) => String(c[0]));
301
- expect(warnings.some((w) => w.includes("malformed matcherCtx.url"))).toBe(true);
302
- expect(warnings.some((w) => w.includes(KEY))).toBe(true);
303
- } finally {
304
- warnSpy.mockRestore();
305
- }
306
- });
307
-
308
- it("never auto-injects `page` — loaders that read __pageUrl apply their own index-base conversion (#391)", async () => {
309
- const calls: Array<Record<string, unknown>> = [];
310
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
311
- calls.push({ ...props });
312
- return null;
313
- });
314
-
315
- await resolveValue({ __resolveType: KEY }, undefined, {
316
- url: "https://store.com/?page=3",
317
- path: "/",
318
- });
319
-
320
- expect(calls[0]?.page).toBeUndefined();
321
- });
322
-
323
- it("coerces `count`/`pageOffset` to numbers instead of injecting raw strings", async () => {
324
- const calls: Array<Record<string, unknown>> = [];
325
- registerCommerceLoader(KEY, async (props: Record<string, unknown>) => {
326
- calls.push({ ...props });
327
- return null;
328
- });
329
-
330
- await resolveValue({ __resolveType: KEY }, undefined, {
331
- url: "https://store.com/?count=24&pageOffset=2",
332
- path: "/",
333
- });
334
-
335
- expect(calls[0]?.count).toBe(24);
336
- expect(calls[0]?.pageOffset).toBe(2);
337
- });
338
- });
339
-
340
- describe("commerce loader resolves legacy .ts-suffixed resolveType", () => {
341
- beforeEach(() => clearCommerceLoaders());
342
- afterEach(() => clearCommerceLoaders());
343
-
344
- it("matches a manifest key (no extension) against a decofile .ts resolveType", async () => {
345
- const calls: Array<Record<string, unknown>> = [];
346
- // Split-package manifests register WITHOUT the file extension.
347
- registerCommerceLoader("shopify/loaders/ProductDetailsPage", async (props) => {
348
- calls.push({ ...props });
349
- return null;
350
- });
351
-
352
- // Legacy (Fresh/Deno) decofile references it WITH the .ts extension.
353
- await resolveValue(
354
- { __resolveType: "shopify/loaders/ProductDetailsPage.ts", slug: "oversize-t-shirt-123" },
355
- undefined,
356
- {
357
- url: "https://store.com/products/oversize-t-shirt-123",
358
- path: "/products/oversize-t-shirt-123",
359
- },
360
- );
361
-
362
- expect(calls).toHaveLength(1);
363
- expect(calls[0]).toMatchObject({ slug: "oversize-t-shirt-123" });
364
- });
365
-
366
- it("prefers an exact .ts registration over the stripped fallback", async () => {
367
- const hits: string[] = [];
368
- registerCommerceLoader("shopify/loaders/X", async () => {
369
- hits.push("plain");
370
- return null;
371
- });
372
- registerCommerceLoader("shopify/loaders/X.ts", async () => {
373
- hits.push("dotts");
374
- return null;
375
- });
376
- await resolveValue({ __resolveType: "shopify/loaders/X.ts" }, undefined, {
377
- url: "https://s.com/",
378
- path: "/",
379
- });
380
- expect(hits).toEqual(["dotts"]);
381
- });
382
- });
383
-
384
- // ---------------------------------------------------------------------------
385
- // Async rendering: the admin (CMS Lazy ⚡ toggle) is the source of truth
386
- // ---------------------------------------------------------------------------
387
- //
388
- // Regression guard for issue #266: the framework must NOT defer a section by
389
- // position, and must NOT let code-level flags (`export const eager/neverDefer`)
390
- // override the editor's ⚡ choice. A section is deferred iff the editor wrapped
391
- // it in CMS Lazy/Deferred in the admin. The position threshold + code flags are
392
- // an explicit per-site opt-in that is OFF by default (foldThreshold = Infinity)
393
- // and never overrides the admin.
394
-
395
- describe("async rendering config defaults", () => {
396
- beforeEach(() => {
397
- // Reset the globalThis-backed config so each assertion is order-independent.
398
- (globalThis as any).__deco.asyncConfig = null;
399
- });
400
-
401
- it("DEFAULT_FOLD_THRESHOLD is Infinity (position-based deferral off)", () => {
402
- expect(DEFAULT_FOLD_THRESHOLD).toBe(Infinity);
403
- });
404
-
405
- it("setAsyncRenderingConfig() defaults to foldThreshold=Infinity, respectCmsLazy=true", () => {
406
- setAsyncRenderingConfig();
407
- const cfg = getAsyncRenderingConfig();
408
- expect(cfg).not.toBeNull();
409
- expect(cfg!.foldThreshold).toBe(Infinity);
410
- expect(cfg!.respectCmsLazy).toBe(true);
411
- expect(cfg!.botAwareSeo).toBe(false); // opt-in — off by default
412
- });
413
-
414
- it("preserves an explicit finite foldThreshold (opt-in)", () => {
415
- setAsyncRenderingConfig({ foldThreshold: 3 });
416
- expect(getAsyncRenderingConfig()!.foldThreshold).toBe(3);
417
- });
418
- });
419
-
420
- describe("shouldDeferSection — admin is the source of truth", () => {
421
- const mkCfg = (over: Partial<AsyncRenderingConfig> = {}): AsyncRenderingConfig => ({
422
- respectCmsLazy: true,
423
- foldThreshold: Infinity,
424
- alwaysEager: new Set(),
425
- botAwareSeo: false,
426
- ...over,
427
- });
428
-
429
- const lazyWrap = (inner: object) => ({
430
- __resolveType: WELL_KNOWN_TYPES.LAZY,
431
- section: inner,
432
- });
433
-
434
- it("defers a section the editor marked ⚡ (wrapped in CMS Lazy)", () => {
435
- const section = lazyWrap({ __resolveType: "site/sections/Hero.tsx" });
436
- expect(shouldDeferSection(section, 0, mkCfg(), false)).toBe(true);
437
- });
438
-
439
- it("renders a non-⚡ section eagerly regardless of position (default Infinity)", () => {
440
- const section = { __resolveType: "site/sections/SeoText.tsx" };
441
- // Position 5 used to auto-defer with the old foldThreshold=3 — now SSR.
442
- expect(shouldDeferSection(section, 5, mkCfg(), false)).toBe(false);
443
- });
444
-
445
- it("admin ⚡ overrides `export const eager` (code flag ignored)", () => {
446
- const key = "site/sections/EagerButLazy.tsx";
447
- registerEagerSections([key]);
448
- const section = lazyWrap({ __resolveType: key });
449
- // Even with a finite threshold where the eager flag would otherwise apply,
450
- // the editor's ⚡ wins → deferred.
451
- expect(shouldDeferSection(section, 0, mkCfg({ foldThreshold: 3 }), false)).toBe(true);
452
- });
453
-
454
- it("admin ⚡ overrides `export const neverDefer` (code flag ignored)", () => {
455
- const key = "site/sections/NeverDeferButLazy.tsx";
456
- registerNeverDeferSections([key]);
457
- const section = lazyWrap({ __resolveType: key });
458
- expect(shouldDeferSection(section, 0, mkCfg(), false)).toBe(true);
459
- });
460
-
461
- it("bots always get SSR, even for ⚡ sections (SEO)", () => {
462
- const section = lazyWrap({ __resolveType: "site/sections/Hero.tsx" });
463
- expect(shouldDeferSection(section, 0, mkCfg(), true)).toBe(false);
464
- });
465
-
466
- it("opt-in finite foldThreshold defers UNMARKED sections by position", () => {
467
- const section = { __resolveType: "site/sections/Shelf.tsx" };
468
- expect(shouldDeferSection(section, 5, mkCfg({ foldThreshold: 3 }), false)).toBe(true);
469
- expect(shouldDeferSection(section, 1, mkCfg({ foldThreshold: 3 }), false)).toBe(false);
470
- });
471
- });
472
-
473
- // ---------------------------------------------------------------------------
474
- // isEagerRequest — programmatic (non-navigation) fetches render eagerly
475
- // ---------------------------------------------------------------------------
476
- //
477
- // An AJAX `fetch()` (e.g. the PLP "Ver mais"/load-more pagination) reads the
478
- // static SSR HTML and never runs the client-side deferred-section resolution,
479
- // so a ⚡ deferred section would be invisible (skeleton only). Such requests —
480
- // identified by `Sec-Fetch-Dest: empty` — must render eagerly. Top-level browser
481
- // navigations (`document`) stay deferred; SPA navigations are excluded so
482
- // page-SEO commerce loaders stay off for humans (#286).
483
- describe("isEagerRequest — programmatic fetch detection", () => {
484
- const HUMAN_UA =
485
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36";
486
- const reqWith = (dest: string) =>
487
- new Request("https://store.com/escolar?page=2", {
488
- headers: { "user-agent": HUMAN_UA, "sec-fetch-dest": dest },
489
- });
490
-
491
- it("programmatic fetch (Sec-Fetch-Dest: empty) is eager", () => {
492
- expect(isEagerRequest({ userAgent: HUMAN_UA, request: reqWith("empty") })).toBe(true);
493
- });
494
-
495
- it("top-level navigation (Sec-Fetch-Dest: document) is NOT eager", () => {
496
- expect(isEagerRequest({ userAgent: HUMAN_UA, request: reqWith("document") })).toBe(false);
497
- });
498
-
499
- it("SPA navigation (empty + isClientNavigation) is NOT eager (preserves #286)", () => {
500
- expect(
501
- isEagerRequest({
502
- userAgent: HUMAN_UA,
503
- request: reqWith("empty"),
504
- isClientNavigation: true,
505
- }),
506
- ).toBe(false);
507
- });
508
-
509
- it("falls back to matcherCtx.headers when no Request is present", () => {
510
- expect(isEagerRequest({ userAgent: HUMAN_UA, headers: { "sec-fetch-dest": "empty" } })).toBe(
511
- true,
512
- );
513
- });
514
-
515
- it("a request with no Sec-Fetch headers stays deferred (no UA bot, no override)", () => {
516
- expect(isEagerRequest({ userAgent: HUMAN_UA, url: "https://store.com/escolar" })).toBe(false);
517
- });
518
- });
519
-
520
- // ---------------------------------------------------------------------------
521
- // Page SEO block — bot-aware commerce resolution
522
- // ---------------------------------------------------------------------------
523
- //
524
- // The page-level SEO block (e.g. `commerce/sections/Seo/SeoPLPV2.tsx` with
525
- // `jsonLD: { __resolveType: "PLP Loader" }`) is always eager. For humans the
526
- // commerce-loader-backed props must be skipped: resolving them blocks SSR on a
527
- // heavy upstream fetch and serializes the full product payload into HTML that a
528
- // human request never renders. Bots keep the full resolution for indexing.
529
- describe("resolvePageSeoBlock — bot-aware commerce SEO", () => {
530
- const KEY = "site/loaders/__test/plpSeoLoader";
531
- const HUMAN_UA =
532
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36";
533
- const BOT_UA = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
534
-
535
- const seoBlock = {
536
- __resolveType: "commerce/sections/Seo/SeoPLPV2.tsx",
537
- title: "Escolar",
538
- jsonLD: { __resolveType: KEY },
539
- };
540
-
541
- const rctx = (userAgent?: string) =>
542
- ({
543
- matcherCtx: { userAgent, url: "https://store.com/escolar", path: "/escolar" },
544
- memo: new Map(),
545
- depth: 0,
546
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
547
- }) as any;
548
-
549
- beforeEach(() => {
550
- clearCommerceLoaders();
551
- // Bot-aware SEO is opt-in — enable it for these cases.
552
- setAsyncRenderingConfig({ botAwareSeo: true });
553
- });
554
- afterEach(() => {
555
- clearCommerceLoaders();
556
- setAsyncRenderingConfig({ botAwareSeo: false });
557
- });
558
-
559
- it("flag OFF (default): humans still get the full SEO — no regression", async () => {
560
- setAsyncRenderingConfig({ botAwareSeo: false });
561
- let calls = 0;
562
- registerCommerceLoader(KEY, async () => {
563
- calls++;
564
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
565
- });
566
-
567
- const res = await resolvePageSeoBlock(seoBlock, rctx(HUMAN_UA));
568
-
569
- expect(calls).toBe(1); // loader runs for everyone when the flag is off
570
- expect(res?.props?.jsonLD).toMatchObject({ seo: { title: "Rich SEO title" } });
571
- });
572
-
573
- it("humans: skips the commerce loader and drops the commerce-backed prop", async () => {
574
- let calls = 0;
575
- registerCommerceLoader(KEY, async () => {
576
- calls++;
577
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
578
- });
579
-
580
- const res = await resolvePageSeoBlock(seoBlock, rctx(HUMAN_UA));
581
-
582
- expect(calls).toBe(0); // heavy upstream fetch never runs for humans
583
- expect(res?.props).toHaveProperty("title", "Escolar"); // literal props kept
584
- expect(res?.props).not.toHaveProperty("jsonLD"); // no product payload in HTML
585
- });
586
-
587
- it("bots: resolves the commerce loader and keeps the JSON-LD payload", async () => {
588
- let calls = 0;
589
- registerCommerceLoader(KEY, async () => {
590
- calls++;
591
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
592
- });
593
-
594
- const res = await resolvePageSeoBlock(seoBlock, rctx(BOT_UA));
595
-
596
- expect(calls).toBe(1);
597
- expect(res?.props?.jsonLD).toMatchObject({ seo: { title: "Rich SEO title" } });
598
- });
599
-
600
- it("?__deco_ssr=1 override: a human UA gets the full eager SEO (QA/audit)", async () => {
601
- let calls = 0;
602
- registerCommerceLoader(KEY, async () => {
603
- calls++;
604
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
605
- });
606
-
607
- const ctx = {
608
- matcherCtx: {
609
- userAgent: HUMAN_UA,
610
- url: "https://store.com/escolar?__deco_ssr=1",
611
- path: "/escolar",
612
- },
613
- memo: new Map(),
614
- depth: 0,
615
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
616
- } as any;
617
- const res = await resolvePageSeoBlock(seoBlock, ctx);
618
-
619
- expect(calls).toBe(1); // override forces the commerce loader to run
620
- expect(res?.props?.jsonLD).toMatchObject({ seo: { title: "Rich SEO title" } });
621
- });
622
- });
623
-
624
- describe("resolvePageSeoBlock — per-section ignoreStructuredData drives the fetch-skip", () => {
625
- const KEY = "site/loaders/__test/plpSeoLoader";
626
- const HUMAN_UA =
627
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36";
628
- const BOT_UA = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
629
-
630
- // PLP toggle lives under `configJsonLD`; PDP toggle is top-level.
631
- const plpBlock = {
632
- __resolveType: "commerce/sections/Seo/SeoPLPV2.tsx",
633
- title: "Escolar",
634
- jsonLD: { __resolveType: KEY },
635
- configJsonLD: { ignoreStructuredData: true },
636
- };
637
- const pdpBlock = {
638
- __resolveType: "commerce/sections/Seo/SeoPDPV2.tsx",
639
- title: "Produto",
640
- jsonLD: { __resolveType: KEY },
641
- ignoreStructuredData: true,
642
- };
643
-
644
- const rctx = (userAgent?: string) =>
645
- ({
646
- matcherCtx: { userAgent, url: "https://store.com/escolar", path: "/escolar" },
647
- memo: new Map(),
648
- depth: 0,
649
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
650
- }) as any;
651
-
652
- beforeEach(() => {
653
- clearCommerceLoaders();
654
- // The per-section toggle is the PRIMARY lever — it must work with the
655
- // site-wide botAwareSeo shortcut OFF.
656
- setAsyncRenderingConfig({ botAwareSeo: false });
657
- });
658
- afterEach(() => {
659
- clearCommerceLoaders();
660
- setAsyncRenderingConfig({ botAwareSeo: false });
661
- });
662
-
663
- it("humans: toggle skips the commerce loader (PLP configJsonLD)", async () => {
664
- let calls = 0;
665
- registerCommerceLoader(KEY, async () => {
666
- calls++;
667
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
668
- });
669
-
670
- const res = await resolvePageSeoBlock(plpBlock, rctx(HUMAN_UA));
671
-
672
- expect(calls).toBe(0); // no product fetch for humans
673
- expect(res?.props).toHaveProperty("title", "Escolar");
674
- expect(res?.props).not.toHaveProperty("jsonLD");
675
- });
676
-
677
- it("bots: toggle still resolves the commerce loader (PLP configJsonLD)", async () => {
678
- let calls = 0;
679
- registerCommerceLoader(KEY, async () => {
680
- calls++;
681
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
682
- });
683
-
684
- const res = await resolvePageSeoBlock(plpBlock, rctx(BOT_UA));
685
-
686
- expect(calls).toBe(1);
687
- expect(res?.props?.jsonLD).toMatchObject({ seo: { title: "Rich SEO title" } });
688
- });
689
-
690
- it("humans: top-level toggle skips the commerce loader (PDP)", async () => {
691
- let calls = 0;
692
- registerCommerceLoader(KEY, async () => {
693
- calls++;
694
- return { seo: { title: "Rich SEO title" }, product: { id: 1 } };
695
- });
696
-
697
- const res = await resolvePageSeoBlock(pdpBlock, rctx(HUMAN_UA));
698
-
699
- expect(calls).toBe(0);
700
- expect(res?.props).not.toHaveProperty("jsonLD");
701
- });
702
-
703
- it("toggle OFF: humans keep the full SEO even with botAwareSeo off (no regression)", async () => {
704
- let calls = 0;
705
- registerCommerceLoader(KEY, async () => {
706
- calls++;
707
- return { seo: { title: "Rich SEO title" }, products: [{ id: 1 }] };
708
- });
709
-
710
- const noToggle = {
711
- __resolveType: "commerce/sections/Seo/SeoPLPV2.tsx",
712
- title: "Escolar",
713
- jsonLD: { __resolveType: KEY },
714
- };
715
- const res = await resolvePageSeoBlock(noToggle, rctx(HUMAN_UA));
716
-
717
- expect(calls).toBe(1); // no toggle + no global flag → resolve for everyone
718
- expect(res?.props?.jsonLD).toMatchObject({ seo: { title: "Rich SEO title" } });
719
- });
720
- });
721
-
722
- // ---------------------------------------------------------------------------
723
- // resolveDecoPage — #277 client-side navigation disables deferral
724
- // ---------------------------------------------------------------------------
725
- //
726
- // When isClientNavigation is true, resolveDecoPageImpl sets useAsync = false so
727
- // shouldDeferSection is never called. All sections — including CMS ⚡-wrapped
728
- // ones — are resolved eagerly. This prevents client-nav from returning a
729
- // deferredSections array that loadDeferredSection would then try to resolve
730
- // without the per-request commerce app context.
731
-
732
- describe("extractSeoFromProps — commerce jsonLD structured data", () => {
733
- const plp = (overrides: Record<string, unknown> = {}) => ({
734
- "@type": "ProductListingPage",
735
- breadcrumb: {
736
- "@type": "BreadcrumbList",
737
- itemListElement: [
738
- { "@type": "ListItem", position: 1, item: "https://x.com/a" },
739
- { "@type": "ListItem", position: 2, item: "https://x.com/a/b" },
740
- ],
741
- },
742
- products: [{ "@type": "Product", name: "P1" }],
743
- seo: { title: "PLP Title", description: "PLP Desc" },
744
- ...overrides,
745
- });
746
-
747
- const pdp = (overrides: Record<string, unknown> = {}) => ({
748
- "@type": "ProductDetailsPage",
749
- breadcrumbList: {
750
- "@type": "BreadcrumbList",
751
- itemListElement: [
752
- { "@type": "ListItem", position: 1, item: "https://x.com/a" },
753
- { "@type": "ListItem", position: 2, item: "https://x.com/a/p" },
754
- ],
755
- },
756
- product: { "@type": "Product", name: "P1", image: [{ url: "https://x.com/p.jpg" }] },
757
- seo: { title: "PDP Title", description: "PDP Desc" },
758
- ...overrides,
759
- });
760
-
761
- it("derives title/description/canonical and emits the ItemList JSON-LD (PLP)", () => {
762
- // The casaevideo.com.br/eletroportateis regression: a page.seo pointing at
763
- // commerce/sections/Seo/SeoPLPV2.tsx resolved its jsonLD but emitted no
764
- // schema.org. There is no section component in start to run this transform.
765
- const seo = extractSeoFromProps({
766
- __resolveType: "commerce/sections/Seo/SeoPLPV2.tsx",
767
- jsonLD: plp(),
768
- });
769
- expect(seo.title).toBe("PLP Title");
770
- expect(seo.description).toBe("PLP Desc");
771
- // Highest-position breadcrumb item wins.
772
- expect(seo.canonical).toBe("https://x.com/a/b");
773
- expect(seo.noIndexing).toBe(false);
774
- expect(seo.jsonLDs).toHaveLength(1);
775
- expect(seo.jsonLDs?.[0]).toMatchObject({ "@type": "ProductListingPage" });
776
- });
777
-
778
- it("emits the product image and JSON-LD for a PDP", () => {
779
- const seo = extractSeoFromProps({
780
- __resolveType: "commerce/sections/Seo/SeoPDPV2.tsx",
781
- jsonLD: {
782
- "@type": "ProductDetailsPage",
783
- breadcrumbList: { "@type": "BreadcrumbList", itemListElement: [] },
784
- product: {
785
- "@type": "Product",
786
- name: "Widget",
787
- image: [{ url: "https://x.com/w.jpg" }],
788
- },
789
- seo: { title: "Widget", description: "A widget" },
790
- },
791
- });
792
- expect(seo.title).toBe("Widget");
793
- expect(seo.image).toBe("https://x.com/w.jpg");
794
- expect(seo.jsonLDs?.[0]).toMatchObject({ "@type": "ProductDetailsPage" });
795
- });
796
-
797
- it("lets manual override fields win over the jsonLD-derived ones", () => {
798
- const seo = extractSeoFromProps({
799
- jsonLD: plp(),
800
- title: "Manual Title",
801
- canonical: "https://x.com/manual",
802
- });
803
- expect(seo.title).toBe("Manual Title");
804
- expect(seo.canonical).toBe("https://x.com/manual");
805
- expect(seo.jsonLDs).toHaveLength(1);
806
- });
807
-
808
- it("omits structured data for humans when ignoreStructuredData is set", () => {
809
- const seo = extractSeoFromProps({
810
- jsonLD: plp(),
811
- configJsonLD: { ignoreStructuredData: true },
812
- });
813
- expect(seo.jsonLDs).toBeUndefined();
814
- // Metadata is still derived — only the ItemList is suppressed.
815
- expect(seo.title).toBe("PLP Title");
816
- });
817
-
818
- it("keeps structured data for bots even when ignoreStructuredData is set", () => {
819
- // Bot-aware: the toggle suppresses JSON-LD for humans only. Crawlers (and the
820
- // `?__deco_ssr=1` audit override, both surfaced via isEager) still get it.
821
- const seo = extractSeoFromProps(
822
- { jsonLD: plp(), configJsonLD: { ignoreStructuredData: true } },
823
- { isEager: true },
824
- );
825
- expect(seo.jsonLDs).toHaveLength(1);
826
- expect(seo.title).toBe("PLP Title");
827
- });
828
-
829
- it("omits structured data for bots too when the listing is empty", () => {
830
- // ignoreStructuredData is bot-aware, but an empty listing contributes no
831
- // ItemList regardless of bot status.
832
- const seo = extractSeoFromProps(
833
- { jsonLD: plp({ products: [] }), configJsonLD: { ignoreStructuredData: true } },
834
- { isEager: true },
835
- );
836
- expect(seo.jsonLDs).toBeUndefined();
837
- });
838
-
839
- it("keeps PDP structured data for bots with top-level ignoreStructuredData", () => {
840
- const seo = extractSeoFromProps(
841
- { jsonLD: pdp(), ignoreStructuredData: true },
842
- { isEager: true },
843
- );
844
- expect(seo.jsonLDs).toHaveLength(1);
845
- });
846
-
847
- it("marks an empty listing noIndexing and emits no ItemList", () => {
848
- const seo = extractSeoFromProps({ jsonLD: plp({ products: [] }) });
849
- expect(seo.noIndexing).toBe(true);
850
- expect(seo.jsonLDs).toBeUndefined();
851
- });
852
-
853
- it("does not touch a section that already emitted jsonLDs", () => {
854
- const existing = [{ "@type": "WebSite" }];
855
- const seo = extractSeoFromProps({ jsonLD: plp(), jsonLDs: existing });
856
- expect(seo.jsonLDs).toBe(existing);
857
- });
858
-
859
- it("removeVideos clones rather than mutating the source jsonLD", () => {
860
- const source = plp({
861
- products: [{ "@type": "Product", name: "P1", video: [{ "@type": "VideoObject" }] }],
862
- });
863
- const seo = extractSeoFromProps({
864
- jsonLD: source,
865
- configJsonLD: { removeVideos: true },
866
- });
867
- expect(seo.jsonLDs?.[0].products[0].video).toBeUndefined();
868
- // Source untouched — it may be shared with a body section.
869
- // biome-ignore lint/suspicious/noExplicitAny: test fixture
870
- expect((source.products[0] as any).video).toBeDefined();
871
- });
872
- });
873
-
874
- describe("resolveDecoPage — #277 client-side navigation disables deferral", () => {
875
- const lazySec = {
876
- __resolveType: WELL_KNOWN_TYPES.LAZY,
877
- section: { __resolveType: "site/sections/Hero.tsx" },
878
- };
879
-
880
- beforeEach(() => {
881
- // Enable async rendering so useAsync can be true for SSR requests.
882
- setAsyncRenderingConfig({ foldThreshold: Infinity, respectCmsLazy: true });
883
- // resolveSectionShallow unwraps the ⚡ and looks up the inner key via
884
- // getSection — return truthy so it produces a DeferredSection rather than
885
- // falling back to eager resolution.
886
- (getSection as ReturnType<typeof vi.fn>).mockReturnValue({ default: () => null });
887
- // Return a page with one CMS ⚡-wrapped section.
888
- (findPageByPath as ReturnType<typeof vi.fn>).mockReturnValue({
889
- page: { name: "test", sections: [lazySec] },
890
- params: {},
891
- blockKey: "test-page",
892
- });
893
- });
894
-
895
- afterEach(() => {
896
- (getSection as ReturnType<typeof vi.fn>).mockReset();
897
- (findPageByPath as ReturnType<typeof vi.fn>).mockReset();
898
- });
899
-
900
- it("SSR request defers a CMS ⚡ section", async () => {
901
- const result = await resolveDecoPage("/product/foo", {});
902
- expect(result?.deferredSections).toHaveLength(1);
903
- expect(result?.deferredSections[0].component).toBe("site/sections/Hero.tsx");
904
- });
905
-
906
- it("client-nav (isClientNavigation: true) resolves the ⚡ section eagerly — empty deferredSections", async () => {
907
- const result = await resolveDecoPage("/product/foo", { isClientNavigation: true });
908
- expect(result?.deferredSections).toHaveLength(0);
909
- });
910
- });
911
-
912
- // ---------------------------------------------------------------------------
913
- // Hidden array items — a `never`-gated multivariate wrapper must vanish from
914
- // the array, not survive as a `null` hole the section renders as empty.
915
- //
916
- // The admin (Studio) hides an array item by wrapping it in
917
- // `{ __resolveType: "website/flags/multivariate.ts", variants: [{ value, rule:
918
- // { __resolveType: "website/matchers/never.ts" } }] }`. `never` never matches,
919
- // so the wrapper resolves to "not present" and the item is dropped.
920
- // ---------------------------------------------------------------------------
921
-
922
- describe("hidden array items (never matcher)", () => {
923
- const NEVER = "website/matchers/never.ts";
924
- const ALWAYS = "website/matchers/always.ts";
925
- const MULTIVARIATE = "website/flags/multivariate.ts";
926
-
927
- const hidden = (value: unknown) => ({
928
- __resolveType: MULTIVARIATE,
929
- variants: [{ value, rule: { __resolveType: NEVER } }],
930
- });
931
-
932
- it("drops a hidden item from an array instead of leaving a null hole", async () => {
933
- const benefits = [
934
- { label: "Parcelamento" },
935
- { label: "Frete" },
936
- hidden({ label: "RetiradaLoja" }),
937
- hidden({ label: "EntregaExpressa" }),
938
- ];
939
-
940
- const result = (await resolveValue({ benefits }, undefined, {})) as {
941
- benefits: unknown[];
942
- };
943
-
944
- expect(result.benefits).toEqual([{ label: "Parcelamento" }, { label: "Frete" }]);
945
- // No null holes.
946
- expect(result.benefits).not.toContain(null);
947
- });
948
-
949
- it("keeps a visible (always-gated) item in the array", async () => {
950
- const benefits = [
951
- {
952
- __resolveType: MULTIVARIATE,
953
- variants: [{ value: { label: "Shown" }, rule: { __resolveType: ALWAYS } }],
954
- },
955
- hidden({ label: "Hidden" }),
956
- ];
957
-
958
- const result = (await resolveValue({ benefits }, undefined, {})) as {
959
- benefits: unknown[];
960
- };
961
-
962
- expect(result.benefits).toEqual([{ label: "Shown" }]);
963
- });
964
-
965
- it("preserves a legitimate null value in an array (matched variant resolving to null)", async () => {
966
- // A matched variant whose value is literally null stays — only the
967
- // no-match sentinel is filtered, not every null.
968
- const items = [
969
- {
970
- __resolveType: MULTIVARIATE,
971
- variants: [{ value: null, rule: { __resolveType: ALWAYS } }],
972
- },
973
- { label: "kept" },
974
- ];
975
-
976
- const result = (await resolveValue({ items }, undefined, {})) as { items: unknown[] };
977
-
978
- expect(result.items).toEqual([null, { label: "kept" }]);
979
- });
980
- });