@open-mercato/telemetry 0.11.1-develop.8298.1.5323e2aa15 → 0.11.1-develop.8317.1.dde3d38b64

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.
@@ -1,8 +1,15 @@
1
1
  "use client";
2
2
  import * as React from "react";
3
+ import { registerTelemetryErrorReporter } from "@open-mercato/shared/lib/telemetry/runtime";
4
+ import { groupableCode } from "@open-mercato/shared/lib/telemetry/error-code";
5
+ import { serializeError } from "../facade/serialize.js";
6
+ import { redactAttributes } from "../facade/redact.js";
3
7
  import { createBackupHeaderPropagator } from "./propagator.js";
4
8
  let bootstrapped = false;
9
+ let disposeErrorReporter;
5
10
  function resetBrowserTelemetryBootstrap() {
11
+ disposeErrorReporter?.();
12
+ disposeErrorReporter = void 0;
6
13
  bootstrapped = false;
7
14
  }
8
15
  async function startBrowserTelemetry(config) {
@@ -15,7 +22,7 @@ async function startBrowserTelemetry(config) {
15
22
  { DocumentLoadInstrumentation },
16
23
  { FetchInstrumentation },
17
24
  { W3CTraceContextPropagator },
18
- { defaultTextMapSetter }
25
+ { defaultTextMapSetter, SpanStatusCode }
19
26
  ] = await Promise.all([
20
27
  import("@opentelemetry/sdk-trace-web"),
21
28
  import("@opentelemetry/sdk-trace-base"),
@@ -90,6 +97,21 @@ async function startBrowserTelemetry(config) {
90
97
  if (document.visibilityState === "hidden") flush();
91
98
  });
92
99
  window.addEventListener("pagehide", flush);
100
+ const tracer = provider.getTracer("@open-mercato/telemetry/browser");
101
+ return (error, context) => {
102
+ const serialized = serializeError(error);
103
+ const attributes = redactAttributes({ ...context?.attributes, module: context?.module });
104
+ delete attributes["error.code"];
105
+ const code = groupableCode(context?.code);
106
+ if (code) attributes["error.code"] = code;
107
+ const span = tracer.startSpan("browser.error", { attributes });
108
+ try {
109
+ span.recordException(serialized);
110
+ span.setStatus({ code: SpanStatusCode.ERROR });
111
+ } finally {
112
+ span.end();
113
+ }
114
+ };
93
115
  }
94
116
  function escapeRegExp(value) {
95
117
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -98,7 +120,14 @@ function BrowserTelemetry({ config }) {
98
120
  React.useEffect(() => {
99
121
  if (!config || bootstrapped) return;
100
122
  bootstrapped = true;
101
- void startBrowserTelemetry(config).catch(() => {
123
+ const reporter = startBrowserTelemetry(config);
124
+ const dispose = registerTelemetryErrorReporter((...args) => {
125
+ void reporter.then((reportError) => reportError(...args)).catch(() => {
126
+ });
127
+ });
128
+ disposeErrorReporter = dispose;
129
+ void reporter.catch(() => {
130
+ dispose();
102
131
  });
103
132
  }, [config]);
104
133
  return null;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/browser/BrowserTelemetry.tsx"],
4
- "sourcesContent": ["'use client'\n\n/**\n * Browser RUM. Boots the OpenTelemetry web SDK once per page load and exports\n * spans through the same-origin proxy (`/api/telemetry/browser-traces`).\n *\n * Why this exists: server traces can only prove where the time *isn't*. A page\n * can render an API answer in 50 ms yet leave the user waiting seconds before\n * the request is even sent \u2014 bundle download, hydration, or a click handler\n * stuck behind a re-render are all invisible to every server span.\n *\n * Two rules this file lives by:\n * - **The SDK is `import()`ed, never statically imported.** RUM often\n * diagnoses routes suspected to be bundle-bound; shipping the SDK in the\n * critical path would be self-defeating. Document-load timings survive the\n * late start because they are read back from the PerformanceTimeline.\n * - **It can never break the app.** Every failure is swallowed. No\n * user-facing surface, no retry.\n *\n * This file, `config.ts`, and `propagator.ts` are the only parts of\n * `@open-mercato/telemetry` a client bundle may reach (via the `/browser` entry).\n * None of them may import the server facade (`node:async_hooks`) or the\n * env-reading `browser/server.ts`; the two wirings are independent and meet only\n * at the collector.\n */\n\nimport * as React from 'react'\nimport type { BrowserTelemetryConfig } from './config'\nimport { createBackupHeaderPropagator } from './propagator'\n\n/** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */\nlet bootstrapped = false\n\n/**\n * Test seam. Production has exactly one bootstrap per page load, so nothing else\n * may call this \u2014 a second bootstrap would double every span.\n */\nexport function resetBrowserTelemetryBootstrap(): void {\n bootstrapped = false\n}\n\nasync function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<void> {\n const [\n { WebTracerProvider },\n { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { registerInstrumentations },\n { DocumentLoadInstrumentation },\n { FetchInstrumentation },\n { W3CTraceContextPropagator },\n { defaultTextMapSetter },\n ] = await Promise.all([\n import('@opentelemetry/sdk-trace-web'),\n import('@opentelemetry/sdk-trace-base'),\n import('@opentelemetry/exporter-trace-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/instrumentation'),\n import('@opentelemetry/instrumentation-document-load'),\n import('@opentelemetry/instrumentation-fetch'),\n import('@opentelemetry/core'),\n import('@opentelemetry/api'),\n ])\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n 'service.name': config.serviceName,\n // Plain attribute name (not the semconv `deployment.environment.name`) so browser spans sort\n // alongside the server spans, which use OTEL_RESOURCE_ATTRIBUTES.\n ...(config.environment ? { 'deployment.environment': config.environment } : {}),\n 'user_agent.original': navigator.userAgent,\n }),\n sampler: new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.samplingRatio),\n }),\n spanProcessors: [\n new BatchSpanProcessor(\n new OTLPTraceExporter({ url: config.endpoint }),\n // The interesting spans arrive in bursts around a navigation; a short delay keeps them\n // close together in the trace view without one request per span.\n { scheduledDelayMillis: 3_000, maxQueueSize: 512 },\n ),\n ],\n })\n\n // Standard `traceparent` plus the backup copy the server continues once\n // TELEMETRY_TRUST_INBOUND_TRACE is on \u2014 see `propagator.ts` for why that flag is the supported\n // way to get one end-to-end trace, and what happens without it.\n provider.register({\n propagator: createBackupHeaderPropagator(new W3CTraceContextPropagator(), defaultTextMapSetter),\n })\n\n // \u2500\u2500 The fetch-patch dance (do not simplify) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // `@open-mercato/ui`'s api utils install a global wrapper at module load so that stray\n // `fetch()` calls still get the 401 session-refresh / 403 banner behaviour:\n // w.__omOriginalFetch = window.fetch // pristine native fetch\n // window.fetch = (i, x) => apiFetch(i, x)\n // and `apiFetch` then calls `__omOriginalFetch` to avoid recursing into itself. Since the whole\n // backoffice (DataTable, CrudForm, react-query queryFns\u2026) imports `apiFetch` DIRECTLY, those\n // calls never touch `window.fetch` \u2014 so instrumenting `window.fetch` alone yields document-load\n // spans and almost no API spans, which is worse than none at all: it looks like it works.\n //\n // Fix: let the instrumentation patch the *native* fetch, then hand the patched version back as\n // the stash. Both paths end up instrumented exactly once:\n // apiFetch \u2192 __omOriginalFetch = OTel(native) \u2713\n // window.fetch \u2192 apiFetch wrapper \u2192 OTel(native) \u2713\n // Assigning `__omOriginalFetch = window.fetch` instead would loop forever\n // (apiFetch \u2192 wrapper \u2192 apiFetch \u2192 \u2026). The swap is synchronous \u2014 `registerInstrumentations`\n // calls `enable()` inline \u2014 so no caller can observe the intermediate state.\n const patchTarget = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const frameworkFetch = patchTarget.__omOriginalFetch ? window.fetch : null\n if (frameworkFetch && patchTarget.__omOriginalFetch) {\n window.fetch = patchTarget.__omOriginalFetch\n }\n\n // `finally`, not a plain sequence: the instrumentation constructors below are evaluated inside\n // this window, and a throw from any of them (SDK version skew, a browser missing an API an\n // instrumentation touches) would otherwise leave `window.fetch` as the raw native fetch stashed\n // above. `apiFetch` would keep working \u2014 it reads `__omOriginalFetch` \u2014 but every stray\n // `window.fetch(...)` would silently bypass the framework wrapper's 401 session-refresh and 403\n // banner behaviour for the rest of the page's life. This is the one path where the file's\n // \"every failure is swallowed\" rule would leave global state degraded.\n try {\n registerInstrumentations({\n tracerProvider: provider,\n instrumentations: [\n // Navigation + resource timings: chunk download vs. parse vs. hydrate.\n new DocumentLoadInstrumentation(),\n // The client-side START of each API call \u2014 the number the server can never see.\n new FetchInstrumentation({\n // Never instrument our own export, or each batch would generate the next one.\n ignoreUrls: [new RegExp(escapeRegExp(config.endpoint))],\n clearTimingResources: true,\n }),\n // No `UserInteractionInstrumentation` here, deliberately. It works by patching\n // `addEventListener` when `enable()` runs, but React attaches a SINGLE delegated `click`\n // listener to the root container during `createRoot`/hydration \u2014 and this SDK boots from\n // `useEffect`, which React runs strictly after hydration. The patch would land after the\n // only listener that will ever see a backoffice click, so it produces no spans at all\n // (confirmed in manual QA). Booting early enough to beat hydration would mean putting the\n // SDK back on the critical path, which is the one thing this file refuses to do. An\n // instrumentation that silently produces nothing is worse than an absent one: an empty\n // interaction view reads as \"nobody clicks\" rather than \"this is broken\".\n ],\n })\n } finally {\n if (frameworkFetch) {\n // On the success path `window.fetch` is OTel's patched native fetch; on the throw path it is\n // the pristine native one. Either way this restores the framework wrapper on top of whatever\n // the stash should now hold, so the pre-swap contract holds in both.\n patchTarget.__omOriginalFetch = window.fetch\n window.fetch = frameworkFetch\n }\n }\n\n // BatchSpanProcessor would otherwise drop whatever is still queued when the user navigates away\n // \u2014 which is exactly when a slow page gets abandoned, i.e. the spans we most want.\n //\n // `forceFlush` exports through the OTLP fetch transport, which sets `keepalive: true` on the\n // request whenever the payload and the number of in-flight requests are within the browser's\n // limits \u2014 so the batch survives the page going away. That is the durable path here;\n // `sendBeacon` would be the other candidate, but upstream deprecated its export delegate in\n // favour of the fetch one, so reaching for it would trade a supported API for a doomed one.\n //\n // Both events, because neither alone covers every exit: `visibilitychange` misses some bfcache\n // entries, and `pagehide` does not fire when a tab is merely backgrounded. A second flush with\n // an empty queue is a no-op, so the overlap costs nothing.\n const flush = () => void provider.forceFlush().catch(() => {})\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n window.addEventListener('pagehide', flush)\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Renders nothing. `config` is resolved server-side (`resolveBrowserTelemetryConfig()`) and is\n * `null` whenever browser telemetry is disabled for the environment \u2014 which is the default, and\n * keeps the SDK chunk from ever being requested.\n */\nexport function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig | null }) {\n React.useEffect(() => {\n if (!config || bootstrapped) return\n bootstrapped = true\n void startBrowserTelemetry(config).catch(() => {\n // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).\n })\n }, [config])\n\n return null\n}\n"],
5
- "mappings": ";AA0BA,YAAY,WAAW;AAEvB,SAAS,oCAAoC;AAG7C,IAAI,eAAe;AAMZ,SAAS,iCAAuC;AACrD,iBAAe;AACjB;AAEA,eAAe,sBAAsB,QAA+C;AAClF,QAAM;AAAA,IACJ,EAAE,kBAAkB;AAAA,IACpB,EAAE,oBAAoB,oBAAoB,yBAAyB;AAAA,IACnE,EAAE,kBAAkB;AAAA,IACpB,EAAE,uBAAuB;AAAA,IACzB,EAAE,yBAAyB;AAAA,IAC3B,EAAE,4BAA4B;AAAA,IAC9B,EAAE,qBAAqB;AAAA,IACvB,EAAE,0BAA0B;AAAA,IAC5B,EAAE,qBAAqB;AAAA,EACzB,IAAI,MAAM,QAAQ,IAAI;AAAA,IACpB,OAAO,8BAA8B;AAAA,IACrC,OAAO,+BAA+B;AAAA,IACtC,OAAO,yCAAyC;AAAA,IAChD,OAAO,0BAA0B;AAAA,IACjC,OAAO,gCAAgC;AAAA,IACvC,OAAO,8CAA8C;AAAA,IACrD,OAAO,sCAAsC;AAAA,IAC7C,OAAO,qBAAqB;AAAA,IAC5B,OAAO,oBAAoB;AAAA,EAC7B,CAAC;AAED,QAAM,WAAW,IAAI,kBAAkB;AAAA,IACrC,UAAU,uBAAuB;AAAA,MAC/B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AoB,SAAU,OAAM;AAAA,EACnD,CAAC;AACD,SAAO,iBAAiB,YAAY,KAAK;AAC3C;AAEA,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAOO,SAAS,iBAAiB,EAAE,OAAO,GAA8C;AACtF,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,UAAU,aAAc;AAC7B,mBAAe;AACf,SAAK,sBAAsB,MAAM,EAAE,MAAM,MAAM;AAAA,IAE/C,CAAC;AAAA,EACH,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AACT;",
4
+ "sourcesContent": ["'use client'\n\n/**\n * Browser RUM. Boots the OpenTelemetry web SDK once per page load and exports\n * spans through the same-origin proxy (`/api/telemetry/browser-traces`).\n *\n * Why this exists: server traces can only prove where the time *isn't*. A page\n * can render an API answer in 50 ms yet leave the user waiting seconds before\n * the request is even sent \u2014 bundle download, hydration, or a click handler\n * stuck behind a re-render are all invisible to every server span.\n *\n * Two rules this file lives by:\n * - **The SDK is `import()`ed, never statically imported.** RUM often\n * diagnoses routes suspected to be bundle-bound; shipping the SDK in the\n * critical path would be self-defeating. Document-load timings survive the\n * late start because they are read back from the PerformanceTimeline.\n * - **It can never break the app.** Every failure is swallowed. No\n * user-facing surface, no retry.\n *\n * The `/browser` entry and its pure serialization/redaction helpers must not\n * import the server facade (`node:async_hooks`) or the\n * env-reading `browser/server.ts`; the two wirings are independent and meet only\n * at the collector.\n */\n\nimport * as React from 'react'\nimport { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport { serializeError } from '../facade/serialize'\nimport { redactAttributes } from '../facade/redact'\nimport type { BrowserTelemetryConfig } from './config'\nimport { createBackupHeaderPropagator } from './propagator'\n\n/** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */\nlet bootstrapped = false\nlet disposeErrorReporter: (() => void) | undefined\n\n/**\n * Test seam. Production has exactly one bootstrap per page load, so nothing else\n * may call this \u2014 a second bootstrap would double every span.\n */\nexport function resetBrowserTelemetryBootstrap(): void {\n disposeErrorReporter?.()\n disposeErrorReporter = undefined\n bootstrapped = false\n}\n\nasync function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<TelemetryRuntime['reportError']> {\n const [\n { WebTracerProvider },\n { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { registerInstrumentations },\n { DocumentLoadInstrumentation },\n { FetchInstrumentation },\n { W3CTraceContextPropagator },\n { defaultTextMapSetter, SpanStatusCode },\n ] = await Promise.all([\n import('@opentelemetry/sdk-trace-web'),\n import('@opentelemetry/sdk-trace-base'),\n import('@opentelemetry/exporter-trace-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/instrumentation'),\n import('@opentelemetry/instrumentation-document-load'),\n import('@opentelemetry/instrumentation-fetch'),\n import('@opentelemetry/core'),\n import('@opentelemetry/api'),\n ])\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n 'service.name': config.serviceName,\n // Plain attribute name (not the semconv `deployment.environment.name`) so browser spans sort\n // alongside the server spans, which use OTEL_RESOURCE_ATTRIBUTES.\n ...(config.environment ? { 'deployment.environment': config.environment } : {}),\n 'user_agent.original': navigator.userAgent,\n }),\n sampler: new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.samplingRatio),\n }),\n spanProcessors: [\n new BatchSpanProcessor(\n new OTLPTraceExporter({ url: config.endpoint }),\n // The interesting spans arrive in bursts around a navigation; a short delay keeps them\n // close together in the trace view without one request per span.\n { scheduledDelayMillis: 3_000, maxQueueSize: 512 },\n ),\n ],\n })\n\n // Standard `traceparent` plus the backup copy the server continues once\n // TELEMETRY_TRUST_INBOUND_TRACE is on \u2014 see `propagator.ts` for why that flag is the supported\n // way to get one end-to-end trace, and what happens without it.\n provider.register({\n propagator: createBackupHeaderPropagator(new W3CTraceContextPropagator(), defaultTextMapSetter),\n })\n\n // \u2500\u2500 The fetch-patch dance (do not simplify) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // `@open-mercato/ui`'s api utils install a global wrapper at module load so that stray\n // `fetch()` calls still get the 401 session-refresh / 403 banner behaviour:\n // w.__omOriginalFetch = window.fetch // pristine native fetch\n // window.fetch = (i, x) => apiFetch(i, x)\n // and `apiFetch` then calls `__omOriginalFetch` to avoid recursing into itself. Since the whole\n // backoffice (DataTable, CrudForm, react-query queryFns\u2026) imports `apiFetch` DIRECTLY, those\n // calls never touch `window.fetch` \u2014 so instrumenting `window.fetch` alone yields document-load\n // spans and almost no API spans, which is worse than none at all: it looks like it works.\n //\n // Fix: let the instrumentation patch the *native* fetch, then hand the patched version back as\n // the stash. Both paths end up instrumented exactly once:\n // apiFetch \u2192 __omOriginalFetch = OTel(native) \u2713\n // window.fetch \u2192 apiFetch wrapper \u2192 OTel(native) \u2713\n // Assigning `__omOriginalFetch = window.fetch` instead would loop forever\n // (apiFetch \u2192 wrapper \u2192 apiFetch \u2192 \u2026). The swap is synchronous \u2014 `registerInstrumentations`\n // calls `enable()` inline \u2014 so no caller can observe the intermediate state.\n const patchTarget = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const frameworkFetch = patchTarget.__omOriginalFetch ? window.fetch : null\n if (frameworkFetch && patchTarget.__omOriginalFetch) {\n window.fetch = patchTarget.__omOriginalFetch\n }\n\n // `finally`, not a plain sequence: the instrumentation constructors below are evaluated inside\n // this window, and a throw from any of them (SDK version skew, a browser missing an API an\n // instrumentation touches) would otherwise leave `window.fetch` as the raw native fetch stashed\n // above. `apiFetch` would keep working \u2014 it reads `__omOriginalFetch` \u2014 but every stray\n // `window.fetch(...)` would silently bypass the framework wrapper's 401 session-refresh and 403\n // banner behaviour for the rest of the page's life. This is the one path where the file's\n // \"every failure is swallowed\" rule would leave global state degraded.\n try {\n registerInstrumentations({\n tracerProvider: provider,\n instrumentations: [\n // Navigation + resource timings: chunk download vs. parse vs. hydrate.\n new DocumentLoadInstrumentation(),\n // The client-side START of each API call \u2014 the number the server can never see.\n new FetchInstrumentation({\n // Never instrument our own export, or each batch would generate the next one.\n ignoreUrls: [new RegExp(escapeRegExp(config.endpoint))],\n clearTimingResources: true,\n }),\n // No `UserInteractionInstrumentation` here, deliberately. It works by patching\n // `addEventListener` when `enable()` runs, but React attaches a SINGLE delegated `click`\n // listener to the root container during `createRoot`/hydration \u2014 and this SDK boots from\n // `useEffect`, which React runs strictly after hydration. The patch would land after the\n // only listener that will ever see a backoffice click, so it produces no spans at all\n // (confirmed in manual QA). Booting early enough to beat hydration would mean putting the\n // SDK back on the critical path, which is the one thing this file refuses to do. An\n // instrumentation that silently produces nothing is worse than an absent one: an empty\n // interaction view reads as \"nobody clicks\" rather than \"this is broken\".\n ],\n })\n } finally {\n if (frameworkFetch) {\n // On the success path `window.fetch` is OTel's patched native fetch; on the throw path it is\n // the pristine native one. Either way this restores the framework wrapper on top of whatever\n // the stash should now hold, so the pre-swap contract holds in both.\n patchTarget.__omOriginalFetch = window.fetch\n window.fetch = frameworkFetch\n }\n }\n\n // BatchSpanProcessor would otherwise drop whatever is still queued when the user navigates away\n // \u2014 which is exactly when a slow page gets abandoned, i.e. the spans we most want.\n //\n // `forceFlush` exports through the OTLP fetch transport, which sets `keepalive: true` on the\n // request whenever the payload and the number of in-flight requests are within the browser's\n // limits \u2014 so the batch survives the page going away. That is the durable path here;\n // `sendBeacon` would be the other candidate, but upstream deprecated its export delegate in\n // favour of the fetch one, so reaching for it would trade a supported API for a doomed one.\n //\n // Both events, because neither alone covers every exit: `visibilitychange` misses some bfcache\n // entries, and `pagehide` does not fire when a tab is merely backgrounded. A second flush with\n // an empty queue is a no-op, so the overlap costs nothing.\n const flush = () => void provider.forceFlush().catch(() => {})\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n window.addEventListener('pagehide', flush)\n\n const tracer = provider.getTracer('@open-mercato/telemetry/browser')\n return (error, context) => {\n const serialized = serializeError(error)\n const attributes = redactAttributes({ ...context?.attributes, module: context?.module })\n delete attributes['error.code']\n const code = groupableCode(context?.code)\n if (code) attributes['error.code'] = code\n const span = tracer.startSpan('browser.error', { attributes })\n try {\n span.recordException(serialized)\n span.setStatus({ code: SpanStatusCode.ERROR })\n } finally {\n span.end()\n }\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Renders nothing. `config` is resolved server-side (`resolveBrowserTelemetryConfig()`) and is\n * `null` whenever browser telemetry is disabled for the environment \u2014 which is the default, and\n * keeps the SDK chunk from ever being requested.\n */\nexport function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig | null }) {\n React.useEffect(() => {\n if (!config || bootstrapped) return\n bootstrapped = true\n const reporter = startBrowserTelemetry(config)\n const dispose = registerTelemetryErrorReporter((...args) => {\n void reporter.then((reportError) => reportError(...args)).catch(() => {})\n })\n disposeErrorReporter = dispose\n void reporter.catch(() => {\n dispose()\n // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).\n })\n }, [config])\n\n return null\n}\n"],
5
+ "mappings": ";AAyBA,YAAY,WAAW;AACvB,SAAS,sCAA6D;AACtE,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AAEjC,SAAS,oCAAoC;AAG7C,IAAI,eAAe;AACnB,IAAI;AAMG,SAAS,iCAAuC;AACrD,yBAAuB;AACvB,yBAAuB;AACvB,iBAAe;AACjB;AAEA,eAAe,sBAAsB,QAA0E;AAC7G,QAAM;AAAA,IACJ,EAAE,kBAAkB;AAAA,IACpB,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EAAE,OAAO,GAA8C;AACtF,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,UAAU,aAAc;AAC7B,mBAAe;AACf,UAAM,WAAW,sBAAsB,MAAM;AAC7C,UAAM,UAAU,+BAA+B,IAAI,SAAS;AAC1D,WAAK,SAAS,KAAK,CAAC,gBAAgB,YAAY,GAAG,IAAI,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC1E,CAAC;AACD,2BAAuB;AACvB,SAAK,SAAS,MAAM,MAAM;AACxB,cAAQ;AAAA,IAEV,CAAC;AAAA,EACH,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AACT;",
6
6
  "names": []
7
7
  }
package/jest.config.cjs CHANGED
@@ -6,6 +6,9 @@ module.exports = {
6
6
  testEnvironment: 'node',
7
7
  watchman: false,
8
8
  rootDir: '.',
9
+ moduleNameMapper: {
10
+ '^@open-mercato/shared/(.*)$': '<rootDir>/../shared/src/$1',
11
+ },
9
12
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
10
13
  transform: {
11
14
  '^.+\\.(t|j)sx?$': [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/telemetry",
3
- "version": "0.11.1-develop.8298.1.5323e2aa15",
3
+ "version": "0.11.1-develop.8317.1.dde3d38b64",
4
4
  "license": "MIT",
5
5
  "description": "Vendor-neutral spans, metrics, and error reporting backed by a pluggable OTLP provider. Off by default; the telemetry runtime is loaded only when explicitly enabled.",
6
6
  "type": "module",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@open-mercato/shared": "0.11.1-develop.8298.1.5323e2aa15"
41
+ "@open-mercato/shared": "0.11.1-develop.8317.1.dde3d38b64"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": ">=18.0.0"
@@ -17,29 +17,35 @@
17
17
  * - **It can never break the app.** Every failure is swallowed. No
18
18
  * user-facing surface, no retry.
19
19
  *
20
- * This file, `config.ts`, and `propagator.ts` are the only parts of
21
- * `@open-mercato/telemetry` a client bundle may reach (via the `/browser` entry).
22
- * None of them may import the server facade (`node:async_hooks`) or the
20
+ * The `/browser` entry and its pure serialization/redaction helpers must not
21
+ * import the server facade (`node:async_hooks`) or the
23
22
  * env-reading `browser/server.ts`; the two wirings are independent and meet only
24
23
  * at the collector.
25
24
  */
26
25
 
27
26
  import * as React from 'react'
27
+ import { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
28
+ import { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'
29
+ import { serializeError } from '../facade/serialize'
30
+ import { redactAttributes } from '../facade/redact'
28
31
  import type { BrowserTelemetryConfig } from './config'
29
32
  import { createBackupHeaderPropagator } from './propagator'
30
33
 
31
34
  /** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */
32
35
  let bootstrapped = false
36
+ let disposeErrorReporter: (() => void) | undefined
33
37
 
34
38
  /**
35
39
  * Test seam. Production has exactly one bootstrap per page load, so nothing else
36
40
  * may call this — a second bootstrap would double every span.
37
41
  */
38
42
  export function resetBrowserTelemetryBootstrap(): void {
43
+ disposeErrorReporter?.()
44
+ disposeErrorReporter = undefined
39
45
  bootstrapped = false
40
46
  }
41
47
 
42
- async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<void> {
48
+ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<TelemetryRuntime['reportError']> {
43
49
  const [
44
50
  { WebTracerProvider },
45
51
  { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },
@@ -49,7 +55,7 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<vo
49
55
  { DocumentLoadInstrumentation },
50
56
  { FetchInstrumentation },
51
57
  { W3CTraceContextPropagator },
52
- { defaultTextMapSetter },
58
+ { defaultTextMapSetter, SpanStatusCode },
53
59
  ] = await Promise.all([
54
60
  import('@opentelemetry/sdk-trace-web'),
55
61
  import('@opentelemetry/sdk-trace-base'),
@@ -170,6 +176,22 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<vo
170
176
  if (document.visibilityState === 'hidden') flush()
171
177
  })
172
178
  window.addEventListener('pagehide', flush)
179
+
180
+ const tracer = provider.getTracer('@open-mercato/telemetry/browser')
181
+ return (error, context) => {
182
+ const serialized = serializeError(error)
183
+ const attributes = redactAttributes({ ...context?.attributes, module: context?.module })
184
+ delete attributes['error.code']
185
+ const code = groupableCode(context?.code)
186
+ if (code) attributes['error.code'] = code
187
+ const span = tracer.startSpan('browser.error', { attributes })
188
+ try {
189
+ span.recordException(serialized)
190
+ span.setStatus({ code: SpanStatusCode.ERROR })
191
+ } finally {
192
+ span.end()
193
+ }
194
+ }
173
195
  }
174
196
 
175
197
  function escapeRegExp(value: string): string {
@@ -185,7 +207,13 @@ export function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig |
185
207
  React.useEffect(() => {
186
208
  if (!config || bootstrapped) return
187
209
  bootstrapped = true
188
- void startBrowserTelemetry(config).catch(() => {
210
+ const reporter = startBrowserTelemetry(config)
211
+ const dispose = registerTelemetryErrorReporter((...args) => {
212
+ void reporter.then((reportError) => reportError(...args)).catch(() => {})
213
+ })
214
+ disposeErrorReporter = dispose
215
+ void reporter.catch(() => {
216
+ dispose()
189
217
  // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).
190
218
  })
191
219
  }, [config])
@@ -44,6 +44,7 @@ jest.mock('@opentelemetry/sdk-trace-web', () =>
44
44
  WebTracerProvider: class {
45
45
  register = jest.fn()
46
46
  forceFlush = jest.fn(async () => {})
47
+ getTracer = jest.fn(() => ({ startSpan: jest.fn() }))
47
48
  constructor(options: Record<string, unknown>) {
48
49
  mockProviderInstances.push({ options, register: this.register, forceFlush: this.forceFlush })
49
50
  }