import { a as AttributeRedactorPreset, c as REDACTOR_PATTERNS, d as builtinPatterns, f as createAttributeRedactor, i as AttributeRedactorFn, l as REDACTOR_PRESETS, m as normalizeAttributeRedactorConfig, n as AttributeRedactingProcessorOptions, o as BuiltinPatternName, p as createRedactedSpan, r as AttributeRedactorConfig, s as MaskFn, t as AttributeRedactingProcessor, u as ValuePatternConfig } from "./attribute-redacting-processor-DtTS9xxh.cjs";
import { A as ExceptionAttrs, B as PeerAttrs, C as CloudAttrs, D as DeploymentAttrs, E as DBAttrs, F as HTTPServerAttrs, G as SessionAttrs, H as RPCAttrs, I as K8sAttrs, J as URLAttrs, K as TLSAttrs, L as MessagingAttrs, M as FeatureFlagAttrs, N as GraphQLAttrs, O as DeviceAttrs, P as HTTPClientAttrs, R as NetworkAttrs, S as ClientAttrs, T as ContainerAttrs, U as ServerAddressAttrs, V as ProcessAttrs, W as ServiceAttrs, Y as UserAttrs, _ as autoRedactPII, a as httpClient, b as validateAttribute, c as mergeServiceResource, d as setError, f as setException, g as AttributePolicy, h as AttributeGuardrails, i as dbClient, j as FaaSAttrs, k as ErrorAttrs, l as request, m as setUser, n as safeSetAttributes, o as httpServer, p as setSession, q as ThreadAttrs, s as identify, t as mergeAttrs, u as setDevice, w as CodeAttrs, x as attrs, z as OTelAttrs } from "./index-eKuioqT1.cjs";
import { n as TraceContext$1, r as defineBaggageSchema, t as AttributeValue$2 } from "./trace-context-Cijqoi6e.cjs";
import { BaggageError, BaggageFieldDefinition, BaggageFieldType, BusinessBaggage, BusinessBaggageValues, SafeBaggageOptions, SafeBaggageSchema, createSafeBaggageSchema } from "./business-baggage.cjs";
import { CORRELATION_ID_BAGGAGE_KEY, generateCorrelationId, getCorrelationId, getOrCreateCorrelationId, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage } from "./correlation-id.cjs";
import { _ as samplingPresets, d as SamplingContext, f as SamplingPreset, g as resolveSamplingPreset, h as extractLinksFromBatch, i as AlwaysSampler, l as RandomSampler, m as createLinkFromHeaders, n as AUTOTEL_SAMPLING_TAIL_KEEP, p as UserIdSampler, r as AdaptiveSampler, s as NeverSampler, t as AUTOTEL_SAMPLING_TAIL_EVALUATED, u as Sampler } from "./sampling-DfYhDJij.cjs";
import { InstrumentOptions, SpanOptions, WithBaggageOptions, WithNewContextOptions, ctx, instrument, markAsImmediate, span, trace as trace$2, withBaggage, withNewContext, withTracing } from "./functional.cjs";
import { DrainPipelineOptions, PipelineDrainFn, createDrainPipeline } from "./drain-pipeline.cjs";
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-D1XLkPzi.cjs";
import { Event, EventsOptions, getEvents, resetEvents } from "./event.cjs";
import { n as FilteringSpanProcessorOptions, r as SpanFilterPredicate, t as FilteringSpanProcessor } from "./filtering-span-processor-B8R8B7Uk.cjs";
import { a as isLoggerLocked, c as createStringRedactor, i as isInitialized, o as lockLogger, r as init, s as StringRedactor, t as AutotelConfig } from "./init-DSrRmVnz.cjs";
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-8ZOGJuwv.cjs";
import { i as defineEvent, n as DefinedEvent, r as SchemaLike, t as DefineEventOptions } from "./define-event-HZRizPwz.cjs";
import { ParsedError, parseError } from "./parse-error.cjs";
import { Metric, MetricsOptions, getMetrics, resetMetrics } from "./metric.cjs";
import { createCounter, createHistogram, createObservableGauge, createUpDownCounter, getMeter } from "./metric-helpers.cjs";
import { TraceContext, createDeterministicTraceId, enrichWithTraceContext, finalizeSpan, flattenMetadata, getActiveContext, getActiveSpan, getTraceContext, getTracer, isTracing, resolveTraceUrl, runWithSpan } from "./trace-helpers.cjs";
import { getAutotelTracer, getAutotelTracerProvider, setAutotelTracerProvider } from "./tracer-provider.cjs";
import { DBConfig, HTTPConfig, MessagingConfig, traceDB, traceHTTP, traceMessaging } from "./semantic-helpers.cjs";
import { a as URLAttributes, i as ServiceAttributes, n as httpResponseHeaderAttribute, r as HTTPAttributes, t as httpRequestHeaderAttribute } from "./semantic-conventions-FhSxv-bK.cjs";
import { ConsumerConfig, ConsumerContext, LagMetricsConfig, MessagingOperation, MessagingSystem, ProducerConfig, ProducerContext, traceConsumer, traceProducer } from "./messaging.cjs";
import { StepConfig, StepContext, StepStatus, WorkflowConfig, WorkflowContext, WorkflowStatus, getCurrentWorkflowContext, isInWorkflow, traceStep, traceWorkflow } from "./workflow.cjs";
import { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-base";
import { AttributeValue, Attributes, Baggage, BaggageEntry, Context, Context as Context$1, Exception, HrTime, Link, Link as SpanLink, ROOT_CONTEXT, Span, Span as Span$2, SpanAttributes, SpanContext, SpanKind, SpanStatusCode, TextMapGetter, TextMapSetter, TimeInput, TraceFlags, TraceState, Tracer, TracerProvider, context, propagation, trace as otelTrace, trace as trace$1 } from "@opentelemetry/api";

//#region src/baggage-span-processor.d.ts
interface BaggageSpanProcessorOptions {
  /**
   * Prefix for baggage attributes
   * @default 'baggage.'
   */
  prefix?: string;
}
/**
 * Span processor that automatically copies baggage entries to span attributes
 *
 * This makes baggage visible in trace UIs (Jaeger, Grafana, DataDog, etc.)
 * without manually calling ctx.setAttribute() for each baggage entry.
 *
 * @example Enable in init()
 * ```typescript
 * init({
 *   service: 'my-app',
 *   baggage: true // Uses default 'baggage.' prefix
 * });
 *
 * // Now baggage automatically appears as span attributes
 * await withBaggage({
 *   baggage: { 'tenant.id': 't1', 'user.id': 'u1' },
 *   fn: async () => {
 *     // Span has baggage.tenant.id and baggage.user.id attributes!
 *   }
 * });
 * ```
 *
 * @example Custom prefix
 * ```typescript
 * init({
 *   service: 'my-app',
 *   baggage: 'ctx' // Uses 'ctx.' prefix
 * });
 * // Creates attributes: ctx.tenant.id, ctx.user.id
 * ```
 */
declare class BaggageSpanProcessor implements SpanProcessor {
  private readonly prefix;
  constructor(options?: BaggageSpanProcessorOptions);
  onStart(span: Span$2, parentContext: Context$1): void;
  onEnd(_span: ReadableSpan): void;
  shutdown(): Promise<void>;
  forceFlush(): Promise<void>;
}
//#endregion
//#region src/trace-hybrid.d.ts
declare const trace: typeof trace$2 & typeof trace$1;
//#endregion
//#region src/operation-context.d.ts
/**
 * Operation context tracking using AsyncLocalStorage
 *
 * This module provides a way to track operation names across async boundaries
 * so they can be automatically captured in events events.
 *
 * We cannot read span attributes from OpenTelemetry's API (it's write-only),
 * so we maintain our own async context storage.
 */
/**
 * Operation context that flows through async operations
 */
interface OperationContext {
  /**
   * The name of the current operation
   * This is set by trace() or span() and can be read by events
   */
  name: string;
}
/**
 * Get the current operation context (if any)
 *
 * @returns The current operation context, or undefined if not in an operation
 *
 * @example
 * ```typescript
 * const ctx = getOperationContext();
 * if (ctx) {
 *   console.log('Current operation:', ctx.name);
 * }
 * ```
 */
declare function getOperationContext(): OperationContext | undefined;
/**
 * Run a function within an operation context
 *
 * This sets the operation name for the duration of the function execution,
 * including all async operations spawned from it.
 *
 * @param name - The operation name to set
 * @param fn - The function to execute within the context
 * @returns The result of the function
 *
 * @example
 * ```typescript
 * const result = await runInOperationContext('user.create', async () => {
 *   // Any events.trackEvent() calls here will automatically capture
 *   // 'operation.name': 'user.create'
 *   await createUser();
 *   return 'success';
 * });
 * ```
 */
declare function runInOperationContext<T>(name: string, fn: () => T): T;
//#endregion
//#region src/rate-limiter.d.ts
/**
 * Token bucket rate limiter for event subscribers
 *
 * Prevents overwhelming downstream events platforms with too many events.
 * Uses token bucket algorithm for smooth rate limiting with burst capacity.
 */
interface RateLimiterConfig {
  /** Maximum events per second (default: 100) */
  maxEventsPerSecond: number;
  /** Burst capacity - max events in a single burst (default: 2x rate) */
  burstCapacity?: number;
}
//#endregion
//#region src/event-queue.d.ts
interface EventData {
  name: string;
  attributes?: EventAttributes;
  timestamp: number;
  /** Internal: correlation ID for debug breadcrumbs */
  _correlationId?: string;
  /** Internal: trace ID for debug breadcrumbs */
  _traceId?: string;
  /** Autotel context for trace correlation (passed to subscribers) */
  autotel?: AutotelEventContext;
  /** Optional schema metadata for contract-aware subscribers. */
  schema?: EventSchemaMetadata;
}
interface QueueConfig {
  maxSize: number;
  batchSize: number;
  flushInterval: number;
  maxRetries: number;
  rateLimit?: RateLimiterConfig;
}
/**
 * Events queue with batching and backpressure
 *
 * Features:
 * - Batches events for efficient sending
 * - Bounded queue with drop-oldest policy (prod) or blocking (dev)
 * - Exponential backoff retry
 * - Rate limiting to prevent overwhelming subscribers
 * - Graceful flush on shutdown
 */
declare class EventQueue {
  private queue;
  private flushTimer;
  private readonly config;
  private readonly subscribers;
  private readonly rateLimiter;
  private flushPromise;
  private isShuttingDown;
  private metrics;
  private observableCleanups;
  private subscriberHealthy;
  constructor(subscribers: EventSubscriber[], config?: Partial<QueueConfig>);
  /**
   * Initialize OTel metrics for queue observability
   */
  private initMetrics;
  /**
   * Record a dropped event with reason and emit debug breadcrumb
   */
  private recordDropped;
  /**
   * Record permanent delivery failure (after all retries exhausted)
   * Increments failed counter and logs error
   */
  private recordFailed;
  /**
   * Mark subscriber as unhealthy on transient failure (without incrementing failed counter)
   * Used during retry attempts - only recordFailed should increment the counter
   */
  private markSubscriberUnhealthy;
  /**
   * Record successful delivery
   */
  private recordDelivered;
  /**
   * Enqueue an event for sending
   *
   * Backpressure policy:
   * - Drops oldest event and logs warning if queue is full (same behavior in all environments)
   */
  enqueue(event: EventData): void;
  /**
   * Schedule a batch flush if not already scheduled
   */
  private scheduleBatchFlush;
  /**
   * Flush a batch of events
   * Uses promise-based concurrency control to prevent race conditions
   */
  private flushBatch;
  /**
   * Internal flush implementation
   */
  private doFlushBatch;
  /**
   * Send events with exponential backoff retry
   * Tracks per-event, per-subscriber failures so failed counter reflects actual failed deliveries.
   * On retry, only failed (event, subscriber) pairs are re-sent to avoid double-counting delivered.
   */
  private sendWithRetry;
  /**
   * Send events to configured subscribers with rate limiting and metrics.
   * When subscribersByEventIndex is provided (retry path), only those subscribers are tried per event.
   * Returns per-event, per-subscriber failures (empty if all succeeded).
   */
  private sendToSubscribers;
  /**
   * Send a single event to subscribers.
   * - When subscriberNames is undefined (initial attempt): send to all subscribers.
   * - When subscriberNames is provided (retry): send only to those subscribers (never re-send to healthy ones).
   * Returns list of subscribers that failed (empty if all succeeded).
   */
  private sendEventToSubscribers;
  /**
   * Flush all remaining events. Queue remains usable after flush (e.g. for
   * auto-flush at root span end). Use shutdown() when tearing down the queue.
   */
  flush(): Promise<void>;
  /**
   * Flush remaining events and permanently disable the queue (reject new events).
   * Use for process/SDK shutdown; use flush() for periodic or span-end drain.
   */
  shutdown(): Promise<void>;
  /**
   * Cleanup observable metric callbacks to prevent memory leaks
   * Call this when destroying the EventQueue instance
   */
  cleanup(): void;
  /**
   * Get queue size (for testing/debugging)
   */
  size(): number;
  /**
   * Get subscriber health status (for testing/debugging)
   */
  getSubscriberHealth(): Map<string, boolean>;
  /**
   * Check if a specific subscriber is healthy
   */
  isSubscriberHealthy(subscriberName: string): boolean;
  /**
   * Manually mark a subscriber as healthy or unhealthy
   * (used for circuit breaker integration)
   */
  setSubscriberHealth(subscriberName: string, healthy: boolean): void;
}
//#endregion
//#region src/track.d.ts
/**
 * Track a business events event
 *
 * Features:
 * - Auto-attaches traceId and spanId if in active span
 * - Batched sending with retry
 * - Type-safe with optional generic
 * - No-op if init() not called or no subscribers configured
 *
 * @example Basic usage
 * ```typescript
 * track('user.signup', { userId: '123', plan: 'pro' })
 * ```
 *
 * @example With type safety
 * ```typescript
 * interface EventDatas {
 *   'user.signup': { userId: string; plan: string }
 *   'plan.upgraded': { userId: string; revenue: number }
 * }
 *
 * track<EventDatas>('user.signup', { userId: '123', plan: 'pro' })
 * ```
 *
 * @example Trace correlation (automatic)
 * ```typescript
 * @Instrumented()
 * class UserService {
 *   async createUser(data: CreateUserData) {
 *     // This track call automatically includes traceId + spanId
 *     track('user.signup', { userId: data.id })
 *   }
 * }
 * ```
 */
declare function track<Events extends Record<string, any> = Record<string, any>>(event: keyof Events & string, data?: Events[typeof event], options?: EventTrackingOptions): void;
/**
 * Get events queue (for flush/shutdown)
 * @internal
 */
declare function getEventQueue(): EventQueue | null;
//#endregion
//#region src/shutdown.d.ts
/**
 * Graceful shutdown with flush and cleanup
 */
/**
 * Flush all pending telemetry
 *
 * Flushes both events events and OpenTelemetry spans to their destinations.
 * Includes timeout protection to prevent hanging in serverless environments.
 *
 * Safe to call multiple times.
 *
 * @param options - Optional configuration
 * @param options.timeout - Timeout in milliseconds (default: 2000ms)
 * @param options.forShutdown - If true, permanently disables the events queue after flush (used internally by shutdown())
 *
 * @example Manual flush in serverless
 * ```typescript
 * import { flush } from 'autotel';
 *
 * export const handler = async (event) => {
 *   // ... process event
 *   await flush(); // Flush before function returns
 *   return result;
 * };
 * ```
 *
 * @example With custom timeout
 * ```typescript
 * await flush({ timeout: 5000 }); // 5 second timeout
 * ```
 */
declare function flush(options?: {
  timeout?: number;
  forShutdown?: boolean;
}): Promise<void>;
/**
 * Shutdown telemetry and cleanup resources
 *
 * - Flushes all pending data
 * - Shuts down OpenTelemetry SDK
 * - Cleans up resources
 *
 * Call this before process exit.
 *
 * Always performs cleanup even if flush fails, preventing resource leaks
 * in serverless handlers or tests.
 *
 * @example Express server
 * ```typescript
 * const server = app.listen(3000)
 *
 * process.on('SIGTERM', async () => {
 *   await server.close()
 *   await shutdown()
 *   process.exit(0)
 * })
 * ```
 */
declare function shutdown(): Promise<void>;
//#endregion
//#region src/request-logger.d.ts
declare function runWithRequestContext<T>(ctx: TraceContext$1, fn: () => T): T;
interface RequestLogger {
  set(fields: Record<string, unknown>): void;
  info(message: string, fields?: Record<string, unknown>): void;
  warn(message: string, fields?: Record<string, unknown>): void;
  error(error: Error | string, fields?: Record<string, unknown>): void;
  getContext(): Record<string, unknown>;
  emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot;
  fork(label: string, fn: () => void | Promise<void>, options?: ForkOptions): void;
}
interface RequestLogSnapshot {
  timestamp: string;
  traceId: string;
  spanId: string;
  correlationId: string;
  context: Record<string, unknown>;
}
interface RequestLoggerOptions {
  /** Callback invoked by emitNow() for manual fan-out. */
  onEmit?: (snapshot: RequestLogSnapshot) => void | Promise<void>;
}
/**
 * Optional lifecycle hooks for adapters that need to track child loggers
 * spawned by `log.fork()` (e.g. active logger maps in framework integrations).
 */
interface ForkLifecycle {
  /** Called after the child logger is created, before `fn` runs. */
  onChildEnter?: (child: RequestLogger) => void;
  /** Called after the child has finished (emit + drain), success or failure. */
  onChildExit?: (child: RequestLogger) => void;
}
interface ForkOptions {
  lifecycle?: ForkLifecycle;
}
declare function getRequestLogger(ctx?: TraceContext$1, options?: RequestLoggerOptions): RequestLogger;
/**
 * Returns `true` when a request-logger context can be resolved without throwing —
 * i.e. an explicit `ctx` was provided, a `runWithRequestContext()` scope is active,
 * or there is an active OpenTelemetry span.
 *
 * Use this to branch on observability availability instead of wrapping
 * {@link getRequestLogger} in try/catch.
 */
declare function hasRequestContext(ctx?: TraceContext$1): boolean;
/**
 * Like {@link getRequestLogger}, but returns `null` instead of throwing when no
 * request context is available. Intended for best-effort instrumentation where a
 * missing telemetry context must never crash business logic.
 */
declare function getRequestLoggerSafe(ctx?: TraceContext$1, options?: RequestLoggerOptions): RequestLogger | null;
/**
 * A no-op {@link RequestLogger} whose methods do nothing. Used as a fallback by
 * best-effort instrumentation so wrapped handlers can run un-instrumented without
 * branching on logger presence.
 */
declare function createNoopRequestLogger(): RequestLogger;
//#endregion
//#region src/structured-error.d.ts
interface StructuredErrorInput {
  message: string;
  why?: string;
  fix?: string;
  link?: string;
  code?: string | number;
  status?: number;
  cause?: unknown;
  details?: Record<string, unknown>;
  name?: string;
  /** Backend-only context. Omitted from toJSON() and never serialized to clients. */
  internal?: Record<string, unknown>;
}
interface StructuredError extends Error {
  why?: string;
  fix?: string;
  link?: string;
  code?: string | number;
  status?: number;
  details?: Record<string, unknown>;
  /** Backend-only context. Omitted from toJSON() and never serialized to clients. */
  readonly internal?: Record<string, unknown>;
}
declare function createStructuredError(input: StructuredErrorInput): StructuredError;
declare function structuredErrorToJSON(error: StructuredError): Record<string, unknown>;
declare function getStructuredErrorAttributes(error: Error): Record<string, AttributeValue$2>;
declare function recordStructuredError(ctx: Pick<TraceContext$1, 'setAttributes' | 'setStatus'>, error: Error): void;
//#endregion
//#region src/error-catalog.d.ts
/** Definition of a single error in a catalog. */
interface ErrorCatalogEntry {
  /**
   * Human-readable message. Use a function to interpolate typed parameters;
   * the parameter type flows through to the call site.
   */
  message: string | ((params: never) => string);
  /** HTTP status to surface to clients. */
  status?: number;
  /** Stable error code. Defaults to `${namespace}.${KEY}`. */
  code?: string | number;
  /** Why it happened. A function receives the same params as `message`. */
  why?: string | ((params: never) => string);
  /** What the caller should do next. */
  fix?: string;
  /** Docs or runbook link. */
  link?: string;
  /** Error name. Defaults to the catalog key. */
  name?: string;
}
/** Per-call options passed alongside (or instead of) typed params. */
interface ErrorBuildOptions {
  cause?: unknown;
  details?: Record<string, unknown>;
  /** Backend-only context. Never serialized to clients. */
  internal?: Record<string, unknown>;
}
type ParamsOf<E> = E extends {
  message: (params: infer P) => string;
} ? P : E extends {
  why: (params: infer P) => string;
} ? P : void;
type BuilderArgs<E extends ErrorCatalogEntry> = ParamsOf<E> extends void ? [options?: ErrorBuildOptions] : [params: ParamsOf<E>, options?: ErrorBuildOptions];
/** A callable error factory produced by {@link defineErrorCatalog}. */
interface ErrorBuilder<E extends ErrorCatalogEntry> {
  (...args: BuilderArgs<E>): StructuredError;
  /** Stable code assigned to every error from this entry. */
  readonly code: string | number;
  /** True when `error` was produced by this catalog entry. */
  match(error: unknown): boolean;
}
type ErrorCatalog<T extends Record<string, ErrorCatalogEntry>> = { readonly [K in keyof T]: ErrorBuilder<T[K]> };
/** True when `error` was produced by any autotel error catalog. */
declare function isCatalogError(error: unknown): error is StructuredError;
/** Returns the catalog code of `error`, or `undefined` if it has none. */
declare function getCatalogCode(error: unknown): string | number | undefined;
/**
 * Define a typed error catalog. Returns an object whose keys are error
 * builders. Each builder produces a {@link StructuredError} carrying the
 * entry's message, status, code, why, fix, and link.
 */
declare function defineErrorCatalog<const T extends Record<string, ErrorCatalogEntry>>(namespace: string, entries: T): ErrorCatalog<T>;
/** Severity of an audit action. */
type AuditSeverity = 'info' | 'warn' | 'critical';
/** Definition of a single action in an audit catalog. */
interface AuditCatalogEntry {
  /** Human-readable description. Use a function for typed params. */
  message?: string | ((params: never) => string);
  /** Stable action name. Defaults to `${namespace}.${KEY}`. */
  action?: string;
  /** Severity of the action. Defaults to `'info'`. */
  severity?: AuditSeverity;
}
/** A resolved audit action descriptor produced by an audit catalog. */
interface AuditAction {
  readonly action: string;
  readonly severity: AuditSeverity;
  readonly message?: string;
}
type AuditDescriptorArgs<E extends AuditCatalogEntry> = ParamsOf<E> extends void ? [] : [params: ParamsOf<E>];
/** A callable audit-action descriptor produced by {@link defineAuditCatalog}. */
interface AuditDescriptor<E extends AuditCatalogEntry> {
  (...args: AuditDescriptorArgs<E>): AuditAction;
  readonly action: string;
  readonly severity: AuditSeverity;
}
type AuditCatalog<T extends Record<string, AuditCatalogEntry>> = { readonly [K in keyof T]: AuditDescriptor<T[K]> };
/**
 * Define a typed audit catalog. Returns typed action descriptors you can pass
 * to `track()` or audit helpers without scattering magic strings.
 */
declare function defineAuditCatalog<const T extends Record<string, AuditCatalogEntry>>(namespace: string, entries: T): AuditCatalog<T>;
//#endregion
//#region src/flatten-attributes.d.ts
/**
 * Convert an unknown value to an OTel-compatible AttributeValue.
 * Returns undefined when the value cannot be represented.
 */
declare function toAttributeValue(value: unknown): AttributeValue$2 | undefined;
/**
 * Recursively flatten a nested object into dot-notation OTel attributes.
 * Includes circular reference protection via WeakSet.
 */
declare function flattenToAttributes(fields: Record<string, unknown>, prefix?: string): Record<string, AttributeValue$2>;
//#endregion
//#region src/drain-toolkit.d.ts
interface DrainOptions<TContext, TConfig, TPayload = TContext> {
  /** Stable identifier used in error logs. */
  name: string;
  /** Return null to skip draining (e.g. missing API key in dev). */
  resolve: () => TConfig | null | Promise<TConfig | null>;
  /** Transform contexts into payloads. Defaults to identity. */
  transform?: (contexts: TContext[]) => TPayload[];
  /** Transport implementation. */
  send: (payloads: TPayload[], config: TConfig) => Promise<void>;
}
interface HttpDrainRequest {
  url: string;
  headers: Record<string, string>;
  body: string;
}
interface HttpDrainOptions<TContext, TConfig, TPayload = TContext> extends Omit<DrainOptions<TContext, TConfig, TPayload>, 'send'> {
  encode: (payloads: TPayload[], config: TConfig) => HttpDrainRequest | null;
  timeoutMs?: number;
  retries?: number;
  resolveTimeoutMs?: (config: TConfig) => number | undefined;
  resolveRetries?: (config: TConfig) => number | undefined;
}
declare function defineDrain<TContext, TConfig, TPayload = TContext>(options: DrainOptions<TContext, TConfig, TPayload>): (ctx: TContext | TContext[]) => Promise<void>;
declare function defineHttpDrain<TContext, TConfig, TPayload = TContext>(options: HttpDrainOptions<TContext, TConfig, TPayload>): (ctx: TContext | TContext[]) => Promise<void>;
//#endregion
//#region src/enricher-toolkit.d.ts
interface EnrichContext<TEvent extends Record<string, unknown>> {
  event: TEvent;
  request?: {
    method?: string;
    path?: string;
    requestId?: string;
  };
  response?: {
    status?: number;
  };
  headers?: Record<string, string>;
}
interface EnricherDefinition<TEvent extends Record<string, unknown>, TValue extends object> {
  /** Stable identifier used in error logs. */
  name: string;
  /** Top-level field to merge computed values into. */
  field: keyof TEvent & string;
  /** Return undefined to skip enrichment. */
  compute: (ctx: EnrichContext<TEvent>) => TValue | undefined;
}
interface EnricherOptions {
  /** Replace existing field value instead of merge. Default false. */
  overwrite?: boolean;
}
declare function defineEnricher<TEvent extends Record<string, unknown>, TValue extends object>(def: EnricherDefinition<TEvent, TValue>, options?: EnricherOptions): (ctx: EnrichContext<TEvent>) => void;
//#endregion
//#region src/pretty-log-formatter.d.ts
/**
 * Format milliseconds into a human-readable duration string.
 *
 * @example
 * formatDuration(45)     // "45ms"
 * formatDuration(1234)   // "1.2s"
 * formatDuration(65000)  // "1m 5s"
 */
declare function formatDuration(ms: number): string;
//#endregion
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 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, 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, markAsImmediate, 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 };
//# sourceMappingURL=index.d.cts.map