@decocms/blocks 8.0.0 → 8.1.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 (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. 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,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
- });
@@ -1,73 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { redactUrl } from "./urlRedaction";
3
-
4
- describe("redactUrl", () => {
5
- it("redacts every query value by default", () => {
6
- expect(redactUrl("https://api.test/path?token=abc&page=2")).toBe(
7
- "https://api.test/path?token=REDACTED&page=REDACTED",
8
- );
9
- });
10
-
11
- it("preserves query keys listed in keepQueryKeys", () => {
12
- expect(
13
- redactUrl("https://api.test/path?token=abc&page=2&sort=name", {
14
- keepQueryKeys: ["page", "sort"],
15
- }),
16
- ).toBe("https://api.test/path?token=REDACTED&page=2&sort=name");
17
- });
18
-
19
- it("preserves empty query values verbatim", () => {
20
- expect(redactUrl("https://api.test/path?page=&token=abc")).toBe(
21
- "https://api.test/path?page=&token=REDACTED",
22
- );
23
- });
24
-
25
- it("strips userinfo from authority component", () => {
26
- expect(redactUrl("https://user:secret@api.test/path?x=1")).toBe(
27
- "https://api.test/path?x=REDACTED",
28
- );
29
- });
30
-
31
- it("drops the fragment", () => {
32
- expect(redactUrl("https://api.test/path?x=1#client-only-state-token=abc")).toBe(
33
- "https://api.test/path?x=REDACTED",
34
- );
35
- });
36
-
37
- it("preserves host and path verbatim", () => {
38
- expect(redactUrl("https://api.test/products/12345/details?x=1")).toBe(
39
- "https://api.test/products/12345/details?x=REDACTED",
40
- );
41
- });
42
-
43
- it("falls back to substring-before-? on unparseable URLs", () => {
44
- // Missing scheme — URL constructor throws.
45
- expect(redactUrl("not-a-url?token=abc")).toBe("not-a-url");
46
- });
47
-
48
- it("falls back to substring-before-# on unparseable URLs (no `?`)", () => {
49
- // Fragments can also carry secrets (`#access_token=…` in OAuth implicit
50
- // grant). The defensive path must drop them too.
51
- expect(redactUrl("not-a-url#access_token=abc")).toBe("not-a-url");
52
- });
53
-
54
- it("falls back to whichever of `?` / `#` appears first on unparseable URLs", () => {
55
- expect(redactUrl("not-a-url?x=1#y=2")).toBe("not-a-url");
56
- expect(redactUrl("not-a-url#frag?then=secret")).toBe("not-a-url");
57
- });
58
-
59
- it("returns the raw value when there is no query and the URL is unparseable", () => {
60
- expect(redactUrl("relative/path")).toBe("relative/path");
61
- });
62
-
63
- it("handles URLs without query string unchanged", () => {
64
- expect(redactUrl("https://api.test/products")).toBe("https://api.test/products");
65
- });
66
-
67
- it("redacts multi-value query parameters (e.g. ?fq=a&fq=b)", () => {
68
- // URLSearchParams collapses repeated keys to a single value when .set() is
69
- // called — the OTel guideline accepts this as acceptable cardinality loss.
70
- const out = redactUrl("https://api.test/path?fq=a&fq=b");
71
- expect(out).toBe("https://api.test/path?fq=REDACTED");
72
- });
73
- });