autotel 5.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +14 -1
  2. package/dist/auto.cjs +1 -1
  3. package/dist/auto.js +1 -1
  4. package/dist/correlation-id.cjs +9 -9
  5. package/dist/correlation-id.js +1 -1
  6. package/dist/decorators.cjs +2 -2
  7. package/dist/decorators.cjs.map +1 -1
  8. package/dist/decorators.js +1 -1
  9. package/dist/drain-pipeline.cjs +10 -1
  10. package/dist/drain-pipeline.cjs.map +1 -1
  11. package/dist/drain-pipeline.d.cts +5 -0
  12. package/dist/drain-pipeline.d.cts.map +1 -1
  13. package/dist/drain-pipeline.d.ts +5 -0
  14. package/dist/drain-pipeline.d.ts.map +1 -1
  15. package/dist/drain-pipeline.js +10 -1
  16. package/dist/drain-pipeline.js.map +1 -1
  17. package/dist/event.cjs +4 -4
  18. package/dist/event.js +1 -1
  19. package/dist/{functional-Bit6noRu.js → functional-BnDUxnSl.js} +2 -4
  20. package/dist/{functional-Bit6noRu.js.map → functional-BnDUxnSl.js.map} +1 -1
  21. package/dist/{functional-Cj7PSItS.cjs → functional-DcLBuCPz.cjs} +12 -14
  22. package/dist/{functional-Cj7PSItS.cjs.map → functional-DcLBuCPz.cjs.map} +1 -1
  23. package/dist/functional.cjs +1 -1
  24. package/dist/functional.js +1 -1
  25. package/dist/http.cjs +2 -2
  26. package/dist/http.cjs.map +1 -1
  27. package/dist/http.js +1 -1
  28. package/dist/index.cjs +33 -166
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +5 -2
  31. package/dist/index.d.cts.map +1 -1
  32. package/dist/index.d.ts +5 -2
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +14 -147
  35. package/dist/index.js.map +1 -1
  36. package/dist/init-C3RApHKJ.cjs +3371 -0
  37. package/dist/init-C3RApHKJ.cjs.map +1 -0
  38. package/dist/{init-CTyqG9qR.d.ts → init-D6n2diBy.d.ts} +21 -2
  39. package/dist/init-D6n2diBy.d.ts.map +1 -0
  40. package/dist/init-R-gSEXkJ.js +3190 -0
  41. package/dist/init-R-gSEXkJ.js.map +1 -0
  42. package/dist/{init-a4yPDYqC.d.cts → init-XzXzrarP.d.cts} +21 -2
  43. package/dist/init-XzXzrarP.d.cts.map +1 -0
  44. package/dist/instrumentation.cjs +1 -1
  45. package/dist/instrumentation.js +1 -1
  46. package/dist/messaging.cjs +1 -1
  47. package/dist/messaging.js +1 -1
  48. package/dist/semantic-helpers.cjs +1 -1
  49. package/dist/semantic-helpers.js +1 -1
  50. package/dist/webhook.cjs +1 -1
  51. package/dist/webhook.js +1 -1
  52. package/dist/workflow-distributed.cjs +1 -1
  53. package/dist/workflow-distributed.js +1 -1
  54. package/dist/workflow.cjs +1 -1
  55. package/dist/workflow.js +1 -1
  56. package/dist/yaml-config.d.cts +1 -1
  57. package/dist/yaml-config.d.ts +1 -1
  58. package/package.json +2 -3
  59. package/dist/event-CwIpFdoY.cjs +0 -778
  60. package/dist/event-CwIpFdoY.cjs.map +0 -1
  61. package/dist/event-pLMF5b3d.js +0 -761
  62. package/dist/event-pLMF5b3d.js.map +0 -1
  63. package/dist/init-B2uvZReD.cjs +0 -1120
  64. package/dist/init-B2uvZReD.cjs.map +0 -1
  65. package/dist/init-CTyqG9qR.d.ts.map +0 -1
  66. package/dist/init-CdEWjhvl.js +0 -1043
  67. package/dist/init-CdEWjhvl.js.map +0 -1
  68. package/dist/init-a4yPDYqC.d.cts.map +0 -1
  69. package/dist/operation-context-CKBoA4Qy.js +0 -59
  70. package/dist/operation-context-CKBoA4Qy.js.map +0 -1
  71. package/dist/operation-context-hzKbTKnt.cjs +0 -72
  72. package/dist/operation-context-hzKbTKnt.cjs.map +0 -1
  73. package/dist/track-BBcxEJEC.js +0 -1110
  74. package/dist/track-BBcxEJEC.js.map +0 -1
  75. package/dist/track-BI6dmZ2X.cjs +0 -1207
  76. package/dist/track-BI6dmZ2X.cjs.map +0 -1
  77. package/skills/analyze-traces/SKILL.md +0 -209
  78. package/skills/autotel-core/SKILL.md +0 -166
  79. package/skills/autotel-events/SKILL.md +0 -84
  80. package/skills/autotel-frameworks/SKILL.md +0 -125
  81. package/skills/autotel-instrumentation/SKILL.md +0 -150
  82. package/skills/autotel-request-logging/SKILL.md +0 -99
  83. package/skills/autotel-structured-errors/SKILL.md +0 -125
  84. package/skills/build-audit-trails/SKILL.md +0 -460
  85. package/skills/build-audit-trails/references/audit-queries.md +0 -73
  86. package/skills/build-audit-trails/references/framework-wiring.md +0 -196
  87. package/skills/debug-missing-spans/SKILL.md +0 -250
  88. package/skills/migrate-to-autotel/SKILL.md +0 -269
  89. package/skills/review-otel-patterns/SKILL.md +0 -540
  90. package/skills/review-otel-patterns/references/code-review.md +0 -76
  91. package/skills/review-otel-patterns/references/processor-pipeline.md +0 -205
  92. package/skills/review-otel-patterns/references/structured-errors.md +0 -102
  93. package/skills/review-otel-patterns/references/wide-spans.md +0 -85
  94. package/skills/tune-sampling/SKILL.md +0 -290
package/dist/index.cjs CHANGED
@@ -2,19 +2,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_rolldown_runtime = require('./rolldown-runtime-C_NdSu1c.cjs');
3
3
  const require_tracer_provider = require('./tracer-provider.cjs');
4
4
  const require_sampling = require('./sampling.cjs');
5
- const require_init = require('./init-B2uvZReD.cjs');
5
+ const require_init = require('./init-C3RApHKJ.cjs');
6
6
  const require_filtering_span_processor = require('./filtering-span-processor.cjs');
7
7
  const require_span_name_normalizer = require('./span-name-normalizer.cjs');
8
8
  const require_attribute_redacting_processor = require('./attribute-redacting-processor.cjs');
9
9
  const require_canonical_log_line_processor = require('./canonical-log-line-processor-DOjb6Kxy.cjs');
10
- const require_track = require('./track-BI6dmZ2X.cjs');
11
10
  const require_structured_error = require('./structured-error-CHg7DoIQ.cjs');
11
+ const require_metric = require('./metric.cjs');
12
12
  const require_trace_helpers = require('./trace-helpers.cjs');
13
- const require_operation_context = require('./operation-context-hzKbTKnt.cjs');
14
- const require_functional = require('./functional-Cj7PSItS.cjs');
13
+ const require_functional = require('./functional-DcLBuCPz.cjs');
15
14
  const require_stable_hash = require('./stable-hash-CS9BxvVQ.cjs');
16
- const require_event = require('./event-CwIpFdoY.cjs');
17
- const require_metric = require('./metric.cjs');
18
15
  const require_correlated_events = require('./correlated-events-kSwLo3mi.cjs');
19
16
  const require_parse_error = require('./parse-error.cjs');
20
17
  const require_drain_pipeline = require('./drain-pipeline.cjs');
@@ -73,149 +70,11 @@ function defineEvent(name, schema, options = {}) {
73
70
  track(payload) {
74
71
  const parsed = schema.safeParse(payload);
75
72
  if (!parsed.success) throw new Error(`Invalid payload for event "${name}". Schema validation failed.`);
76
- require_track.track(name, parsed.data, schemaMetadata ? { schema: schemaMetadata } : void 0);
73
+ require_init.track(name, parsed.data, schemaMetadata ? { schema: schemaMetadata } : void 0);
77
74
  }
78
75
  };
79
76
  }
80
77
 
81
- //#endregion
82
- //#region src/shutdown.ts
83
- /**
84
- * Graceful shutdown with flush and cleanup
85
- */
86
- /**
87
- * Flush all pending telemetry
88
- *
89
- * Flushes both events events and OpenTelemetry spans to their destinations.
90
- * Includes timeout protection to prevent hanging in serverless environments.
91
- *
92
- * Safe to call multiple times.
93
- *
94
- * @param options - Optional configuration
95
- * @param options.timeout - Timeout in milliseconds (default: 2000ms)
96
- * @param options.forShutdown - If true, permanently disables the events queue after flush (used internally by shutdown())
97
- *
98
- * @example Manual flush in serverless
99
- * ```typescript
100
- * import { flush } from 'autotel';
101
- *
102
- * export const handler = async (event) => {
103
- * // ... process event
104
- * await flush(); // Flush before function returns
105
- * return result;
106
- * };
107
- * ```
108
- *
109
- * @example With custom timeout
110
- * ```typescript
111
- * await flush({ timeout: 5000 }); // 5 second timeout
112
- * ```
113
- */
114
- async function flush(options) {
115
- const timeout = options?.timeout ?? 2e3;
116
- const forShutdown = options?.forShutdown ?? false;
117
- const doFlush = async () => {
118
- const eventsQueue = require_track.getEventQueue();
119
- if (eventsQueue) await (forShutdown ? eventsQueue.shutdown() : eventsQueue.flush());
120
- try {
121
- const tracerProvider = require_tracer_provider.getForceFlushableProvider(require_init.getSdk());
122
- if (tracerProvider) await tracerProvider.forceFlush();
123
- } catch {}
124
- };
125
- let timeoutHandle;
126
- try {
127
- await Promise.race([doFlush().finally(() => {
128
- if (timeoutHandle) clearTimeout(timeoutHandle);
129
- }), new Promise((_, reject) => {
130
- timeoutHandle = setTimeout(() => reject(/* @__PURE__ */ new Error("Flush timeout")), timeout);
131
- timeoutHandle.unref();
132
- })]);
133
- } catch (error) {
134
- if (timeoutHandle) clearTimeout(timeoutHandle);
135
- require_init.getLogger().error({ err: error instanceof Error ? error : new Error(String(error)) }, "[autotel] Flush error");
136
- throw error;
137
- }
138
- }
139
- /**
140
- * Shutdown telemetry and cleanup resources
141
- *
142
- * - Flushes all pending data
143
- * - Shuts down OpenTelemetry SDK
144
- * - Cleans up resources
145
- *
146
- * Call this before process exit.
147
- *
148
- * Always performs cleanup even if flush fails, preventing resource leaks
149
- * in serverless handlers or tests.
150
- *
151
- * @example Express server
152
- * ```typescript
153
- * const server = app.listen(3000)
154
- *
155
- * process.on('SIGTERM', async () => {
156
- * await server.close()
157
- * await shutdown()
158
- * process.exit(0)
159
- * })
160
- * ```
161
- */
162
- async function shutdown() {
163
- const logger = require_init.getLogger();
164
- let shutdownError = null;
165
- try {
166
- await flush({ forShutdown: true });
167
- } catch (error) {
168
- const err = error instanceof Error ? error : new Error(String(error));
169
- shutdownError = err;
170
- logger.error({ err }, "[autotel] Flush failed during shutdown, continuing cleanup");
171
- }
172
- try {
173
- const sdk = require_init.getSdk();
174
- if (sdk) await sdk.shutdown();
175
- } catch (error) {
176
- const err = error instanceof Error ? error : new Error(String(error));
177
- if (!(typeof error === "object" && error !== null && "code" in error && error.code === "ECONNREFUSED")) {
178
- if (!shutdownError) shutdownError = err;
179
- logger.error({ err }, "[autotel] SDK shutdown failed");
180
- }
181
- } finally {
182
- await require_init._closeEmbeddedDevtools();
183
- const eventsQueue = require_track.getEventQueue();
184
- if (eventsQueue && typeof eventsQueue.cleanup === "function") eventsQueue.cleanup();
185
- require_event.resetEvents();
186
- require_metric.resetMetrics();
187
- require_track.resetEventQueue();
188
- }
189
- if (shutdownError) throw shutdownError;
190
- }
191
- /**
192
- * Register automatic shutdown hooks for common signals
193
- *
194
- * Handles:
195
- * - SIGTERM (Docker/K8s graceful shutdown)
196
- * - SIGINT (Ctrl+C)
197
- *
198
- * @internal Called automatically on module load
199
- */
200
- function registerShutdownHooks() {
201
- if (typeof process === "undefined") return;
202
- const signals = ["SIGTERM", "SIGINT"];
203
- let shuttingDown = false;
204
- for (const signal of signals) process.on(signal, async () => {
205
- if (shuttingDown) return;
206
- shuttingDown = true;
207
- if (process.env.NODE_ENV !== "test") require_init.getLogger().info({}, `[autotel] Received ${signal}, flushing telemetry...`);
208
- try {
209
- await shutdown();
210
- } catch (error) {
211
- require_init.getLogger().error({ err: error instanceof Error ? error : void 0 }, "[autotel] Error during shutdown");
212
- } finally {
213
- process.exit(0);
214
- }
215
- });
216
- }
217
- registerShutdownHooks();
218
-
219
78
  //#endregion
220
79
  //#region src/request-logger.ts
221
80
  const POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when available.";
@@ -242,13 +101,14 @@ function resolveContext(ctx) {
242
101
  if (stored) return stored;
243
102
  const span = _opentelemetry_api.trace.getActiveSpan();
244
103
  if (!span) throw new Error("[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext().");
245
- return require_track.createTraceContext(span);
104
+ return require_init.createTraceContext(span);
246
105
  }
247
106
  function getRequestLogger(ctx, options) {
248
107
  const activeContext = resolveContext(ctx);
249
108
  const contextState = {};
250
109
  let emitted = false;
251
110
  let lastSnapshot = null;
111
+ let hasExplicitLevel = false;
252
112
  const addLogEvent = (level, message, fields) => {
253
113
  const attrs = fields ? require_structured_error.flattenToAttributes(fields) : void 0;
254
114
  require_correlated_events.emitCorrelatedEvent(activeContext, `log.${level}`, {
@@ -266,6 +126,12 @@ function getRequestLogger(ctx, options) {
266
126
  mergeInto$1(contextState, fields);
267
127
  activeContext.setAttributes(require_structured_error.flattenToAttributes(fields));
268
128
  },
129
+ setLevel(level) {
130
+ sealCheck("log.setLevel()", ["autotel.log.level"]);
131
+ if (emitted) return;
132
+ hasExplicitLevel = true;
133
+ activeContext.setAttribute("autotel.log.level", level);
134
+ },
269
135
  info(message, fields) {
270
136
  const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"];
271
137
  sealCheck("log.info()", keys);
@@ -281,7 +147,7 @@ function getRequestLogger(ctx, options) {
281
147
  sealCheck("log.warn()", keys);
282
148
  if (emitted) return;
283
149
  addLogEvent("warn", message, fields);
284
- activeContext.setAttribute("autotel.log.level", "warn");
150
+ if (!hasExplicitLevel) activeContext.setAttribute("autotel.log.level", "warn");
285
151
  if (fields) {
286
152
  mergeInto$1(contextState, fields);
287
153
  activeContext.setAttributes(require_structured_error.flattenToAttributes(fields));
@@ -298,7 +164,7 @@ function getRequestLogger(ctx, options) {
298
164
  mergeInto$1(contextState, fields);
299
165
  activeContext.setAttributes(require_structured_error.flattenToAttributes(fields));
300
166
  }
301
- activeContext.setAttribute("autotel.log.level", "error");
167
+ if (!hasExplicitLevel) activeContext.setAttribute("autotel.log.level", "error");
302
168
  },
303
169
  getContext() {
304
170
  return { ...contextState };
@@ -336,7 +202,7 @@ function getRequestLogger(ctx, options) {
336
202
  const lifecycle = forkOptions?.lifecycle;
337
203
  tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {
338
204
  const childContext = {
339
- ...require_track.createTraceContext(childSpan),
205
+ ...require_init.createTraceContext(childSpan),
340
206
  correlationId: crypto.randomUUID()
341
207
  };
342
208
  requestContextStore.run(childContext, () => {
@@ -402,6 +268,7 @@ function createNoopRequestLogger() {
402
268
  });
403
269
  return {
404
270
  set() {},
271
+ setLevel() {},
405
272
  info() {},
406
273
  warn() {},
407
274
  error() {},
@@ -650,8 +517,8 @@ exports.AlwaysSampler = require_sampling.AlwaysSampler;
650
517
  exports.AttributeRedactingProcessor = require_attribute_redacting_processor.AttributeRedactingProcessor;
651
518
  exports.BaggageSpanProcessor = require_init.BaggageSpanProcessor;
652
519
  exports.BusinessBaggage = require_business_baggage.BusinessBaggage;
653
- exports.CORRELATION_ID_BAGGAGE_KEY = require_track.CORRELATION_ID_BAGGAGE_KEY;
654
- exports.Event = require_event.Event;
520
+ exports.CORRELATION_ID_BAGGAGE_KEY = require_init.CORRELATION_ID_BAGGAGE_KEY;
521
+ exports.Event = require_init.Event;
655
522
  exports.FilteringSpanProcessor = require_filtering_span_processor.FilteringSpanProcessor;
656
523
  exports.HTTPAttributes = require_registry.HTTPAttributes;
657
524
  exports.Metric = require_metric.Metric;
@@ -708,7 +575,7 @@ exports.createUpDownCounter = require_metric_helpers.createUpDownCounter;
708
575
  exports.ctx = require_functional.ctx;
709
576
  exports.dbClient = require_attributes.dbClient;
710
577
  exports.defineAuditCatalog = defineAuditCatalog;
711
- exports.defineBaggageSchema = require_track.defineBaggageSchema;
578
+ exports.defineBaggageSchema = require_init.defineBaggageSchema;
712
579
  exports.defineDrain = defineDrain;
713
580
  exports.defineEnricher = defineEnricher;
714
581
  exports.defineErrorCatalog = defineErrorCatalog;
@@ -719,23 +586,23 @@ exports.extractLinksFromBatch = require_sampling.extractLinksFromBatch;
719
586
  exports.finalizeSpan = require_trace_helpers.finalizeSpan;
720
587
  exports.flattenMetadata = require_trace_helpers.flattenMetadata;
721
588
  exports.flattenToAttributes = require_structured_error.flattenToAttributes;
722
- exports.flush = flush;
589
+ exports.flush = require_init.flush;
723
590
  exports.formatDuration = require_canonical_log_line_processor.formatDuration;
724
- exports.generateCorrelationId = require_track.generateCorrelationId;
591
+ exports.generateCorrelationId = require_init.generateCorrelationId;
725
592
  exports.getActiveContext = require_trace_helpers.getActiveContext;
726
593
  exports.getActiveSpan = require_trace_helpers.getActiveSpan;
727
594
  exports.getActiveTraceContext = require_functional.getActiveTraceContext;
728
595
  exports.getAutotelTracer = require_tracer_provider.getAutotelTracer;
729
596
  exports.getAutotelTracerProvider = require_tracer_provider.getAutotelTracerProvider;
730
597
  exports.getCatalogCode = getCatalogCode;
731
- exports.getCorrelationId = require_track.getCorrelationId;
598
+ exports.getCorrelationId = require_init.getCorrelationId;
732
599
  exports.getCurrentWorkflowContext = require_workflow.getCurrentWorkflowContext;
733
- exports.getEventQueue = require_track.getEventQueue;
734
- exports.getEvents = require_event.getEvents;
600
+ exports.getEventQueue = require_init.getEventQueue;
601
+ exports.getEvents = require_init.getEvents;
735
602
  exports.getMeter = require_metric_helpers.getMeter;
736
603
  exports.getMetrics = require_metric.getMetrics;
737
- exports.getOperationContext = require_operation_context.getOperationContext;
738
- exports.getOrCreateCorrelationId = require_track.getOrCreateCorrelationId;
604
+ exports.getOperationContext = require_init.getOperationContext;
605
+ exports.getOrCreateCorrelationId = require_init.getOrCreateCorrelationId;
739
606
  exports.getRequestLogger = getRequestLogger;
740
607
  exports.getRequestLoggerSafe = getRequestLoggerSafe;
741
608
  exports.getStructuredErrorAttributes = require_structured_error.getStructuredErrorAttributes;
@@ -773,25 +640,25 @@ Object.defineProperty(exports, 'propagation', {
773
640
  });
774
641
  exports.recordStructuredError = require_structured_error.recordStructuredError;
775
642
  exports.request = require_attributes.request;
776
- exports.resetEvents = require_event.resetEvents;
643
+ exports.resetEvents = require_init.resetEvents;
777
644
  exports.resetMetrics = require_metric.resetMetrics;
778
645
  exports.resolveSamplingPreset = require_sampling.resolveSamplingPreset;
779
646
  exports.resolveTraceUrl = require_trace_helpers.resolveTraceUrl;
780
- exports.runInOperationContext = require_operation_context.runInOperationContext;
781
- exports.runWithCorrelationId = require_track.runWithCorrelationId;
647
+ exports.runInOperationContext = require_init.runInOperationContext;
648
+ exports.runWithCorrelationId = require_init.runWithCorrelationId;
782
649
  exports.runWithRequestContext = runWithRequestContext;
783
650
  exports.runWithSpan = require_trace_helpers.runWithSpan;
784
651
  exports.safeSetAttributes = require_attributes.safeSetAttributes;
785
652
  exports.samplingPresets = require_sampling.samplingPresets;
786
653
  exports.setAutotelTracerProvider = require_tracer_provider.setAutotelTracerProvider;
787
- exports.setCorrelationId = require_track.setCorrelationId;
788
- exports.setCorrelationIdInBaggage = require_track.setCorrelationIdInBaggage;
654
+ exports.setCorrelationId = require_init.setCorrelationId;
655
+ exports.setCorrelationIdInBaggage = require_init.setCorrelationIdInBaggage;
789
656
  exports.setDevice = require_attributes.setDevice;
790
657
  exports.setError = require_attributes.setError;
791
658
  exports.setException = require_attributes.setException;
792
659
  exports.setSession = require_attributes.setSession;
793
660
  exports.setUser = require_attributes.setUser;
794
- exports.shutdown = shutdown;
661
+ exports.shutdown = require_init.shutdown;
795
662
  exports.span = require_functional.span;
796
663
  exports.structuredErrorToJSON = require_structured_error.structuredErrorToJSON;
797
664
  exports.toAttributeValue = require_structured_error.toAttributeValue;
@@ -803,7 +670,7 @@ exports.traceMessaging = require_semantic_helpers.traceMessaging;
803
670
  exports.traceProducer = require_messaging.traceProducer;
804
671
  exports.traceStep = require_workflow.traceStep;
805
672
  exports.traceWorkflow = require_workflow.traceWorkflow;
806
- exports.track = require_track.track;
673
+ exports.track = require_init.track;
807
674
  exports.validateAttribute = require_attributes.validateAttribute;
808
675
  exports.withBaggage = require_functional.withBaggage;
809
676
  exports.withNewContext = require_functional.withNewContext;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["otelTraceApi","autotelTraceFn","hashJson","getEventQueue","getForceFlushableProvider","getSdk","getLogger","_closeEmbeddedDevtools","mergeInto","nodeAsyncHooks","otelTrace","createTraceContext","flattenToAttributes","createStructuredError"],"sources":["../src/trace-hybrid.ts","../src/define-event.ts","../src/shutdown.ts","../src/request-logger.ts","../src/error-catalog.ts","../src/drain-toolkit.ts","../src/enricher-toolkit.ts"],"sourcesContent":["/**\n * Hybrid `trace` export: callable like autotel's `trace(fn)`, AND exposes the\n * full `@opentelemetry/api` `TraceAPI` surface (`trace.getActiveSpan()`,\n * `trace.getTracer()`, …) so existing OTel code \"just works\" when imported\n * from `autotel`.\n *\n * Implementation: `Object.assign` mutates the autotel `trace` function to\n * attach the OTel TraceAPI methods. Because every reference to `trace` across\n * autotel resolves to the same function instance, this is a one-time, global\n * augmentation.\n */\n\nimport { trace as otelTraceApi } from '@opentelemetry/api';\nimport { trace as autotelTraceFn } from './functional';\n\nconst otelMethods = {\n // Class methods on TraceAPI — bind to the singleton.\n setGlobalTracerProvider:\n otelTraceApi.setGlobalTracerProvider.bind(otelTraceApi),\n getTracerProvider: otelTraceApi.getTracerProvider.bind(otelTraceApi),\n getTracer: otelTraceApi.getTracer.bind(otelTraceApi),\n disable: otelTraceApi.disable.bind(otelTraceApi),\n // Instance fields on TraceAPI — already standalone, copy by reference.\n wrapSpanContext: otelTraceApi.wrapSpanContext,\n isSpanContextValid: otelTraceApi.isSpanContextValid,\n deleteSpan: otelTraceApi.deleteSpan,\n getSpan: otelTraceApi.getSpan,\n getActiveSpan: otelTraceApi.getActiveSpan,\n getSpanContext: otelTraceApi.getSpanContext,\n setSpan: otelTraceApi.setSpan,\n setSpanContext: otelTraceApi.setSpanContext,\n};\n\nexport const trace: typeof autotelTraceFn & typeof otelTraceApi = Object.assign(\n autotelTraceFn,\n otelMethods,\n) as typeof autotelTraceFn & typeof otelTraceApi;\n","import { track } from './track';\nimport { hashJson } from './stable-hash';\nimport type { EventSchemaMetadata } from './event-subscriber';\n\ntype SafeParseResult<T> =\n { success: true; data: T } | { success: false; error: unknown };\n\nexport interface SchemaLike<T> {\n safeParse(input: unknown): SafeParseResult<T>;\n}\n\nexport interface DefineEventOptions<S> {\n toJsonSchema?: (schema: S) => unknown;\n}\n\nexport interface DefinedEvent<Name extends string, Payload> {\n readonly name: Name;\n readonly schemaMetadata?: EventSchemaMetadata;\n track(payload: Payload): void;\n}\n\nexport function defineEvent<\n Name extends string,\n Payload,\n S extends SchemaLike<Payload>,\n>(\n name: Name,\n schema: S,\n options: DefineEventOptions<S> = {},\n): DefinedEvent<Name, Payload> {\n const jsonSchema = options.toJsonSchema?.(schema);\n const schemaMetadata = jsonSchema\n ? {\n source: 'zod' as const,\n jsonSchema,\n hash: hashJson(jsonSchema),\n }\n : undefined;\n\n return {\n name,\n schemaMetadata,\n track(payload: Payload) {\n const parsed = schema.safeParse(payload);\n if (!parsed.success) {\n throw new Error(\n `Invalid payload for event \"${name}\". Schema validation failed.`,\n );\n }\n track(\n name,\n parsed.data,\n schemaMetadata ? { schema: schemaMetadata } : undefined,\n );\n },\n };\n}\n","/**\n * Graceful shutdown with flush and cleanup\n */\n\nimport { getSdk, getLogger, _closeEmbeddedDevtools } from './init';\nimport { getEventQueue, resetEventQueue } from './track';\nimport { resetEvents } from './event';\nimport { resetMetrics } from './metric';\nimport { getForceFlushableProvider } from './tracer-provider';\n\n/**\n * Flush all pending telemetry\n *\n * Flushes both events events and OpenTelemetry spans to their destinations.\n * Includes timeout protection to prevent hanging in serverless environments.\n *\n * Safe to call multiple times.\n *\n * @param options - Optional configuration\n * @param options.timeout - Timeout in milliseconds (default: 2000ms)\n * @param options.forShutdown - If true, permanently disables the events queue after flush (used internally by shutdown())\n *\n * @example Manual flush in serverless\n * ```typescript\n * import { flush } from 'autotel';\n *\n * export const handler = async (event) => {\n * // ... process event\n * await flush(); // Flush before function returns\n * return result;\n * };\n * ```\n *\n * @example With custom timeout\n * ```typescript\n * await flush({ timeout: 5000 }); // 5 second timeout\n * ```\n */\nexport async function flush(options?: {\n timeout?: number;\n forShutdown?: boolean;\n}): Promise<void> {\n const timeout = options?.timeout ?? 2000;\n const forShutdown = options?.forShutdown ?? false;\n\n const doFlush = async () => {\n // Flush events queue (or shutdown queue when tearing down)\n const eventsQueue = getEventQueue();\n if (eventsQueue) {\n await (forShutdown ? eventsQueue.shutdown() : eventsQueue.flush());\n }\n\n // Flush OpenTelemetry spans\n // This ensures spans are exported immediately, critical for serverless.\n // NodeSDK.getTracerProvider() returns undefined on sdk-node 0.220+, so\n // resolve a force-flushable provider from the global registry too.\n try {\n const tracerProvider = getForceFlushableProvider(getSdk());\n if (tracerProvider) {\n await tracerProvider.forceFlush();\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n };\n\n // Add timeout protection to prevent hanging\n let timeoutHandle: NodeJS.Timeout | undefined;\n try {\n await Promise.race([\n doFlush().finally(() => {\n // Clear timeout as soon as flush completes\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n }),\n new Promise<void>((_, reject) => {\n timeoutHandle = setTimeout(\n () => reject(new Error('Flush timeout')),\n timeout,\n );\n // Use unref() to allow Node to exit if flush completes first\n // This prevents the 2s delay in serverless when flush succeeds immediately\n timeoutHandle.unref();\n }),\n ]);\n } catch (error) {\n // Clear timeout on error too\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n const logger = getLogger();\n logger.error(\n {\n err: error instanceof Error ? error : new Error(String(error)),\n },\n '[autotel] Flush error',\n );\n throw error;\n }\n}\n\n/**\n * Shutdown telemetry and cleanup resources\n *\n * - Flushes all pending data\n * - Shuts down OpenTelemetry SDK\n * - Cleans up resources\n *\n * Call this before process exit.\n *\n * Always performs cleanup even if flush fails, preventing resource leaks\n * in serverless handlers or tests.\n *\n * @example Express server\n * ```typescript\n * const server = app.listen(3000)\n *\n * process.on('SIGTERM', async () => {\n * await server.close()\n * await shutdown()\n * process.exit(0)\n * })\n * ```\n */\nexport async function shutdown(): Promise<void> {\n const logger = getLogger();\n let shutdownError: Error | null = null;\n\n // Attempt to flush (with queue shutdown so new events are rejected), but continue with cleanup even if it fails\n try {\n await flush({ forShutdown: true });\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n shutdownError = err;\n logger.error(\n {\n err,\n },\n '[autotel] Flush failed during shutdown, continuing cleanup',\n );\n }\n\n // Always shutdown SDK and clean up resources\n try {\n // Shutdown OpenTelemetry SDK\n const sdk = getSdk();\n if (sdk) {\n await sdk.shutdown();\n }\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Ignore ECONNREFUSED errors - this happens when no OTLP endpoint was configured\n // The SDK tries to flush exporters that don't exist, which is harmless\n const isConnectionRefused =\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n error.code === 'ECONNREFUSED';\n\n if (!isConnectionRefused) {\n // Only store/log non-connection errors\n if (!shutdownError) {\n shutdownError = err;\n }\n logger.error({ err }, '[autotel] SDK shutdown failed');\n }\n } finally {\n await _closeEmbeddedDevtools();\n\n // Clean up singleton Maps and queues to prevent memory leaks\n // This runs even if SDK shutdown fails\n const eventsQueue = getEventQueue();\n if (eventsQueue && typeof eventsQueue.cleanup === 'function') {\n eventsQueue.cleanup();\n }\n resetEvents();\n resetMetrics();\n resetEventQueue();\n }\n\n // Rethrow first error after cleanup completes\n // This allows tests and CI to detect failures while still ensuring cleanup\n if (shutdownError) {\n throw shutdownError;\n }\n}\n\n/**\n * Register automatic shutdown hooks for common signals\n *\n * Handles:\n * - SIGTERM (Docker/K8s graceful shutdown)\n * - SIGINT (Ctrl+C)\n *\n * @internal Called automatically on module load\n */\nfunction registerShutdownHooks(): void {\n if (typeof process === 'undefined') return; // Not in Node.js\n\n const signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\n let shuttingDown = false;\n\n for (const signal of signals) {\n process.on(signal, async () => {\n if (shuttingDown) return; // Prevent double shutdown\n shuttingDown = true;\n\n if (process.env.NODE_ENV !== 'test') {\n getLogger().info(\n {},\n `[autotel] Received ${signal}, flushing telemetry...`,\n );\n }\n\n try {\n await shutdown();\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n '[autotel] Error during shutdown',\n );\n } finally {\n process.exit(0);\n }\n });\n }\n}\n\n// Auto-register shutdown hooks\nregisterShutdownHooks();\n","// namespace import for browser-bundler compat — see node-require.ts\nimport * as nodeAsyncHooks from 'node:async_hooks';\nimport { trace as otelTrace } from '@opentelemetry/api';\nimport type { TraceContext } from './trace-context';\nimport { createTraceContext } from './trace-context';\nimport { recordStructuredError } from './structured-error';\nimport { flattenToAttributes } from './flatten-attributes';\nimport { emitCorrelatedEvent } from './correlated-events';\n\nconst POST_EMIT_FORK_HINT =\n \"For intentional background work tied to this request, use log.fork('label', fn) when available.\";\n\nfunction warnPostEmit(method: string, detail: string): void {\n console.warn(\n `[autotel] ${method} called after the wide event was emitted — ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`,\n );\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key in source) {\n const sourceVal = source[key];\n if (sourceVal === undefined) continue;\n const targetVal = target[key];\n if (\n sourceVal !== null &&\n typeof sourceVal === 'object' &&\n !Array.isArray(sourceVal) &&\n targetVal !== null &&\n typeof targetVal === 'object' &&\n !Array.isArray(targetVal)\n ) {\n mergeInto(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>,\n );\n } else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n target[key] = [...targetVal, ...sourceVal];\n } else {\n target[key] = sourceVal;\n }\n }\n}\n\nconst requestContextStore =\n new nodeAsyncHooks.AsyncLocalStorage<TraceContext>();\n\nexport function runWithRequestContext<T>(ctx: TraceContext, fn: () => T): T {\n return requestContextStore.run(ctx, fn);\n}\n\nexport interface RequestLogger {\n set(fields: Record<string, unknown>): void;\n info(message: string, fields?: Record<string, unknown>): void;\n warn(message: string, fields?: Record<string, unknown>): void;\n error(error: Error | string, fields?: Record<string, unknown>): void;\n getContext(): Record<string, unknown>;\n emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot;\n fork(\n label: string,\n fn: () => void | Promise<void>,\n options?: ForkOptions,\n ): void;\n}\n\nexport interface RequestLogSnapshot {\n timestamp: string;\n traceId: string;\n spanId: string;\n correlationId: string;\n context: Record<string, unknown>;\n}\n\nexport interface RequestLoggerOptions {\n /** Callback invoked by emitNow() for manual fan-out. */\n onEmit?: (snapshot: RequestLogSnapshot) => void | Promise<void>;\n}\n\n/**\n * Optional lifecycle hooks for adapters that need to track child loggers\n * spawned by `log.fork()` (e.g. active logger maps in framework integrations).\n */\nexport interface ForkLifecycle {\n /** Called after the child logger is created, before `fn` runs. */\n onChildEnter?: (child: RequestLogger) => void;\n /** Called after the child has finished (emit + drain), success or failure. */\n onChildExit?: (child: RequestLogger) => void;\n}\n\nexport interface ForkOptions {\n lifecycle?: ForkLifecycle;\n}\n\nfunction resolveContext(ctx?: TraceContext): TraceContext {\n if (ctx) return ctx;\n\n const stored = requestContextStore.getStore();\n if (stored) return stored;\n\n const span = otelTrace.getActiveSpan();\n if (!span) {\n throw new Error(\n '[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext().',\n );\n }\n return createTraceContext(span);\n}\n\nexport function getRequestLogger(\n ctx?: TraceContext,\n options?: RequestLoggerOptions,\n): RequestLogger {\n const activeContext = resolveContext(ctx);\n const contextState: Record<string, unknown> = {};\n let emitted = false;\n let lastSnapshot: RequestLogSnapshot | null = null;\n\n const addLogEvent = (\n level: 'info' | 'warn' | 'error',\n message: string,\n fields?: Record<string, unknown>,\n ) => {\n const attrs = fields ? flattenToAttributes(fields) : undefined;\n emitCorrelatedEvent(activeContext, `log.${level}`, {\n message,\n ...attrs,\n });\n };\n\n const sealCheck = (method: string, keys: string[]): void => {\n if (emitted) {\n warnPostEmit(\n method,\n `Keys dropped: ${keys.length > 0 ? keys.join(', ') : '(empty)'}.`,\n );\n }\n };\n\n return {\n set(fields: Record<string, unknown>) {\n sealCheck('log.set()', Object.keys(fields));\n if (emitted) return;\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n },\n\n info(message: string, fields?: Record<string, unknown>) {\n const keys = fields\n ? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]\n : ['message'];\n sealCheck('log.info()', keys);\n if (emitted) return;\n addLogEvent('info', message, fields);\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n },\n\n warn(message: string, fields?: Record<string, unknown>) {\n const keys = fields\n ? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]\n : ['message'];\n sealCheck('log.warn()', keys);\n if (emitted) return;\n addLogEvent('warn', message, fields);\n activeContext.setAttribute('autotel.log.level', 'warn');\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n },\n\n error(error: Error | string, fields?: Record<string, unknown>) {\n const keys = fields ? [...Object.keys(fields), 'error'] : ['error'];\n sealCheck('log.error()', keys);\n if (emitted) return;\n const err = typeof error === 'string' ? new Error(error) : error;\n recordStructuredError(activeContext, err);\n addLogEvent('error', err.message, fields);\n\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n activeContext.setAttribute('autotel.log.level', 'error');\n },\n\n getContext() {\n return { ...contextState };\n },\n\n emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot {\n if (emitted) {\n warnPostEmit('log.emitNow()', 'Ignoring duplicate emit.');\n return lastSnapshot as RequestLogSnapshot;\n }\n\n const mergedContext = {\n ...contextState,\n ...overrides,\n };\n const flattened = flattenToAttributes(mergedContext);\n activeContext.setAttributes(flattened);\n\n const snapshot: RequestLogSnapshot = {\n timestamp: new Date().toISOString(),\n traceId: activeContext.traceId,\n spanId: activeContext.spanId,\n correlationId: activeContext.correlationId,\n context: mergedContext,\n };\n\n emitCorrelatedEvent(activeContext, 'log.emit.manual', {\n ...flattened,\n });\n\n if (options?.onEmit) {\n Promise.resolve(options.onEmit(snapshot)).catch((error) => {\n console.warn('[autotel] request logger onEmit failed:', error);\n });\n }\n\n emitted = true;\n lastSnapshot = snapshot;\n return snapshot;\n },\n\n fork(\n label: string,\n fn: () => void | Promise<void>,\n forkOptions?: ForkOptions,\n ): void {\n const parentRequestId = activeContext.correlationId;\n if (typeof parentRequestId !== 'string' || parentRequestId.length === 0) {\n throw new Error(\n '[autotel] log.fork() requires the parent logger to have a correlationId. ' +\n 'Ensure the request was created by autotel middleware.',\n );\n }\n\n const tracer = otelTrace.getTracer('autotel.request-logger');\n const lifecycle = forkOptions?.lifecycle;\n void tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {\n const childContext: TraceContext = {\n ...createTraceContext(childSpan),\n correlationId: crypto.randomUUID(),\n };\n\n requestContextStore.run(childContext, () => {\n const childLog = getRequestLogger(childContext);\n childLog.set({\n operation: label,\n _parentCorrelationId: parentRequestId,\n });\n\n lifecycle?.onChildEnter?.(childLog);\n\n void Promise.resolve()\n .then(() => fn())\n .then(() => {\n childLog.emitNow();\n })\n .catch((error_: unknown) => {\n const error =\n error_ instanceof Error ? error_ : new Error(String(error_));\n childLog.error(error);\n childLog.emitNow();\n })\n .finally(() => {\n try {\n lifecycle?.onChildExit?.(childLog);\n } catch (hookError) {\n console.warn(\n '[autotel] fork onChildExit hook threw:',\n hookError,\n );\n }\n childSpan.end();\n });\n });\n });\n },\n };\n}\n\n/**\n * Returns `true` when a request-logger context can be resolved without throwing —\n * i.e. an explicit `ctx` was provided, a `runWithRequestContext()` scope is active,\n * or there is an active OpenTelemetry span.\n *\n * Use this to branch on observability availability instead of wrapping\n * {@link getRequestLogger} in try/catch.\n */\nexport function hasRequestContext(ctx?: TraceContext): boolean {\n if (ctx) return true;\n if (requestContextStore.getStore()) return true;\n return otelTrace.getActiveSpan() != null;\n}\n\n/**\n * Like {@link getRequestLogger}, but returns `null` instead of throwing when no\n * request context is available. Intended for best-effort instrumentation where a\n * missing telemetry context must never crash business logic.\n */\nexport function getRequestLoggerSafe(\n ctx?: TraceContext,\n options?: RequestLoggerOptions,\n): RequestLogger | null {\n if (!hasRequestContext(ctx)) return null;\n return getRequestLogger(ctx, options);\n}\n\n/**\n * A no-op {@link RequestLogger} whose methods do nothing. Used as a fallback by\n * best-effort instrumentation so wrapped handlers can run un-instrumented without\n * branching on logger presence.\n */\nexport function createNoopRequestLogger(): RequestLogger {\n const snapshot = (): RequestLogSnapshot => ({\n timestamp: new Date().toISOString(),\n traceId: '',\n spanId: '',\n correlationId: '',\n context: {},\n });\n\n return {\n set() {},\n info() {},\n warn() {},\n error() {},\n getContext() {\n return {};\n },\n emitNow() {\n return snapshot();\n },\n fork(_label, fn) {\n void Promise.resolve().then(() => fn());\n },\n };\n}\n","/**\n * Typed error and audit catalogs.\n *\n * Group related errors into one catalog and get a refactor-safe builder per\n * code, with autocomplete at every call site and typed message parameters.\n *\n * @example\n * ```typescript\n * import { defineErrorCatalog } from 'autotel';\n *\n * export const billing = defineErrorCatalog('billing', {\n * PAYMENT_DECLINED: {\n * status: 402,\n * message: 'Card declined',\n * why: 'The issuer rejected the charge',\n * fix: 'Try a different payment method',\n * },\n * INSUFFICIENT_FUNDS: {\n * status: 402,\n * message: ({ available, required }: { available: number; required: number }) =>\n * `Insufficient funds: $${available} of $${required}`,\n * },\n * });\n *\n * throw billing.PAYMENT_DECLINED({ cause: stripeError });\n * throw billing.INSUFFICIENT_FUNDS({ available: 5, required: 100 });\n *\n * // In a catch block — refactor-safe, no magic strings:\n * if (billing.PAYMENT_DECLINED.match(err)) { ... }\n * ```\n */\n\nimport {\n createStructuredError,\n type StructuredError,\n} from './structured-error';\n\nconst catalogCodeKey = Symbol.for('autotel.catalog.code');\n\n/** Definition of a single error in a catalog. */\nexport interface ErrorCatalogEntry {\n /**\n * Human-readable message. Use a function to interpolate typed parameters;\n * the parameter type flows through to the call site.\n */\n message: string | ((params: never) => string);\n /** HTTP status to surface to clients. */\n status?: number;\n /** Stable error code. Defaults to `${namespace}.${KEY}`. */\n code?: string | number;\n /** Why it happened. A function receives the same params as `message`. */\n why?: string | ((params: never) => string);\n /** What the caller should do next. */\n fix?: string;\n /** Docs or runbook link. */\n link?: string;\n /** Error name. Defaults to the catalog key. */\n name?: string;\n}\n\n/** Per-call options passed alongside (or instead of) typed params. */\nexport interface ErrorBuildOptions {\n cause?: unknown;\n details?: Record<string, unknown>;\n /** Backend-only context. Never serialized to clients. */\n internal?: Record<string, unknown>;\n}\n\ntype ParamsOf<E> = E extends { message: (params: infer P) => string }\n ? P\n : E extends { why: (params: infer P) => string }\n ? P\n : void;\n\ntype BuilderArgs<E extends ErrorCatalogEntry> =\n ParamsOf<E> extends void\n ? [options?: ErrorBuildOptions]\n : [params: ParamsOf<E>, options?: ErrorBuildOptions];\n\n/** A callable error factory produced by {@link defineErrorCatalog}. */\nexport interface ErrorBuilder<E extends ErrorCatalogEntry> {\n (...args: BuilderArgs<E>): StructuredError;\n /** Stable code assigned to every error from this entry. */\n readonly code: string | number;\n /** True when `error` was produced by this catalog entry. */\n match(error: unknown): boolean;\n}\n\nexport type ErrorCatalog<T extends Record<string, ErrorCatalogEntry>> = {\n readonly [K in keyof T]: ErrorBuilder<T[K]>;\n};\n\nfunction readCatalogCode(error: unknown): string | number | undefined {\n if (error === null || typeof error !== 'object') return undefined;\n return (error as Record<symbol, unknown>)[catalogCodeKey] as\n string | number | undefined;\n}\n\n/** True when `error` was produced by any autotel error catalog. */\nexport function isCatalogError(error: unknown): error is StructuredError {\n return readCatalogCode(error) !== undefined;\n}\n\n/** Returns the catalog code of `error`, or `undefined` if it has none. */\nexport function getCatalogCode(error: unknown): string | number | undefined {\n return readCatalogCode(error);\n}\n\n/**\n * Define a typed error catalog. Returns an object whose keys are error\n * builders. Each builder produces a {@link StructuredError} carrying the\n * entry's message, status, code, why, fix, and link.\n */\nexport function defineErrorCatalog<\n const T extends Record<string, ErrorCatalogEntry>,\n>(namespace: string, entries: T): ErrorCatalog<T> {\n const catalog: Record<string, ErrorBuilder<ErrorCatalogEntry>> = {};\n\n for (const [key, entry] of Object.entries(entries) as [\n string,\n ErrorCatalogEntry,\n ][]) {\n const code = entry.code ?? `${namespace}.${key}`;\n const usesParams =\n typeof entry.message === 'function' || typeof entry.why === 'function';\n\n const builder = ((\n paramsOrOptions?: unknown,\n maybeOptions?: ErrorBuildOptions,\n ): StructuredError => {\n const params = usesParams ? paramsOrOptions : undefined;\n const options = (usesParams ? maybeOptions : paramsOrOptions) as\n ErrorBuildOptions | undefined;\n\n const message =\n typeof entry.message === 'function'\n ? (entry.message as (p: unknown) => string)(params)\n : entry.message;\n const why =\n typeof entry.why === 'function'\n ? (entry.why as (p: unknown) => string)(params)\n : entry.why;\n\n const error = createStructuredError({\n message,\n name: entry.name ?? key,\n code,\n ...(entry.status === undefined ? {} : { status: entry.status }),\n ...(why === undefined ? {} : { why }),\n ...(entry.fix === undefined ? {} : { fix: entry.fix }),\n ...(entry.link === undefined ? {} : { link: entry.link }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n ...(options?.details === undefined ? {} : { details: options.details }),\n ...(options?.internal === undefined\n ? {}\n : { internal: options.internal }),\n });\n\n Object.defineProperty(error, catalogCodeKey, {\n value: code,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n\n return error;\n }) as ErrorBuilder<ErrorCatalogEntry>;\n\n Object.defineProperty(builder, 'code', {\n value: code,\n enumerable: true,\n });\n Object.defineProperty(builder, 'match', {\n value: (error: unknown): boolean => readCatalogCode(error) === code,\n enumerable: false,\n });\n\n catalog[key] = builder;\n }\n\n return Object.freeze(catalog) as ErrorCatalog<T>;\n}\n\n/** Severity of an audit action. */\nexport type AuditSeverity = 'info' | 'warn' | 'critical';\n\n/** Definition of a single action in an audit catalog. */\nexport interface AuditCatalogEntry {\n /** Human-readable description. Use a function for typed params. */\n message?: string | ((params: never) => string);\n /** Stable action name. Defaults to `${namespace}.${KEY}`. */\n action?: string;\n /** Severity of the action. Defaults to `'info'`. */\n severity?: AuditSeverity;\n}\n\n/** A resolved audit action descriptor produced by an audit catalog. */\nexport interface AuditAction {\n readonly action: string;\n readonly severity: AuditSeverity;\n readonly message?: string;\n}\n\ntype AuditDescriptorArgs<E extends AuditCatalogEntry> =\n ParamsOf<E> extends void ? [] : [params: ParamsOf<E>];\n\n/** A callable audit-action descriptor produced by {@link defineAuditCatalog}. */\nexport interface AuditDescriptor<E extends AuditCatalogEntry> {\n (...args: AuditDescriptorArgs<E>): AuditAction;\n readonly action: string;\n readonly severity: AuditSeverity;\n}\n\nexport type AuditCatalog<T extends Record<string, AuditCatalogEntry>> = {\n readonly [K in keyof T]: AuditDescriptor<T[K]>;\n};\n\n/**\n * Define a typed audit catalog. Returns typed action descriptors you can pass\n * to `track()` or audit helpers without scattering magic strings.\n */\nexport function defineAuditCatalog<\n const T extends Record<string, AuditCatalogEntry>,\n>(namespace: string, entries: T): AuditCatalog<T> {\n const catalog: Record<string, AuditDescriptor<AuditCatalogEntry>> = {};\n\n for (const [key, entry] of Object.entries(entries) as [\n string,\n AuditCatalogEntry,\n ][]) {\n const action = entry.action ?? `${namespace}.${key}`;\n const severity: AuditSeverity = entry.severity ?? 'info';\n\n const descriptor = ((params?: unknown): AuditAction => {\n const message =\n typeof entry.message === 'function'\n ? (entry.message as (p: unknown) => string)(params)\n : entry.message;\n return Object.freeze({\n action,\n severity,\n ...(message === undefined ? {} : { message }),\n });\n }) as AuditDescriptor<AuditCatalogEntry>;\n\n Object.defineProperty(descriptor, 'action', {\n value: action,\n enumerable: true,\n });\n Object.defineProperty(descriptor, 'severity', {\n value: severity,\n enumerable: true,\n });\n\n catalog[key] = descriptor;\n }\n\n return Object.freeze(catalog) as AuditCatalog<T>;\n}\n","export interface DrainOptions<TContext, TConfig, TPayload = TContext> {\n /** Stable identifier used in error logs. */\n name: string;\n /** Return null to skip draining (e.g. missing API key in dev). */\n resolve: () => TConfig | null | Promise<TConfig | null>;\n /** Transform contexts into payloads. Defaults to identity. */\n transform?: (contexts: TContext[]) => TPayload[];\n /** Transport implementation. */\n send: (payloads: TPayload[], config: TConfig) => Promise<void>;\n}\n\nexport interface HttpDrainRequest {\n url: string;\n headers: Record<string, string>;\n body: string;\n}\n\nexport interface HttpDrainOptions<\n TContext,\n TConfig,\n TPayload = TContext,\n> extends Omit<DrainOptions<TContext, TConfig, TPayload>, 'send'> {\n encode: (payloads: TPayload[], config: TConfig) => HttpDrainRequest | null;\n timeoutMs?: number;\n retries?: number;\n resolveTimeoutMs?: (config: TConfig) => number | undefined;\n resolveRetries?: (config: TConfig) => number | undefined;\n}\n\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_RETRIES = 2;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nasync function postWithRetry(options: {\n name: string;\n request: HttpDrainRequest;\n timeoutMs: number;\n retries: number;\n}): Promise<void> {\n const { name, request, timeoutMs, retries } = options;\n const attempts = Math.max(1, retries);\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n timeout.unref?.();\n try {\n const response = await fetch(request.url, {\n method: 'POST',\n headers: request.headers,\n body: request.body,\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new Error(\n `[autotel/${name}] HTTP ${response.status} draining ${request.url}`,\n );\n }\n return;\n } catch (error) {\n lastError = error;\n if (attempt < attempts) {\n await delay(100 * attempt);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n\n throw lastError;\n}\n\nexport function defineDrain<TContext, TConfig, TPayload = TContext>(\n options: DrainOptions<TContext, TConfig, TPayload>,\n): (ctx: TContext | TContext[]) => Promise<void> {\n return async (ctx: TContext | TContext[]) => {\n const contexts = Array.isArray(ctx) ? ctx : [ctx];\n if (contexts.length === 0) return;\n\n const config = await options.resolve();\n if (!config) return;\n\n const payloads = options.transform\n ? options.transform(contexts)\n : (contexts as unknown as TPayload[]);\n\n if (payloads.length === 0) return;\n\n try {\n await options.send(payloads, config);\n } catch (error) {\n console.error(`[autotel/${options.name}] drain failed:`, error);\n }\n };\n}\n\nexport function defineHttpDrain<TContext, TConfig, TPayload = TContext>(\n options: HttpDrainOptions<TContext, TConfig, TPayload>,\n): (ctx: TContext | TContext[]) => Promise<void> {\n return defineDrain<TContext, TConfig, TPayload>({\n name: options.name,\n resolve: options.resolve,\n transform: options.transform,\n send: async (payloads, config) => {\n const request = options.encode(payloads, config);\n if (!request) return;\n const timeoutMs =\n options.resolveTimeoutMs?.(config) ??\n options.timeoutMs ??\n DEFAULT_TIMEOUT_MS;\n const retries =\n options.resolveRetries?.(config) ?? options.retries ?? DEFAULT_RETRIES;\n\n await postWithRetry({\n name: options.name,\n request,\n timeoutMs,\n retries,\n });\n },\n });\n}\n","export interface EnrichContext<TEvent extends Record<string, unknown>> {\n event: TEvent;\n request?: {\n method?: string;\n path?: string;\n requestId?: string;\n };\n response?: {\n status?: number;\n };\n headers?: Record<string, string>;\n}\n\nexport interface EnricherDefinition<\n TEvent extends Record<string, unknown>,\n TValue extends object,\n> {\n /** Stable identifier used in error logs. */\n name: string;\n /** Top-level field to merge computed values into. */\n field: keyof TEvent & string;\n /** Return undefined to skip enrichment. */\n compute: (ctx: EnrichContext<TEvent>) => TValue | undefined;\n}\n\nexport interface EnricherOptions {\n /** Replace existing field value instead of merge. Default false. */\n overwrite?: boolean;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key in source) {\n const sourceVal = source[key];\n if (sourceVal === undefined) continue;\n const targetVal = target[key];\n if (isPlainObject(sourceVal) && isPlainObject(targetVal)) {\n mergeInto(targetVal, sourceVal);\n } else {\n target[key] = sourceVal;\n }\n }\n}\n\nexport function defineEnricher<\n TEvent extends Record<string, unknown>,\n TValue extends object,\n>(\n def: EnricherDefinition<TEvent, TValue>,\n options: EnricherOptions = {},\n): (ctx: EnrichContext<TEvent>) => void {\n return (ctx: EnrichContext<TEvent>) => {\n let computed: TValue | undefined;\n try {\n computed = def.compute(ctx);\n } catch (error) {\n console.error(`[autotel/${def.name}] enrich failed:`, error);\n return;\n }\n\n if (!computed) return;\n\n if (options.overwrite || !isPlainObject(ctx.event[def.field])) {\n (ctx.event as Record<string, unknown>)[def.field] = computed;\n return;\n }\n\n mergeInto(\n ctx.event[def.field] as unknown as Record<string, unknown>,\n computed as unknown as Record<string, unknown>,\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;CAElB,yBACEA,yBAAa,wBAAwB,KAAKA,wBAAY;CACxD,mBAAmBA,yBAAa,kBAAkB,KAAKA,wBAAY;CACnE,WAAWA,yBAAa,UAAU,KAAKA,wBAAY;CACnD,SAASA,yBAAa,QAAQ,KAAKA,wBAAY;CAE/C,iBAAiBA,yBAAa;CAC9B,oBAAoBA,yBAAa;CACjC,YAAYA,yBAAa;CACzB,SAASA,yBAAa;CACtB,eAAeA,yBAAa;CAC5B,gBAAgBA,yBAAa;CAC7B,SAASA,yBAAa;CACtB,gBAAgBA,yBAAa;AAC/B;AAEA,MAAa,QAAqD,OAAO,OACvEC,0BACA,WACF;;;;ACfA,SAAgB,YAKd,MACA,QACA,UAAiC,CAAC,GACL;CAC7B,MAAM,aAAa,QAAQ,eAAe,MAAM;CAChD,MAAM,iBAAiB,aACnB;EACE,QAAQ;EACR;EACA,MAAMC,6BAAS,UAAU;CAC3B,IACA;CAEJ,OAAO;EACL;EACA;EACA,MAAM,SAAkB;GACtB,MAAM,SAAS,OAAO,UAAU,OAAO;GACvC,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,MACR,8BAA8B,KAAK,6BACrC;GAEF,oBACE,MACA,OAAO,MACP,iBAAiB,EAAE,QAAQ,eAAe,IAAI,MAChD;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AClBA,eAAsB,MAAM,SAGV;CAChB,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,cAAc,SAAS,eAAe;CAE5C,MAAM,UAAU,YAAY;EAE1B,MAAM,cAAcC,4BAAc;EAClC,IAAI,aACF,OAAO,cAAc,YAAY,SAAS,IAAI,YAAY,MAAM;EAOlE,IAAI;GACF,MAAM,i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F;CACF;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["otelTraceApi","autotelTraceFn","hashJson","mergeInto","nodeAsyncHooks","otelTrace","createTraceContext","flattenToAttributes","createStructuredError"],"sources":["../src/trace-hybrid.ts","../src/define-event.ts","../src/request-logger.ts","../src/error-catalog.ts","../src/drain-toolkit.ts","../src/enricher-toolkit.ts"],"sourcesContent":["/**\n * Hybrid `trace` export: callable like autotel's `trace(fn)`, AND exposes the\n * full `@opentelemetry/api` `TraceAPI` surface (`trace.getActiveSpan()`,\n * `trace.getTracer()`, …) so existing OTel code \"just works\" when imported\n * from `autotel`.\n *\n * Implementation: `Object.assign` mutates the autotel `trace` function to\n * attach the OTel TraceAPI methods. Because every reference to `trace` across\n * autotel resolves to the same function instance, this is a one-time, global\n * augmentation.\n */\n\nimport { trace as otelTraceApi } from '@opentelemetry/api';\nimport { trace as autotelTraceFn } from './functional';\n\nconst otelMethods = {\n // Class methods on TraceAPI — bind to the singleton.\n setGlobalTracerProvider:\n otelTraceApi.setGlobalTracerProvider.bind(otelTraceApi),\n getTracerProvider: otelTraceApi.getTracerProvider.bind(otelTraceApi),\n getTracer: otelTraceApi.getTracer.bind(otelTraceApi),\n disable: otelTraceApi.disable.bind(otelTraceApi),\n // Instance fields on TraceAPI — already standalone, copy by reference.\n wrapSpanContext: otelTraceApi.wrapSpanContext,\n isSpanContextValid: otelTraceApi.isSpanContextValid,\n deleteSpan: otelTraceApi.deleteSpan,\n getSpan: otelTraceApi.getSpan,\n getActiveSpan: otelTraceApi.getActiveSpan,\n getSpanContext: otelTraceApi.getSpanContext,\n setSpan: otelTraceApi.setSpan,\n setSpanContext: otelTraceApi.setSpanContext,\n};\n\nexport const trace: typeof autotelTraceFn & typeof otelTraceApi = Object.assign(\n autotelTraceFn,\n otelMethods,\n) as typeof autotelTraceFn & typeof otelTraceApi;\n","import { track } from './track';\nimport { hashJson } from './stable-hash';\nimport type { EventSchemaMetadata } from './event-subscriber';\n\ntype SafeParseResult<T> =\n { success: true; data: T } | { success: false; error: unknown };\n\nexport interface SchemaLike<T> {\n safeParse(input: unknown): SafeParseResult<T>;\n}\n\nexport interface DefineEventOptions<S> {\n toJsonSchema?: (schema: S) => unknown;\n}\n\nexport interface DefinedEvent<Name extends string, Payload> {\n readonly name: Name;\n readonly schemaMetadata?: EventSchemaMetadata;\n track(payload: Payload): void;\n}\n\nexport function defineEvent<\n Name extends string,\n Payload,\n S extends SchemaLike<Payload>,\n>(\n name: Name,\n schema: S,\n options: DefineEventOptions<S> = {},\n): DefinedEvent<Name, Payload> {\n const jsonSchema = options.toJsonSchema?.(schema);\n const schemaMetadata = jsonSchema\n ? {\n source: 'zod' as const,\n jsonSchema,\n hash: hashJson(jsonSchema),\n }\n : undefined;\n\n return {\n name,\n schemaMetadata,\n track(payload: Payload) {\n const parsed = schema.safeParse(payload);\n if (!parsed.success) {\n throw new Error(\n `Invalid payload for event \"${name}\". Schema validation failed.`,\n );\n }\n track(\n name,\n parsed.data,\n schemaMetadata ? { schema: schemaMetadata } : undefined,\n );\n },\n };\n}\n","// namespace import for browser-bundler compat — see node-require.ts\nimport * as nodeAsyncHooks from 'node:async_hooks';\nimport { trace as otelTrace } from '@opentelemetry/api';\nimport type { TraceContext } from './trace-context';\nimport { createTraceContext } from './trace-context';\nimport { recordStructuredError } from './structured-error';\nimport { flattenToAttributes } from './flatten-attributes';\nimport { emitCorrelatedEvent } from './correlated-events';\n\nconst POST_EMIT_FORK_HINT =\n \"For intentional background work tied to this request, use log.fork('label', fn) when available.\";\n\nfunction warnPostEmit(method: string, detail: string): void {\n console.warn(\n `[autotel] ${method} called after the wide event was emitted — ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`,\n );\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key in source) {\n const sourceVal = source[key];\n if (sourceVal === undefined) continue;\n const targetVal = target[key];\n if (\n sourceVal !== null &&\n typeof sourceVal === 'object' &&\n !Array.isArray(sourceVal) &&\n targetVal !== null &&\n typeof targetVal === 'object' &&\n !Array.isArray(targetVal)\n ) {\n mergeInto(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>,\n );\n } else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n target[key] = [...targetVal, ...sourceVal];\n } else {\n target[key] = sourceVal;\n }\n }\n}\n\nconst requestContextStore =\n new nodeAsyncHooks.AsyncLocalStorage<TraceContext>();\n\nexport function runWithRequestContext<T>(ctx: TraceContext, fn: () => T): T {\n return requestContextStore.run(ctx, fn);\n}\n\nexport interface RequestLogger {\n set(fields: Record<string, unknown>): void;\n /** Set snapshot severity without adding a log event or exception. */\n setLevel(level: RequestLogLevel): void;\n info(message: string, fields?: Record<string, unknown>): void;\n warn(message: string, fields?: Record<string, unknown>): void;\n error(error: Error | string, fields?: Record<string, unknown>): void;\n getContext(): Record<string, unknown>;\n emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot;\n fork(\n label: string,\n fn: () => void | Promise<void>,\n options?: ForkOptions,\n ): void;\n}\n\nexport type RequestLogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface RequestLogSnapshot {\n timestamp: string;\n traceId: string;\n spanId: string;\n correlationId: string;\n context: Record<string, unknown>;\n}\n\nexport interface RequestLoggerOptions {\n /** Callback invoked by emitNow() for manual fan-out. */\n onEmit?: (snapshot: RequestLogSnapshot) => void | Promise<void>;\n}\n\n/**\n * Optional lifecycle hooks for adapters that need to track child loggers\n * spawned by `log.fork()` (e.g. active logger maps in framework integrations).\n */\nexport interface ForkLifecycle {\n /** Called after the child logger is created, before `fn` runs. */\n onChildEnter?: (child: RequestLogger) => void;\n /** Called after the child has finished (emit + drain), success or failure. */\n onChildExit?: (child: RequestLogger) => void;\n}\n\nexport interface ForkOptions {\n lifecycle?: ForkLifecycle;\n}\n\nfunction resolveContext(ctx?: TraceContext): TraceContext {\n if (ctx) return ctx;\n\n const stored = requestContextStore.getStore();\n if (stored) return stored;\n\n const span = otelTrace.getActiveSpan();\n if (!span) {\n throw new Error(\n '[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext().',\n );\n }\n return createTraceContext(span);\n}\n\nexport function getRequestLogger(\n ctx?: TraceContext,\n options?: RequestLoggerOptions,\n): RequestLogger {\n const activeContext = resolveContext(ctx);\n const contextState: Record<string, unknown> = {};\n let emitted = false;\n let lastSnapshot: RequestLogSnapshot | null = null;\n let hasExplicitLevel = false;\n\n const addLogEvent = (\n level: 'info' | 'warn' | 'error',\n message: string,\n fields?: Record<string, unknown>,\n ) => {\n const attrs = fields ? flattenToAttributes(fields) : undefined;\n emitCorrelatedEvent(activeContext, `log.${level}`, {\n message,\n ...attrs,\n });\n };\n\n const sealCheck = (method: string, keys: string[]): void => {\n if (emitted) {\n warnPostEmit(\n method,\n `Keys dropped: ${keys.length > 0 ? keys.join(', ') : '(empty)'}.`,\n );\n }\n };\n\n return {\n set(fields: Record<string, unknown>) {\n sealCheck('log.set()', Object.keys(fields));\n if (emitted) return;\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n },\n\n setLevel(level: RequestLogLevel) {\n sealCheck('log.setLevel()', ['autotel.log.level']);\n if (emitted) return;\n hasExplicitLevel = true;\n activeContext.setAttribute('autotel.log.level', level);\n },\n\n info(message: string, fields?: Record<string, unknown>) {\n const keys = fields\n ? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]\n : ['message'];\n sealCheck('log.info()', keys);\n if (emitted) return;\n addLogEvent('info', message, fields);\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n },\n\n warn(message: string, fields?: Record<string, unknown>) {\n const keys = fields\n ? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]\n : ['message'];\n sealCheck('log.warn()', keys);\n if (emitted) return;\n addLogEvent('warn', message, fields);\n if (!hasExplicitLevel) {\n activeContext.setAttribute('autotel.log.level', 'warn');\n }\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n },\n\n error(error: Error | string, fields?: Record<string, unknown>) {\n const keys = fields ? [...Object.keys(fields), 'error'] : ['error'];\n sealCheck('log.error()', keys);\n if (emitted) return;\n const err = typeof error === 'string' ? new Error(error) : error;\n recordStructuredError(activeContext, err);\n addLogEvent('error', err.message, fields);\n\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n if (!hasExplicitLevel) {\n activeContext.setAttribute('autotel.log.level', 'error');\n }\n },\n\n getContext() {\n return { ...contextState };\n },\n\n emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot {\n if (emitted) {\n warnPostEmit('log.emitNow()', 'Ignoring duplicate emit.');\n return lastSnapshot as RequestLogSnapshot;\n }\n\n const mergedContext = {\n ...contextState,\n ...overrides,\n };\n const flattened = flattenToAttributes(mergedContext);\n activeContext.setAttributes(flattened);\n\n const snapshot: RequestLogSnapshot = {\n timestamp: new Date().toISOString(),\n traceId: activeContext.traceId,\n spanId: activeContext.spanId,\n correlationId: activeContext.correlationId,\n context: mergedContext,\n };\n\n emitCorrelatedEvent(activeContext, 'log.emit.manual', {\n ...flattened,\n });\n\n if (options?.onEmit) {\n Promise.resolve(options.onEmit(snapshot)).catch((error) => {\n console.warn('[autotel] request logger onEmit failed:', error);\n });\n }\n\n emitted = true;\n lastSnapshot = snapshot;\n return snapshot;\n },\n\n fork(\n label: string,\n fn: () => void | Promise<void>,\n forkOptions?: ForkOptions,\n ): void {\n const parentRequestId = activeContext.correlationId;\n if (typeof parentRequestId !== 'string' || parentRequestId.length === 0) {\n throw new Error(\n '[autotel] log.fork() requires the parent logger to have a correlationId. ' +\n 'Ensure the request was created by autotel middleware.',\n );\n }\n\n const tracer = otelTrace.getTracer('autotel.request-logger');\n const lifecycle = forkOptions?.lifecycle;\n void tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {\n const childContext: TraceContext = {\n ...createTraceContext(childSpan),\n correlationId: crypto.randomUUID(),\n };\n\n requestContextStore.run(childContext, () => {\n const childLog = getRequestLogger(childContext);\n childLog.set({\n operation: label,\n _parentCorrelationId: parentRequestId,\n });\n\n lifecycle?.onChildEnter?.(childLog);\n\n void Promise.resolve()\n .then(() => fn())\n .then(() => {\n childLog.emitNow();\n })\n .catch((error_: unknown) => {\n const error =\n error_ instanceof Error ? error_ : new Error(String(error_));\n childLog.error(error);\n childLog.emitNow();\n })\n .finally(() => {\n try {\n lifecycle?.onChildExit?.(childLog);\n } catch (hookError) {\n console.warn(\n '[autotel] fork onChildExit hook threw:',\n hookError,\n );\n }\n childSpan.end();\n });\n });\n });\n },\n };\n}\n\n/**\n * Returns `true` when a request-logger context can be resolved without throwing —\n * i.e. an explicit `ctx` was provided, a `runWithRequestContext()` scope is active,\n * or there is an active OpenTelemetry span.\n *\n * Use this to branch on observability availability instead of wrapping\n * {@link getRequestLogger} in try/catch.\n */\nexport function hasRequestContext(ctx?: TraceContext): boolean {\n if (ctx) return true;\n if (requestContextStore.getStore()) return true;\n return otelTrace.getActiveSpan() != null;\n}\n\n/**\n * Like {@link getRequestLogger}, but returns `null` instead of throwing when no\n * request context is available. Intended for best-effort instrumentation where a\n * missing telemetry context must never crash business logic.\n */\nexport function getRequestLoggerSafe(\n ctx?: TraceContext,\n options?: RequestLoggerOptions,\n): RequestLogger | null {\n if (!hasRequestContext(ctx)) return null;\n return getRequestLogger(ctx, options);\n}\n\n/**\n * A no-op {@link RequestLogger} whose methods do nothing. Used as a fallback by\n * best-effort instrumentation so wrapped handlers can run un-instrumented without\n * branching on logger presence.\n */\nexport function createNoopRequestLogger(): RequestLogger {\n const snapshot = (): RequestLogSnapshot => ({\n timestamp: new Date().toISOString(),\n traceId: '',\n spanId: '',\n correlationId: '',\n context: {},\n });\n\n return {\n set() {},\n setLevel() {},\n info() {},\n warn() {},\n error() {},\n getContext() {\n return {};\n },\n emitNow() {\n return snapshot();\n },\n fork(_label, fn) {\n void Promise.resolve().then(() => fn());\n },\n };\n}\n","/**\n * Typed error and audit catalogs.\n *\n * Group related errors into one catalog and get a refactor-safe builder per\n * code, with autocomplete at every call site and typed message parameters.\n *\n * @example\n * ```typescript\n * import { defineErrorCatalog } from 'autotel';\n *\n * export const billing = defineErrorCatalog('billing', {\n * PAYMENT_DECLINED: {\n * status: 402,\n * message: 'Card declined',\n * why: 'The issuer rejected the charge',\n * fix: 'Try a different payment method',\n * },\n * INSUFFICIENT_FUNDS: {\n * status: 402,\n * message: ({ available, required }: { available: number; required: number }) =>\n * `Insufficient funds: $${available} of $${required}`,\n * },\n * });\n *\n * throw billing.PAYMENT_DECLINED({ cause: stripeError });\n * throw billing.INSUFFICIENT_FUNDS({ available: 5, required: 100 });\n *\n * // In a catch block — refactor-safe, no magic strings:\n * if (billing.PAYMENT_DECLINED.match(err)) { ... }\n * ```\n */\n\nimport {\n createStructuredError,\n type StructuredError,\n} from './structured-error';\n\nconst catalogCodeKey = Symbol.for('autotel.catalog.code');\n\n/** Definition of a single error in a catalog. */\nexport interface ErrorCatalogEntry {\n /**\n * Human-readable message. Use a function to interpolate typed parameters;\n * the parameter type flows through to the call site.\n */\n message: string | ((params: never) => string);\n /** HTTP status to surface to clients. */\n status?: number;\n /** Stable error code. Defaults to `${namespace}.${KEY}`. */\n code?: string | number;\n /** Why it happened. A function receives the same params as `message`. */\n why?: string | ((params: never) => string);\n /** What the caller should do next. */\n fix?: string;\n /** Docs or runbook link. */\n link?: string;\n /** Error name. Defaults to the catalog key. */\n name?: string;\n}\n\n/** Per-call options passed alongside (or instead of) typed params. */\nexport interface ErrorBuildOptions {\n cause?: unknown;\n details?: Record<string, unknown>;\n /** Backend-only context. Never serialized to clients. */\n internal?: Record<string, unknown>;\n}\n\ntype ParamsOf<E> = E extends { message: (params: infer P) => string }\n ? P\n : E extends { why: (params: infer P) => string }\n ? P\n : void;\n\ntype BuilderArgs<E extends ErrorCatalogEntry> =\n ParamsOf<E> extends void\n ? [options?: ErrorBuildOptions]\n : [params: ParamsOf<E>, options?: ErrorBuildOptions];\n\n/** A callable error factory produced by {@link defineErrorCatalog}. */\nexport interface ErrorBuilder<E extends ErrorCatalogEntry> {\n (...args: BuilderArgs<E>): StructuredError;\n /** Stable code assigned to every error from this entry. */\n readonly code: string | number;\n /** True when `error` was produced by this catalog entry. */\n match(error: unknown): boolean;\n}\n\nexport type ErrorCatalog<T extends Record<string, ErrorCatalogEntry>> = {\n readonly [K in keyof T]: ErrorBuilder<T[K]>;\n};\n\nfunction readCatalogCode(error: unknown): string | number | undefined {\n if (error === null || typeof error !== 'object') return undefined;\n return (error as Record<symbol, unknown>)[catalogCodeKey] as\n string | number | undefined;\n}\n\n/** True when `error` was produced by any autotel error catalog. */\nexport function isCatalogError(error: unknown): error is StructuredError {\n return readCatalogCode(error) !== undefined;\n}\n\n/** Returns the catalog code of `error`, or `undefined` if it has none. */\nexport function getCatalogCode(error: unknown): string | number | undefined {\n return readCatalogCode(error);\n}\n\n/**\n * Define a typed error catalog. Returns an object whose keys are error\n * builders. Each builder produces a {@link StructuredError} carrying the\n * entry's message, status, code, why, fix, and link.\n */\nexport function defineErrorCatalog<\n const T extends Record<string, ErrorCatalogEntry>,\n>(namespace: string, entries: T): ErrorCatalog<T> {\n const catalog: Record<string, ErrorBuilder<ErrorCatalogEntry>> = {};\n\n for (const [key, entry] of Object.entries(entries) as [\n string,\n ErrorCatalogEntry,\n ][]) {\n const code = entry.code ?? `${namespace}.${key}`;\n const usesParams =\n typeof entry.message === 'function' || typeof entry.why === 'function';\n\n const builder = ((\n paramsOrOptions?: unknown,\n maybeOptions?: ErrorBuildOptions,\n ): StructuredError => {\n const params = usesParams ? paramsOrOptions : undefined;\n const options = (usesParams ? maybeOptions : paramsOrOptions) as\n ErrorBuildOptions | undefined;\n\n const message =\n typeof entry.message === 'function'\n ? (entry.message as (p: unknown) => string)(params)\n : entry.message;\n const why =\n typeof entry.why === 'function'\n ? (entry.why as (p: unknown) => string)(params)\n : entry.why;\n\n const error = createStructuredError({\n message,\n name: entry.name ?? key,\n code,\n ...(entry.status === undefined ? {} : { status: entry.status }),\n ...(why === undefined ? {} : { why }),\n ...(entry.fix === undefined ? {} : { fix: entry.fix }),\n ...(entry.link === undefined ? {} : { link: entry.link }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n ...(options?.details === undefined ? {} : { details: options.details }),\n ...(options?.internal === undefined\n ? {}\n : { internal: options.internal }),\n });\n\n Object.defineProperty(error, catalogCodeKey, {\n value: code,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n\n return error;\n }) as ErrorBuilder<ErrorCatalogEntry>;\n\n Object.defineProperty(builder, 'code', {\n value: code,\n enumerable: true,\n });\n Object.defineProperty(builder, 'match', {\n value: (error: unknown): boolean => readCatalogCode(error) === code,\n enumerable: false,\n });\n\n catalog[key] = builder;\n }\n\n return Object.freeze(catalog) as ErrorCatalog<T>;\n}\n\n/** Severity of an audit action. */\nexport type AuditSeverity = 'info' | 'warn' | 'critical';\n\n/** Definition of a single action in an audit catalog. */\nexport interface AuditCatalogEntry {\n /** Human-readable description. Use a function for typed params. */\n message?: string | ((params: never) => string);\n /** Stable action name. Defaults to `${namespace}.${KEY}`. */\n action?: string;\n /** Severity of the action. Defaults to `'info'`. */\n severity?: AuditSeverity;\n}\n\n/** A resolved audit action descriptor produced by an audit catalog. */\nexport interface AuditAction {\n readonly action: string;\n readonly severity: AuditSeverity;\n readonly message?: string;\n}\n\ntype AuditDescriptorArgs<E extends AuditCatalogEntry> =\n ParamsOf<E> extends void ? [] : [params: ParamsOf<E>];\n\n/** A callable audit-action descriptor produced by {@link defineAuditCatalog}. */\nexport interface AuditDescriptor<E extends AuditCatalogEntry> {\n (...args: AuditDescriptorArgs<E>): AuditAction;\n readonly action: string;\n readonly severity: AuditSeverity;\n}\n\nexport type AuditCatalog<T extends Record<string, AuditCatalogEntry>> = {\n readonly [K in keyof T]: AuditDescriptor<T[K]>;\n};\n\n/**\n * Define a typed audit catalog. Returns typed action descriptors you can pass\n * to `track()` or audit helpers without scattering magic strings.\n */\nexport function defineAuditCatalog<\n const T extends Record<string, AuditCatalogEntry>,\n>(namespace: string, entries: T): AuditCatalog<T> {\n const catalog: Record<string, AuditDescriptor<AuditCatalogEntry>> = {};\n\n for (const [key, entry] of Object.entries(entries) as [\n string,\n AuditCatalogEntry,\n ][]) {\n const action = entry.action ?? `${namespace}.${key}`;\n const severity: AuditSeverity = entry.severity ?? 'info';\n\n const descriptor = ((params?: unknown): AuditAction => {\n const message =\n typeof entry.message === 'function'\n ? (entry.message as (p: unknown) => string)(params)\n : entry.message;\n return Object.freeze({\n action,\n severity,\n ...(message === undefined ? {} : { message }),\n });\n }) as AuditDescriptor<AuditCatalogEntry>;\n\n Object.defineProperty(descriptor, 'action', {\n value: action,\n enumerable: true,\n });\n Object.defineProperty(descriptor, 'severity', {\n value: severity,\n enumerable: true,\n });\n\n catalog[key] = descriptor;\n }\n\n return Object.freeze(catalog) as AuditCatalog<T>;\n}\n","export interface DrainOptions<TContext, TConfig, TPayload = TContext> {\n /** Stable identifier used in error logs. */\n name: string;\n /** Return null to skip draining (e.g. missing API key in dev). */\n resolve: () => TConfig | null | Promise<TConfig | null>;\n /** Transform contexts into payloads. Defaults to identity. */\n transform?: (contexts: TContext[]) => TPayload[];\n /** Transport implementation. */\n send: (payloads: TPayload[], config: TConfig) => Promise<void>;\n}\n\nexport interface HttpDrainRequest {\n url: string;\n headers: Record<string, string>;\n body: string;\n}\n\nexport interface HttpDrainOptions<\n TContext,\n TConfig,\n TPayload = TContext,\n> extends Omit<DrainOptions<TContext, TConfig, TPayload>, 'send'> {\n encode: (payloads: TPayload[], config: TConfig) => HttpDrainRequest | null;\n timeoutMs?: number;\n retries?: number;\n resolveTimeoutMs?: (config: TConfig) => number | undefined;\n resolveRetries?: (config: TConfig) => number | undefined;\n}\n\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_RETRIES = 2;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nasync function postWithRetry(options: {\n name: string;\n request: HttpDrainRequest;\n timeoutMs: number;\n retries: number;\n}): Promise<void> {\n const { name, request, timeoutMs, retries } = options;\n const attempts = Math.max(1, retries);\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n timeout.unref?.();\n try {\n const response = await fetch(request.url, {\n method: 'POST',\n headers: request.headers,\n body: request.body,\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new Error(\n `[autotel/${name}] HTTP ${response.status} draining ${request.url}`,\n );\n }\n return;\n } catch (error) {\n lastError = error;\n if (attempt < attempts) {\n await delay(100 * attempt);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n\n throw lastError;\n}\n\nexport function defineDrain<TContext, TConfig, TPayload = TContext>(\n options: DrainOptions<TContext, TConfig, TPayload>,\n): (ctx: TContext | TContext[]) => Promise<void> {\n return async (ctx: TContext | TContext[]) => {\n const contexts = Array.isArray(ctx) ? ctx : [ctx];\n if (contexts.length === 0) return;\n\n const config = await options.resolve();\n if (!config) return;\n\n const payloads = options.transform\n ? options.transform(contexts)\n : (contexts as unknown as TPayload[]);\n\n if (payloads.length === 0) return;\n\n try {\n await options.send(payloads, config);\n } catch (error) {\n console.error(`[autotel/${options.name}] drain failed:`, error);\n }\n };\n}\n\nexport function defineHttpDrain<TContext, TConfig, TPayload = TContext>(\n options: HttpDrainOptions<TContext, TConfig, TPayload>,\n): (ctx: TContext | TContext[]) => Promise<void> {\n return defineDrain<TContext, TConfig, TPayload>({\n name: options.name,\n resolve: options.resolve,\n transform: options.transform,\n send: async (payloads, config) => {\n const request = options.encode(payloads, config);\n if (!request) return;\n const timeoutMs =\n options.resolveTimeoutMs?.(config) ??\n options.timeoutMs ??\n DEFAULT_TIMEOUT_MS;\n const retries =\n options.resolveRetries?.(config) ?? options.retries ?? DEFAULT_RETRIES;\n\n await postWithRetry({\n name: options.name,\n request,\n timeoutMs,\n retries,\n });\n },\n });\n}\n","export interface EnrichContext<TEvent extends Record<string, unknown>> {\n event: TEvent;\n request?: {\n method?: string;\n path?: string;\n requestId?: string;\n };\n response?: {\n status?: number;\n };\n headers?: Record<string, string>;\n}\n\nexport interface EnricherDefinition<\n TEvent extends Record<string, unknown>,\n TValue extends object,\n> {\n /** Stable identifier used in error logs. */\n name: string;\n /** Top-level field to merge computed values into. */\n field: keyof TEvent & string;\n /** Return undefined to skip enrichment. */\n compute: (ctx: EnrichContext<TEvent>) => TValue | undefined;\n}\n\nexport interface EnricherOptions {\n /** Replace existing field value instead of merge. Default false. */\n overwrite?: boolean;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key in source) {\n const sourceVal = source[key];\n if (sourceVal === undefined) continue;\n const targetVal = target[key];\n if (isPlainObject(sourceVal) && isPlainObject(targetVal)) {\n mergeInto(targetVal, sourceVal);\n } else {\n target[key] = sourceVal;\n }\n }\n}\n\nexport function defineEnricher<\n TEvent extends Record<string, unknown>,\n TValue extends object,\n>(\n def: EnricherDefinition<TEvent, TValue>,\n options: EnricherOptions = {},\n): (ctx: EnrichContext<TEvent>) => void {\n return (ctx: EnrichContext<TEvent>) => {\n let computed: TValue | undefined;\n try {\n computed = def.compute(ctx);\n } catch (error) {\n console.error(`[autotel/${def.name}] enrich failed:`, error);\n return;\n }\n\n if (!computed) return;\n\n if (options.overwrite || !isPlainObject(ctx.event[def.field])) {\n (ctx.event as Record<string, unknown>)[def.field] = computed;\n return;\n }\n\n mergeInto(\n ctx.event[def.field] as unknown as Record<string, unknown>,\n computed as unknown as Record<string, unknown>,\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;CAElB,yBACEA,yBAAa,w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EA,SAAgB,eAId,KACA,UAA2B,CAAC,GACU;CACtC,QAAQ,QAA+B;EACrC,IAAI;EACJ,IAAI;GACF,WAAW,IAAI,QAAQ,GAAG;EAC5B,SAAS,OAAO;GACd,QAAQ,MAAM,YAAY,IAAI,KAAK,mBAAmB,KAAK;GAC3D;EACF;EAEA,IAAI,CAAC,UAAU;EAEf,IAAI,QAAQ,aAAa,CAAC,cAAc,IAAI,MAAM,IAAI,MAAM,GAAG;GAC7D,AAAC,IAAI,MAAkC,IAAI,SAAS;GACpD;EACF;EAEA,UACE,IAAI,MAAM,IAAI,QACd,QACF;CACF;AACF"}
package/dist/index.d.cts CHANGED
@@ -9,7 +9,7 @@ import { DrainPipelineOptions, PipelineDrainFn, createDrainPipeline } from "./dr
9
9
  import { a as EventSubscriber, c as OutcomeStatus, i as EventSchemaMetadata, n as EventAttributes, o as EventTrackingOptions, s as FunnelStatus, t as AutotelEventContext } from "./event-subscriber-CWh8sTGh.cjs";
10
10
  import { Event, EventsOptions, getEvents, resetEvents } from "./event.cjs";
11
11
  import { n as FilteringSpanProcessorOptions, r as SpanFilterPredicate, t as FilteringSpanProcessor } from "./filtering-span-processor-BpDagWNa.cjs";
12
- import { a as isLoggerLocked, c as createStringRedactor, i as isInitialized, o as lockLogger, r as init, s as StringRedactor, t as AutotelConfig } from "./init-a4yPDYqC.cjs";
12
+ import { a as isLoggerLocked, c as StringRedactor, i as isInitialized, l as createStringRedactor, o as lockLogger, r as init, s as ProcessHandlersConfig, t as AutotelConfig } from "./init-XzXzrarP.cjs";
13
13
  import { a as SpanNameNormalizerPreset, i as SpanNameNormalizerFn, n as NORMALIZER_PRESETS, o as SpanNameNormalizingProcessor, r as SpanNameNormalizerConfig, s as SpanNameNormalizingProcessorOptions, t as NORMALIZER_PATTERNS } from "./span-name-normalizer-CN1-8C76.cjs";
14
14
  import "./canonical-log-line-processor-B4WgG-VS.cjs";
15
15
  import { i as defineEvent, n as DefinedEvent, r as SchemaLike, t as DefineEventOptions } from "./define-event-CGG048HE.cjs";
@@ -391,6 +391,8 @@ declare function shutdown(): Promise<void>;
391
391
  declare function runWithRequestContext<T>(ctx: TraceContext$1, fn: () => T): T;
392
392
  interface RequestLogger {
393
393
  set(fields: Record<string, unknown>): void;
394
+ /** Set snapshot severity without adding a log event or exception. */
395
+ setLevel(level: RequestLogLevel): void;
394
396
  info(message: string, fields?: Record<string, unknown>): void;
395
397
  warn(message: string, fields?: Record<string, unknown>): void;
396
398
  error(error: Error | string, fields?: Record<string, unknown>): void;
@@ -398,6 +400,7 @@ interface RequestLogger {
398
400
  emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot;
399
401
  fork(label: string, fn: () => void | Promise<void>, options?: ForkOptions): void;
400
402
  }
403
+ type RequestLogLevel = 'debug' | 'info' | 'warn' | 'error';
401
404
  interface RequestLogSnapshot {
402
405
  timestamp: string;
403
406
  traceId: string;
@@ -634,5 +637,5 @@ declare function defineEnricher<TEvent extends Record<string, unknown>, TValue e
634
637
  */
635
638
  declare function formatDuration(ms: number): string;
636
639
  //#endregion
637
- export { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, type AttributeGuardrails, type AttributePolicy, AttributeRedactingProcessor, type AttributeRedactingProcessorOptions, type AttributeRedactorConfig, type AttributeRedactorFn, type AttributeRedactorPreset, type AttributeValue, type Attributes, type AuditAction, type AuditCatalog, type AuditCatalogEntry, type AuditDescriptor, type AuditSeverity, type AutotelConfig, type Baggage, type BaggageEntry, type BaggageError, type BaggageFieldDefinition, type BaggageFieldType, BaggageSpanProcessor, type BaggageSpanProcessorOptions, type BuiltinPatternName, BusinessBaggage, type BusinessBaggageValues, CORRELATION_ID_BAGGAGE_KEY, type ClientAttrs, type CloudAttrs, type CodeAttrs, type ConsumerConfig, type ConsumerContext, type ContainerAttrs, type Context, type DBAttrs, type DBConfig, type DefineEventOptions, type DefinedEvent, type DeploymentAttrs, type DeviceAttrs, type DrainOptions, type DrainPipelineOptions, type EnrichContext, type EnricherDefinition, type EnricherOptions, type ErrorAttrs, type ErrorBuildOptions, type ErrorBuilder, type ErrorCatalog, type ErrorCatalogEntry, Event, type EventAttributes, type EventSubscriber, type EventsOptions, type Exception, type ExceptionAttrs, type FaaSAttrs, type FeatureFlagAttrs, FilteringSpanProcessor, type FilteringSpanProcessorOptions, type ForkLifecycle, type ForkOptions, type FunnelStatus, type GraphQLAttrs, HTTPAttributes, type HTTPClientAttrs, type HTTPConfig, type HTTPServerAttrs, type HrTime, type HttpDrainOptions, type HttpDrainRequest, type InstrumentOptions, type K8sAttrs, type LagMetricsConfig, type Link, type MaskFn, type MessagingAttrs, type MessagingConfig, type MessagingOperation, type MessagingSystem, Metric, type MetricsOptions, NORMALIZER_PATTERNS, NORMALIZER_PRESETS, type NetworkAttrs, NeverSampler, type OTelAttrs, type OperationContext, type TraceContext as OtelTraceContext, type OutcomeStatus, type ParsedError, type PeerAttrs, type PipelineDrainFn, type ProcessAttrs, type ProducerConfig, type ProducerContext, REDACTOR_PATTERNS, REDACTOR_PRESETS, ROOT_CONTEXT, type RPCAttrs, RandomSampler, type RequestLogSnapshot, type RequestLogger, type RequestLoggerOptions, type SafeBaggageOptions, type SafeBaggageSchema, type Sampler, type SamplingContext, type SamplingPreset, type SchemaLike, type ServerAddressAttrs, ServiceAttributes, type ServiceAttrs, type SessionAttrs, type SingleInstrumentOptions, type Span, type SpanAttributes, type SpanContext, type SpanFilterPredicate, SpanKind, type SpanLink, type SpanNameNormalizerConfig, type SpanNameNormalizerFn, type SpanNameNormalizerPreset, SpanNameNormalizingProcessor, type SpanNameNormalizingProcessorOptions, type SpanOptions, SpanStatusCode, type StepConfig, type StepContext, type StepStatus, type StringRedactor, type StructuredError, type StructuredErrorInput, type TLSAttrs, type TextMapGetter, type TextMapSetter, type ThreadAttrs, type TimeInput, type TraceContext$1 as TraceContext, type TraceFlags, type TraceState, type Tracer, type TracerProvider, URLAttributes, type URLAttrs, type UserAttrs, UserIdSampler, type ValuePatternConfig, type WithBaggageOptions, type WithNewContextOptions, type WorkflowConfig, type WorkflowContext, type WorkflowStatus, attrs, autoRedactPII, builtinPatterns, context, createAttributeRedactor, createCounter, createDeterministicTraceId, createDrainPipeline, createHistogram, createLinkFromHeaders, createNoopRequestLogger, createObservableGauge, createRedactedSpan, createSafeBaggageSchema, createStringRedactor, createStructuredError, createUpDownCounter, ctx, dbClient, defineAuditCatalog, defineBaggageSchema, defineDrain, defineEnricher, defineErrorCatalog, defineEvent, defineHttpDrain, enrichWithTraceContext, extractLinksFromBatch, finalizeSpan, flattenMetadata, flattenToAttributes, flush, formatDuration, generateCorrelationId, getActiveContext, getActiveSpan, getActiveTraceContext, getAutotelTracer, getAutotelTracerProvider, getCatalogCode, getCorrelationId, getCurrentWorkflowContext, getEventQueue, getEvents, getMeter, getMetrics, getOperationContext, getOrCreateCorrelationId, getRequestLogger, getRequestLoggerSafe, getStructuredErrorAttributes, getTraceContext, getTracer, hasRequestContext, httpClient, httpRequestHeaderAttribute, httpResponseHeaderAttribute, httpServer, identify, init, instrument, isCatalogError, isInWorkflow, isInitialized, isLoggerLocked, isTracing, lockLogger, mergeAttrs, mergeServiceResource, normalizeAttributeRedactorConfig, otelTrace, parseError, propagation, recordStructuredError, request, resetEvents, resetMetrics, resolveSamplingPreset, resolveTraceUrl, runInOperationContext, runWithCorrelationId, runWithRequestContext, runWithSpan, safeSetAttributes, samplingPresets, setAutotelTracerProvider, setCorrelationId, setCorrelationIdInBaggage, setDevice, setError, setException, setSession, setUser, shutdown, span, structuredErrorToJSON, toAttributeValue, trace, traceConsumer, traceDB, traceHTTP, traceMessaging, traceProducer, traceStep, traceWorkflow, track, validateAttribute, withBaggage, withNewContext, withTracing };
640
+ export { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, type AttributeGuardrails, type AttributePolicy, AttributeRedactingProcessor, type AttributeRedactingProcessorOptions, type AttributeRedactorConfig, type AttributeRedactorFn, type AttributeRedactorPreset, type AttributeValue, type Attributes, type AuditAction, type AuditCatalog, type AuditCatalogEntry, type AuditDescriptor, type AuditSeverity, type AutotelConfig, type Baggage, type BaggageEntry, type BaggageError, type BaggageFieldDefinition, type BaggageFieldType, BaggageSpanProcessor, type BaggageSpanProcessorOptions, type BuiltinPatternName, BusinessBaggage, type BusinessBaggageValues, CORRELATION_ID_BAGGAGE_KEY, type ClientAttrs, type CloudAttrs, type CodeAttrs, type ConsumerConfig, type ConsumerContext, type ContainerAttrs, type Context, type DBAttrs, type DBConfig, type DefineEventOptions, type DefinedEvent, type DeploymentAttrs, type DeviceAttrs, type DrainOptions, type DrainPipelineOptions, type EnrichContext, type EnricherDefinition, type EnricherOptions, type ErrorAttrs, type ErrorBuildOptions, type ErrorBuilder, type ErrorCatalog, type ErrorCatalogEntry, Event, type EventAttributes, type EventSubscriber, type EventsOptions, type Exception, type ExceptionAttrs, type FaaSAttrs, type FeatureFlagAttrs, FilteringSpanProcessor, type FilteringSpanProcessorOptions, type ForkLifecycle, type ForkOptions, type FunnelStatus, type GraphQLAttrs, HTTPAttributes, type HTTPClientAttrs, type HTTPConfig, type HTTPServerAttrs, type HrTime, type HttpDrainOptions, type HttpDrainRequest, type InstrumentOptions, type K8sAttrs, type LagMetricsConfig, type Link, type MaskFn, type MessagingAttrs, type MessagingConfig, type MessagingOperation, type MessagingSystem, Metric, type MetricsOptions, NORMALIZER_PATTERNS, NORMALIZER_PRESETS, type NetworkAttrs, NeverSampler, type OTelAttrs, type OperationContext, type TraceContext as OtelTraceContext, type OutcomeStatus, type ParsedError, type PeerAttrs, type PipelineDrainFn, type ProcessAttrs, type ProcessHandlersConfig, type ProducerConfig, type ProducerContext, REDACTOR_PATTERNS, REDACTOR_PRESETS, ROOT_CONTEXT, type RPCAttrs, RandomSampler, type RequestLogLevel, type RequestLogSnapshot, type RequestLogger, type RequestLoggerOptions, type SafeBaggageOptions, type SafeBaggageSchema, type Sampler, type SamplingContext, type SamplingPreset, type SchemaLike, type ServerAddressAttrs, ServiceAttributes, type ServiceAttrs, type SessionAttrs, type SingleInstrumentOptions, type Span, type SpanAttributes, type SpanContext, type SpanFilterPredicate, SpanKind, type SpanLink, type SpanNameNormalizerConfig, type SpanNameNormalizerFn, type SpanNameNormalizerPreset, SpanNameNormalizingProcessor, type SpanNameNormalizingProcessorOptions, type SpanOptions, SpanStatusCode, type StepConfig, type StepContext, type StepStatus, type StringRedactor, type StructuredError, type StructuredErrorInput, type TLSAttrs, type TextMapGetter, type TextMapSetter, type ThreadAttrs, type TimeInput, type TraceContext$1 as TraceContext, type TraceFlags, type TraceState, type Tracer, type TracerProvider, URLAttributes, type URLAttrs, type UserAttrs, UserIdSampler, type ValuePatternConfig, type WithBaggageOptions, type WithNewContextOptions, type WorkflowConfig, type WorkflowContext, type WorkflowStatus, attrs, autoRedactPII, builtinPatterns, context, createAttributeRedactor, createCounter, createDeterministicTraceId, createDrainPipeline, createHistogram, createLinkFromHeaders, createNoopRequestLogger, createObservableGauge, createRedactedSpan, createSafeBaggageSchema, createStringRedactor, createStructuredError, createUpDownCounter, ctx, dbClient, defineAuditCatalog, defineBaggageSchema, defineDrain, defineEnricher, defineErrorCatalog, defineEvent, defineHttpDrain, enrichWithTraceContext, extractLinksFromBatch, finalizeSpan, flattenMetadata, flattenToAttributes, flush, formatDuration, generateCorrelationId, getActiveContext, getActiveSpan, getActiveTraceContext, getAutotelTracer, getAutotelTracerProvider, getCatalogCode, getCorrelationId, getCurrentWorkflowContext, getEventQueue, getEvents, getMeter, getMetrics, getOperationContext, getOrCreateCorrelationId, getRequestLogger, getRequestLoggerSafe, getStructuredErrorAttributes, getTraceContext, getTracer, hasRequestContext, httpClient, httpRequestHeaderAttribute, httpResponseHeaderAttribute, httpServer, identify, init, instrument, isCatalogError, isInWorkflow, isInitialized, isLoggerLocked, isTracing, lockLogger, mergeAttrs, mergeServiceResource, normalizeAttributeRedactorConfig, otelTrace, parseError, propagation, recordStructuredError, request, resetEvents, resetMetrics, resolveSamplingPreset, resolveTraceUrl, runInOperationContext, runWithCorrelationId, runWithRequestContext, runWithSpan, safeSetAttributes, samplingPresets, setAutotelTracerProvider, setCorrelationId, setCorrelationIdInBaggage, setDevice, setError, setException, setSession, setUser, shutdown, span, structuredErrorToJSON, toAttributeValue, trace, traceConsumer, traceDB, traceHTTP, traceMessaging, traceProducer, traceStep, traceWorkflow, track, validateAttribute, withBaggage, withNewContext, withTracing };
638
641
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/baggage-span-processor.ts","../src/trace-hybrid.ts","../src/operation-context.ts","../src/rate-limiter.ts","../src/event-queue.ts","../src/track.ts","../src/shutdown.ts","../src/request-logger.ts","../src/structured-error.ts","../src/error-catalog.ts","../src/flatten-attributes.ts","../src/drain-toolkit.ts","../src/enricher-toolkit.ts","../src/pretty-log-formatter.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;UAaiB;;;;;EAKf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCW,gCAAgC;mBAC1B;EAEL,YAAA,UAAS;EAIrB,QAAQ,MAAM,QAAM,eAAe;EA4BnC,MAAM,OAAO;EAIP,YAAY;EAIZ,cAAc;;;;cC9DT,cAAc,iBAAwB;;;;;;;;;;;;;;;UCjBlC;;;;;EAKf;;;;;;;;;;;;;;;iBAsBc,uBAAuB;;;;;;;;;;;;;;;;;;;;;iBAwBvB,sBAAsB,GAAG,cAAc,UAAU,IAAI;;;;;;;;;UC5DpD;;EAEf;;EAEA;;;;UCoBe;EACf;EACA,aAAa;EACb;;EAEA;;EAEA;;EAEA,UAAU;;EAEV,SAAS;;UAUM;EACf;EACA;EACA;EACA;EACA,YAAY;;;;;;;;;;;;cAmED;UACH;UACA;mBACS;mBACA;mBACA;UACT;UACA;UAGA;UAGA;UAGA;EAEI,YAAA,aAAa,mBAAmB,SAAS,QAAQ;;;;UAsBr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YAAY,QAAQ,YAAY;EACnD;EACA;EACA,oBAAoB,QAAQ;EAC5B,kBAAkB,QAAQ;;iBAqDZ,YAAY,UAAU,SAAS,WAAW,UACxD,SAAS,aAAa,UAAU,SAAS,aACvC,KAAK,WAAW,eAAe;iBAsBnB,gBAAgB,UAAU,SAAS,WAAW,UAC5D,SAAS,iBAAiB,UAAU,SAAS,aAC3C,KAAK,WAAW,eAAe;;;UCzGlB,cAAc,eAAe;EAC5C,OAAO;EACP;IACE;IACA;IACA;;EAEF;IACE;;EAEF,UAAU;;UAGK,mBACf,eAAe,yBACf;;EAGA;;EAEA,aAAa;;EAEb,UAAU,KAAK,cAAc,YAAY;;UAG1B;;EAEf;;iBAuBc,eACd,eAAe,yBACf,uBAEA,KAAK,mBAAmB,QAAQ,SAChC,UAAS,mBACP,KAAK,cAAc;;;;;;;;;;;iBCUP,eAAe"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/baggage-span-processor.ts","../src/trace-hybrid.ts","../src/operation-context.ts","../src/rate-limiter.ts","../src/event-queue.ts","../src/track.ts","../src/shutdown.ts","../src/request-logger.ts","../src/structured-error.ts","../src/error-catalog.ts","../src/flatten-attributes.ts","../src/drain-toolkit.ts","../src/enricher-toolkit.ts","../src/pretty-log-formatter.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;UAaiB;;;;;EAKf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCW,gCAAgC;mBAC1B;EAEL,YAAA,UAAS;EAIrB,QAAQ,MAAM,QAAM,eAAe;EA4BnC,MAAM,OAAO;EAIP,YAAY;EAIZ,cAAc;;;;cC9DT,cAAc,iBAAwB;;;;;;;;;;;;;;;UCjBlC;;;;;EAKf;;;;;;;;;;;;;;;iBAsBc,uBAAuB;;;;;;;;;;;;;;;;;;;;;iBAwBvB,sBAAsB,GAAG,cAAc,UAAU,IAAI;;;;;;;;;UC5DpD;;EAEf;;EAEA;;;;UCoBe;EACf;EACA,aAAa;EACb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