@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,356 +0,0 @@
1
- /**
2
- * Tests for the schema registry's real-over-stub precedence and the
3
- * definition builders' additionalProperties preservation.
4
- *
5
- * Background: registerCommerceLoaders() auto-registers a
6
- * `{ type: "object", additionalProperties: true }` stub for every commerce
7
- * loader/action key. App packages register REAL props schemas (from their
8
- * build-time schemas.gen.ts) via registerAppSchemas(). The published meta
9
- * must contain the real schema no matter which side registered first, and
10
- * the stub's additionalProperties flag must survive into the definition so
11
- * the Studio can tell "props unknown — edit as JSON" apart from "takes no
12
- * input".
13
- *
14
- * NOTE: the registries are module-global singletons — every test uses its own
15
- * unique keys instead of resetting shared state.
16
- */
17
- import { describe, expect, it } from "vitest";
18
- import {
19
- composeMeta,
20
- getRegisteredLoaders,
21
- type MetaResponse,
22
- registerActionSchema,
23
- registerAppSchemas,
24
- registerLoaderSchema,
25
- } from "./schema";
26
-
27
- const b64 = (s: string) => Buffer.from(s).toString("base64");
28
-
29
- const emptySiteMeta = (): MetaResponse => ({
30
- major: 1,
31
- version: "1.0.0",
32
- namespace: "site",
33
- site: "test",
34
- manifest: { blocks: {} },
35
- schema: { definitions: {}, root: {} },
36
- });
37
-
38
- const STUB_SCHEMA = { type: "object" as const, additionalProperties: true };
39
-
40
- function stubLoader(key: string) {
41
- registerLoaderSchema({
42
- key,
43
- title: key,
44
- namespace: "vtex",
45
- propsSchema: STUB_SCHEMA,
46
- isStub: true,
47
- });
48
- }
49
-
50
- const REAL_PLP_PROPS = {
51
- type: "object" as const,
52
- properties: {
53
- sort: {
54
- type: "string",
55
- enum: ["OrderByPriceDESC", "OrderByPriceASC", "OrderByTopSaleDESC"],
56
- },
57
- count: { type: "number" },
58
- fq: { type: "string" },
59
- },
60
- required: ["count"],
61
- };
62
-
63
- function realLoader(key: string) {
64
- registerAppSchemas({ namespace: "vtex", loaders: { [key]: REAL_PLP_PROPS } });
65
- }
66
-
67
- function definitionFor(key: string) {
68
- return composeMeta(emptySiteMeta()).schema.definitions[b64(key)];
69
- }
70
-
71
- describe("real-over-stub precedence", () => {
72
- it("keeps the real schema when the stub registers afterwards (loaders)", () => {
73
- const key = "vtex/loaders/test/realThenStub.ts";
74
- realLoader(key);
75
- stubLoader(key);
76
-
77
- const def = definitionFor(key);
78
- expect(def.properties.sort.enum).toEqual([
79
- "OrderByPriceDESC",
80
- "OrderByPriceASC",
81
- "OrderByTopSaleDESC",
82
- ]);
83
- expect(def.required).toEqual(["__resolveType", "count"]);
84
- expect(def.additionalProperties).toBeUndefined();
85
- });
86
-
87
- it("replaces the stub when the real schema registers afterwards (loaders)", () => {
88
- const key = "vtex/loaders/test/stubThenReal.ts";
89
- stubLoader(key);
90
- realLoader(key);
91
-
92
- const def = definitionFor(key);
93
- expect(def.properties.count).toEqual({ type: "number" });
94
- expect(def.additionalProperties).toBeUndefined();
95
- });
96
-
97
- it("applies the same precedence to actions", () => {
98
- const key = "vtex/actions/test/addCoupon.ts";
99
- registerAppSchemas({
100
- namespace: "vtex",
101
- actions: {
102
- [key]: {
103
- type: "object",
104
- properties: { coupon: { type: "string" } },
105
- required: ["coupon"],
106
- },
107
- },
108
- });
109
- registerActionSchema({
110
- key,
111
- title: key,
112
- namespace: "vtex",
113
- propsSchema: STUB_SCHEMA,
114
- isStub: true,
115
- });
116
-
117
- const def = definitionFor(key);
118
- expect(def.properties.coupon).toEqual({ type: "string" });
119
- expect(def.required).toEqual(["__resolveType", "coupon"]);
120
- expect(def.additionalProperties).toBeUndefined();
121
- });
122
-
123
- it("lets a later stub replace an earlier stub (hot-reload re-registration)", () => {
124
- const key = "vtex/loaders/test/stubTwice.ts";
125
- stubLoader(key);
126
- stubLoader(key);
127
- expect(definitionFor(key).additionalProperties).toBe(true);
128
- });
129
-
130
- it("lets a later real schema replace an earlier real schema", () => {
131
- const key = "vtex/loaders/test/realTwice.ts";
132
- realLoader(key);
133
- registerAppSchemas({
134
- namespace: "vtex",
135
- loaders: {
136
- [key]: { type: "object", properties: { slug: { type: "string" } } },
137
- },
138
- });
139
- const def = definitionFor(key);
140
- expect(def.properties.slug).toEqual({ type: "string" });
141
- expect(def.properties.sort).toBeUndefined();
142
- });
143
- });
144
-
145
- describe("additionalProperties preservation in definitions", () => {
146
- it("emits additionalProperties: true for stub-only keys (props unknown → JSON editor)", () => {
147
- const key = "vtex/loaders/test/stubOnly.ts";
148
- stubLoader(key);
149
-
150
- const def = definitionFor(key);
151
- expect(def.additionalProperties).toBe(true);
152
- expect(Object.keys(def.properties)).toEqual(["__resolveType"]);
153
- });
154
-
155
- it("emits NO additionalProperties for a real schema without props (takes no input)", () => {
156
- const key = "vtex/loaders/test/noInput.ts";
157
- registerAppSchemas({
158
- namespace: "vtex",
159
- loaders: { [key]: { type: "object", properties: {} } },
160
- });
161
-
162
- const def = definitionFor(key);
163
- expect(def.additionalProperties).toBeUndefined();
164
- expect(Object.keys(def.properties)).toEqual(["__resolveType"]);
165
- });
166
- });
167
-
168
- describe("registerAppSchemas", () => {
169
- it("registers every key form present in the artifact (bare and .ts)", () => {
170
- const bare = "vtex/loaders/test/aliased";
171
- registerAppSchemas({
172
- namespace: "vtex",
173
- loaders: {
174
- [bare]: REAL_PLP_PROPS,
175
- [`${bare}.ts`]: REAL_PLP_PROPS,
176
- },
177
- });
178
-
179
- const meta = composeMeta(emptySiteMeta());
180
- for (const key of [bare, `${bare}.ts`]) {
181
- const def = meta.schema.definitions[b64(key)];
182
- expect(def.properties.sort.enum).toContain("OrderByPriceDESC");
183
- expect(def.properties.__resolveType.enum).toEqual([key]);
184
- expect(meta.manifest.blocks.loaders[key]).toEqual({
185
- $ref: `#/definitions/${b64(key)}`,
186
- namespace: "vtex",
187
- });
188
- }
189
- });
190
-
191
- it("propagates schema title/description into the definition", () => {
192
- const key = "vtex/loaders/test/titled.ts";
193
- registerAppSchemas({
194
- namespace: "vtex",
195
- loaders: {
196
- [key]: {
197
- type: "object",
198
- title: "Product Listing Page",
199
- description: "Fetches a PLP",
200
- properties: { term: { type: "string" } },
201
- },
202
- },
203
- });
204
-
205
- const def = definitionFor(key);
206
- expect(def.title).toBe("Product Listing Page");
207
- expect(def.description).toBe("Fetches a PLP");
208
- });
209
-
210
- it("infers the product-list tag for loader keys, matching the stub inference", () => {
211
- const key = "vtex/loaders/test/productListShelf.ts";
212
- registerAppSchemas({
213
- namespace: "vtex",
214
- loaders: { [key]: { type: "object", properties: {} } },
215
- });
216
-
217
- const registered = getRegisteredLoaders().find((l) => l.key === key);
218
- expect(registered?.tags).toEqual(["product-list"]);
219
- });
220
- });
221
-
222
- describe("composeMeta framework option", () => {
223
- it("defaults the framework field to tanstack-start", () => {
224
- expect(composeMeta(emptySiteMeta()).framework).toBe("tanstack-start");
225
- });
226
-
227
- it("honors an explicit framework override (e.g. eitri)", () => {
228
- expect(composeMeta(emptySiteMeta(), { framework: "eitri" }).framework).toBe("eitri");
229
- });
230
-
231
- it("still bakes in the framework block types regardless of framework name", () => {
232
- const meta = composeMeta(emptySiteMeta(), { framework: "eitri" });
233
- // The whole point of composing at generation time: Page + section-picker +
234
- // Resolvable land in definitions so an FS-only consumer is self-contained.
235
- expect(meta.schema.definitions).toHaveProperty("__SECTION_REF__");
236
- expect(meta.schema.definitions).toHaveProperty("Resolvable");
237
- expect(meta.manifest.blocks.pages).toHaveProperty("website/pages/Page.tsx");
238
- });
239
- });
240
-
241
- describe("commerce SEO section schemas", () => {
242
- const b64Ref = (key: string) => ({ $ref: `#/definitions/${b64(key)}` });
243
-
244
- it("emits editable props for the product-listing SEO section (plp mode)", () => {
245
- const def = definitionFor("commerce/sections/Seo/SeoPLPV2.tsx");
246
- // Without a schema here, resolveSchema() returns null and the Studio SEO
247
- // editor renders no fields — the "não tem props" bug.
248
- expect(def).toBeDefined();
249
- const props = def.properties;
250
- expect(props).toHaveProperty("title");
251
- expect(props).toHaveProperty("description");
252
- expect(props).toHaveProperty("noIndexing");
253
- // PLP-specific structured-data config (see seo-form-mode.ts PLP_SEO_FIELD_KEYS).
254
- expect(props.configJsonLD.properties).toHaveProperty("removeVideos");
255
- expect(props.configJsonLD.properties).toHaveProperty("ignoreStructuredData");
256
- // The data source is a loader picker (anyOf over the loader union), not
257
- // hidden — the user picks the PLP loader that feeds the structured data.
258
- expect(Array.isArray(props.jsonLD.anyOf)).toBe(true);
259
- expect(props.jsonLD.title).toBe("Data Source");
260
- });
261
-
262
- it("emits editable props for the product-details SEO section (pdp mode)", () => {
263
- const def = definitionFor("commerce/sections/Seo/SeoPDPV2.tsx");
264
- expect(def).toBeDefined();
265
- const props = def.properties;
266
- expect(props).toHaveProperty("title");
267
- expect(props).toHaveProperty("description");
268
- expect(props).toHaveProperty("noIndexing");
269
- // PDP-specific fields (see seo-form-mode.ts PDP_SEO_FIELD_KEYS).
270
- expect(props).toHaveProperty("omitVariants");
271
- expect(props).toHaveProperty("ignoreStructuredData");
272
- expect(Array.isArray(props.jsonLD.anyOf)).toBe(true);
273
- expect(props.jsonLD.title).toBe("Data Source");
274
- });
275
-
276
- it("registers the defs + manifest blocks and offers them as page.seo options", () => {
277
- // Unconditional (no commerce gate): meta.gen.json is baked at generation
278
- // time when the loader registry is empty, and the runtime serves that baked
279
- // meta as-is, so a registry-based gate would never bake the options.
280
- const meta = composeMeta(emptySiteMeta());
281
- for (const key of [
282
- "commerce/sections/Seo/SeoPLPV2.tsx",
283
- "commerce/sections/Seo/SeoPDPV2.tsx",
284
- ]) {
285
- expect(meta.manifest.blocks.sections).toHaveProperty(key);
286
- expect(meta.schema.definitions).toHaveProperty(b64(key));
287
- expect(meta.schema.root.sections.anyOf).toContainEqual(b64Ref(key));
288
- }
289
- });
290
-
291
- // Mirrors a generated site meta: a loader carries a real def AND is listed in
292
- // the site's loader union. `@ignore`d loaders are the exception — they get a
293
- // def but are withheld from the union.
294
- function siteMetaWithLoader(key: string, opts: { inUnion: boolean }) {
295
- const site = emptySiteMeta();
296
- site.schema.definitions[b64(key)] = {
297
- title: key,
298
- type: "object",
299
- properties: { __resolveType: { type: "string", enum: [key] } },
300
- };
301
- site.manifest.blocks.loaders = {
302
- [key]: { $ref: `#/definitions/${b64(key)}`, namespace: "site" },
303
- };
304
- site.schema.root = { loaders: { anyOf: opts.inUnion ? [b64Ref(key)] : [] } };
305
- return site;
306
- }
307
-
308
- it("feeds the site's own loaders into the jsonLD data-source picker", () => {
309
- // The runtime loader registry is empty at generation time, so the union must
310
- // be seeded from the site's own loader union — else the picker has no
311
- // options and the user can't wire the data source.
312
- const loaderKey = "site/loaders/product/productDetailsPage.ts";
313
- const meta = composeMeta(siteMetaWithLoader(loaderKey, { inUnion: true }));
314
-
315
- // The picker option is real, not a dangling $ref: its def survives.
316
- expect(meta.schema.definitions).toHaveProperty(b64(loaderKey));
317
- // …offered in both the root union and the commerce SEO jsonLD picker.
318
- expect(meta.schema.root.loaders.anyOf).toContainEqual(b64Ref(loaderKey));
319
- const seoDef =
320
- meta.schema.definitions[b64("commerce/sections/Seo/SeoPDPV2.tsx")];
321
- expect(seoDef.properties.jsonLD.anyOf).toContainEqual(b64Ref(loaderKey));
322
- });
323
-
324
- it("keeps @ignore'd loaders (in the manifest, not the union) out of the picker", () => {
325
- // Seeding from `manifest.blocks.loaders` would resurrect hidden loaders;
326
- // seeding from the union keeps them out.
327
- const hiddenKey = "site/loaders/internal/hidden.ts";
328
- const meta = composeMeta(siteMetaWithLoader(hiddenKey, { inUnion: false }));
329
-
330
- expect(meta.schema.root.loaders.anyOf).not.toContainEqual(b64Ref(hiddenKey));
331
- const seoDef =
332
- meta.schema.definitions[b64("commerce/sections/Seo/SeoPDPV2.tsx")];
333
- expect(seoDef.properties.jsonLD.anyOf).not.toContainEqual(b64Ref(hiddenKey));
334
- });
335
- });
336
-
337
- describe("composeMeta idempotency", () => {
338
- it("returns an already-composed meta unchanged (no double-compose)", () => {
339
- const once = composeMeta(emptySiteMeta());
340
- const twice = composeMeta(once);
341
- // The sentinel is the top-level `framework` field, which only composeMeta
342
- // sets — re-composing must be a no-op, returning the same object.
343
- expect(twice).toBe(once);
344
- });
345
-
346
- it("does not duplicate framework section refs when re-composed", () => {
347
- // Simulate the tanstack runtime path: a self-contained meta.gen.json (baked
348
- // at gen time) is loaded from disk and composeMeta runs again on top of it.
349
- const composed = composeMeta(emptySiteMeta());
350
- const sectionsAnyOf = composed.schema.root.sections.anyOf;
351
- const recomposed = composeMeta(composed);
352
- // Without the guard, framework section refs (Lazy/Seo/…) would be appended
353
- // to root.sections.anyOf a second time.
354
- expect(recomposed.schema.root.sections.anyOf).toHaveLength(sectionsAnyOf.length);
355
- });
356
- });
@@ -1,111 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { RequestContext } from "../sdk/requestContext";
3
- import { buildSectionLoaderContext } from "./sectionLoaderContext";
4
-
5
- const MOBILE_UA =
6
- "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148";
7
- const DESKTOP_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36";
8
- const TABLET_UA = "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15";
9
-
10
- function reqWithUA(ua: string, url = "https://store.example/path?q=shoes"): Request {
11
- return new Request(url, { headers: { "user-agent": ua } });
12
- }
13
-
14
- describe("buildSectionLoaderContext", () => {
15
- describe("device", () => {
16
- it("detects mobile / desktop / tablet from the request User-Agent", () => {
17
- expect(buildSectionLoaderContext(reqWithUA(MOBILE_UA)).device).toBe("mobile");
18
- expect(buildSectionLoaderContext(reqWithUA(DESKTOP_UA)).device).toBe("desktop");
19
- expect(buildSectionLoaderContext(reqWithUA(TABLET_UA)).device).toBe("tablet");
20
- });
21
-
22
- it("defaults to desktop when there is no User-Agent", () => {
23
- expect(buildSectionLoaderContext(new Request("https://store.example/")).device).toBe(
24
- "desktop",
25
- );
26
- });
27
-
28
- it("never throws for a minimal/mock request without headers", () => {
29
- const badReq = { url: "not a url" } as unknown as Request;
30
- expect(() => buildSectionLoaderContext(badReq)).not.toThrow();
31
- expect(buildSectionLoaderContext(badReq).device).toBe("desktop");
32
- });
33
- });
34
-
35
- describe("app state", () => {
36
- it("resolves ctx.<appName> to the app's registered state inside a request scope", async () => {
37
- const req = reqWithUA(DESKTOP_UA);
38
- await RequestContext.run(req, async () => {
39
- RequestContext.setBag("app:vtex:state", { config: { account: "acme" } });
40
- const ctx = buildSectionLoaderContext(req);
41
- expect((ctx as any).vtex).toEqual({ config: { account: "acme" } });
42
- expect(ctx.getAppState("vtex")).toEqual({ config: { account: "acme" } });
43
- });
44
- });
45
-
46
- it("returns undefined for an unconfigured app (no fake object)", async () => {
47
- const req = reqWithUA(DESKTOP_UA);
48
- await RequestContext.run(req, async () => {
49
- const ctx = buildSectionLoaderContext(req);
50
- expect((ctx as any).salesforce).toBeUndefined();
51
- });
52
- });
53
-
54
- it("returns undefined for app state outside a request scope", () => {
55
- const ctx = buildSectionLoaderContext(reqWithUA(DESKTOP_UA));
56
- expect((ctx as any).vtex).toBeUndefined();
57
- });
58
- });
59
-
60
- describe("response.headers", () => {
61
- it("writes through to RequestContext.responseHeaders inside a scope", async () => {
62
- const req = reqWithUA(DESKTOP_UA);
63
- await RequestContext.run(req, async () => {
64
- const ctx = buildSectionLoaderContext(req);
65
- ctx.response.headers.set("set-cookie", "a=1");
66
- expect(RequestContext.responseHeaders.get("set-cookie")).toBe("a=1");
67
- });
68
- });
69
-
70
- it("degrades to an inert Headers outside a scope (does not throw)", () => {
71
- const ctx = buildSectionLoaderContext(reqWithUA(DESKTOP_UA));
72
- expect(() => ctx.response.headers.set("x", "y")).not.toThrow();
73
- });
74
- });
75
-
76
- describe("invoke (server-side self-fetch)", () => {
77
- let fetchMock: ReturnType<typeof vi.fn>;
78
-
79
- beforeEach(() => {
80
- fetchMock = vi
81
- .fn()
82
- .mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 }));
83
- vi.stubGlobal("fetch", fetchMock);
84
- });
85
-
86
- afterEach(() => {
87
- vi.unstubAllGlobals();
88
- });
89
-
90
- it("POSTs to the request's absolute origin /deco/invoke/<key>", async () => {
91
- const ctx = buildSectionLoaderContext(reqWithUA(DESKTOP_UA, "https://store.example/pdp"));
92
- const result = await ctx.invoke.vtex.loaders.product.detailsPageGQL({ slug: "x" });
93
-
94
- expect(result).toEqual({ ok: true });
95
- const [url, init] = fetchMock.mock.calls[0];
96
- expect(url).toBe("https://store.example/deco/invoke/vtex/loaders/product/detailsPageGQL");
97
- expect(init.method).toBe("POST");
98
- expect(JSON.parse(init.body)).toEqual({ slug: "x" });
99
- });
100
-
101
- it("injects the request AbortSignal when invoked inside a request scope", async () => {
102
- const req = reqWithUA(DESKTOP_UA, "https://store.example/pdp");
103
- await RequestContext.run(req, async () => {
104
- const ctx = buildSectionLoaderContext(req);
105
- await ctx.invoke.vtex.loaders.x({});
106
- const [, init] = fetchMock.mock.calls[0];
107
- expect(init.signal).toBeInstanceOf(AbortSignal);
108
- });
109
- });
110
- });
111
- });