@decocms/blocks 7.72.0 → 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,335 +0,0 @@
1
- /**
2
- * Phase 2 (D-11) coverage for the metric surface — canonical label set,
3
- * cache_layer, commerce_request_duration_ms. The Phase 1 logger/trace
4
- * tests live under `src/sdk/logger.test.ts` and `src/sdk/otel.test.ts`;
5
- * this file focuses on the middleware-level helpers.
6
- */
7
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
8
- import {
9
- configureMeter,
10
- DURATION_BUCKET_BOUNDARIES_SECONDS,
11
- METRIC_METADATA,
12
- type MeterAdapter,
13
- MetricNames,
14
- normalizePath,
15
- recordCacheMetric,
16
- recordCommerceMetric,
17
- recordRequestMetric,
18
- statusClassFor,
19
- } from "./observability";
20
-
21
- interface Counter {
22
- name: string;
23
- value: number;
24
- labels?: Record<string, unknown>;
25
- }
26
- interface Histogram {
27
- name: string;
28
- value: number;
29
- labels?: Record<string, unknown>;
30
- }
31
-
32
- function captureMeter(): {
33
- adapter: MeterAdapter;
34
- counters: Counter[];
35
- histograms: Histogram[];
36
- } {
37
- const counters: Counter[] = [];
38
- const histograms: Histogram[] = [];
39
- const adapter: MeterAdapter = {
40
- counterInc(name, value, labels) {
41
- counters.push({ name, value: value ?? 1, labels });
42
- },
43
- histogramRecord(name, value, labels) {
44
- histograms.push({ name, value, labels });
45
- },
46
- };
47
- return { adapter, counters, histograms };
48
- }
49
-
50
- describe("statusClassFor", () => {
51
- it("maps 2xx / 3xx / 4xx / 5xx to canonical class labels", () => {
52
- expect(statusClassFor(200)).toBe("2xx");
53
- expect(statusClassFor(204)).toBe("2xx");
54
- expect(statusClassFor(301)).toBe("3xx");
55
- expect(statusClassFor(404)).toBe("4xx");
56
- expect(statusClassFor(500)).toBe("5xx");
57
- expect(statusClassFor(503)).toBe("5xx");
58
- });
59
-
60
- it("returns 'unknown' for out-of-range / NaN / non-numeric inputs", () => {
61
- expect(statusClassFor(-1)).toBe("unknown");
62
- expect(statusClassFor(99)).toBe("unknown");
63
- expect(statusClassFor(600)).toBe("unknown");
64
- expect(statusClassFor(Number.NaN)).toBe("unknown");
65
- expect(statusClassFor(Infinity)).toBe("unknown");
66
- });
67
- });
68
-
69
- describe("recordRequestMetric — canonical labels (D-11)", () => {
70
- afterEach(() => {
71
- // Reset meter so other tests start clean.
72
- configureMeter({ counterInc: () => {} });
73
- });
74
-
75
- it("stamps method + route_pattern + status + status_class by default", () => {
76
- const { adapter, counters, histograms } = captureMeter();
77
- configureMeter(adapter);
78
-
79
- recordRequestMetric("GET", "/products/abc123/p", 200, 42);
80
-
81
- // Canonical OTel HTTP server metric is histogram-only; the count
82
- // dimension is derived from the histogram's bucket counts at query
83
- // time, so we no longer emit a parallel `_total` counter.
84
- expect(counters).toHaveLength(0);
85
- expect(histograms).toHaveLength(1);
86
- expect(histograms[0]?.name).toBe(MetricNames.HTTP_SERVER_REQUEST_DURATION);
87
- expect(histograms[0]?.value).toBe(0.042); // seconds (semconv)
88
- expect(histograms[0]?.labels).toMatchObject({
89
- "http.request.method": "GET",
90
- // Default normalization: dynamic segments collapsed.
91
- "http.route": "/products/:slug/p",
92
- "http.response.status_code": 200,
93
- "deco.http.status_class": "2xx",
94
- });
95
- });
96
-
97
- it("prefers caller-supplied route_pattern over normalized path", () => {
98
- const { adapter, histograms } = captureMeter();
99
- configureMeter(adapter);
100
-
101
- recordRequestMetric("GET", "/anything/random/123", 200, 5, {
102
- route_pattern: "/_products/$slug/p",
103
- });
104
-
105
- expect(histograms[0]?.labels?.["http.route"]).toBe("/_products/$slug/p");
106
- });
107
-
108
- it("tags 5xx requests with status_class=5xx for downstream error filtering", () => {
109
- const { adapter, histograms } = captureMeter();
110
- configureMeter(adapter);
111
-
112
- recordRequestMetric("POST", "/checkout", 503, 120);
113
-
114
- expect(histograms[0]?.labels?.["deco.http.status_class"]).toBe("5xx");
115
- expect(histograms[0]?.labels?.["http.response.status_code"]).toBe(503);
116
- });
117
-
118
- it("propagates optional labels (outcome, cache_decision, cache_layer, region, extra)", () => {
119
- const { adapter, histograms } = captureMeter();
120
- configureMeter(adapter);
121
-
122
- recordRequestMetric("GET", "/", 200, 10, {
123
- outcome: "ok",
124
- cache_decision: "STALE-HIT",
125
- cache_layer: "edge",
126
- region: "GRU",
127
- extra: { ab_variant: "B" },
128
- });
129
-
130
- expect(histograms[0]?.labels).toMatchObject({
131
- "deco.http.outcome": "ok",
132
- "deco.cache.decision": "STALE-HIT",
133
- "deco.cache.layer": "edge",
134
- "deco.http.region": "GRU",
135
- ab_variant: "B",
136
- });
137
- });
138
-
139
- it("is a no-op when no meter is configured", () => {
140
- // We can't easily prove a no-op other than verifying no throw —
141
- // safer than calling configureMeter(null), which would mask real
142
- // bugs. The previous test's `afterEach` reset already gives us a
143
- // bare meter; this test confirms the call is benign.
144
- expect(() => recordRequestMetric("GET", "/", 200, 1)).not.toThrow();
145
- });
146
- });
147
-
148
- describe("recordCacheMetric — cache_layer label", () => {
149
- beforeEach(() => {
150
- configureMeter({ counterInc: () => {} });
151
- });
152
-
153
- it("stamps profile + decision + layer when all are provided", () => {
154
- const { adapter, counters } = captureMeter();
155
- configureMeter(adapter);
156
-
157
- recordCacheMetric(true, "product", "HIT", "edge");
158
-
159
- expect(counters).toHaveLength(1);
160
- expect(counters[0]?.name).toBe(MetricNames.CACHE_REQUESTS);
161
- expect(counters[0]?.labels).toMatchObject({
162
- "profile": "product",
163
- "status": "HIT",
164
- "layer": "edge",
165
- });
166
- });
167
-
168
- it("records status=MISS when hit=false", () => {
169
- const { adapter, counters } = captureMeter();
170
- configureMeter(adapter);
171
-
172
- recordCacheMetric(false, "search", "MISS", "edge");
173
-
174
- expect(counters[0]?.name).toBe(MetricNames.CACHE_REQUESTS);
175
- expect(counters[0]?.labels?.["status"]).toBe("MISS");
176
- });
177
-
178
- it("supports the legacy 3-arg signature for backward compat", () => {
179
- const { adapter, counters } = captureMeter();
180
- configureMeter(adapter);
181
-
182
- recordCacheMetric(true, "static");
183
-
184
- expect(counters[0]?.labels).toEqual({
185
- "status": "HIT",
186
- "profile": "static",
187
- });
188
- });
189
-
190
- it("distinguishes cachedLoader vs edge vs swr layers", () => {
191
- const { adapter, counters } = captureMeter();
192
- configureMeter(adapter);
193
-
194
- recordCacheMetric(true, "loader-x", "HIT", "cachedLoader");
195
- recordCacheMetric(true, undefined, "HIT", "swr", "vtex");
196
-
197
- expect(counters[0]?.labels?.["layer"]).toBe("cachedLoader");
198
- expect(counters[1]?.labels?.["layer"]).toBe("swr");
199
- });
200
-
201
- it("keeps provider (swr backend) on a separate label from profile (edge page-type)", () => {
202
- const { adapter, counters } = captureMeter();
203
- configureMeter(adapter);
204
-
205
- // edge: profile carries the page-type; no provider.
206
- recordCacheMetric(true, "product", "HIT", "edge");
207
- // swr: provider carries the backend; profile left unset so a
208
- // `sum by (profile)` panel never blends page-types with backend names.
209
- recordCacheMetric(true, undefined, "HIT", "swr", "magento");
210
-
211
- expect(counters[0]?.labels?.["profile"]).toBe("product");
212
- expect(counters[0]?.labels?.["provider"]).toBeUndefined();
213
- expect(counters[1]?.labels?.["profile"]).toBeUndefined();
214
- expect(counters[1]?.labels?.["provider"]).toBe("magento");
215
- });
216
- });
217
-
218
- describe("recordCommerceMetric (D-11)", () => {
219
- beforeEach(() => {
220
- configureMeter({ counterInc: () => {} });
221
- });
222
-
223
- it("emits http.client.request.duration with provider + operation labels", () => {
224
- const { adapter, histograms } = captureMeter();
225
- configureMeter(adapter);
226
-
227
- recordCommerceMetric(123, {
228
- provider: "vtex",
229
- operation: "intelligent-search.product_search",
230
- status_class: "2xx",
231
- });
232
-
233
- expect(histograms).toHaveLength(1);
234
- expect(histograms[0]?.name).toBe(MetricNames.HTTP_CLIENT_REQUEST_DURATION);
235
- expect(histograms[0]?.value).toBe(0.123); // seconds (semconv)
236
- expect(histograms[0]?.labels).toMatchObject({
237
- provider: "vtex",
238
- operation: "intelligent-search.product_search",
239
- status_class: "2xx",
240
- });
241
- });
242
-
243
- it("includes the cached boolean when provided", () => {
244
- const { adapter, histograms } = captureMeter();
245
- configureMeter(adapter);
246
-
247
- recordCommerceMetric(5, {
248
- provider: "shopify",
249
- operation: "graphql.cart_query",
250
- cached: true,
251
- });
252
-
253
- expect(histograms[0]?.labels?.cached).toBe(true);
254
- });
255
-
256
- it("is a no-op when no meter is configured", () => {
257
- expect(() =>
258
- recordCommerceMetric(1, { provider: "vtex", operation: "test" }),
259
- ).not.toThrow();
260
- });
261
- });
262
-
263
- /**
264
- * Guards the unit/bucket agreement. Durations are recorded in seconds, but the
265
- * OTel SDK's default explicit buckets are milliseconds
266
- * (`[0, 5, 10, 25, 50, 75, 100, 250, 500, 1000]`). A duration metric that ships
267
- * without `boundaries` inherits those defaults and files ~100% of real traffic
268
- * into the first bucket, which silently destroys every quantile computed from
269
- * it. These assertions exist so that regression fails here instead of in a
270
- * dashboard six months later.
271
- */
272
- describe("METRIC_METADATA duration buckets", () => {
273
- it("declares second-scale boundaries for every metric measured in seconds", () => {
274
- const secondValued = Object.entries(METRIC_METADATA).filter(
275
- ([, meta]) => meta.unit === "s",
276
- );
277
-
278
- expect(secondValued.length).toBeGreaterThan(0);
279
-
280
- for (const [name, meta] of secondValued) {
281
- expect(meta.boundaries, `${name} must declare boundaries`).toBeDefined();
282
- // A millisecond-scaled bucket set starts at 5; a second-scaled one starts
283
- // well below 1. This is the exact mistake being guarded against.
284
- expect(meta.boundaries![0], `${name} boundaries look like milliseconds`)
285
- .toBeLessThan(1);
286
- }
287
- });
288
-
289
- it("keeps boundaries sorted ascending and free of duplicates", () => {
290
- const b = DURATION_BUCKET_BOUNDARIES_SECONDS;
291
- expect([...b]).toEqual([...new Set(b)]);
292
- expect([...b]).toEqual([...b].sort((x, y) => x - y));
293
- });
294
-
295
- it("covers the latency range real traffic falls in", () => {
296
- // Observed production averages sat between 0.14s and 0.49s, with a tail
297
- // past 10s on uncached loader paths. Buckets must resolve both ends.
298
- expect(DURATION_BUCKET_BOUNDARIES_SECONDS.some((x) => x <= 0.05)).toBe(true);
299
- expect(DURATION_BUCKET_BOUNDARIES_SECONDS.some((x) => x >= 10)).toBe(true);
300
- });
301
- });
302
-
303
- /**
304
- * `http.route` is the highest-cardinality risk on the highest-volume metric.
305
- * These cases are the real paths measured on production when the label reached
306
- * 20,714 distinct values across 6 tenants.
307
- */
308
- describe("normalizePath cardinality", () => {
309
- it("collapses CMS content slugs", () => {
310
- expect(normalizePath("/mochila-de-couro")).toBe("/:slug");
311
- expect(normalizePath("/moveis/quarto-infantil")).toBe("/moveis/:slug");
312
- expect(normalizePath("/acme/eau-de-toilette-spritz-100ml")).toBe("/acme/:slug");
313
- expect(normalizePath("/moveis/quarto-adulto/cabeceiras-mesa-de-cabeceiras")).toBe(
314
- "/moveis/:slug/:slug",
315
- );
316
- });
317
-
318
- it("leaves bounded framework and API routes intact", () => {
319
- expect(normalizePath("/")).toBe("/");
320
- expect(normalizePath("/api/sessions")).toBe("/api/sessions");
321
- expect(normalizePath("/deco/invoke/magento/loaders/features")).toBe(
322
- "/deco/invoke/magento/loaders/features",
323
- );
324
- });
325
-
326
- it("keeps dotfile segments readable", () => {
327
- expect(normalizePath("/.well-known/passkey-endpoints")).toBe("/.well-known/:slug");
328
- });
329
-
330
- it("still collapses ids and product pages", () => {
331
- expect(normalizePath("/produto/12345")).toBe("/produto/:id");
332
- expect(normalizePath("/a/deadbeefcafe")).toBe("/a/:id");
333
- expect(normalizePath("/some-product/p")).toBe("/:slug/p");
334
- });
335
- });
@@ -1,147 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- createSectionValidator,
4
- validateDeferredSectionInput,
5
- } from "./validateSection";
6
-
7
- describe("validateDeferredSectionInput", () => {
8
- it("accepts valid input", () => {
9
- const result = validateDeferredSectionInput({
10
- component: "site/sections/ProductShelf.tsx",
11
- rawProps: { title: "Best Sellers" },
12
- pagePath: "/",
13
- });
14
- expect(result.component).toBe("site/sections/ProductShelf.tsx");
15
- expect(result.rawProps).toEqual({ title: "Best Sellers" });
16
- expect(result.pagePath).toBe("/");
17
- expect(result.pageUrl).toBeUndefined();
18
- });
19
-
20
- it("accepts input with optional pageUrl", () => {
21
- const result = validateDeferredSectionInput({
22
- component: "site/sections/Hero.tsx",
23
- rawProps: {},
24
- pagePath: "/home",
25
- pageUrl: "https://store.com/home?ref=nav",
26
- });
27
- expect(result.pageUrl).toBe("https://store.com/home?ref=nav");
28
- });
29
-
30
- it("accepts input with index for SPA navigation ordering", () => {
31
- const result = validateDeferredSectionInput({
32
- component: "site/sections/Shelf.tsx",
33
- rawProps: {},
34
- pagePath: "/",
35
- index: 5,
36
- });
37
- expect(result.index).toBe(5);
38
- });
39
-
40
- it("index is undefined when not provided", () => {
41
- const result = validateDeferredSectionInput({
42
- component: "site/sections/Shelf.tsx",
43
- rawProps: {},
44
- pagePath: "/",
45
- });
46
- expect(result.index).toBeUndefined();
47
- });
48
-
49
- it("throws on null input", () => {
50
- expect(() => validateDeferredSectionInput(null)).toThrow("Expected an object");
51
- });
52
-
53
- it("throws on undefined input", () => {
54
- expect(() => validateDeferredSectionInput(undefined)).toThrow("Expected an object");
55
- });
56
-
57
- it("throws on string input", () => {
58
- expect(() => validateDeferredSectionInput("nope")).toThrow("Expected an object");
59
- });
60
-
61
- it("throws when component is missing", () => {
62
- expect(() =>
63
- validateDeferredSectionInput({ rawProps: {}, pagePath: "/" }),
64
- ).toThrow("component");
65
- });
66
-
67
- it("throws when component is not a string", () => {
68
- expect(() =>
69
- validateDeferredSectionInput({ component: 123, rawProps: {}, pagePath: "/" }),
70
- ).toThrow("component");
71
- });
72
-
73
- it("throws when rawProps is missing", () => {
74
- expect(() =>
75
- validateDeferredSectionInput({ component: "X", pagePath: "/" }),
76
- ).toThrow("rawProps");
77
- });
78
-
79
- it("throws when rawProps is an array", () => {
80
- expect(() =>
81
- validateDeferredSectionInput({ component: "X", rawProps: [1, 2], pagePath: "/" }),
82
- ).toThrow("rawProps");
83
- });
84
-
85
- it("throws when rawProps is null", () => {
86
- expect(() =>
87
- validateDeferredSectionInput({ component: "X", rawProps: null, pagePath: "/" }),
88
- ).toThrow("rawProps");
89
- });
90
-
91
- it("throws when pagePath is missing", () => {
92
- expect(() =>
93
- validateDeferredSectionInput({ component: "X", rawProps: {} }),
94
- ).toThrow("pagePath");
95
- });
96
-
97
- it("throws when pageUrl is not a string", () => {
98
- expect(() =>
99
- validateDeferredSectionInput({
100
- component: "X",
101
- rawProps: {},
102
- pagePath: "/",
103
- pageUrl: 42,
104
- }),
105
- ).toThrow("pageUrl");
106
- });
107
-
108
- it("throws when index is not a number", () => {
109
- expect(() =>
110
- validateDeferredSectionInput({
111
- component: "X",
112
- rawProps: {},
113
- pagePath: "/",
114
- index: "three" as any,
115
- }),
116
- ).toThrow("index");
117
- });
118
- });
119
-
120
- describe("createSectionValidator", () => {
121
- it("passes when all required fields present", () => {
122
- const validate = createSectionValidator(["title", "maxItems"]);
123
- const result = validate({ title: "Shelf", maxItems: 8 });
124
- expect(result).toEqual({ title: "Shelf", maxItems: 8 });
125
- });
126
-
127
- it("throws when a required field is missing", () => {
128
- const validate = createSectionValidator(["title", "maxItems"]);
129
- expect(() => validate({ title: "Shelf" })).toThrow("maxItems");
130
- });
131
-
132
- it("throws on null input", () => {
133
- const validate = createSectionValidator(["title"]);
134
- expect(() => validate(null)).toThrow("Expected an object");
135
- });
136
-
137
- it("allows extra fields", () => {
138
- const validate = createSectionValidator(["title"]);
139
- const result = validate({ title: "Hi", extra: true });
140
- expect(result).toEqual({ title: "Hi", extra: true });
141
- });
142
-
143
- it("empty required fields always passes for objects", () => {
144
- const validate = createSectionValidator([]);
145
- expect(validate({})).toEqual({});
146
- });
147
- });
@@ -1,67 +0,0 @@
1
- import { act } from "react";
2
- import { createRoot, type Root } from "react-dom/client";
3
- import { renderToString } from "react-dom/server";
4
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
-
6
- import { DraftPreviewBadge } from "./DraftPreviewBadge";
7
-
8
- describe("DraftPreviewBadge (render)", () => {
9
- // Raw SSR (react-dom/server) never runs effects — this is what a consumer
10
- // site that never hydrates this component, or the server's own render
11
- // pass, actually ships. The badge fails closed: nothing here, by design
12
- // (see the module doc for why render-then-hide is worse).
13
- it("renders nothing without a client to run the reveal effect", () => {
14
- const html = renderToString(<DraftPreviewBadge pointer="acme.vtex.app@v1" />);
15
- expect(html).toBe("");
16
- });
17
-
18
- describe("mounted in a browser", () => {
19
- let container: HTMLDivElement;
20
- let root: Root;
21
-
22
- beforeEach(() => {
23
- container = document.createElement("div");
24
- document.body.appendChild(container);
25
- root = createRoot(container);
26
- });
27
-
28
- afterEach(() => {
29
- act(() => {
30
- root.unmount();
31
- });
32
- container.remove();
33
- });
34
-
35
- it("reveals the preview-mode label after mount, once confirmed unframed", () => {
36
- act(() => {
37
- root.render(<DraftPreviewBadge pointer="acme.vtex.app@v1" />);
38
- });
39
- expect(container.textContent).toContain("Preview mode");
40
- });
41
-
42
- it("embeds the deco mark inline (no external asset that could 404 on a consumer site)", () => {
43
- act(() => {
44
- root.render(<DraftPreviewBadge pointer="acme.vtex.app@v1" />);
45
- });
46
- expect(container.innerHTML).toContain("data:image/png;base64,");
47
- });
48
-
49
- describe("embedded in an iframe", () => {
50
- const realTop = window.top;
51
- afterEach(() => {
52
- Object.defineProperty(window, "top", {
53
- value: realTop,
54
- configurable: true,
55
- });
56
- });
57
-
58
- it("stays hidden — Studio's own preview surface already has its own chrome", () => {
59
- Object.defineProperty(window, "top", { value: {}, configurable: true });
60
- act(() => {
61
- root.render(<DraftPreviewBadge pointer="acme.vtex.app@v1" />);
62
- });
63
- expect(container.textContent).toBe("");
64
- });
65
- });
66
- });
67
- });
@@ -1,55 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import { buildExitUrl, buildShareUrl, isFramed } from "./DraftPreviewBadge";
4
-
5
- describe("buildShareUrl", () => {
6
- it("pins the exact draft version so a recipient sees the same working tree", () => {
7
- expect(buildShareUrl("https://acme.vtex.app/pdp/shoe", "abc.localhost:60534@v7")).toBe(
8
- "https://acme.vtex.app/pdp/shoe?__draft=abc.localhost%3A60534%40v7",
9
- );
10
- });
11
-
12
- it("preserves existing query params, only setting the draft token", () => {
13
- expect(buildShareUrl("https://acme.vtex.app/plp?sort=price", "h@v1")).toBe(
14
- "https://acme.vtex.app/plp?sort=price&__draft=h%40v1",
15
- );
16
- });
17
-
18
- it("replaces a stale token already in the URL rather than appending a second", () => {
19
- expect(buildShareUrl("https://acme.vtex.app/p?__draft=h@old", "h@new")).toBe(
20
- "https://acme.vtex.app/p?__draft=h%40new",
21
- );
22
- });
23
- });
24
-
25
- describe("buildExitUrl", () => {
26
- it("sets the ?__draft=off exit sentinel", () => {
27
- expect(buildExitUrl("https://acme.vtex.app/pdp/shoe")).toBe(
28
- "https://acme.vtex.app/pdp/shoe?__draft=off",
29
- );
30
- });
31
-
32
- it("overrides an active token with off (leaves preview from anywhere)", () => {
33
- expect(buildExitUrl("https://acme.vtex.app/p?__draft=h@v1")).toBe(
34
- "https://acme.vtex.app/p?__draft=off",
35
- );
36
- });
37
- });
38
-
39
- describe("isFramed", () => {
40
- it("is false for a same top window — the ordinary top-level tab case", () => {
41
- const win = {} as typeof window;
42
- win.top = win;
43
- expect(isFramed(win)).toBe(false);
44
- });
45
-
46
- it("is true when top differs — embedded in another page's iframe", () => {
47
- const win = {} as typeof window;
48
- win.top = {} as typeof window; // a distinct object: the parent frame
49
- expect(isFramed(win)).toBe(true);
50
- });
51
-
52
- it("fails open (not framed) with no window — SSR / no hydration", () => {
53
- expect(isFramed(undefined)).toBe(false);
54
- });
55
- });