@decocms/blocks 7.77.12 → 7.77.13

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/blocks",
3
- "version": "7.77.12",
3
+ "version": "7.77.13",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24"
@@ -18,7 +18,12 @@ const getSectionModule = (c: string) => modules[c];
18
18
  describe("serializeRenderJson", () => {
19
19
  it("applies a projection function to the props", () => {
20
20
  const out = serializeRenderJson(
21
- [{ component: "site/sections/Product/ProductDetails.tsx", props: { storeConfig: {}, page: 1 } }],
21
+ [
22
+ {
23
+ component: "site/sections/Product/ProductDetails.tsx",
24
+ props: { storeConfig: {}, page: 1 },
25
+ },
26
+ ],
22
27
  { getSectionModule },
23
28
  );
24
29
  expect(out).toEqual([
@@ -38,9 +43,12 @@ describe("serializeRenderJson", () => {
38
43
  });
39
44
 
40
45
  it("passes full props through when there is no renderJson export", () => {
41
- const out = serializeRenderJson([{ component: "site/sections/Footer/Footer.tsx", props: { y: 2 } }], {
42
- getSectionModule,
43
- });
46
+ const out = serializeRenderJson(
47
+ [{ component: "site/sections/Footer/Footer.tsx", props: { y: 2 } }],
48
+ {
49
+ getSectionModule,
50
+ },
51
+ );
44
52
  expect(out).toEqual([{ component: "site/sections/Footer/Footer.tsx", props: { y: 2 } }]);
45
53
  });
46
54
 
@@ -94,9 +102,12 @@ describe("serializeRenderJson", () => {
94
102
  });
95
103
 
96
104
  it("strips injected keys even when a projection rest-spreads them through", () => {
97
- const out = serializeRenderJson([{ component: "a", props: { keep: 1, __pageUrl: "u", device: "d" } }], {
98
- getSectionModule: () => ({ renderJson: (p: Record<string, unknown>) => p }), // identity passes __ through
99
- });
105
+ const out = serializeRenderJson(
106
+ [{ component: "a", props: { keep: 1, __pageUrl: "u", device: "d" } }],
107
+ {
108
+ getSectionModule: () => ({ renderJson: (p: Record<string, unknown>) => p }), // identity passes __ through
109
+ },
110
+ );
100
111
  expect(out).toEqual([{ component: "a", props: { keep: 1 } }]);
101
112
  });
102
113
 
@@ -120,15 +131,18 @@ describe("serializeRenderJson", () => {
120
131
  });
121
132
 
122
133
  it("does not emit a lazyUrl for a dropped deferred section", () => {
123
- const out = serializeRenderJson([{ component: "site/sections/Header.tsx", props: {}, index: 0 }], {
124
- getSectionModule,
125
- sectionsToIgnore: ["SeoV2.tsx"],
126
- deferred: [
127
- { component: "website/sections/Seo/SeoV2.tsx", index: 1 }, // suffix-dropped
128
- { component: "site/sections/Theme/Theme.tsx", index: 2 }, // renderJson === false
129
- ],
130
- lazyUrlFor: (ref) => `/p?renderJson&__lazy=${ref.index}`,
131
- });
134
+ const out = serializeRenderJson(
135
+ [{ component: "site/sections/Header.tsx", props: {}, index: 0 }],
136
+ {
137
+ getSectionModule,
138
+ sectionsToIgnore: ["SeoV2.tsx"],
139
+ deferred: [
140
+ { component: "website/sections/Seo/SeoV2.tsx", index: 1 }, // suffix-dropped
141
+ { component: "site/sections/Theme/Theme.tsx", index: 2 }, // renderJson === false
142
+ ],
143
+ lazyUrlFor: (ref) => `/p?renderJson&__lazy=${ref.index}`,
144
+ },
145
+ );
132
146
  expect(out).toEqual([{ component: "site/sections/Header.tsx", props: {} }]);
133
147
  });
134
148
  });
@@ -136,7 +150,9 @@ describe("serializeRenderJson", () => {
136
150
  describe("isSecretValue / stringifyWithoutSecrets", () => {
137
151
  it("detects a resolved Secret ({ get: fn }) and an unresolved secret block", () => {
138
152
  expect(isSecretValue({ get: () => "plaintext" })).toBe(true);
139
- expect(isSecretValue({ __resolveType: "website/loaders/secret.ts", encrypted: "x" })).toBe(true);
153
+ expect(isSecretValue({ __resolveType: "website/loaders/secret.ts", encrypted: "x" })).toBe(
154
+ true,
155
+ );
140
156
  });
141
157
 
142
158
  it("does not flag content that merely has a `get` method or other shapes", () => {
@@ -165,3 +181,160 @@ describe("isSecretValue / stringifyWithoutSecrets", () => {
165
181
  expect("block" in out).toBe(false);
166
182
  });
167
183
  });
184
+
185
+ describe("serializeRenderJson — nested sections", () => {
186
+ const nestedModules: Record<string, RenderJsonModule> = {
187
+ "site/sections/Tabs.tsx": {},
188
+ "site/sections/Banner.tsx": {
189
+ renderJson: ({ link, media, ...rest }: any) => ({ ...rest, path: link, image: media.mobile }),
190
+ },
191
+ "site/sections/Theme.tsx": { renderJson: false },
192
+ };
193
+ const getSectionModule = (c: string) => nestedModules[c];
194
+
195
+ it("projects a section nested in a plain object inside an array and writes it as { component, props }", () => {
196
+ const out = serializeRenderJson(
197
+ [
198
+ {
199
+ component: "site/sections/Tabs.tsx",
200
+ props: {
201
+ variants: [
202
+ {
203
+ name: "Linho",
204
+ section: {
205
+ Component: "site/sections/Banner.tsx",
206
+ props: {
207
+ link: "roupas/linho",
208
+ media: { desktop: "d.jpg", mobile: "m.jpg" },
209
+ device: "mobile",
210
+ },
211
+ },
212
+ },
213
+ ],
214
+ },
215
+ },
216
+ ],
217
+ { getSectionModule },
218
+ );
219
+ expect(out).toEqual([
220
+ {
221
+ component: "site/sections/Tabs.tsx",
222
+ props: {
223
+ variants: [
224
+ {
225
+ name: "Linho",
226
+ section: {
227
+ component: "site/sections/Banner.tsx",
228
+ props: { path: "roupas/linho", image: "m.jpg" },
229
+ },
230
+ },
231
+ ],
232
+ },
233
+ },
234
+ ]);
235
+ });
236
+
237
+ it("drops a nested section with renderJson === false: null in an object, removed from an array", () => {
238
+ const out = serializeRenderJson(
239
+ [
240
+ {
241
+ component: "site/sections/Tabs.tsx",
242
+ props: {
243
+ aside: { Component: "site/sections/Theme.tsx", props: {} },
244
+ sections: [
245
+ { Component: "site/sections/Theme.tsx", props: {} },
246
+ {
247
+ Component: "site/sections/Banner.tsx",
248
+ props: { link: "a", media: { mobile: "m" } },
249
+ },
250
+ ],
251
+ },
252
+ },
253
+ ],
254
+ { getSectionModule },
255
+ );
256
+ expect(out[0]).toEqual({
257
+ component: "site/sections/Tabs.tsx",
258
+ props: {
259
+ aside: null,
260
+ sections: [{ component: "site/sections/Banner.tsx", props: { path: "a", image: "m" } }],
261
+ },
262
+ });
263
+ });
264
+
265
+ it("recurses through the parent's projection output (wrapper inside wrapper)", () => {
266
+ const out = serializeRenderJson(
267
+ [
268
+ {
269
+ component: "site/sections/Tabs.tsx",
270
+ props: {
271
+ child: {
272
+ Component: "site/sections/Tabs.tsx",
273
+ props: {
274
+ grandchild: {
275
+ Component: "site/sections/Banner.tsx",
276
+ props: { link: "x", media: { mobile: "y" } },
277
+ },
278
+ },
279
+ },
280
+ },
281
+ },
282
+ ],
283
+ { getSectionModule },
284
+ );
285
+ expect((out[0] as any).props.child.props.grandchild).toEqual({
286
+ component: "site/sections/Banner.tsx",
287
+ props: { path: "x", image: "y" },
288
+ });
289
+ });
290
+
291
+ it("leaves props without nested sections untouched (same reference)", () => {
292
+ const props = { items: [{ id: 1 }], config: { Component: "ButtonStyle", color: "red" } };
293
+ const out = serializeRenderJson([{ component: "site/sections/Tabs.tsx", props }], {
294
+ getSectionModule,
295
+ });
296
+ expect((out[0] as any).props).toBe(props);
297
+ });
298
+ });
299
+
300
+ describe("serializeRenderJson — keepInjectedKeys", () => {
301
+ it("keeps a loader-owned injected key only for the sections that opt in", () => {
302
+ const out = serializeRenderJson(
303
+ [
304
+ {
305
+ component: "site/sections/Product/ProductDetails.tsx",
306
+ props: { device: "desktop", isMobile: false, page: 1 },
307
+ },
308
+ { component: "site/sections/Footer/Footer.tsx", props: { device: "desktop", y: 2 } },
309
+ ],
310
+ {
311
+ keepInjectedKeys: (c) => (c.endsWith("ProductDetails.tsx") ? ["device"] : undefined),
312
+ },
313
+ );
314
+ expect(out).toEqual([
315
+ {
316
+ component: "site/sections/Product/ProductDetails.tsx",
317
+ props: { device: "desktop", page: 1 },
318
+ },
319
+ { component: "site/sections/Footer/Footer.tsx", props: { y: 2 } },
320
+ ]);
321
+ });
322
+
323
+ it("applies to nested sections too", () => {
324
+ const out = serializeRenderJson(
325
+ [
326
+ {
327
+ component: "site/sections/Wrapper.tsx",
328
+ props: {
329
+ child: { Component: "site/sections/Rich.tsx", props: { device: "mobile", a: 1 } },
330
+ },
331
+ },
332
+ ],
333
+ { keepInjectedKeys: (c) => (c === "site/sections/Rich.tsx" ? ["device"] : undefined) },
334
+ );
335
+ expect((out[0] as any).props.child).toEqual({
336
+ component: "site/sections/Rich.tsx",
337
+ props: { device: "mobile", a: 1 },
338
+ });
339
+ });
340
+ });
@@ -21,9 +21,9 @@
21
21
  * serializer has no lazy-placeholder (`{ component, lazyUrl }`) branch — the
22
22
  * mobile app receives the whole page in one request.
23
23
  *
24
- * ponytail: no nested section-in-section recursion (composite/layout sections).
25
- * deepOmit handles trimming within a single section's data; add a recursive walk
26
- * here if a composite section must project its child sections.
24
+ * Nested sections (a composite/layout section holding `{ Component, props }`
25
+ * anywhere in its props) are serialized recursively with their own `renderJson`
26
+ * contract and emitted as `{ component, props }` — see `walkValue`.
27
27
  */
28
28
 
29
29
  // deno-lint-ignore-style any: a projection accepts the section's own resolved props.
@@ -74,6 +74,16 @@ export interface SerializeOptions {
74
74
  deferred?: DeferredRef[];
75
75
  /** Builds the lazy-fetch URL for a deferred section. Required when `deferred` is set. */
76
76
  lazyUrlFor?: (ref: DeferredRef) => string;
77
+ /**
78
+ * Request-derived keys (`device`, `isMobile`, `currentSearchParam`) are
79
+ * stripped from every section because the `withDevice`/`withMobile`/
80
+ * `withSearchParam` mixins inject them. A section whose own loader returns
81
+ * one of them as CONTENT (Fresh: `device: ctx.device`, which production's
82
+ * `?renderJson` carries) can keep it: return the keys to preserve for that
83
+ * resolveType. Opt-in per section — the ETag of a kept key varies per
84
+ * device, which is correct for content that does.
85
+ */
86
+ keepInjectedKeys?: (component: string) => readonly string[] | undefined;
77
87
  }
78
88
 
79
89
  /**
@@ -96,9 +106,13 @@ export interface SerializeOptions {
96
106
  */
97
107
  const FRAMEWORK_INJECTED_KEYS = new Set(["device", "isMobile", "currentSearchParam"]);
98
108
 
99
- function stripFrameworkKeys(props: Record<string, unknown>): Record<string, unknown> {
109
+ function stripFrameworkKeys(
110
+ props: Record<string, unknown>,
111
+ keep?: readonly string[],
112
+ ): Record<string, unknown> {
100
113
  let out: Record<string, unknown> | null = null;
101
114
  for (const k of Object.keys(props)) {
115
+ if (keep?.includes(k)) continue;
102
116
  if (k.startsWith("__") || FRAMEWORK_INJECTED_KEYS.has(k)) {
103
117
  out ??= { ...props };
104
118
  delete out[k];
@@ -107,28 +121,113 @@ function stripFrameworkKeys(props: Record<string, unknown>): Record<string, unkn
107
121
  return out ?? props;
108
122
  }
109
123
 
124
+ /**
125
+ * A nested section as the resolver represents it inside another section's
126
+ * props (`normalizeNestedSections` in resolve.ts): `{ Component, props }`.
127
+ * The capital `Component` is the renderer's convention; the JSON contract
128
+ * uses `component`, like the top level and like Fresh's serializer.
129
+ */
130
+ function isNestedSection(
131
+ value: unknown,
132
+ ): value is { Component: string; props: Record<string, unknown> } {
133
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
134
+ const o = value as Record<string, unknown>;
135
+ return (
136
+ typeof o.Component === "string" &&
137
+ !!o.props &&
138
+ typeof o.props === "object" &&
139
+ !Array.isArray(o.props)
140
+ );
141
+ }
142
+
143
+ interface Projector {
144
+ isDropped: (component: string) => boolean;
145
+ project: (component: string, props: Record<string, unknown>) => Record<string, unknown>;
146
+ }
147
+
148
+ /**
149
+ * Walks a section's (already projected) props and serializes every nested
150
+ * section the same way the top level is: its own `renderJson` projection,
151
+ * framework keys stripped, `{ component, props }`. Mirrors deco-runtime's
152
+ * `walkValue` (runtime/routes/serialize-section.ts): a dropped nested
153
+ * section (`renderJson === false` / ignored) becomes `null` in an object and
154
+ * is removed from an array, so consumers iterate a dense list. Returns the
155
+ * same reference when nothing changed.
156
+ */
157
+ function walkValue(value: unknown, p: Projector): unknown {
158
+ if (Array.isArray(value)) {
159
+ let changed = false;
160
+ const out: unknown[] = [];
161
+ for (const v of value) {
162
+ if (isNestedSection(v)) {
163
+ changed = true;
164
+ if (!p.isDropped(v.Component)) out.push(serializeNested(v, p));
165
+ continue;
166
+ }
167
+ const next = walkValue(v, p);
168
+ if (next !== v) changed = true;
169
+ out.push(next);
170
+ }
171
+ return changed ? out : value;
172
+ }
173
+ if (value && typeof value === "object") {
174
+ if (isNestedSection(value)) {
175
+ return p.isDropped(value.Component) ? null : serializeNested(value, p);
176
+ }
177
+ let out: Record<string, unknown> | null = null;
178
+ for (const [k, v] of Object.entries(value)) {
179
+ const next = walkValue(v, p);
180
+ if (next !== v) {
181
+ out ??= { ...(value as Record<string, unknown>) };
182
+ out[k] = next;
183
+ }
184
+ }
185
+ return out ?? value;
186
+ }
187
+ return value;
188
+ }
189
+
190
+ function serializeNested(
191
+ section: { Component: string; props: Record<string, unknown> },
192
+ p: Projector,
193
+ ): { component: string; props: Record<string, unknown> } {
194
+ return { component: section.Component, props: p.project(section.Component, section.props) };
195
+ }
196
+
110
197
  export function serializeRenderJson(
111
198
  sections: SerializableSection[],
112
199
  opts: SerializeOptions = {},
113
200
  ): SerializedSection[] {
114
- const ignore = (opts.sectionsToIgnore ?? [])
115
- .map((s) => s.trim())
116
- .filter((s) => s.length > 0);
201
+ const ignore = (opts.sectionsToIgnore ?? []).map((s) => s.trim()).filter((s) => s.length > 0);
117
202
 
118
203
  const renderJsonOf = (component: string): RenderJson | undefined =>
119
204
  opts.getSectionModule?.(component)?.renderJson;
120
205
 
121
206
  const isDropped = (component: string): boolean =>
122
- ignore.some((suffix) => component.endsWith(suffix)) ||
123
- renderJsonOf(component) === false;
207
+ ignore.some((suffix) => component.endsWith(suffix)) || renderJsonOf(component) === false;
208
+
209
+ // Projection → strip → recurse into nested sections. The strip runs after
210
+ // the projection so a rest-spread cannot leak an injected key; the walk
211
+ // runs last so nested sections inside the projected output are serialized
212
+ // with their own contract too.
213
+ const projector: Projector = {
214
+ isDropped,
215
+ project: (component, props) => {
216
+ const rj = renderJsonOf(component);
217
+ const projected = typeof rj === "function" ? rj(props) : props;
218
+ const stripped = stripFrameworkKeys(projected, opts.keepInjectedKeys?.(component));
219
+ return walkValue(stripped, projector) as Record<string, unknown>;
220
+ },
221
+ };
124
222
 
125
223
  const eager = sections
126
224
  .filter((s) => !isDropped(s.component))
127
225
  .map((section) => {
128
- const rj = renderJsonOf(section.component);
129
- const projected = typeof rj === "function" ? rj(section.props ?? {}) : section.props ?? {};
130
- const props = stripFrameworkKeys(projected);
131
- return { index: section.index, out: { component: section.component, props } as SerializedSection };
226
+ const props = projector.project(section.component, section.props ?? {});
227
+ return {
228
+ index: section.index,
229
+ out: { component: section.component, props } as SerializedSection,
230
+ };
132
231
  });
133
232
 
134
233
  // No deferred sections → preserve input order (backward compatible).
@@ -459,6 +459,27 @@ describe("runSingleSectionLoader — nested section recursion", () => {
459
459
  expect(grandchild.props).toMatchObject({ tag: "deep", deep: true });
460
460
  });
461
461
 
462
+ it("runs the loader of a section nested inside a plain object in an array (variants[].section)", async () => {
463
+ const banner = vi.fn(async (props: any) => ({ ...props, ranBanner: true }));
464
+ registerSectionLoader("site/sections/Banner.tsx", banner);
465
+
466
+ const parent = makeSection("site/sections/Tabs.tsx", {
467
+ variants: [
468
+ { name: "Linho", section: { Component: "site/sections/Banner.tsx", props: { id: 1 } } },
469
+ { name: "Sem seção" },
470
+ ],
471
+ layout: { aside: { Component: "site/sections/Banner.tsx", props: { id: 2 } } },
472
+ });
473
+
474
+ const result = await runSingleSectionLoader(parent, new Request("https://store.com/vitrine"));
475
+
476
+ expect(banner).toHaveBeenCalledTimes(2);
477
+ const props = result.props as any;
478
+ expect(props.variants[0].section.props).toMatchObject({ id: 1, ranBanner: true });
479
+ expect(props.variants[1]).toEqual({ name: "Sem seção" });
480
+ expect(props.layout.aside.props).toMatchObject({ id: 2, ranBanner: true });
481
+ });
482
+
462
483
  it("ignores nested objects that do not look like sections", async () => {
463
484
  const loader = vi.fn(async (props: Record<string, unknown>) => props);
464
485
  registerSectionLoader("site/sections/Leaf.tsx", loader);
@@ -501,6 +522,103 @@ describe("runSingleSectionLoader — nested section recursion", () => {
501
522
  });
502
523
  });
503
524
 
525
+ describe("runSingleSectionLoader — nested walk cost and cycles", () => {
526
+ // A PLP-sized payload: hundreds of products, each a deep plain-object tree,
527
+ // and not a single nested section anywhere.
528
+ const bigLeafProps = () => ({
529
+ products: Array.from({ length: 200 }, (_, i) => ({
530
+ productID: String(i),
531
+ offers: { offers: [{ price: i, seller: "1", priceSpecification: [{ price: i }] }] },
532
+ image: [{ url: `https://img/${i}.jpg`, additionalProperty: [{ name: "a", value: "b" }] }],
533
+ isVariantOf: { hasVariant: [{ sku: `${i}-1` }, { sku: `${i}-2` }] },
534
+ })),
535
+ });
536
+
537
+ it("walks props without a nested section synchronously — no Promise.all, same reference", async () => {
538
+ const out = bigLeafProps();
539
+ registerSectionLoader("site/sections/PLP.tsx", async () => out);
540
+
541
+ const all = vi.spyOn(Promise, "all");
542
+ try {
543
+ const result = await runSingleSectionLoader(
544
+ makeSection("site/sections/PLP.tsx"),
545
+ new Request("https://store.com/c"),
546
+ );
547
+ expect(result.props).toBe(out);
548
+ expect(all).not.toHaveBeenCalled();
549
+ } finally {
550
+ all.mockRestore();
551
+ }
552
+ });
553
+
554
+ it("only descends into the subtree that holds a nested section", async () => {
555
+ const banner = vi.fn(async (props: any) => ({ ...props, ranBanner: true }));
556
+ registerSectionLoader("site/sections/Banner.tsx", banner);
557
+ const big = bigLeafProps();
558
+ const parent = makeSection("site/sections/Wrapper.tsx", {
559
+ ...big,
560
+ aside: { Component: "site/sections/Banner.tsx", props: { id: 1 } },
561
+ });
562
+
563
+ const result = await runSingleSectionLoader(parent, new Request("https://store.com/"));
564
+
565
+ expect(banner).toHaveBeenCalledTimes(1);
566
+ const props = result.props as any;
567
+ expect(props.aside.props).toMatchObject({ id: 1, ranBanner: true });
568
+ // Untouched subtrees keep identity.
569
+ expect(props.products).toBe(big.products);
570
+ });
571
+
572
+ it("survives cyclic loader output — the page resolves and the section keeps its props", async () => {
573
+ const cyclic: Record<string, unknown> = { name: "a" };
574
+ cyclic.self = cyclic;
575
+ const list: unknown[] = [cyclic];
576
+ list.push(list);
577
+ const out = { cyclic, list };
578
+ registerSectionLoader("site/sections/Cyclic.tsx", async () => out);
579
+ registerSectionLoader("site/sections/Other.tsx", async (props) => ({ ...props, ok: true }));
580
+
581
+ const results = await runSectionLoaders(
582
+ [makeSection("site/sections/Cyclic.tsx"), makeSection("site/sections/Other.tsx")],
583
+ new Request("https://store.com/"),
584
+ );
585
+
586
+ expect(results[0].props).toBe(out);
587
+ expect((results[1].props as any).ok).toBe(true);
588
+ });
589
+
590
+ it("enriches a subtree shared by two props in both places", async () => {
591
+ const banner = vi.fn(async (props: any) => ({ ...props, ranBanner: true }));
592
+ registerSectionLoader("site/sections/Banner.tsx", banner);
593
+ const shared = { section: { Component: "site/sections/Banner.tsx", props: { id: 1 } } };
594
+ const parent = makeSection("site/sections/Tabs.tsx", { a: shared, b: [shared] });
595
+
596
+ const result = await runSingleSectionLoader(parent, new Request("https://store.com/"));
597
+
598
+ const props = result.props as any;
599
+ expect(props.a.section.props).toMatchObject({ id: 1, ranBanner: true });
600
+ expect(props.b[0].section.props).toMatchObject({ id: 1, ranBanner: true });
601
+ });
602
+
603
+ it("runs a nested section reachable through a cycle exactly once", async () => {
604
+ const banner = vi.fn(async (props: any) => ({ ...props, ranBanner: true }));
605
+ registerSectionLoader("site/sections/Banner.tsx", banner);
606
+ const layout: Record<string, unknown> = {
607
+ aside: { Component: "site/sections/Banner.tsx", props: { id: 1 } },
608
+ };
609
+ layout.parent = layout;
610
+ registerSectionLoader("site/sections/Cyclic.tsx", async () => ({ layout }));
611
+
612
+ const result = await runSingleSectionLoader(
613
+ makeSection("site/sections/Cyclic.tsx"),
614
+ new Request("https://store.com/"),
615
+ );
616
+
617
+ expect(banner).toHaveBeenCalledTimes(1);
618
+ expect((result.props as any).layout.aside.props).toMatchObject({ id: 1, ranBanner: true });
619
+ });
620
+ });
621
+
504
622
  describe("runSectionLoaders — batch span", () => {
505
623
  afterEach(() => {
506
624
  configureTracer({ startSpan: () => ({ end: () => {} }) });
@@ -568,9 +568,18 @@ async function runSingleSectionLoaderImpl(
568
568
  // the same reference (no allocation, no extra work).
569
569
  const props = result.props as Record<string, unknown> | undefined;
570
570
  if (props && typeof props === "object") {
571
- const enrichedProps = await enrichNestedSections(props, request);
572
- if (enrichedProps !== props) {
573
- return { ...result, props: enrichedProps };
571
+ try {
572
+ const enrichedProps = await enrichNestedSections(props, request);
573
+ if (enrichedProps !== props) {
574
+ return { ...result, props: enrichedProps };
575
+ }
576
+ } catch (error) {
577
+ // The walk runs on arbitrary loader output; a failure here must not
578
+ // reject the whole runSectionLoaders batch — keep the section's props.
579
+ console.error(
580
+ `[SectionLoader] Error enriching nested sections of "${section.component}":`,
581
+ error,
582
+ );
574
583
  }
575
584
  }
576
585
  return result;
@@ -604,11 +613,19 @@ function isNestedSection(
604
613
 
605
614
  /**
606
615
  * Walk a props object and run section loaders for any nested sections.
607
- * Handles direct child sections AND arrays of sections (e.g.
608
- * `sections: Section[]`, `slides: Slide[]`).
616
+ * Handles direct child sections, arrays of sections (`sections: Section[]`,
617
+ * `slides: Slide[]`) AND sections nested inside plain objects/arrays at any
618
+ * depth (`variants: [{ name, section: Section }]`, `layout: { aside: Section }`)
619
+ * — the resolver resolves a section reference wherever the CMS placed it, so
620
+ * the loader walk has to find it there too; a section reachable only through
621
+ * a plain object used to be skipped and rendered with its raw CMS props.
609
622
  *
610
- * Returns the same reference if nothing changed — so leaf sections (the
611
- * vast majority) incur zero allocation overhead.
623
+ * Two passes: a synchronous scan marks every object/array whose subtree
624
+ * holds a nested section, and the walk descends only into marked nodes.
625
+ * Props without any nested section (the vast majority — including multi-MB
626
+ * PLP payloads) cost one sync traversal and return the same reference, with
627
+ * no Promise allocated. Cyclic loader output terminates instead of
628
+ * overflowing the stack (see `markSectionSubtrees` and `walkNested`).
612
629
  *
613
630
  * Concurrency: all nested loader calls run in parallel via Promise.all.
614
631
  */
@@ -616,71 +633,113 @@ async function enrichNestedSections(
616
633
  props: Record<string, unknown>,
617
634
  request: Request,
618
635
  ): Promise<Record<string, unknown>> {
619
- type Pending = {
620
- key: string;
621
- index?: number;
622
- promise: Promise<ResolvedSection>;
623
- };
624
- const pending: Pending[] = [];
625
-
626
- for (const [key, value] of Object.entries(props)) {
627
- if (isNestedSection(value)) {
628
- pending.push({
629
- key,
630
- promise: runSingleSectionLoader(
631
- {
632
- component: value.Component,
633
- props: value.props,
634
- key: value.Component,
635
- } as ResolvedSection,
636
- request,
637
- ),
638
- });
639
- continue;
640
- }
641
-
642
- if (Array.isArray(value)) {
643
- for (let i = 0; i < value.length; i++) {
644
- const item = value[i];
645
- if (isNestedSection(item)) {
646
- pending.push({
647
- key,
648
- index: i,
649
- promise: runSingleSectionLoader(
650
- {
651
- component: item.Component,
652
- props: item.props,
653
- key: item.Component,
654
- } as ResolvedSection,
655
- request,
656
- ),
657
- });
658
- }
659
- }
660
- }
661
- }
636
+ const scan: SectionScan = { marked: new WeakSet(), deep: new WeakMap() };
637
+ if (!markSectionSubtrees(props, scan, 0)) return props;
638
+ return (await walkNested(props, request, scan.marked, new WeakMap())) as Record<string, unknown>;
639
+ }
662
640
 
663
- if (pending.length === 0) return props;
641
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
642
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
643
+ const proto = Object.getPrototypeOf(value);
644
+ return proto === Object.prototype || proto === null;
645
+ }
664
646
 
665
- const results = await Promise.all(pending.map((p) => p.promise));
666
- const updated: Record<string, unknown> = { ...props };
647
+ /**
648
+ * Real props are a few dozen levels deep at most. Above this depth the scan
649
+ * keeps no per-node bookkeeping (a visited map costs 2-3x the bare traversal
650
+ * on a PLP payload); a cycle necessarily recurses past it, and from there on
651
+ * every node is memoized, so the scan terminates.
652
+ */
653
+ const CYCLE_GUARD_DEPTH = 32;
667
654
 
668
- for (let i = 0; i < pending.length; i++) {
669
- const { key, index } = pending[i];
670
- const enriched = results[i];
671
- const nestedValue = { Component: enriched.component, props: enriched.props };
655
+ interface SectionScan {
656
+ /** Arrays/plain objects whose subtree holds a nested section. */
657
+ marked: WeakSet<object>;
658
+ /** Scan results for nodes reached below CYCLE_GUARD_DEPTH. */
659
+ deep: WeakMap<object, boolean>;
660
+ }
672
661
 
673
- if (index != null) {
674
- // Array item — clone the array on first mutation for this key
675
- const current = updated[key];
676
- if (current === props[key]) {
677
- updated[key] = [...(current as unknown[])];
678
- }
679
- (updated[key] as unknown[])[index] = nestedValue;
680
- } else {
681
- updated[key] = nestedValue;
662
+ /**
663
+ * Sync scan: whether `value` is or contains a nested section, adding every
664
+ * array/plain object on the path to one to `scan.marked`. Does not look
665
+ * inside a nested section's props — its own runSingleSectionLoader call
666
+ * walks those after its loader runs. Below CYCLE_GUARD_DEPTH a node is
667
+ * recorded as `false` on entry, so a cycle back to it reports false; the
668
+ * first visit already covers that subtree.
669
+ */
670
+ function markSectionSubtrees(value: unknown, scan: SectionScan, depth: number): boolean {
671
+ if (isNestedSection(value)) return true;
672
+ const isArray = Array.isArray(value);
673
+ if (!isArray && !isPlainObject(value)) return false;
674
+ const node = value as object;
675
+ const guarded = depth >= CYCLE_GUARD_DEPTH;
676
+ if (guarded) {
677
+ const known = scan.deep.get(node);
678
+ if (known !== undefined) return known;
679
+ scan.deep.set(node, false);
680
+ }
681
+ let found = false;
682
+ if (isArray) {
683
+ const arr = value as unknown[];
684
+ for (let i = 0; i < arr.length; i++) {
685
+ if (markSectionSubtrees(arr[i], scan, depth + 1)) found = true;
686
+ }
687
+ } else {
688
+ const obj = value as Record<string, unknown>;
689
+ for (const key in obj) {
690
+ if (markSectionSubtrees(obj[key], scan, depth + 1)) found = true;
682
691
  }
683
692
  }
693
+ if (found) {
694
+ scan.marked.add(node);
695
+ if (guarded) scan.deep.set(node, true);
696
+ }
697
+ return found;
698
+ }
684
699
 
685
- return updated;
700
+ /**
701
+ * Returns the enriched value — a Promise only for nodes on a path to a
702
+ * nested section. The descent itself is synchronous (depth-first), so a
703
+ * `null` memo entry means "an ancestor still being walked": a cycle, which
704
+ * keeps its original reference. A subtree shared by several props is
705
+ * enriched once and the result reused at every position.
706
+ */
707
+ function walkNested(
708
+ value: unknown,
709
+ request: Request,
710
+ marked: WeakSet<object>,
711
+ memo: WeakMap<object, Promise<unknown> | null>,
712
+ ): unknown {
713
+ if (isNestedSection(value)) {
714
+ return runSingleSectionLoader(
715
+ { component: value.Component, props: value.props, key: value.Component } as ResolvedSection,
716
+ request,
717
+ ).then((enriched) => ({ Component: enriched.component, props: enriched.props }));
718
+ }
719
+ if (!value || typeof value !== "object" || !marked.has(value)) return value;
720
+ const known = memo.get(value);
721
+ if (known !== undefined) return known ?? value;
722
+ memo.set(value, null);
723
+ let pending: Promise<unknown>;
724
+ if (Array.isArray(value)) {
725
+ pending = Promise.all(value.map((item) => walkNested(item, request, marked, memo))).then(
726
+ (next) => (next.some((item, i) => item !== value[i]) ? next : value),
727
+ );
728
+ } else {
729
+ const entries = Object.entries(value);
730
+ pending = Promise.all(entries.map(([, v]) => walkNested(v, request, marked, memo))).then(
731
+ (next) => {
732
+ let out: Record<string, unknown> | null = null;
733
+ for (let i = 0; i < entries.length; i++) {
734
+ if (next[i] !== entries[i][1]) {
735
+ out ??= { ...value };
736
+ out[entries[i][0]] = next[i];
737
+ }
738
+ }
739
+ return out ?? value;
740
+ },
741
+ );
742
+ }
743
+ memo.set(value, pending);
744
+ return pending;
686
745
  }