@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,643 +0,0 @@
1
- /**
2
- * Observability utilities for deco middleware.
3
- *
4
- * Pluggable adapters for tracing (spans) and metrics (counters, gauges,
5
- * histograms). Works with any backend: OpenTelemetry, Sentry, Datadog, etc.
6
- *
7
- * Per-request active spans are propagated via an injectable `RequestStore`
8
- * — by default an AsyncLocalStorage-backed implementation. Tests can swap
9
- * it via `setObservabilitySpanStore()` to assert span lifecycle without
10
- * relying on `node:async_hooks` semantics in the test runner.
11
- *
12
- * @example
13
- * ```ts
14
- * import { configureTracer, configureMeter } from "@decocms/start/middleware";
15
- * import { trace, metrics } from "@opentelemetry/api";
16
- *
17
- * configureTracer({
18
- * startSpan: (name, attrs) => {
19
- * const span = trace.getTracer("deco").startSpan(name, { attributes: attrs });
20
- * return {
21
- * end: () => span.end(),
22
- * setError: (e) => span.recordException(e),
23
- * setAttribute: (k, v) => span.setAttribute(k, v),
24
- * };
25
- * },
26
- * });
27
- *
28
- * configureMeter({
29
- * counterInc: (name, value, labels) => metrics.getMeter("deco").createCounter(name).add(value, labels),
30
- * histogramRecord: (name, value, labels) => metrics.getMeter("deco").createHistogram(name).record(value, labels),
31
- * });
32
- * ```
33
- */
34
-
35
- import * as asyncHooks from "node:async_hooks";
36
- import {
37
- ATTR_HTTP_REQUEST_METHOD,
38
- ATTR_HTTP_RESPONSE_STATUS_CODE,
39
- ATTR_HTTP_ROUTE,
40
- METRIC_HTTP_CLIENT_REQUEST_DURATION,
41
- METRIC_HTTP_SERVER_REQUEST_DURATION,
42
- } from "@opentelemetry/semantic-conventions";
43
- import { logger } from "../sdk/logger";
44
-
45
- // ---------------------------------------------------------------------------
46
- // RequestStore — minimal per-request context abstraction. Inlined here so
47
- // the observability module has zero cross-package dependencies and tests
48
- // can inject a custom implementation via `setObservabilitySpanStore`.
49
- // ---------------------------------------------------------------------------
50
-
51
- export interface RequestStore<T> {
52
- get(): T | undefined;
53
- run<R>(value: T, fn: () => R): R;
54
- }
55
-
56
- class NoopRequestStore implements RequestStore<unknown> {
57
- get(): undefined {
58
- return undefined;
59
- }
60
- run<R>(_value: unknown, fn: () => R): R {
61
- return fn();
62
- }
63
- }
64
-
65
- const noopRequestStore: RequestStore<unknown> = new NoopRequestStore();
66
-
67
- class AlsRequestStore<T> implements RequestStore<T> {
68
- private readonly als:
69
- | { getStore(): T | undefined; run<R>(store: T, fn: () => R): R }
70
- | null;
71
- constructor() {
72
- const ALS = (asyncHooks as { AsyncLocalStorage?: new <U>() => {
73
- getStore(): U | undefined;
74
- run<R>(store: U, fn: () => R): R;
75
- } }).AsyncLocalStorage;
76
- this.als = ALS ? new ALS<T>() : null;
77
- }
78
- get(): T | undefined {
79
- return this.als?.getStore();
80
- }
81
- run<R>(value: T, fn: () => R): R {
82
- return this.als ? this.als.run(value, fn) : fn();
83
- }
84
- }
85
-
86
- // ---------------------------------------------------------------------------
87
- // Tracer
88
- // ---------------------------------------------------------------------------
89
-
90
- export interface Span {
91
- end(): void;
92
- setError?(error: unknown): void;
93
- setAttribute?(key: string, value: string | number | boolean): void;
94
- /**
95
- * Return W3C trace context for the current span. Used by helpers that
96
- * need to correlate logs to traces (`logger`) or propagate context to
97
- * downstream services (`injectTraceContext`). Optional — adapters that
98
- * can't expose it simply leave it off and callers no-op gracefully.
99
- */
100
- spanContext?(): { traceId: string; spanId: string; traceFlags: number };
101
- }
102
-
103
- export interface TracerAdapter {
104
- startSpan(name: string, attributes?: Record<string, string | number | boolean>): Span;
105
- }
106
-
107
- // ---------------------------------------------------------------------------
108
- // Shared module state — pinned to globalThis via Symbol.for so multiple
109
- // inlined copies of this module (one per bundled entry file if/when
110
- // bundling is ever reintroduced) converge on the SAME state. Without this
111
- // indirection, `configureMeter()` from one entry's copy writes to a meter
112
- // that `getMeter()` in another entry's copy never sees, and direct-POST
113
- // telemetry silently no-ops.
114
- //
115
- // Pattern borrowed from @opentelemetry/api / Sentry — both solve the same
116
- // "library with multiple entry exports re-bundles internal state modules"
117
- // problem. Cloudflare Workers guarantee one `globalThis` per isolate, so
118
- // there's no risk of cross-isolate bleed. Defensive against future
119
- // bundling changes; harmless when consumers import from src/ as today.
120
- // ---------------------------------------------------------------------------
121
-
122
- interface ObservabilityState {
123
- tracer: TracerAdapter | null;
124
- meter: MeterAdapter | null;
125
- spanStore: RequestStore<Span | null>;
126
- }
127
-
128
- const STATE_KEY = Symbol.for("@decocms/start/observability/state.v1");
129
-
130
- function getState(): ObservabilityState {
131
- const g = globalThis as Record<symbol, unknown>;
132
- if (!g[STATE_KEY]) {
133
- g[STATE_KEY] = {
134
- tracer: null,
135
- meter: null,
136
- spanStore: new AlsRequestStore<Span | null>(),
137
- } satisfies ObservabilityState;
138
- }
139
- return g[STATE_KEY] as ObservabilityState;
140
- }
141
-
142
- /**
143
- * Swap the RequestStore used for active-span propagation.
144
- *
145
- * Pass `undefined` to reset to the default AsyncLocalStorage-backed store.
146
- * Primarily intended for tests that need deterministic span access without
147
- * setting up an actual ALS context.
148
- */
149
- export function setObservabilitySpanStore(s: RequestStore<Span | null> | undefined): void {
150
- getState().spanStore = s ?? new AlsRequestStore<Span | null>();
151
- }
152
-
153
- export function configureTracer(t: TracerAdapter) {
154
- getState().tracer = t;
155
- }
156
-
157
- export function getTracer(): TracerAdapter | null {
158
- return getState().tracer;
159
- }
160
-
161
- /** Get the currently active span for the current async context, if any. */
162
- export function getActiveSpan(): Span | null {
163
- return getState().spanStore.get() ?? null;
164
- }
165
-
166
- /** Set an attribute on the active span, if one exists. */
167
- export function setSpanAttribute(key: string, value: string | number | boolean) {
168
- getActiveSpan()?.setAttribute?.(key, value);
169
- }
170
-
171
- /**
172
- * Inject the active span's W3C trace context into outbound request headers
173
- * as a `traceparent` header (RFC W3C-tracecontext format
174
- * `version-traceId-parentId-flags`). Call this from outbound `fetch`
175
- * wrappers (e.g. `createInstrumentedFetch` in `@decocms/apps`) so upstream
176
- * services that participate in OTel can correlate their spans with ours.
177
- *
178
- * No-op when no active span exists, when the active span has no
179
- * `spanContext()` adapter method, or when the trace/span IDs aren't
180
- * populated. Never throws.
181
- *
182
- * @example
183
- * ```ts
184
- * import { injectTraceContext } from "@decocms/start/sdk/observability";
185
- *
186
- * async function tracedFetch(url: string, init?: RequestInit) {
187
- * const headers = new Headers(init?.headers);
188
- * injectTraceContext(headers);
189
- * return fetch(url, { ...init, headers });
190
- * }
191
- * ```
192
- */
193
- export function injectTraceContext(headers: Headers): void {
194
- const ctx = getActiveSpan()?.spanContext?.();
195
- if (!ctx || !ctx.traceId || !ctx.spanId) return;
196
- const flags = (ctx.traceFlags & 0xff).toString(16).padStart(2, "0");
197
- headers.set("traceparent", `00-${ctx.traceId}-${ctx.spanId}-${flags}`);
198
- }
199
-
200
- export async function withTracing<T>(
201
- name: string,
202
- fn: () => Promise<T>,
203
- attributes?: Record<string, string | number | boolean>,
204
- ): Promise<T> {
205
- const s = getState();
206
- if (!s.tracer) return fn();
207
-
208
- const span = s.tracer.startSpan(name, attributes);
209
-
210
- try {
211
- const result = await s.spanStore.run(span, fn);
212
- span.end();
213
- return result;
214
- } catch (error) {
215
- span.setError?.(error);
216
- span.end();
217
- throw error;
218
- }
219
- }
220
-
221
- // ---------------------------------------------------------------------------
222
- // Meter
223
- // ---------------------------------------------------------------------------
224
-
225
- type Labels = Record<string, string | number | boolean>;
226
-
227
- export interface MeterAdapter {
228
- counterInc(name: string, value?: number, labels?: Labels): void;
229
- gaugeSet?(name: string, value: number, labels?: Labels): void;
230
- histogramRecord?(name: string, value: number, labels?: Labels): void;
231
- }
232
-
233
- export function configureMeter(m: MeterAdapter) {
234
- getState().meter = m;
235
- }
236
-
237
- export function getMeter(): MeterAdapter | null {
238
- return getState().meter;
239
- }
240
-
241
- /**
242
- * Pre-defined metric names. Where the OTel community SemConv defines a
243
- * canonical metric we use the constant imported from
244
- * `@opentelemetry/semantic-conventions` (e.g.
245
- * `METRIC_HTTP_SERVER_REQUEST_DURATION`) — never write the string ourselves.
246
- * Browse: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
247
- *
248
- * Concepts the OTel community does NOT define (cache hits, CMS resolve,
249
- * per-loader latency) use the Deco extension namespace `deco.*` in dotted
250
- * notation, matching the OTel attribute-naming convention.
251
- *
252
- * Unit / value handling: emitters declare the unit honestly via the
253
- * METRIC_METADATA map below; the framework never converts numeric values.
254
- * Consumers (otel-ingest collector, future Go Collector swap, query
255
- * layers) apply UCUM conversions if their target backend requires a
256
- * specific unit (e.g. canonical OTel `s` for HTTP durations).
257
- */
258
- export const MetricNames = {
259
- // OTel SemConv (stable).
260
- HTTP_SERVER_REQUEST_DURATION: METRIC_HTTP_SERVER_REQUEST_DURATION,
261
- HTTP_CLIENT_REQUEST_DURATION: METRIC_HTTP_CLIENT_REQUEST_DURATION,
262
- // Deco extensions — no canonical OTel metric exists for these concepts.
263
- // Single cache counter dimensioned by `deco.cache.status` — follows the OTel
264
- // semconv pattern (cf. nfs.server.repcache.requests + .status). deco-cx/deco
265
- // uses the same name so both frameworks aggregate together.
266
- CACHE_REQUESTS: "deco.cache.requests",
267
- RESOLVE_DURATION: "deco.cms.resolve.duration",
268
- LOADER_DURATION: "deco.loader.duration",
269
- LOADER_ERRORS: "deco.loader.errors",
270
- } as const;
271
-
272
- /**
273
- * Per-metric metadata emitted in the OTLP payload's `description` and
274
- * `unit` fields. Durations are normalized to **seconds at the source** (OTel
275
- * semconv), matching the deco-cx/deco framework — NOT converted downstream in
276
- * the collector. Callers still pass milliseconds; the record helpers divide.
277
- *
278
- * Keep keys aligned with `MetricNames` values so a missing entry is a
279
- * type error at compile time when a new metric ships without metadata.
280
- */
281
- export const METRIC_METADATA: Record<string, { description: string; unit: string }> = {
282
- [MetricNames.HTTP_SERVER_REQUEST_DURATION]: {
283
- description: "Duration of HTTP server requests handled at the Worker entry point.",
284
- unit: "s",
285
- },
286
- [MetricNames.HTTP_CLIENT_REQUEST_DURATION]: {
287
- description: "Duration of outbound HTTP client requests (commerce, generic fetch).",
288
- unit: "s",
289
- },
290
- [MetricNames.CACHE_REQUESTS]: {
291
- description: "Cache lookups, dimensioned by deco.cache.status (hit/stale/miss/bypass).",
292
- unit: "{request}",
293
- },
294
- [MetricNames.RESOLVE_DURATION]: {
295
- description: "Duration of `deco.cms.resolvePage` — CMS route to block tree resolution.",
296
- unit: "s",
297
- },
298
- [MetricNames.LOADER_DURATION]: {
299
- description: "Per-loader execution duration, emitted by cachedLoader.",
300
- unit: "s",
301
- },
302
- [MetricNames.LOADER_ERRORS]: {
303
- description: "Per-loader error count.",
304
- unit: "{error}",
305
- },
306
- };
307
-
308
- /**
309
- * Map an HTTP status code to its canonical class label (`2xx` / ... /
310
- * `5xx`). Out-of-range numbers (e.g. -1 from a thrown fetch) fall back
311
- * to `"unknown"` so dashboards don't break on edge cases.
312
- *
313
- * Exported because callers occasionally need the same mapping for
314
- * non-metric purposes (logging, tail enrichment).
315
- */
316
- export function statusClassFor(status: number): string {
317
- if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
318
- if (status < 100 || status >= 600) return "unknown";
319
- return `${Math.floor(status / 100)}xx`;
320
- }
321
-
322
- /**
323
- * Optional dimensions stamped on `http.server.request.duration` (semconv).
324
- * Request count and error rate are derived from the histogram's `count` and
325
- * a `http.response.status_code` filter — the old separate `_total` /
326
- * `_errors_total` counters were removed. All fields are optional — callers
327
- * pass what they have, the framework fills in the rest from defaults.
328
- *
329
- * Cardinality discipline: every field here is bounded. `route_pattern`
330
- * comes from the TanStack router (a closed set), `outcome` is the CF
331
- * Workers Observability enum, `cache_decision` / `cache_layer` are
332
- * union types declared in this module, `region` is a small set of CF
333
- * colo codes. Status is unbounded by spec but bounded in practice; the
334
- * `status_class` label bounds the cardinality further for dashboards
335
- * that don't need the raw value.
336
- */
337
- /**
338
- * Per-request identifiers that MUST NOT be stamped on metric labels.
339
- * They belong on spans (where they are 1:1 with the entity being
340
- * observed) and on logs (where they enable cross-channel correlation).
341
- * Putting them on metric labels collapses aggregation — every request
342
- * becomes its own histogram data point.
343
- */
344
- const HIGH_CARDINALITY_BLOCKLIST = new Set<string>([
345
- "request.id",
346
- "trace.id",
347
- "span.id",
348
- "session.id",
349
- "user.id",
350
- ]);
351
-
352
- export interface RequestMetricLabels {
353
- /** TanStack route pattern (`/_products/$slug/p`) — closed set. */
354
- route_pattern?: string;
355
- /** Cloudflare Workers Observability `outcome` (`ok`, `exception`, ...). */
356
- outcome?: string;
357
- /** Cache layer + decision when known. */
358
- cache_decision?: CacheDecision;
359
- cache_layer?: CacheLayer;
360
- /** Cloudflare colo (`GRU`, `IAD`, ...). */
361
- region?: string;
362
- /**
363
- * Arbitrary extra labels — callers should avoid this and add fields
364
- * to the typed surface above instead. Kept as an escape hatch so
365
- * non-canonical experiments don't require a framework release.
366
- */
367
- extra?: Record<string, string | number | boolean>;
368
- }
369
-
370
- /**
371
- * Record an HTTP request metric.
372
- *
373
- * Call in middleware after the response is produced. Two-call surface
374
- * for backward compat:
375
- *
376
- * recordRequestMetric(method, path, status, durationMs)
377
- * recordRequestMetric(method, path, status, durationMs, labels)
378
- *
379
- * The labels argument is optional — sites that haven't bumped to the
380
- * Phase 2 metric shape still emit the original three labels
381
- * (`method`, `route_pattern`, `status`). Adding labels never changes
382
- * existing labels' values; only adds new ones.
383
- */
384
- export function recordRequestMetric(
385
- method: string,
386
- path: string,
387
- status: number,
388
- durationMs: number,
389
- labels?: RequestMetricLabels,
390
- ) {
391
- const m = getState().meter;
392
- if (!m) return;
393
- // Cardinality discipline:
394
- // - `method`: small (GET, POST, ...).
395
- // - `route_pattern`: closed set (caller-supplied) OR normalized path
396
- // (fallback). Either way bounded.
397
- // - `status`: full HTTP code (bounded ~50 values in practice).
398
- // - `status_class`: 5-element enum (2xx / 3xx / 4xx / 5xx / unknown).
399
- // - `outcome`: CF outcome enum (~7 values).
400
- // - `cache_decision`: 5-element enum.
401
- // - `cache_layer`: 3-element enum (edge / cachedLoader / vtex-swr).
402
- // - `region`: ~250 CF colo codes worldwide.
403
- // Total combinations are bounded — safe for unbounded series on
404
- // ClickHouse but operators should still avoid grouping by `region`
405
- // unless explicitly needed.
406
- // semconv attribute keys for the core HTTP dimensions; deco.* for the
407
- // proprietary extras. Unified with deco-cx/deco so both frameworks land on
408
- // the same series/labels in ClickHouse.
409
- const merged: Labels = {
410
- [ATTR_HTTP_REQUEST_METHOD]: method,
411
- [ATTR_HTTP_ROUTE]: labels?.route_pattern ?? normalizePath(path),
412
- [ATTR_HTTP_RESPONSE_STATUS_CODE]: status,
413
- "deco.http.status_class": statusClassFor(status),
414
- };
415
- if (labels?.outcome) merged["deco.http.outcome"] = labels.outcome;
416
- if (labels?.cache_decision) merged["deco.cache.decision"] = labels.cache_decision;
417
- if (labels?.cache_layer) merged["deco.cache.layer"] = labels.cache_layer;
418
- if (labels?.region) merged["deco.http.region"] = labels.region;
419
- if (labels?.extra) {
420
- for (const [k, v] of Object.entries(labels.extra)) {
421
- // Defense-in-depth — refuse to stamp known per-request identifiers
422
- // on metric labels. These belong on spans and logs only; putting
423
- // them here makes every request its own histogram data point and
424
- // destroys aggregation. Caller-supplied `extra` should remain a
425
- // low-cardinality escape hatch (A/B variant, feature flag, ...).
426
- if (HIGH_CARDINALITY_BLOCKLIST.has(k)) continue;
427
- merged[k] = v;
428
- }
429
- }
430
- // OTel canonical HTTP metrics define a single histogram per direction
431
- // (`http.server.request.duration` for incoming). The request count is
432
- // derived from the histogram's `count` field; error rate is derived by
433
- // filtering on `http.response.status_code`. Separate `_total` /
434
- // `_errors_total` counters were removed because they duplicate
435
- // histogram-derived signals and aren't part of the canonical spec.
436
- // Record in seconds (semconv) — caller passes ms.
437
- m.histogramRecord?.(
438
- MetricNames.HTTP_SERVER_REQUEST_DURATION,
439
- durationMs / 1000,
440
- merged,
441
- );
442
- }
443
-
444
- /**
445
- * Cache decision label. Mirrors the `X-Cache` response header we set in
446
- * `workerEntry.ts` so dashboards can join on it.
447
- * - `HIT` — fresh entry returned from cache
448
- * - `STALE-HIT` — stale entry served, async revalidation kicked off (SWR)
449
- * - `STALE-ERROR` — stale entry served because origin errored (SIE)
450
- * - `MISS` — cache lookup returned nothing, origin fetched
451
- * - `BYPASS` — request not eligible for caching (private, cookies, etc.)
452
- */
453
- export type CacheDecision = "HIT" | "STALE-HIT" | "STALE-ERROR" | "MISS" | "BYPASS";
454
-
455
- /**
456
- * Where the cache lives. Phase 2 label expansion (D-11).
457
- * - `edge` — Cloudflare Cache API (HTML pages, server-fn responses)
458
- * - `cachedLoader` — In-memory per-isolate via `sdk/cachedLoader.ts`
459
- * (loader-level SWR, dedup, in-flight)
460
- * - `vtex-swr` — Apps-side in-memory cache shared by VTEX clients
461
- * (intelligent-search, cross-selling, etc.)
462
- */
463
- export type CacheLayer = "edge" | "cachedLoader" | "vtex-swr";
464
-
465
- /**
466
- * Record a cache hit/miss metric. Also stamps the decision on the active
467
- * trace span (when one exists) as `deco.cache.decision` / `deco.cache.profile`
468
- * so operators can filter ClickStack traces by cache decision directly,
469
- * without joining to metrics.
470
- *
471
- * Backward-compatible signature:
472
- * recordCacheMetric(hit, profile?, decision?)
473
- * recordCacheMetric(hit, profile?, decision?, layer?)
474
- *
475
- * `decision` is optional — when omitted, the metric still records HIT
476
- * vs MISS but dashboards can't distinguish SWR/SIE paths. Pass it
477
- * whenever known. `layer` defaults to `edge` when called from
478
- * workerEntry; cachedLoader / vtex-swr call sites should pass their
479
- * value explicitly.
480
- */
481
- export function recordCacheMetric(
482
- hit: boolean,
483
- profile?: string,
484
- decision?: CacheDecision,
485
- layer?: CacheLayer,
486
- ) {
487
- // Stamp on the active span FIRST so the attribute survives even if the
488
- // meter is a no-op (e.g. on tests, or in dev without DECO_METRICS).
489
- const active = getActiveSpan();
490
- if (active) {
491
- if (decision) active.setAttribute?.("deco.cache.status", decision);
492
- if (profile) active.setAttribute?.("deco.cache.profile", profile);
493
- if (layer) active.setAttribute?.("deco.cache.layer", layer);
494
- }
495
-
496
- const m = getState().meter;
497
- if (!m) return;
498
- // Single counter dimensioned by deco.cache.status — unified with deco-cx/deco
499
- // (follows the semconv nfs.server.repcache.requests + .status pattern). status
500
- // is the decision when known (HIT/STALE-HIT/STALE-ERROR/MISS/BYPASS), else the
501
- // hit boolean. Same key on span + metric.
502
- const labels: Labels = {
503
- "deco.cache.status": decision ?? (hit ? "HIT" : "MISS"),
504
- };
505
- if (profile) labels["deco.cache.profile"] = profile;
506
- if (layer) labels["deco.cache.layer"] = layer;
507
- m.counterInc(MetricNames.CACHE_REQUESTS, 1, labels);
508
- }
509
-
510
- /**
511
- * Labels for the outbound commerce sample recorded on
512
- * `http.client.request.duration`. Owned by the framework so apps-start (and
513
- * any future provider package) can register operation strings without owning
514
- * the histogram declaration. Phase 2 (D-11).
515
- */
516
- export interface CommerceMetricLabels {
517
- /** `vtex`, `shopify`, `wake`, ... — small closed set. */
518
- provider: string;
519
- /** Per-provider operation, e.g. `intelligent-search.product_search`. */
520
- operation: string;
521
- /** Set when known (e.g. from the HTTP response). Bounded enum. */
522
- status_class?: string;
523
- /** Whether the underlying fetch was served from a cache. */
524
- cached?: boolean;
525
- }
526
-
527
- /**
528
- * Record a commerce / outbound-fetch duration sample. No-op when no meter is
529
- * configured. Emitted on the canonical `http.client.request.duration` metric
530
- * (semconv) — providers vary by the `provider`/`operation` labels, not by
531
- * name, so dashboards aggregate cleanly across the fleet.
532
- */
533
- export function recordCommerceMetric(
534
- durationMs: number,
535
- labels: CommerceMetricLabels,
536
- ) {
537
- const m = getState().meter;
538
- if (!m) return;
539
- const merged: Labels = {
540
- provider: labels.provider,
541
- operation: labels.operation,
542
- };
543
- if (labels.status_class) merged.status_class = labels.status_class;
544
- if (typeof labels.cached === "boolean") merged.cached = labels.cached;
545
- // Canonical OTel HTTP client metric — outbound commerce calls share the
546
- // same metric as any other outbound HTTP request; `peer.service` /
547
- // `commerce.operation` attributes disambiguate consumer queries.
548
- // Record in seconds (semconv) — caller passes ms.
549
- m.histogramRecord?.(
550
- MetricNames.HTTP_CLIENT_REQUEST_DURATION,
551
- durationMs / 1000,
552
- merged,
553
- );
554
- }
555
-
556
- /**
557
- * Record a loader execution sample. Call from `cachedLoader` after the
558
- * loader resolves or rejects. `cache_status` mirrors `CacheDecision` so
559
- * dashboards can distinguish HIT (fresh) from STALE-HIT (SWR), STALE-ERROR
560
- * (SIE fallback), MISS (origin fetch), and BYPASS (dev / no-store).
561
- */
562
- export function recordLoaderMetric(
563
- name: string,
564
- durationMs: number,
565
- cacheStatus: CacheDecision | "BYPASS",
566
- ) {
567
- const m = getState().meter;
568
- if (!m) return;
569
- // Record in seconds (semconv) — caller passes ms.
570
- m.histogramRecord?.(MetricNames.LOADER_DURATION, durationMs / 1000, {
571
- "deco.loader.name": name,
572
- "deco.cache.result": cacheStatus,
573
- });
574
- }
575
-
576
- /**
577
- * Increment the loader error counter. Call when a loader throws and the
578
- * error is not swallowed by a SIE fallback.
579
- */
580
- export function recordLoaderError(name: string) {
581
- const m = getState().meter;
582
- if (!m) return;
583
- m.counterInc(MetricNames.LOADER_ERRORS, 1, { "deco.loader.name": name });
584
- }
585
-
586
- /**
587
- * Collapse dynamic path segments (ids, product slugs) into placeholders so a
588
- * path can be used as a bounded metric label. Exported so every metric that
589
- * labels by route (`http.server.request.duration`, `deco.cms.resolve.duration`)
590
- * shares the exact same normalization — a raw path is unbounded cardinality
591
- * (one histogram series per URL) and must never reach a metric attribute.
592
- */
593
- export function normalizePath(path: string): string {
594
- // Collapse dynamic segments to reduce cardinality
595
- return path
596
- .replace(/\/[0-9a-f]{8,}/gi, "/:id")
597
- .replace(/\/\d+/g, "/:id")
598
- .replace(/\/[^/]+\/p$/, "/:slug/p");
599
- }
600
-
601
- // ---------------------------------------------------------------------------
602
- // Request logging
603
- // ---------------------------------------------------------------------------
604
-
605
- const isDev =
606
- typeof globalThis.process !== "undefined" && globalThis.process.env?.NODE_ENV === "development";
607
-
608
- /**
609
- * Structured request log entry.
610
- * JSON in production, colorized in development.
611
- * Includes traceId when available.
612
- */
613
- export function logRequest(
614
- request: Request,
615
- status: number,
616
- durationMs: number,
617
- extra?: Record<string, unknown>,
618
- ) {
619
- const url = new URL(request.url);
620
- // Truncate long paths (e.g. /_serverFn/ base64 payloads) so log messages
621
- // remain readable. Full path is preserved in the `path` attribute.
622
- const rawPath = url.pathname;
623
- const displayPath = rawPath.length > 80 ? `${rawPath.slice(0, 80)}…` : rawPath;
624
- // Route through the framework logger so the access log fans out to every
625
- // configured adapter — local stdout via `defaultLoggerAdapter`, OTLP direct-
626
- // POST via `otlpLog.adapter` when configured (subject to its
627
- // `DECO_OTEL_LOGS_MIN_LEVEL` threshold). Always debug: filtered in prod
628
- // (default `warn` minLevel), visible in dev with DECO_OTEL_LOGS_MIN_LEVEL=debug.
629
- // 5xx errors are already logged at the throw site with full context; the
630
- // access log is just a dev convenience, not a production alert source.
631
- logger.debug(`${request.method} ${displayPath} ${status}`, {
632
- method: request.method,
633
- path: rawPath,
634
- status,
635
- duration_ms: Math.round(durationMs),
636
- ...extra,
637
- });
638
- }
639
-
640
- // noopRequestStore is kept as a no-op fallback for advanced tests; not
641
- // re-exported because consumers should reach for `setObservabilitySpanStore`
642
- // instead.
643
- void noopRequestStore;