autotel 6.3.0 → 6.4.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 (51) hide show
  1. package/dist/auto.cjs +1 -1
  2. package/dist/auto.js +1 -1
  3. package/dist/correlation-id.cjs +1 -1
  4. package/dist/correlation-id.js +1 -1
  5. package/dist/decorators.cjs +1 -1
  6. package/dist/decorators.d.cts +1 -1
  7. package/dist/decorators.d.ts +1 -1
  8. package/dist/decorators.js +1 -1
  9. package/dist/event.cjs +1 -1
  10. package/dist/event.js +1 -1
  11. package/dist/functional-AT22vCw6.d.ts +389 -0
  12. package/dist/{functional-TbnG2lu7.cjs → functional-BEEhlVKD.cjs} +221 -283
  13. package/dist/{functional-DCBhFool.js → functional-DbCVvGfT.js} +221 -283
  14. package/dist/functional-e6jw5zQj.d.cts +389 -0
  15. package/dist/functional.cjs +1 -1
  16. package/dist/functional.d.cts +2 -432
  17. package/dist/functional.d.ts +2 -432
  18. package/dist/functional.js +1 -1
  19. package/dist/http.cjs +1 -1
  20. package/dist/http.js +1 -1
  21. package/dist/index.cjs +2 -2
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +2 -2
  25. package/dist/{init-Qn4gIW1i.js → init-C2fjPVkW.js} +18 -9
  26. package/dist/{init-BneZ7WJ8.cjs → init-C5V4z7S5.cjs} +18 -9
  27. package/dist/{init-CfVWN4ND.d.cts → init-Cc7-vvzj.d.cts} +18 -0
  28. package/dist/{init-C1i2_2zl.d.ts → init-CsODvlau.d.ts} +18 -0
  29. package/dist/instrumentation.cjs +1 -1
  30. package/dist/instrumentation.js +1 -1
  31. package/dist/messaging.cjs +1 -1
  32. package/dist/messaging.js +1 -1
  33. package/dist/policy-CbpP4tFH.d.cts +147 -0
  34. package/dist/policy-CbpP4tFH.d.ts +147 -0
  35. package/dist/policy.cjs +0 -0
  36. package/dist/policy.d.cts +2 -0
  37. package/dist/policy.d.ts +2 -0
  38. package/dist/policy.js +0 -0
  39. package/dist/semantic-helpers.cjs +1 -1
  40. package/dist/semantic-helpers.js +1 -1
  41. package/dist/webhook.cjs +1 -1
  42. package/dist/webhook.js +1 -1
  43. package/dist/workflow-distributed.cjs +1 -1
  44. package/dist/workflow-distributed.js +1 -1
  45. package/dist/workflow.cjs +1 -1
  46. package/dist/workflow.js +1 -1
  47. package/dist/yaml-config.cjs +1 -0
  48. package/dist/yaml-config.d.cts +3 -1
  49. package/dist/yaml-config.d.ts +3 -1
  50. package/dist/yaml-config.js +1 -0
  51. package/package.json +6 -1
@@ -1,433 +1,3 @@
1
1
  import { n as TraceContext } from "./trace-context-IuyoPyNq.js";
2
- import { p as Sampler } from "./sampling-CP3e7-Yr.js";
3
- import { Span } from "@opentelemetry/api";
4
- //#region src/functional.d.ts
5
- type WrappedFunction<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn | Promise<TReturn>;
6
- /**
7
- * Common options for functional tracing
8
- */
9
- interface TracingOptions<TArgs extends unknown[] = unknown[], TReturn = unknown> {
10
- /**
11
- * Span name (highest priority)
12
- * If provided, this is used as the span name
13
- */
14
- name?: string;
15
- /**
16
- * Service name (used to compose final span name)
17
- * If name not provided, span name becomes: ${serviceName}.${functionName}
18
- */
19
- serviceName?: string;
20
- /**
21
- * Sampling strategy
22
- * @default AlwaysSampler
23
- */
24
- sampler?: Sampler;
25
- /**
26
- * Enable metrics collection (counter, histogram)
27
- * @default false
28
- */
29
- withMetrics?: boolean;
30
- /**
31
- * Extract attributes from function arguments
32
- */
33
- attributesFromArgs?: (args: TArgs) => Record<string, unknown>;
34
- /**
35
- * Extract attributes from function result
36
- */
37
- attributesFromResult?: (result: TReturn) => Record<string, unknown>;
38
- /**
39
- * Capture the function arguments onto the span as `autotel.input`
40
- * (JSON, truncated). One arg is captured directly; multiple are captured as
41
- * an array. Off by default — opt in per call. Tools (visualizers, devtools)
42
- * read this alongside `ai.toolCall.args` to show function I/O uniformly.
43
- * Avoid on args with secrets/PII, or pair with a redacting processor.
44
- */
45
- captureInput?: boolean;
46
- /**
47
- * Capture the function return value onto the span as `autotel.output`
48
- * (JSON, truncated). Off by default. Same caveats as {@link captureInput}.
49
- */
50
- captureOutput?: boolean;
51
- /**
52
- * Start a new root span instead of creating a child
53
- * Useful for serverless entry points
54
- * @default false
55
- */
56
- startNewRoot?: boolean;
57
- /**
58
- * Flush events queue when span ends
59
- * Only flushes on root spans (to avoid excessive flushing)
60
- * @default true
61
- */
62
- flushOnRootSpanEnd?: boolean;
63
- /**
64
- * Span kind for semantic convention compliance
65
- * Used for messaging (PRODUCER/CONSUMER), HTTP (CLIENT/SERVER), etc.
66
- * @default SpanKind.INTERNAL
67
- */
68
- spanKind?: import('@opentelemetry/api').SpanKind;
69
- /**
70
- * Classify a thrown value as a real error. Return `false` to treat the throw
71
- * as expected control flow: the span is marked OK, no exception is recorded,
72
- * and the value is rethrown untouched. Use this for framework control-flow
73
- * signals that propagate via `throw` but are not failures — e.g. TanStack
74
- * Router / Next.js `redirect()` and `notFound()`.
75
- * @default every throw is treated as an error
76
- */
77
- isError?: (error: unknown) => boolean;
78
- }
79
- /**
80
- * Options for instrument() batch instrumentation
81
- */
82
- interface InstrumentOptions<T extends Record<string, AnyInstrumentable> = Record<string, AnyInstrumentable>> extends TracingOptions {
83
- /** Object whose function properties should be instrumented */
84
- functions: T;
85
- /**
86
- * Per-function configuration overrides
87
- */
88
- overrides?: Record<string, Partial<TracingOptions>>;
89
- /**
90
- * Functions to skip (won't be instrumented)
91
- * Supports:
92
- * - String keys: 'functionName'
93
- * - RegExp: /^_internal/
94
- * - Predicate: (key, fn) => boolean
95
- *
96
- * By default, functions starting with _ are skipped
97
- */
98
- skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[];
99
- }
100
- /**
101
- * Options for instrumenting one function with an explicit stable key.
102
- */
103
- interface SingleInstrumentOptions<TFunction extends AnyInstrumentable = AnyInstrumentable> extends TracingOptions {
104
- /** Stable function key used for span naming */
105
- key: string;
106
- /** Function to instrument */
107
- fn: TFunction;
108
- }
109
- /**
110
- * Constraint alias for `instrument()` and friends. `never[]` parameters make
111
- * every concretely-typed function (e.g. `(name: string) => Promise<User>`)
112
- * satisfy the constraint under `strictFunctionTypes` without resorting to
113
- * `any`. Use ONLY in constraint positions — the concrete `T` is still
114
- * inferred from the actual argument, so call-site argument and return types
115
- * are fully preserved.
116
- */
117
- type AnyInstrumentable = ((...args: never[]) => unknown) & {
118
- displayName?: string;
119
- name?: string;
120
- };
121
- /**
122
- * Get the autotel {@link TraceContext} for the currently active span.
123
- *
124
- * This is the ambient accessor for the functional API: instead of threading a
125
- * `ctx` parameter through a factory, call this inside any traced function (or a
126
- * helper it calls) to reach `setAttribute`, `setUser`, `getBaggage`, and the
127
- * rest of the context surface. Returns `undefined` when no span is active.
128
- *
129
- * @example
130
- * ```typescript
131
- * const getUser = trace('getUser', async (id: string) => {
132
- * getActiveTraceContext()?.setAttribute('user.id', id);
133
- * return db.users.find(id);
134
- * });
135
- * ```
136
- *
137
- * @see getActiveSpan for the raw OpenTelemetry span
138
- * @see getRequestLogger which reads the active context when called with no args
139
- */
140
- declare function getActiveTraceContext<TBaggage extends Record<string, unknown> | undefined = undefined>(): TraceContext<TBaggage> | undefined;
141
- /**
142
- * Context object that lazily evaluates the active span on property access
143
- *
144
- * Access trace context directly without function call syntax.
145
- *
146
- * @example
147
- * ```typescript
148
- * import { trace, ctx } from 'autotel'
149
- *
150
- * export const createUser = trace(async (data) => {
151
- * // Direct property access - no function call!
152
- * if (ctx.traceId) {
153
- * ctx.setAttribute('user.id', data.id)
154
- * console.log('Trace:', ctx.traceId)
155
- * }
156
- * })
157
- * ```
158
- */
159
- declare const ctx: TraceContext;
160
- /**
161
- * Approach 1: trace() - Zero-ceremony HOF
162
- *
163
- * Wrap a plain function with automatic tracing. The function receives its real
164
- * arguments; no context parameter is injected. Use
165
- * {@link getActiveTraceContext} inside the function, or use {@link withTracing}
166
- * for the explicit `(ctx) => (...args) => result` factory form.
167
- *
168
- * @example Auto-inferred name - Plain function
169
- * ```typescript
170
- * export const createUser = trace(async (data) => {
171
- * return await db.users.create(data)
172
- * })
173
- * // → Traced as "createUser"
174
- * ```
175
- *
176
- * @example Ambient context access
177
- * ```typescript
178
- * export const createUser = trace(async (data) => {
179
- * getActiveTraceContext()?.setAttribute('user.id', data.id)
180
- * return await db.users.create(data)
181
- * })
182
- * ```
183
- *
184
- * @example Custom name - Plain function
185
- * ```typescript
186
- * export const createUser = trace('user.create', async (data) => {
187
- * return await db.users.create(data)
188
- * })
189
- * // → Traced as "user.create"
190
- * ```
191
- *
192
- * @example Explicit factory context with withTracing()
193
- * ```typescript
194
- * export const createUser = withTracing({ name: 'user.create' })((ctx) => async (data) => {
195
- * ctx.setAttribute('user.id', data.id)
196
- * return await db.users.create(data)
197
- * })
198
- * ```
199
- *
200
- * @example Full options - Plain function
201
- * ```typescript
202
- * export const createUser = trace({
203
- * name: 'user.create',
204
- * sampler: new AdaptiveSampler(),
205
- * withMetrics: true
206
- * }, async (data) => {
207
- * return await db.users.create(data)
208
- * })
209
- * ```
210
- *
211
- */
212
- declare function trace<TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
213
- declare function trace<TArgs extends unknown[], TReturn>(name: string, fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
214
- declare function trace<TArgs extends unknown[], TReturn>(options: TracingOptions<TArgs, TReturn>, fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
215
- /**
216
- * Approach 2: withTracing() - Middleware-style composable wrapper
217
- *
218
- * Returns a HOF that wraps functions with tracing.
219
- * Perfect for composition and reusable configuration.
220
- *
221
- * @example Standard usage
222
- * ```typescript
223
- * export const createUser = withTracing({
224
- * name: 'user.create'
225
- * })(ctx => async (data) => {
226
- * ctx.setAttribute('user.id', data.id)
227
- * return await db.users.create(data)
228
- * })
229
- * ```
230
- *
231
- * @example Composable
232
- * ```typescript
233
- * const tracer = withTracing({ serviceName: 'user' })
234
- *
235
- * export const createUser = tracer(ctx => async (data) => { })
236
- * export const updateUser = tracer(ctx => async (id, data) => { })
237
- * ```
238
- *
239
- * @example With other middleware
240
- * ```typescript
241
- * export const createUser = compose(
242
- * withAuth({ role: 'admin' }),
243
- * withTracing({ name: 'user.create' }),
244
- * withRateLimit({ max: 100 })
245
- * )(ctx => async (data) => { })
246
- * ```
247
- */
248
- declare function withTracing<TCfgArgs extends unknown[] = unknown[], TCfgReturn = unknown>(options?: TracingOptions<TCfgArgs, TCfgReturn>): <TArgs extends TCfgArgs, TReturn extends TCfgReturn>(fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn>) => WrappedFunction<TArgs, TReturn>;
249
- /**
250
- * Approach 3: instrument() - Batch auto-instrumentation
251
- *
252
- * Instrument an entire module/object at once.
253
- * Closest to @Instrumented decorator pattern.
254
- *
255
- * @example Basic usage
256
- * ```typescript
257
- * export default instrument({
258
- * functions: {
259
- * createUser: async (data) => { },
260
- * updateUser: async (id, data) => { },
261
- * deleteUser: async (id) => { }
262
- * },
263
- * serviceName: 'user',
264
- * sampler: new AdaptiveSampler()
265
- * })
266
- * // → Traced as "user.createUser", "user.updateUser", "user.deleteUser"
267
- * ```
268
- *
269
- * @example Per-function overrides
270
- * ```typescript
271
- * export default instrument({
272
- * functions: {
273
- * createUser: async (data) => { },
274
- * deleteUser: async (id) => { }
275
- * },
276
- * serviceName: 'user',
277
- * overrides: {
278
- * deleteUser: {
279
- * sampler: new AlwaysSampler(),
280
- * withMetrics: true
281
- * }
282
- * }
283
- * })
284
- * ```
285
- *
286
- * @example Skip functions
287
- * ```typescript
288
- * export default instrument({
289
- * functions: {
290
- * createUser: async (data) => { },
291
- * _internal: async () => { }, // Auto-skipped (_-prefix)
292
- * deleteUser: async (id) => { }
293
- * },
294
- * serviceName: 'user',
295
- * skip: [/^test/, (key) => key.includes('debug')]
296
- * })
297
- * ```
298
- */
299
- declare function instrument<TFunction extends AnyInstrumentable>(options: SingleInstrumentOptions<TFunction>): TFunction;
300
- declare function instrument<T extends Record<string, AnyInstrumentable>>(options: InstrumentOptions<T>): T;
301
- /**
302
- * Options for span() function
303
- */
304
- interface SpanOptions {
305
- /** Span name */
306
- name: string;
307
- /** Attributes to set on the span */
308
- attributes?: Record<string, string | number | boolean>;
309
- /** OpenTelemetry span kind */
310
- spanKind?: import('@opentelemetry/api').SpanKind;
311
- }
312
- /**
313
- * Execute a function within a named span
314
- *
315
- * Useful for adding tracing to specific code blocks without wrapping
316
- * the entire function. Supports both synchronous and asynchronous functions.
317
- *
318
- * Mirrors `trace()`: pass a span name as the first argument for the common
319
- * case, or full `SpanOptions` when you need to attach attributes.
320
- *
321
- * @example
322
- * ```typescript
323
- * // Name shorthand
324
- * await span('payment.charge', async (span) => {
325
- * await chargeCustomer(order);
326
- * })
327
- *
328
- * // Full options when attributes are needed
329
- * await span(
330
- * { name: 'payment.charge', attributes: { amount: order.total } },
331
- * async (span) => {
332
- * await chargeCustomer(order);
333
- * },
334
- * )
335
- *
336
- * // Sync
337
- * const total = span('calculateTotal', (span) => {
338
- * return items.reduce((sum, item) => sum + item.price, 0);
339
- * })
340
- * ```
341
- */
342
- declare function span<T = unknown>(name: string, fn: (span: Span) => T): T;
343
- declare function span<T = unknown>(name: string, fn: (span: Span) => Promise<T>): Promise<T>;
344
- declare function span<T = unknown>(options: SpanOptions, fn: (span: Span) => T): T;
345
- declare function span<T = unknown>(options: SpanOptions, fn: (span: Span) => Promise<T>): Promise<T>;
346
- /**
347
- * Options for withNewContext() function
348
- */
349
- interface WithNewContextOptions<T = unknown> {
350
- /** Function to execute in new root context */
351
- fn: () => Promise<T>;
352
- }
353
- /**
354
- * Execute a function in a new root context (prevents span propagation)
355
- *
356
- * Useful when you want to start a completely new trace without
357
- * parent-child relationships.
358
- *
359
- * @example
360
- * ```typescript
361
- * async function handleWebhook(payload: WebhookPayload) {
362
- * // This creates a new root trace, not connected to the HTTP request trace
363
- * await withNewContext({
364
- * fn: async () => {
365
- * await span('webhook.process', async () => {
366
- * await processWebhookPayload(payload)
367
- * })
368
- * }
369
- * })
370
- * }
371
- * ```
372
- */
373
- declare function withNewContext<T = unknown>(options: WithNewContextOptions<T>): Promise<T>;
374
- /**
375
- * Options for withBaggage() function
376
- */
377
- interface WithBaggageOptions<T = unknown> {
378
- /** Baggage entries to set (key-value pairs) */
379
- baggage: Record<string, string>;
380
- /** Function to execute with the updated baggage */
381
- fn: () => T | Promise<T>;
382
- }
383
- /**
384
- * Execute a function with updated baggage entries
385
- *
386
- * Baggage is immutable in OpenTelemetry, so this helper creates a new context
387
- * with the specified baggage entries and runs the function within that context.
388
- * All child spans created within the function will inherit the baggage.
389
- *
390
- * @example Setting baggage for downstream services
391
- * ```typescript
392
- * import { withTracing, withBaggage } from 'autotel';
393
- *
394
- * export const createOrder = withTracing({ name: 'order.create' })((ctx) => async (order: Order) => {
395
- * // Set baggage that will be propagated to downstream HTTP calls
396
- * return await withBaggage({
397
- * baggage: {
398
- * 'tenant.id': order.tenantId,
399
- * 'user.id': order.userId,
400
- * },
401
- * fn: async () => {
402
- * // This HTTP call will include the baggage in headers
403
- * await fetch('/api/charge', {
404
- * method: 'POST',
405
- * body: JSON.stringify(order),
406
- * });
407
- * },
408
- * });
409
- * });
410
- * ```
411
- *
412
- * @example Using with existing baggage
413
- * ```typescript
414
- * export const processOrder = withTracing({ name: 'order.process' })((ctx) => async (order: Order) => {
415
- * // Read existing baggage
416
- * const tenantId = ctx.getBaggage('tenant.id');
417
- *
418
- * // Add additional baggage entries
419
- * return await withBaggage({
420
- * baggage: {
421
- * 'order.id': order.id,
422
- * 'order.amount': String(order.amount),
423
- * },
424
- * fn: async () => {
425
- * await charge(order);
426
- * },
427
- * });
428
- * });
429
- * ```
430
- */
431
- declare function withBaggage<T = unknown>(options: WithBaggageOptions<T>): T | Promise<T>;
432
- //#endregion
433
- export { InstrumentOptions, SingleInstrumentOptions, SpanOptions, type TraceContext, TracingOptions, WithBaggageOptions, WithNewContextOptions, ctx, getActiveTraceContext, instrument, span, trace, withBaggage, withNewContext, withTracing };
2
+ import { a as getActiveTraceContext, c as trace, d as withTracing, f as InstrumentOptions, i as ctx, l as withBaggage, m as TracingOptions, n as WithBaggageOptions, o as instrument, p as SingleInstrumentOptions, r as WithNewContextOptions, s as span, t as SpanOptions, u as withNewContext } from "./functional-AT22vCw6.js";
3
+ export { type InstrumentOptions, type SingleInstrumentOptions, SpanOptions, type TraceContext, type TracingOptions, WithBaggageOptions, WithNewContextOptions, ctx, getActiveTraceContext, instrument, span, trace, withBaggage, withNewContext, withTracing };
@@ -1,3 +1,3 @@
1
- import { a as trace, c as withTracing, i as span, n as getActiveTraceContext, o as withBaggage, r as instrument, s as withNewContext, t as ctx } from "./functional-DCBhFool.js";
1
+ import { a as trace, c as withTracing, i as span, n as getActiveTraceContext, o as withBaggage, r as instrument, s as withNewContext, t as ctx } from "./functional-DbCVvGfT.js";
2
2
 
3
3
  export { ctx, getActiveTraceContext, instrument, span, trace, withBaggage, withNewContext, withTracing };
package/dist/http.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_config = require('./config.cjs');
3
- const require_init = require('./init-BneZ7WJ8.cjs');
3
+ const require_init = require('./init-C5V4z7S5.cjs');
4
4
  let _opentelemetry_api = require("@opentelemetry/api");
5
5
 
6
6
  //#region src/http.ts
package/dist/http.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getConfig } from "./config.js";
2
- import { D as getActiveContextWithBaggage } from "./init-Qn4gIW1i.js";
2
+ import { D as getActiveContextWithBaggage } from "./init-C2fjPVkW.js";
3
3
  import { SpanStatusCode, context, propagation } from "@opentelemetry/api";
4
4
 
5
5
  //#region src/http.ts
package/dist/index.cjs CHANGED
@@ -2,7 +2,7 @@ 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-BneZ7WJ8.cjs');
5
+ const require_init = require('./init-C5V4z7S5.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');
@@ -10,7 +10,7 @@ const require_canonical_log_line_processor = require('./canonical-log-line-proce
10
10
  const require_structured_error = require('./structured-error-CHg7DoIQ.cjs');
11
11
  const require_metric = require('./metric.cjs');
12
12
  const require_trace_helpers = require('./trace-helpers.cjs');
13
- const require_functional = require('./functional-TbnG2lu7.cjs');
13
+ const require_functional = require('./functional-BEEhlVKD.cjs');
14
14
  const require_stable_hash = require('./stable-hash-CS9BxvVQ.cjs');
15
15
  const require_correlated_events = require('./correlated-events-kSwLo3mi.cjs');
16
16
  const require_parse_error = require('./parse-error.cjs');
package/dist/index.d.cts CHANGED
@@ -4,12 +4,12 @@ import { n as TraceContext$1, r as defineBaggageSchema, t as AttributeValue$2 }
4
4
  import { BaggageError, BaggageFieldDefinition, BaggageFieldType, BusinessBaggage, BusinessBaggageValues, SafeBaggageOptions, SafeBaggageSchema, createSafeBaggageSchema } from "./business-baggage.cjs";
5
5
  import { CORRELATION_ID_BAGGAGE_KEY, generateCorrelationId, getCorrelationId, getOrCreateCorrelationId, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage } from "./correlation-id.cjs";
6
6
  import { _ as createLinkFromHeaders, a as AlwaysSampler, b as resolveSamplingPreset, f as RandomSampler, g as UserIdSampler, h as SamplingPreset, i as AdaptiveSampler, m as SamplingContext, n as AUTOTEL_SAMPLING_TAIL_EVALUATED, p as Sampler, r as AUTOTEL_SAMPLING_TAIL_KEEP, u as NeverSampler, v as extractLinksFromBatch, x as samplingPresets } from "./sampling-BR9fkSwx.cjs";
7
- import { InstrumentOptions, SingleInstrumentOptions, SpanOptions, WithBaggageOptions, WithNewContextOptions, ctx, getActiveTraceContext, instrument, span, trace as trace$2, withBaggage, withNewContext, withTracing } from "./functional.cjs";
7
+ import { a as getActiveTraceContext, c as trace$2, d as withTracing, f as InstrumentOptions, i as ctx, l as withBaggage, n as WithBaggageOptions, o as instrument, p as SingleInstrumentOptions, r as WithNewContextOptions, s as span, t as SpanOptions, u as withNewContext } from "./functional-e6jw5zQj.cjs";
8
8
  import { DrainPipelineOptions, PipelineDrainFn, createDrainPipeline } from "./drain-pipeline.cjs";
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 AutotelConfig, c as StringRedactor, i as lockLogger, l as createStringRedactor, n as isInitialized, r as isLoggerLocked, s as ProcessHandlersConfig, t as init } from "./init-CfVWN4ND.cjs";
12
+ import { a as AutotelConfig, c as StringRedactor, i as lockLogger, l as createStringRedactor, n as isInitialized, r as isLoggerLocked, s as ProcessHandlersConfig, t as init } from "./init-Cc7-vvzj.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";
package/dist/index.d.ts CHANGED
@@ -4,12 +4,12 @@ import { n as TraceContext$1, r as defineBaggageSchema, t as AttributeValue$2 }
4
4
  import { BaggageError, BaggageFieldDefinition, BaggageFieldType, BusinessBaggage, BusinessBaggageValues, SafeBaggageOptions, SafeBaggageSchema, createSafeBaggageSchema } from "./business-baggage.js";
5
5
  import { CORRELATION_ID_BAGGAGE_KEY, generateCorrelationId, getCorrelationId, getOrCreateCorrelationId, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage } from "./correlation-id.js";
6
6
  import { _ as createLinkFromHeaders, a as AlwaysSampler, b as resolveSamplingPreset, f as RandomSampler, g as UserIdSampler, h as SamplingPreset, i as AdaptiveSampler, m as SamplingContext, n as AUTOTEL_SAMPLING_TAIL_EVALUATED, p as Sampler, r as AUTOTEL_SAMPLING_TAIL_KEEP, u as NeverSampler, v as extractLinksFromBatch, x as samplingPresets } from "./sampling-CP3e7-Yr.js";
7
- import { InstrumentOptions, SingleInstrumentOptions, SpanOptions, WithBaggageOptions, WithNewContextOptions, ctx, getActiveTraceContext, instrument, span, trace as trace$2, withBaggage, withNewContext, withTracing } from "./functional.js";
7
+ import { a as getActiveTraceContext, c as trace$2, d as withTracing, f as InstrumentOptions, i as ctx, l as withBaggage, n as WithBaggageOptions, o as instrument, p as SingleInstrumentOptions, r as WithNewContextOptions, s as span, t as SpanOptions, u as withNewContext } from "./functional-AT22vCw6.js";
8
8
  import { DrainPipelineOptions, PipelineDrainFn, createDrainPipeline } from "./drain-pipeline.js";
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.js";
10
10
  import { Event, EventsOptions, getEvents, resetEvents } from "./event.js";
11
11
  import { n as FilteringSpanProcessorOptions, r as SpanFilterPredicate, t as FilteringSpanProcessor } from "./filtering-span-processor-BpDagWNa.js";
12
- import { a as AutotelConfig, c as StringRedactor, i as lockLogger, l as createStringRedactor, n as isInitialized, r as isLoggerLocked, s as ProcessHandlersConfig, t as init } from "./init-C1i2_2zl.js";
12
+ import { a as AutotelConfig, c as StringRedactor, i as lockLogger, l as createStringRedactor, n as isInitialized, r as isLoggerLocked, s as ProcessHandlersConfig, t as init } from "./init-CsODvlau.js";
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.js";
14
14
  import "./canonical-log-line-processor-CL_J7gb5.js";
15
15
  import { i as defineEvent, n as DefinedEvent, r as SchemaLike, t as DefineEventOptions } from "./define-event-B2z1SBe7.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { getAutotelTracer, getAutotelTracerProvider, setAutotelTracerProvider } from "./tracer-provider.js";
2
2
  import { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, NeverSampler, RandomSampler, UserIdSampler, createLinkFromHeaders, extractLinksFromBatch, resolveSamplingPreset, samplingPresets } from "./sampling.js";
3
- import { A as BaggageSpanProcessor, C as setCorrelationId, E as defineBaggageSchema, S as runWithCorrelationId, T as createTraceContext, _ as CORRELATION_ID_BAGGAGE_KEY, a as isInitialized, c as flush, d as getEvents, f as resetEvents, g as track, h as getEventQueue, i as init, k as createStringRedactor, l as shutdown, m as runInOperationContext, o as isLoggerLocked, p as getOperationContext, s as lockLogger, u as Event, v as generateCorrelationId, w as setCorrelationIdInBaggage, x as getOrCreateCorrelationId, y as getCorrelationId } from "./init-Qn4gIW1i.js";
3
+ import { A as BaggageSpanProcessor, C as setCorrelationId, E as defineBaggageSchema, S as runWithCorrelationId, T as createTraceContext, _ as CORRELATION_ID_BAGGAGE_KEY, a as isInitialized, c as flush, d as getEvents, f as resetEvents, g as track, h as getEventQueue, i as init, k as createStringRedactor, l as shutdown, m as runInOperationContext, o as isLoggerLocked, p as getOperationContext, s as lockLogger, u as Event, v as generateCorrelationId, w as setCorrelationIdInBaggage, x as getOrCreateCorrelationId, y as getCorrelationId } from "./init-C2fjPVkW.js";
4
4
  import { FilteringSpanProcessor } from "./filtering-span-processor.js";
5
5
  import { NORMALIZER_PATTERNS, NORMALIZER_PRESETS, SpanNameNormalizingProcessor } from "./span-name-normalizer.js";
6
6
  import { AttributeRedactingProcessor, REDACTOR_PATTERNS, REDACTOR_PRESETS, builtinPatterns, createAttributeRedactor, createRedactedSpan, normalizeAttributeRedactorConfig } from "./attribute-redacting-processor.js";
@@ -8,7 +8,7 @@ import { n as formatDuration } from "./canonical-log-line-processor-mKABvGP0.js"
8
8
  import { a as flattenToAttributes, i as structuredErrorToJSON, n as getStructuredErrorAttributes, o as toAttributeValue, r as recordStructuredError, t as createStructuredError } from "./structured-error-9--cxBay.js";
9
9
  import { Metric, getMetrics, resetMetrics } from "./metric.js";
10
10
  import { createDeterministicTraceId, enrichWithTraceContext, finalizeSpan, flattenMetadata, getActiveContext, getActiveSpan, getTraceContext, getTracer, isTracing, resolveTraceUrl, runWithSpan } from "./trace-helpers.js";
11
- import { a as trace$2, c as withTracing, i as span, n as getActiveTraceContext, o as withBaggage, r as instrument, s as withNewContext, t as ctx } from "./functional-DCBhFool.js";
11
+ import { a as trace$2, c as withTracing, i as span, n as getActiveTraceContext, o as withBaggage, r as instrument, s as withNewContext, t as ctx } from "./functional-DbCVvGfT.js";
12
12
  import { t as hashJson } from "./stable-hash-ChFBIhNt.js";
13
13
  import { t as emitCorrelatedEvent } from "./correlated-events-Bzh5y-UB.js";
14
14
  import { parseError } from "./parse-error.js";
@@ -4,6 +4,7 @@ import { AUTOTEL_SAMPLING_RATE, resolveSamplingPreset, samplingPresets } from ".
4
4
  import { n as safeRequire, t as requireModule } from "./node-require-vROmTeJ8.js";
5
5
  import { TailSamplingSpanProcessor } from "./tail-sampling-processor.js";
6
6
  import { FilteringSpanProcessor } from "./filtering-span-processor.js";
7
+ import { PolicyLogRecordProcessor, policySpanFilter, setPolicies, watchPolicyFile } from "./policy.js";
7
8
  import { SpanNameNormalizingProcessor } from "./span-name-normalizer.js";
8
9
  import { AttributeRedactingProcessor, REDACTOR_PRESETS, normalizeAttributeRedactorConfig } from "./attribute-redacting-processor.js";
9
10
  import { t as PrettyConsoleExporter } from "./pretty-console-exporter-DqKl_q9z.js";
@@ -544,11 +545,15 @@ function getContextStorage() {
544
545
  return contextStorage;
545
546
  }
546
547
  /**
547
- * Get the active context, checking our stored context first
548
- * This ensures baggage setters work with OpenTelemetry's propagation
548
+ * Get the active OTel context with the latest stored baggage overlaid.
549
+ * Span identity always comes from the active OTel scope.
549
550
  */
550
551
  function getActiveContextWithBaggage() {
551
- return contextStorage.getStore()?.value ?? context.active();
552
+ const activeContext = context.active();
553
+ const stored = contextStorage.getStore()?.value;
554
+ if (!stored) return activeContext;
555
+ const storedBaggage = propagation.getBaggage(stored);
556
+ return storedBaggage ? propagation.setBaggage(activeContext, storedBaggage) : activeContext;
552
557
  }
553
558
  /**
554
559
  * Set a value in AsyncLocalStorage, preferring enterWith() when available
@@ -628,15 +633,13 @@ function createTraceContext(span) {
628
633
  return baggage?.getEntry(key)?.value;
629
634
  },
630
635
  setBaggage(key, value) {
631
- const activeCtx = context.active();
632
- const currentContext = contextStorage.getStore()?.value ?? activeCtx;
636
+ const currentContext = getActiveContextWithBaggage();
633
637
  const updated = (propagation.getBaggage(currentContext) ?? propagation.createBaggage()).setEntry(key, { value });
634
638
  updateActiveContext(propagation.setBaggage(currentContext, updated));
635
639
  return value;
636
640
  },
637
641
  deleteBaggage(key) {
638
- const activeCtx = context.active();
639
- const currentContext = contextStorage.getStore()?.value ?? activeCtx;
642
+ const currentContext = getActiveContextWithBaggage();
640
643
  const baggage = propagation.getBaggage(currentContext);
641
644
  if (baggage) {
642
645
  const updated = baggage.removeEntry(key);
@@ -672,8 +675,7 @@ function createTraceContext(span) {
672
675
  return Object.keys(result).length > 0 ? result : void 0;
673
676
  }),
674
677
  setTypedBaggage: ((namespace, value) => {
675
- const activeCtx = context.active();
676
- const currentContext = contextStorage.getStore()?.value ?? activeCtx;
678
+ const currentContext = getActiveContextWithBaggage();
677
679
  let baggage = propagation.getBaggage(currentContext) ?? propagation.createBaggage();
678
680
  const prefix = namespace ? `${namespace}.` : "";
679
681
  for (const [key, val] of Object.entries(value)) if (val !== void 0) {
@@ -3177,6 +3179,12 @@ function init(cfg) {
3177
3179
  for (const subscriber of mergedConfig.subscribers) if (acceptsStringRedactor(subscriber)) subscriber.setStringRedactor(_stringRedactor);
3178
3180
  }
3179
3181
  if (mergedConfig.spanNameNormalizer && spanProcessors.length > 0) spanProcessors = spanProcessors.map((processor) => new SpanNameNormalizingProcessor(processor, { normalizer: mergedConfig.spanNameNormalizer }));
3182
+ if (mergedConfig.policies) {
3183
+ if (typeof mergedConfig.policies === "string") watchPolicyFile(mergedConfig.policies);
3184
+ else setPolicies(mergedConfig.policies);
3185
+ const userSpanFilter = mergedConfig.spanFilter;
3186
+ mergedConfig.spanFilter = userSpanFilter ? (span) => userSpanFilter(span) && policySpanFilter(span) : policySpanFilter;
3187
+ }
3180
3188
  if (mergedConfig.spanFilter && spanProcessors.length > 0) spanProcessors = spanProcessors.map((processor) => new FilteringSpanProcessor(processor, { filter: mergedConfig.spanFilter }));
3181
3189
  const metricReaders = [];
3182
3190
  if (configuredMetricReaders && configuredMetricReaders.length > 0) metricReaders.push(...configuredMetricReaders);
@@ -3215,6 +3223,7 @@ function init(cfg) {
3215
3223
  logRecordProcessors.push(...posthogProcessors);
3216
3224
  logger.info({}, "[autotel] PostHog OTLP logs configured");
3217
3225
  }
3226
+ if (mergedConfig.policies && logRecordProcessors) logRecordProcessors = logRecordProcessors.map((processor) => new PolicyLogRecordProcessor(processor));
3218
3227
  let finalInstrumentations = mergedConfig.instrumentations ? [...mergedConfig.instrumentations] : [];
3219
3228
  if (mergedConfig.autoInstrumentations !== void 0 && mergedConfig.autoInstrumentations !== false) {
3220
3229
  if (isESMMode()) logger.info({}, "[autotel] ESM mode detected. For auto-instrumentation to work:\n 1. Install @opentelemetry/auto-instrumentations-node as a direct dependency\n 2. Import autotel/register FIRST in your instrumentation file\n 3. Use getNodeAutoInstrumentations() directly instead of autoInstrumentations\n See: https://github.com/jagreehal/autotel#esm-setup");