@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,167 +0,0 @@
1
- /**
2
- * Section mixins — focused on `withSectionLoader` since the device/mobile
3
- * mixins are exercised by sectionLoaders integration tests already.
4
- */
5
- import { describe, expect, it, vi } from "vitest";
6
- import {
7
- compose,
8
- withDevice,
9
- withMobile,
10
- withSearchParam,
11
- withSectionLoader,
12
- } from "./sectionMixins";
13
-
14
- // `__requestDependent` is the runtime tag the framework reads in
15
- // `registerSectionLoaders` to decide whether to emit the layout-cache
16
- // contamination warning (#206). Any future mixin that depends on the
17
- // request must opt in by setting this flag — and `compose` must propagate
18
- // it whenever any input has it.
19
- const isRequestDependent = (fn: unknown): boolean =>
20
- typeof fn === "function" && (fn as { __requestDependent?: boolean }).__requestDependent === true;
21
-
22
- const makeReq = (url = "https://store.example/foo?q=hello") =>
23
- new Request(url, { headers: { "user-agent": "vitest" } });
24
-
25
- describe("withSectionLoader", () => {
26
- it("invokes the section's exported loader and returns its result", async () => {
27
- const loader = vi.fn(async (props: Record<string, unknown>) => ({
28
- ...props,
29
- url: "https://store.example/foo?q=hello",
30
- enriched: true,
31
- }));
32
-
33
- const mixin = withSectionLoader(async () => ({ loader }));
34
- const result = await mixin({ original: "value" }, makeReq());
35
-
36
- expect(loader).toHaveBeenCalledTimes(1);
37
- expect(result).toEqual({
38
- original: "value",
39
- url: "https://store.example/foo?q=hello",
40
- enriched: true,
41
- });
42
- });
43
-
44
- it("returns props unchanged when module has no loader export", async () => {
45
- const mixin = withSectionLoader(async () => ({ default: () => null }));
46
- const props = { foo: "bar" };
47
- const result = await mixin(props, makeReq());
48
- expect(result).toBe(props);
49
- });
50
-
51
- it("returns props unchanged when module is undefined / loader is not a function", async () => {
52
- const mixin = withSectionLoader(async () => undefined);
53
- const props = { foo: "bar" };
54
- expect(await mixin(props, makeReq())).toBe(props);
55
-
56
- const mixinWithBadLoader = withSectionLoader(async () => ({
57
- loader: "not-a-function",
58
- }));
59
- expect(await mixinWithBadLoader(props, makeReq())).toBe(props);
60
- });
61
-
62
- it("swallows loader errors and returns the original props", async () => {
63
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
64
- const mixin = withSectionLoader(async () => ({
65
- loader: async () => {
66
- throw new Error("boom");
67
- },
68
- }));
69
- const props = { foo: "bar" };
70
- const result = await mixin(props, makeReq());
71
- expect(result).toBe(props);
72
- expect(errorSpy).toHaveBeenCalledWith(
73
- "[withSectionLoader] section loader threw:",
74
- expect.any(Error),
75
- );
76
- errorSpy.mockRestore();
77
- });
78
-
79
- it("falls back to original props when loader returns undefined", async () => {
80
- const mixin = withSectionLoader(async () => ({
81
- loader: async () => undefined,
82
- }));
83
- const props = { foo: "bar" };
84
- expect(await mixin(props, makeReq())).toBe(props);
85
- });
86
-
87
- it("composes alongside mixins: mixins run first, then the section loader sees the enriched props", async () => {
88
- const seen: Array<Record<string, unknown>> = [];
89
- const sectionLoader = vi.fn(async (props: Record<string, unknown>) => {
90
- seen.push({ ...props });
91
- return { ...props, sectionLoaderRan: true };
92
- });
93
-
94
- const composed = compose(
95
- withSearchParam(),
96
- withSectionLoader(async () => ({ loader: sectionLoader })),
97
- );
98
-
99
- const result = await composed({ original: 1 }, makeReq());
100
-
101
- expect(seen).toHaveLength(1);
102
- // The section loader sees the enriched props (currentSearchParam injected by withSearchParam)
103
- expect(seen[0]).toMatchObject({
104
- original: 1,
105
- currentSearchParam: "hello",
106
- });
107
- expect(result).toMatchObject({
108
- original: 1,
109
- currentSearchParam: "hello",
110
- sectionLoaderRan: true,
111
- });
112
- });
113
-
114
- it("loads the module lazily — modImport is only called on first invocation", async () => {
115
- const modImport = vi.fn(async () => ({
116
- loader: async (p: Record<string, unknown>) => ({ ...p, ran: true }),
117
- }));
118
- const mixin = withSectionLoader(modImport);
119
- expect(modImport).not.toHaveBeenCalled();
120
-
121
- await mixin({ a: 1 }, makeReq());
122
- expect(modImport).toHaveBeenCalledTimes(1);
123
-
124
- // A second invocation calls the import again — caching is the
125
- // dynamic import's responsibility (which the runtime memoises).
126
- await mixin({ a: 2 }, makeReq());
127
- expect(modImport).toHaveBeenCalledTimes(2);
128
- });
129
- });
130
-
131
- describe("request-dependent tagging (#206)", () => {
132
- it("tags withDevice", () => {
133
- expect(isRequestDependent(withDevice())).toBe(true);
134
- });
135
-
136
- it("tags withMobile", () => {
137
- expect(isRequestDependent(withMobile())).toBe(true);
138
- });
139
-
140
- it("tags withSearchParam", () => {
141
- expect(isRequestDependent(withSearchParam())).toBe(true);
142
- });
143
-
144
- it("does NOT tag withSectionLoader (its loader may or may not touch req)", () => {
145
- expect(isRequestDependent(withSectionLoader(async () => ({})))).toBe(false);
146
- });
147
-
148
- it("compose propagates the flag when any input is request-dependent", () => {
149
- expect(isRequestDependent(compose(withDevice(), async (p) => p))).toBe(true);
150
- expect(isRequestDependent(compose(async (p) => p, withSearchParam()))).toBe(true);
151
- });
152
-
153
- it("compose does NOT set the flag when no input is request-dependent", () => {
154
- expect(
155
- isRequestDependent(
156
- compose(
157
- async (p) => p,
158
- async (p) => p,
159
- ),
160
- ),
161
- ).toBe(false);
162
- });
163
-
164
- it("empty compose() is not request-dependent", () => {
165
- expect(isRequestDependent(compose())).toBe(false);
166
- });
167
- });
@@ -1,117 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
-
3
- vi.mock("./sectionLoaders", () => ({
4
- isLayoutSection: () => false,
5
- runSingleSectionLoader: vi.fn(async (section: any) => section),
6
- }));
7
-
8
- vi.mock("../sdk/normalizeUrls", () => ({
9
- normalizeUrlsInObject: vi.fn(<T>(x: T) => x),
10
- }));
11
-
12
- // A page whose A/B "TestHero" matcher block resolves to a 50/50 random matcher.
13
- vi.mock("./loader", () => ({
14
- findPageByPath: vi.fn(),
15
- loadBlocks: vi.fn(() => ({
16
- TestHero: { __resolveType: "website/matchers/random.ts", traffic: 0.5 },
17
- })),
18
- }));
19
-
20
- vi.mock("./registry", () => ({
21
- getSection: vi.fn(),
22
- }));
23
-
24
- import { DECO_MATCHERS_OVERRIDE_PARAM } from "../matchers/override";
25
- import { type StoredFlag, serializeSegmentCookie } from "../sdk/flags";
26
- import type { MatcherContext } from "./resolve";
27
- import { resolveValue } from "./resolve";
28
-
29
- const FLAG = {
30
- __resolveType: "website/flags/multivariate.ts",
31
- variants: [
32
- { rule: { __resolveType: "TestHero" }, value: "VARIANT_1" },
33
- { rule: { __resolveType: "website/matchers/always.ts" }, value: "VARIANT_2" },
34
- ],
35
- };
36
-
37
- function ctx(decision?: { value: boolean; pct: number }): MatcherContext & { flags: StoredFlag[] } {
38
- const cookie = decision
39
- ? serializeSegmentCookie([{ name: "TestHero", value: decision.value, pct: decision.pct }])
40
- : undefined;
41
- return {
42
- cookies: cookie ? { deco_segment: cookie } : {},
43
- flags: [],
44
- };
45
- }
46
-
47
- afterEach(() => vi.restoreAllMocks());
48
-
49
- describe("sticky A/B multivariate resolution", () => {
50
- it("honors a matching cookie without rolling (test cohort)", async () => {
51
- const rand = vi.spyOn(Math, "random");
52
- const c = ctx({ value: true, pct: 50 });
53
-
54
- const result = await resolveValue(FLAG, undefined, c);
55
-
56
- expect(result).toBe("VARIANT_1");
57
- expect(rand).not.toHaveBeenCalled();
58
- expect(c.flags).toEqual([{ name: "TestHero", value: true, pct: 50 }]);
59
- });
60
-
61
- it("honors a matching cookie without rolling (control cohort)", async () => {
62
- const rand = vi.spyOn(Math, "random");
63
- const c = ctx({ value: false, pct: 50 });
64
-
65
- const result = await resolveValue(FLAG, undefined, c);
66
-
67
- expect(result).toBe("VARIANT_2");
68
- expect(rand).not.toHaveBeenCalled();
69
- expect(c.flags).toEqual([{ name: "TestHero", value: false, pct: 50 }]);
70
- });
71
-
72
- it("rolls and records when there is no cookie", async () => {
73
- vi.spyOn(Math, "random").mockReturnValue(0.9); // >= 0.5 -> control
74
- const c = ctx();
75
-
76
- const result = await resolveValue(FLAG, undefined, c);
77
-
78
- expect(result).toBe("VARIANT_2");
79
- expect(c.flags).toEqual([{ name: "TestHero", value: false, pct: 50 }]);
80
- });
81
-
82
- it("re-rolls when the cookie's traffic fingerprint is stale", async () => {
83
- vi.spyOn(Math, "random").mockReturnValue(0.1); // < 0.5 -> test
84
- // Cookie says the user was in control at 70% traffic; current traffic is 50%.
85
- const c = ctx({ value: false, pct: 70 });
86
-
87
- const result = await resolveValue(FLAG, undefined, c);
88
-
89
- expect(result).toBe("VARIANT_1");
90
- expect(c.flags).toEqual([{ name: "TestHero", value: true, pct: 50 }]);
91
- });
92
-
93
- it("does not record flags when recording is not opted into", async () => {
94
- vi.spyOn(Math, "random").mockReturnValue(0.1);
95
- // No `flags` array on the context -> nothing to record, but still resolves.
96
- const result = await resolveValue(FLAG, undefined, { cookies: {} });
97
- expect(result).toBe("VARIANT_1");
98
- });
99
-
100
- it("honors the admin matchers-override instead of the cookie/roll", async () => {
101
- const rand = vi.spyOn(Math, "random");
102
- // Admin forces TestHero=0 for preview, but the cookie says test cohort.
103
- const c: MatcherContext & { flags: StoredFlag[] } = {
104
- cookies: {
105
- deco_segment: serializeSegmentCookie([{ name: "TestHero", value: true, pct: 50 }]),
106
- },
107
- headers: { [DECO_MATCHERS_OVERRIDE_PARAM]: "TestHero=0" },
108
- flags: [],
109
- };
110
-
111
- const result = await resolveValue(FLAG, undefined, c);
112
-
113
- expect(result).toBe("VARIANT_2"); // override wins over the cookie
114
- expect(rand).not.toHaveBeenCalled();
115
- expect(c.flags).toEqual([]); // previews don't persist a cohort
116
- });
117
- });
@@ -1,148 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import Audience from "./audience";
3
- import Everyone from "./everyone";
4
- import Flag from "./flag";
5
- import type { Matcher } from "./types";
6
- import multivariate from "./utils/multivariate";
7
- import ImageVariants from "./multivariate/image";
8
- import MessageVariants from "./multivariate/message";
9
- import PageVariants from "./multivariate/page";
10
- import SectionVariants from "./multivariate/section";
11
-
12
- // ---------------------------------------------------------------------------
13
- // flag.ts
14
- // ---------------------------------------------------------------------------
15
-
16
- describe("Flag", () => {
17
- it("returns a FlagObj with the same values", () => {
18
- const matcher: Matcher = () => true;
19
- const result = Flag({
20
- matcher,
21
- true: "variant-a",
22
- false: "variant-b",
23
- name: "test-flag",
24
- });
25
-
26
- expect(result.matcher).toBe(matcher);
27
- expect(result.true).toBe("variant-a");
28
- expect(result.false).toBe("variant-b");
29
- expect(result.name).toBe("test-flag");
30
- });
31
-
32
- it("preserves complex true/false values", () => {
33
- const routes = [{ pathTemplate: "/*", handler: { value: {} } }];
34
- const result = Flag<typeof routes>({
35
- matcher: () => false,
36
- true: routes,
37
- false: [],
38
- name: "routes-flag",
39
- });
40
-
41
- expect(result.true).toBe(routes);
42
- expect(result.false).toEqual([]);
43
- });
44
- });
45
-
46
- // ---------------------------------------------------------------------------
47
- // audience.ts
48
- // ---------------------------------------------------------------------------
49
-
50
- describe("Audience", () => {
51
- it("returns FlagObj with routes as true branch and empty as false", () => {
52
- const matcher: Matcher = () => true;
53
- const routes = [{ pathTemplate: "/products/*", handler: { value: {} } }];
54
-
55
- const result = Audience({ matcher, name: "vip-users", routes });
56
-
57
- expect(result.name).toBe("vip-users");
58
- expect(result.true).toEqual(routes);
59
- expect(result.false).toEqual([]);
60
- });
61
-
62
- it("defaults routes to empty array when not provided", () => {
63
- const result = Audience({ matcher: () => false, name: "empty" });
64
-
65
- expect(result.true).toEqual([]);
66
- expect(result.false).toEqual([]);
67
- });
68
- });
69
-
70
- // ---------------------------------------------------------------------------
71
- // everyone.ts
72
- // ---------------------------------------------------------------------------
73
-
74
- describe("Everyone", () => {
75
- it("creates a flag named Everyone that always matches", () => {
76
- const routes = [{ pathTemplate: "/*", handler: { value: {} } }];
77
- const result = Everyone({ routes });
78
-
79
- expect(result.name).toBe("Everyone");
80
- expect(result.true).toEqual(routes);
81
- expect(result.false).toEqual([]);
82
- // The matcher should be MatchAlways which returns true
83
- expect(result.matcher({} as any)).toBe(true);
84
- });
85
-
86
- it("works with no routes", () => {
87
- const result = Everyone({});
88
-
89
- expect(result.name).toBe("Everyone");
90
- expect(result.true).toEqual([]);
91
- });
92
- });
93
-
94
- // ---------------------------------------------------------------------------
95
- // multivariate
96
- // ---------------------------------------------------------------------------
97
-
98
- describe("multivariate", () => {
99
- it("returns the variants as-is", () => {
100
- const variants = [
101
- { value: "A", weight: 0.5 },
102
- { value: "B", weight: 0.5 },
103
- ];
104
-
105
- const result = multivariate({ variants });
106
-
107
- expect(result.variants).toBe(variants);
108
- expect(result.variants).toHaveLength(2);
109
- });
110
-
111
- it("supports variants with matchers", () => {
112
- const matcher: Matcher = () => true;
113
- const variants = [{ value: "control", matcher }, { value: "default" }];
114
-
115
- const result = multivariate({ variants });
116
-
117
- expect(result.variants[0].matcher).toBe(matcher);
118
- expect(result.variants[1].matcher).toBeUndefined();
119
- });
120
- });
121
-
122
- // ---------------------------------------------------------------------------
123
- // multivariate/* (Image/Message/Page/Section variants) + the multivariate.ts
124
- // re-export (`./multivariate.ts` re-exports `./multivariate/page.ts`'s
125
- // default, so `PageVariants` doubles as the coverage for that re-export).
126
- // ---------------------------------------------------------------------------
127
-
128
- describe("multivariate/*", () => {
129
- it("Image delegates to multivariate", () => {
130
- const variants = [{ value: "a.png" }, { value: "b.png" }];
131
- expect(ImageVariants({ variants })).toEqual({ variants });
132
- });
133
-
134
- it("Message delegates to multivariate", () => {
135
- const variants = [{ value: "hello" }, { value: "world" }];
136
- expect(MessageVariants({ variants })).toEqual({ variants });
137
- });
138
-
139
- it("Page delegates to multivariate", () => {
140
- const variants = [{ value: [] }, { value: [] }];
141
- expect(PageVariants({ variants })).toEqual({ variants });
142
- });
143
-
144
- it("Section delegates to multivariate", () => {
145
- const variants = [{ value: {} }, { value: {} }];
146
- expect(SectionVariants({ variants })).toEqual({ variants });
147
- });
148
- });
@@ -1,239 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- getImageCdnDomain,
4
- getImageQuality,
5
- getOptimizedMediaUrl,
6
- getSrcSet,
7
- type ImageQuality,
8
- registerImageCdnDomain,
9
- registerImageQuality,
10
- } from "./Image";
11
-
12
- describe("getOptimizedMediaUrl", () => {
13
- let warnSpy: ReturnType<typeof vi.spyOn>;
14
- let prevNodeEnv: string | undefined;
15
-
16
- beforeEach(() => {
17
- prevNodeEnv = process.env.NODE_ENV;
18
- process.env.NODE_ENV = "development";
19
- warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
20
- });
21
-
22
- afterEach(() => {
23
- warnSpy.mockRestore();
24
- if (prevNodeEnv === undefined) delete process.env.NODE_ENV;
25
- else process.env.NODE_ENV = prevNodeEnv;
26
- });
27
-
28
- it("returns empty string and warns when src is undefined", () => {
29
- const result = getOptimizedMediaUrl({
30
- originalSrc: undefined as unknown as string,
31
- width: 100,
32
- fit: "cover",
33
- });
34
- expect(result).toBe("");
35
- expect(warnSpy).toHaveBeenCalledTimes(1);
36
- expect(warnSpy.mock.calls[0][0]).toMatch(/empty\/undefined src/);
37
- });
38
-
39
- it("returns empty string when src is empty", () => {
40
- const result = getOptimizedMediaUrl({
41
- originalSrc: "",
42
- width: 100,
43
- fit: "cover",
44
- });
45
- expect(result).toBe("");
46
- });
47
-
48
- it("returns empty string when src is null", () => {
49
- const result = getOptimizedMediaUrl({
50
- originalSrc: null as unknown as string,
51
- width: 100,
52
- fit: "cover",
53
- });
54
- expect(result).toBe("");
55
- });
56
-
57
- it("does NOT warn in production for missing src", () => {
58
- process.env.NODE_ENV = "production";
59
- const result = getOptimizedMediaUrl({
60
- originalSrc: undefined as unknown as string,
61
- width: 100,
62
- fit: "cover",
63
- });
64
- expect(result).toBe("");
65
- expect(warnSpy).not.toHaveBeenCalled();
66
- });
67
-
68
- it("returns data URI as-is", () => {
69
- const dataUri = "data:image/png;base64,iVBORw0KGgo=";
70
- expect(
71
- getOptimizedMediaUrl({
72
- originalSrc: dataUri,
73
- width: 100,
74
- fit: "cover",
75
- }),
76
- ).toBe(dataUri);
77
- });
78
-
79
- it("routes through Deco image CDN for arbitrary src", () => {
80
- const result = getOptimizedMediaUrl({
81
- originalSrc: "https://cdn.example.com/foo.jpg",
82
- width: 200,
83
- fit: "cover",
84
- });
85
- expect(result).toContain("/image?");
86
- expect(result).toContain("width=200");
87
- expect(result).toContain("fit=cover");
88
- expect(result).toContain("src=https://cdn.example.com/foo.jpg");
89
- });
90
-
91
- it("strips the legacy decoims.com host so the CDN doesn't fetch itself (508)", () => {
92
- const result = getOptimizedMediaUrl({
93
- originalSrc: "https://decoims.com/site/2026/09/banner.png",
94
- width: 100,
95
- fit: "cover",
96
- });
97
- expect(result).toContain("&src=site/2026/09/banner.png");
98
- expect(result).not.toContain("src=https://decoims.com/");
99
- });
100
-
101
- it("strips decoims.com and drops its query string", () => {
102
- const result = getOptimizedMediaUrl({
103
- originalSrc: "https://decoims.com/site/a.png?v=2",
104
- width: 100,
105
- fit: "cover",
106
- });
107
- expect(result).toMatch(/&src=site\/a\.png$/);
108
- });
109
-
110
- it("keeps decoims.com absolute on Azion CDNs, which may 404 the relative path", () => {
111
- const prev = getImageCdnDomain();
112
- registerImageCdnDomain("deco-assets.edgedeco.com");
113
- try {
114
- const result = getOptimizedMediaUrl({
115
- originalSrc: "https://decoims.com/site/a.png",
116
- width: 100,
117
- fit: "cover",
118
- });
119
- expect(result).toContain("https://deco-assets.edgedeco.com/image?");
120
- expect(result).toContain("&src=https://decoims.com/site/a.png");
121
- } finally {
122
- registerImageCdnDomain(prev);
123
- }
124
- });
125
-
126
- it("only strips a leading Deco host", () => {
127
- const result = getOptimizedMediaUrl({
128
- originalSrc: "https://cdn.example.com/https://decoims.com/x.png",
129
- width: 100,
130
- fit: "cover",
131
- });
132
- expect(result).toContain("&src=https://cdn.example.com/https://decoims.com/x.png");
133
- });
134
- });
135
-
136
- describe("getSrcSet", () => {
137
- it("returns undefined when src is undefined", () => {
138
- expect(getSrcSet(undefined as unknown as string, 100)).toBeUndefined();
139
- });
140
-
141
- it("returns undefined when src is empty", () => {
142
- expect(getSrcSet("", 100)).toBeUndefined();
143
- });
144
-
145
- it("produces a srcset string for valid src", () => {
146
- const result = getSrcSet("https://cdn.example.com/foo.jpg", 100);
147
- expect(result).toBeDefined();
148
- // Each factor entry is "<url> <width>w".
149
- expect(result).toMatch(/\d+w/);
150
- expect(result).toContain("foo.jpg");
151
- });
152
- });
153
-
154
- describe("registerImageQuality", () => {
155
- // Module-level setter, so every test has to put it back or it leaks into
156
- // the rest of the file.
157
- afterEach(() => {
158
- registerImageQuality(undefined);
159
- });
160
-
161
- it("emits no quality param by default", () => {
162
- // The guarantee that makes this safe to land: every site that does not
163
- // opt in keeps byte-identical URLs, so no CDN cache is invalidated.
164
- expect(getImageQuality()).toBeUndefined();
165
- const result = getOptimizedMediaUrl({
166
- originalSrc: "https://cdn.example.com/foo.jpg",
167
- width: 200,
168
- fit: "cover",
169
- });
170
- expect(result).not.toContain("quality");
171
- });
172
-
173
- it("emits the registered quality for CDN-routed images", () => {
174
- registerImageQuality("high");
175
- const result = getOptimizedMediaUrl({
176
- originalSrc: "https://cdn.example.com/foo.jpg",
177
- width: 200,
178
- fit: "cover",
179
- });
180
- expect(result).toContain("quality=high");
181
- });
182
- it("pins the exact URL, param order included", () => {
183
- // Param ORDER is part of the CDN cache key, and `toContain` cannot see
184
- // it: reordering the params would keep every other assertion here green
185
- // while cold-caching every image on every site. It is also the property
186
- // that lets a site swap its node_modules patch for this setter without a
187
- // cache flush, so it needs a real equality check.
188
- registerImageQuality("high");
189
- expect(
190
- getOptimizedMediaUrl({
191
- originalSrc: "https://cdn.example.com/foo.jpg",
192
- width: 200,
193
- height: 300,
194
- fit: "cover",
195
- }),
196
- ).toBe(
197
- "https://assets.decocms.com/image?fit=cover&width=200&height=300&quality=high&src=https://cdn.example.com/foo.jpg",
198
- );
199
- });
200
-
201
- it("carries the quality into every srcset entry", () => {
202
- registerImageQuality("high");
203
- const result = getSrcSet("https://cdn.example.com/foo.jpg", 100);
204
- const entries = result?.split(", ") ?? [];
205
- expect(entries.length).toBeGreaterThan(1);
206
- for (const entry of entries) {
207
- expect(entry).toContain("quality=high");
208
- }
209
- });
210
-
211
- it("leaves VTEX sources alone — they resize via their own path syntax", () => {
212
- registerImageQuality("high");
213
- const result = getOptimizedMediaUrl({
214
- originalSrc:
215
- "https://acme.vtexassets.com/arquivos/ids/123456/product.jpg?v=1",
216
- width: 200,
217
- height: 300,
218
- fit: "cover",
219
- });
220
- expect(result).toContain("/arquivos/ids/123456-200-300/");
221
- expect(result).not.toContain("quality");
222
- });
223
-
224
- it("treats an empty string as unset, for untyped callers", () => {
225
- // Unreachable from TypeScript now that the parameter is a union, but a
226
- // value read from env or CMS config arrives as a plain string, so the
227
- // runtime guard still earns its keep.
228
- registerImageQuality("" as unknown as ImageQuality);
229
- expect(getImageQuality()).toBeUndefined();
230
- });
231
- });
232
-
233
- describe("getSrcSet — legacy decoims.com sources", () => {
234
- it("strips decoims.com from every srcset entry", () => {
235
- const result = getSrcSet("https://decoims.com/site/b.png", 200, 100, "cover") ?? "";
236
- expect(result).not.toContain("src=https://decoims.com/");
237
- for (const entry of result.split(", ")) expect(entry).toContain("&src=site/b.png");
238
- });
239
- });