@decocms/blocks 7.71.6 → 8.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
@@ -1,691 +0,0 @@
1
- /**
2
- * Coverage for the public observability surface and `instrumentWorker`.
3
- *
4
- * As of 5.0.0 the framework no longer bundles an in-Worker OTLP exporter
5
- * for logs/metrics. Tests below verify:
6
- * - public exports stay stable (logger, composite helpers, AE adapter,
7
- * observability primitives)
8
- * - `instrumentWorker` is a thin wrapper: bridge tracer + boot logger/meter,
9
- * forward `fetch` to the wrapped handler, no flush registry, no
10
- * `ctx.waitUntil` for telemetry plumbing.
11
- */
12
- import { SpanStatusCode, trace } from "@opentelemetry/api";
13
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14
- import * as composite from "./composite";
15
- import * as logger from "./logger";
16
- import * as observability from "./observability";
17
- import {
18
- _resetBootStateForTests,
19
- flushObservability,
20
- instrumentWorker,
21
- instrumentWorkflowRun,
22
- } from "./otel";
23
- import * as adapters from "./otelAdapters";
24
- import { createClickhouseCollectorAdapter } from "./otelAdapters/clickhouseCollector";
25
-
26
- interface TestEnv extends Record<string, unknown> {
27
- DECO_SITE_NAME?: string;
28
- DECO_METRICS?: { writeDataPoint: () => void };
29
- CF_VERSION_METADATA?: { id: string };
30
- }
31
-
32
- function fakeCtx() {
33
- const waited: Array<Promise<unknown>> = [];
34
- return {
35
- waitUntil: (p: Promise<unknown>) => {
36
- waited.push(p);
37
- },
38
- passThroughOnException: () => {},
39
- waited,
40
- };
41
- }
42
-
43
- describe("observability granular modules", () => {
44
- it("exports the logger surface", () => {
45
- expect(typeof logger.logger.info).toBe("function");
46
- expect(typeof logger.configureLogger).toBe("function");
47
- expect(typeof logger.setLogLevel).toBe("function");
48
- expect(typeof logger.defaultLoggerAdapter.log).toBe("function");
49
- expect(typeof logger.serializeError).toBe("function");
50
- expect(typeof logger.setLoggerAttributeFloor).toBe("function");
51
- });
52
-
53
- it("exports composite helpers", () => {
54
- expect(typeof composite.createCompositeLogger).toBe("function");
55
- expect(typeof composite.createCompositeMeter).toBe("function");
56
- });
57
-
58
- it("exports only the AE adapter factory + runtime env helpers", () => {
59
- expect(typeof adapters.createAnalyticsEngineMeterAdapter).toBe("function");
60
- expect(typeof adapters.setRuntimeEnv).toBe("function");
61
- expect(typeof adapters.getRuntimeEnv).toBe("function");
62
- // OTLP factories + flush registry were removed in 5.0.0.
63
- expect("createOtelLoggerAdapter" in adapters).toBe(false);
64
- expect("createOtelMeterAdapter" in adapters).toBe(false);
65
- expect("flushOtelProviders" in adapters).toBe(false);
66
- expect("registerOtelFlushHandler" in adapters).toBe(false);
67
- });
68
-
69
- it("exports observability primitives from middleware/observability", () => {
70
- expect(typeof observability.withTracing).toBe("function");
71
- expect(typeof observability.recordRequestMetric).toBe("function");
72
- expect(typeof observability.recordCacheMetric).toBe("function");
73
- expect(observability.MetricNames.HTTP_SERVER_REQUEST_DURATION).toBe(
74
- "http.server.request.duration",
75
- );
76
- expect(observability.MetricNames.RESOLVE_DURATION).toBe("deco.cms.resolve.duration");
77
- });
78
-
79
- it("ClickHouse collector adapter is a documented stub that throws", () => {
80
- expect(() =>
81
- createClickhouseCollectorAdapter({ endpoint: "https://otel-collector.internal" }),
82
- ).toThrow(/not implemented/i);
83
- });
84
- });
85
-
86
- describe("instrumentWorker — CF-native default boot", () => {
87
- beforeEach(() => {
88
- _resetBootStateForTests();
89
- });
90
-
91
- afterEach(() => {
92
- _resetBootStateForTests();
93
- });
94
-
95
- it("forwards fetch to the wrapped handler", async () => {
96
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
97
- const wrapped = instrumentWorker(handler);
98
-
99
- const env: TestEnv = {};
100
- const ctx = fakeCtx();
101
- const res = await wrapped.fetch(new Request("https://example.test/"), env, ctx);
102
-
103
- expect(handler.fetch).toHaveBeenCalledOnce();
104
- expect(await res.text()).toBe("ok");
105
- // No flush registry anymore — instrumentWorker should NOT push anything
106
- // into ctx.waitUntil for telemetry plumbing.
107
- expect(ctx.waited).toHaveLength(0);
108
- });
109
-
110
- it("does not call ctx.waitUntil even when the handler throws", async () => {
111
- const handler = { fetch: vi.fn().mockRejectedValue(new Error("boom")) };
112
- const wrapped = instrumentWorker(handler);
113
-
114
- const env: TestEnv = {};
115
- const ctx = fakeCtx();
116
- await expect(wrapped.fetch(new Request("https://example.test/"), env, ctx)).rejects.toThrow(
117
- "boom",
118
- );
119
- expect(ctx.waited).toHaveLength(0);
120
- });
121
-
122
- it("boot is idempotent across requests", async () => {
123
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
124
- const wrapped = instrumentWorker(handler, { decoRuntimeVersion: "5.0.0-test" });
125
-
126
- const env: TestEnv = {};
127
- for (let i = 0; i < 3; i++) {
128
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
129
- }
130
-
131
- expect(handler.fetch).toHaveBeenCalledTimes(3);
132
- });
133
-
134
- it("AE meter is wired without OTLP when DECO_METRICS binding is present", async () => {
135
- const writeDataPoint = vi.fn();
136
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
137
- const wrapped = instrumentWorker(handler);
138
-
139
- const env: TestEnv = { DECO_METRICS: { writeDataPoint } };
140
- const ctx = fakeCtx();
141
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
142
-
143
- // AE adapter does not register flush handlers (writeDataPoint is
144
- // fire-and-forget), so ctx.waitUntil stays empty even with AE wired.
145
- expect(ctx.waited).toHaveLength(0);
146
- });
147
-
148
- it("accepts a function for options so site code can read env at boot time", async () => {
149
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
150
- const wrapped = instrumentWorker(handler, (env) => ({
151
- serviceName: (env.DECO_SITE_NAME as string) ?? "fallback",
152
- }));
153
-
154
- const env: TestEnv = { DECO_SITE_NAME: "my-store-test" };
155
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
156
-
157
- expect(handler.fetch).toHaveBeenCalledOnce();
158
- });
159
- });
160
-
161
- describe("instrumentWorker — identity floor", () => {
162
- beforeEach(() => {
163
- _resetBootStateForTests();
164
- });
165
-
166
- afterEach(() => {
167
- _resetBootStateForTests();
168
- });
169
-
170
- it("stamps service.name and service.version on the logger floor", async () => {
171
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
172
- const wrapped = instrumentWorker(handler, { serviceName: "acme-tanstack" });
173
-
174
- const env: TestEnv = { CF_VERSION_METADATA: { id: "abc123" } };
175
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
176
-
177
- const floor = logger._getLoggerAttributeFloorForTests();
178
- expect(floor["service.name"]).toBe("acme-tanstack");
179
- expect(floor["service.version"]).toBe("abc123");
180
- });
181
-
182
- it("falls back to DECO_SITE_NAME for service.name", async () => {
183
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
184
- const wrapped = instrumentWorker(handler);
185
-
186
- const env: TestEnv = { DECO_SITE_NAME: "fallback-site" };
187
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
188
-
189
- const floor = logger._getLoggerAttributeFloorForTests();
190
- expect(floor["service.name"]).toBe("fallback-site");
191
- });
192
-
193
- it("omits service.version when CF_VERSION_METADATA is absent", async () => {
194
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
195
- const wrapped = instrumentWorker(handler, { serviceName: "no-version-site" });
196
-
197
- const env: TestEnv = {};
198
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
199
-
200
- const floor = logger._getLoggerAttributeFloorForTests();
201
- expect("service.version" in floor).toBe(false);
202
- });
203
- });
204
-
205
- describe("instrumentWorker — tracer bridge", () => {
206
- beforeEach(() => {
207
- _resetBootStateForTests();
208
- });
209
-
210
- afterEach(() => {
211
- _resetBootStateForTests();
212
- observability.configureTracer({
213
- startSpan: () => ({ end: () => {} }),
214
- });
215
- // installBridgeWithFakeOtelSpan() below uses vi.spyOn(trace, "getTracer").
216
- // Without restoring, that spy leaks into any later test that touches the
217
- // real OTel API.
218
- vi.restoreAllMocks();
219
- });
220
-
221
- function installBridgeWithFakeOtelSpan() {
222
- const span = {
223
- end: vi.fn(),
224
- recordException: vi.fn(),
225
- setStatus: vi.fn(),
226
- setAttribute: vi.fn(),
227
- spanContext: vi.fn(() => ({
228
- traceId: "0123456789abcdef0123456789abcdef",
229
- spanId: "fedcba9876543210",
230
- traceFlags: 1,
231
- })),
232
- };
233
- const getTracer = vi.spyOn(trace, "getTracer").mockReturnValue({
234
- startSpan: () => span,
235
- startActiveSpan: () => undefined,
236
- } as unknown as ReturnType<typeof trace.getTracer>);
237
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
238
- const wrapped = instrumentWorker(handler);
239
- return { span, wrapped, getTracer };
240
- }
241
-
242
- it("setError sets SpanStatusCode.ERROR and records exception", async () => {
243
- const { span, wrapped } = installBridgeWithFakeOtelSpan();
244
- await wrapped.fetch(new Request("https://example.test/"), {}, fakeCtx());
245
-
246
- // Drive a span through the bridge via withTracing.
247
- await expect(
248
- observability.withTracing("t", async () => {
249
- throw new Error("boom");
250
- }),
251
- ).rejects.toThrow("boom");
252
-
253
- expect(span.recordException).toHaveBeenCalledOnce();
254
- expect(span.setStatus).toHaveBeenCalledWith({
255
- code: SpanStatusCode.ERROR,
256
- message: "boom",
257
- });
258
- });
259
-
260
- it("setError sets ERROR status for non-Error throws too", async () => {
261
- const { span, wrapped } = installBridgeWithFakeOtelSpan();
262
- await wrapped.fetch(new Request("https://example.test/"), {}, fakeCtx());
263
-
264
- await expect(
265
- observability.withTracing("t", async () => {
266
- throw "string-error";
267
- }),
268
- ).rejects.toBe("string-error");
269
-
270
- expect(span.recordException).not.toHaveBeenCalled();
271
- expect(span.setStatus).toHaveBeenCalledWith({
272
- code: SpanStatusCode.ERROR,
273
- message: "string-error",
274
- });
275
- });
276
-
277
- it("spanContext round-trips traceId/spanId/traceFlags", async () => {
278
- const { wrapped } = installBridgeWithFakeOtelSpan();
279
- await wrapped.fetch(new Request("https://example.test/"), {}, fakeCtx());
280
-
281
- const tracer = observability.getTracer();
282
- const span = tracer?.startSpan("t");
283
- expect(span?.spanContext?.()).toEqual({
284
- traceId: "0123456789abcdef0123456789abcdef",
285
- spanId: "fedcba9876543210",
286
- traceFlags: 1,
287
- });
288
- });
289
- });
290
-
291
- describe("instrumentWorker — OTLP/HTTP metrics exporter wiring", () => {
292
- beforeEach(() => {
293
- _resetBootStateForTests();
294
- });
295
-
296
- afterEach(() => {
297
- _resetBootStateForTests();
298
- vi.restoreAllMocks();
299
- });
300
-
301
- function makeFetchSpy() {
302
- const calls: Array<{ url: string; body: string }> = [];
303
- const impl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
304
- calls.push({ url: String(input), body: String(init?.body ?? "") });
305
- return new Response("{}", { status: 200 });
306
- });
307
- return { impl: impl as unknown as typeof fetch, calls };
308
- }
309
-
310
- it("wires the OTLP meter only when DECO_OTEL_METRICS_ENDPOINT is set on env", async () => {
311
- const { impl } = makeFetchSpy();
312
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
313
- const wrapped = instrumentWorker(handler, {
314
- serviceName: "smoke-site",
315
- otlpMetricsFetchImpl: impl,
316
- });
317
-
318
- // Without the env var, no flush is enqueued via ctx.waitUntil.
319
- const ctxNoEndpoint = fakeCtx();
320
- await wrapped.fetch(new Request("https://example.test/"), {}, ctxNoEndpoint);
321
- expect(ctxNoEndpoint.waited).toHaveLength(0);
322
- });
323
-
324
- it("records metrics + flushes via ctx.waitUntil at request end", async () => {
325
- const { impl, calls } = makeFetchSpy();
326
- const handler = {
327
- fetch: vi.fn(async () => {
328
- observability.recordRequestMetric("GET", "/p/123", 200, 42);
329
- return new Response("ok");
330
- }),
331
- };
332
- const wrapped = instrumentWorker(handler, {
333
- serviceName: "smoke-site",
334
- otlpMetricsFetchImpl: impl,
335
- });
336
-
337
- const env: TestEnv = {
338
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
339
- } as TestEnv & { DECO_OTEL_METRICS_ENDPOINT: string };
340
- const ctx = fakeCtx();
341
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
342
-
343
- // ctx.waitUntil was used to drain the buffer.
344
- expect(ctx.waited).toHaveLength(1);
345
- await Promise.all(ctx.waited);
346
-
347
- // Exactly one POST to the configured endpoint.
348
- expect(calls).toHaveLength(1);
349
- expect(calls[0].url).toBe("https://ingest.test/v1/metrics");
350
-
351
- // Payload carries the resource floor and at least the canonical
352
- // `http.server.request.duration` histogram that recordRequestMetric emits.
353
- const payload = JSON.parse(calls[0].body) as {
354
- resourceMetrics: Array<{
355
- resource: { attributes: Array<{ key: string; value: { stringValue: string } }> };
356
- scopeMetrics: Array<{ metrics: Array<{ name: string }> }>;
357
- }>;
358
- };
359
- const attrs = payload.resourceMetrics[0].resource.attributes;
360
- expect(attrs).toContainEqual({
361
- key: "service.name",
362
- value: { stringValue: "smoke-site" },
363
- });
364
- const names = payload.resourceMetrics[0].scopeMetrics[0].metrics.map((m) => m.name);
365
- expect(names).toContain("http.server.request.duration");
366
- });
367
-
368
- it("otlpMetricsEnabled=false disables the OTLP meter even when env is set", async () => {
369
- const { impl, calls } = makeFetchSpy();
370
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
371
- const wrapped = instrumentWorker(handler, {
372
- otlpMetricsEnabled: false,
373
- otlpMetricsFetchImpl: impl,
374
- });
375
-
376
- const env: TestEnv = {
377
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
378
- } as TestEnv & { DECO_OTEL_METRICS_ENDPOINT: string };
379
- const ctx = fakeCtx();
380
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
381
-
382
- expect(ctx.waited).toHaveLength(0);
383
- expect(calls).toHaveLength(0);
384
- });
385
-
386
- it("falling back to handler.fetch failure still triggers a flush", async () => {
387
- const { impl } = makeFetchSpy();
388
- const handler = { fetch: vi.fn().mockRejectedValue(new Error("boom")) };
389
- const wrapped = instrumentWorker(handler, {
390
- otlpMetricsFetchImpl: impl,
391
- });
392
-
393
- const env: TestEnv = {
394
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
395
- } as TestEnv & { DECO_OTEL_METRICS_ENDPOINT: string };
396
- const ctx = fakeCtx();
397
- await expect(
398
- wrapped.fetch(new Request("https://example.test/"), env, ctx),
399
- ).rejects.toThrow("boom");
400
-
401
- expect(ctx.waited).toHaveLength(1);
402
- });
403
- });
404
-
405
- describe("instrumentWorker — OTLP/HTTP error-log channel wiring", () => {
406
- beforeEach(() => {
407
- _resetBootStateForTests();
408
- });
409
-
410
- afterEach(() => {
411
- _resetBootStateForTests();
412
- vi.restoreAllMocks();
413
- });
414
-
415
- function makeFetchSpy() {
416
- const calls: Array<{ url: string; body: string }> = [];
417
- const impl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
418
- calls.push({ url: String(input), body: String(init?.body ?? "") });
419
- return new Response("{}", { status: 200 });
420
- });
421
- return { impl: impl as unknown as typeof fetch, calls };
422
- }
423
-
424
- it("routes logger.error through the direct-POST channel when env is set", async () => {
425
- const { impl, calls } = makeFetchSpy();
426
- const handler = {
427
- fetch: vi.fn(async () => {
428
- logger.logger.error("payment failed", { stage: "checkout", reason: "declined" });
429
- return new Response("ok");
430
- }),
431
- };
432
- const wrapped = instrumentWorker(handler, {
433
- serviceName: "smoke-site",
434
- otlpLogsFetchImpl: impl,
435
- });
436
-
437
- const env: TestEnv = {
438
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
439
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
440
- const ctx = fakeCtx();
441
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
442
-
443
- // ctx.waitUntil(flushErrors) was queued.
444
- expect(ctx.waited.length).toBeGreaterThanOrEqual(1);
445
- await Promise.all(ctx.waited);
446
-
447
- expect(calls).toHaveLength(1);
448
- expect(calls[0].url).toBe("https://ingest.test/v1/logs");
449
- const payload = JSON.parse(calls[0].body) as {
450
- resourceLogs: Array<{
451
- scopeLogs: Array<{
452
- logRecords: Array<{ severityText: string; body: { stringValue: string } }>;
453
- }>;
454
- }>;
455
- };
456
- const rec = payload.resourceLogs[0].scopeLogs[0].logRecords[0];
457
- expect(rec.severityText).toBe("error");
458
- expect(rec.body.stringValue).toBe("payment failed");
459
- });
460
-
461
- it("debug calls do NOT trigger a direct POST (below default info minLevel)", async () => {
462
- const { impl, calls } = makeFetchSpy();
463
- const handler = {
464
- fetch: vi.fn(async () => {
465
- logger.logger.debug("debug msg");
466
- return new Response("ok");
467
- }),
468
- };
469
- const wrapped = instrumentWorker(handler, {
470
- otlpLogsFetchImpl: impl,
471
- });
472
-
473
- const env: TestEnv = {
474
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
475
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
476
- const ctx = fakeCtx();
477
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
478
- await Promise.all(ctx.waited);
479
-
480
- expect(calls).toHaveLength(0);
481
- });
482
-
483
- it("info calls DO trigger a direct POST (at default info minLevel)", async () => {
484
- const { impl, calls } = makeFetchSpy();
485
- const handler = {
486
- fetch: vi.fn(async () => {
487
- logger.logger.info("section loaded");
488
- return new Response("ok");
489
- }),
490
- };
491
- const wrapped = instrumentWorker(handler, {
492
- otlpLogsFetchImpl: impl,
493
- });
494
-
495
- const env: TestEnv = {
496
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
497
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
498
- const ctx = fakeCtx();
499
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
500
- await Promise.all(ctx.waited);
501
-
502
- expect(calls).toHaveLength(1);
503
- const payload = JSON.parse(calls[0].body) as {
504
- resourceLogs: Array<{ scopeLogs: Array<{ logRecords: Array<{ severityText: string }> }> }>;
505
- };
506
- expect(payload.resourceLogs[0].scopeLogs[0].logRecords[0].severityText).toBe("info");
507
- });
508
-
509
- async function shipConsoleError(...args: unknown[]): Promise<string> {
510
- const { impl, calls } = makeFetchSpy();
511
- const handler = {
512
- fetch: vi.fn(async () => {
513
- console.error(...args);
514
- return new Response("ok");
515
- }),
516
- };
517
- const wrapped = instrumentWorker(handler, {
518
- otlpLogsFetchImpl: impl,
519
- });
520
-
521
- const env: TestEnv = {
522
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
523
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
524
- const ctx = fakeCtx();
525
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
526
- await Promise.all(ctx.waited);
527
-
528
- expect(calls).toHaveLength(1);
529
- const payload = JSON.parse(calls[0].body) as {
530
- resourceLogs: Array<{
531
- scopeLogs: Array<{ logRecords: Array<{ body: { stringValue: string } }> }>;
532
- }>;
533
- };
534
- return payload.resourceLogs[0].scopeLogs[0].logRecords[0].body.stringValue;
535
- }
536
-
537
- it("console.error(err) ships message and stack, not \"{}\"", async () => {
538
- const body = await shipConsoleError("[VTEX] PLP error:", new TypeError("boom"));
539
- expect(body).toContain("[VTEX] PLP error: TypeError: boom");
540
- expect(body).toMatch(/TypeError: boom\n\s+at /); // stack frames shipped
541
- expect(body).not.toContain("{}");
542
- });
543
-
544
- it("keeps enumerable fields of an Error subclass", async () => {
545
- const err = Object.assign(new Error("circuit open"), { host: "x.vtex.com", status: 503 });
546
- const body = await shipConsoleError(err);
547
- expect(body).toContain("Error: circuit open");
548
- expect(body).toContain('{"host":"x.vtex.com","status":503}');
549
- });
550
-
551
- it("expands errors nested in objects and arrays", async () => {
552
- const body = await shipConsoleError({ error: new Error("nested") }, [new RangeError("in array")]);
553
- expect(body).toContain('"message":"nested"');
554
- expect(body).toContain('"name":"RangeError","message":"in array"');
555
- expect(body).not.toContain('{"error":{}}');
556
- });
557
-
558
- it("formats error-like values that are not instanceof Error", async () => {
559
- const domLike = { name: "AbortError", message: "aborted", stack: "AbortError: aborted\n at x" };
560
- const body = await shipConsoleError(domLike);
561
- expect(body).toBe("AbortError: aborted\n at x");
562
- });
563
-
564
- it("otlpLogsEnabled=false disables the channel even when env is set", async () => {
565
- const { impl, calls } = makeFetchSpy();
566
- const handler = {
567
- fetch: vi.fn(async () => {
568
- logger.logger.error("boom");
569
- return new Response("ok");
570
- }),
571
- };
572
- const wrapped = instrumentWorker(handler, {
573
- otlpLogsEnabled: false,
574
- otlpLogsFetchImpl: impl,
575
- });
576
-
577
- const env: TestEnv = {
578
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
579
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
580
- const ctx = fakeCtx();
581
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
582
- await Promise.all(ctx.waited);
583
-
584
- expect(calls).toHaveLength(0);
585
- });
586
- });
587
-
588
- describe("instrumentWorkflowRun / flushObservability — Workflow entrypoints", () => {
589
- beforeEach(() => {
590
- _resetBootStateForTests();
591
- });
592
-
593
- afterEach(() => {
594
- _resetBootStateForTests();
595
- });
596
-
597
- it("flushObservability resolves without throwing when no adapters are configured", async () => {
598
- await expect(flushObservability()).resolves.toBeUndefined();
599
- });
600
-
601
- it("instrumentWorkflowRun returns fn's result and does not throw with no OTel env vars set", async () => {
602
- const fn = vi.fn().mockResolvedValue("step-result");
603
- const result = await instrumentWorkflowRun({}, undefined, fn);
604
-
605
- expect(result).toBe("step-result");
606
- expect(fn).toHaveBeenCalledOnce();
607
- });
608
-
609
- function makeFetchSpy() {
610
- const calls: Array<{ url: string; body: string }> = [];
611
- const impl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
612
- calls.push({ url: String(input), body: String(init?.body ?? "") });
613
- return new Response("{}", { status: 200 });
614
- });
615
- return { impl: impl as unknown as typeof fetch, calls };
616
- }
617
-
618
- it("rethrows fn's rejection but still flushes buffered metrics", async () => {
619
- const { impl, calls } = makeFetchSpy();
620
- const fn = vi.fn(async () => {
621
- observability.recordRequestMetric("WORKFLOW", "/batch-product", 500, 9);
622
- throw new Error("workflow step failed");
623
- });
624
- const env = { DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics" };
625
-
626
- await expect(
627
- instrumentWorkflowRun(env, { otlpMetricsFetchImpl: impl }, fn),
628
- ).rejects.toThrow("workflow step failed");
629
-
630
- expect(calls).toHaveLength(1);
631
- expect(calls[0].url).toBe("https://ingest.test/v1/metrics");
632
- });
633
-
634
- it("still flushes when fn throws synchronously instead of returning a rejected promise", async () => {
635
- const { impl, calls } = makeFetchSpy();
636
- const fn = vi.fn(() => {
637
- observability.recordRequestMetric("WORKFLOW", "/batch-product", 500, 9);
638
- throw new Error("sync boom");
639
- }) as unknown as () => Promise<string>;
640
- const env = { DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics" };
641
-
642
- await expect(
643
- instrumentWorkflowRun(env, { otlpMetricsFetchImpl: impl }, fn),
644
- ).rejects.toThrow("sync boom");
645
-
646
- expect(calls).toHaveLength(1);
647
- });
648
-
649
- it("wires and flushes the OTLP metrics exporter, same as instrumentWorker's channel", async () => {
650
- const { impl, calls } = makeFetchSpy();
651
- const fn = vi.fn(async () => {
652
- observability.recordRequestMetric("WORKFLOW", "/batch-product", 200, 12);
653
- return "done";
654
- });
655
-
656
- const env = {
657
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
658
- } as unknown as Record<string, unknown>;
659
-
660
- const result = await instrumentWorkflowRun(
661
- env,
662
- { serviceName: "workflow-smoke", otlpMetricsFetchImpl: impl },
663
- fn,
664
- );
665
-
666
- expect(result).toBe("done");
667
- expect(calls).toHaveLength(1);
668
- expect(calls[0].url).toBe("https://ingest.test/v1/metrics");
669
- });
670
-
671
- it("forces the flush past the per-isolate cooldown across consecutive replay legs", async () => {
672
- // Regression test: instrumentWorkflowRun forces its exit-time flush past
673
- // the ~5s default cooldown each OTLP adapter otherwise enforces, since a
674
- // Workflow run() only gets one flush attempt per leg — no next request
675
- // to retry on like a fetch handler has.
676
- const { impl, calls } = makeFetchSpy();
677
- const env = { DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics" };
678
- const opts = { otlpMetricsFetchImpl: impl };
679
-
680
- await instrumentWorkflowRun(env, opts, async () => {
681
- observability.recordRequestMetric("WORKFLOW", "/leg-1", 200, 5);
682
- });
683
- // A second replay leg immediately after — well within the default
684
- // cooldown window — must still flush, not get silently skipped.
685
- await instrumentWorkflowRun(env, opts, async () => {
686
- observability.recordRequestMetric("WORKFLOW", "/leg-2", 200, 5);
687
- });
688
-
689
- expect(calls).toHaveLength(2);
690
- });
691
- });