@burdenoff/be-sdk 2026.1110.4 → 2026.1111.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.
@@ -20,18 +20,19 @@ const asyncDisposeMetricReader = async (metricReaderCandidate) => {
20
20
  }
21
21
  };
22
22
  async function createOtelSdk(cfg) {
23
+ const load = (name) => cfg.modules?.[name] !== void 0 ? Promise.resolve(cfg.modules[name]) : importOptionalPeer(name);
23
24
  console.log("[sdk] importing @opentelemetry/sdk-node...");
24
- const sdkMod = await importOptionalPeer("@opentelemetry/sdk-node");
25
+ const sdkMod = await load("@opentelemetry/sdk-node");
25
26
  console.log("[sdk] importing @opentelemetry/resources...");
26
- const resources = await importOptionalPeer("@opentelemetry/resources");
27
+ const resources = await load("@opentelemetry/resources");
27
28
  console.log("[sdk] importing @opentelemetry/semantic-conventions...");
28
- const sem = await importOptionalPeer("@opentelemetry/semantic-conventions");
29
+ const sem = await load("@opentelemetry/semantic-conventions");
29
30
  console.log("[sdk] importing @opentelemetry/exporter-trace-otlp-http...");
30
- const traceExp = await importOptionalPeer("@opentelemetry/exporter-trace-otlp-http");
31
+ const traceExp = await load("@opentelemetry/exporter-trace-otlp-http");
31
32
  console.log("[sdk] importing @opentelemetry/exporter-metrics-otlp-http...");
32
33
  let metricsExp;
33
34
  try {
34
- metricsExp = await importOptionalPeer("@opentelemetry/exporter-metrics-otlp-http");
35
+ metricsExp = await load("@opentelemetry/exporter-metrics-otlp-http");
35
36
  } catch {
36
37
  metricsExp = void 0;
37
38
  console.log("[sdk] metrics exporter not available (non-fatal)");
@@ -40,7 +41,7 @@ async function createOtelSdk(cfg) {
40
41
  let metricsEnabled = false;
41
42
  let metricsDropReason;
42
43
  if (metricsExp?.OTLPMetricExporter) try {
43
- const candidate = new (await (importOptionalPeer("@opentelemetry/sdk-metrics"))).PeriodicExportingMetricReader({ exporter: new metricsExp.OTLPMetricExporter({ url: `${cfg.otlpEndpoint.replace(/\/$/, "")}/v1/metrics` }) });
44
+ const candidate = new (await (load("@opentelemetry/sdk-metrics"))).PeriodicExportingMetricReader({ exporter: new metricsExp.OTLPMetricExporter({ url: `${cfg.otlpEndpoint.replace(/\/$/, "")}/v1/metrics` }) });
44
45
  if (typeof candidate.setMetricProducer === "function") {
45
46
  metricReader = candidate;
46
47
  metricsEnabled = true;
@@ -56,7 +57,7 @@ async function createOtelSdk(cfg) {
56
57
  console.log("[sdk] importing @opentelemetry/sdk-trace-base for sampler...");
57
58
  let sampler;
58
59
  try {
59
- const traceBase = await importOptionalPeer("@opentelemetry/sdk-trace-base");
60
+ const traceBase = await load("@opentelemetry/sdk-trace-base");
60
61
  sampler = new traceBase.ParentBasedSampler({ root: new traceBase.TraceIdRatioBasedSampler(Math.min(1, Math.max(0, cfg.sampleRatio))) });
61
62
  } catch {
62
63
  sampler = void 0;
@@ -65,7 +66,7 @@ async function createOtelSdk(cfg) {
65
66
  console.log("[sdk] importing @opentelemetry/auto-instrumentations-node...");
66
67
  let autoInstrumentations;
67
68
  try {
68
- autoInstrumentations = (await importOptionalPeer("@opentelemetry/auto-instrumentations-node")).getNodeAutoInstrumentations({ "@opentelemetry/instrumentation-fs": { enabled: false } });
69
+ autoInstrumentations = (await load("@opentelemetry/auto-instrumentations-node")).getNodeAutoInstrumentations({ "@opentelemetry/instrumentation-fs": { enabled: false } });
69
70
  console.log("[sdk] auto-instrumentations loaded");
70
71
  } catch {
71
72
  autoInstrumentations = void 0;
@@ -107,7 +108,7 @@ async function createOtelSdk(cfg) {
107
108
  if (isThenable(startResult)) await startResult;
108
109
  console.log("[sdk] NodeSDK started");
109
110
  try {
110
- globalThis.__otelApi = await importOptionalPeer("@opentelemetry/api");
111
+ globalThis.__otelApi = await load("@opentelemetry/api");
111
112
  console.log("[sdk] @opentelemetry/api stashed for pino mixin");
112
113
  } catch {
113
114
  console.log("[sdk] @opentelemetry/api stash failed (non-fatal)");
@@ -121,4 +122,4 @@ async function createOtelSdk(cfg) {
121
122
  }
122
123
 
123
124
  export { createOtelSdk };
124
- //# sourceMappingURL=sdk-Dju9o-sq.js.map
125
+ //# sourceMappingURL=sdk-B62itAH1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-B62itAH1.js","names":[],"sources":["../src/telemetry/sdk.ts"],"sourcesContent":["/**\n * Thin wrapper that initializes `@opentelemetry/sdk-node` with the\n * OTLPTrace + OTLPMetric exporters and standard auto-instrumentations.\n *\n * All imports are dynamic so services that haven't installed sdk-node\n * still compile and run. The function resolves `undefined` when the SDK\n * isn't available, letting `bootstrapTelemetry` fall back gracefully.\n */\nimport { importOptionalPeer } from '../utils/import-optional-peer.js';\nimport type { TelemetryIdGenerator } from './id-generator.js';\nimport type { Boundary, Env } from './index.js';\n\nexport interface OtelSdkConfig {\n serviceName: string;\n serviceVersion: string;\n boundary: Boundary;\n module?: string;\n env: Env;\n otlpEndpoint: string;\n sampleRatio: number;\n /**\n * Optional trace/span id generator handed to NodeSDK's tracer provider.\n * Omitted means the SDK's default random generator.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name. A package found\n * here is used as is; any other one is loaded at runtime from the consumer's\n * `node_modules` through `importOptionalPeer`. A service built with\n * `bun build --compile` has no `node_modules` at runtime, so it imports the\n * packages statically and hands them in here.\n */\n modules?: OtelModules;\n}\n\n/** The OpenTelemetry packages `createOtelSdk` can load. */\nexport type OtelPeerPackage =\n | '@opentelemetry/api'\n | '@opentelemetry/auto-instrumentations-node'\n | '@opentelemetry/exporter-metrics-otlp-http'\n | '@opentelemetry/exporter-trace-otlp-http'\n | '@opentelemetry/resources'\n | '@opentelemetry/sdk-metrics'\n | '@opentelemetry/sdk-node'\n | '@opentelemetry/sdk-trace-base'\n | '@opentelemetry/semantic-conventions';\n\n/** Module namespaces injected in place of runtime imports (see `OtelSdkConfig.modules`). */\nexport type OtelModules = Partial<Record<OtelPeerPackage, unknown>>;\n\nexport interface OtelSdkHandle {\n shutdown: () => Promise<void>;\n metricsEnabled: boolean;\n metricsDropReason?: string;\n}\n\ntype Thenable = {\n then: (onfulfilled?: (value: void) => void, onrejected?: (reason: unknown) => void) => unknown;\n};\n\nconst isThenable = (value: unknown): value is Thenable => {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n};\n\nconst asyncDisposeMetricReader = async (metricReaderCandidate: unknown): Promise<void> => {\n const shutdown = (metricReaderCandidate as { shutdown?: () => void | Promise<void> }).shutdown;\n if (typeof shutdown === 'function') {\n const result = shutdown.call(metricReaderCandidate) as unknown;\n if (isThenable(result)) await result;\n }\n};\n\nexport async function createOtelSdk(cfg: OtelSdkConfig): Promise<OtelSdkHandle> {\n const load = (name: OtelPeerPackage): Promise<unknown> =>\n cfg.modules?.[name] !== undefined ? Promise.resolve(cfg.modules[name]) : importOptionalPeer(name);\n console.log('[sdk] importing @opentelemetry/sdk-node...');\n const sdkMod = (await load('@opentelemetry/sdk-node')) as {\n NodeSDK: new (init: Record<string, unknown>) => {\n start: () => void;\n shutdown: () => Promise<void>;\n };\n };\n\n console.log('[sdk] importing @opentelemetry/resources...');\n const resources = (await load('@opentelemetry/resources')) as {\n resourceFromAttributes: (attrs: Record<string, string | number>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/semantic-conventions...');\n const sem = (await load('@opentelemetry/semantic-conventions')) as Record<string, string>;\n\n console.log('[sdk] importing @opentelemetry/exporter-trace-otlp-http...');\n const traceExp = (await load('@opentelemetry/exporter-trace-otlp-http')) as {\n OTLPTraceExporter: new (init: Record<string, string>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/exporter-metrics-otlp-http...');\n let metricsExp: { OTLPMetricExporter?: new (init: Record<string, string>) => unknown } | undefined;\n try {\n metricsExp = (await load('@opentelemetry/exporter-metrics-otlp-http')) as typeof metricsExp;\n } catch {\n metricsExp = undefined;\n console.log('[sdk] metrics exporter not available (non-fatal)');\n }\n\n let metricReader: unknown;\n let metricsEnabled = false;\n let metricsDropReason: string | undefined;\n if (metricsExp?.OTLPMetricExporter) {\n try {\n const metricsSdk = (await load('@opentelemetry/sdk-metrics')) as {\n PeriodicExportingMetricReader: new (init: Record<string, unknown>) => unknown;\n };\n const candidate = new metricsSdk.PeriodicExportingMetricReader({\n exporter: new metricsExp.OTLPMetricExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/metrics`,\n }),\n });\n // Pre-flight API compatibility check. Some OTel package version\n // combinations construct `PeriodicExportingMetricReader` successfully\n // but lack `setMetricProducer` on the prototype chain (mixed\n // sdk-metrics versions, or runtime-specific class-inheritance\n // quirks — Bun has surfaced this in the past). Without the check,\n // `NodeSDK.start()` may register the global tracer provider BEFORE\n // it tries to call `setMetricProducer` and throws — leaving the\n // global tracer pointing at a half-initialized provider whose\n // span pipeline never drains. Skipping the metric reader when the\n // API isn't there avoids that whole failure mode in one pass.\n const setProducer = (candidate as { setMetricProducer?: unknown }).setMetricProducer;\n if (typeof setProducer === 'function') {\n metricReader = candidate;\n metricsEnabled = true;\n } else {\n metricsDropReason =\n 'setMetricProducer is not a function on PeriodicExportingMetricReader; skipping metrics path';\n await asyncDisposeMetricReader(candidate);\n metricReader = undefined;\n }\n } catch {\n if (metricsDropReason === undefined) {\n metricsDropReason = 'metric reader construction or compatibility check failed';\n }\n metricReader = undefined;\n }\n }\n\n console.log('[sdk] importing @opentelemetry/sdk-trace-base for sampler...');\n let sampler: unknown;\n try {\n const traceBase = (await load('@opentelemetry/sdk-trace-base')) as {\n ParentBasedSampler: new (init: Record<string, unknown>) => unknown;\n TraceIdRatioBasedSampler: new (ratio: number) => unknown;\n };\n sampler = new traceBase.ParentBasedSampler({\n root: new traceBase.TraceIdRatioBasedSampler(Math.min(1, Math.max(0, cfg.sampleRatio))),\n });\n } catch {\n sampler = undefined;\n console.log('[sdk] sampler not available (non-fatal)');\n }\n\n // Some services have auto-instrumentations installed; optional.\n console.log('[sdk] importing @opentelemetry/auto-instrumentations-node...');\n let autoInstrumentations: unknown[] | undefined;\n try {\n const auto = (await load('@opentelemetry/auto-instrumentations-node')) as {\n getNodeAutoInstrumentations: (cfg?: Record<string, unknown>) => unknown[];\n };\n autoInstrumentations = auto.getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-fs': { enabled: false },\n });\n console.log('[sdk] auto-instrumentations loaded');\n } catch {\n autoInstrumentations = undefined;\n console.log('[sdk] auto-instrumentations not available (non-fatal)');\n }\n\n const serviceNamespaceByBoundary: Record<Boundary, string> = {\n wspace: 'workspaces',\n global: 'tenant',\n gateway: 'gateways',\n };\n const resourceAttributes: Record<string, string> = {\n [sem['SEMRESATTRS_SERVICE_NAME'] ?? 'service.name']: cfg.serviceName,\n [sem['SEMRESATTRS_SERVICE_VERSION'] ?? 'service.version']: cfg.serviceVersion,\n [sem['SEMRESATTRS_SERVICE_NAMESPACE'] ?? 'service.namespace']: serviceNamespaceByBoundary[cfg.boundary],\n [sem['SEMRESATTRS_DEPLOYMENT_ENVIRONMENT'] ?? 'deployment.environment']: cfg.env,\n 'burdenoff.boundary': cfg.boundary,\n };\n if (cfg.module) resourceAttributes['burdenoff.module'] = cfg.module;\n const serviceInstanceId = process.env['POD_NAME'] ?? process.env['HOSTNAME'];\n if (serviceInstanceId) resourceAttributes['service.instance.id'] = serviceInstanceId;\n const clusterName = process.env['CLUSTER_NAME'];\n if (clusterName) {\n resourceAttributes['cluster'] = clusterName;\n resourceAttributes['k8s.cluster.name'] = clusterName;\n }\n\n const resource = resources.resourceFromAttributes(resourceAttributes);\n\n const traceExporter = new traceExp.OTLPTraceExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/traces`,\n });\n\n // Single NodeSDK, single start. The pre-flight `setMetricProducer`\n // check above means we never pass an incompatible metric reader into\n // NodeSDK construction — so we no longer need the prior catch+rebuild\n // fallback dance, which had its own side-effect: the failed first\n // NodeSDK could leave the global tracer provider partially registered,\n // and the second NodeSDK's `setGlobalTracerProvider` becomes a no-op\n // — meaning spans flow into the FIRST (broken) provider and never\n // reach the exporter. Eliminating the fallback eliminates that hazard.\n console.log('[sdk] constructing NodeSDK...');\n const nodeSdk = new sdkMod.NodeSDK({\n resource,\n traceExporter,\n ...(metricReader ? { metricReader } : {}),\n ...(sampler ? { sampler } : {}),\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(autoInstrumentations ? { instrumentations: autoInstrumentations } : {}),\n });\n console.log('[sdk] NodeSDK constructed, calling start()...');\n // NodeSDK.start() returns void in modern versions and Promise<void> in older\n // ones. Cast to a permissive thenable shape so awaiting works either way\n // without tripping `@typescript-eslint/await-thenable`.\n const startResult = nodeSdk.start() as unknown;\n if (isThenable(startResult)) {\n await startResult;\n }\n console.log('[sdk] NodeSDK started');\n\n // Stash the @opentelemetry/api reference for pino-logger's mixin.\n try {\n (globalThis as unknown as { __otelApi?: unknown }).__otelApi = await load('@opentelemetry/api');\n console.log('[sdk] @opentelemetry/api stashed for pino mixin');\n } catch {\n console.log('[sdk] @opentelemetry/api stash failed (non-fatal)');\n }\n\n console.log('[sdk] OTel SDK initialization complete');\n return {\n shutdown: async (): Promise<void> => nodeSdk.shutdown(),\n metricsEnabled,\n metricsDropReason,\n };\n}\n"],"mappings":";;;;;;;;;;;AA4DA,MAAM,cAAc,UAAsC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAA6B,SAAS;AACtG;AAEA,MAAM,2BAA2B,OAAO,0BAAkD;CACxF,MAAM,WAAY,sBAAoE;CACtF,IAAI,OAAO,aAAa,YAAY;EAClC,MAAM,SAAS,SAAS,KAAK,qBAAqB;EAClD,IAAI,WAAW,MAAM,GAAG,MAAM;CAChC;AACF;AAEA,eAAsB,cAAc,KAA4C;CAC9E,MAAM,QAAQ,SACZ,IAAI,UAAU,UAAU,SAAY,QAAQ,QAAQ,IAAI,QAAQ,KAAK,IAAI,mBAAmB,IAAI;CAClG,QAAQ,IAAI,4CAA4C;CACxD,MAAM,SAAU,MAAM,KAAK,yBAAyB;C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D;CAC/D,QAAQ;EACN,QAAQ,IAAI,mDAAmD;CACjE;CAEA,QAAQ,IAAI,wCAAwC;CACpD,OAAO;EACL,UAAU,YAA2B,QAAQ,SAAS;EACtD;EACA;CACF;AACF"}
@@ -5,6 +5,8 @@ interface TelemetryIdGenerator {
5
5
  generateSpanId(): string;
6
6
  }
7
7
  export declare function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined;
8
+ type OtelPeerPackage = '@opentelemetry/api' | '@opentelemetry/auto-instrumentations-node' | '@opentelemetry/exporter-metrics-otlp-http' | '@opentelemetry/exporter-trace-otlp-http' | '@opentelemetry/resources' | '@opentelemetry/sdk-metrics' | '@opentelemetry/sdk-node' | '@opentelemetry/sdk-trace-base' | '@opentelemetry/semantic-conventions';
9
+ type OtelModules = Partial<Record<OtelPeerPackage, unknown>>;
8
10
  interface PrismaLike {
9
11
  $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;
10
12
  }
@@ -73,6 +75,7 @@ export interface TelemetryConfig {
73
75
  sampleRatio?: number;
74
76
  instrumentation?: SetupInstrumentationOptions;
75
77
  idGenerator?: TelemetryIdGenerator;
78
+ otelModules?: OtelModules;
76
79
  }
77
80
  export interface TelemetryHandle {
78
81
  serviceName: string;
@@ -83,4 +86,4 @@ export interface TelemetryHandle {
83
86
  shutdown: () => Promise<void>;
84
87
  }
85
88
  export declare function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle>;
86
- export { type CollectorLayer, type TelemetryIdGenerator, initializeInstrumentation, setupInstrumentation };
89
+ export { type CollectorLayer, type OtelModules, type OtelPeerPackage, type TelemetryIdGenerator, initializeInstrumentation, setupInstrumentation };
@@ -348,7 +348,7 @@ async function bootstrapTelemetry(cfg) {
348
348
  if (resolveOtelSdkEnabled()) {
349
349
  console.log("[telemetry] OTel SDK bootstrap starting...");
350
350
  try {
351
- const { createOtelSdk } = await import("../sdk-Dju9o-sq.js");
351
+ const { createOtelSdk } = await import("../sdk-B62itAH1.js");
352
352
  otelSdk = await createOtelSdk({
353
353
  serviceName: cfg.serviceName,
354
354
  serviceVersion,
@@ -357,7 +357,8 @@ async function bootstrapTelemetry(cfg) {
357
357
  env,
358
358
  otlpEndpoint,
359
359
  sampleRatio,
360
- ...cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}
360
+ ...cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {},
361
+ ...cfg.otelModules ? { modules: cfg.otelModules } : {}
361
362
  });
362
363
  logger$1.info("[telemetry] OpenTelemetry exporter pipeline started", {
363
364
  serviceName: cfg.serviceName,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as {\n register: PromRegistryLike;\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n };\n // Kick runtime metrics into the default registry if not already.\n try {\n mod.collectDefaultMetrics({ register: mod.register });\n } catch {\n // Already registered — ignore duplicate-metric errors.\n }\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelSdkHandle } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAgB,2BAA2B,WAA2E;CACpH,IAAI,cAAc,QAAW;CAC7B,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,IAAI,UAAU,2FAA2F;CAEjH,MAAM,EAAE,iBAAiB,mBAAmB;CAI5C,IAAI,OAAO,oBAAoB,cAAc,OAAO,mBAAmB,YACrE,MAAM,IAAI,UAAU,4FAA4F;AAEpH;;;ACyCA,SAAgB,mBAAmB,QAAoB,CAAC,GAAY;CAElE,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,SAAS,MAAe;EAI1B,IAAI,SAAS,SAAS,SAAS,QAAQ,OAAO;CAEhD,EACF,CACF;AACF;;;ACjFA,eAAsB,sBAAwD;CAC5E,IAAI;EACF,MAAM,MAAO,MAAM,OAAO;EAK1B,IAAI;GACF,IAAI,sBAAsB,EAAE,UAAU,IAAI,SAAS,CAAC;EACtD,QAAQ,CAER;EACA,OAAO,IAAI;CACb,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,wBAId,KAAU,OAA4B,CAAC,GAAQ;CAC/C,MAAM,OAAO,KAAK,QAAQ;CAE1B,IAAI,IAAI,MAAM,OAAO,QAAmC;EACtD,MAAM,WAAW,KAAK,YAAa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,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as {\n register: PromRegistryLike;\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n };\n // Kick runtime metrics into the default registry if not already.\n try {\n mod.collectDefaultMetrics({ register: mod.register });\n } catch {\n // Already registered — ignore duplicate-metric errors.\n }\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelModules, OtelSdkHandle } from './sdk.js';\n\nexport type { OtelModules, OtelPeerPackage } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name (see\n * `OtelModules`). Needed by services built with `bun build --compile`,\n * which have no `node_modules` to load the optional peers from at runtime.\n */\n otelModules?: OtelModules;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(cfg.otelModules ? { modules: cfg.otelModules } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAgB,2BAA2B,WAA2E;CACpH,IAAI,cAAc,QAAW;CAC7B,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,IAAI,UAAU,2FAA2F;CAEjH,MAAM,EAAE,iBAAiB,mBAAmB;CAI5C,IAAI,OAAO,oBAAoB,cAAc,OAAO,mBAAmB,YACrE,MAAM,IAAI,UAAU,4FAA4F;AAEpH;;;ACyCA,SAAgB,mBAAmB,QAAoB,CAAC,GAAY;CAElE,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,SAAS,MAAe;EAI1B,IAAI,SAAS,SAAS,SAAS,QAAQ,OAAO;CAEhD,EACF,CACF;AACF;;;ACjFA,eAAsB,sBAAwD;CAC5E,IAAI;EACF,MAAM,MAAO,MAAM,OAAO;EAK1B,IAAI;GACF,IAAI,sBAAsB,EAAE,UAAU,IAAI,SAAS,CAAC;EACtD,QAAQ,CAER;EACA,OAAO,IAAI;CACb,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,wBAId,KAAU,OAA4B,CAAC,GAAQ;CAC/C,MAAM,OAAO,KAAK,QAAQ;CAE1B,IAAI,IAAI,MA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+CAA+C;CAC7D;CAEA,MAAM,WAAW,YAA2B;EAC1C,IAAI;GACF,IAAI,SAAS,UAAU,MAAM,QAAQ,SAAS;EAChD,SAAS,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/be-sdk",
3
- "version": "2026.1110.4",
3
+ "version": "2026.1111.1",
4
4
  "description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-Dju9o-sq.js","names":[],"sources":["../src/telemetry/sdk.ts"],"sourcesContent":["/**\n * Thin wrapper that initializes `@opentelemetry/sdk-node` with the\n * OTLPTrace + OTLPMetric exporters and standard auto-instrumentations.\n *\n * All imports are dynamic so services that haven't installed sdk-node\n * still compile and run. The function resolves `undefined` when the SDK\n * isn't available, letting `bootstrapTelemetry` fall back gracefully.\n */\nimport { importOptionalPeer } from '../utils/import-optional-peer.js';\nimport type { TelemetryIdGenerator } from './id-generator.js';\nimport type { Boundary, Env } from './index.js';\n\nexport interface OtelSdkConfig {\n serviceName: string;\n serviceVersion: string;\n boundary: Boundary;\n module?: string;\n env: Env;\n otlpEndpoint: string;\n sampleRatio: number;\n /**\n * Optional trace/span id generator handed to NodeSDK's tracer provider.\n * Omitted means the SDK's default random generator.\n */\n idGenerator?: TelemetryIdGenerator;\n}\n\nexport interface OtelSdkHandle {\n shutdown: () => Promise<void>;\n metricsEnabled: boolean;\n metricsDropReason?: string;\n}\n\ntype Thenable = {\n then: (onfulfilled?: (value: void) => void, onrejected?: (reason: unknown) => void) => unknown;\n};\n\nconst isThenable = (value: unknown): value is Thenable => {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n};\n\nconst asyncDisposeMetricReader = async (metricReaderCandidate: unknown): Promise<void> => {\n const shutdown = (metricReaderCandidate as { shutdown?: () => void | Promise<void> }).shutdown;\n if (typeof shutdown === 'function') {\n const result = shutdown.call(metricReaderCandidate) as unknown;\n if (isThenable(result)) await result;\n }\n};\n\nexport async function createOtelSdk(cfg: OtelSdkConfig): Promise<OtelSdkHandle> {\n console.log('[sdk] importing @opentelemetry/sdk-node...');\n const sdkMod = (await importOptionalPeer('@opentelemetry/sdk-node')) as {\n NodeSDK: new (init: Record<string, unknown>) => {\n start: () => void;\n shutdown: () => Promise<void>;\n };\n };\n\n console.log('[sdk] importing @opentelemetry/resources...');\n const resources = (await importOptionalPeer('@opentelemetry/resources')) as {\n resourceFromAttributes: (attrs: Record<string, string | number>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/semantic-conventions...');\n const sem = (await importOptionalPeer('@opentelemetry/semantic-conventions')) as Record<string, string>;\n\n console.log('[sdk] importing @opentelemetry/exporter-trace-otlp-http...');\n const traceExp = (await importOptionalPeer('@opentelemetry/exporter-trace-otlp-http')) as {\n OTLPTraceExporter: new (init: Record<string, string>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/exporter-metrics-otlp-http...');\n let metricsExp: { OTLPMetricExporter?: new (init: Record<string, string>) => unknown } | undefined;\n try {\n metricsExp = (await importOptionalPeer('@opentelemetry/exporter-metrics-otlp-http')) as typeof metricsExp;\n } catch {\n metricsExp = undefined;\n console.log('[sdk] metrics exporter not available (non-fatal)');\n }\n\n let metricReader: unknown;\n let metricsEnabled = false;\n let metricsDropReason: string | undefined;\n if (metricsExp?.OTLPMetricExporter) {\n try {\n const metricsSdk = (await importOptionalPeer('@opentelemetry/sdk-metrics')) as {\n PeriodicExportingMetricReader: new (init: Record<string, unknown>) => unknown;\n };\n const candidate = new metricsSdk.PeriodicExportingMetricReader({\n exporter: new metricsExp.OTLPMetricExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/metrics`,\n }),\n });\n // Pre-flight API compatibility check. Some OTel package version\n // combinations construct `PeriodicExportingMetricReader` successfully\n // but lack `setMetricProducer` on the prototype chain (mixed\n // sdk-metrics versions, or runtime-specific class-inheritance\n // quirks — Bun has surfaced this in the past). Without the check,\n // `NodeSDK.start()` may register the global tracer provider BEFORE\n // it tries to call `setMetricProducer` and throws — leaving the\n // global tracer pointing at a half-initialized provider whose\n // span pipeline never drains. Skipping the metric reader when the\n // API isn't there avoids that whole failure mode in one pass.\n const setProducer = (candidate as { setMetricProducer?: unknown }).setMetricProducer;\n if (typeof setProducer === 'function') {\n metricReader = candidate;\n metricsEnabled = true;\n } else {\n metricsDropReason =\n 'setMetricProducer is not a function on PeriodicExportingMetricReader; skipping metrics path';\n await asyncDisposeMetricReader(candidate);\n metricReader = undefined;\n }\n } catch {\n if (metricsDropReason === undefined) {\n metricsDropReason = 'metric reader construction or compatibility check failed';\n }\n metricReader = undefined;\n }\n }\n\n console.log('[sdk] importing @opentelemetry/sdk-trace-base for sampler...');\n let sampler: unknown;\n try {\n const traceBase = (await importOptionalPeer('@opentelemetry/sdk-trace-base')) as {\n ParentBasedSampler: new (init: Record<string, unknown>) => unknown;\n TraceIdRatioBasedSampler: new (ratio: number) => unknown;\n };\n sampler = new traceBase.ParentBasedSampler({\n root: new traceBase.TraceIdRatioBasedSampler(Math.min(1, Math.max(0, cfg.sampleRatio))),\n });\n } catch {\n sampler = undefined;\n console.log('[sdk] sampler not available (non-fatal)');\n }\n\n // Some services have auto-instrumentations installed; optional.\n console.log('[sdk] importing @opentelemetry/auto-instrumentations-node...');\n let autoInstrumentations: unknown[] | undefined;\n try {\n const auto = (await importOptionalPeer('@opentelemetry/auto-instrumentations-node')) as {\n getNodeAutoInstrumentations: (cfg?: Record<string, unknown>) => unknown[];\n };\n autoInstrumentations = auto.getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-fs': { enabled: false },\n });\n console.log('[sdk] auto-instrumentations loaded');\n } catch {\n autoInstrumentations = undefined;\n console.log('[sdk] auto-instrumentations not available (non-fatal)');\n }\n\n const serviceNamespaceByBoundary: Record<Boundary, string> = {\n wspace: 'workspaces',\n global: 'tenant',\n gateway: 'gateways',\n };\n const resourceAttributes: Record<string, string> = {\n [sem['SEMRESATTRS_SERVICE_NAME'] ?? 'service.name']: cfg.serviceName,\n [sem['SEMRESATTRS_SERVICE_VERSION'] ?? 'service.version']: cfg.serviceVersion,\n [sem['SEMRESATTRS_SERVICE_NAMESPACE'] ?? 'service.namespace']: serviceNamespaceByBoundary[cfg.boundary],\n [sem['SEMRESATTRS_DEPLOYMENT_ENVIRONMENT'] ?? 'deployment.environment']: cfg.env,\n 'burdenoff.boundary': cfg.boundary,\n };\n if (cfg.module) resourceAttributes['burdenoff.module'] = cfg.module;\n const serviceInstanceId = process.env['POD_NAME'] ?? process.env['HOSTNAME'];\n if (serviceInstanceId) resourceAttributes['service.instance.id'] = serviceInstanceId;\n const clusterName = process.env['CLUSTER_NAME'];\n if (clusterName) {\n resourceAttributes['cluster'] = clusterName;\n resourceAttributes['k8s.cluster.name'] = clusterName;\n }\n\n const resource = resources.resourceFromAttributes(resourceAttributes);\n\n const traceExporter = new traceExp.OTLPTraceExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/traces`,\n });\n\n // Single NodeSDK, single start. The pre-flight `setMetricProducer`\n // check above means we never pass an incompatible metric reader into\n // NodeSDK construction — so we no longer need the prior catch+rebuild\n // fallback dance, which had its own side-effect: the failed first\n // NodeSDK could leave the global tracer provider partially registered,\n // and the second NodeSDK's `setGlobalTracerProvider` becomes a no-op\n // — meaning spans flow into the FIRST (broken) provider and never\n // reach the exporter. Eliminating the fallback eliminates that hazard.\n console.log('[sdk] constructing NodeSDK...');\n const nodeSdk = new sdkMod.NodeSDK({\n resource,\n traceExporter,\n ...(metricReader ? { metricReader } : {}),\n ...(sampler ? { sampler } : {}),\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(autoInstrumentations ? { instrumentations: autoInstrumentations } : {}),\n });\n console.log('[sdk] NodeSDK constructed, calling start()...');\n // NodeSDK.start() returns void in modern versions and Promise<void> in older\n // ones. Cast to a permissive thenable shape so awaiting works either way\n // without tripping `@typescript-eslint/await-thenable`.\n const startResult = nodeSdk.start() as unknown;\n if (isThenable(startResult)) {\n await startResult;\n }\n console.log('[sdk] NodeSDK started');\n\n // Stash the @opentelemetry/api reference for pino-logger's mixin.\n try {\n (globalThis as unknown as { __otelApi?: unknown }).__otelApi = await importOptionalPeer('@opentelemetry/api');\n console.log('[sdk] @opentelemetry/api stashed for pino mixin');\n } catch {\n console.log('[sdk] @opentelemetry/api stash failed (non-fatal)');\n }\n\n console.log('[sdk] OTel SDK initialization complete');\n return {\n shutdown: async (): Promise<void> => nodeSdk.shutdown(),\n metricsEnabled,\n metricsDropReason,\n };\n}\n"],"mappings":";;;;;;;;;;;AAqCA,MAAM,cAAc,UAAsC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAA6B,SAAS;AACtG;AAEA,MAAM,2BAA2B,OAAO,0BAAkD;CACxF,MAAM,WAAY,sBAAoE;CACtF,IAAI,OAAO,aAAa,YAAY;EAClC,MAAM,SAAS,SAAS,KAAK,qBAAqB;EAClD,IAAI,WAAW,MAAM,GAAG,MAAM;CAChC;AACF;AAEA,eAAsB,cAAc,KAA4C;CAC9E,QAAQ,IAAI,4CAA4C;CACxD,MAAM,SAAU,MAAM,mBAAmB,yBAAyB;CAOlE,QAAQ,IAAI,6CAA6C;CACzD,MAAM,YAAa,MAAM,mBAAmB,0BAA0B;CAItE,QAAQ,IAAI,wDAAwD;CACpE,MAAM,MAAO,MAAM,mBAAmB,qCAAqC;CAE3E,QAAQ,IAAI,4DAA4D;CACxE,MAAM,WAAY,MAAM,mBAAmB,yC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