@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,474 +0,0 @@
1
- /**
2
- * Phase 3 (D-12) coverage for the direct-POST OTLP trace exporter.
3
- * Mirrors the test style of `otelHttpMeter.test.ts` — fake fetch,
4
- * deterministic clock, deterministic IDs via injected accessors.
5
- */
6
- import { describe, expect, it, vi } from "vitest";
7
- import type { Span } from "../middleware/observability";
8
- import {
9
- createOtlpHttpTracerAdapter,
10
- newSpanId,
11
- newTraceId,
12
- parseTraceparent,
13
- shouldSampleTrace,
14
- type TraceContext,
15
- } from "./otelHttpTracer";
16
-
17
- // ---------------------------------------------------------------------------
18
- // Helpers — capture fetch & emulate active-span propagation
19
- // ---------------------------------------------------------------------------
20
-
21
- function captureFetch(): {
22
- fetchImpl: typeof fetch;
23
- calls: Array<{ url: string; payload: Record<string, unknown> }>;
24
- } {
25
- const calls: Array<{ url: string; payload: Record<string, unknown> }> = [];
26
- const fetchImpl: typeof fetch = async (input, init) => {
27
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
28
- const body = init?.body as string | undefined;
29
- calls.push({ url, payload: body ? JSON.parse(body) : {} });
30
- return new Response("", { status: 200 });
31
- };
32
- return { fetchImpl, calls };
33
- }
34
-
35
- /**
36
- * Build a minimal active-span scope helper. Tests can push a parent
37
- * span before calling `startSpan`, simulating what `withTracing` does
38
- * via ALS.
39
- */
40
- function activeSpanStack(): {
41
- push(span: Span): void;
42
- pop(): void;
43
- get(): Span | null;
44
- } {
45
- const stack: Span[] = [];
46
- return {
47
- push(span) {
48
- stack.push(span);
49
- },
50
- pop() {
51
- stack.pop();
52
- },
53
- get() {
54
- return stack[stack.length - 1] ?? null;
55
- },
56
- };
57
- }
58
-
59
- // ---------------------------------------------------------------------------
60
- // parseTraceparent
61
- // ---------------------------------------------------------------------------
62
-
63
- describe("parseTraceparent (D-12)", () => {
64
- it("parses a well-formed sampled header", () => {
65
- const ctx = parseTraceparent("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01");
66
- expect(ctx).toEqual({
67
- traceId: "0af7651916cd43dd8448eb211c80319c",
68
- parentSpanId: "b7ad6b7169203331",
69
- sampled: true,
70
- remoteParent: true,
71
- });
72
- });
73
-
74
- it("parses a well-formed unsampled header", () => {
75
- const ctx = parseTraceparent("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00");
76
- expect(ctx?.sampled).toBe(false);
77
- });
78
-
79
- it("returns null on null / undefined / empty string", () => {
80
- expect(parseTraceparent(null)).toBeNull();
81
- expect(parseTraceparent(undefined)).toBeNull();
82
- expect(parseTraceparent("")).toBeNull();
83
- });
84
-
85
- it("rejects unknown versions", () => {
86
- expect(parseTraceparent("01-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")).toBeNull();
87
- });
88
-
89
- it("rejects the well-known all-zero IDs (per W3C §3.2.2)", () => {
90
- expect(
91
- parseTraceparent("00-00000000000000000000000000000000-b7ad6b7169203331-01"),
92
- ).toBeNull();
93
- expect(
94
- parseTraceparent("00-0af7651916cd43dd8448eb211c80319c-0000000000000000-01"),
95
- ).toBeNull();
96
- });
97
-
98
- it("rejects malformed lengths and non-hex characters", () => {
99
- expect(parseTraceparent("00-tooshort-b7ad6b7169203331-01")).toBeNull();
100
- expect(parseTraceparent("00-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz-b7ad6b7169203331-01")).toBeNull();
101
- });
102
- });
103
-
104
- // ---------------------------------------------------------------------------
105
- // shouldSampleTrace — consistency + boundary cases
106
- // ---------------------------------------------------------------------------
107
-
108
- describe("shouldSampleTrace (D-12)", () => {
109
- it("returns true for rate >= 1 (always sample)", () => {
110
- expect(shouldSampleTrace("0".repeat(31) + "1", 1)).toBe(true);
111
- expect(shouldSampleTrace("0".repeat(31) + "1", 5)).toBe(true);
112
- expect(shouldSampleTrace("0".repeat(31) + "1", Infinity)).toBe(true);
113
- });
114
-
115
- it("returns false for rate <= 0 (never sample)", () => {
116
- expect(shouldSampleTrace("0".repeat(31) + "1", 0)).toBe(false);
117
- expect(shouldSampleTrace("0".repeat(31) + "1", -1)).toBe(false);
118
- });
119
-
120
- it("decisions are stable per trace ID (called twice → same answer)", () => {
121
- const traceId = newTraceId();
122
- const first = shouldSampleTrace(traceId, 0.1);
123
- const second = shouldSampleTrace(traceId, 0.1);
124
- expect(first).toBe(second);
125
- });
126
-
127
- it("approximates the configured rate over a large sample", () => {
128
- // 5000 random trace IDs sampled at 10% should land within ±3% of
129
- // the target — bounded statistical noise, deterministic seed not
130
- // required because `Math.random` flakes here would already
131
- // indicate a broken hash.
132
- const trials = 5000;
133
- let kept = 0;
134
- for (let i = 0; i < trials; i++) {
135
- if (shouldSampleTrace(newTraceId(), 0.1)) kept++;
136
- }
137
- const observed = kept / trials;
138
- expect(observed).toBeGreaterThan(0.07);
139
- expect(observed).toBeLessThan(0.13);
140
- });
141
- });
142
-
143
- // ---------------------------------------------------------------------------
144
- // ID generation — shape only (entropy depends on crypto.getRandomValues)
145
- // ---------------------------------------------------------------------------
146
-
147
- describe("newTraceId / newSpanId (D-12)", () => {
148
- it("returns 32-hex-char trace IDs and 16-hex-char span IDs", () => {
149
- expect(newTraceId()).toMatch(/^[0-9a-f]{32}$/);
150
- expect(newSpanId()).toMatch(/^[0-9a-f]{16}$/);
151
- });
152
- it("does not repeat over 100 calls", () => {
153
- const set = new Set<string>();
154
- for (let i = 0; i < 100; i++) set.add(newTraceId());
155
- expect(set.size).toBe(100);
156
- });
157
- });
158
-
159
- // ---------------------------------------------------------------------------
160
- // Adapter — startSpan / end / flush
161
- // ---------------------------------------------------------------------------
162
-
163
- describe("createOtlpHttpTracerAdapter (D-12)", () => {
164
- it("buffers a root span and POSTs OTLP payload on flush", async () => {
165
- const { fetchImpl, calls } = captureFetch();
166
- const stack = activeSpanStack();
167
- let clock = 100;
168
-
169
- const tracer = createOtlpHttpTracerAdapter({
170
- endpoint: "https://collector.example/v1/traces",
171
- resourceAttributes: { "service.name": "test-site" },
172
- headSamplingRate: 1,
173
- minFlushIntervalMs: 0,
174
- fetchImpl,
175
- nowMs: () => clock,
176
- getActiveSpanForParent: () => stack.get(),
177
- });
178
-
179
- const span = tracer.startSpan("deco.http.request", { "http.method": "GET" });
180
- clock = 250;
181
- span.setAttribute?.("http.status_code", 200);
182
- span.end();
183
-
184
- expect(tracer.pendingSpanCount()).toBe(1);
185
- await tracer.flush();
186
- expect(tracer.pendingSpanCount()).toBe(0);
187
- expect(calls).toHaveLength(1);
188
-
189
- const resourceSpans = (calls[0].payload as { resourceSpans: unknown[] }).resourceSpans as Array<{
190
- resource: { attributes: Array<{ key: string; value: { stringValue: string } }> };
191
- scopeSpans: Array<{
192
- spans: Array<{
193
- name: string;
194
- traceId: string;
195
- spanId: string;
196
- parentSpanId: string;
197
- startTimeUnixNano: string;
198
- endTimeUnixNano: string;
199
- attributes: Array<{ key: string; value: unknown }>;
200
- status: { code: number };
201
- }>;
202
- }>;
203
- }>;
204
- const rs = resourceSpans[0];
205
- expect(rs.resource.attributes).toContainEqual({
206
- key: "service.name",
207
- value: { stringValue: "test-site" },
208
- });
209
- const spans = rs.scopeSpans[0].spans;
210
- expect(spans).toHaveLength(1);
211
- expect(spans[0].name).toBe("deco.http.request");
212
- expect(spans[0].traceId).toMatch(/^[0-9a-f]{32}$/);
213
- expect(spans[0].spanId).toMatch(/^[0-9a-f]{16}$/);
214
- expect(spans[0].parentSpanId).toBe("");
215
- // 200 status_code → status.code = OK (1)
216
- expect(spans[0].status.code).toBe(1);
217
- });
218
-
219
- it("inherits trace ID from the active parent span", async () => {
220
- const { fetchImpl, calls } = captureFetch();
221
- const stack = activeSpanStack();
222
- const tracer = createOtlpHttpTracerAdapter({
223
- endpoint: "https://collector.example/v1/traces",
224
- resourceAttributes: {},
225
- headSamplingRate: 1,
226
- minFlushIntervalMs: 0,
227
- fetchImpl,
228
- getActiveSpanForParent: () => stack.get(),
229
- });
230
-
231
- const parent = tracer.startSpan("deco.http.request");
232
- stack.push(parent);
233
- const child = tracer.startSpan("deco.cache.lookup");
234
- stack.pop();
235
-
236
- const parentCtx = parent.spanContext?.();
237
- const childCtx = child.spanContext?.();
238
- expect(childCtx?.traceId).toBe(parentCtx?.traceId);
239
- expect(childCtx?.spanId).not.toBe(parentCtx?.spanId);
240
-
241
- child.end();
242
- parent.end();
243
- await tracer.flush();
244
-
245
- const payload = calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{
246
- name: string;
247
- parentSpanId: string;
248
- spanId: string;
249
- }> }> }> };
250
- const spans = payload.resourceSpans[0].scopeSpans[0].spans;
251
- const childRow = spans.find((s) => s.name === "deco.cache.lookup");
252
- const parentRow = spans.find((s) => s.name === "deco.http.request");
253
- expect(childRow?.parentSpanId).toBe(parentRow?.spanId);
254
- });
255
-
256
- it("honors an inbound W3C traceparent for root spans", async () => {
257
- const { fetchImpl } = captureFetch();
258
- const stack = activeSpanStack();
259
- const remote: TraceContext = {
260
- traceId: "0af7651916cd43dd8448eb211c80319c",
261
- parentSpanId: "b7ad6b7169203331",
262
- sampled: true,
263
- remoteParent: true,
264
- };
265
- const tracer = createOtlpHttpTracerAdapter({
266
- endpoint: "https://collector.example/v1/traces",
267
- resourceAttributes: {},
268
- headSamplingRate: 0, // would normally drop everything
269
- minFlushIntervalMs: 0,
270
- fetchImpl,
271
- getActiveSpanForParent: () => stack.get(),
272
- getRequestTraceContext: () => remote,
273
- });
274
-
275
- const root = tracer.startSpan("deco.http.request");
276
- const ctx = root.spanContext?.();
277
- expect(ctx?.traceId).toBe(remote.traceId);
278
- // parentSpanId from the remote should appear on the OTLP record
279
- root.end();
280
-
281
- // Even at samplingRate=0, the remote `sampled=true` overrides and
282
- // keeps this span.
283
- expect(tracer.pendingSpanCount()).toBe(1);
284
- });
285
-
286
- it("drops spans deterministically when samplingRate=0 and no remote sample bit", async () => {
287
- const stack = activeSpanStack();
288
- const tracer = createOtlpHttpTracerAdapter({
289
- endpoint: "https://collector.example/v1/traces",
290
- resourceAttributes: {},
291
- headSamplingRate: 0,
292
- minFlushIntervalMs: 0,
293
- fetchImpl: vi.fn() as unknown as typeof fetch,
294
- getActiveSpanForParent: () => stack.get(),
295
- });
296
- const span = tracer.startSpan("deco.http.request");
297
- span.end();
298
- expect(tracer.pendingSpanCount()).toBe(0);
299
- });
300
-
301
- it("captures setError as an OTLP exception event", async () => {
302
- const { fetchImpl, calls } = captureFetch();
303
- const stack = activeSpanStack();
304
- const tracer = createOtlpHttpTracerAdapter({
305
- endpoint: "https://collector.example/v1/traces",
306
- resourceAttributes: {},
307
- headSamplingRate: 1,
308
- minFlushIntervalMs: 0,
309
- fetchImpl,
310
- getActiveSpanForParent: () => stack.get(),
311
- });
312
- const span = tracer.startSpan("deco.cache.lookup");
313
- span.setError?.(new TypeError("boom"));
314
- span.end();
315
- await tracer.flush();
316
-
317
- const payload = calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{
318
- status: { code: number; message?: string };
319
- events: Array<{ name: string; attributes: Array<{ key: string }> }>;
320
- attributes: Array<{ key: string; value: { stringValue: string } }>;
321
- }> }> }> };
322
- const span0 = payload.resourceSpans[0].scopeSpans[0].spans[0];
323
- expect(span0.status.code).toBe(2);
324
- expect(span0.status.message).toBe("boom");
325
- expect(span0.events[0].name).toBe("exception");
326
- expect(span0.attributes.find((a) => a.key === "exception.type")?.value.stringValue).toBe(
327
- "TypeError",
328
- );
329
- });
330
-
331
- it("setAttribute http.status_code >= 400 promotes span to ERROR", async () => {
332
- const { fetchImpl, calls } = captureFetch();
333
- const stack = activeSpanStack();
334
- const tracer = createOtlpHttpTracerAdapter({
335
- endpoint: "https://collector.example/v1/traces",
336
- resourceAttributes: {},
337
- headSamplingRate: 1,
338
- minFlushIntervalMs: 0,
339
- fetchImpl,
340
- getActiveSpanForParent: () => stack.get(),
341
- });
342
-
343
- for (const status of [400, 429, 500, 503]) {
344
- const span = tracer.startSpan("vtex.catalog.search");
345
- span.setAttribute?.("http.status_code", status);
346
- span.end();
347
- }
348
- await tracer.flush();
349
-
350
- const spans = (calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{ status: { code: number; message: string } }> }> }> })
351
- .resourceSpans[0].scopeSpans[0].spans;
352
- for (const span of spans) {
353
- // ERROR = 2
354
- expect(span.status.code).toBe(2);
355
- expect(span.status.message).toMatch(/^HTTP (400|429|500|503)$/);
356
- }
357
- });
358
-
359
- it("setAttribute http.status_code < 400 does not overwrite an existing ERROR status", async () => {
360
- const { fetchImpl, calls } = captureFetch();
361
- const stack = activeSpanStack();
362
- const tracer = createOtlpHttpTracerAdapter({
363
- endpoint: "https://collector.example/v1/traces",
364
- resourceAttributes: {},
365
- headSamplingRate: 1,
366
- minFlushIntervalMs: 0,
367
- fetchImpl,
368
- getActiveSpanForParent: () => stack.get(),
369
- });
370
-
371
- const span = tracer.startSpan("deco.cache.lookup");
372
- span.setError?.(new Error("internal failure"));
373
- // A 200 attribute set afterwards should not clear the ERROR status
374
- span.setAttribute?.("http.status_code", 200);
375
- span.end();
376
- await tracer.flush();
377
-
378
- const span0 = (calls[0].payload as { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{ status: { code: number } }> }> }> })
379
- .resourceSpans[0].scopeSpans[0].spans[0];
380
- expect(span0.status.code).toBe(2);
381
- });
382
-
383
- it("flush is a no-op when the buffer is empty", async () => {
384
- const fetchImpl = vi.fn() as unknown as typeof fetch;
385
- const stack = activeSpanStack();
386
- const tracer = createOtlpHttpTracerAdapter({
387
- endpoint: "https://collector.example/v1/traces",
388
- resourceAttributes: {},
389
- headSamplingRate: 1,
390
- minFlushIntervalMs: 0,
391
- fetchImpl,
392
- getActiveSpanForParent: () => stack.get(),
393
- });
394
- await tracer.flush();
395
- expect(fetchImpl).not.toHaveBeenCalled();
396
- });
397
-
398
- it("respects the cooldown — second flush within window is skipped", async () => {
399
- const { fetchImpl, calls } = captureFetch();
400
- const stack = activeSpanStack();
401
- // Use wall-clock-realistic values: `lastFlushAt` starts at 0, so the
402
- // first flush's `elapsed` needs to exceed `minFlushIntervalMs` to
403
- // get through. That's always true in production where `now() =
404
- // Date.now() ~= 1.7e12`; we model that by starting the fake clock
405
- // at the same scale.
406
- let clock = 1_000_000_000_000;
407
- const tracer = createOtlpHttpTracerAdapter({
408
- endpoint: "https://collector.example/v1/traces",
409
- resourceAttributes: {},
410
- headSamplingRate: 1,
411
- minFlushIntervalMs: 5000,
412
- fetchImpl,
413
- nowMs: () => clock,
414
- getActiveSpanForParent: () => stack.get(),
415
- });
416
- const a = tracer.startSpan("a");
417
- a.end();
418
- clock += 100;
419
- await tracer.flush();
420
- expect(calls).toHaveLength(1);
421
-
422
- const b = tracer.startSpan("b");
423
- b.end();
424
- clock += 100; // 200ms after first flush — still within 5s cooldown
425
- await tracer.flush();
426
- expect(calls).toHaveLength(1); // still one — cooldown blocked it
427
- expect(tracer.pendingSpanCount()).toBe(1);
428
-
429
- clock += 10_000; // past cooldown
430
- await tracer.flush();
431
- expect(calls).toHaveLength(2);
432
- });
433
-
434
- it("calls onError when the buffer overflows", async () => {
435
- const stack = activeSpanStack();
436
- const onError = vi.fn();
437
- const tracer = createOtlpHttpTracerAdapter({
438
- endpoint: "https://collector.example/v1/traces",
439
- resourceAttributes: {},
440
- headSamplingRate: 1,
441
- minFlushIntervalMs: 0,
442
- maxBufferSpans: 2,
443
- fetchImpl: (async () => new Response("", { status: 200 })) as typeof fetch,
444
- getActiveSpanForParent: () => stack.get(),
445
- onError,
446
- });
447
- for (let i = 0; i < 5; i++) {
448
- const s = tracer.startSpan(`s${i}`);
449
- s.end();
450
- }
451
- expect(onError).toHaveBeenCalled();
452
- expect(onError.mock.calls[0][0]).toBe("overflow");
453
- });
454
-
455
- it("calls onError on flush failure (non-2xx)", async () => {
456
- const stack = activeSpanStack();
457
- const onError = vi.fn();
458
- const fetchImpl: typeof fetch = async () => new Response("server explosion", { status: 503 });
459
- const tracer = createOtlpHttpTracerAdapter({
460
- endpoint: "https://collector.example/v1/traces",
461
- resourceAttributes: {},
462
- headSamplingRate: 1,
463
- minFlushIntervalMs: 0,
464
- fetchImpl,
465
- getActiveSpanForParent: () => stack.get(),
466
- onError,
467
- });
468
- const s = tracer.startSpan("x");
469
- s.end();
470
- await tracer.flush();
471
- expect(onError).toHaveBeenCalled();
472
- expect(onError.mock.calls[0][0]).toBe("flush");
473
- });
474
- });
@@ -1,117 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { createReplaceStream } from "./abTesting";
3
-
4
- /**
5
- * The A/B fallback proxy used to buffer the whole upstream body into a JS
6
- * string (two bytes per character) plus the replaced copy, just to swap a
7
- * hostname — megabytes of a 128MB isolate budget. This streams it instead,
8
- * which is only correct if two hazards are handled: a match straddling a chunk
9
- * boundary, and a multi-byte character split across chunks.
10
- */
11
-
12
- const enc = new TextEncoder();
13
-
14
- /** Push `chunks` through the transform and read the whole output back. */
15
- async function run(search: string, replace: string, chunks: string[] | Uint8Array[]) {
16
- const source = new ReadableStream<Uint8Array>({
17
- start(controller) {
18
- for (const c of chunks) {
19
- controller.enqueue(typeof c === "string" ? enc.encode(c) : c);
20
- }
21
- controller.close();
22
- },
23
- });
24
- const out = source.pipeThrough(createReplaceStream(search, replace));
25
- return await new Response(out).text();
26
- }
27
-
28
- describe("createReplaceStream", () => {
29
- it("replaces within a single chunk", async () => {
30
- await expect(run("old.site", "new.site", ["go to old.site now"])).resolves.toBe(
31
- "go to new.site now",
32
- );
33
- });
34
-
35
- it("replaces every occurrence, not just the first", async () => {
36
- await expect(run("a", "X", ["banana"])).resolves.toBe("bXnXnX");
37
- });
38
-
39
- it("replaces a match split across a chunk boundary", async () => {
40
- // The hazard the hold-back exists for.
41
- await expect(run("old.site", "new.site", ["go to old.", "site now"])).resolves.toBe(
42
- "go to new.site now",
43
- );
44
- });
45
-
46
- it("replaces a match split one character at a time", async () => {
47
- await expect(run("abc", "X", [..."1abc2"])).resolves.toBe("1X2");
48
- });
49
-
50
- it("does not re-replace when the replacement ends in a prefix of the search", async () => {
51
- // Held-back text is taken from the RAW input, never from replaced output.
52
- // Otherwise "abc"->"xab" would leave "ab", join the next chunk's "c", and
53
- // be replaced a second time.
54
- await expect(run("abc", "xab", ["abc", "c"])).resolves.toBe("xabc");
55
- });
56
-
57
- it("carries a multi-byte character split across chunks", async () => {
58
- // "ã" is two bytes in UTF-8 — split them.
59
- const bytes = enc.encode("promoção");
60
- const mid = bytes.indexOf(0xc3); // first byte of "ç"
61
- const out = await run("x", "y", [bytes.slice(0, mid + 1), bytes.slice(mid + 1)]);
62
- expect(out).toBe("promoção");
63
- });
64
-
65
- it("passes a body through untouched when nothing matches", async () => {
66
- await expect(run("nope", "!", ["hello ", "world"])).resolves.toBe("hello world");
67
- });
68
-
69
- it("handles an empty body", async () => {
70
- await expect(run("a", "b", [])).resolves.toBe("");
71
- });
72
-
73
- it("handles a match at the very end of the stream", async () => {
74
- // Lands entirely in the held-back tail, so only `flush` can emit it.
75
- await expect(run("end", "END", ["the ", "end"])).resolves.toBe("the END");
76
- });
77
-
78
- it("handles a match at the very start", async () => {
79
- await expect(run("go", "GO", ["go home"])).resolves.toBe("GO home");
80
- });
81
-
82
- it("holds back at most search.length - 1 characters", async () => {
83
- // Peak memory must be one chunk plus a bounded tail, never the body.
84
- const big = "z".repeat(10_000);
85
- await expect(run("old.site", "new.site", [big, "old.site", big])).resolves.toBe(
86
- `${big}new.site${big}`,
87
- );
88
- });
89
-
90
- it("replaces a self-overlapping match that straddles the hold-back cut", async () => {
91
- await expect(run("aaa", "Y", ["xaaaa"])).resolves.toBe("xYa");
92
- await expect(run("aa", "Y", ["aaa", "a"])).resolves.toBe("aaaa".replaceAll("aa", "Y"));
93
- await expect(run("abab", "Y", ["ababab", "ab"])).resolves.toBe("abababab".replaceAll("abab", "Y"));
94
- });
95
-
96
- it("matches native replaceAll over random chunkings", async () => {
97
- let seed = 1;
98
- const rnd = (n: number) => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) % n);
99
- for (let iter = 0; iter < 500; iter++) {
100
- const alpha = "ab\u00e7";
101
- const str = (n: number) => Array.from({ length: n }, () => alpha[rnd(alpha.length)]).join("");
102
- const search = str(1 + rnd(4));
103
- const replace = str(rnd(4));
104
- const text = str(rnd(40));
105
- const bytes = enc.encode(text);
106
- const chunks: Uint8Array[] = [];
107
- for (let p = 0; p < bytes.length; ) {
108
- const n = 1 + rnd(6);
109
- chunks.push(bytes.slice(p, p + n));
110
- p += n;
111
- }
112
- expect(await run(search, replace, chunks), JSON.stringify({ search, replace, text })).toBe(
113
- text.replaceAll(search, replace),
114
- );
115
- }
116
- });
117
- });
@@ -1,29 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- // Import the browser stub explicitly by path. Vitest (no "browser" export
3
- // condition) would otherwise resolve `@decocms/blocks/sdk/requestContextStorage`
4
- // to the real `node:async_hooks`-backed module; here we assert the client-safe
5
- // stand-in that Next.js's client webpack compiler selects via the "browser"
6
- // export condition behaves exactly like the real storage does outside a request
7
- // scope.
8
- import { storage } from "./requestContextStorage.browser";
9
-
10
- describe("requestContextStorage.browser (client-safe stub)", () => {
11
- it("getStore() returns undefined — no per-request async context on the client", () => {
12
- expect(storage.getStore()).toBeUndefined();
13
- });
14
-
15
- it("run() invokes the callback inline and returns its value", () => {
16
- let ran = false;
17
- const result = storage.run({} as never, () => {
18
- ran = true;
19
- return 42;
20
- });
21
- expect(ran).toBe(true);
22
- expect(result).toBe(42);
23
- });
24
-
25
- it("run() does not establish a store — getStore() is still undefined inside the callback", () => {
26
- const inside = storage.run({} as never, () => storage.getStore());
27
- expect(inside).toBeUndefined();
28
- });
29
- });