@decocms/blocks 7.77.11 → 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.
@@ -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
  }
package/src/sdk/index.ts CHANGED
@@ -55,6 +55,7 @@ export {
55
55
  parseRedirectsCsv,
56
56
  type Redirect,
57
57
  type RedirectMap,
58
+ redirectLocation,
58
59
  registerRedirectResolveType,
59
60
  } from "./redirects";
60
61
  export { createServerTimings, type ServerTimings } from "./serverTimings";
@@ -0,0 +1,164 @@
1
+ /**
2
+ * `semantics: "legacy"` — the default. Pins what sites already on `@decocms/*`
3
+ * answer (case- and trailing-slash-insensitive match, 302 for temporary, query
4
+ * dropped), so turning on `"fresh"` for one site changes nothing for the
5
+ * others. The rows mirror real rules of two such storefronts.
6
+ *
7
+ * The only differences from before are rules that could never be served (a
8
+ * self-redirect loops forever) and a `Location` that `encodeURI` double-encoded.
9
+ */
10
+ import { afterEach, describe, expect, it } from "vitest";
11
+ import {
12
+ addRedirects,
13
+ getRedirectSemantics,
14
+ loadRedirects,
15
+ matchRedirect,
16
+ normalizePath,
17
+ parseRedirectsCsv,
18
+ redirectLocation,
19
+ selectExactRedirect,
20
+ setRedirectSemantics,
21
+ splitExactRedirects,
22
+ } from "./redirects";
23
+
24
+ afterEach(() => setRedirectSemantics("legacy"));
25
+
26
+ const block = (redirects: Array<Record<string, unknown>>) =>
27
+ loadRedirects({ r: { __resolveType: "website/loaders/redirects.ts", redirects } });
28
+
29
+ describe("default", () => {
30
+ it("is legacy", () => {
31
+ expect(getRedirectSemantics()).toBe("legacy");
32
+ });
33
+ });
34
+
35
+ describe("matching folds case and a trailing slash", () => {
36
+ const map = block([
37
+ { from: "/baixeoapp", to: "/baixe-o-app", type: "permanent" },
38
+ { from: "/Loja/Produto/123", to: "/kit-123", type: "permanent" },
39
+ ]);
40
+
41
+ it("matches any case and with or without a trailing slash", () => {
42
+ for (const path of ["/baixeoapp", "/BaixeoApp", "/baixeoapp/", "/BAIXEOAPP/"]) {
43
+ expect(matchRedirect(path, map)).toMatchObject({ to: "/baixe-o-app", status: 301 });
44
+ }
45
+ expect(matchRedirect("/loja/produto/123", map)?.to).toBe("/kit-123");
46
+ });
47
+
48
+ it("scans globs case-insensitively", () => {
49
+ const globs = block([{ from: "/PharolGranado/*", to: "/blog/*", type: "permanent" }]);
50
+ expect(matchRedirect("/pharolgranado/post-1", globs)?.to).toBe("/blog/post-1");
51
+ expect(matchRedirect("/PharolGranado/post-1", globs)?.to).toBe("/blog/post-1");
52
+ });
53
+
54
+ it("keys an absolute source by its pathname alone", () => {
55
+ expect(normalizePath("https://www.example.com/Old/?x=1")).toBe("/old");
56
+ const abs = block([{ from: "https://www.example.com/Old/?x=1", to: "/new" }]);
57
+ expect(matchRedirect("/old", abs)?.to).toBe("/new");
58
+ });
59
+
60
+ it("adds the leading slash a source was written without", () => {
61
+ const map = block([{ from: "camisa-roma", to: "/roupas/camisas", type: "permanent" }]);
62
+ expect(matchRedirect("/camisa-roma", map)?.to).toBe("/roupas/camisas");
63
+ });
64
+ });
65
+
66
+ describe("status", () => {
67
+ it("is 301 for permanent and 302 for anything else", () => {
68
+ const map = block([
69
+ { from: "/a", to: "/b", type: "permanent" },
70
+ { from: "/exemplo", to: "https://www.google.com", type: "temporary" },
71
+ { from: "/c", to: "/d" },
72
+ ]);
73
+ expect(matchRedirect("/a", map)?.status).toBe(301);
74
+ expect(matchRedirect("/exemplo", map)?.status).toBe(302);
75
+ expect(matchRedirect("/c", map)?.status).toBe(302);
76
+ });
77
+
78
+ it("is 302 for a CSV row that is not `permanent`/`301`", () => {
79
+ const map = loadRedirects({});
80
+ addRedirects(map, parseRedirectsCsv("from,to,type\n/a,/b,PERMANENT\n/c,/d,301\n/e,/f\n"));
81
+ expect(matchRedirect("/a", map)?.status).toBe(302);
82
+ expect(matchRedirect("/c", map)?.status).toBe(301);
83
+ expect(matchRedirect("/e", map)?.status).toBe(302);
84
+ });
85
+ });
86
+
87
+ describe("Location", () => {
88
+ it("drops the request's query string", () => {
89
+ expect(redirectLocation({ to: "/baixe-o-app" }, "?utm_source=a&gclid=x")).toBe("/baixe-o-app");
90
+ });
91
+
92
+ it("encodes what a header cannot carry, without double-encoding an escape", () => {
93
+ expect(redirectLocation({ to: "/promoção" })).toBe("/promo%C3%A7%C3%A3o");
94
+ expect(redirectLocation({ to: "/Regulamento%20Oficina.pdf" })).toBe(
95
+ "/Regulamento%20Oficina.pdf",
96
+ );
97
+ });
98
+ });
99
+
100
+ describe("rules that can never be served are dropped", () => {
101
+ it("drops a rule whose source equals its target as written", () => {
102
+ const map = block([{ from: "kit-de-sabonetes", to: "kit-de-sabonetes", type: "permanent" }]);
103
+ expect(matchRedirect("/kit-de-sabonetes", map)).toBeNull();
104
+ });
105
+
106
+ it("drops a rule that folding turns into a self-redirect", () => {
107
+ const map = block([
108
+ { from: "/Calca/p", to: "/calca/p", type: "permanent" },
109
+ { from: "/x/", to: "/x?utm_source=a", type: "permanent" },
110
+ ]);
111
+ expect(matchRedirect("/Calca/p", map)).toBeNull();
112
+ expect(matchRedirect("/calca/p", map)).toBeNull();
113
+ expect(matchRedirect("/x", map)).toBeNull();
114
+ });
115
+
116
+ it("keeps a rule to another host with the same path", () => {
117
+ const map = block([{ from: "/exemplo", to: "https://www.google.com/exemplo" }]);
118
+ expect(matchRedirect("/exemplo", map)?.to).toBe("https://www.google.com/exemplo");
119
+ });
120
+ });
121
+
122
+ describe("KV-keyed exact rules", () => {
123
+ it("serve the last rule written for a key, temporary as 302", () => {
124
+ const { exact } = splitExactRedirects({
125
+ r: {
126
+ __resolveType: "website/loaders/redirects.ts",
127
+ redirects: [
128
+ { from: "/meia/p", to: "/a" },
129
+ { from: "/Meia/p/", to: "/b" },
130
+ ],
131
+ },
132
+ });
133
+ expect(exact).toHaveLength(1);
134
+ const value = [...exact[0].shadowed!, exact[0]];
135
+ for (const path of ["/meia/p", "/MEIA/p", "/meia/p/"]) {
136
+ expect(selectExactRedirect(value, path)).toMatchObject({ to: "/b", status: 302 });
137
+ }
138
+ });
139
+
140
+ it("read a value written before `from` was stored", () => {
141
+ expect(selectExactRedirect({ to: "/new", status: 301 }, "/Old")).toMatchObject({
142
+ to: "/new",
143
+ status: 301,
144
+ });
145
+ });
146
+
147
+ it("never serve a folded self-redirect", () => {
148
+ expect(
149
+ selectExactRedirect({ from: "/Calca/p", to: "/calca/p", status: 301 }, "/calca/p"),
150
+ ).toBeNull();
151
+ });
152
+ });
153
+
154
+ describe("switching to fresh", () => {
155
+ it("changes only maps built afterwards", () => {
156
+ const legacy = block([{ from: "/Old", to: "/new" }]);
157
+ setRedirectSemantics("fresh");
158
+ const fresh = block([{ from: "/Old", to: "/new" }]);
159
+ expect(matchRedirect("/old", fresh)).toBeNull();
160
+ expect(matchRedirect("/Old", fresh)?.status).toBe(307);
161
+ setRedirectSemantics("legacy");
162
+ expect(matchRedirect("/old", legacy)?.status).toBe(302);
163
+ });
164
+ });