@decocms/blocks 8.0.0 → 8.1.0-next.1

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 (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -1,526 +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 { _resetBootStateForTests, instrumentWorker } from "./otel";
18
- import * as adapters from "./otelAdapters";
19
- import { createClickhouseCollectorAdapter } from "./otelAdapters/clickhouseCollector";
20
-
21
- interface TestEnv extends Record<string, unknown> {
22
- DECO_SITE_NAME?: string;
23
- DECO_METRICS?: { writeDataPoint: () => void };
24
- CF_VERSION_METADATA?: { id: string };
25
- }
26
-
27
- function fakeCtx() {
28
- const waited: Array<Promise<unknown>> = [];
29
- return {
30
- waitUntil: (p: Promise<unknown>) => {
31
- waited.push(p);
32
- },
33
- passThroughOnException: () => {},
34
- waited,
35
- };
36
- }
37
-
38
- describe("observability granular modules", () => {
39
- it("exports the logger surface", () => {
40
- expect(typeof logger.logger.info).toBe("function");
41
- expect(typeof logger.configureLogger).toBe("function");
42
- expect(typeof logger.setLogLevel).toBe("function");
43
- expect(typeof logger.defaultLoggerAdapter.log).toBe("function");
44
- expect(typeof logger.serializeError).toBe("function");
45
- expect(typeof logger.setLoggerAttributeFloor).toBe("function");
46
- });
47
-
48
- it("exports composite helpers", () => {
49
- expect(typeof composite.createCompositeLogger).toBe("function");
50
- expect(typeof composite.createCompositeMeter).toBe("function");
51
- });
52
-
53
- it("exports only the AE adapter factory + runtime env helpers", () => {
54
- expect(typeof adapters.createAnalyticsEngineMeterAdapter).toBe("function");
55
- expect(typeof adapters.setRuntimeEnv).toBe("function");
56
- expect(typeof adapters.getRuntimeEnv).toBe("function");
57
- // OTLP factories + flush registry were removed in 5.0.0.
58
- expect("createOtelLoggerAdapter" in adapters).toBe(false);
59
- expect("createOtelMeterAdapter" in adapters).toBe(false);
60
- expect("flushOtelProviders" in adapters).toBe(false);
61
- expect("registerOtelFlushHandler" in adapters).toBe(false);
62
- });
63
-
64
- it("exports observability primitives from middleware/observability", () => {
65
- expect(typeof observability.withTracing).toBe("function");
66
- expect(typeof observability.recordRequestMetric).toBe("function");
67
- expect(typeof observability.recordCacheMetric).toBe("function");
68
- expect(observability.MetricNames.HTTP_SERVER_REQUEST_DURATION).toBe(
69
- "http.server.request.duration",
70
- );
71
- expect(observability.MetricNames.RESOLVE_DURATION).toBe("deco.cms.resolve.duration");
72
- });
73
-
74
- it("ClickHouse collector adapter is a documented stub that throws", () => {
75
- expect(() =>
76
- createClickhouseCollectorAdapter({ endpoint: "https://otel-collector.internal" }),
77
- ).toThrow(/not implemented/i);
78
- });
79
- });
80
-
81
- describe("instrumentWorker — CF-native default boot", () => {
82
- beforeEach(() => {
83
- _resetBootStateForTests();
84
- });
85
-
86
- afterEach(() => {
87
- _resetBootStateForTests();
88
- });
89
-
90
- it("forwards fetch to the wrapped handler", async () => {
91
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
92
- const wrapped = instrumentWorker(handler);
93
-
94
- const env: TestEnv = {};
95
- const ctx = fakeCtx();
96
- const res = await wrapped.fetch(new Request("https://example.test/"), env, ctx);
97
-
98
- expect(handler.fetch).toHaveBeenCalledOnce();
99
- expect(await res.text()).toBe("ok");
100
- // No flush registry anymore — instrumentWorker should NOT push anything
101
- // into ctx.waitUntil for telemetry plumbing.
102
- expect(ctx.waited).toHaveLength(0);
103
- });
104
-
105
- it("does not call ctx.waitUntil even when the handler throws", async () => {
106
- const handler = { fetch: vi.fn().mockRejectedValue(new Error("boom")) };
107
- const wrapped = instrumentWorker(handler);
108
-
109
- const env: TestEnv = {};
110
- const ctx = fakeCtx();
111
- await expect(wrapped.fetch(new Request("https://example.test/"), env, ctx)).rejects.toThrow(
112
- "boom",
113
- );
114
- expect(ctx.waited).toHaveLength(0);
115
- });
116
-
117
- it("boot is idempotent across requests", async () => {
118
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
119
- const wrapped = instrumentWorker(handler, { decoRuntimeVersion: "5.0.0-test" });
120
-
121
- const env: TestEnv = {};
122
- for (let i = 0; i < 3; i++) {
123
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
124
- }
125
-
126
- expect(handler.fetch).toHaveBeenCalledTimes(3);
127
- });
128
-
129
- it("AE meter is wired without OTLP when DECO_METRICS binding is present", async () => {
130
- const writeDataPoint = vi.fn();
131
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
132
- const wrapped = instrumentWorker(handler);
133
-
134
- const env: TestEnv = { DECO_METRICS: { writeDataPoint } };
135
- const ctx = fakeCtx();
136
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
137
-
138
- // AE adapter does not register flush handlers (writeDataPoint is
139
- // fire-and-forget), so ctx.waitUntil stays empty even with AE wired.
140
- expect(ctx.waited).toHaveLength(0);
141
- });
142
-
143
- it("accepts a function for options so site code can read env at boot time", async () => {
144
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
145
- const wrapped = instrumentWorker(handler, (env) => ({
146
- serviceName: (env.DECO_SITE_NAME as string) ?? "fallback",
147
- }));
148
-
149
- const env: TestEnv = { DECO_SITE_NAME: "my-store-test" };
150
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
151
-
152
- expect(handler.fetch).toHaveBeenCalledOnce();
153
- });
154
- });
155
-
156
- describe("instrumentWorker — identity floor", () => {
157
- beforeEach(() => {
158
- _resetBootStateForTests();
159
- });
160
-
161
- afterEach(() => {
162
- _resetBootStateForTests();
163
- });
164
-
165
- it("stamps service.name and service.version on the logger floor", async () => {
166
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
167
- const wrapped = instrumentWorker(handler, { serviceName: "casaevideo-tanstack" });
168
-
169
- const env: TestEnv = { CF_VERSION_METADATA: { id: "abc123" } };
170
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
171
-
172
- const floor = logger._getLoggerAttributeFloorForTests();
173
- expect(floor["service.name"]).toBe("casaevideo-tanstack");
174
- expect(floor["service.version"]).toBe("abc123");
175
- });
176
-
177
- it("falls back to DECO_SITE_NAME for service.name", async () => {
178
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
179
- const wrapped = instrumentWorker(handler);
180
-
181
- const env: TestEnv = { DECO_SITE_NAME: "fallback-site" };
182
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
183
-
184
- const floor = logger._getLoggerAttributeFloorForTests();
185
- expect(floor["service.name"]).toBe("fallback-site");
186
- });
187
-
188
- it("omits service.version when CF_VERSION_METADATA is absent", async () => {
189
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
190
- const wrapped = instrumentWorker(handler, { serviceName: "no-version-site" });
191
-
192
- const env: TestEnv = {};
193
- await wrapped.fetch(new Request("https://example.test/"), env, fakeCtx());
194
-
195
- const floor = logger._getLoggerAttributeFloorForTests();
196
- expect("service.version" in floor).toBe(false);
197
- });
198
- });
199
-
200
- describe("instrumentWorker — tracer bridge", () => {
201
- beforeEach(() => {
202
- _resetBootStateForTests();
203
- });
204
-
205
- afterEach(() => {
206
- _resetBootStateForTests();
207
- observability.configureTracer({
208
- startSpan: () => ({ end: () => {} }),
209
- });
210
- // installBridgeWithFakeOtelSpan() below uses vi.spyOn(trace, "getTracer").
211
- // Without restoring, that spy leaks into any later test that touches the
212
- // real OTel API.
213
- vi.restoreAllMocks();
214
- });
215
-
216
- function installBridgeWithFakeOtelSpan() {
217
- const span = {
218
- end: vi.fn(),
219
- recordException: vi.fn(),
220
- setStatus: vi.fn(),
221
- setAttribute: vi.fn(),
222
- spanContext: vi.fn(() => ({
223
- traceId: "0123456789abcdef0123456789abcdef",
224
- spanId: "fedcba9876543210",
225
- traceFlags: 1,
226
- })),
227
- };
228
- const getTracer = vi.spyOn(trace, "getTracer").mockReturnValue({
229
- startSpan: () => span,
230
- startActiveSpan: () => undefined,
231
- } as unknown as ReturnType<typeof trace.getTracer>);
232
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
233
- const wrapped = instrumentWorker(handler);
234
- return { span, wrapped, getTracer };
235
- }
236
-
237
- it("setError sets SpanStatusCode.ERROR and records exception", async () => {
238
- const { span, wrapped } = installBridgeWithFakeOtelSpan();
239
- await wrapped.fetch(new Request("https://example.test/"), {}, fakeCtx());
240
-
241
- // Drive a span through the bridge via withTracing.
242
- await expect(
243
- observability.withTracing("t", async () => {
244
- throw new Error("boom");
245
- }),
246
- ).rejects.toThrow("boom");
247
-
248
- expect(span.recordException).toHaveBeenCalledOnce();
249
- expect(span.setStatus).toHaveBeenCalledWith({
250
- code: SpanStatusCode.ERROR,
251
- message: "boom",
252
- });
253
- });
254
-
255
- it("setError sets ERROR status for non-Error throws too", async () => {
256
- const { span, wrapped } = installBridgeWithFakeOtelSpan();
257
- await wrapped.fetch(new Request("https://example.test/"), {}, fakeCtx());
258
-
259
- await expect(
260
- observability.withTracing("t", async () => {
261
- throw "string-error";
262
- }),
263
- ).rejects.toBe("string-error");
264
-
265
- expect(span.recordException).not.toHaveBeenCalled();
266
- expect(span.setStatus).toHaveBeenCalledWith({
267
- code: SpanStatusCode.ERROR,
268
- message: "string-error",
269
- });
270
- });
271
-
272
- it("spanContext round-trips traceId/spanId/traceFlags", async () => {
273
- const { wrapped } = installBridgeWithFakeOtelSpan();
274
- await wrapped.fetch(new Request("https://example.test/"), {}, fakeCtx());
275
-
276
- const tracer = observability.getTracer();
277
- const span = tracer?.startSpan("t");
278
- expect(span?.spanContext?.()).toEqual({
279
- traceId: "0123456789abcdef0123456789abcdef",
280
- spanId: "fedcba9876543210",
281
- traceFlags: 1,
282
- });
283
- });
284
- });
285
-
286
- describe("instrumentWorker — OTLP/HTTP metrics exporter wiring", () => {
287
- beforeEach(() => {
288
- _resetBootStateForTests();
289
- });
290
-
291
- afterEach(() => {
292
- _resetBootStateForTests();
293
- vi.restoreAllMocks();
294
- });
295
-
296
- function makeFetchSpy() {
297
- const calls: Array<{ url: string; body: string }> = [];
298
- const impl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
299
- calls.push({ url: String(input), body: String(init?.body ?? "") });
300
- return new Response("{}", { status: 200 });
301
- });
302
- return { impl: impl as unknown as typeof fetch, calls };
303
- }
304
-
305
- it("wires the OTLP meter only when DECO_OTEL_METRICS_ENDPOINT is set on env", async () => {
306
- const { impl } = makeFetchSpy();
307
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
308
- const wrapped = instrumentWorker(handler, {
309
- serviceName: "smoke-site",
310
- otlpMetricsFetchImpl: impl,
311
- });
312
-
313
- // Without the env var, no flush is enqueued via ctx.waitUntil.
314
- const ctxNoEndpoint = fakeCtx();
315
- await wrapped.fetch(new Request("https://example.test/"), {}, ctxNoEndpoint);
316
- expect(ctxNoEndpoint.waited).toHaveLength(0);
317
- });
318
-
319
- it("records metrics + flushes via ctx.waitUntil at request end", async () => {
320
- const { impl, calls } = makeFetchSpy();
321
- const handler = {
322
- fetch: vi.fn(async () => {
323
- observability.recordRequestMetric("GET", "/p/123", 200, 42);
324
- return new Response("ok");
325
- }),
326
- };
327
- const wrapped = instrumentWorker(handler, {
328
- serviceName: "smoke-site",
329
- otlpMetricsFetchImpl: impl,
330
- });
331
-
332
- const env: TestEnv = {
333
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
334
- } as TestEnv & { DECO_OTEL_METRICS_ENDPOINT: string };
335
- const ctx = fakeCtx();
336
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
337
-
338
- // ctx.waitUntil was used to drain the buffer.
339
- expect(ctx.waited).toHaveLength(1);
340
- await Promise.all(ctx.waited);
341
-
342
- // Exactly one POST to the configured endpoint.
343
- expect(calls).toHaveLength(1);
344
- expect(calls[0].url).toBe("https://ingest.test/v1/metrics");
345
-
346
- // Payload carries the resource floor and at least the canonical
347
- // `http.server.request.duration` histogram that recordRequestMetric emits.
348
- const payload = JSON.parse(calls[0].body) as {
349
- resourceMetrics: Array<{
350
- resource: { attributes: Array<{ key: string; value: { stringValue: string } }> };
351
- scopeMetrics: Array<{ metrics: Array<{ name: string }> }>;
352
- }>;
353
- };
354
- const attrs = payload.resourceMetrics[0].resource.attributes;
355
- expect(attrs).toContainEqual({
356
- key: "service.name",
357
- value: { stringValue: "smoke-site" },
358
- });
359
- const names = payload.resourceMetrics[0].scopeMetrics[0].metrics.map((m) => m.name);
360
- expect(names).toContain("http.server.request.duration");
361
- });
362
-
363
- it("otlpMetricsEnabled=false disables the OTLP meter even when env is set", async () => {
364
- const { impl, calls } = makeFetchSpy();
365
- const handler = { fetch: vi.fn().mockResolvedValue(new Response("ok")) };
366
- const wrapped = instrumentWorker(handler, {
367
- otlpMetricsEnabled: false,
368
- otlpMetricsFetchImpl: impl,
369
- });
370
-
371
- const env: TestEnv = {
372
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
373
- } as TestEnv & { DECO_OTEL_METRICS_ENDPOINT: string };
374
- const ctx = fakeCtx();
375
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
376
-
377
- expect(ctx.waited).toHaveLength(0);
378
- expect(calls).toHaveLength(0);
379
- });
380
-
381
- it("falling back to handler.fetch failure still triggers a flush", async () => {
382
- const { impl } = makeFetchSpy();
383
- const handler = { fetch: vi.fn().mockRejectedValue(new Error("boom")) };
384
- const wrapped = instrumentWorker(handler, {
385
- otlpMetricsFetchImpl: impl,
386
- });
387
-
388
- const env: TestEnv = {
389
- DECO_OTEL_METRICS_ENDPOINT: "https://ingest.test/v1/metrics",
390
- } as TestEnv & { DECO_OTEL_METRICS_ENDPOINT: string };
391
- const ctx = fakeCtx();
392
- await expect(
393
- wrapped.fetch(new Request("https://example.test/"), env, ctx),
394
- ).rejects.toThrow("boom");
395
-
396
- expect(ctx.waited).toHaveLength(1);
397
- });
398
- });
399
-
400
- describe("instrumentWorker — OTLP/HTTP error-log channel wiring", () => {
401
- beforeEach(() => {
402
- _resetBootStateForTests();
403
- });
404
-
405
- afterEach(() => {
406
- _resetBootStateForTests();
407
- vi.restoreAllMocks();
408
- });
409
-
410
- function makeFetchSpy() {
411
- const calls: Array<{ url: string; body: string }> = [];
412
- const impl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
413
- calls.push({ url: String(input), body: String(init?.body ?? "") });
414
- return new Response("{}", { status: 200 });
415
- });
416
- return { impl: impl as unknown as typeof fetch, calls };
417
- }
418
-
419
- it("routes logger.error through the direct-POST channel when env is set", async () => {
420
- const { impl, calls } = makeFetchSpy();
421
- const handler = {
422
- fetch: vi.fn(async () => {
423
- logger.logger.error("payment failed", { stage: "checkout", reason: "declined" });
424
- return new Response("ok");
425
- }),
426
- };
427
- const wrapped = instrumentWorker(handler, {
428
- serviceName: "smoke-site",
429
- otlpLogsFetchImpl: impl,
430
- });
431
-
432
- const env: TestEnv = {
433
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
434
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
435
- const ctx = fakeCtx();
436
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
437
-
438
- // ctx.waitUntil(flushErrors) was queued.
439
- expect(ctx.waited.length).toBeGreaterThanOrEqual(1);
440
- await Promise.all(ctx.waited);
441
-
442
- expect(calls).toHaveLength(1);
443
- expect(calls[0].url).toBe("https://ingest.test/v1/logs");
444
- const payload = JSON.parse(calls[0].body) as {
445
- resourceLogs: Array<{
446
- scopeLogs: Array<{
447
- logRecords: Array<{ severityText: string; body: { stringValue: string } }>;
448
- }>;
449
- }>;
450
- };
451
- const rec = payload.resourceLogs[0].scopeLogs[0].logRecords[0];
452
- expect(rec.severityText).toBe("error");
453
- expect(rec.body.stringValue).toBe("payment failed");
454
- });
455
-
456
- it("debug calls do NOT trigger a direct POST (below default info minLevel)", async () => {
457
- const { impl, calls } = makeFetchSpy();
458
- const handler = {
459
- fetch: vi.fn(async () => {
460
- logger.logger.debug("debug msg");
461
- return new Response("ok");
462
- }),
463
- };
464
- const wrapped = instrumentWorker(handler, {
465
- otlpLogsFetchImpl: impl,
466
- });
467
-
468
- const env: TestEnv = {
469
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
470
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
471
- const ctx = fakeCtx();
472
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
473
- await Promise.all(ctx.waited);
474
-
475
- expect(calls).toHaveLength(0);
476
- });
477
-
478
- it("info calls DO trigger a direct POST (at default info minLevel)", async () => {
479
- const { impl, calls } = makeFetchSpy();
480
- const handler = {
481
- fetch: vi.fn(async () => {
482
- logger.logger.info("section loaded");
483
- return new Response("ok");
484
- }),
485
- };
486
- const wrapped = instrumentWorker(handler, {
487
- otlpLogsFetchImpl: impl,
488
- });
489
-
490
- const env: TestEnv = {
491
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
492
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
493
- const ctx = fakeCtx();
494
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
495
- await Promise.all(ctx.waited);
496
-
497
- expect(calls).toHaveLength(1);
498
- const payload = JSON.parse(calls[0].body) as {
499
- resourceLogs: Array<{ scopeLogs: Array<{ logRecords: Array<{ severityText: string }> }> }>;
500
- };
501
- expect(payload.resourceLogs[0].scopeLogs[0].logRecords[0].severityText).toBe("info");
502
- });
503
-
504
- it("otlpLogsEnabled=false disables the channel even when env is set", async () => {
505
- const { impl, calls } = makeFetchSpy();
506
- const handler = {
507
- fetch: vi.fn(async () => {
508
- logger.logger.error("boom");
509
- return new Response("ok");
510
- }),
511
- };
512
- const wrapped = instrumentWorker(handler, {
513
- otlpLogsEnabled: false,
514
- otlpLogsFetchImpl: impl,
515
- });
516
-
517
- const env: TestEnv = {
518
- DECO_OTEL_LOGS_ENDPOINT: "https://ingest.test/v1/logs",
519
- } as TestEnv & { DECO_OTEL_LOGS_ENDPOINT: string };
520
- const ctx = fakeCtx();
521
- await wrapped.fetch(new Request("https://example.test/"), env, ctx);
522
- await Promise.all(ctx.waited);
523
-
524
- expect(calls).toHaveLength(0);
525
- });
526
- });