@decocms/blocks 7.71.6 → 8.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
@@ -1,109 +0,0 @@
1
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { loadDecofileDirectory } from "./loadDecofileDirectory";
6
-
7
- describe("loadDecofileDirectory", () => {
8
- let dir: string;
9
-
10
- beforeEach(() => {
11
- dir = mkdtempSync(join(tmpdir(), "decofile-test-"));
12
- });
13
-
14
- afterEach(() => {
15
- rmSync(dir, { recursive: true, force: true });
16
- });
17
-
18
- it("loads every .json file in the directory into a keyed map", async () => {
19
- writeFileSync(
20
- join(dir, "pages-home-123.json"),
21
- JSON.stringify({ __resolveType: "website/pages/Page.tsx", path: "/" }),
22
- );
23
- writeFileSync(
24
- join(dir, "Banner Grid - 01.json"),
25
- JSON.stringify({ __resolveType: "site/sections/BannerGrid.tsx" }),
26
- );
27
-
28
- const blocks = await loadDecofileDirectory(dir);
29
-
30
- expect(Object.keys(blocks)).toHaveLength(2);
31
- expect(blocks["pages-home-123"]).toEqual({
32
- __resolveType: "website/pages/Page.tsx",
33
- path: "/",
34
- });
35
- expect(blocks["Banner Grid - 01"]).toEqual({
36
- __resolveType: "site/sections/BannerGrid.tsx",
37
- });
38
- });
39
-
40
- it("ignores non-.json files", async () => {
41
- writeFileSync(join(dir, "readme.md"), "not a block");
42
- writeFileSync(join(dir, "a.json"), JSON.stringify({ x: 1 }));
43
-
44
- const blocks = await loadDecofileDirectory(dir);
45
- expect(Object.keys(blocks)).toEqual(["a"]);
46
- });
47
-
48
- it("throws with the filename on invalid JSON", async () => {
49
- writeFileSync(join(dir, "broken.json"), "{not valid json");
50
- await expect(loadDecofileDirectory(dir)).rejects.toThrow(/broken\.json/);
51
- });
52
-
53
- it("URL-decodes the filename stem once to produce the block key", async () => {
54
- // Classic deco stores blocks as encodeURIComponent(<block id>).json and
55
- // derives the id back with one decodeURIComponent (parseBlockId). Content
56
- // references saved blocks by the DECODED id ("Cores dos preços"), so the
57
- // map must be keyed by it or every such reference dangles.
58
- writeFileSync(
59
- join(dir, "Cores%20dos%20pre%C3%A7os.json"),
60
- JSON.stringify({ __resolveType: "site/loaders/priceColors.ts" }),
61
- );
62
- // Double-encoded page snapshot (deco.cx corpus shape): decodes ONCE.
63
- writeFileSync(
64
- join(dir, "pages-Acess%25C3%25B3rios-421596.json"),
65
- JSON.stringify({ __resolveType: "website/pages/Page.tsx" }),
66
- );
67
- // Encoded slash becomes a real slash in the id — ids are plain map keys.
68
- writeFileSync(join(dir, "collections%2Fblog%2Fauthors.json"), JSON.stringify({ authors: [] }));
69
-
70
- const blocks = await loadDecofileDirectory(dir);
71
-
72
- expect(blocks["Cores dos preços"]).toEqual({
73
- __resolveType: "site/loaders/priceColors.ts",
74
- });
75
- expect(blocks["pages-Acess%C3%B3rios-421596"]).toEqual({
76
- __resolveType: "website/pages/Page.tsx",
77
- });
78
- expect(blocks["collections/blog/authors"]).toEqual({ authors: [] });
79
- // The raw stems must NOT appear as keys.
80
- expect(blocks["Cores%20dos%20pre%C3%A7os"]).toBeUndefined();
81
- expect(blocks["pages-Acess%25C3%25B3rios-421596"]).toBeUndefined();
82
- });
83
-
84
- it("keeps a stem verbatim when it is not valid percent-encoding", async () => {
85
- // A lone % (e.g. a page literally named "50% off") throws in
86
- // decodeURIComponent — the stem is already the id, keep it.
87
- writeFileSync(join(dir, "pages-50% off-7.json"), JSON.stringify({ x: 1 }));
88
-
89
- const blocks = await loadDecofileDirectory(dir);
90
- expect(blocks["pages-50% off-7"]).toEqual({ x: 1 });
91
- });
92
-
93
- it("resolves decoded-key collisions deterministically (last sorted filename wins) and warns", async () => {
94
- writeFileSync(join(dir, "A B.json"), JSON.stringify({ raw: true }));
95
- writeFileSync(join(dir, "A%20B.json"), JSON.stringify({ encoded: true }));
96
-
97
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
98
- try {
99
- const blocks = await loadDecofileDirectory(dir);
100
- // Code-unit sort: " " (0x20) < "%" (0x25), so "A B.json" comes first
101
- // and "A%20B.json" is processed last — the encoded file wins.
102
- expect(blocks["A B"]).toEqual({ encoded: true });
103
- expect(Object.keys(blocks)).toHaveLength(1);
104
- expect(warn).toHaveBeenCalledWith(expect.stringContaining("A%20B.json"));
105
- } finally {
106
- warn.mockRestore();
107
- }
108
- });
109
- });
@@ -1,557 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { setDraftOverrideGetter } from "./draftSource";
3
- import {
4
- findPageByPath,
5
- getAllPages,
6
- loadBlocks,
7
- matchPath,
8
- setBlocks,
9
- withBlocksOverride,
10
- withDraftBlocks,
11
- } from "./loader";
12
-
13
- // Mirrors the behavior of the original deco-cx/deco Fresh framework
14
- // (runtime/features/render.tsx), which uses native `URLPattern` directly
15
- // and returns `result.pathname.groups`. Splats become numbered groups
16
- // ("0", "1", …) — there is no `_splat` rename.
17
-
18
- describe("matchPath", () => {
19
- describe("literal segments", () => {
20
- it("matches the root path", () => {
21
- expect(matchPath("/", "/")).toEqual({});
22
- });
23
-
24
- it("matches exact literal paths", () => {
25
- expect(matchPath("/foo/bar", "/foo/bar")).toEqual({});
26
- });
27
-
28
- it("returns null when literals differ", () => {
29
- expect(matchPath("/foo/bar", "/foo/baz")).toBeNull();
30
- });
31
-
32
- it("returns null when literal-only pattern does not span the whole URL", () => {
33
- expect(matchPath("/foo", "/foo/bar")).toBeNull();
34
- });
35
- });
36
-
37
- describe("named params (:slug)", () => {
38
- it("captures a single param", () => {
39
- expect(matchPath("/foo/:slug", "/foo/sabonete")).toEqual({
40
- slug: "sabonete",
41
- });
42
- });
43
-
44
- it("captures a param sandwiched between literals (VTEX PDP)", () => {
45
- expect(matchPath("/produto/:slug/p", "/produto/sabonete/p")).toEqual({
46
- slug: "sabonete",
47
- });
48
- });
49
-
50
- it("returns null when the URL is shorter than the pattern", () => {
51
- expect(matchPath("/foo/:slug", "/foo")).toBeNull();
52
- });
53
- });
54
-
55
- describe("trailing splat (*)", () => {
56
- it("captures the rest as group '0'", () => {
57
- expect(matchPath("/*", "/foo/bar")).toEqual({ "0": "foo/bar" });
58
- });
59
-
60
- it("matches root with empty splat", () => {
61
- expect(matchPath("/*", "/")).toEqual({ "0": "" });
62
- });
63
-
64
- it("captures the remainder under a prefix", () => {
65
- expect(matchPath("/foo/*", "/foo/bar/baz")).toEqual({ "0": "bar/baz" });
66
- });
67
-
68
- // Intentional bug fix: the previous custom matchPath accidentally matched
69
- // `/foo` against `/foo/*` due to its naive split("/") logic, which also
70
- // mis-handled trailing slashes. Native URLPattern (and the Fresh original)
71
- // require at least one segment after `/foo/`.
72
- it("does NOT match the bare prefix without a trailing segment", () => {
73
- expect(matchPath("/foo/*", "/foo")).toBeNull();
74
- });
75
- });
76
-
77
- describe("URLPattern optional groups ({...}?)", () => {
78
- // Patterns emitted by the deco-cx admin / present in production CMS data.
79
- // These are the cases that issue #213 documents as broken.
80
-
81
- it("matches with the optional group present", () => {
82
- expect(matchPath("/{acme/}?*", "/acme/perfumaria")).toEqual({
83
- "0": "perfumaria",
84
- });
85
- });
86
-
87
- it("matches with the optional group absent", () => {
88
- expect(matchPath("/{acme/}?*", "/perfumaria")).toEqual({
89
- "0": "perfumaria",
90
- });
91
- });
92
-
93
- it("matches root when optional prefix and splat collapse to empty", () => {
94
- expect(matchPath("/{acme/}?*", "/")).toEqual({ "0": "" });
95
- });
96
-
97
- it("matches with an optional prefix before a literal segment", () => {
98
- expect(
99
- matchPath(
100
- "/{acme/}?campanhas/*",
101
- "/acme/campanhas/destaques-2023",
102
- ),
103
- ).toEqual({
104
- "0": "destaques-2023",
105
- });
106
- expect(
107
- matchPath("/{acme/}?campanhas/*", "/campanhas/destaques-2023"),
108
- ).toEqual({
109
- "0": "destaques-2023",
110
- });
111
- });
112
-
113
- it("matches an optional suffix group present and absent", () => {
114
- expect(matchPath("/black-friday{/70-off}?", "/black-friday")).toEqual({});
115
- expect(
116
- matchPath("/black-friday{/70-off}?", "/black-friday/70-off"),
117
- ).toEqual({});
118
- });
119
- });
120
-
121
- describe("error tolerance", () => {
122
- it("returns null for malformed patterns instead of throwing", () => {
123
- expect(() => matchPath("/[invalid", "/anything")).not.toThrow();
124
- expect(matchPath("/[invalid", "/anything")).toBeNull();
125
- });
126
-
127
- // Node <= 22 has no URLPattern global. The malformed-pattern try/catch
128
- // above must NOT absorb that ReferenceError — a missing API has to fail
129
- // loudly at first match, not degrade into every CMS page silently
130
- // returning null (which renders as sitewide 404s).
131
- it("throws a descriptive error when the runtime lacks URLPattern", () => {
132
- const g = globalThis as { URLPattern?: unknown };
133
- const saved = g.URLPattern;
134
- // biome-ignore lint/performance/noDelete: restoring exact global state
135
- delete g.URLPattern;
136
- try {
137
- expect(() => matchPath("/foo/:slug", "/foo/bar")).toThrow(
138
- /URLPattern.*Node\.js >= 24/s,
139
- );
140
- } finally {
141
- if (saved !== undefined) g.URLPattern = saved;
142
- }
143
- });
144
- });
145
- });
146
-
147
- describe("findPageByPath specificity", () => {
148
- beforeEach(() => {
149
- setBlocks({
150
- "pages-bf": {
151
- name: "Black Friday",
152
- path: "/black-friday",
153
- sections: [],
154
- },
155
- "pages-bf-splat": {
156
- name: "Black Friday with optional suffix",
157
- path: "/black-friday{/70-off}?",
158
- sections: [],
159
- },
160
- "pages-pdp-plp": {
161
- name: "PDP & PLP",
162
- path: "/{acme/}?*",
163
- sections: [],
164
- },
165
- "pages-product": {
166
- name: "Product",
167
- path: "/produto/:slug/p",
168
- sections: [],
169
- },
170
- });
171
- });
172
-
173
- afterEach(() => {
174
- setBlocks({});
175
- });
176
-
177
- it("prefers an exact literal over an optional-group splat", () => {
178
- const match = findPageByPath("/black-friday");
179
- expect(match?.blockKey).toBe("pages-bf");
180
- });
181
-
182
- it("prefers the home page over an optional-group splat catch-all", () => {
183
- // Regression: /{acme/}?* matches "/" and was out-ranking the home
184
- // because the `{acme` segment counted as a param. The home block
185
- // is a literal-only `/` path and must always win.
186
- setBlocks({
187
- "pages-home": {
188
- name: "Home",
189
- path: "/",
190
- sections: [],
191
- },
192
- "pages-pdp-plp": {
193
- name: "PDP & PLP",
194
- path: "/{acme/}?*",
195
- sections: [],
196
- },
197
- });
198
- const match = findPageByPath("/");
199
- expect(match?.blockKey).toBe("pages-home");
200
- });
201
-
202
- it("falls back to the splat page for unknown URLs", () => {
203
- const match = findPageByPath("/perfumaria");
204
- expect(match?.blockKey).toBe("pages-pdp-plp");
205
- expect(match?.params).toEqual({ "0": "perfumaria" });
206
- });
207
-
208
- it("matches the param-bearing route ahead of the splat catch-all", () => {
209
- const match = findPageByPath("/produto/sabonete/p");
210
- expect(match?.blockKey).toBe("pages-product");
211
- expect(match?.params).toEqual({ slug: "sabonete" });
212
- });
213
-
214
- it("returns null when no page matches", () => {
215
- setBlocks({
216
- "pages-only-bf": {
217
- name: "Black Friday",
218
- path: "/black-friday",
219
- sections: [],
220
- },
221
- });
222
- expect(findPageByPath("/nope")).toBeNull();
223
- });
224
- });
225
-
226
- describe("findPageByPath page index cache", () => {
227
- afterEach(() => {
228
- setBlocks({});
229
- });
230
-
231
- it("serves a change published by setBlocks()", () => {
232
- setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
233
- expect(findPageByPath("/a")?.blockKey).toBe("pages-a");
234
-
235
- setBlocks({ "pages-b": { name: "B", path: "/b", sections: [] } });
236
- expect(findPageByPath("/a")).toBeNull();
237
- expect(findPageByPath("/b")?.blockKey).toBe("pages-b");
238
- });
239
-
240
- it("serves a change when setBlocks() gets the same object mutated in place", () => {
241
- const blocks: Record<string, unknown> = {
242
- "pages-a": { name: "A", path: "/a", sections: [] },
243
- };
244
- setBlocks(blocks);
245
- expect(findPageByPath("/a")?.blockKey).toBe("pages-a");
246
-
247
- blocks["pages-b"] = { name: "B", path: "/b", sections: [] };
248
- setBlocks(blocks);
249
- expect(findPageByPath("/b")?.blockKey).toBe("pages-b");
250
- });
251
-
252
- it("matches a page that only exists in the draft override", () => {
253
- setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
254
- const match = withBlocksOverride(
255
- { "pages-draft": { name: "Draft", path: "/draft", sections: [] } },
256
- () => findPageByPath("/draft"),
257
- );
258
- expect(match?.blockKey).toBe("pages-draft");
259
- expect(findPageByPath("/draft")).toBeNull();
260
- });
261
-
262
- it("matches a literal path through its percent-encoded spelling", () => {
263
- setBlocks({ "pages-promo": { name: "Promo", path: "/promoção", sections: [] } });
264
- expect(findPageByPath("/promo%C3%A7%C3%A3o")?.blockKey).toBe("pages-promo");
265
- expect(findPageByPath("/promoção")?.blockKey).toBe("pages-promo");
266
- });
267
-
268
- it("keeps literal matching case-sensitive and trailing-slash exact", () => {
269
- setBlocks({ "pages-lego": { name: "Lego", path: "/lego", sections: [] } });
270
- expect(findPageByPath("/lego")?.params).toEqual({});
271
- expect(findPageByPath("/LEGO")).toBeNull();
272
- expect(findPageByPath("/lego/")).toBeNull();
273
- });
274
-
275
- it("keeps the first of two pages with the same path", () => {
276
- setBlocks({
277
- "pages-first": { name: "First", path: "/same", sections: [] },
278
- "pages-second": { name: "Second", path: "/same", sections: [] },
279
- });
280
- expect(findPageByPath("/same")?.blockKey).toBe("pages-first");
281
- });
282
-
283
- it("skips a malformed pattern without throwing", () => {
284
- setBlocks({
285
- "pages-bad": { name: "Bad", path: "/(unclosed", sections: [] },
286
- "pages-ok": { name: "OK", path: "/ok", sections: [] },
287
- });
288
- expect(findPageByPath("/(unclosed")).toBeNull();
289
- expect(findPageByPath("/ok")?.blockKey).toBe("pages-ok");
290
- });
291
-
292
- it("invalidates the index for every module instance sharing the blocks", async () => {
293
- const blocks: Record<string, unknown> = {
294
- "pages-a": { name: "A", path: "/a", sections: [] },
295
- };
296
- setBlocks(blocks);
297
- vi.resetModules();
298
- const other = await import("./loader");
299
- expect(other.findPageByPath("/a")?.blockKey).toBe("pages-a");
300
-
301
- blocks["pages-b"] = { name: "B", path: "/b", sections: [] };
302
- setBlocks(blocks);
303
- expect(other.findPageByPath("/b")?.blockKey).toBe("pages-b");
304
- });
305
-
306
- it("keeps matchPath correct past its compiled-pattern cache bound", () => {
307
- for (let i = 0; i < 600; i++) {
308
- expect(matchPath(`/p${i}/:slug`, `/p${i}/x`)).toEqual({ slug: "x" });
309
- }
310
- expect(matchPath("/p0/:slug", "/p0/y")).toEqual({ slug: "y" });
311
- });
312
-
313
- it("returns a fresh array from getAllPages()", () => {
314
- setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
315
- getAllPages().pop();
316
- expect(getAllPages()).toHaveLength(1);
317
- });
318
-
319
- it("throws when the runtime lacks URLPattern, even for literal-only pages", () => {
320
- setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
321
- const g = globalThis as { URLPattern?: unknown };
322
- const saved = g.URLPattern;
323
- delete g.URLPattern;
324
- try {
325
- expect(() => findPageByPath("/a")).toThrow(/URLPattern.*Node\.js >= 24/s);
326
- } finally {
327
- if (saved !== undefined) g.URLPattern = saved;
328
- }
329
- });
330
- });
331
-
332
- describe("getAllPages — page blocks without the `pages-` prefix", () => {
333
- afterEach(() => {
334
- setBlocks({});
335
- });
336
-
337
- it("routes a page block whose key lacks the prefix", () => {
338
- // Decofiles carried over from Deco on Fresh hold page blocks under
339
- // arbitrary keys: renaming a page in the CMS renames its snapshot file,
340
- // and the key follows the filename. Fresh enumerated pages by
341
- // __resolveType, so these routed fine there.
342
- setBlocks({
343
- "plp-verao": {
344
- name: "Verão",
345
- path: "/verao",
346
- sections: [],
347
- __resolveType: "website/pages/Page.tsx",
348
- },
349
- });
350
-
351
- const match = findPageByPath("/verao");
352
- expect(match?.blockKey).toBe("plp-verao");
353
- });
354
-
355
- it("still ranks by path specificity across both key shapes", () => {
356
- setBlocks({
357
- "pages-catch-all": {
358
- name: "Catch all",
359
- path: "/*",
360
- sections: [],
361
- },
362
- "plp-inverno": {
363
- name: "Inverno",
364
- path: "/inverno",
365
- sections: [],
366
- __resolveType: "website/pages/Page.tsx",
367
- },
368
- });
369
-
370
- // The literal must win over the catch-all regardless of which one
371
- // carries the prefix.
372
- expect(findPageByPath("/inverno")?.blockKey).toBe("plp-inverno");
373
- expect(findPageByPath("/qualquer-outra")?.blockKey).toBe("pages-catch-all");
374
- });
375
-
376
- it("ignores non-page blocks that happen to carry a path", () => {
377
- // A loader block is not a page: no __resolveType match, no prefix.
378
- setBlocks({
379
- "some-loader": {
380
- name: "Not a page",
381
- path: "/not-a-page",
382
- sections: [],
383
- __resolveType: "site/loaders/whatever.ts",
384
- },
385
- });
386
-
387
- expect(findPageByPath("/not-a-page")).toBeNull();
388
- });
389
-
390
- it("keeps honouring the prefix when there is no __resolveType", () => {
391
- // The admin emits prefixed keys and does not always write a
392
- // __resolveType onto the snapshot — the fast path must still apply.
393
- setBlocks({
394
- "pages-sem-tipo": {
395
- name: "Sem tipo",
396
- path: "/sem-tipo",
397
- sections: [],
398
- },
399
- });
400
-
401
- expect(findPageByPath("/sem-tipo")?.blockKey).toBe("pages-sem-tipo");
402
- });
403
- });
404
-
405
- describe("loadBlocks draft override — key percent-encoding", () => {
406
- // The published decofile encodes special characters in block keys
407
- // (`pages-Home%20(principal)-1`); the Studio draft emits them raw
408
- // (`pages-Home (principal)-1`). Under snapshot semantics the draft REPLACES
409
- // the file-backed base wholesale, so an encoded/raw twin pair can never
410
- // coexist — these regression tests (from the merge era, when ~73% of
411
- // one production site's pages silently ignored drafts) now pin that property.
412
-
413
- afterEach(() => {
414
- setBlocks({});
415
- setDraftOverrideGetter(() => undefined);
416
- });
417
-
418
- it("replaces an encoded base key with its raw-encoded draft twin (home)", () => {
419
- setBlocks({
420
- "pages-Home%20(principal)-1": {
421
- name: "Home",
422
- path: "/",
423
- sections: [{ __resolveType: "published" }],
424
- },
425
- });
426
- setDraftOverrideGetter(() => ({
427
- "pages-Home (principal)-1": {
428
- name: "Home",
429
- path: "/",
430
- sections: [{ __resolveType: "draft" }],
431
- },
432
- }));
433
-
434
- // Exactly one page for "/" survives the merge — no encoded/raw duplicate.
435
- const pageBlocks = Object.keys(loadBlocks()).filter((k) =>
436
- k.startsWith("pages-"),
437
- );
438
- expect(pageBlocks).toHaveLength(1);
439
-
440
- const match = findPageByPath("/");
441
- const sections = match?.page.sections as Array<{ __resolveType: string }>;
442
- expect(sections[0].__resolveType).toBe("draft");
443
- });
444
-
445
- it("still replaces a plain (unescaped) base key", () => {
446
- setBlocks({
447
- "pages-disney-1": {
448
- name: "Disney",
449
- path: "/disney",
450
- sections: [{ __resolveType: "published" }],
451
- },
452
- });
453
- setDraftOverrideGetter(() => ({
454
- "pages-disney-1": {
455
- name: "Disney",
456
- path: "/disney",
457
- sections: [{ __resolveType: "draft" }],
458
- },
459
- }));
460
-
461
- const match = findPageByPath("/disney");
462
- const sections = match?.page.sections as Array<{ __resolveType: string }>;
463
- expect(sections[0].__resolveType).toBe("draft");
464
- });
465
-
466
- it("a null draft value removes the encoded base twin too", () => {
467
- setBlocks({
468
- "pages-Home%20(principal)-1": {
469
- name: "Home",
470
- path: "/",
471
- sections: [{ __resolveType: "published" }],
472
- },
473
- });
474
- setDraftOverrideGetter(() => ({
475
- "pages-Home (principal)-1": null,
476
- }));
477
-
478
- expect(findPageByPath("/")).toBeNull();
479
- const pageBlocks = Object.keys(loadBlocks()).filter((k) =>
480
- k.startsWith("pages-"),
481
- );
482
- expect(pageBlocks).toHaveLength(0);
483
- });
484
- });
485
-
486
- describe("loadBlocks draft snapshot semantics", () => {
487
- afterEach(() => {
488
- setBlocks({});
489
- setDraftOverrideGetter(() => undefined);
490
- });
491
-
492
- it("a block absent from the draft is deleted — the draft is the complete truth", () => {
493
- setBlocks({
494
- "pages-home-1": { name: "Home", path: "/", sections: [{}] },
495
- "pages-old-2": { name: "Old", path: "/old", sections: [{}] },
496
- });
497
- setDraftOverrideGetter(() => ({
498
- "pages-home-1": { name: "Home", path: "/", sections: [{}] },
499
- }));
500
-
501
- const keys = Object.keys(loadBlocks());
502
- expect(keys).toEqual(["pages-home-1"]);
503
- expect(findPageByPath("/old")).toBeNull();
504
- });
505
-
506
- it("synthetic CSV-redirect base blocks survive the snapshot", () => {
507
- setBlocks({
508
- "__csv_redirects__bulk.csv": { redirects: [{ from: "/a", to: "/b" }] },
509
- "pages-home-1": { name: "Home", path: "/", sections: [{}] },
510
- });
511
- setDraftOverrideGetter(() => ({
512
- "pages-home-1": { name: "Home", path: "/", sections: [{}] },
513
- }));
514
-
515
- const blocks = loadBlocks();
516
- expect(blocks["__csv_redirects__bulk.csv"]).toEqual({
517
- redirects: [{ from: "/a", to: "/b" }],
518
- });
519
- });
520
-
521
- it("withDraftBlocks applies snapshot semantics; withBlocksOverride keeps merge", () => {
522
- setBlocks({
523
- "pages-home-1": { name: "Home", path: "/", sections: [{}] },
524
- "pages-other-2": { name: "Other", path: "/other", sections: [{}] },
525
- });
526
- const draft = {
527
- "pages-home-1": { name: "Home", path: "/", sections: [{}] },
528
- };
529
-
530
- // Snapshot: the base-only block is gone.
531
- withDraftBlocks(draft, () => {
532
- expect(Object.keys(loadBlocks())).toEqual(["pages-home-1"]);
533
- });
534
-
535
- // Merge (admin partial payloads): the base-only block survives.
536
- withBlocksOverride(draft, () => {
537
- expect(Object.keys(loadBlocks()).sort()).toEqual([
538
- "pages-home-1",
539
- "pages-other-2",
540
- ]);
541
- });
542
- });
543
-
544
- it("an explicit scope wins over the ambient draft", () => {
545
- setBlocks({ "pages-home-1": { name: "Home", path: "/", sections: [{}] } });
546
- setDraftOverrideGetter(() => ({
547
- "pages-ambient-9": { name: "A", path: "/a", sections: [{}] },
548
- }));
549
-
550
- withDraftBlocks(
551
- { "pages-scoped-3": { name: "S", path: "/s", sections: [{}] } },
552
- () => {
553
- expect(Object.keys(loadBlocks())).toEqual(["pages-scoped-3"]);
554
- },
555
- );
556
- });
557
- });