@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
package/src/sdk/flags.ts CHANGED
@@ -23,6 +23,12 @@
23
23
  * changes `traffic` and redeploys, the fingerprint no longer matches and the
24
24
  * visitor is re-rolled once, then re-sticks — same self-healing scheme as
25
25
  * {@link ./abTesting.ts}.
26
+ * - `exp` — `{ experimentKey: variantId }`, the N-way assignments written by
27
+ * {@link ./experiments.ts}. `active`/`inactiveDrawn` are boolean buckets and
28
+ * physically cannot hold a variant id, so string-valued decisions ride in
29
+ * their own map. It is deliberately the same shape Deco Analytics consumes,
30
+ * so pointing the collector at it later is a read, not a translation.
31
+ * Their re-roll fingerprints share the `pct` map, keyed by experiment key.
26
32
  *
27
33
  * The cookie MUST be written un-encoded (raw base64) — OneDollarStats reads it
28
34
  * with `atob()` directly. Base64's `+ / =` are all valid cookie-value octets
@@ -35,11 +41,19 @@ export const SEGMENT_COOKIE = "deco_segment";
35
41
  /** A recorded flag decision: which named flag, the branch taken, and the
36
42
  * `traffic` fingerprint (0–100) it was decided under. */
37
43
  export interface StoredFlag {
38
- /** Matcher block name, e.g. "TestHero". Stable identity for the cohort. */
44
+ /** Matcher block name, e.g. "TestHero", or an experiment key, e.g.
45
+ * "plp-ranking". Stable identity for the cohort. */
39
46
  name: string;
40
- /** The branch the visitor was assigned to. */
41
- value: boolean;
42
- /** `round(traffic * 100)` at assignment time — the re-roll fingerprint. */
47
+ /**
48
+ * The branch the visitor was assigned to. A boolean for CMS multivariate
49
+ * matchers (the historical case); a variant id for N-way experiments.
50
+ */
51
+ value: boolean | string;
52
+ /**
53
+ * The fingerprint this decision was made under — `round(traffic * 100)` for
54
+ * a CMS matcher, a weight-vector hash for an experiment. A decision whose
55
+ * stored fingerprint no longer matches the current one is re-rolled once.
56
+ */
43
57
  pct: number;
44
58
  }
45
59
 
@@ -49,6 +63,8 @@ interface DecoSegment {
49
63
  inactiveDrawn?: string[];
50
64
  /** blocks extension: per-flag traffic fingerprint. Ignored by analytics. */
51
65
  pct?: Record<string, number>;
66
+ /** blocks extension: N-way experiment assignments, `{ key: variantId }`. */
67
+ exp?: Record<string, string>;
52
68
  }
53
69
 
54
70
  /** Convert a 0–1 traffic ratio to the 0–100 integer fingerprint. */
@@ -75,6 +91,9 @@ export function parseSegmentCookie(raw: string | undefined | null): StoredFlag[]
75
91
  for (const name of seg.inactiveDrawn ?? []) {
76
92
  out.push({ name, value: false, pct: pct[name] ?? -1 });
77
93
  }
94
+ for (const [name, variantId] of Object.entries(seg.exp ?? {})) {
95
+ out.push({ name, value: variantId, pct: pct[name] ?? -1 });
96
+ }
78
97
  return out;
79
98
  } catch {
80
99
  return [];
@@ -86,23 +105,34 @@ export function serializeSegmentCookie(flags: StoredFlag[]): string {
86
105
  const active: string[] = [];
87
106
  const inactiveDrawn: string[] = [];
88
107
  const pct: Record<string, number> = {};
108
+ const exp: Record<string, string> = {};
89
109
  for (const f of [...flags].sort((a, b) => a.name.localeCompare(b.name))) {
90
- (f.value ? active : inactiveDrawn).push(f.name);
110
+ if (typeof f.value === "string") {
111
+ exp[f.name] = f.value;
112
+ } else {
113
+ (f.value ? active : inactiveDrawn).push(f.name);
114
+ }
91
115
  pct[f.name] = f.pct;
92
116
  }
93
117
  const seg: DecoSegment = { active, inactiveDrawn, pct };
118
+ // Omit `exp` entirely when unused so the cookie stays byte-identical to what
119
+ // sites emit today — an added empty map would re-issue every visitor's cookie
120
+ // on deploy and, via segmentCacheToken, cold-start every edge cache entry.
121
+ if (Object.keys(exp).length) seg.exp = exp;
94
122
  return btoa(encodeURIComponent(JSON.stringify(seg)));
95
123
  }
96
124
 
97
125
  /**
98
126
  * Stable token for the cache key — includes the `pct` fingerprint so a
99
- * `traffic` change lands cohorts in fresh buckets. Empty string when there are
100
- * no flags, so non-A/B pages keep sharing one entry.
127
+ * `traffic` (or experiment weight) change lands cohorts in fresh buckets.
128
+ * Empty string when there are no flags, so non-A/B pages keep sharing one
129
+ * entry. Experiment assignments fold in on the same footing as boolean flags:
130
+ * without that, two visitors on different variants would share cached HTML.
101
131
  */
102
132
  export function segmentCacheToken(flags: StoredFlag[]): string {
103
133
  if (!flags.length) return "";
104
134
  return [...flags]
105
135
  .sort((a, b) => a.name.localeCompare(b.name))
106
- .map((f) => `${f.name}:${f.value ? "1" : "0"}:${f.pct}`)
136
+ .map((f) => `${f.name}:${typeof f.value === "string" ? f.value : f.value ? "1" : "0"}:${f.pct}`)
107
137
  .join(",");
108
138
  }
package/src/sdk/index.ts CHANGED
@@ -18,8 +18,15 @@ export {
18
18
  export { clx } from "./clx";
19
19
  export { decodeCookie, deleteCookie, getCookie, getServerSideCookie, setCookie } from "./cookie";
20
20
  export { buildCSPHeaderValue, type CSPOptions, setCSPHeaders } from "./csp";
21
+ export { deepOmit } from "./deepOmit";
21
22
  export { djb2, djb2Hex } from "./djb2";
22
23
  export { isDevMode } from "./env";
24
+ export {
25
+ DEFAULT_FETCH_TIMEOUT_MS,
26
+ type FetchFn,
27
+ withFetchTimeout,
28
+ withTimeoutSignal,
29
+ } from "./fetchTimeout";
23
30
  export {
24
31
  createInstrumentedFetch,
25
32
  type FetchInstrumentationOptions,
@@ -15,6 +15,7 @@
15
15
  * ```
16
16
  */
17
17
 
18
+ import { DEFAULT_FETCH_TIMEOUT_MS, withTimeoutSignal } from "./fetchTimeout";
18
19
  import { logger } from "./logger";
19
20
  import { getTracer, injectTraceContext } from "./observability";
20
21
  import { redactUrl } from "./urlRedaction";
@@ -87,6 +88,15 @@ export interface FetchInstrumentationOptions {
87
88
  * `init.operation` ?? `defaultOperation` ?? `resolveOperation(url, method)` ?? `"fetch"`
88
89
  */
89
90
  resolveOperation?: (url: string, method: string) => string | undefined;
91
+ /**
92
+ * Abort a request after this many ms unless it settles first, via
93
+ * `AbortSignal.timeout` composed with any signal the caller already
94
+ * passed in `init.signal`. Default: {@link DEFAULT_FETCH_TIMEOUT_MS}
95
+ * (10s). Pass `0` or `Infinity` to disable for this integration (e.g. a
96
+ * client that intentionally makes long-lived/streaming requests).
97
+ * Override per-call via `init.timeoutMs`.
98
+ */
99
+ timeoutMs?: number;
90
100
  }
91
101
 
92
102
  export interface FetchMetrics {
@@ -115,6 +125,12 @@ export type InstrumentedFetchInit = RequestInit & {
115
125
  * surfaces to the network as a request property.
116
126
  */
117
127
  operation?: string;
128
+ /**
129
+ * Per-call timeout override (ms). See
130
+ * {@link FetchInstrumentationOptions.timeoutMs}. Stripped from the init
131
+ * before reaching `baseFetch`.
132
+ */
133
+ timeoutMs?: number;
118
134
  };
119
135
 
120
136
  /**
@@ -149,6 +165,7 @@ export function createInstrumentedFetch(
149
165
  injectTraceparent = true,
150
166
  defaultOperation,
151
167
  resolveOperation,
168
+ timeoutMs = DEFAULT_FETCH_TIMEOUT_MS,
152
169
  } = options;
153
170
 
154
171
  return async (input: RequestInfo | URL, init?: InstrumentedFetchInit): Promise<Response> => {
@@ -177,9 +194,10 @@ export function createInstrumentedFetch(
177
194
  // off init so it never reaches `baseFetch` as an unknown RequestInit
178
195
  // property (some runtimes warn / future runtimes might reject).
179
196
  const explicitOp = init?.operation;
197
+ const effectiveTimeoutMs = init?.timeoutMs ?? timeoutMs;
180
198
  let initForFetch: RequestInit | undefined = init;
181
- if (init && "operation" in init) {
182
- const { operation: _drop, ...rest } = init;
199
+ if (init && ("operation" in init || "timeoutMs" in init)) {
200
+ const { operation: _drop, timeoutMs: _drop2, ...rest } = init;
183
201
  initForFetch = rest;
184
202
  }
185
203
  const operation =
@@ -218,6 +236,11 @@ export function createInstrumentedFetch(
218
236
  finalInit = { ...(initForFetch ?? {}), headers };
219
237
  }
220
238
 
239
+ finalInit = {
240
+ ...(finalInit ?? {}),
241
+ signal: withTimeoutSignal(finalInit?.signal, effectiveTimeoutMs),
242
+ };
243
+
221
244
  const doFetch = async (): Promise<Response> => {
222
245
  if (logging) {
223
246
  console.log(`[${name}] ${method} ${truncateUrl(safeUrl)}`);
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Per-request CSP nonce.
3
+ *
4
+ * When the TanStack worker entry runs with `cspMode: "enforce"`, it generates a
5
+ * fresh nonce per request, stashes it in the RequestContext bag (below), and
6
+ * threads it into:
7
+ *
8
+ * - the TanStack router (`router.options.ssr.nonce`), so `ScriptOnce` and the
9
+ * framework's own hydration scripts carry `nonce=…`;
10
+ * - the hand-written inline `<script>` tags in the deco layout / live-controls
11
+ * components (they read it via `getRequestNonce()`);
12
+ * - the enforced `Content-Security-Policy` header's `script-src`.
13
+ *
14
+ * Lives in `runtime` (not `tanstack`) so both the tanstack worker and the
15
+ * runtime components (e.g. LiveControls) can reach it without crossing the
16
+ * one-way package dependency graph.
17
+ *
18
+ * The nonce is only produced on the server and only in enforce mode; in the
19
+ * browser the RequestContext is a no-op stub, so `getRequestNonce()` returns
20
+ * `undefined` and every consumer degrades to "no nonce attribute".
21
+ */
22
+ import { RequestContext } from "./requestContext";
23
+
24
+ /** RequestContext bag key holding the current request's CSP nonce. */
25
+ export const NONCE_BAG_KEY = "deco.csp.nonce";
26
+
27
+ /**
28
+ * Generate a CSP nonce: 128 bits of CSPRNG randomness, base64-encoded. Fresh
29
+ * per request — never reuse across responses, or the nonce loses all value.
30
+ */
31
+ export function generateNonce(): string {
32
+ const bytes = new Uint8Array(16);
33
+ crypto.getRandomValues(bytes);
34
+ let binary = "";
35
+ for (const byte of bytes) binary += String.fromCharCode(byte);
36
+ return btoa(binary);
37
+ }
38
+
39
+ /**
40
+ * The current request's CSP nonce, or `undefined` when CSP is not enforced
41
+ * (report-only mode) or on the client. Read this in an SSR component to nonce
42
+ * an inline `<script>`: `<script nonce={getRequestNonce()} … />`.
43
+ */
44
+ export function getRequestNonce(): string | undefined {
45
+ return RequestContext.getBag<string>(NONCE_BAG_KEY);
46
+ }
@@ -13,8 +13,8 @@
13
13
  * // In site's setup.ts:
14
14
  * import { registerProductionOrigins } from "@decocms/start/sdk/normalizeUrls";
15
15
  * registerProductionOrigins([
16
- * "https://www.casaevideo.com.br",
17
- * "https://casaevideo.com.br",
16
+ * "https://www.acme.com.br",
17
+ * "https://acme.com.br",
18
18
  * ]);
19
19
  * ```
20
20
  */
@@ -64,6 +64,7 @@ export {
64
64
  type MeterAdapter,
65
65
  MetricNames,
66
66
  recordCacheMetric,
67
+ recordCacheSizeMetric,
67
68
  recordCommerceMetric,
68
69
  recordLoaderError,
69
70
  recordLoaderMetric,
@@ -78,7 +79,13 @@ export {
78
79
  withTracing,
79
80
  } from "../middleware/observability";
80
81
  // Worker-entry wrapper + adapter wiring
81
- export { instrumentWorker, type OtelOptions } from "./otel";
82
+ export {
83
+ bootObservability,
84
+ flushObservability,
85
+ instrumentWorker,
86
+ instrumentWorkflowRun,
87
+ type OtelOptions,
88
+ } from "./otel";
82
89
  // Direct-POST OTLP trace exporter (Phase 3 / D-12). Exported for sites
83
90
  // that need to wire a custom traces endpoint outside `instrumentWorker`,
84
91
  // and for the audit tooling that asserts framework spans are flowing.
package/src/sdk/otel.ts CHANGED
@@ -312,7 +312,7 @@ interface WorkerHandler {
312
312
  // into Copy A's `otlpMeter` while the per-request `recordRequestMetric`
313
313
  // closure reads from Copy B's empty `otlpMeter`. Net effect in prod:
314
314
  // `bootObservability` runs (we observed the very first `POST /v1/metrics`
315
- // from miess-tanstack), but every subsequent request's `flush()` finds an
315
+ // from a production storefront), but every subsequent request's `flush()` finds an
316
316
  // empty buffer because the meter the framework writes into is a different
317
317
  // instance from the one the exporter drains.
318
318
  //
@@ -446,34 +446,98 @@ export function instrumentWorker(
446
446
  // ctx.waitUntil so no POST blocks the response. Each exporter
447
447
  // throttles itself per isolate — calling on every request is
448
448
  // cheap; the network only fires when the cooldown elapses or
449
- // the buffer fills.
449
+ // the buffer fills. Skip the waitUntil call entirely when no
450
+ // adapter is configured (nothing to flush).
450
451
  const state = getBootState();
451
- if (state.otlpMeter) {
452
+ if (state.otlpMeter || state.otlpLog || state.otlpTracer) {
452
453
  try {
453
- ctx.waitUntil(state.otlpMeter.flush());
454
+ ctx.waitUntil(flushObservability());
454
455
  } catch {
455
456
  /* ctx.waitUntil throwing is benign — never block the response */
456
457
  }
457
458
  }
458
- if (state.otlpLog) {
459
- try {
460
- ctx.waitUntil(state.otlpLog.flush());
461
- } catch {
462
- /* swallow */
463
- }
464
- }
465
- if (state.otlpTracer) {
466
- try {
467
- ctx.waitUntil(state.otlpTracer.flush());
468
- } catch {
469
- /* swallow */
470
- }
471
- }
472
459
  }
473
460
  },
474
461
  };
475
462
  }
476
463
 
464
+ /**
465
+ * Drains the OTLP metrics + error-log + traces buffers (whichever are
466
+ * configured for this isolate). Extracted out of `instrumentWorker`'s
467
+ * `finally` block so callers without a `{fetch}`/`ctx.waitUntil` lifecycle —
468
+ * e.g. Cloudflare Workflow `run()` handlers — can flush explicitly too. See
469
+ * `instrumentWorkflowRun` below.
470
+ *
471
+ * Each adapter's `flush()` is throttled by a per-isolate cooldown (default
472
+ * 5s) so a busy fetch handler doesn't fire a POST per request — pass
473
+ * `force: true` to bypass that cooldown for callers that only get one flush
474
+ * attempt with no next request to retry on (Workflow `run()` exit).
475
+ */
476
+ export async function flushObservability(force = false): Promise<void> {
477
+ const state = getBootState();
478
+ await Promise.allSettled([
479
+ state.otlpMeter?.flush(force),
480
+ state.otlpLog?.flush(force),
481
+ state.otlpTracer?.flush(force),
482
+ ]);
483
+ }
484
+
485
+ /**
486
+ * Boots observability (same env-var-driven wiring `instrumentWorker` uses)
487
+ * and runs `fn`, flushing on the way out — the Workflow-entrypoint
488
+ * equivalent of `instrumentWorker`. Cloudflare Workflows have no `{fetch}` /
489
+ * `ctx.waitUntil` lifecycle, so this awaits the flush directly instead.
490
+ *
491
+ * Deliberately does NOT open a root span around `fn()`. Code in a
492
+ * `WorkflowEntrypoint.run(event, step)` outside `step.do`/`step.sleep`
493
+ * re-executes on every hibernate/wake replay — a span opened here would get
494
+ * a fresh random trace ID on every replay leg, producing disconnected
495
+ * traces instead of one coherent run. Create spans for individual
496
+ * `step.do(...)` callbacks with `withTracing` instead (each step only truly
497
+ * runs once, since `step.do` memoizes across replays), tagging them with
498
+ * `event.instanceId` so a backend can group replay legs under one logical
499
+ * run.
500
+ *
501
+ * The exit-time flush is `force`d (bypasses the per-isolate cooldown other
502
+ * `flush()` callers respect) — a Workflow `run()` invocation gets exactly
503
+ * one flush attempt on the way out, unlike a fetch handler where the next
504
+ * request's `ctx.waitUntil(flush())` can pick up whatever a cooldown-skipped
505
+ * flush left behind. Without forcing, a workflow with several replay legs in
506
+ * quick succession could have its final leg's flush silently skipped by the
507
+ * cooldown, losing that leg's buffered spans/metrics if the isolate is torn
508
+ * down before the next wake.
509
+ *
510
+ * @example
511
+ * ```ts
512
+ * async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
513
+ * return instrumentWorkflowRun(this.env, undefined, async () => {
514
+ * await step.do("fetch-product", () =>
515
+ * withTracing("deco.workflow.step", () => fetchProduct(), {
516
+ * "workflow.instance_id": event.instanceId,
517
+ * "workflow.step": "fetch-product",
518
+ * }),
519
+ * );
520
+ * });
521
+ * }
522
+ * ```
523
+ */
524
+ export async function instrumentWorkflowRun<T>(
525
+ env: Record<string, unknown>,
526
+ options: OtelOptions | undefined,
527
+ fn: () => Promise<T>,
528
+ ): Promise<T> {
529
+ configureTracer(buildOtelApiTracer());
530
+ bootObservability(options ?? {}, env);
531
+ try {
532
+ // Awaiting inside this try (rather than `return fn().finally(...)`)
533
+ // ensures a synchronous throw from `fn` — not just a rejected promise —
534
+ // still reaches the `finally` below instead of skipping it.
535
+ return await fn();
536
+ } finally {
537
+ await flushObservability(true);
538
+ }
539
+ }
540
+
477
541
  /**
478
542
  * Build the legacy `@opentelemetry/api` global-tracer bridge. Stays a
479
543
  * no-op when no global TracerProvider is registered — same outcome as
@@ -587,6 +651,42 @@ function configureTracerStack(otlpAdapter: OtlpHttpTracer | null): void {
587
651
  // Boot — wires the loggers/meters once (per worker isolate)
588
652
  // ---------------------------------------------------------------------------
589
653
 
654
+ /**
655
+ * Error's `name`/`message`/`stack` are non-enumerable, so a plain
656
+ * `JSON.stringify(err)` ships `"{}"`. Duck-typed so DOMException and
657
+ * cross-realm errors are covered too.
658
+ */
659
+ function isErrorLike(v: unknown): v is Error {
660
+ return v instanceof Error || (
661
+ typeof v === "object" && v !== null &&
662
+ typeof (v as Error).message === "string" &&
663
+ typeof (v as Error).name === "string" &&
664
+ "stack" in v
665
+ );
666
+ }
667
+
668
+ /** Expands nested errors (`{ error: err }`, `[err]`) instead of `{}`. */
669
+ const errorReplacer = (_key: string, v: unknown) =>
670
+ isErrorLike(v) ? { ...(v as object), name: v.name, message: v.message, stack: v.stack } : v;
671
+
672
+ /** Formats one `console.*` argument as a log-body fragment. */
673
+ function formatConsoleArg(a: unknown): string {
674
+ if (typeof a === "string") return a;
675
+ try {
676
+ if (isErrorLike(a)) {
677
+ const head = a.stack ?? `${a.name}: ${a.message}`;
678
+ // Keep enumerable own fields (e.g. `status`, `host`) the old
679
+ // JSON.stringify path used to ship.
680
+ const { name: _n, message: _m, stack: _s, ...rest } = a as object as Record<string, unknown>;
681
+ const extra = JSON.stringify(rest, errorReplacer);
682
+ return extra === "{}" ? head : `${head} ${extra}`;
683
+ }
684
+ return JSON.stringify(a, errorReplacer);
685
+ } catch {
686
+ return String(a);
687
+ }
688
+ }
689
+
590
690
  /**
591
691
  * Replaces `console.*` with thin shims that route every call through the
592
692
  * framework `logger`, which forwards to the configured adapter (direct-POST
@@ -620,12 +720,7 @@ function patchConsole(state: BootState): void {
620
720
  if (busy) return;
621
721
  busy = true;
622
722
  try {
623
- const msg = args
624
- .map((a) => {
625
- if (typeof a === "string") return a;
626
- try { return JSON.stringify(a); } catch { return String(a); }
627
- })
628
- .join(" ");
723
+ const msg = args.map(formatConsoleArg).join(" ");
629
724
  logger[level](msg);
630
725
  } finally {
631
726
  busy = false;
@@ -639,7 +734,18 @@ function patchConsole(state: BootState): void {
639
734
  console.debug = (...args: unknown[]) => forward("debug", args);
640
735
  }
641
736
 
642
- function bootObservability(opts: OtelOptions, env: Record<string, unknown>): void {
737
+ /**
738
+ * Boots the observability stack for the current isolate: resolves the
739
+ * `DECO_OTEL` on/off/auto switch, builds the resource-attribute floor
740
+ * (service name/version/instance, deployment environment, cloud platform),
741
+ * and — gated per env var — wires the AE meter and OTLP metrics/logs/traces
742
+ * adapters. Idempotent per isolate (`BootState.booted` guards re-entry).
743
+ *
744
+ * Exported so callers with a lifecycle `instrumentWorker` doesn't fit
745
+ * (Cloudflare Workflows — see `instrumentWorkflowRun`) can boot the same
746
+ * stack directly.
747
+ */
748
+ export function bootObservability(opts: OtelOptions, env: Record<string, unknown>): void {
643
749
  const state = getBootState();
644
750
  if (state.booted) return;
645
751
 
@@ -107,8 +107,8 @@ export interface OtlpHttpLogOptions {
107
107
 
108
108
  export interface OtlpHttpLog {
109
109
  adapter: LoggerAdapter;
110
- /** Force a flush, subject to the per-isolate cooldown. */
111
- flush(): Promise<void>;
110
+ /** Flush, subject to the per-isolate cooldown unless `force` is true. */
111
+ flush(force?: boolean): Promise<void>;
112
112
  /** Pending log record count. For tests + audit. */
113
113
  pendingRecordCount(): number;
114
114
  }
@@ -324,12 +324,12 @@ export function createOtlpHttpLogAdapter(options: OtlpHttpLogOptions): OtlpHttpL
324
324
  }
325
325
  }
326
326
 
327
- async function flush(): Promise<void> {
327
+ async function flush(force = false): Promise<void> {
328
328
  if (inflight) return inflight;
329
329
 
330
330
  const elapsed = now() - lastFlushAt;
331
331
  const overCap = buffer.length >= maxBuffer;
332
- if (!overCap && elapsed < minFlushIntervalMs) return;
332
+ if (!force && !overCap && elapsed < minFlushIntervalMs) return;
333
333
 
334
334
  inflight = doFlush().finally(() => {
335
335
  lastFlushAt = now();
@@ -84,8 +84,20 @@ export interface OtlpHttpMeterOptions {
84
84
  * The framework owns the lookup; callers MUST NOT pass metadata at
85
85
  * record time. See `MetricNames` / `METRIC_METADATA` in
86
86
  * `middleware/observability.ts`.
87
+ *
88
+ * `boundaries`, when present, is ALSO used to bucket that metric, overriding
89
+ * the adapter-wide `histogramBounds`. Without this a byte-sized histogram and
90
+ * a seconds-valued one would share the single ms-tuned default and both read
91
+ * back as a single saturated bucket.
87
92
  */
88
- metricMetadata?: Record<string, { description?: string; unit?: string }>;
93
+ metricMetadata?: Record<string, MetricMetadata>;
94
+ }
95
+
96
+ export interface MetricMetadata {
97
+ description?: string;
98
+ unit?: string;
99
+ /** Explicit bucket bounds for THIS metric, in the metric's own unit. */
100
+ boundaries?: readonly number[];
89
101
  }
90
102
 
91
103
  export interface OtlpHttpMeter extends MeterAdapter {
@@ -93,8 +105,8 @@ export interface OtlpHttpMeter extends MeterAdapter {
93
105
  gaugeSet(name: string, value: number, labels?: Labels): void;
94
106
  /** Always defined on this adapter — declared required to drop the `?.` at call sites. */
95
107
  histogramRecord(name: string, value: number, labels?: Labels): void;
96
- /** Force a flush, subject to the per-isolate cooldown. */
97
- flush(): Promise<void>;
108
+ /** Flush, subject to the per-isolate cooldown unless `force` is true. */
109
+ flush(force?: boolean): Promise<void>;
98
110
  /** Pending datapoint count across all metric kinds. For tests + audit. */
99
111
  pendingDatapointCount(): number;
100
112
  }
@@ -130,6 +142,13 @@ interface MetricEntry {
130
142
  counter?: Map<string, CounterPoint>;
131
143
  gauge?: Map<string, GaugePoint>;
132
144
  histogram?: Map<string, HistogramPoint>;
145
+ /**
146
+ * Bounds this metric is bucketed with — resolved once from the metric's own
147
+ * `boundaries` metadata, falling back to the adapter-wide default. Held on
148
+ * the entry so `serializeOtlp` emits the bounds the counts were actually
149
+ * filed against; emitting a different array silently mislabels every bucket.
150
+ */
151
+ bounds?: readonly number[];
133
152
  }
134
153
 
135
154
  // ---------------------------------------------------------------------------
@@ -273,6 +292,8 @@ export function createOtlpHttpMeterAdapter(options: OtlpHttpMeterOptions): OtlpH
273
292
  }
274
293
  const entry = existing ?? materializeEntry(name, "histogram");
275
294
  if (!entry.histogram) return;
295
+ const bounds = entry.bounds ?? metricMetadata[name]?.boundaries ?? histogramBounds;
296
+ entry.bounds = bounds;
276
297
  let point = entry.histogram.get(key);
277
298
  if (!point) {
278
299
  point = {
@@ -280,7 +301,7 @@ export function createOtlpHttpMeterAdapter(options: OtlpHttpMeterOptions): OtlpH
280
301
  sum: 0,
281
302
  min: Number.POSITIVE_INFINITY,
282
303
  max: Number.NEGATIVE_INFINITY,
283
- bucketCounts: new Array(histogramBounds.length + 1).fill(0),
304
+ bucketCounts: new Array(bounds.length + 1).fill(0),
284
305
  attrs: labels ? { ...labels } : {},
285
306
  startTimeUnixNano: msToNs(isolateStartMs),
286
307
  };
@@ -290,10 +311,10 @@ export function createOtlpHttpMeterAdapter(options: OtlpHttpMeterOptions): OtlpH
290
311
  point.sum += value;
291
312
  if (value < point.min) point.min = value;
292
313
  if (value > point.max) point.max = value;
293
- // Locate bucket. histogramBounds is small (<=20); linear scan is fine.
294
- let bucketIdx = histogramBounds.length;
295
- for (let i = 0; i < histogramBounds.length; i++) {
296
- if (value <= histogramBounds[i]) {
314
+ // Locate bucket. bounds is small (<=20); linear scan is fine.
315
+ let bucketIdx = bounds.length;
316
+ for (let i = 0; i < bounds.length; i++) {
317
+ if (value <= bounds[i]) {
297
318
  bucketIdx = i;
298
319
  break;
299
320
  }
@@ -341,7 +362,7 @@ export function createOtlpHttpMeterAdapter(options: OtlpHttpMeterOptions): OtlpH
341
362
  }
342
363
  }
343
364
 
344
- async function flush(): Promise<void> {
365
+ async function flush(force = false): Promise<void> {
345
366
  // If a flush is in flight, reuse it — concurrent requests should not
346
367
  // pile up POSTs. The in-flight POST already snapshotted the buffer at
347
368
  // its enqueue time; new datapoints land in the buffer and will go out
@@ -350,8 +371,11 @@ export function createOtlpHttpMeterAdapter(options: OtlpHttpMeterOptions): OtlpH
350
371
 
351
372
  const elapsed = now() - lastFlushAt;
352
373
  const overCap = pendingDatapointCount() >= maxBuffer;
353
- if (!overCap && elapsed < minFlushIntervalMs) {
354
- // Cooldown not elapsed and buffer is not at the cap — skip.
374
+ if (!force && !overCap && elapsed < minFlushIntervalMs) {
375
+ // Cooldown not elapsed and buffer is not at the cap — skip. `force`
376
+ // bypasses this for callers with no next-request opportunity to
377
+ // retry the flush (e.g. a Cloudflare Workflow's `run()` exit — see
378
+ // `instrumentWorkflowRun` in `otel.ts`).
355
379
  return;
356
380
  }
357
381
 
@@ -407,7 +431,7 @@ interface SerializeOpts {
407
431
  scopeVersion: string;
408
432
  histogramBounds: number[];
409
433
  flushAtNs: string;
410
- metricMetadata: Record<string, { description?: string; unit?: string }>;
434
+ metricMetadata: Record<string, MetricMetadata>;
411
435
  }
412
436
 
413
437
  function serializeOtlp(
@@ -467,7 +491,9 @@ function serializeOtlp(
467
491
  min: point.min === Number.POSITIVE_INFINITY ? 0 : point.min,
468
492
  max: point.max === Number.NEGATIVE_INFINITY ? 0 : point.max,
469
493
  bucketCounts: point.bucketCounts.map((c) => String(c)),
470
- explicitBounds: opts.histogramBounds,
494
+ // Must be the array the counts were bucketed against, not the
495
+ // adapter-wide default — see MetricEntry.bounds.
496
+ explicitBounds: entry.bounds ?? opts.histogramBounds,
471
497
  });
472
498
  }
473
499
  otlpMetrics.push({
@@ -233,8 +233,8 @@ export interface OtlpHttpTracerOptions {
233
233
  }
234
234
 
235
235
  export interface OtlpHttpTracer extends TracerAdapter {
236
- /** Drain the buffer (subject to cooldown). */
237
- flush(): Promise<void>;
236
+ /** Drain the buffer, subject to cooldown unless `force` is true. */
237
+ flush(force?: boolean): Promise<void>;
238
238
  /** For tests + the audit channel. */
239
239
  pendingSpanCount(): number;
240
240
  /**
@@ -433,11 +433,11 @@ export function createOtlpHttpTracerAdapter(options: OtlpHttpTracerOptions): Otl
433
433
  }
434
434
  }
435
435
 
436
- async function flush(): Promise<void> {
436
+ async function flush(force = false): Promise<void> {
437
437
  if (inflight) return inflight;
438
438
  const elapsed = now() - lastFlushAt;
439
439
  const overCap = spans.length >= maxBuffer;
440
- if (!overCap && elapsed < minFlushIntervalMs) return;
440
+ if (!force && !overCap && elapsed < minFlushIntervalMs) return;
441
441
  inflight = doFlush().finally(() => {
442
442
  lastFlushAt = now();
443
443
  inflight = null;