autotel 4.2.2 → 4.2.4

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 (87) hide show
  1. package/dist/{attributes-CmYpdqCN.js → attributes-B7wix2VG.js} +2 -2
  2. package/dist/{attributes-CmYpdqCN.js.map → attributes-B7wix2VG.js.map} +1 -1
  3. package/dist/{attributes-PZ5doLgw.cjs → attributes-aDmJYral.cjs} +2 -2
  4. package/dist/{attributes-PZ5doLgw.cjs.map → attributes-aDmJYral.cjs.map} +1 -1
  5. package/dist/attributes.cjs +1 -1
  6. package/dist/attributes.js +1 -1
  7. package/dist/auto.cjs +3 -3
  8. package/dist/auto.js +1 -1
  9. package/dist/{canonical-log-line-processor--RlFDHhm.cjs → canonical-log-line-processor-CcrDi6TO.cjs} +2 -2
  10. package/dist/{canonical-log-line-processor--RlFDHhm.cjs.map → canonical-log-line-processor-CcrDi6TO.cjs.map} +1 -1
  11. package/dist/{canonical-log-line-processor-DbBQT5vY.js → canonical-log-line-processor-FLezvFCB.js} +2 -2
  12. package/dist/{canonical-log-line-processor-DbBQT5vY.js.map → canonical-log-line-processor-FLezvFCB.js.map} +1 -1
  13. package/dist/correlation-id.cjs +1 -1
  14. package/dist/correlation-id.js +1 -1
  15. package/dist/decorators.cjs +1 -1
  16. package/dist/decorators.js +1 -1
  17. package/dist/diagnostics.cjs +1 -1
  18. package/dist/drain-pipeline.cjs +8 -2
  19. package/dist/drain-pipeline.cjs.map +1 -1
  20. package/dist/drain-pipeline.js +8 -2
  21. package/dist/drain-pipeline.js.map +1 -1
  22. package/dist/{event-531asIM6.js → event-BEm5IJ8U.js} +3 -3
  23. package/dist/{event-531asIM6.js.map → event-BEm5IJ8U.js.map} +1 -1
  24. package/dist/{event-CcZYwp50.cjs → event-rzA1X5h3.cjs} +4 -4
  25. package/dist/{event-CcZYwp50.cjs.map → event-rzA1X5h3.cjs.map} +1 -1
  26. package/dist/event.cjs +1 -1
  27. package/dist/event.js +1 -1
  28. package/dist/{functional-C8B0Qa7o.cjs → functional-BCtxvYir.cjs} +9 -9
  29. package/dist/{functional-C8B0Qa7o.cjs.map → functional-BCtxvYir.cjs.map} +1 -1
  30. package/dist/{functional-r-AUIRy_.js → functional-CrAq8Az8.js} +4 -4
  31. package/dist/{functional-r-AUIRy_.js.map → functional-CrAq8Az8.js.map} +1 -1
  32. package/dist/functional.cjs +1 -1
  33. package/dist/functional.js +1 -1
  34. package/dist/http.cjs +1 -1
  35. package/dist/http.js +1 -1
  36. package/dist/index.cjs +17 -14
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.js +12 -9
  39. package/dist/index.js.map +1 -1
  40. package/dist/{init-BS2JVkrL.js → init-BvBB45-T.js} +4 -4
  41. package/dist/{init-BS2JVkrL.js.map → init-BvBB45-T.js.map} +1 -1
  42. package/dist/{init-BXiuPK6j.cjs → init-BxJEJ9Tn.cjs} +5 -5
  43. package/dist/{init-BXiuPK6j.cjs.map → init-BxJEJ9Tn.cjs.map} +1 -1
  44. package/dist/instrumentation.cjs +4 -4
  45. package/dist/instrumentation.cjs.map +1 -1
  46. package/dist/instrumentation.js +3 -3
  47. package/dist/instrumentation.js.map +1 -1
  48. package/dist/logger-thMPLpOG.cjs +487 -0
  49. package/dist/logger-thMPLpOG.cjs.map +1 -0
  50. package/dist/logger.cjs +8 -236
  51. package/dist/messaging.cjs +1 -1
  52. package/dist/messaging.js +1 -1
  53. package/dist/{node-require-CZ_PU448.cjs → node-require-PFqDihze.cjs} +3 -3
  54. package/dist/{node-require-CZ_PU448.cjs.map → node-require-PFqDihze.cjs.map} +1 -1
  55. package/dist/{operation-context-D6LDf4W_.cjs → operation-context-hzKbTKnt.cjs} +3 -3
  56. package/dist/{operation-context-D6LDf4W_.cjs.map → operation-context-hzKbTKnt.cjs.map} +1 -1
  57. package/dist/processors.cjs +1 -1
  58. package/dist/processors.js +1 -1
  59. package/dist/register.cjs +2 -2
  60. package/dist/semantic-helpers.cjs +1 -1
  61. package/dist/semantic-helpers.js +1 -1
  62. package/dist/{stable-hash-brKISGf1.cjs → stable-hash-CS9BxvVQ.cjs} +3 -3
  63. package/dist/{stable-hash-brKISGf1.cjs.map → stable-hash-CS9BxvVQ.cjs.map} +1 -1
  64. package/dist/test-span-collector.cjs.map +1 -1
  65. package/dist/test-span-collector.d.cts.map +1 -1
  66. package/dist/test-span-collector.d.ts.map +1 -1
  67. package/dist/test-span-collector.js.map +1 -1
  68. package/dist/testing.cjs +4 -2
  69. package/dist/testing.cjs.map +1 -1
  70. package/dist/testing.js +4 -2
  71. package/dist/testing.js.map +1 -1
  72. package/dist/trace-helpers.cjs +1 -1
  73. package/dist/{track-COUuU48p.js → track-D7O7oIZa.js} +9 -5
  74. package/dist/{track-COUuU48p.js.map → track-D7O7oIZa.js.map} +1 -1
  75. package/dist/{track-Cb3Q4QmS.cjs → track-eovhCJ-I.cjs} +11 -7
  76. package/dist/{track-Cb3Q4QmS.cjs.map → track-eovhCJ-I.cjs.map} +1 -1
  77. package/dist/validate.cjs +1 -1
  78. package/dist/webhook.cjs +1 -1
  79. package/dist/webhook.js +1 -1
  80. package/dist/workflow-distributed.cjs +1 -1
  81. package/dist/workflow-distributed.js +1 -1
  82. package/dist/workflow.cjs +3 -3
  83. package/dist/workflow.js +1 -1
  84. package/dist/yaml-config.cjs +4 -4
  85. package/package.json +40 -40
  86. package/dist/logger.cjs.map +0 -1
  87. /package/dist/{chunk-C_NdSu1c.cjs → rolldown-runtime-C_NdSu1c.cjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"canonical-log-line-processor--RlFDHhm.cjs","names":["logs","SeverityNumber"],"sources":["../src/pretty-log-formatter.ts","../src/processors/canonical-log-line-processor.ts"],"sourcesContent":["import type { CanonicalLogLineEvent } from './processors/canonical-log-line-processor';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst YELLOW = '\\x1b[33m';\nconst GREEN = '\\x1b[32m';\nconst CYAN = '\\x1b[36m';\nconst GRAY = '\\x1b[90m';\n\nconst LEVEL_COLORS: Record<string, string> = {\n debug: GRAY,\n info: GREEN,\n warn: YELLOW,\n error: RED,\n};\n\n/** Internal OTel attributes to skip in pretty output. */\nconst SKIP_PREFIXES = [\n 'telemetry.',\n 'otel.',\n 'process.',\n 'os.',\n 'host.',\n 'service.',\n 'autotel.',\n];\n\nconst SKIP_KEYS = new Set([\n 'operation',\n 'traceId',\n 'spanId',\n 'correlationId',\n 'duration_ms',\n 'duration',\n 'status_code',\n 'status_message',\n 'timestamp',\n 'http.request.method',\n 'url.path',\n 'http.route',\n 'http.response.status_code',\n]);\n\nfunction useColor(): boolean {\n if (typeof process !== 'undefined') {\n if (process.env.NO_COLOR) return false;\n if (process.env.FORCE_COLOR) return true;\n if (process.stdout?.isTTY) return true;\n }\n return false;\n}\n\nfunction c(color: string, text: string): string {\n return useColor() ? `${color}${text}${RESET}` : text;\n}\n\n/**\n * Format milliseconds into a human-readable duration string.\n *\n * @example\n * formatDuration(45) // \"45ms\"\n * formatDuration(1234) // \"1.2s\"\n * formatDuration(65000) // \"1m 5s\"\n */\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) {\n const seconds = ms / 1000;\n return seconds < 10 ? `${seconds.toFixed(1)}s` : `${Math.round(seconds)}s`;\n }\n const minutes = Math.floor(ms / 60_000);\n const seconds = Math.round((ms % 60_000) / 1000);\n return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;\n}\n\nfunction formatTime(iso: string): string {\n try {\n const d = new Date(iso);\n return d.toLocaleTimeString('en-GB', { hour12: false });\n } catch {\n return iso.slice(11, 19);\n }\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean')\n return String(value);\n if (value == null) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Group flat dot-notation attributes into a nested tree for pretty display.\n * e.g. { 'user.id': '1', 'user.plan': 'pro' } → { user: { id: '1', plan: 'pro' } }\n */\nfunction groupAttributes(\n event: Record<string, unknown>,\n): Record<string, unknown> {\n const tree: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(event)) {\n if (SKIP_KEYS.has(key)) continue;\n if (SKIP_PREFIXES.some((p) => key.startsWith(p))) continue;\n if (value == null || value === '') continue;\n\n const parts = key.split('.');\n if (parts.length === 1) {\n tree[key] = value;\n } else {\n let current = tree;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (!(part in current) || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return tree;\n}\n\nfunction renderTree(\n obj: Record<string, unknown>,\n indent: string,\n isLast: boolean[],\n): string[] {\n const lines: string[] = [];\n const entries = Object.entries(obj);\n\n entries.forEach(([key, value], idx) => {\n const last = idx === entries.length - 1;\n const connector = last ? '\\u2514\\u2500' : '\\u251c\\u2500';\n const prefix = indent + connector + ' ';\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const nested = value as Record<string, unknown>;\n const flatValues = Object.entries(nested).filter(\n ([, v]) => typeof v !== 'object' || v === null,\n );\n const nestedObjs = Object.entries(nested).filter(\n ([, v]) => typeof v === 'object' && v !== null && !Array.isArray(v),\n );\n\n if (nestedObjs.length === 0) {\n const inline = flatValues\n .map(([k, v]) => `${c(CYAN, k)}=${formatValue(v)}`)\n .join(' ');\n lines.push(`${prefix}${c(BOLD, key)}: ${inline}`);\n } else {\n lines.push(`${prefix}${c(BOLD, key)}:`);\n const nextIndent = indent + (last ? ' ' : '\\u2502 ');\n lines.push(...renderTree(nested, nextIndent, [...isLast, last]));\n }\n } else {\n lines.push(`${prefix}${c(CYAN, key)}: ${c(DIM, formatValue(value))}`);\n }\n });\n\n return lines;\n}\n\n/**\n * Format a canonical log line event as a pretty tree for development output.\n */\nexport function formatPrettyLogLine(ctx: CanonicalLogLineEvent): string {\n const { event, level, message } = ctx;\n\n const timestamp = formatTime(String(event.timestamp ?? ''));\n const service = event['service.name'] || event.service || '';\n const method = event['http.request.method'] || '';\n const path = event['http.route'] || event['url.path'] || '';\n const status = event['http.response.status_code'] || event.status_code || '';\n const durationMs = Number(event.duration_ms ?? 0);\n const duration = formatDuration(durationMs);\n\n const levelColor = LEVEL_COLORS[level] ?? '';\n const levelStr = c(levelColor, level.toUpperCase().padEnd(5));\n\n const parts = [c(DIM, timestamp), levelStr];\n if (service) parts.push(c(DIM, `[${service}]`));\n if (method) parts.push(c(BOLD, String(method)));\n if (path) parts.push(String(path));\n if (status) {\n const statusNum = Number(status);\n const statusColor =\n statusNum >= 500 ? RED : statusNum >= 400 ? YELLOW : GREEN;\n parts.push(c(statusColor, String(status)));\n }\n parts.push(c(DIM, `in ${duration}`));\n\n const header = parts.join(' ');\n\n const tree = groupAttributes(event);\n if (Object.keys(tree).length === 0) {\n return header;\n }\n\n const treeLines = renderTree(tree, ' ', []);\n return [header, ...treeLines].join('\\n');\n}\n","/**\n * Canonical Log Line Processor\n *\n * Automatically emits spans as canonical log lines (wide events) when they end.\n * Implements canonical log line\" pattern: one comprehensive\n * event per request with all context.\n *\n * When a span ends, this processor creates a log record with ALL span attributes,\n * making the span itself the canonical log line that can be queried like structured data.\n *\n * @example\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n */\n\nimport type {\n SpanProcessor,\n ReadableSpan,\n} from '@opentelemetry/sdk-trace-base';\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Logger } from '../logger';\nimport { formatPrettyLogLine, formatDuration } from '../pretty-log-formatter';\n\n/**\n * Function to redact sensitive attribute values\n */\nexport type AttributeRedactorFn = (\n key: string,\n value: AttributeValue,\n) => AttributeValue;\n\nexport interface CanonicalLogLineEvent {\n span: ReadableSpan;\n level: 'debug' | 'info' | 'warn' | 'error';\n message: string;\n event: Record<string, unknown>;\n}\n\nexport interface KeepCondition {\n /** Keep events where HTTP status >= this value. */\n status?: number;\n /** Keep events where duration_ms >= this value. */\n durationMs?: number;\n /** Keep events matching this path pattern (simple prefix match). */\n path?: string;\n}\n\nexport interface CanonicalLogLineOptions {\n /** Logger to use for emitting canonical log lines (defaults to OTel Logs API) */\n logger?: Logger;\n /** Only emit canonical log lines for root spans (default: false) */\n rootSpansOnly?: boolean;\n /** Minimum log level for canonical log lines (default: 'info') */\n minLevel?: 'debug' | 'info' | 'warn' | 'error';\n /** Custom message format (default: uses span name) */\n messageFormat?: (span: ReadableSpan) => string;\n /** Whether to include resource attributes (default: true) */\n includeResourceAttributes?: boolean;\n /**\n * Attribute redactor function to apply before logging.\n * This ensures sensitive data is redacted in canonical log lines,\n * matching the behavior of attributeRedactor in init().\n */\n attributeRedactor?: AttributeRedactorFn;\n /** Predicate to decide whether to emit (runs after event is built). */\n shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n /**\n * Declarative tail sampling conditions (OR logic). If any condition matches,\n * the event is kept. Ignored when `shouldEmit` is provided.\n *\n * @example\n * keep: [{ status: 500 }, { durationMs: 1000 }]\n */\n keep?: KeepCondition[];\n /** Callback invoked after emit for custom fan-out. */\n drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n /** Handler for drain failures. */\n onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n /**\n * Pretty-print canonical log lines to console in a tree format.\n * Defaults to true when NODE_ENV is 'development'.\n */\n pretty?: boolean;\n}\n\n/**\n * Span processor that automatically emits spans as canonical log lines\n *\n * When a span ends, this processor creates a log record with ALL span attributes.\n * This implements the \"canonical log line\" pattern: one comprehensive event\n * per request with all context, queryable as structured data.\n *\n * **Key Benefits:**\n * - One log line per request with all context (wide event)\n * - High-cardinality, high-dimensionality data for powerful queries\n * - Automatic - no manual logging needed\n * - Works with any logger or OTel Logs API\n *\n * @example Basic usage\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'checkout-api',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n *\n * @example With custom logger\n * ```typescript\n * import pino from 'pino';\n * import { init } from 'autotel';\n *\n * const logger = pino();\n * init({\n * service: 'my-app',\n * logger,\n * canonicalLogLines: {\n * enabled: true,\n * logger, // Use Pino for canonical log lines\n * rootSpansOnly: true,\n * },\n * });\n * ```\n *\n * @example Custom message format\n * ```typescript\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * messageFormat: (span) => {\n * const status = span.status.code === 2 ? 'ERROR' : 'SUCCESS';\n * return `${span.name} [${status}]`;\n * },\n * },\n * });\n * ```\n */\nexport class CanonicalLogLineProcessor implements SpanProcessor {\n private logger?: Logger;\n private rootSpansOnly: boolean;\n private minLevel: 'debug' | 'info' | 'warn' | 'error';\n private messageFormat: (span: ReadableSpan) => string;\n private includeResourceAttributes: boolean;\n private attributeRedactor?: AttributeRedactorFn;\n private shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n private drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n private onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n private pretty: boolean;\n private getOTelLogger: (() => ReturnType<typeof logs.getLogger>) | null =\n null;\n\n constructor(options: CanonicalLogLineOptions = {}) {\n this.logger = options.logger;\n this.rootSpansOnly = options.rootSpansOnly ?? false;\n this.minLevel = options.minLevel ?? 'info';\n this.messageFormat =\n options.messageFormat ?? ((span) => `[${span.name}] Request completed`);\n this.includeResourceAttributes = options.includeResourceAttributes ?? true;\n this.attributeRedactor = options.attributeRedactor;\n this.shouldEmit =\n options.shouldEmit ?? this.buildKeepPredicate(options.keep);\n this.drain = options.drain;\n this.onDrainError = options.onDrainError;\n this.pretty =\n options.pretty ??\n (typeof process !== 'undefined' &&\n process.env.NODE_ENV === 'development');\n\n if (!this.logger) {\n this.getOTelLogger = () => logs.getLogger('autotel.canonical-log-line');\n }\n }\n\n private buildKeepPredicate(\n keep?: KeepCondition[],\n ): ((ctx: CanonicalLogLineEvent) => boolean) | undefined {\n if (!keep || keep.length === 0) return undefined;\n\n return (ctx: CanonicalLogLineEvent) => {\n return keep.some((condition) => {\n if (condition.status !== undefined) {\n const httpStatus = Number(\n ctx.event['http.response.status_code'] ?? 0,\n );\n if (httpStatus >= condition.status) return true;\n }\n if (\n condition.durationMs !== undefined &&\n Number(ctx.event.duration_ms ?? 0) >= condition.durationMs\n ) {\n return true;\n }\n if (condition.path !== undefined) {\n const route = String(\n ctx.event['http.route'] ?? ctx.event['url.path'] ?? '',\n );\n if (route.startsWith(condition.path)) return true;\n }\n return false;\n });\n };\n }\n\n onStart(): void {\n // No-op\n }\n\n onEnd(span: ReadableSpan): void {\n if (\n this.rootSpansOnly &&\n span.parentSpanContext?.spanId &&\n !span.parentSpanContext.isRemote\n ) {\n return;\n }\n\n const level = this.getLogLevel(span);\n if (!this.shouldLog(level)) {\n return;\n }\n\n const canonicalLogLine = this.buildCanonicalLogLine(span);\n const message = this.messageFormat(span);\n const eventContext: CanonicalLogLineEvent = {\n span,\n level,\n message,\n event: canonicalLogLine,\n };\n\n if (this.shouldEmit && !this.shouldEmit(eventContext)) return;\n\n if (this.pretty) {\n console.log(formatPrettyLogLine(eventContext));\n }\n\n if (this.logger) {\n this.emitViaLogger(level, message, canonicalLogLine);\n } else if (this.getOTelLogger) {\n const otelLogger = this.getOTelLogger();\n this.emitViaOTel(level, message, canonicalLogLine, otelLogger);\n }\n\n if (this.drain) {\n Promise.resolve(this.drain(eventContext)).catch((error) => {\n if (this.onDrainError) {\n this.onDrainError(error, eventContext);\n return;\n }\n this.reportInternalWarning('canonicalLogLines.drain failed', error);\n });\n }\n }\n\n private buildCanonicalLogLine(span: ReadableSpan): Record<string, unknown> {\n const durationMs = span.duration[0] * 1000 + span.duration[1] / 1_000_000;\n const timestamp = new Date(\n span.startTime[0] * 1000 + span.startTime[1] / 1_000_000,\n ).toISOString();\n\n // Span attributes first so core metadata fields below take precedence\n const canonicalLogLine: Record<string, unknown> = {};\n const attributes = this.redactAttributes(span.attributes);\n Object.assign(canonicalLogLine, attributes);\n\n if (this.includeResourceAttributes) {\n const resourceAttrs = this.redactAttributes(\n span.resource.attributes as Attributes,\n );\n Object.assign(canonicalLogLine, resourceAttrs);\n }\n\n canonicalLogLine.operation = span.name;\n canonicalLogLine.traceId = span.spanContext().traceId;\n canonicalLogLine.spanId = span.spanContext().spanId;\n canonicalLogLine.correlationId = span.spanContext().traceId.slice(0, 16);\n canonicalLogLine.duration_ms = Math.round(durationMs * 100) / 100;\n canonicalLogLine.duration = formatDuration(durationMs);\n canonicalLogLine.status_code = span.status.code;\n canonicalLogLine.status_message = span.status.message || undefined;\n canonicalLogLine.timestamp = timestamp;\n\n return canonicalLogLine;\n }\n\n private redactAttributes(attributes: Attributes): Record<string, unknown> {\n if (!this.attributeRedactor) {\n return { ...attributes };\n }\n\n const redacted: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n redacted[key] = this.attributeRedactor(key, value);\n }\n }\n return redacted;\n }\n\n private emitViaLogger(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n ): void {\n this.logger![level](canonicalLogLine, message);\n }\n\n private emitViaOTel(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n otelLogger: ReturnType<typeof logs.getLogger>,\n ): void {\n const otelAttributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(canonicalLogLine)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n otelAttributes[key] = value;\n } else if (value !== null && value !== undefined) {\n otelAttributes[key] = String(value);\n }\n }\n otelLogger.emit({\n severityNumber: this.getSeverityNumber(level),\n severityText: level.toUpperCase(),\n body: message,\n attributes: otelAttributes,\n });\n }\n\n private getLogLevel(span: ReadableSpan): 'debug' | 'info' | 'warn' | 'error' {\n const explicitLevel = span.attributes['autotel.log.level'];\n if (\n explicitLevel === 'debug' ||\n explicitLevel === 'info' ||\n explicitLevel === 'warn' ||\n explicitLevel === 'error'\n ) {\n return explicitLevel;\n }\n\n if (span.status.code === 2) return 'error';\n return 'info';\n }\n\n private shouldLog(level: string): boolean {\n const levels = ['debug', 'info', 'warn', 'error'];\n return levels.indexOf(level) >= levels.indexOf(this.minLevel);\n }\n\n private getSeverityNumber(level: string): SeverityNumber {\n const mapping: Record<string, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n };\n return mapping[level] ?? SeverityNumber.INFO;\n }\n\n private reportInternalWarning(message: string, error: unknown): void {\n const err =\n error instanceof Error ? error.message : String(error ?? 'unknown error');\n if (this.logger) {\n this.logger.warn({ error: err }, `[autotel] ${message}`);\n return;\n }\n console.warn(`[autotel] ${message}: ${err}`);\n }\n\n async forceFlush(): Promise<void> {\n // No-op\n }\n\n async shutdown(): Promise<void> {\n // No-op\n }\n}\n"],"mappings":";;;AAEA,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,MAAM;AACZ,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,OAAO;AAGb,MAAM,eAAuC;CAC3C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;AACT;;AAGA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,YAAY,IAAI,IAAI;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,WAAoB;CAC3B,IAAI,OAAO,YAAY,aAAa;EAClC,IAAI,QAAQ,IAAI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gBAAgB,KAAK,WAAW;EACtC,IACE,kBAAkB,WAClB,kBAAkB,UAClB,kBAAkB,UAClB,kBAAkB,SAElB,OAAO;EAGT,IAAI,KAAK,OAAO,SAAS,GAAG,OAAO;EACnC,OAAO;CACT;CAEA,AAAQ,UAAU,OAAwB;EACxC,MAAM,SAAS;GAAC;GAAS;GAAQ;GAAQ;EAAO;EAChD,OAAO,OAAO,QAAQ,KAAK,KAAK,OAAO,QAAQ,KAAK,QAAQ;CAC9D;CAEA,AAAQ,kBAAkB,OAA+B;EAOvD,OAAO;GALL,OAAOC,uCAAe;GACtB,MAAMA,uCAAe;GACrB,MAAMA,uCAAe;GACrB,OAAOA,uCAAe;EAEX,EAAE,UAAUA,uCAAe;CAC1C;CAEA,AAAQ,sBAAsB,SAAiB,OAAsB;EACnE,MAAM,MACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,eAAe;EAC1E,IAAI,KAAK,QAAQ;GACf,KAAK,OAAO,KAAK,EAAE,OAAO,IAAI,GAAG,aAAa,SAAS;GACvD;EACF;EACA,QAAQ,KAAK,aAAa,QAAQ,IAAI,KAAK;CAC7C;CAEA,MAAM,aAA4B,CAElC;CAEA,MAAM,WAA0B,CAEhC;AACF"}
1
+ {"version":3,"file":"canonical-log-line-processor-CcrDi6TO.cjs","names":["logs","SeverityNumber"],"sources":["../src/pretty-log-formatter.ts","../src/processors/canonical-log-line-processor.ts"],"sourcesContent":["import type { CanonicalLogLineEvent } from './processors/canonical-log-line-processor';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst YELLOW = '\\x1b[33m';\nconst GREEN = '\\x1b[32m';\nconst CYAN = '\\x1b[36m';\nconst GRAY = '\\x1b[90m';\n\nconst LEVEL_COLORS: Record<string, string> = {\n debug: GRAY,\n info: GREEN,\n warn: YELLOW,\n error: RED,\n};\n\n/** Internal OTel attributes to skip in pretty output. */\nconst SKIP_PREFIXES = [\n 'telemetry.',\n 'otel.',\n 'process.',\n 'os.',\n 'host.',\n 'service.',\n 'autotel.',\n];\n\nconst SKIP_KEYS = new Set([\n 'operation',\n 'traceId',\n 'spanId',\n 'correlationId',\n 'duration_ms',\n 'duration',\n 'status_code',\n 'status_message',\n 'timestamp',\n 'http.request.method',\n 'url.path',\n 'http.route',\n 'http.response.status_code',\n]);\n\nfunction useColor(): boolean {\n if (typeof process !== 'undefined') {\n if (process.env.NO_COLOR) return false;\n if (process.env.FORCE_COLOR) return true;\n if (process.stdout?.isTTY) return true;\n }\n return false;\n}\n\nfunction c(color: string, text: string): string {\n return useColor() ? `${color}${text}${RESET}` : text;\n}\n\n/**\n * Format milliseconds into a human-readable duration string.\n *\n * @example\n * formatDuration(45) // \"45ms\"\n * formatDuration(1234) // \"1.2s\"\n * formatDuration(65000) // \"1m 5s\"\n */\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) {\n const seconds = ms / 1000;\n return seconds < 10 ? `${seconds.toFixed(1)}s` : `${Math.round(seconds)}s`;\n }\n const minutes = Math.floor(ms / 60_000);\n const seconds = Math.round((ms % 60_000) / 1000);\n return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;\n}\n\nfunction formatTime(iso: string): string {\n try {\n const d = new Date(iso);\n return d.toLocaleTimeString('en-GB', { hour12: false });\n } catch {\n return iso.slice(11, 19);\n }\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean')\n return String(value);\n if (value == null) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Group flat dot-notation attributes into a nested tree for pretty display.\n * e.g. { 'user.id': '1', 'user.plan': 'pro' } → { user: { id: '1', plan: 'pro' } }\n */\nfunction groupAttributes(\n event: Record<string, unknown>,\n): Record<string, unknown> {\n const tree: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(event)) {\n if (SKIP_KEYS.has(key)) continue;\n if (SKIP_PREFIXES.some((p) => key.startsWith(p))) continue;\n if (value == null || value === '') continue;\n\n const parts = key.split('.');\n if (parts.length === 1) {\n tree[key] = value;\n } else {\n let current = tree;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (!(part in current) || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return tree;\n}\n\nfunction renderTree(\n obj: Record<string, unknown>,\n indent: string,\n isLast: boolean[],\n): string[] {\n const lines: string[] = [];\n const entries = Object.entries(obj);\n\n entries.forEach(([key, value], idx) => {\n const last = idx === entries.length - 1;\n const connector = last ? '\\u2514\\u2500' : '\\u251c\\u2500';\n const prefix = indent + connector + ' ';\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const nested = value as Record<string, unknown>;\n const flatValues = Object.entries(nested).filter(\n ([, v]) => typeof v !== 'object' || v === null,\n );\n const nestedObjs = Object.entries(nested).filter(\n ([, v]) => typeof v === 'object' && v !== null && !Array.isArray(v),\n );\n\n if (nestedObjs.length === 0) {\n const inline = flatValues\n .map(([k, v]) => `${c(CYAN, k)}=${formatValue(v)}`)\n .join(' ');\n lines.push(`${prefix}${c(BOLD, key)}: ${inline}`);\n } else {\n lines.push(`${prefix}${c(BOLD, key)}:`);\n const nextIndent = indent + (last ? ' ' : '\\u2502 ');\n lines.push(...renderTree(nested, nextIndent, [...isLast, last]));\n }\n } else {\n lines.push(`${prefix}${c(CYAN, key)}: ${c(DIM, formatValue(value))}`);\n }\n });\n\n return lines;\n}\n\n/**\n * Format a canonical log line event as a pretty tree for development output.\n */\nexport function formatPrettyLogLine(ctx: CanonicalLogLineEvent): string {\n const { event, level, message } = ctx;\n\n const timestamp = formatTime(String(event.timestamp ?? ''));\n const service = event['service.name'] || event.service || '';\n const method = event['http.request.method'] || '';\n const path = event['http.route'] || event['url.path'] || '';\n const status = event['http.response.status_code'] || event.status_code || '';\n const durationMs = Number(event.duration_ms ?? 0);\n const duration = formatDuration(durationMs);\n\n const levelColor = LEVEL_COLORS[level] ?? '';\n const levelStr = c(levelColor, level.toUpperCase().padEnd(5));\n\n const parts = [c(DIM, timestamp), levelStr];\n if (service) parts.push(c(DIM, `[${service}]`));\n if (method) parts.push(c(BOLD, String(method)));\n if (path) parts.push(String(path));\n if (status) {\n const statusNum = Number(status);\n const statusColor =\n statusNum >= 500 ? RED : statusNum >= 400 ? YELLOW : GREEN;\n parts.push(c(statusColor, String(status)));\n }\n parts.push(c(DIM, `in ${duration}`));\n\n const header = parts.join(' ');\n\n const tree = groupAttributes(event);\n if (Object.keys(tree).length === 0) {\n return header;\n }\n\n const treeLines = renderTree(tree, ' ', []);\n return [header, ...treeLines].join('\\n');\n}\n","/**\n * Canonical Log Line Processor\n *\n * Automatically emits spans as canonical log lines (wide events) when they end.\n * Implements canonical log line\" pattern: one comprehensive\n * event per request with all context.\n *\n * When a span ends, this processor creates a log record with ALL span attributes,\n * making the span itself the canonical log line that can be queried like structured data.\n *\n * @example\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n */\n\nimport type {\n SpanProcessor,\n ReadableSpan,\n} from '@opentelemetry/sdk-trace-base';\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Logger } from '../logger';\nimport { formatPrettyLogLine, formatDuration } from '../pretty-log-formatter';\n\n/**\n * Function to redact sensitive attribute values\n */\nexport type AttributeRedactorFn = (\n key: string,\n value: AttributeValue,\n) => AttributeValue;\n\nexport interface CanonicalLogLineEvent {\n span: ReadableSpan;\n level: 'debug' | 'info' | 'warn' | 'error';\n message: string;\n event: Record<string, unknown>;\n}\n\nexport interface KeepCondition {\n /** Keep events where HTTP status >= this value. */\n status?: number;\n /** Keep events where duration_ms >= this value. */\n durationMs?: number;\n /** Keep events matching this path pattern (simple prefix match). */\n path?: string;\n}\n\nexport interface CanonicalLogLineOptions {\n /** Logger to use for emitting canonical log lines (defaults to OTel Logs API) */\n logger?: Logger;\n /** Only emit canonical log lines for root spans (default: false) */\n rootSpansOnly?: boolean;\n /** Minimum log level for canonical log lines (default: 'info') */\n minLevel?: 'debug' | 'info' | 'warn' | 'error';\n /** Custom message format (default: uses span name) */\n messageFormat?: (span: ReadableSpan) => string;\n /** Whether to include resource attributes (default: true) */\n includeResourceAttributes?: boolean;\n /**\n * Attribute redactor function to apply before logging.\n * This ensures sensitive data is redacted in canonical log lines,\n * matching the behavior of attributeRedactor in init().\n */\n attributeRedactor?: AttributeRedactorFn;\n /** Predicate to decide whether to emit (runs after event is built). */\n shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n /**\n * Declarative tail sampling conditions (OR logic). If any condition matches,\n * the event is kept. Ignored when `shouldEmit` is provided.\n *\n * @example\n * keep: [{ status: 500 }, { durationMs: 1000 }]\n */\n keep?: KeepCondition[];\n /** Callback invoked after emit for custom fan-out. */\n drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n /** Handler for drain failures. */\n onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n /**\n * Pretty-print canonical log lines to console in a tree format.\n * Defaults to true when NODE_ENV is 'development'.\n */\n pretty?: boolean;\n}\n\n/**\n * Span processor that automatically emits spans as canonical log lines\n *\n * When a span ends, this processor creates a log record with ALL span attributes.\n * This implements the \"canonical log line\" pattern: one comprehensive event\n * per request with all context, queryable as structured data.\n *\n * **Key Benefits:**\n * - One log line per request with all context (wide event)\n * - High-cardinality, high-dimensionality data for powerful queries\n * - Automatic - no manual logging needed\n * - Works with any logger or OTel Logs API\n *\n * @example Basic usage\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'checkout-api',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n *\n * @example With custom logger\n * ```typescript\n * import pino from 'pino';\n * import { init } from 'autotel';\n *\n * const logger = pino();\n * init({\n * service: 'my-app',\n * logger,\n * canonicalLogLines: {\n * enabled: true,\n * logger, // Use Pino for canonical log lines\n * rootSpansOnly: true,\n * },\n * });\n * ```\n *\n * @example Custom message format\n * ```typescript\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * messageFormat: (span) => {\n * const status = span.status.code === 2 ? 'ERROR' : 'SUCCESS';\n * return `${span.name} [${status}]`;\n * },\n * },\n * });\n * ```\n */\nexport class CanonicalLogLineProcessor implements SpanProcessor {\n private logger?: Logger;\n private rootSpansOnly: boolean;\n private minLevel: 'debug' | 'info' | 'warn' | 'error';\n private messageFormat: (span: ReadableSpan) => string;\n private includeResourceAttributes: boolean;\n private attributeRedactor?: AttributeRedactorFn;\n private shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n private drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n private onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n private pretty: boolean;\n private getOTelLogger: (() => ReturnType<typeof logs.getLogger>) | null =\n null;\n\n constructor(options: CanonicalLogLineOptions = {}) {\n this.logger = options.logger;\n this.rootSpansOnly = options.rootSpansOnly ?? false;\n this.minLevel = options.minLevel ?? 'info';\n this.messageFormat =\n options.messageFormat ?? ((span) => `[${span.name}] Request completed`);\n this.includeResourceAttributes = options.includeResourceAttributes ?? true;\n this.attributeRedactor = options.attributeRedactor;\n this.shouldEmit =\n options.shouldEmit ?? this.buildKeepPredicate(options.keep);\n this.drain = options.drain;\n this.onDrainError = options.onDrainError;\n this.pretty =\n options.pretty ??\n (typeof process !== 'undefined' &&\n process.env.NODE_ENV === 'development');\n\n if (!this.logger) {\n this.getOTelLogger = () => logs.getLogger('autotel.canonical-log-line');\n }\n }\n\n private buildKeepPredicate(\n keep?: KeepCondition[],\n ): ((ctx: CanonicalLogLineEvent) => boolean) | undefined {\n if (!keep || keep.length === 0) return undefined;\n\n return (ctx: CanonicalLogLineEvent) => {\n return keep.some((condition) => {\n if (condition.status !== undefined) {\n const httpStatus = Number(\n ctx.event['http.response.status_code'] ?? 0,\n );\n if (httpStatus >= condition.status) return true;\n }\n if (\n condition.durationMs !== undefined &&\n Number(ctx.event.duration_ms ?? 0) >= condition.durationMs\n ) {\n return true;\n }\n if (condition.path !== undefined) {\n const route = String(\n ctx.event['http.route'] ?? ctx.event['url.path'] ?? '',\n );\n if (route.startsWith(condition.path)) return true;\n }\n return false;\n });\n };\n }\n\n onStart(): void {\n // No-op\n }\n\n onEnd(span: ReadableSpan): void {\n if (\n this.rootSpansOnly &&\n span.parentSpanContext?.spanId &&\n !span.parentSpanContext.isRemote\n ) {\n return;\n }\n\n const level = this.getLogLevel(span);\n if (!this.shouldLog(level)) {\n return;\n }\n\n const canonicalLogLine = this.buildCanonicalLogLine(span);\n const message = this.messageFormat(span);\n const eventContext: CanonicalLogLineEvent = {\n span,\n level,\n message,\n event: canonicalLogLine,\n };\n\n if (this.shouldEmit && !this.shouldEmit(eventContext)) return;\n\n if (this.pretty) {\n console.log(formatPrettyLogLine(eventContext));\n }\n\n if (this.logger) {\n this.emitViaLogger(level, message, canonicalLogLine);\n } else if (this.getOTelLogger) {\n const otelLogger = this.getOTelLogger();\n this.emitViaOTel(level, message, canonicalLogLine, otelLogger);\n }\n\n if (this.drain) {\n Promise.resolve(this.drain(eventContext)).catch((error) => {\n if (this.onDrainError) {\n this.onDrainError(error, eventContext);\n return;\n }\n this.reportInternalWarning('canonicalLogLines.drain failed', error);\n });\n }\n }\n\n private buildCanonicalLogLine(span: ReadableSpan): Record<string, unknown> {\n const durationMs = span.duration[0] * 1000 + span.duration[1] / 1_000_000;\n const timestamp = new Date(\n span.startTime[0] * 1000 + span.startTime[1] / 1_000_000,\n ).toISOString();\n\n // Span attributes first so core metadata fields below take precedence\n const canonicalLogLine: Record<string, unknown> = {};\n const attributes = this.redactAttributes(span.attributes);\n Object.assign(canonicalLogLine, attributes);\n\n if (this.includeResourceAttributes) {\n const resourceAttrs = this.redactAttributes(\n span.resource.attributes as Attributes,\n );\n Object.assign(canonicalLogLine, resourceAttrs);\n }\n\n canonicalLogLine.operation = span.name;\n canonicalLogLine.traceId = span.spanContext().traceId;\n canonicalLogLine.spanId = span.spanContext().spanId;\n canonicalLogLine.correlationId = span.spanContext().traceId.slice(0, 16);\n canonicalLogLine.duration_ms = Math.round(durationMs * 100) / 100;\n canonicalLogLine.duration = formatDuration(durationMs);\n canonicalLogLine.status_code = span.status.code;\n canonicalLogLine.status_message = span.status.message || undefined;\n canonicalLogLine.timestamp = timestamp;\n\n return canonicalLogLine;\n }\n\n private redactAttributes(attributes: Attributes): Record<string, unknown> {\n if (!this.attributeRedactor) {\n return { ...attributes };\n }\n\n const redacted: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n redacted[key] = this.attributeRedactor(key, value);\n }\n }\n return redacted;\n }\n\n private emitViaLogger(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n ): void {\n this.logger![level](canonicalLogLine, message);\n }\n\n private emitViaOTel(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n otelLogger: ReturnType<typeof logs.getLogger>,\n ): void {\n const otelAttributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(canonicalLogLine)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n otelAttributes[key] = value;\n } else if (value !== null && value !== undefined) {\n otelAttributes[key] = String(value);\n }\n }\n otelLogger.emit({\n severityNumber: this.getSeverityNumber(level),\n severityText: level.toUpperCase(),\n body: message,\n attributes: otelAttributes,\n });\n }\n\n private getLogLevel(span: ReadableSpan): 'debug' | 'info' | 'warn' | 'error' {\n const explicitLevel = span.attributes['autotel.log.level'];\n if (\n explicitLevel === 'debug' ||\n explicitLevel === 'info' ||\n explicitLevel === 'warn' ||\n explicitLevel === 'error'\n ) {\n return explicitLevel;\n }\n\n if (span.status.code === 2) return 'error';\n return 'info';\n }\n\n private shouldLog(level: string): boolean {\n const levels = ['debug', 'info', 'warn', 'error'];\n return levels.indexOf(level) >= levels.indexOf(this.minLevel);\n }\n\n private getSeverityNumber(level: string): SeverityNumber {\n const mapping: Record<string, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n };\n return mapping[level] ?? SeverityNumber.INFO;\n }\n\n private reportInternalWarning(message: string, error: unknown): void {\n const err =\n error instanceof Error ? error.message : String(error ?? 'unknown error');\n if (this.logger) {\n this.logger.warn({ error: err }, `[autotel] ${message}`);\n return;\n }\n console.warn(`[autotel] ${message}: ${err}`);\n }\n\n async forceFlush(): Promise<void> {\n // No-op\n }\n\n async shutdown(): Promise<void> {\n // No-op\n }\n}\n"],"mappings":";;;AAEA,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,MAAM;AACZ,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,OAAO;AAGb,MAAM,eAAuC;CAC3C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;AACT;;AAGA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,4BAAY,IAAI,IAAI;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,WAAoB;CAC3B,IAAI,OAAO,YAAY,aAAa;EAClC,IAAI,QAAQ,IAAI,UAAU,OAAO;EACjC,IAAI,QAAQ,IAAI,aAAa,OAAO;EACpC,IAAI,QAAQ,QAAQ,OAAO,OAAO;CACpC;CACA,OAAO;AACT;AAEA,SAAS,EAAE,OAAe,MAAsB;CAC9C,OAAO,SAAS,IAAI,GAAG,QAAQ,OA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xC,MAAM,SAAS;GAAC;GAAS;GAAQ;GAAQ;EAAO;EAChD,OAAO,OAAO,QAAQ,KAAK,KAAK,OAAO,QAAQ,KAAK,QAAQ;CAC9D;CAEA,AAAQ,kBAAkB,OAA+B;EAOvD,OAAO;GALL,OAAOC,uCAAe;GACtB,MAAMA,uCAAe;GACrB,MAAMA,uCAAe;GACrB,OAAOA,uCAAe;EAEX,EAAE,UAAUA,uCAAe;CAC1C;CAEA,AAAQ,sBAAsB,SAAiB,OAAsB;EACnE,MAAM,MACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,eAAe;EAC1E,IAAI,KAAK,QAAQ;GACf,KAAK,OAAO,KAAK,EAAE,OAAO,IAAI,GAAG,aAAa,SAAS;GACvD;EACF;EACA,QAAQ,KAAK,aAAa,QAAQ,IAAI,KAAK;CAC7C;CAEA,MAAM,aAA4B,CAElC;CAEA,MAAM,WAA0B,CAEhC;AACF"}
@@ -24,7 +24,7 @@ const SKIP_PREFIXES = [
24
24
  "service.",
25
25
  "autotel."
26
26
  ];
27
- const SKIP_KEYS = new Set([
27
+ const SKIP_KEYS = /* @__PURE__ */ new Set([
28
28
  "operation",
29
29
  "traceId",
30
30
  "spanId",
@@ -363,4 +363,4 @@ var CanonicalLogLineProcessor = class {
363
363
 
364
364
  //#endregion
365
365
  export { formatDuration as n, CanonicalLogLineProcessor as t };
366
- //# sourceMappingURL=canonical-log-line-processor-DbBQT5vY.js.map
366
+ //# sourceMappingURL=canonical-log-line-processor-FLezvFCB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"canonical-log-line-processor-DbBQT5vY.js","names":[],"sources":["../src/pretty-log-formatter.ts","../src/processors/canonical-log-line-processor.ts"],"sourcesContent":["import type { CanonicalLogLineEvent } from './processors/canonical-log-line-processor';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst YELLOW = '\\x1b[33m';\nconst GREEN = '\\x1b[32m';\nconst CYAN = '\\x1b[36m';\nconst GRAY = '\\x1b[90m';\n\nconst LEVEL_COLORS: Record<string, string> = {\n debug: GRAY,\n info: GREEN,\n warn: YELLOW,\n error: RED,\n};\n\n/** Internal OTel attributes to skip in pretty output. */\nconst SKIP_PREFIXES = [\n 'telemetry.',\n 'otel.',\n 'process.',\n 'os.',\n 'host.',\n 'service.',\n 'autotel.',\n];\n\nconst SKIP_KEYS = new Set([\n 'operation',\n 'traceId',\n 'spanId',\n 'correlationId',\n 'duration_ms',\n 'duration',\n 'status_code',\n 'status_message',\n 'timestamp',\n 'http.request.method',\n 'url.path',\n 'http.route',\n 'http.response.status_code',\n]);\n\nfunction useColor(): boolean {\n if (typeof process !== 'undefined') {\n if (process.env.NO_COLOR) return false;\n if (process.env.FORCE_COLOR) return true;\n if (process.stdout?.isTTY) return true;\n }\n return false;\n}\n\nfunction c(color: string, text: string): string {\n return useColor() ? `${color}${text}${RESET}` : text;\n}\n\n/**\n * Format milliseconds into a human-readable duration string.\n *\n * @example\n * formatDuration(45) // \"45ms\"\n * formatDuration(1234) // \"1.2s\"\n * formatDuration(65000) // \"1m 5s\"\n */\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) {\n const seconds = ms / 1000;\n return seconds < 10 ? `${seconds.toFixed(1)}s` : `${Math.round(seconds)}s`;\n }\n const minutes = Math.floor(ms / 60_000);\n const seconds = Math.round((ms % 60_000) / 1000);\n return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;\n}\n\nfunction formatTime(iso: string): string {\n try {\n const d = new Date(iso);\n return d.toLocaleTimeString('en-GB', { hour12: false });\n } catch {\n return iso.slice(11, 19);\n }\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean')\n return String(value);\n if (value == null) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Group flat dot-notation attributes into a nested tree for pretty display.\n * e.g. { 'user.id': '1', 'user.plan': 'pro' } → { user: { id: '1', plan: 'pro' } }\n */\nfunction groupAttributes(\n event: Record<string, unknown>,\n): Record<string, unknown> {\n const tree: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(event)) {\n if (SKIP_KEYS.has(key)) continue;\n if (SKIP_PREFIXES.some((p) => key.startsWith(p))) continue;\n if (value == null || value === '') continue;\n\n const parts = key.split('.');\n if (parts.length === 1) {\n tree[key] = value;\n } else {\n let current = tree;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (!(part in current) || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return tree;\n}\n\nfunction renderTree(\n obj: Record<string, unknown>,\n indent: string,\n isLast: boolean[],\n): string[] {\n const lines: string[] = [];\n const entries = Object.entries(obj);\n\n entries.forEach(([key, value], idx) => {\n const last = idx === entries.length - 1;\n const connector = last ? '\\u2514\\u2500' : '\\u251c\\u2500';\n const prefix = indent + connector + ' ';\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const nested = value as Record<string, unknown>;\n const flatValues = Object.entries(nested).filter(\n ([, v]) => typeof v !== 'object' || v === null,\n );\n const nestedObjs = Object.entries(nested).filter(\n ([, v]) => typeof v === 'object' && v !== null && !Array.isArray(v),\n );\n\n if (nestedObjs.length === 0) {\n const inline = flatValues\n .map(([k, v]) => `${c(CYAN, k)}=${formatValue(v)}`)\n .join(' ');\n lines.push(`${prefix}${c(BOLD, key)}: ${inline}`);\n } else {\n lines.push(`${prefix}${c(BOLD, key)}:`);\n const nextIndent = indent + (last ? ' ' : '\\u2502 ');\n lines.push(...renderTree(nested, nextIndent, [...isLast, last]));\n }\n } else {\n lines.push(`${prefix}${c(CYAN, key)}: ${c(DIM, formatValue(value))}`);\n }\n });\n\n return lines;\n}\n\n/**\n * Format a canonical log line event as a pretty tree for development output.\n */\nexport function formatPrettyLogLine(ctx: CanonicalLogLineEvent): string {\n const { event, level, message } = ctx;\n\n const timestamp = formatTime(String(event.timestamp ?? ''));\n const service = event['service.name'] || event.service || '';\n const method = event['http.request.method'] || '';\n const path = event['http.route'] || event['url.path'] || '';\n const status = event['http.response.status_code'] || event.status_code || '';\n const durationMs = Number(event.duration_ms ?? 0);\n const duration = formatDuration(durationMs);\n\n const levelColor = LEVEL_COLORS[level] ?? '';\n const levelStr = c(levelColor, level.toUpperCase().padEnd(5));\n\n const parts = [c(DIM, timestamp), levelStr];\n if (service) parts.push(c(DIM, `[${service}]`));\n if (method) parts.push(c(BOLD, String(method)));\n if (path) parts.push(String(path));\n if (status) {\n const statusNum = Number(status);\n const statusColor =\n statusNum >= 500 ? RED : statusNum >= 400 ? YELLOW : GREEN;\n parts.push(c(statusColor, String(status)));\n }\n parts.push(c(DIM, `in ${duration}`));\n\n const header = parts.join(' ');\n\n const tree = groupAttributes(event);\n if (Object.keys(tree).length === 0) {\n return header;\n }\n\n const treeLines = renderTree(tree, ' ', []);\n return [header, ...treeLines].join('\\n');\n}\n","/**\n * Canonical Log Line Processor\n *\n * Automatically emits spans as canonical log lines (wide events) when they end.\n * Implements canonical log line\" pattern: one comprehensive\n * event per request with all context.\n *\n * When a span ends, this processor creates a log record with ALL span attributes,\n * making the span itself the canonical log line that can be queried like structured data.\n *\n * @example\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n */\n\nimport type {\n SpanProcessor,\n ReadableSpan,\n} from '@opentelemetry/sdk-trace-base';\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Logger } from '../logger';\nimport { formatPrettyLogLine, formatDuration } from '../pretty-log-formatter';\n\n/**\n * Function to redact sensitive attribute values\n */\nexport type AttributeRedactorFn = (\n key: string,\n value: AttributeValue,\n) => AttributeValue;\n\nexport interface CanonicalLogLineEvent {\n span: ReadableSpan;\n level: 'debug' | 'info' | 'warn' | 'error';\n message: string;\n event: Record<string, unknown>;\n}\n\nexport interface KeepCondition {\n /** Keep events where HTTP status >= this value. */\n status?: number;\n /** Keep events where duration_ms >= this value. */\n durationMs?: number;\n /** Keep events matching this path pattern (simple prefix match). */\n path?: string;\n}\n\nexport interface CanonicalLogLineOptions {\n /** Logger to use for emitting canonical log lines (defaults to OTel Logs API) */\n logger?: Logger;\n /** Only emit canonical log lines for root spans (default: false) */\n rootSpansOnly?: boolean;\n /** Minimum log level for canonical log lines (default: 'info') */\n minLevel?: 'debug' | 'info' | 'warn' | 'error';\n /** Custom message format (default: uses span name) */\n messageFormat?: (span: ReadableSpan) => string;\n /** Whether to include resource attributes (default: true) */\n includeResourceAttributes?: boolean;\n /**\n * Attribute redactor function to apply before logging.\n * This ensures sensitive data is redacted in canonical log lines,\n * matching the behavior of attributeRedactor in init().\n */\n attributeRedactor?: AttributeRedactorFn;\n /** Predicate to decide whether to emit (runs after event is built). */\n shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n /**\n * Declarative tail sampling conditions (OR logic). If any condition matches,\n * the event is kept. Ignored when `shouldEmit` is provided.\n *\n * @example\n * keep: [{ status: 500 }, { durationMs: 1000 }]\n */\n keep?: KeepCondition[];\n /** Callback invoked after emit for custom fan-out. */\n drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n /** Handler for drain failures. */\n onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n /**\n * Pretty-print canonical log lines to console in a tree format.\n * Defaults to true when NODE_ENV is 'development'.\n */\n pretty?: boolean;\n}\n\n/**\n * Span processor that automatically emits spans as canonical log lines\n *\n * When a span ends, this processor creates a log record with ALL span attributes.\n * This implements the \"canonical log line\" pattern: one comprehensive event\n * per request with all context, queryable as structured data.\n *\n * **Key Benefits:**\n * - One log line per request with all context (wide event)\n * - High-cardinality, high-dimensionality data for powerful queries\n * - Automatic - no manual logging needed\n * - Works with any logger or OTel Logs API\n *\n * @example Basic usage\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'checkout-api',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n *\n * @example With custom logger\n * ```typescript\n * import pino from 'pino';\n * import { init } from 'autotel';\n *\n * const logger = pino();\n * init({\n * service: 'my-app',\n * logger,\n * canonicalLogLines: {\n * enabled: true,\n * logger, // Use Pino for canonical log lines\n * rootSpansOnly: true,\n * },\n * });\n * ```\n *\n * @example Custom message format\n * ```typescript\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * messageFormat: (span) => {\n * const status = span.status.code === 2 ? 'ERROR' : 'SUCCESS';\n * return `${span.name} [${status}]`;\n * },\n * },\n * });\n * ```\n */\nexport class CanonicalLogLineProcessor implements SpanProcessor {\n private logger?: Logger;\n private rootSpansOnly: boolean;\n private minLevel: 'debug' | 'info' | 'warn' | 'error';\n private messageFormat: (span: ReadableSpan) => string;\n private includeResourceAttributes: boolean;\n private attributeRedactor?: AttributeRedactorFn;\n private shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n private drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n private onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n private pretty: boolean;\n private getOTelLogger: (() => ReturnType<typeof logs.getLogger>) | null =\n null;\n\n constructor(options: CanonicalLogLineOptions = {}) {\n this.logger = options.logger;\n this.rootSpansOnly = options.rootSpansOnly ?? false;\n this.minLevel = options.minLevel ?? 'info';\n this.messageFormat =\n options.messageFormat ?? ((span) => `[${span.name}] Request completed`);\n this.includeResourceAttributes = options.includeResourceAttributes ?? true;\n this.attributeRedactor = options.attributeRedactor;\n this.shouldEmit =\n options.shouldEmit ?? this.buildKeepPredicate(options.keep);\n this.drain = options.drain;\n this.onDrainError = options.onDrainError;\n this.pretty =\n options.pretty ??\n (typeof process !== 'undefined' &&\n process.env.NODE_ENV === 'development');\n\n if (!this.logger) {\n this.getOTelLogger = () => logs.getLogger('autotel.canonical-log-line');\n }\n }\n\n private buildKeepPredicate(\n keep?: KeepCondition[],\n ): ((ctx: CanonicalLogLineEvent) => boolean) | undefined {\n if (!keep || keep.length === 0) return undefined;\n\n return (ctx: CanonicalLogLineEvent) => {\n return keep.some((condition) => {\n if (condition.status !== undefined) {\n const httpStatus = Number(\n ctx.event['http.response.status_code'] ?? 0,\n );\n if (httpStatus >= condition.status) return true;\n }\n if (\n condition.durationMs !== undefined &&\n Number(ctx.event.duration_ms ?? 0) >= condition.durationMs\n ) {\n return true;\n }\n if (condition.path !== undefined) {\n const route = String(\n ctx.event['http.route'] ?? ctx.event['url.path'] ?? '',\n );\n if (route.startsWith(condition.path)) return true;\n }\n return false;\n });\n };\n }\n\n onStart(): void {\n // No-op\n }\n\n onEnd(span: ReadableSpan): void {\n if (\n this.rootSpansOnly &&\n span.parentSpanContext?.spanId &&\n !span.parentSpanContext.isRemote\n ) {\n return;\n }\n\n const level = this.getLogLevel(span);\n if (!this.shouldLog(level)) {\n return;\n }\n\n const canonicalLogLine = this.buildCanonicalLogLine(span);\n const message = this.messageFormat(span);\n const eventContext: CanonicalLogLineEvent = {\n span,\n level,\n message,\n event: canonicalLogLine,\n };\n\n if (this.shouldEmit && !this.shouldEmit(eventContext)) return;\n\n if (this.pretty) {\n console.log(formatPrettyLogLine(eventContext));\n }\n\n if (this.logger) {\n this.emitViaLogger(level, message, canonicalLogLine);\n } else if (this.getOTelLogger) {\n const otelLogger = this.getOTelLogger();\n this.emitViaOTel(level, message, canonicalLogLine, otelLogger);\n }\n\n if (this.drain) {\n Promise.resolve(this.drain(eventContext)).catch((error) => {\n if (this.onDrainError) {\n this.onDrainError(error, eventContext);\n return;\n }\n this.reportInternalWarning('canonicalLogLines.drain failed', error);\n });\n }\n }\n\n private buildCanonicalLogLine(span: ReadableSpan): Record<string, unknown> {\n const durationMs = span.duration[0] * 1000 + span.duration[1] / 1_000_000;\n const timestamp = new Date(\n span.startTime[0] * 1000 + span.startTime[1] / 1_000_000,\n ).toISOString();\n\n // Span attributes first so core metadata fields below take precedence\n const canonicalLogLine: Record<string, unknown> = {};\n const attributes = this.redactAttributes(span.attributes);\n Object.assign(canonicalLogLine, attributes);\n\n if (this.includeResourceAttributes) {\n const resourceAttrs = this.redactAttributes(\n span.resource.attributes as Attributes,\n );\n Object.assign(canonicalLogLine, resourceAttrs);\n }\n\n canonicalLogLine.operation = span.name;\n canonicalLogLine.traceId = span.spanContext().traceId;\n canonicalLogLine.spanId = span.spanContext().spanId;\n canonicalLogLine.correlationId = span.spanContext().traceId.slice(0, 16);\n canonicalLogLine.duration_ms = Math.round(durationMs * 100) / 100;\n canonicalLogLine.duration = formatDuration(durationMs);\n canonicalLogLine.status_code = span.status.code;\n canonicalLogLine.status_message = span.status.message || undefined;\n canonicalLogLine.timestamp = timestamp;\n\n return canonicalLogLine;\n }\n\n private redactAttributes(attributes: Attributes): Record<string, unknown> {\n if (!this.attributeRedactor) {\n return { ...attributes };\n }\n\n const redacted: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n redacted[key] = this.attributeRedactor(key, value);\n }\n }\n return redacted;\n }\n\n private emitViaLogger(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n ): void {\n this.logger![level](canonicalLogLine, message);\n }\n\n private emitViaOTel(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n otelLogger: ReturnType<typeof logs.getLogger>,\n ): void {\n const otelAttributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(canonicalLogLine)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n otelAttributes[key] = value;\n } else if (value !== null && value !== undefined) {\n otelAttributes[key] = String(value);\n }\n }\n otelLogger.emit({\n severityNumber: this.getSeverityNumber(level),\n severityText: level.toUpperCase(),\n body: message,\n attributes: otelAttributes,\n });\n }\n\n private getLogLevel(span: ReadableSpan): 'debug' | 'info' | 'warn' | 'error' {\n const explicitLevel = span.attributes['autotel.log.level'];\n if (\n explicitLevel === 'debug' ||\n explicitLevel === 'info' ||\n explicitLevel === 'warn' ||\n explicitLevel === 'error'\n ) {\n return explicitLevel;\n }\n\n if (span.status.code === 2) return 'error';\n return 'info';\n }\n\n private shouldLog(level: string): boolean {\n const levels = ['debug', 'info', 'warn', 'error'];\n return levels.indexOf(level) >= levels.indexOf(this.minLevel);\n }\n\n private getSeverityNumber(level: string): SeverityNumber {\n const mapping: Record<string, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n };\n return mapping[level] ?? SeverityNumber.INFO;\n }\n\n private reportInternalWarning(message: string, error: unknown): void {\n const err =\n error instanceof Error ? error.message : String(error ?? 'unknown error');\n if (this.logger) {\n this.logger.warn({ error: err }, `[autotel] ${message}`);\n return;\n }\n console.warn(`[autotel] ${message}: ${err}`);\n }\n\n async forceFlush(): Promise<void> {\n // No-op\n }\n\n async shutdown(): Promise<void> {\n // No-op\n }\n}\n"],"mappings":";;;AAEA,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,MAAM;AACZ,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,OAAO;AAGb,MAAM,eAAuC;CAC3C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;AACT;;AAGA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,YAAY,IAAI,IAAI;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,WAAoB;CAC3B,IAAI,OAAO,YAAY,aAAa;EAClC,IAAI,QAAQ,IAAI,UAAU,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AAK,WAAW;EACtC,IACE,kBAAkB,WAClB,kBAAkB,UAClB,kBAAkB,UAClB,kBAAkB,SAElB,OAAO;EAGT,IAAI,KAAK,OAAO,SAAS,GAAG,OAAO;EACnC,OAAO;CACT;CAEA,AAAQ,UAAU,OAAwB;EACxC,MAAM,SAAS;GAAC;GAAS;GAAQ;GAAQ;EAAO;EAChD,OAAO,OAAO,QAAQ,KAAK,KAAK,OAAO,QAAQ,KAAK,QAAQ;CAC9D;CAEA,AAAQ,kBAAkB,OAA+B;EAOvD,OAAO;GALL,OAAO,eAAe;GACtB,MAAM,eAAe;GACrB,MAAM,eAAe;GACrB,OAAO,eAAe;EAEX,EAAE,UAAU,eAAe;CAC1C;CAEA,AAAQ,sBAAsB,SAAiB,OAAsB;EACnE,MAAM,MACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,eAAe;EAC1E,IAAI,KAAK,QAAQ;GACf,KAAK,OAAO,KAAK,EAAE,OAAO,IAAI,GAAG,aAAa,SAAS;GACvD;EACF;EACA,QAAQ,KAAK,aAAa,QAAQ,IAAI,KAAK;CAC7C;CAEA,MAAM,aAA4B,CAElC;CAEA,MAAM,WAA0B,CAEhC;AACF"}
1
+ {"version":3,"file":"canonical-log-line-processor-FLezvFCB.js","names":[],"sources":["../src/pretty-log-formatter.ts","../src/processors/canonical-log-line-processor.ts"],"sourcesContent":["import type { CanonicalLogLineEvent } from './processors/canonical-log-line-processor';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst YELLOW = '\\x1b[33m';\nconst GREEN = '\\x1b[32m';\nconst CYAN = '\\x1b[36m';\nconst GRAY = '\\x1b[90m';\n\nconst LEVEL_COLORS: Record<string, string> = {\n debug: GRAY,\n info: GREEN,\n warn: YELLOW,\n error: RED,\n};\n\n/** Internal OTel attributes to skip in pretty output. */\nconst SKIP_PREFIXES = [\n 'telemetry.',\n 'otel.',\n 'process.',\n 'os.',\n 'host.',\n 'service.',\n 'autotel.',\n];\n\nconst SKIP_KEYS = new Set([\n 'operation',\n 'traceId',\n 'spanId',\n 'correlationId',\n 'duration_ms',\n 'duration',\n 'status_code',\n 'status_message',\n 'timestamp',\n 'http.request.method',\n 'url.path',\n 'http.route',\n 'http.response.status_code',\n]);\n\nfunction useColor(): boolean {\n if (typeof process !== 'undefined') {\n if (process.env.NO_COLOR) return false;\n if (process.env.FORCE_COLOR) return true;\n if (process.stdout?.isTTY) return true;\n }\n return false;\n}\n\nfunction c(color: string, text: string): string {\n return useColor() ? `${color}${text}${RESET}` : text;\n}\n\n/**\n * Format milliseconds into a human-readable duration string.\n *\n * @example\n * formatDuration(45) // \"45ms\"\n * formatDuration(1234) // \"1.2s\"\n * formatDuration(65000) // \"1m 5s\"\n */\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) {\n const seconds = ms / 1000;\n return seconds < 10 ? `${seconds.toFixed(1)}s` : `${Math.round(seconds)}s`;\n }\n const minutes = Math.floor(ms / 60_000);\n const seconds = Math.round((ms % 60_000) / 1000);\n return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;\n}\n\nfunction formatTime(iso: string): string {\n try {\n const d = new Date(iso);\n return d.toLocaleTimeString('en-GB', { hour12: false });\n } catch {\n return iso.slice(11, 19);\n }\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean')\n return String(value);\n if (value == null) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Group flat dot-notation attributes into a nested tree for pretty display.\n * e.g. { 'user.id': '1', 'user.plan': 'pro' } → { user: { id: '1', plan: 'pro' } }\n */\nfunction groupAttributes(\n event: Record<string, unknown>,\n): Record<string, unknown> {\n const tree: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(event)) {\n if (SKIP_KEYS.has(key)) continue;\n if (SKIP_PREFIXES.some((p) => key.startsWith(p))) continue;\n if (value == null || value === '') continue;\n\n const parts = key.split('.');\n if (parts.length === 1) {\n tree[key] = value;\n } else {\n let current = tree;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (!(part in current) || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return tree;\n}\n\nfunction renderTree(\n obj: Record<string, unknown>,\n indent: string,\n isLast: boolean[],\n): string[] {\n const lines: string[] = [];\n const entries = Object.entries(obj);\n\n entries.forEach(([key, value], idx) => {\n const last = idx === entries.length - 1;\n const connector = last ? '\\u2514\\u2500' : '\\u251c\\u2500';\n const prefix = indent + connector + ' ';\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const nested = value as Record<string, unknown>;\n const flatValues = Object.entries(nested).filter(\n ([, v]) => typeof v !== 'object' || v === null,\n );\n const nestedObjs = Object.entries(nested).filter(\n ([, v]) => typeof v === 'object' && v !== null && !Array.isArray(v),\n );\n\n if (nestedObjs.length === 0) {\n const inline = flatValues\n .map(([k, v]) => `${c(CYAN, k)}=${formatValue(v)}`)\n .join(' ');\n lines.push(`${prefix}${c(BOLD, key)}: ${inline}`);\n } else {\n lines.push(`${prefix}${c(BOLD, key)}:`);\n const nextIndent = indent + (last ? ' ' : '\\u2502 ');\n lines.push(...renderTree(nested, nextIndent, [...isLast, last]));\n }\n } else {\n lines.push(`${prefix}${c(CYAN, key)}: ${c(DIM, formatValue(value))}`);\n }\n });\n\n return lines;\n}\n\n/**\n * Format a canonical log line event as a pretty tree for development output.\n */\nexport function formatPrettyLogLine(ctx: CanonicalLogLineEvent): string {\n const { event, level, message } = ctx;\n\n const timestamp = formatTime(String(event.timestamp ?? ''));\n const service = event['service.name'] || event.service || '';\n const method = event['http.request.method'] || '';\n const path = event['http.route'] || event['url.path'] || '';\n const status = event['http.response.status_code'] || event.status_code || '';\n const durationMs = Number(event.duration_ms ?? 0);\n const duration = formatDuration(durationMs);\n\n const levelColor = LEVEL_COLORS[level] ?? '';\n const levelStr = c(levelColor, level.toUpperCase().padEnd(5));\n\n const parts = [c(DIM, timestamp), levelStr];\n if (service) parts.push(c(DIM, `[${service}]`));\n if (method) parts.push(c(BOLD, String(method)));\n if (path) parts.push(String(path));\n if (status) {\n const statusNum = Number(status);\n const statusColor =\n statusNum >= 500 ? RED : statusNum >= 400 ? YELLOW : GREEN;\n parts.push(c(statusColor, String(status)));\n }\n parts.push(c(DIM, `in ${duration}`));\n\n const header = parts.join(' ');\n\n const tree = groupAttributes(event);\n if (Object.keys(tree).length === 0) {\n return header;\n }\n\n const treeLines = renderTree(tree, ' ', []);\n return [header, ...treeLines].join('\\n');\n}\n","/**\n * Canonical Log Line Processor\n *\n * Automatically emits spans as canonical log lines (wide events) when they end.\n * Implements canonical log line\" pattern: one comprehensive\n * event per request with all context.\n *\n * When a span ends, this processor creates a log record with ALL span attributes,\n * making the span itself the canonical log line that can be queried like structured data.\n *\n * @example\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n */\n\nimport type {\n SpanProcessor,\n ReadableSpan,\n} from '@opentelemetry/sdk-trace-base';\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Logger } from '../logger';\nimport { formatPrettyLogLine, formatDuration } from '../pretty-log-formatter';\n\n/**\n * Function to redact sensitive attribute values\n */\nexport type AttributeRedactorFn = (\n key: string,\n value: AttributeValue,\n) => AttributeValue;\n\nexport interface CanonicalLogLineEvent {\n span: ReadableSpan;\n level: 'debug' | 'info' | 'warn' | 'error';\n message: string;\n event: Record<string, unknown>;\n}\n\nexport interface KeepCondition {\n /** Keep events where HTTP status >= this value. */\n status?: number;\n /** Keep events where duration_ms >= this value. */\n durationMs?: number;\n /** Keep events matching this path pattern (simple prefix match). */\n path?: string;\n}\n\nexport interface CanonicalLogLineOptions {\n /** Logger to use for emitting canonical log lines (defaults to OTel Logs API) */\n logger?: Logger;\n /** Only emit canonical log lines for root spans (default: false) */\n rootSpansOnly?: boolean;\n /** Minimum log level for canonical log lines (default: 'info') */\n minLevel?: 'debug' | 'info' | 'warn' | 'error';\n /** Custom message format (default: uses span name) */\n messageFormat?: (span: ReadableSpan) => string;\n /** Whether to include resource attributes (default: true) */\n includeResourceAttributes?: boolean;\n /**\n * Attribute redactor function to apply before logging.\n * This ensures sensitive data is redacted in canonical log lines,\n * matching the behavior of attributeRedactor in init().\n */\n attributeRedactor?: AttributeRedactorFn;\n /** Predicate to decide whether to emit (runs after event is built). */\n shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n /**\n * Declarative tail sampling conditions (OR logic). If any condition matches,\n * the event is kept. Ignored when `shouldEmit` is provided.\n *\n * @example\n * keep: [{ status: 500 }, { durationMs: 1000 }]\n */\n keep?: KeepCondition[];\n /** Callback invoked after emit for custom fan-out. */\n drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n /** Handler for drain failures. */\n onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n /**\n * Pretty-print canonical log lines to console in a tree format.\n * Defaults to true when NODE_ENV is 'development'.\n */\n pretty?: boolean;\n}\n\n/**\n * Span processor that automatically emits spans as canonical log lines\n *\n * When a span ends, this processor creates a log record with ALL span attributes.\n * This implements the \"canonical log line\" pattern: one comprehensive event\n * per request with all context, queryable as structured data.\n *\n * **Key Benefits:**\n * - One log line per request with all context (wide event)\n * - High-cardinality, high-dimensionality data for powerful queries\n * - Automatic - no manual logging needed\n * - Works with any logger or OTel Logs API\n *\n * @example Basic usage\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({\n * service: 'checkout-api',\n * canonicalLogLines: {\n * enabled: true,\n * rootSpansOnly: true, // One canonical log line per request\n * },\n * });\n * ```\n *\n * @example With custom logger\n * ```typescript\n * import pino from 'pino';\n * import { init } from 'autotel';\n *\n * const logger = pino();\n * init({\n * service: 'my-app',\n * logger,\n * canonicalLogLines: {\n * enabled: true,\n * logger, // Use Pino for canonical log lines\n * rootSpansOnly: true,\n * },\n * });\n * ```\n *\n * @example Custom message format\n * ```typescript\n * init({\n * service: 'my-app',\n * canonicalLogLines: {\n * enabled: true,\n * messageFormat: (span) => {\n * const status = span.status.code === 2 ? 'ERROR' : 'SUCCESS';\n * return `${span.name} [${status}]`;\n * },\n * },\n * });\n * ```\n */\nexport class CanonicalLogLineProcessor implements SpanProcessor {\n private logger?: Logger;\n private rootSpansOnly: boolean;\n private minLevel: 'debug' | 'info' | 'warn' | 'error';\n private messageFormat: (span: ReadableSpan) => string;\n private includeResourceAttributes: boolean;\n private attributeRedactor?: AttributeRedactorFn;\n private shouldEmit?: (ctx: CanonicalLogLineEvent) => boolean;\n private drain?: (ctx: CanonicalLogLineEvent) => void | Promise<void>;\n private onDrainError?: (error: unknown, ctx: CanonicalLogLineEvent) => void;\n private pretty: boolean;\n private getOTelLogger: (() => ReturnType<typeof logs.getLogger>) | null =\n null;\n\n constructor(options: CanonicalLogLineOptions = {}) {\n this.logger = options.logger;\n this.rootSpansOnly = options.rootSpansOnly ?? false;\n this.minLevel = options.minLevel ?? 'info';\n this.messageFormat =\n options.messageFormat ?? ((span) => `[${span.name}] Request completed`);\n this.includeResourceAttributes = options.includeResourceAttributes ?? true;\n this.attributeRedactor = options.attributeRedactor;\n this.shouldEmit =\n options.shouldEmit ?? this.buildKeepPredicate(options.keep);\n this.drain = options.drain;\n this.onDrainError = options.onDrainError;\n this.pretty =\n options.pretty ??\n (typeof process !== 'undefined' &&\n process.env.NODE_ENV === 'development');\n\n if (!this.logger) {\n this.getOTelLogger = () => logs.getLogger('autotel.canonical-log-line');\n }\n }\n\n private buildKeepPredicate(\n keep?: KeepCondition[],\n ): ((ctx: CanonicalLogLineEvent) => boolean) | undefined {\n if (!keep || keep.length === 0) return undefined;\n\n return (ctx: CanonicalLogLineEvent) => {\n return keep.some((condition) => {\n if (condition.status !== undefined) {\n const httpStatus = Number(\n ctx.event['http.response.status_code'] ?? 0,\n );\n if (httpStatus >= condition.status) return true;\n }\n if (\n condition.durationMs !== undefined &&\n Number(ctx.event.duration_ms ?? 0) >= condition.durationMs\n ) {\n return true;\n }\n if (condition.path !== undefined) {\n const route = String(\n ctx.event['http.route'] ?? ctx.event['url.path'] ?? '',\n );\n if (route.startsWith(condition.path)) return true;\n }\n return false;\n });\n };\n }\n\n onStart(): void {\n // No-op\n }\n\n onEnd(span: ReadableSpan): void {\n if (\n this.rootSpansOnly &&\n span.parentSpanContext?.spanId &&\n !span.parentSpanContext.isRemote\n ) {\n return;\n }\n\n const level = this.getLogLevel(span);\n if (!this.shouldLog(level)) {\n return;\n }\n\n const canonicalLogLine = this.buildCanonicalLogLine(span);\n const message = this.messageFormat(span);\n const eventContext: CanonicalLogLineEvent = {\n span,\n level,\n message,\n event: canonicalLogLine,\n };\n\n if (this.shouldEmit && !this.shouldEmit(eventContext)) return;\n\n if (this.pretty) {\n console.log(formatPrettyLogLine(eventContext));\n }\n\n if (this.logger) {\n this.emitViaLogger(level, message, canonicalLogLine);\n } else if (this.getOTelLogger) {\n const otelLogger = this.getOTelLogger();\n this.emitViaOTel(level, message, canonicalLogLine, otelLogger);\n }\n\n if (this.drain) {\n Promise.resolve(this.drain(eventContext)).catch((error) => {\n if (this.onDrainError) {\n this.onDrainError(error, eventContext);\n return;\n }\n this.reportInternalWarning('canonicalLogLines.drain failed', error);\n });\n }\n }\n\n private buildCanonicalLogLine(span: ReadableSpan): Record<string, unknown> {\n const durationMs = span.duration[0] * 1000 + span.duration[1] / 1_000_000;\n const timestamp = new Date(\n span.startTime[0] * 1000 + span.startTime[1] / 1_000_000,\n ).toISOString();\n\n // Span attributes first so core metadata fields below take precedence\n const canonicalLogLine: Record<string, unknown> = {};\n const attributes = this.redactAttributes(span.attributes);\n Object.assign(canonicalLogLine, attributes);\n\n if (this.includeResourceAttributes) {\n const resourceAttrs = this.redactAttributes(\n span.resource.attributes as Attributes,\n );\n Object.assign(canonicalLogLine, resourceAttrs);\n }\n\n canonicalLogLine.operation = span.name;\n canonicalLogLine.traceId = span.spanContext().traceId;\n canonicalLogLine.spanId = span.spanContext().spanId;\n canonicalLogLine.correlationId = span.spanContext().traceId.slice(0, 16);\n canonicalLogLine.duration_ms = Math.round(durationMs * 100) / 100;\n canonicalLogLine.duration = formatDuration(durationMs);\n canonicalLogLine.status_code = span.status.code;\n canonicalLogLine.status_message = span.status.message || undefined;\n canonicalLogLine.timestamp = timestamp;\n\n return canonicalLogLine;\n }\n\n private redactAttributes(attributes: Attributes): Record<string, unknown> {\n if (!this.attributeRedactor) {\n return { ...attributes };\n }\n\n const redacted: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n redacted[key] = this.attributeRedactor(key, value);\n }\n }\n return redacted;\n }\n\n private emitViaLogger(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n ): void {\n this.logger![level](canonicalLogLine, message);\n }\n\n private emitViaOTel(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n canonicalLogLine: Record<string, unknown>,\n otelLogger: ReturnType<typeof logs.getLogger>,\n ): void {\n const otelAttributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(canonicalLogLine)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n otelAttributes[key] = value;\n } else if (value !== null && value !== undefined) {\n otelAttributes[key] = String(value);\n }\n }\n otelLogger.emit({\n severityNumber: this.getSeverityNumber(level),\n severityText: level.toUpperCase(),\n body: message,\n attributes: otelAttributes,\n });\n }\n\n private getLogLevel(span: ReadableSpan): 'debug' | 'info' | 'warn' | 'error' {\n const explicitLevel = span.attributes['autotel.log.level'];\n if (\n explicitLevel === 'debug' ||\n explicitLevel === 'info' ||\n explicitLevel === 'warn' ||\n explicitLevel === 'error'\n ) {\n return explicitLevel;\n }\n\n if (span.status.code === 2) return 'error';\n return 'info';\n }\n\n private shouldLog(level: string): boolean {\n const levels = ['debug', 'info', 'warn', 'error'];\n return levels.indexOf(level) >= levels.indexOf(this.minLevel);\n }\n\n private getSeverityNumber(level: string): SeverityNumber {\n const mapping: Record<string, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n };\n return mapping[level] ?? SeverityNumber.INFO;\n }\n\n private reportInternalWarning(message: string, error: unknown): void {\n const err =\n error instanceof Error ? error.message : String(error ?? 'unknown error');\n if (this.logger) {\n this.logger.warn({ error: err }, `[autotel] ${message}`);\n return;\n }\n console.warn(`[autotel] ${message}: ${err}`);\n }\n\n async forceFlush(): Promise<void> {\n // No-op\n }\n\n async shutdown(): Promise<void> {\n // No-op\n }\n}\n"],"mappings":";;;AAEA,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,MAAM;AACZ,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,OAAO;AAGb,MAAM,eAAuC;CAC3C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;AACT;;AAGA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,4BAAY,IAAI,IAAI;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,WAAoB;CAC3B,IAAI,OAAO,YAAY,aAAa;EAClC,IAAI,QAAQ,IAAI,UAAU,OAAO;EACjC,IAAI,QAAQ,IAAI,aAAa,OAAO;EACpC,IAAI,QAAQ,QAAQ,OAAO,OAAO;CACpC;CACA,OAAO;AACT;AAEA,SAAS,EAAE,OAAe,MAAsB;CAC9C,OAAO,SAAS,IAAI,GAAG,QAAQ,OAAO,UAAU;AAClD;;;;;;;;;AAUA,SAAgB,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;EAAO;EAChD,OAAO,OAAO,QAAQ,KAAK,KAAK,OAAO,QAAQ,KAAK,QAAQ;CAC9D;CAEA,AAAQ,kBAAkB,OAA+B;EAOvD,OAAO;GALL,OAAO,eAAe;GACtB,MAAM,eAAe;GACrB,MAAM,eAAe;GACrB,OAAO,eAAe;EAEX,EAAE,UAAU,eAAe;CAC1C;CAEA,AAAQ,sBAAsB,SAAiB,OAAsB;EACnE,MAAM,MACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,eAAe;EAC1E,IAAI,KAAK,QAAQ;GACf,KAAK,OAAO,KAAK,EAAE,OAAO,IAAI,GAAG,aAAa,SAAS;GACvD;EACF;EACA,QAAQ,KAAK,aAAa,QAAQ,IAAI,KAAK;CAC7C;CAEA,MAAM,aAA4B,CAElC;CAEA,MAAM,WAA0B,CAEhC;AACF"}
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_track = require('./track-Cb3Q4QmS.cjs');
2
+ const require_track = require('./track-eovhCJ-I.cjs');
3
3
 
4
4
  exports.CORRELATION_ID_BAGGAGE_KEY = require_track.CORRELATION_ID_BAGGAGE_KEY;
5
5
  exports.generateCorrelationId = require_track.generateCorrelationId;
@@ -1,3 +1,3 @@
1
- import { a as CORRELATION_ID_BAGGAGE_KEY, c as getCorrelationStorage, d as setCorrelationId, f as setCorrelationIdInBaggage, l as getOrCreateCorrelationId, o as generateCorrelationId, s as getCorrelationId, u as runWithCorrelationId } from "./track-COUuU48p.js";
1
+ import { a as CORRELATION_ID_BAGGAGE_KEY, c as getCorrelationStorage, d as setCorrelationId, f as setCorrelationIdInBaggage, l as getOrCreateCorrelationId, o as generateCorrelationId, s as getCorrelationId, u as runWithCorrelationId } from "./track-D7O7oIZa.js";
2
2
 
3
3
  export { CORRELATION_ID_BAGGAGE_KEY, generateCorrelationId, getCorrelationId, getCorrelationStorage, getOrCreateCorrelationId, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage };
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_config = require('./config.cjs');
3
- const require_track = require('./track-Cb3Q4QmS.cjs');
3
+ const require_track = require('./track-eovhCJ-I.cjs');
4
4
  let _opentelemetry_api = require("@opentelemetry/api");
5
5
 
6
6
  //#region src/decorators.ts
@@ -1,5 +1,5 @@
1
1
  import { getConfig } from "./config.js";
2
- import { p as createTraceContext } from "./track-COUuU48p.js";
2
+ import { p as createTraceContext } from "./track-D7O7oIZa.js";
3
3
  import { SpanStatusCode } from "@opentelemetry/api";
4
4
 
5
5
  //#region src/decorators.ts
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_node_require = require('./node-require-CZ_PU448.cjs');
2
+ const require_node_require = require('./node-require-PFqDihze.cjs');
3
3
  let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
4
4
  let _opentelemetry_api = require("@opentelemetry/api");
5
5
  let _opentelemetry_api_logs = require("@opentelemetry/api-logs");
@@ -51,7 +51,10 @@ function createDrainPipeline(options) {
51
51
  onDropped?.(batch, lastError);
52
52
  };
53
53
  const drainBuffer = async () => {
54
- while (buffer.length > 0) await sendWithRetry(buffer.splice(0, batchSize));
54
+ while (buffer.length > 0) {
55
+ const batch = buffer.splice(0, batchSize);
56
+ await sendWithRetry(batch);
57
+ }
55
58
  };
56
59
  const scheduleFlush = () => {
57
60
  if (isShutdown || timer || activeFlush) return;
@@ -92,7 +95,10 @@ function createDrainPipeline(options) {
92
95
  const snapshot = buffer.length;
93
96
  if (snapshot <= 0) return;
94
97
  const toFlush = buffer.splice(0, snapshot);
95
- while (toFlush.length > 0) await sendWithRetry(toFlush.splice(0, batchSize));
98
+ while (toFlush.length > 0) {
99
+ const batch = toFlush.splice(0, batchSize);
100
+ await sendWithRetry(batch);
101
+ }
96
102
  };
97
103
  const shutdown = async () => {
98
104
  isShutdown = true;
@@ -1 +1 @@
1
- {"version":3,"file":"drain-pipeline.cjs","names":[],"sources":["../src/drain-pipeline.ts"],"sourcesContent":["export interface DrainPipelineOptions<T = unknown> {\n batch?: {\n /** Maximum events per batch. @default 50 */\n size?: number;\n /** Max time an event can stay buffered before flush. @default 5000 */\n intervalMs?: number;\n };\n retry?: {\n /** Total attempts including first try. @default 3 */\n maxAttempts?: number;\n /** Delay strategy between attempts. @default 'exponential' */\n backoff?: 'exponential' | 'linear' | 'fixed';\n /** Base delay for first retry. @default 1000 */\n initialDelayMs?: number;\n /** Max delay cap. @default 30000 */\n maxDelayMs?: number;\n /** Add random jitter to delays. @default true */\n jitter?: boolean;\n };\n /** Max buffered events before dropping. @default 1000 */\n maxBufferSize?: number;\n /** Overflow policy. @default 'oldest' */\n dropPolicy?: 'oldest' | 'newest';\n /** Called when events are dropped from overflow or exhausted retries. */\n onDropped?: (events: T[], error?: Error) => void;\n}\n\nexport interface PipelineDrainFn<T> {\n (ctx: T): void;\n /** Flush all buffered events. */\n flush: () => Promise<void>;\n /** Flush and stop scheduling future timer work. */\n shutdown: () => Promise<void>;\n readonly pending: number;\n}\n\nfunction wait(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n\nexport function createDrainPipeline<T = unknown>(\n options?: DrainPipelineOptions<T>,\n): (drain: (batch: T[]) => void | Promise<void>) => PipelineDrainFn<T> {\n const batchSize = options?.batch?.size ?? 50;\n const intervalMs = options?.batch?.intervalMs ?? 5000;\n const maxBufferSize = options?.maxBufferSize ?? 1000;\n const maxAttempts = options?.retry?.maxAttempts ?? 3;\n const backoff = options?.retry?.backoff ?? 'exponential';\n const initialDelayMs = options?.retry?.initialDelayMs ?? 1000;\n const maxDelayMs = options?.retry?.maxDelayMs ?? 30_000;\n const jitter = options?.retry?.jitter ?? true;\n const dropPolicy = options?.dropPolicy ?? 'oldest';\n const onDropped = options?.onDropped;\n\n if (!Number.isFinite(batchSize) || batchSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.size must be a positive finite number, got: ${batchSize}`,\n );\n }\n if (!Number.isFinite(intervalMs) || intervalMs <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.intervalMs must be a positive finite number, got: ${intervalMs}`,\n );\n }\n if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] maxBufferSize must be a positive finite number, got: ${maxBufferSize}`,\n );\n }\n if (!Number.isFinite(maxAttempts) || maxAttempts <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] retry.maxAttempts must be a positive finite number, got: ${maxAttempts}`,\n );\n }\n\n return (drain: (batch: T[]) => void | Promise<void>): PipelineDrainFn<T> => {\n const buffer: T[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n let activeFlush: Promise<void> | null = null;\n let isShutdown = false;\n\n const clearTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n const computeDelay = (attempt: number): number => {\n const base =\n backoff === 'fixed'\n ? initialDelayMs\n : backoff === 'linear'\n ? initialDelayMs * attempt\n : initialDelayMs * 2 ** (attempt - 1);\n\n const bounded = Math.min(base, maxDelayMs);\n if (!jitter || bounded <= 0) return bounded;\n const factor = 0.5 + Math.random(); // [0.5, 1.5)\n return Math.max(0, Math.round(bounded * factor));\n };\n\n const sendWithRetry = async (batch: T[]): Promise<void> => {\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n await drain(batch);\n return;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt < maxAttempts) {\n await wait(computeDelay(attempt));\n }\n }\n }\n onDropped?.(batch, lastError);\n };\n\n const drainBuffer = async (): Promise<void> => {\n while (buffer.length > 0) {\n const batch = buffer.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const scheduleFlush = () => {\n if (isShutdown || timer || activeFlush) return;\n timer = setTimeout(() => {\n timer = null;\n startFlush();\n }, intervalMs);\n timer.unref?.();\n };\n\n const startFlush = () => {\n if (activeFlush || isShutdown) return;\n activeFlush = drainBuffer().finally(() => {\n activeFlush = null;\n if (isShutdown) return;\n if (buffer.length >= batchSize) {\n startFlush();\n } else if (buffer.length > 0) {\n scheduleFlush();\n }\n });\n };\n\n const push = (ctx: T) => {\n if (isShutdown) return;\n\n if (buffer.length >= maxBufferSize) {\n if (dropPolicy === 'newest') {\n onDropped?.([ctx]);\n return;\n }\n const dropped = buffer.splice(0, 1);\n onDropped?.(dropped);\n }\n\n buffer.push(ctx);\n if (buffer.length >= batchSize) {\n clearTimer();\n startFlush();\n } else {\n scheduleFlush();\n }\n };\n\n const flush = async (): Promise<void> => {\n clearTimer();\n if (activeFlush) await activeFlush;\n\n const snapshot = buffer.length;\n if (snapshot <= 0) return;\n const toFlush = buffer.splice(0, snapshot);\n while (toFlush.length > 0) {\n const batch = toFlush.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const shutdown = async (): Promise<void> => {\n isShutdown = true;\n await flush();\n };\n\n const fn = push as PipelineDrainFn<T>;\n fn.flush = flush;\n fn.shutdown = shutdown;\n Object.defineProperty(fn, 'pending', {\n enumerable: true,\n get: () => buffer.length,\n });\n return fn;\n };\n}\n"],"mappings":";;;AAoCA,SAAS,KAAK,IAA2B;CACvC,OAAO,IAAI,SAAS,YAAY;EAE9B,AADc,WAAW,SAAS,EAC9B,CAAC,CAAC,QAAQ;CAChB,CAAC;AACH;AAEA,SAAgB,oBACd,SACqE;CACrE,MAAM,YAAY,SAAS,OAAO,QAAQ;CAC1C,MAAM,aAAa,SAAS,OAAO,cAAc;CACjD,MAAM,gBAAgB,SAAS,iBAAiB;CAChD,MAAM,cAAc,SAAS,OAAO,eAAe;CACnD,MAAM,UAAU,SAAS,OAAO,WAAW;CAC3C,MAAM,iBAAiB,SAAS,OAAO,kBAAkB;CACzD,MAAM,aAAa,SAAS,OAAO,cAAc;CACjD,MAAM,SAAS,SAAS,OAAO,UAAU;C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GAErB,MAAM,cADQ,OAAO,OAAO,GAAG,SACP,CAAC;EAE7B;EAEA,MAAM,sBAAsB;GAC1B,IAAI,cAAc,SAAS,aAAa;GACxC,QAAQ,iBAAiB;IACvB,QAAQ;IACR,WAAW;GACb,GAAG,UAAU;GACb,MAAM,QAAQ;EAChB;EAEA,MAAM,mBAAmB;GACvB,IAAI,eAAe,YAAY;GAC/B,cAAc,YAAY,CAAC,CAAC,cAAc;IACxC,cAAc;IACd,IAAI,YAAY;IAChB,IAAI,OAAO,UAAU,WACnB,WAAW;SACN,IAAI,OAAO,SAAS,GACzB,cAAc;GAElB,CAAC;EACH;EAEA,MAAM,QAAQ,QAAW;GACvB,IAAI,YAAY;GAEhB,IAAI,OAAO,UAAU,eAAe;IAClC,IAAI,eAAe,UAAU;KAC3B,YAAY,CAAC,GAAG,CAAC;KACjB;IACF;IACA,MAAM,UAAU,OAAO,OAAO,GAAG,CAAC;IAClC,YAAY,OAAO;GACrB;GAEA,OAAO,KAAK,GAAG;GACf,IAAI,OAAO,UAAU,WAAW;IAC9B,WAAW;IACX,WAAW;GACb,OACE,cAAc;EAElB;EAEA,MAAM,QAAQ,YAA2B;GACvC,WAAW;GACX,IAAI,aAAa,MAAM;GAEvB,MAAM,WAAW,OAAO;GACxB,IAAI,YAAY,GAAG;GACnB,MAAM,UAAU,OAAO,OAAO,GAAG,QAAQ;GACzC,OAAO,QAAQ,SAAS,GAEtB,MAAM,cADQ,QAAQ,OAAO,GAAG,SACR,CAAC;EAE7B;EAEA,MAAM,WAAW,YAA2B;GAC1C,aAAa;GACb,MAAM,MAAM;EACd;EAEA,MAAM,KAAK;EACX,GAAG,QAAQ;EACX,GAAG,WAAW;EACd,OAAO,eAAe,IAAI,WAAW;GACnC,YAAY;GACZ,WAAW,OAAO;EACpB,CAAC;EACD,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"drain-pipeline.cjs","names":[],"sources":["../src/drain-pipeline.ts"],"sourcesContent":["export interface DrainPipelineOptions<T = unknown> {\n batch?: {\n /** Maximum events per batch. @default 50 */\n size?: number;\n /** Max time an event can stay buffered before flush. @default 5000 */\n intervalMs?: number;\n };\n retry?: {\n /** Total attempts including first try. @default 3 */\n maxAttempts?: number;\n /** Delay strategy between attempts. @default 'exponential' */\n backoff?: 'exponential' | 'linear' | 'fixed';\n /** Base delay for first retry. @default 1000 */\n initialDelayMs?: number;\n /** Max delay cap. @default 30000 */\n maxDelayMs?: number;\n /** Add random jitter to delays. @default true */\n jitter?: boolean;\n };\n /** Max buffered events before dropping. @default 1000 */\n maxBufferSize?: number;\n /** Overflow policy. @default 'oldest' */\n dropPolicy?: 'oldest' | 'newest';\n /** Called when events are dropped from overflow or exhausted retries. */\n onDropped?: (events: T[], error?: Error) => void;\n}\n\nexport interface PipelineDrainFn<T> {\n (ctx: T): void;\n /** Flush all buffered events. */\n flush: () => Promise<void>;\n /** Flush and stop scheduling future timer work. */\n shutdown: () => Promise<void>;\n readonly pending: number;\n}\n\nfunction wait(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n\nexport function createDrainPipeline<T = unknown>(\n options?: DrainPipelineOptions<T>,\n): (drain: (batch: T[]) => void | Promise<void>) => PipelineDrainFn<T> {\n const batchSize = options?.batch?.size ?? 50;\n const intervalMs = options?.batch?.intervalMs ?? 5000;\n const maxBufferSize = options?.maxBufferSize ?? 1000;\n const maxAttempts = options?.retry?.maxAttempts ?? 3;\n const backoff = options?.retry?.backoff ?? 'exponential';\n const initialDelayMs = options?.retry?.initialDelayMs ?? 1000;\n const maxDelayMs = options?.retry?.maxDelayMs ?? 30_000;\n const jitter = options?.retry?.jitter ?? true;\n const dropPolicy = options?.dropPolicy ?? 'oldest';\n const onDropped = options?.onDropped;\n\n if (!Number.isFinite(batchSize) || batchSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.size must be a positive finite number, got: ${batchSize}`,\n );\n }\n if (!Number.isFinite(intervalMs) || intervalMs <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.intervalMs must be a positive finite number, got: ${intervalMs}`,\n );\n }\n if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] maxBufferSize must be a positive finite number, got: ${maxBufferSize}`,\n );\n }\n if (!Number.isFinite(maxAttempts) || maxAttempts <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] retry.maxAttempts must be a positive finite number, got: ${maxAttempts}`,\n );\n }\n\n return (drain: (batch: T[]) => void | Promise<void>): PipelineDrainFn<T> => {\n const buffer: T[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n let activeFlush: Promise<void> | null = null;\n let isShutdown = false;\n\n const clearTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n const computeDelay = (attempt: number): number => {\n const base =\n backoff === 'fixed'\n ? initialDelayMs\n : backoff === 'linear'\n ? initialDelayMs * attempt\n : initialDelayMs * 2 ** (attempt - 1);\n\n const bounded = Math.min(base, maxDelayMs);\n if (!jitter || bounded <= 0) return bounded;\n const factor = 0.5 + Math.random(); // [0.5, 1.5)\n return Math.max(0, Math.round(bounded * factor));\n };\n\n const sendWithRetry = async (batch: T[]): Promise<void> => {\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n await drain(batch);\n return;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt < maxAttempts) {\n await wait(computeDelay(attempt));\n }\n }\n }\n onDropped?.(batch, lastError);\n };\n\n const drainBuffer = async (): Promise<void> => {\n while (buffer.length > 0) {\n const batch = buffer.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const scheduleFlush = () => {\n if (isShutdown || timer || activeFlush) return;\n timer = setTimeout(() => {\n timer = null;\n startFlush();\n }, intervalMs);\n timer.unref?.();\n };\n\n const startFlush = () => {\n if (activeFlush || isShutdown) return;\n activeFlush = drainBuffer().finally(() => {\n activeFlush = null;\n if (isShutdown) return;\n if (buffer.length >= batchSize) {\n startFlush();\n } else if (buffer.length > 0) {\n scheduleFlush();\n }\n });\n };\n\n const push = (ctx: T) => {\n if (isShutdown) return;\n\n if (buffer.length >= maxBufferSize) {\n if (dropPolicy === 'newest') {\n onDropped?.([ctx]);\n return;\n }\n const dropped = buffer.splice(0, 1);\n onDropped?.(dropped);\n }\n\n buffer.push(ctx);\n if (buffer.length >= batchSize) {\n clearTimer();\n startFlush();\n } else {\n scheduleFlush();\n }\n };\n\n const flush = async (): Promise<void> => {\n clearTimer();\n if (activeFlush) await activeFlush;\n\n const snapshot = buffer.length;\n if (snapshot <= 0) return;\n const toFlush = buffer.splice(0, snapshot);\n while (toFlush.length > 0) {\n const batch = toFlush.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const shutdown = async (): Promise<void> => {\n isShutdown = true;\n await flush();\n };\n\n const fn = push as PipelineDrainFn<T>;\n fn.flush = flush;\n fn.shutdown = shutdown;\n Object.defineProperty(fn, 'pending', {\n enumerable: true,\n get: () => buffer.length,\n });\n return fn;\n };\n}\n"],"mappings":";;;AAoCA,SAAS,KAAK,IAA2B;CACvC,OAAO,IAAI,SAAS,YAAY;EAE9B,AADc,WAAW,SAAS,EAC9B,CAAC,CAAC,QAAQ;CAChB,CAAC;AACH;AAEA,SAAgB,oBACd,SACqE;CACrE,MAAM,YAAY,SAAS,OAAO,QAAQ;CAC1C,MAAM,aAAa,SAAS,OAAO,cAAc;CACjD,MAAM,gBAAgB,SAAS,iBAAiB;CAChD,MAAM,cAAc,SAAS,OAAO,eAAe;CACnD,MAAM,UAAU,SAAS,OAAO,WAAW;CAC3C,MAAM,iBAAiB,SAAS,OAAO,kBAAkB;CACzD,MAAM,aAAa,SAAS,OAAO,cAAc;CACjD,MAAM,SAAS,SAAS,OAAO,UAAU;CACzC,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,YAAY,SAAS;CAE3B,IAAI,CAAC,OAAO,SAAS,SAAS,KAAK,aAA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AsB;GAC1B,IAAI,cAAc,SAAS,aAAa;GACxC,QAAQ,iBAAiB;IACvB,QAAQ;IACR,WAAW;GACb,GAAG,UAAU;GACb,MAAM,QAAQ;EAChB;EAEA,MAAM,mBAAmB;GACvB,IAAI,eAAe,YAAY;GAC/B,cAAc,YAAY,CAAC,CAAC,cAAc;IACxC,cAAc;IACd,IAAI,YAAY;IAChB,IAAI,OAAO,UAAU,WACnB,WAAW;SACN,IAAI,OAAO,SAAS,GACzB,cAAc;GAElB,CAAC;EACH;EAEA,MAAM,QAAQ,QAAW;GACvB,IAAI,YAAY;GAEhB,IAAI,OAAO,UAAU,eAAe;IAClC,IAAI,eAAe,UAAU;KAC3B,YAAY,CAAC,GAAG,CAAC;KACjB;IACF;IACA,MAAM,UAAU,OAAO,OAAO,GAAG,CAAC;IAClC,YAAY,OAAO;GACrB;GAEA,OAAO,KAAK,GAAG;GACf,IAAI,OAAO,UAAU,WAAW;IAC9B,WAAW;IACX,WAAW;GACb,OACE,cAAc;EAElB;EAEA,MAAM,QAAQ,YAA2B;GACvC,WAAW;GACX,IAAI,aAAa,MAAM;GAEvB,MAAM,WAAW,OAAO;GACxB,IAAI,YAAY,GAAG;GACnB,MAAM,UAAU,OAAO,OAAO,GAAG,QAAQ;GACzC,OAAO,QAAQ,SAAS,GAAG;IACzB,MAAM,QAAQ,QAAQ,OAAO,GAAG,SAAS;IACzC,MAAM,cAAc,KAAK;GAC3B;EACF;EAEA,MAAM,WAAW,YAA2B;GAC1C,aAAa;GACb,MAAM,MAAM;EACd;EAEA,MAAM,KAAK;EACX,GAAG,QAAQ;EACX,GAAG,WAAW;EACd,OAAO,eAAe,IAAI,WAAW;GACnC,YAAY;GACZ,WAAW,OAAO;EACpB,CAAC;EACD,OAAO;CACT;AACF"}
@@ -49,7 +49,10 @@ function createDrainPipeline(options) {
49
49
  onDropped?.(batch, lastError);
50
50
  };
51
51
  const drainBuffer = async () => {
52
- while (buffer.length > 0) await sendWithRetry(buffer.splice(0, batchSize));
52
+ while (buffer.length > 0) {
53
+ const batch = buffer.splice(0, batchSize);
54
+ await sendWithRetry(batch);
55
+ }
53
56
  };
54
57
  const scheduleFlush = () => {
55
58
  if (isShutdown || timer || activeFlush) return;
@@ -90,7 +93,10 @@ function createDrainPipeline(options) {
90
93
  const snapshot = buffer.length;
91
94
  if (snapshot <= 0) return;
92
95
  const toFlush = buffer.splice(0, snapshot);
93
- while (toFlush.length > 0) await sendWithRetry(toFlush.splice(0, batchSize));
96
+ while (toFlush.length > 0) {
97
+ const batch = toFlush.splice(0, batchSize);
98
+ await sendWithRetry(batch);
99
+ }
94
100
  };
95
101
  const shutdown = async () => {
96
102
  isShutdown = true;
@@ -1 +1 @@
1
- {"version":3,"file":"drain-pipeline.js","names":[],"sources":["../src/drain-pipeline.ts"],"sourcesContent":["export interface DrainPipelineOptions<T = unknown> {\n batch?: {\n /** Maximum events per batch. @default 50 */\n size?: number;\n /** Max time an event can stay buffered before flush. @default 5000 */\n intervalMs?: number;\n };\n retry?: {\n /** Total attempts including first try. @default 3 */\n maxAttempts?: number;\n /** Delay strategy between attempts. @default 'exponential' */\n backoff?: 'exponential' | 'linear' | 'fixed';\n /** Base delay for first retry. @default 1000 */\n initialDelayMs?: number;\n /** Max delay cap. @default 30000 */\n maxDelayMs?: number;\n /** Add random jitter to delays. @default true */\n jitter?: boolean;\n };\n /** Max buffered events before dropping. @default 1000 */\n maxBufferSize?: number;\n /** Overflow policy. @default 'oldest' */\n dropPolicy?: 'oldest' | 'newest';\n /** Called when events are dropped from overflow or exhausted retries. */\n onDropped?: (events: T[], error?: Error) => void;\n}\n\nexport interface PipelineDrainFn<T> {\n (ctx: T): void;\n /** Flush all buffered events. */\n flush: () => Promise<void>;\n /** Flush and stop scheduling future timer work. */\n shutdown: () => Promise<void>;\n readonly pending: number;\n}\n\nfunction wait(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n\nexport function createDrainPipeline<T = unknown>(\n options?: DrainPipelineOptions<T>,\n): (drain: (batch: T[]) => void | Promise<void>) => PipelineDrainFn<T> {\n const batchSize = options?.batch?.size ?? 50;\n const intervalMs = options?.batch?.intervalMs ?? 5000;\n const maxBufferSize = options?.maxBufferSize ?? 1000;\n const maxAttempts = options?.retry?.maxAttempts ?? 3;\n const backoff = options?.retry?.backoff ?? 'exponential';\n const initialDelayMs = options?.retry?.initialDelayMs ?? 1000;\n const maxDelayMs = options?.retry?.maxDelayMs ?? 30_000;\n const jitter = options?.retry?.jitter ?? true;\n const dropPolicy = options?.dropPolicy ?? 'oldest';\n const onDropped = options?.onDropped;\n\n if (!Number.isFinite(batchSize) || batchSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.size must be a positive finite number, got: ${batchSize}`,\n );\n }\n if (!Number.isFinite(intervalMs) || intervalMs <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.intervalMs must be a positive finite number, got: ${intervalMs}`,\n );\n }\n if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] maxBufferSize must be a positive finite number, got: ${maxBufferSize}`,\n );\n }\n if (!Number.isFinite(maxAttempts) || maxAttempts <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] retry.maxAttempts must be a positive finite number, got: ${maxAttempts}`,\n );\n }\n\n return (drain: (batch: T[]) => void | Promise<void>): PipelineDrainFn<T> => {\n const buffer: T[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n let activeFlush: Promise<void> | null = null;\n let isShutdown = false;\n\n const clearTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n const computeDelay = (attempt: number): number => {\n const base =\n backoff === 'fixed'\n ? initialDelayMs\n : backoff === 'linear'\n ? initialDelayMs * attempt\n : initialDelayMs * 2 ** (attempt - 1);\n\n const bounded = Math.min(base, maxDelayMs);\n if (!jitter || bounded <= 0) return bounded;\n const factor = 0.5 + Math.random(); // [0.5, 1.5)\n return Math.max(0, Math.round(bounded * factor));\n };\n\n const sendWithRetry = async (batch: T[]): Promise<void> => {\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n await drain(batch);\n return;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt < maxAttempts) {\n await wait(computeDelay(attempt));\n }\n }\n }\n onDropped?.(batch, lastError);\n };\n\n const drainBuffer = async (): Promise<void> => {\n while (buffer.length > 0) {\n const batch = buffer.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const scheduleFlush = () => {\n if (isShutdown || timer || activeFlush) return;\n timer = setTimeout(() => {\n timer = null;\n startFlush();\n }, intervalMs);\n timer.unref?.();\n };\n\n const startFlush = () => {\n if (activeFlush || isShutdown) return;\n activeFlush = drainBuffer().finally(() => {\n activeFlush = null;\n if (isShutdown) return;\n if (buffer.length >= batchSize) {\n startFlush();\n } else if (buffer.length > 0) {\n scheduleFlush();\n }\n });\n };\n\n const push = (ctx: T) => {\n if (isShutdown) return;\n\n if (buffer.length >= maxBufferSize) {\n if (dropPolicy === 'newest') {\n onDropped?.([ctx]);\n return;\n }\n const dropped = buffer.splice(0, 1);\n onDropped?.(dropped);\n }\n\n buffer.push(ctx);\n if (buffer.length >= batchSize) {\n clearTimer();\n startFlush();\n } else {\n scheduleFlush();\n }\n };\n\n const flush = async (): Promise<void> => {\n clearTimer();\n if (activeFlush) await activeFlush;\n\n const snapshot = buffer.length;\n if (snapshot <= 0) return;\n const toFlush = buffer.splice(0, snapshot);\n while (toFlush.length > 0) {\n const batch = toFlush.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const shutdown = async (): Promise<void> => {\n isShutdown = true;\n await flush();\n };\n\n const fn = push as PipelineDrainFn<T>;\n fn.flush = flush;\n fn.shutdown = shutdown;\n Object.defineProperty(fn, 'pending', {\n enumerable: true,\n get: () => buffer.length,\n });\n return fn;\n };\n}\n"],"mappings":";AAoCA,SAAS,KAAK,IAA2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B,MAAM,UAAU,OAAO,OAAO,GAAG,QAAQ;GACzC,OAAO,QAAQ,SAAS,GAEtB,MAAM,cADQ,QAAQ,OAAO,GAAG,SACR,CAAC;EAE7B;EAEA,MAAM,WAAW,YAA2B;GAC1C,aAAa;GACb,MAAM,MAAM;EACd;EAEA,MAAM,KAAK;EACX,GAAG,QAAQ;EACX,GAAG,WAAW;EACd,OAAO,eAAe,IAAI,WAAW;GACnC,YAAY;GACZ,WAAW,OAAO;EACpB,CAAC;EACD,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"drain-pipeline.js","names":[],"sources":["../src/drain-pipeline.ts"],"sourcesContent":["export interface DrainPipelineOptions<T = unknown> {\n batch?: {\n /** Maximum events per batch. @default 50 */\n size?: number;\n /** Max time an event can stay buffered before flush. @default 5000 */\n intervalMs?: number;\n };\n retry?: {\n /** Total attempts including first try. @default 3 */\n maxAttempts?: number;\n /** Delay strategy between attempts. @default 'exponential' */\n backoff?: 'exponential' | 'linear' | 'fixed';\n /** Base delay for first retry. @default 1000 */\n initialDelayMs?: number;\n /** Max delay cap. @default 30000 */\n maxDelayMs?: number;\n /** Add random jitter to delays. @default true */\n jitter?: boolean;\n };\n /** Max buffered events before dropping. @default 1000 */\n maxBufferSize?: number;\n /** Overflow policy. @default 'oldest' */\n dropPolicy?: 'oldest' | 'newest';\n /** Called when events are dropped from overflow or exhausted retries. */\n onDropped?: (events: T[], error?: Error) => void;\n}\n\nexport interface PipelineDrainFn<T> {\n (ctx: T): void;\n /** Flush all buffered events. */\n flush: () => Promise<void>;\n /** Flush and stop scheduling future timer work. */\n shutdown: () => Promise<void>;\n readonly pending: number;\n}\n\nfunction wait(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n\nexport function createDrainPipeline<T = unknown>(\n options?: DrainPipelineOptions<T>,\n): (drain: (batch: T[]) => void | Promise<void>) => PipelineDrainFn<T> {\n const batchSize = options?.batch?.size ?? 50;\n const intervalMs = options?.batch?.intervalMs ?? 5000;\n const maxBufferSize = options?.maxBufferSize ?? 1000;\n const maxAttempts = options?.retry?.maxAttempts ?? 3;\n const backoff = options?.retry?.backoff ?? 'exponential';\n const initialDelayMs = options?.retry?.initialDelayMs ?? 1000;\n const maxDelayMs = options?.retry?.maxDelayMs ?? 30_000;\n const jitter = options?.retry?.jitter ?? true;\n const dropPolicy = options?.dropPolicy ?? 'oldest';\n const onDropped = options?.onDropped;\n\n if (!Number.isFinite(batchSize) || batchSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.size must be a positive finite number, got: ${batchSize}`,\n );\n }\n if (!Number.isFinite(intervalMs) || intervalMs <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] batch.intervalMs must be a positive finite number, got: ${intervalMs}`,\n );\n }\n if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] maxBufferSize must be a positive finite number, got: ${maxBufferSize}`,\n );\n }\n if (!Number.isFinite(maxAttempts) || maxAttempts <= 0) {\n throw new Error(\n `[autotel/drain-pipeline] retry.maxAttempts must be a positive finite number, got: ${maxAttempts}`,\n );\n }\n\n return (drain: (batch: T[]) => void | Promise<void>): PipelineDrainFn<T> => {\n const buffer: T[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n let activeFlush: Promise<void> | null = null;\n let isShutdown = false;\n\n const clearTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n const computeDelay = (attempt: number): number => {\n const base =\n backoff === 'fixed'\n ? initialDelayMs\n : backoff === 'linear'\n ? initialDelayMs * attempt\n : initialDelayMs * 2 ** (attempt - 1);\n\n const bounded = Math.min(base, maxDelayMs);\n if (!jitter || bounded <= 0) return bounded;\n const factor = 0.5 + Math.random(); // [0.5, 1.5)\n return Math.max(0, Math.round(bounded * factor));\n };\n\n const sendWithRetry = async (batch: T[]): Promise<void> => {\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n await drain(batch);\n return;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt < maxAttempts) {\n await wait(computeDelay(attempt));\n }\n }\n }\n onDropped?.(batch, lastError);\n };\n\n const drainBuffer = async (): Promise<void> => {\n while (buffer.length > 0) {\n const batch = buffer.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const scheduleFlush = () => {\n if (isShutdown || timer || activeFlush) return;\n timer = setTimeout(() => {\n timer = null;\n startFlush();\n }, intervalMs);\n timer.unref?.();\n };\n\n const startFlush = () => {\n if (activeFlush || isShutdown) return;\n activeFlush = drainBuffer().finally(() => {\n activeFlush = null;\n if (isShutdown) return;\n if (buffer.length >= batchSize) {\n startFlush();\n } else if (buffer.length > 0) {\n scheduleFlush();\n }\n });\n };\n\n const push = (ctx: T) => {\n if (isShutdown) return;\n\n if (buffer.length >= maxBufferSize) {\n if (dropPolicy === 'newest') {\n onDropped?.([ctx]);\n return;\n }\n const dropped = buffer.splice(0, 1);\n onDropped?.(dropped);\n }\n\n buffer.push(ctx);\n if (buffer.length >= batchSize) {\n clearTimer();\n startFlush();\n } else {\n scheduleFlush();\n }\n };\n\n const flush = async (): Promise<void> => {\n clearTimer();\n if (activeFlush) await activeFlush;\n\n const snapshot = buffer.length;\n if (snapshot <= 0) return;\n const toFlush = buffer.splice(0, snapshot);\n while (toFlush.length > 0) {\n const batch = toFlush.splice(0, batchSize);\n await sendWithRetry(batch);\n }\n };\n\n const shutdown = async (): Promise<void> => {\n isShutdown = true;\n await flush();\n };\n\n const fn = push as PipelineDrainFn<T>;\n fn.flush = flush;\n fn.shutdown = shutdown;\n Object.defineProperty(fn, 'pending', {\n enumerable: true,\n get: () => buffer.length,\n });\n return fn;\n };\n}\n"],"mappings":";AAoCA,SAAS,KAAK,IAA2B;CACvC,OAAO,IAAI,SAAS,YAAY;EAE9B,AADc,WAAW,SAAS,EAC9B,CAAC,CAAC,QAAQ;CAChB,CAAC;AACH;AAEA,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B,MAAM,QAAQ,QAAQ,OAAO,GAAG,SAAS;IACzC,MAAM,cAAc,KAAK;GAC3B;EACF;EAEA,MAAM,WAAW,YAA2B;GAC1C,aAAa;GACb,MAAM,MAAM;EACd;EAEA,MAAM,KAAK;EACX,GAAG,QAAQ;EACX,GAAG,WAAW;EACd,OAAO,eAAe,IAAI,WAAW;GACnC,YAAY;GACZ,WAAW,OAAO;EACpB,CAAC;EACD,OAAO;CACT;AACF"}
@@ -1,5 +1,5 @@
1
- import { i as getLogger, n as getConfig, o as getValidationConfig, r as getEventsConfig } from "./init-BS2JVkrL.js";
2
- import { i as validateEvent, l as getOrCreateCorrelationId } from "./track-COUuU48p.js";
1
+ import { i as getLogger, n as getConfig, o as getValidationConfig, r as getEventsConfig } from "./init-BvBB45-T.js";
2
+ import { i as validateEvent, l as getOrCreateCorrelationId } from "./track-D7O7oIZa.js";
3
3
  import { t as getOperationContext } from "./operation-context-CKBoA4Qy.js";
4
4
  import { TraceFlags, context, propagation, trace } from "@opentelemetry/api";
5
5
 
@@ -758,4 +758,4 @@ function resetEvents() {
758
758
 
759
759
  //#endregion
760
760
  export { getEvents as n, resetEvents as r, Event as t };
761
- //# sourceMappingURL=event-531asIM6.js.map
761
+ //# sourceMappingURL=event-BEm5IJ8U.js.map