autotel 3.7.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -1
- package/dist/{attributes-ksn4HVbd.js → attributes-CmYpdqCN.js} +2 -11
- package/dist/attributes-CmYpdqCN.js.map +1 -0
- package/dist/{attributes-D3etyRVc.cjs → attributes-PZ5doLgw.cjs} +2 -11
- package/dist/attributes-PZ5doLgw.cjs.map +1 -0
- package/dist/attributes.cjs +1 -1
- package/dist/attributes.d.cts +2 -2
- package/dist/attributes.d.ts +2 -2
- package/dist/attributes.js +1 -1
- package/dist/auto.cjs +2 -2
- package/dist/auto.js +1 -1
- package/dist/correlation-id.cjs +1 -1
- package/dist/correlation-id.js +1 -1
- package/dist/decorators.cjs +1 -1
- package/dist/decorators.js +1 -1
- package/dist/{event-Dlqr4ZNL.cjs → event-BhHREDJk.cjs} +3 -3
- package/dist/{event-Dlqr4ZNL.cjs.map → event-BhHREDJk.cjs.map} +1 -1
- package/dist/{event-_58ryBjh.js → event-ByBTV9M2.js} +3 -3
- package/dist/{event-_58ryBjh.js.map → event-ByBTV9M2.js.map} +1 -1
- package/dist/event.cjs +1 -1
- package/dist/event.js +1 -1
- package/dist/{functional-BGkT8J-h.js → functional-DtI0u4vx.js} +19 -19
- package/dist/functional-DtI0u4vx.js.map +1 -0
- package/dist/{functional-C4CzoVrX.cjs → functional-zpzNLhky.cjs} +4 -4
- package/dist/{functional-C4CzoVrX.cjs.map → functional-zpzNLhky.cjs.map} +1 -1
- package/dist/functional.cjs +1 -1
- package/dist/functional.js +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.js +1 -1
- package/dist/{index-CX0aG1Uh.d.ts → index-Ck06vlW2.d.ts} +2 -32
- package/dist/index-Ck06vlW2.d.ts.map +1 -0
- package/dist/{index-DIWZFKUS.d.cts → index-eKuioqT1.d.cts} +2 -32
- package/dist/index-eKuioqT1.d.cts.map +1 -0
- package/dist/index.cjs +7 -351
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -172
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +4 -172
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -338
- package/dist/index.js.map +1 -1
- package/dist/{init-DJQOdVlN.d.ts → init-B7u-DjxM.d.ts} +57 -2
- package/dist/init-B7u-DjxM.d.ts.map +1 -0
- package/dist/{init-DvapOXCc.cjs → init-BX7AmFRl.cjs} +40 -21
- package/dist/init-BX7AmFRl.cjs.map +1 -0
- package/dist/{init-Ch6t7MNI.js → init-D-jnNMix.js} +39 -20
- package/dist/init-D-jnNMix.js.map +1 -0
- package/dist/{init-CNp-ee80.d.cts → init-DSrRmVnz.d.cts} +57 -2
- package/dist/init-DSrRmVnz.d.cts.map +1 -0
- package/dist/instrumentation.cjs +1 -1
- package/dist/instrumentation.js +1 -1
- package/dist/logger-D3Ej3DII.js +446 -0
- package/dist/logger-D3Ej3DII.js.map +1 -0
- package/dist/logger-thMPLpOG.cjs +487 -0
- package/dist/logger-thMPLpOG.cjs.map +1 -0
- package/dist/logger.cjs +8 -236
- package/dist/logger.js +2 -204
- package/dist/messaging.cjs +1 -1
- package/dist/messaging.js +1 -1
- package/dist/{registry-DfXA3R1L.js → registry-DVSmWg6Y.js} +2 -11
- package/dist/registry-DVSmWg6Y.js.map +1 -0
- package/dist/{registry-JZg2J3RZ.cjs → registry-DYgvb62e.cjs} +1 -16
- package/dist/registry-DYgvb62e.cjs.map +1 -0
- package/dist/semantic-conventions.cjs +1 -1
- package/dist/semantic-conventions.js +1 -1
- package/dist/semantic-helpers.cjs +1 -114
- package/dist/semantic-helpers.cjs.map +1 -1
- package/dist/semantic-helpers.d.cts +1 -114
- package/dist/semantic-helpers.d.cts.map +1 -1
- package/dist/semantic-helpers.d.ts +1 -114
- package/dist/semantic-helpers.d.ts.map +1 -1
- package/dist/semantic-helpers.js +2 -114
- package/dist/semantic-helpers.js.map +1 -1
- package/dist/{track-3HY4NGV-.cjs → track-D59FfpL0.cjs} +2 -2
- package/dist/{track-3HY4NGV-.cjs.map → track-D59FfpL0.cjs.map} +1 -1
- package/dist/{track-nsKVy-pj.js → track-wc0HafS_.js} +6 -6
- package/dist/track-wc0HafS_.js.map +1 -0
- package/dist/webhook.cjs +1 -1
- package/dist/webhook.js +1 -1
- package/dist/workflow-distributed.cjs +1 -1
- package/dist/workflow-distributed.js +1 -1
- package/dist/workflow.cjs +1 -1
- package/dist/workflow.js +1 -1
- package/dist/{yaml-config-B3dQ82GR.cjs → yaml-config-Ck2uB0Dp.cjs} +2 -1
- package/dist/yaml-config-Ck2uB0Dp.cjs.map +1 -0
- package/dist/yaml-config.cjs +1 -1
- package/dist/yaml-config.d.cts +7 -1
- package/dist/yaml-config.d.cts.map +1 -1
- package/dist/yaml-config.d.ts +7 -1
- package/dist/yaml-config.d.ts.map +1 -1
- package/dist/yaml-config.js +1 -0
- package/dist/yaml-config.js.map +1 -1
- package/package.json +1 -1
- package/skills/analyze-traces/SKILL.md +14 -12
- package/skills/autotel-core/SKILL.md +2 -0
- package/skills/autotel-instrumentation/SKILL.md +25 -0
- package/skills/debug-missing-spans/SKILL.md +3 -1
- package/skills/migrate-to-autotel/SKILL.md +24 -23
- package/skills/review-otel-patterns/SKILL.md +9 -6
- package/skills/tune-sampling/SKILL.md +8 -3
- package/src/attributes/builders.ts +2 -20
- package/src/attributes/index.ts +0 -1
- package/src/attributes/registry.ts +2 -9
- package/src/attributes/types.ts +0 -8
- package/src/index.ts +4 -41
- package/src/init.customization.test.ts +71 -0
- package/src/init.ts +167 -40
- package/src/semantic-helpers.test.ts +2 -87
- package/src/semantic-helpers.ts +0 -146
- package/src/yaml-config.test.ts +36 -0
- package/src/yaml-config.ts +10 -1
- package/dist/attributes-D3etyRVc.cjs.map +0 -1
- package/dist/attributes-ksn4HVbd.js.map +0 -1
- package/dist/functional-BGkT8J-h.js.map +0 -1
- package/dist/index-CX0aG1Uh.d.ts.map +0 -1
- package/dist/index-DIWZFKUS.d.cts.map +0 -1
- package/dist/init-CNp-ee80.d.cts.map +0 -1
- package/dist/init-Ch6t7MNI.js.map +0 -1
- package/dist/init-DJQOdVlN.d.ts.map +0 -1
- package/dist/init-DvapOXCc.cjs.map +0 -1
- package/dist/logger.cjs.map +0 -1
- package/dist/logger.js.map +0 -1
- package/dist/registry-DfXA3R1L.js.map +0 -1
- package/dist/registry-JZg2J3RZ.cjs.map +0 -1
- package/dist/track-nsKVy-pj.js.map +0 -1
- package/dist/yaml-config-B3dQ82GR.cjs.map +0 -1
- package/src/gen-ai-cost.test.ts +0 -81
- package/src/gen-ai-cost.ts +0 -145
- package/src/gen-ai-events.test.ts +0 -135
- package/src/gen-ai-events.ts +0 -208
- package/src/gen-ai-metrics.test.ts +0 -96
- package/src/gen-ai-metrics.ts +0 -128
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"functional-BGkT8J-h.js","names":["otelTrace","getConfig","getInitConfig","trace"],"sources":["../src/variable-name-inference.ts","../src/functional.ts"],"sourcesContent":["/**\n * Variable Name Inference Utility\n *\n * Attempts to infer variable names from const/export const assignments\n * by analyzing the call stack and parsing source code.\n *\n * This is a best-effort approach with graceful degradation - if inference\n * fails for any reason, it returns undefined without breaking the application.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\n\ninterface CallLocation {\n file: string;\n line: number;\n column: number;\n}\n\n/**\n * LRU Cache for inferred variable names\n * Key: \"file:line\" (e.g., \"/path/to/file.ts:42\")\n * Value: inferred variable name or undefined\n */\nconst inferenceCache = new Map<string, string | undefined>();\nconst MAX_CACHE_SIZE = 50;\n\n/**\n * Captures the current call stack\n */\nfunction captureStackTrace(): string {\n const originalStackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 10; // Only need first few frames\n\n const err = new Error('Stack trace capture');\n const stack = err.stack || '';\n\n Error.stackTraceLimit = originalStackTraceLimit;\n return stack;\n}\n\n/**\n * Parses the stack trace to find where trace() was called\n *\n * Stack trace format (Node.js):\n * at functionName (file:line:column)\n * at file:line:column\n *\n * We skip frames until we find one that's NOT in functional.ts or this file.\n * We also need to skip one additional frame (the trace/span/instrument function itself)\n * to get to the actual user code.\n */\nfunction parseCallLocation(stack: string): CallLocation | undefined {\n const lines = stack.split('\\n');\n let skippedExternalFrame = false;\n\n for (const line of lines) {\n // Skip if line contains this file or functional.ts (internal frames)\n // Be specific about the filename to avoid matching test files\n if (\n line.includes('variable-name-inference.ts') ||\n line.includes('variable-name-inference.js') ||\n line.includes('functional.ts') ||\n line.includes('functional.js')\n ) {\n continue;\n }\n\n // Match various stack trace formats\n // Format 1: at functionName (file:line:column)\n // Format 2: at file:line:column\n const match =\n line.match(/at\\s+(?:.*\\s+)?\\(?([^:]+):(\\d+):(\\d+)\\)?/) ||\n line.match(/^.*?([^:]+):(\\d+):(\\d+)/);\n\n if (match) {\n let filePath = match[1]!.trim();\n\n // Handle file:// URLs (convert to paths)\n if (filePath.startsWith('file://')) {\n try {\n filePath = fileURLToPath(filePath);\n } catch {\n continue;\n }\n }\n\n // Skip the first external frame (the trace/span function itself)\n // We want the frame where the user CALLS trace(), not inside trace()\n if (!skippedExternalFrame) {\n skippedExternalFrame = true;\n continue;\n }\n\n return {\n file: filePath,\n line: Number.parseInt(match[2]!, 10),\n column: Number.parseInt(match[3]!, 10),\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Reads a specific line from a source file\n */\nfunction readSourceLine(\n filePath: string,\n lineNumber: number,\n): string | undefined {\n try {\n // Check if we can access the file system (not available in edge runtimes)\n if (typeof readFileSync !== 'function') {\n return undefined;\n }\n\n const content = readFileSync(filePath, 'utf8');\n const lines = content.split('\\n');\n\n // Line numbers are 1-based\n return lines[lineNumber - 1];\n } catch {\n // File doesn't exist, permission denied, or other error\n return undefined;\n }\n}\n\n/**\n * Extracts variable name from source code line using regex patterns\n *\n * Supported patterns:\n * - const varName = anyFunction(\n * - export const varName = anyFunction(\n * - let varName = anyFunction(\n * - var varName = anyFunction(\n *\n * Note: This won't work with destructuring assignments or complex patterns\n */\nfunction extractVariableName(sourceLine: string): string | undefined {\n // Remove leading/trailing whitespace\n const trimmed = sourceLine.trim();\n\n // Pattern: (export)? (const|let|var) varName = anyFunctionCall(\n // We match any function call, not just trace(), to support wrapper functions\n const patterns = [\n // export const varName = anyFunction(\n /export\\s+const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // const varName = anyFunction(\n /const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export let varName = anyFunction(\n /export\\s+let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // let varName = anyFunction(\n /let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export var varName = anyFunction(\n /export\\s+var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // var varName = anyFunction(\n /var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n ];\n\n for (const pattern of patterns) {\n const match = trimmed.match(pattern);\n if (match && match[1]) {\n return match[1];\n }\n }\n\n return undefined;\n}\n\n/**\n * Adds an entry to the cache with LRU eviction\n */\nfunction cacheInference(key: string, value: string | undefined): void {\n // If cache is full, remove oldest entry (first entry in Map)\n if (inferenceCache.size >= MAX_CACHE_SIZE) {\n const firstKey = inferenceCache.keys().next().value;\n if (firstKey) {\n inferenceCache.delete(firstKey);\n }\n }\n\n inferenceCache.set(key, value);\n}\n\n/**\n * Main entry point: Attempts to infer the variable name from the call stack\n *\n * This function:\n * 1. Captures the call stack\n * 2. Parses it to find where trace() was called (file + line)\n * 3. Reads that line from the source file\n * 4. Extracts the variable name using regex\n *\n * Returns undefined if inference fails at any step (graceful degradation).\n * Results are cached to avoid repeated file I/O.\n *\n * @returns The inferred variable name, or undefined if inference failed\n */\nexport function inferVariableNameFromCallStack(): string | undefined {\n try {\n // Capture stack trace\n const stack = captureStackTrace();\n\n // Parse stack to find trace() call location\n const callLocation = parseCallLocation(stack);\n if (!callLocation) {\n return undefined;\n }\n\n // Check cache\n const cacheKey = `${callLocation.file}:${callLocation.line}`;\n if (inferenceCache.has(cacheKey)) {\n return inferenceCache.get(cacheKey);\n }\n\n // Read source line\n const sourceLine = readSourceLine(callLocation.file, callLocation.line);\n if (!sourceLine) {\n return undefined;\n }\n\n // Extract variable name\n const variableName = extractVariableName(sourceLine);\n\n // Cache result (even if undefined, to avoid repeated failed attempts)\n cacheInference(cacheKey, variableName);\n\n return variableName;\n } catch {\n // Graceful degradation - don't break the app if inference fails\n return undefined;\n }\n}\n\n/**\n * Clears the inference cache (useful for testing)\n */\nexport function clearInferenceCache(): void {\n inferenceCache.clear();\n}\n","/**\n * Functional API for non-class code\n *\n * Three approaches for different use cases:\n * 1. trace() - Zero-ceremony HOF for single functions\n * 2. withTracing() - Middleware-style composable wrapper\n * 3. instrument() - Batch auto-instrumentation for modules\n *\n * @example trace() - Single function\n * ```typescript\n * export const createUser = trace(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example withTracing() - Composable middleware\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example instrument() - Batch instrumentation\n * ```typescript\n * export default instrument({\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { }\n * }, { serviceName: 'user' })\n * ```\n */\n\nimport {\n SpanStatusCode,\n trace as otelTrace,\n context,\n propagation,\n type Span,\n} from '@opentelemetry/api';\nimport { getConfig } from './config';\nimport { getConfig as getInitConfig, getSdk } from './init';\nimport {\n type Sampler,\n type SamplingContext,\n AlwaysSampler,\n AUTOTEL_SAMPLING_TAIL_KEEP,\n AUTOTEL_SAMPLING_TAIL_EVALUATED,\n} from './sampling';\nimport { getEventQueue } from './track';\nimport type { TraceContext } from './trace-context';\nimport {\n createTraceContext,\n enterOrRun,\n getActiveContextWithBaggage,\n getContextStorage,\n} from './trace-context';\nimport { setSpanName } from './trace-helpers';\nimport { runInOperationContext } from './operation-context';\nimport { inferVariableNameFromCallStack } from './variable-name-inference';\n\n/**\n * Complete trace context containing trace identifiers and span methods\n *\n * The ctx parameter in trace() functions provides:\n * - traceId, spanId, correlationId from the active span\n * - Span manipulation methods (setAttribute, setAttributes, setStatus, recordException)\n *\n * For custom context, access it directly in your functions (standard OpenTelemetry pattern).\n *\n * @example\n * ```typescript\n * import { trace } from 'autotel'\n *\n * export const createUser = trace(ctx => async (data: CreateUserData) => {\n * // Get custom context directly (standard OTel approach)\n * const userId = getCurrentUserId()\n * const tenantId = getCurrentTenant()\n *\n * // Use ctx for span operations and trace IDs\n * ctx.setAttribute('user.id', data.id)\n * ctx.setAttribute('user.tenant', tenantId)\n * console.log(ctx.traceId) // Trace IDs available\n * })\n * ```\n */\nexport type { TraceContext } from './trace-context';\n\n/**\n * Helper type to extract function signature from factory pattern\n * This helps TypeScript infer types correctly for factory functions\n */\ntype ExtractFunctionSignature<T> = T extends (ctx: TraceContext) => infer F\n ? F extends (...args: infer Args) => infer Return\n ? (...args: Args) => Return\n : never\n : never;\n\n/**\n * Helper type to exclude functions that return functions from immediate execution overloads\n */\ntype ExcludeFactoryReturn<T> = T extends (ctx: TraceContext) => infer F\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n F extends (...args: any[]) => any\n ? never\n : T\n : T;\n\ntype GenericFunction = (...args: unknown[]) => unknown;\n\nconst FACTORY_NAME_HINTS = new Set([\n 'ctx',\n '_ctx',\n 'context',\n 'tracecontext',\n 'tracectx',\n]);\nconst TRACE_FACTORY_SET = new WeakSet<object>();\n\nconst SINGLE_LINE_COMMENT_REGEX = /\\/\\/.*$/gm;\nconst MULTI_LINE_COMMENT_REGEX = /\\/\\*[\\s\\S]*?\\*\\//gm;\nconst PARAM_TOKEN_SANITIZE_REGEX = new RegExp(String.raw`[{}\\[\\]\\s]`, 'g');\n\nfunction markAsTraceFactory(fn: object): void {\n TRACE_FACTORY_SET.add(fn);\n}\n\nfunction hasFactoryMark(fn: object): boolean {\n return TRACE_FACTORY_SET.has(fn);\n}\n\nfunction sanitizeParameterToken(token: string): string {\n const [firstToken] = token.split('=');\n return (firstToken ?? '').replaceAll(PARAM_TOKEN_SANITIZE_REGEX, '').trim();\n}\n\nfunction getFirstParameterToken(fn: GenericFunction): string | null {\n let source = Function.prototype.toString.call(fn);\n source = source\n .replaceAll(MULTI_LINE_COMMENT_REGEX, '')\n .replaceAll(SINGLE_LINE_COMMENT_REGEX, '')\n .trim();\n\n // Arrow functions\n const arrowMatch = source.match(\n /^(?:async\\s*)?(?:\\(([^)]*)\\)|([^=()]+))\\s*=>/,\n );\n if (arrowMatch) {\n const params = (arrowMatch[1] ?? arrowMatch[2] ?? '').split(',');\n const first = params[0]?.trim();\n if (first) {\n return sanitizeParameterToken(first);\n }\n return null;\n }\n\n // Function declarations/expressions\n const functionMatch = source.match(/^[^(]*\\(([^)]*)\\)/);\n if (functionMatch) {\n const params = functionMatch[1]?.split(',');\n const first = params?.[0]?.trim();\n if (first) {\n return sanitizeParameterToken(first);\n }\n }\n\n return null;\n}\n\n/**\n * Symbol that explicitly marks a function as immediate-execution-with-ctx\n * (`(ctx) => result`), bypassing parameter-name introspection. Library\n * authors who wrap user handlers — like `autotel-aws/lambda`'s `wrapHandler`\n * — should mark their inner trace function with this so dispatch survives\n * downstream bundlers that minify parameter names.\n */\nconst IMMEDIATE_EXECUTION_SYMBOL = Symbol.for('autotel.immediate-execution');\n\ntype ImmediateExecutionFlag = {\n [IMMEDIATE_EXECUTION_SYMBOL]?: true;\n};\n\nfunction hasImmediateExecutionMark(fn: unknown): boolean {\n return (\n typeof fn === 'function' &&\n (fn as ImmediateExecutionFlag)[IMMEDIATE_EXECUTION_SYMBOL] === true\n );\n}\n\n/**\n * Mark a function as immediate-execution-with-ctx so `trace(name, fn)`\n * dispatch doesn't depend on the first parameter being named `ctx`.\n *\n * Necessary when the function will be bundled by a minifier (esbuild,\n * terser, etc.) that renames identifiers. The name-allowlist heuristic in\n * `looksLikeTraceFactory` cannot recover from that; the marker can.\n *\n * @example\n * ```ts\n * import { markAsImmediate, trace } from 'autotel';\n *\n * const inner = markAsImmediate(async (ctx) => {\n * ctx.setAttribute('user.id', '123');\n * return { ok: true };\n * });\n * const result = await trace('user.read', inner);\n * ```\n */\nexport function markAsImmediate<F>(fn: F): F {\n if (typeof fn === 'function') {\n (fn as unknown as ImmediateExecutionFlag)[IMMEDIATE_EXECUTION_SYMBOL] =\n true;\n }\n return fn;\n}\n\nfunction looksLikeTraceFactory(fn: GenericFunction): boolean {\n if (hasFactoryMark(fn)) {\n return true;\n }\n if (hasImmediateExecutionMark(fn)) {\n return true;\n }\n\n if (fn.length === 0) {\n if (!isAsyncFunction(fn)) {\n try {\n const result = fn();\n return typeof result === 'function';\n } catch {\n return false;\n }\n }\n return false;\n }\n\n const firstParam = getFirstParameterToken(fn);\n if (!firstParam) {\n return false;\n }\n\n const normalized = firstParam.toLowerCase();\n if (\n FACTORY_NAME_HINTS.has(normalized) ||\n normalized.startsWith('ctx') ||\n normalized.startsWith('_ctx') ||\n normalized.startsWith('trace') ||\n normalized.endsWith('ctx') || // Match baseCtx, spanCtx, etc.\n normalized.includes('context') // Match traceContext, spanContext, etc.\n ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Check if a function that takes ctx returns another function (factory pattern)\n * vs returning a value directly (immediate execution pattern)\n *\n * IMPORTANT: For async functions, we skip probing entirely and assume immediate execution.\n * This is because:\n * - Factory pattern: `(ctx) => async (...args) => result` - outer function is SYNC\n * - Immediate execution: `async (ctx) => result` - function itself is ASYNC\n *\n * Probing async functions by executing them causes side effects (like creating orphan spans)\n * because the async function starts executing synchronously until the first await.\n */\nfunction isFactoryReturningFunction(\n fnWithCtx: (ctx: TraceContext) => unknown,\n): boolean {\n // Async functions with ctx parameter are always immediate execution\n // because factory patterns have a sync outer function that returns the async inner\n if (isAsyncFunction(fnWithCtx)) {\n return false;\n }\n\n try {\n const result = fnWithCtx(createDummyCtx());\n return typeof result === 'function';\n } catch {\n // If the function throws when called with dummy ctx, assume it's immediate execution\n // since factory functions typically just return a function and don't execute logic\n return false;\n }\n}\n\nfunction isTraceFactoryFunction<TArgs extends unknown[], TReturn>(\n fn:\n | ((...args: TArgs) => TReturn)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn),\n): fn is (ctx: TraceContext) => (...args: TArgs) => TReturn {\n if (typeof fn !== 'function') {\n return false;\n }\n\n if (hasFactoryMark(fn)) {\n return true;\n }\n\n if (looksLikeTraceFactory(fn as GenericFunction)) {\n markAsTraceFactory(fn);\n return true;\n }\n\n return false;\n}\n\nfunction ensureTraceFactory<TArgs extends unknown[], TReturn>(\n fnOrFactory:\n | ((...args: TArgs) => TReturn | Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn>),\n): (ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn> {\n if (isTraceFactoryFunction(fnOrFactory)) {\n return fnOrFactory;\n }\n\n const plainFn = fnOrFactory as (...args: TArgs) => TReturn | Promise<TReturn>;\n const factory = (ctx: TraceContext) => {\n void ctx;\n return plainFn;\n };\n markAsTraceFactory(factory);\n return factory;\n}\n\ntype WrappedFunction<TArgs extends unknown[], TReturn> = (\n ...args: TArgs\n) => TReturn | Promise<TReturn>;\n\nfunction wrapFactoryWithTracing<TArgs extends unknown[], TReturn>(\n fnOrFactory:\n | ((...args: TArgs) => TReturn | Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn>),\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n const factory = ensureTraceFactory(fnOrFactory);\n\n // Get the inner function (the actual function being traced)\n const sampleFn = factory(createDummyCtx());\n\n // Infer function name with priority:\n // 1. Explicit variable name (from instrument() or explicit name parameter)\n // 2. Inner function name (named function expressions - e.g., \"async function createUser\")\n // 3. Variable name from call stack (inferred from const assignment, for arrow functions)\n // 4. Factory function name (for cases where factory itself is named)\n const innerFunctionName = inferFunctionName(\n sampleFn as InstrumentableFunction,\n );\n const callStackVariableName = innerFunctionName\n ? undefined\n : inferVariableNameFromCallStack(); // Only infer from call stack if no inner function name\n const factoryName = inferFunctionName(factory as InstrumentableFunction);\n const effectiveVariableName =\n variableName || innerFunctionName || callStackVariableName || factoryName;\n\n const useAsyncWrapper = isAsyncFunction(sampleFn);\n\n if (useAsyncWrapper) {\n return wrapWithTracing(\n factory as (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n }\n\n return wrapWithTracingSync(\n factory as (ctx: TraceContext) => (...args: TArgs) => TReturn,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Common options for functional tracing\n */\nexport interface TracingOptions<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> {\n /**\n * Span name (highest priority)\n * If provided, this is used as the span name\n */\n name?: string;\n\n /**\n * Service name (used to compose final span name)\n * If name not provided, span name becomes: ${serviceName}.${functionName}\n */\n serviceName?: string;\n\n /**\n * Sampling strategy\n * @default AlwaysSampler\n */\n sampler?: Sampler;\n\n /**\n * Enable metrics collection (counter, histogram)\n * @default false\n */\n withMetrics?: boolean;\n\n /**\n * Extract attributes from function arguments\n */\n attributesFromArgs?: (args: TArgs) => Record<string, unknown>;\n\n /**\n * Extract attributes from function result\n */\n attributesFromResult?: (result: TReturn) => Record<string, unknown>;\n\n /**\n * Capture the function arguments onto the span as `autotel.input`\n * (JSON, truncated). One arg is captured directly; multiple are captured as\n * an array. Off by default — opt in per call. Tools (visualizers, devtools)\n * read this alongside `ai.toolCall.args` to show function I/O uniformly.\n * Avoid on args with secrets/PII, or pair with a redacting processor.\n */\n captureInput?: boolean;\n\n /**\n * Capture the function return value onto the span as `autotel.output`\n * (JSON, truncated). Off by default. Same caveats as {@link captureInput}.\n */\n captureOutput?: boolean;\n\n /**\n * Start a new root span instead of creating a child\n * Useful for serverless entry points\n * @default false\n */\n startNewRoot?: boolean;\n\n /**\n * Flush events queue when span ends\n * Only flushes on root spans (to avoid excessive flushing)\n * @default true\n */\n flushOnRootSpanEnd?: boolean;\n\n /**\n * Span kind for semantic convention compliance\n * Used for messaging (PRODUCER/CONSUMER), HTTP (CLIENT/SERVER), etc.\n * @default SpanKind.INTERNAL\n */\n spanKind?: import('@opentelemetry/api').SpanKind;\n}\n\n/**\n * Options for instrument() batch instrumentation\n */\nexport interface InstrumentOptions<\n T extends Record<string, InstrumentableFunction> = Record<\n string,\n InstrumentableFunction\n >,\n> extends TracingOptions {\n /** Functions to instrument */\n functions: T;\n /**\n * Per-function configuration overrides\n */\n overrides?: Record<string, Partial<TracingOptions>>;\n\n /**\n * Functions to skip (won't be instrumented)\n * Supports:\n * - String keys: 'functionName'\n * - RegExp: /^_internal/\n * - Predicate: (key, fn) => boolean\n *\n * By default, functions starting with _ are skipped\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[];\n}\n\n// Maximum error message length to prevent span bloat\nconst MAX_ERROR_MESSAGE_LENGTH = 500;\n\nfunction createDummyCtx<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> {\n // `recordException` / `addEvent` are no-op shims kept for the same\n // compatibility window as `createTraceContext` (see trace-context.ts).\n return {\n traceId: '',\n spanId: '',\n correlationId: '',\n setAttribute: () => {},\n setAttributes: () => {},\n setStatus: () => {},\n recordException: () => {},\n addEvent: () => {},\n addLink: () => {},\n addLinks: () => {},\n updateName: () => {},\n isRecording: () => false,\n getBaggage: () => {},\n setBaggage: () => '',\n deleteBaggage: () => {},\n getAllBaggage: () => new Map(),\n } as unknown as TraceContext<TBaggage>;\n}\n\n/** Attribute keys for opt-in function I/O capture (see TracingOptions). */\nconst AUTOTEL_INPUT_ATTR = 'autotel.input';\nconst AUTOTEL_OUTPUT_ATTR = 'autotel.output';\nconst CAPTURE_MAX_CHARS = 4096;\n\n/** JSON-serialize a captured value, defensively (truncate, swallow cycles). */\nfunction serializeCapture(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n try {\n const json = typeof value === 'string' ? value : JSON.stringify(value);\n if (json === undefined) return undefined;\n return json.length > CAPTURE_MAX_CHARS\n ? `${json.slice(0, CAPTURE_MAX_CHARS)}…[truncated]`\n : json;\n } catch {\n return undefined;\n }\n}\n\n/** `autotel.input` from args (single arg captured directly, else the array). */\nfunction captureInputAttrs(\n args: unknown[],\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(args.length === 1 ? args[0] : args);\n return s === undefined ? {} : { [AUTOTEL_INPUT_ATTR]: s };\n}\n\n/** `autotel.output` from the return value. */\nfunction captureOutputAttrs(\n result: unknown,\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(result);\n return s === undefined ? {} : { [AUTOTEL_OUTPUT_ATTR]: s };\n}\n\nfunction isAsyncFunction(fn: unknown): boolean {\n return typeof fn === 'function' && fn.constructor?.name === 'AsyncFunction';\n}\n\n// Symbol to prevent double-instrumentation (idempotency flag)\nconst INSTRUMENTED_SYMBOL = Symbol.for('autotel.functional.instrumented');\n\ntype InstrumentedFlag = {\n [INSTRUMENTED_SYMBOL]?: true;\n};\n\nfunction hasInstrumentationFlag(value: unknown): value is InstrumentedFlag {\n return (\n (typeof value === 'function' || typeof value === 'object') &&\n value !== null &&\n Boolean((value as InstrumentedFlag)[INSTRUMENTED_SYMBOL])\n );\n}\n\n/**\n * Truncate error message to prevent span bloat\n */\nfunction truncateErrorMessage(message: string): string {\n if (message.length <= MAX_ERROR_MESSAGE_LENGTH) {\n return message;\n }\n return `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}... (truncated)`;\n}\n\ntype InstrumentableFunction<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> = ((...args: TArgs) => TReturn | Promise<TReturn>) & {\n displayName?: string;\n name?: string;\n};\n\n/**\n * Try to infer function name from function properties\n * Checks for displayName, name, or other metadata that might be set\n */\nfunction inferFunctionName<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(fn: InstrumentableFunction<TArgs, TReturn>): string | undefined {\n // Check for displayName property (sometimes set by bundlers)\n const displayName = (fn as { displayName?: string }).displayName;\n if (displayName) {\n return displayName;\n }\n\n // Check function.name (works for named functions and modern arrow function assignment)\n // Note: Empty string is falsy, so this handles both undefined and ''\n if (fn.name && fn.name !== 'anonymous' && fn.name !== '') {\n return fn.name;\n }\n\n // Try to extract name from function source (for function declarations)\n const source = Function.prototype.toString.call(fn);\n const match = source.match(/function\\s+([^(\\s]+)/);\n if (match && match[1] && match[1] !== 'anonymous') {\n return match[1];\n }\n\n return undefined;\n}\n\n/**\n * Determine span name using priority:\n * 1. Explicit name option\n * 2. serviceName + functionName\n * 3. Inferred from function/variable name (including stack trace fallback)\n * 4. Fallback to 'unknown'\n */\nfunction getSpanName<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fn: InstrumentableFunction<TArgs, TReturn>,\n variableName?: string,\n): string {\n // 1. Explicit name\n if (options.name) {\n return options.name;\n }\n\n // 2. Try variable name, function name, or function properties\n let fnName = variableName || inferFunctionName(fn);\n\n // Default to 'anonymous' if still no name\n fnName = fnName || 'anonymous';\n\n // 2. serviceName + functionName\n if (options.serviceName) {\n return `${options.serviceName}.${fnName}`;\n }\n\n // 3. Inferred from function name\n if (fnName && fnName !== 'anonymous') {\n return fnName;\n }\n\n // 4. Fallback\n return 'unknown';\n}\n\n/**\n * Check if function should be skipped\n */\nfunction shouldSkip(\n key: string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n fn: Function,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[],\n): boolean {\n // Default: skip functions starting with _\n if (key.startsWith('_')) {\n return true;\n }\n\n if (!skip || skip.length === 0) {\n return false;\n }\n\n for (const rule of skip) {\n if (typeof rule === 'string' && key === rule) {\n return true;\n } else if (rule instanceof RegExp && rule.test(key)) {\n return true;\n } else if (typeof rule === 'function' && rule(key, fn)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Get current trace context value (internal helper)\n *\n * Returns base context (trace IDs) + span methods from the active span.\n */\nfunction getCtxValue<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> | null {\n const activeSpan = otelTrace.getActiveSpan();\n if (!activeSpan) return null;\n\n // Use shared utility to create trace context\n return createTraceContext<TBaggage>(activeSpan);\n}\n\n/**\n * Context object that lazily evaluates the active span on property access\n *\n * Access trace context directly without function call syntax.\n *\n * @example\n * ```typescript\n * import { trace, ctx } from 'autotel'\n *\n * export const createUser = trace(async (data) => {\n * // Direct property access - no function call!\n * if (ctx.traceId) {\n * ctx.setAttribute('user.id', data.id)\n * console.log('Trace:', ctx.traceId)\n * }\n * })\n * ```\n */\nexport const ctx = new Proxy(\n {},\n {\n get(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return ctxValue[prop as keyof typeof ctxValue];\n },\n\n has(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return false;\n }\n return prop in ctxValue;\n },\n\n ownKeys() {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return [];\n }\n return Object.keys(ctxValue);\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return Object.getOwnPropertyDescriptor(ctxValue, prop);\n },\n },\n);\n\n/**\n * Core tracing wrapper for async functions (internal implementation)\n */\nfunction wrapWithTracing<TArgs extends unknown[], TReturn>(\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): (...args: TArgs) => Promise<TReturn> {\n // Idempotency check: if already instrumented, return as-is\n if (hasInstrumentationFlag(fnFactory)) {\n // Already instrumented - proceed\n }\n\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n const sampler = options.sampler || new AlwaysSampler();\n\n const tempFn = fnFactory(createDummyCtx());\n const spanName = getSpanName(options, tempFn, variableName);\n\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n const wrappedFunction = async function wrappedFunction(\n this: unknown,\n ...args: TArgs\n ): Promise<TReturn> {\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args,\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n const needsTailSampling =\n 'needsTailSampling' in sampler &&\n typeof sampler.needsTailSampling === 'function'\n ? sampler.needsTailSampling()\n : false;\n\n if (!shouldSample && !needsTailSampling) {\n const fn = fnFactory(createDummyCtx());\n return await fn.call(this, ...args);\n }\n\n const startTime = performance.now();\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const shouldAutoFlush =\n options.flushOnRootSpanEnd ?? getInitConfig()?.flushOnRootSpanEnd ?? true;\n const shouldAutoFlushSpans = getInitConfig()?.forceFlushOnShutdown ?? false;\n\n const flushIfNeeded = async () => {\n if (!shouldAutoFlush || !isRootSpan) return;\n\n try {\n // Flush events queue\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n await queue.flush();\n }\n\n // Flush OpenTelemetry spans if enabled\n if (shouldAutoFlushSpans) {\n const sdk = getSdk();\n if (sdk) {\n try {\n // Type assertion needed as getTracerProvider is not in the public NodeSDK interface\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const sdkAny = sdk as any;\n if (typeof sdkAny.getTracerProvider === 'function') {\n const tracerProvider = sdkAny.getTracerProvider();\n if (\n tracerProvider &&\n typeof tracerProvider.forceFlush === 'function'\n ) {\n await tracerProvider.forceFlush();\n }\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n }\n }\n } catch (error) {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n }\n };\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n async (span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(spanName, async () => {\n let shouldKeepSpan = true;\n\n setSpanName(span, spanName);\n\n // Initialize context storage with the active context BEFORE creating trace context\n const initialContext = context.active();\n const contextStorage = getContextStorage();\n if (!contextStorage.getStore()) {\n enterOrRun(contextStorage, initialContext);\n }\n\n const ctxValue = createTraceContext(span);\n const fn = fnFactory(ctxValue);\n const argsAttributes = {\n ...captureInputAttrs(args, options.captureInput),\n ...(options.attributesFromArgs\n ? options.attributesFromArgs(args)\n : {}),\n };\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: unknown,\n ) => {\n if (\n needsTailSampling &&\n 'shouldKeepTrace' in sampler &&\n typeof sampler.shouldKeepTrace === 'function'\n ) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n const onSuccess = async (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n const resultAttributes = {\n ...captureOutputAttrs(result, options.captureOutput),\n ...(options.attributesFromResult\n ? options.attributesFromResult(result)\n : {}),\n };\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n ...argsAttributes,\n ...resultAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n await flushIfNeeded();\n return result;\n };\n\n const onError = async (error: unknown): Promise<never> => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n ...argsAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n await flushIfNeeded();\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n // Execute the user's function with the updated context\n // This ensures ctx.setBaggage() changes are visible to OpenTelemetry operations\n // (like BaggageSpanProcessor, child spans, etc.)\n // We use getActiveContextWithBaggage() which checks the stored context,\n // so if baggage is set during execution, it will be picked up\n const executeWithContext = async () => {\n // Get the current context (may have been updated by ctx.setBaggage())\n const currentContext = getActiveContextWithBaggage();\n // Establish the context in OpenTelemetry's context manager\n return context.with(currentContext, async () => {\n return fn.call(this, ...args);\n });\n };\n const result = await executeWithContext();\n\n return await onSuccess(result);\n } catch (error) {\n await onError(error);\n throw error;\n }\n });\n },\n );\n };\n\n // Mark as instrumented to prevent double-wrapping\n (wrappedFunction as InstrumentedFlag)[INSTRUMENTED_SYMBOL] = true;\n\n Object.defineProperty(wrappedFunction, 'name', {\n value: tempFn.name || 'trace',\n configurable: true,\n });\n\n return wrappedFunction;\n}\n\n/**\n * Core tracing wrapper for sync functions (internal implementation)\n */\nfunction wrapWithTracingSync<TArgs extends unknown[], TReturn>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): (...args: TArgs) => TReturn {\n // Idempotency check: if already instrumented, return as-is\n if (hasInstrumentationFlag(fnFactory)) {\n // If already instrumented, we need to extract the original factory\n // For now, we'll just proceed - this edge case is handled by the wrapped function check\n }\n\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n const sampler = options.sampler || new AlwaysSampler();\n\n // We need to get a reference function name for span naming\n // Create a minimal dummy context just for extracting the function name\n // This won't affect actual tracing - we use the real context inside the span\n const tempFn = fnFactory(createDummyCtx());\n const spanName = getSpanName(options, tempFn, variableName);\n\n // Metrics setup (if enabled)\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n // Return wrapped function\n function wrappedFunction(\n this: unknown,\n ...args: TArgs\n ): TReturn | Promise<TReturn> {\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args,\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n const needsTailSampling =\n 'needsTailSampling' in sampler &&\n typeof sampler.needsTailSampling === 'function'\n ? sampler.needsTailSampling()\n : false;\n\n // If not sampling and no tail sampling, execute without tracing\n if (!shouldSample && !needsTailSampling) {\n const fn = fnFactory(createDummyCtx());\n return fn.call(this, ...args);\n }\n\n const startTime = performance.now();\n\n // Track if this is a root span for auto-flush\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const shouldAutoFlush =\n options.flushOnRootSpanEnd ?? getInitConfig()?.flushOnRootSpanEnd ?? true;\n const shouldAutoFlushSpans = getInitConfig()?.forceFlushOnShutdown ?? false;\n\n // Note: This is intentionally fire-and-forget (void) for synchronous functions.\n // Synchronous functions cannot await flush completion without blocking execution.\n // The forceFlushOnShutdown guarantee only applies to async functions.\n const flushIfNeeded = () => {\n if (!shouldAutoFlush || !isRootSpan) return;\n\n // Flush events queue\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n void queue.flush().catch((error) => {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n });\n }\n\n // Flush OpenTelemetry spans if enabled\n if (shouldAutoFlushSpans) {\n const sdk = getSdk();\n if (sdk) {\n try {\n // Type assertion needed as getTracerProvider is not in the public NodeSDK interface\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const sdkAny = sdk as any;\n if (typeof sdkAny.getTracerProvider === 'function') {\n const tracerProvider = sdkAny.getTracerProvider();\n if (\n tracerProvider &&\n typeof tracerProvider.forceFlush === 'function'\n ) {\n void tracerProvider.forceFlush().catch((error: unknown) => {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Span flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n });\n }\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n }\n }\n };\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n (span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(spanName, () => {\n let shouldKeepSpan = true;\n\n // Store span name for trace context helpers\n setSpanName(span, spanName);\n\n // Create trace context for this span using shared utility\n const ctxValue = createTraceContext(span);\n\n // Get the actual function from the factory\n const fn = fnFactory(ctxValue);\n\n // Extract attributes only when actually tracing\n // This avoids expensive preprocessing when sampling rejects the trace\n const argsAttributes = {\n ...captureInputAttrs(args, options.captureInput),\n ...(options.attributesFromArgs\n ? options.attributesFromArgs(args)\n : {}),\n };\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: unknown,\n ) => {\n if (\n needsTailSampling &&\n 'shouldKeepTrace' in sampler &&\n typeof sampler.shouldKeepTrace === 'function'\n ) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n const onSuccess = (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n const resultAttributes = {\n ...captureOutputAttrs(result, options.captureOutput),\n ...(options.attributesFromResult\n ? options.attributesFromResult(result)\n : {}),\n };\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n ...argsAttributes,\n ...resultAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n void flushIfNeeded();\n return result;\n };\n\n const onError = (error: unknown): never => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n ...argsAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n void flushIfNeeded();\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n const result = fn.call(this, ...args);\n\n if (result instanceof Promise) {\n return result.then(onSuccess, onError);\n }\n\n return onSuccess(result);\n } catch (error) {\n return onError(error);\n }\n });\n },\n );\n }\n\n // Mark as instrumented to prevent double-wrapping\n (wrappedFunction as InstrumentedFlag)[INSTRUMENTED_SYMBOL] = true;\n\n // Preserve function name for better debugging\n // Use the same tempFn we created earlier for span naming\n Object.defineProperty(wrappedFunction, 'name', {\n value: tempFn.name || 'trace',\n configurable: true,\n });\n\n return wrappedFunction as unknown as (...args: TArgs) => TReturn;\n}\n\n/**\n * Execute a function immediately within a trace span\n * Used for the immediate execution pattern: trace((ctx) => result)\n */\nfunction executeImmediately<TReturn = unknown>(\n fn: (ctx: TraceContext) => TReturn | Promise<TReturn>,\n options: TracingOptions<unknown[], unknown>,\n): TReturn | Promise<TReturn> {\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n const sampler = options.sampler || new AlwaysSampler();\n\n // Get span name from options or use 'anonymous'\n const spanName = options.name || 'anonymous';\n\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args: [],\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n const needsTailSampling =\n 'needsTailSampling' in sampler &&\n typeof sampler.needsTailSampling === 'function'\n ? sampler.needsTailSampling()\n : false;\n\n if (!shouldSample && !needsTailSampling) {\n return fn(createDummyCtx());\n }\n\n const startTime = performance.now();\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const shouldAutoFlush =\n options.flushOnRootSpanEnd ?? getInitConfig()?.flushOnRootSpanEnd ?? true;\n const shouldAutoFlushSpans = getInitConfig()?.forceFlushOnShutdown ?? false;\n\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n const flushIfNeeded = async () => {\n if (!shouldAutoFlush || !isRootSpan) return;\n\n try {\n // Flush events queue\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n await queue.flush();\n }\n\n // Flush OpenTelemetry spans if enabled\n if (shouldAutoFlushSpans) {\n const sdk = getSdk();\n if (sdk) {\n try {\n // Type assertion needed as getTracerProvider is not in the public NodeSDK interface\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const sdkAny = sdk as any;\n if (typeof sdkAny.getTracerProvider === 'function') {\n const tracerProvider = sdkAny.getTracerProvider();\n if (\n tracerProvider &&\n typeof tracerProvider.forceFlush === 'function'\n ) {\n await tracerProvider.forceFlush();\n }\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n }\n }\n } catch (error) {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n }\n };\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n (span) => {\n return runInOperationContext(spanName, () => {\n let shouldKeepSpan = true;\n\n setSpanName(span, spanName);\n const ctxValue = createTraceContext(span);\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: unknown,\n ) => {\n if (\n needsTailSampling &&\n 'shouldKeepTrace' in sampler &&\n typeof sampler.shouldKeepTrace === 'function'\n ) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n // Sync handlers for synchronous results (can't await)\n // NOTE: forceFlushOnShutdown will NOT block for synchronous trace() calls\n // Flush is fire-and-forget, so spans may be dropped if process exits immediately\n const onSuccessSync = (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n void flushIfNeeded();\n return result;\n };\n\n const onErrorSync = (error: unknown): never => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n void flushIfNeeded();\n throw error;\n };\n\n // Async handlers for Promise results (await flush)\n const onSuccessAsync = async (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n await flushIfNeeded();\n return result;\n };\n\n const onErrorAsync = async (error: unknown): Promise<never> => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n await flushIfNeeded();\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n const result = fn(ctxValue);\n\n // Check if result is a Promise - use async handlers to await flush\n if (result instanceof Promise) {\n return result.then(onSuccessAsync, onErrorAsync);\n }\n\n // Synchronous result - use sync handlers\n return onSuccessSync(result);\n } catch (error) {\n return onErrorSync(error);\n }\n });\n },\n );\n}\n\n/**\n * Approach 1: trace() - Zero-ceremony HOF\n *\n * Wrap a single function with automatic tracing.\n * The function receives a context object as the first parameter.\n *\n * Supports two patterns:\n * 1. **Factory pattern** - Returns a traced function: `trace(ctx => (...args) => result)`\n * 2. **Immediate execution** - Executes immediately with tracing: `trace(ctx => result)`\n *\n * @example Auto-inferred name - Plain function\n * ```typescript\n * export const createUser = trace(async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"createUser\"\n * ```\n *\n * @example Auto-inferred name - Factory pattern (with ctx access)\n * ```typescript\n * export const createUser = trace(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * // → Traced as \"createUser\", returns wrapped function\n * ```\n *\n * @example Immediate execution - Execute once with tracing\n * ```typescript\n * // Wraps an existing function and executes immediately\n * function timed<T>(fn: () => Promise<T>): Promise<T> {\n * return trace(async (ctx) => {\n * ctx.setAttribute('operation', 'timed')\n * return await fn()\n * })\n * }\n * // → Executes immediately, returns result directly\n * ```\n *\n * @example Custom name - Plain function\n * ```typescript\n * export const createUser = trace('user.create', async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"user.create\"\n * ```\n *\n * @example Custom name - Factory pattern\n * ```typescript\n * export const createUser = trace('user.create', ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * // → Traced as \"user.create\"\n * ```\n *\n * @example Custom name - Immediate execution\n * ```typescript\n * const result = trace('fetch.user', async (ctx) => {\n * ctx.setAttribute('userId', '123')\n * return await fetchUser('123')\n * })\n * // → Executes immediately with span name \"fetch.user\"\n * ```\n *\n * @example Full options - Plain function\n * ```typescript\n * export const createUser = trace({\n * name: 'user.create',\n * sampler: new AdaptiveSampler(),\n * withMetrics: true\n * }, async (data) => {\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Full options - Factory pattern\n * ```typescript\n * export const createUser = trace({\n * name: 'user.create',\n * sampler: new AdaptiveSampler(),\n * withMetrics: true\n * }, ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n */\n// Sync overloads - Ordered from most specific to most generic for better type inference\n\n// Single argument - Specific overloads with TraceContext first\n// Overload 1a: Immediate execution - sync function with context\nexport function trace<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n TReturn = unknown,\n>(fn: (ctx: TraceContext<TBaggage>) => TReturn): TReturn;\n// Overload 1b: Factory sync function with no args - non-generic for type inference\nexport function trace<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(fnFactory: (ctx: TraceContext<TBaggage>) => () => unknown): () => unknown;\n// Overload 1c: Factory sync function - non-generic for type inference\nexport function trace<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(\n fnFactory: (ctx: TraceContext<TBaggage>) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Overload 1d: Factory sync function with no args returning explicit type (typed generic)\nexport function trace<TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => () => TReturn,\n): () => TReturn;\n// Overload 1e: Factory sync function - use conditional type to extract signature\n// This overload is more specific and helps TypeScript infer types from factory functions\nexport function trace<\n TFactory extends (ctx: TraceContext) => (...args: unknown[]) => unknown,\n>(fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 1f: Generic factory sync function (fallback)\nexport function trace<TArgs extends unknown[], TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Single argument - Plain function overloads (no ctx parameter)\n// Overload 1g: Plain sync function with no args\nexport function trace<TReturn = unknown>(fn: () => TReturn): () => TReturn;\n// Overload 1h: Plain sync function (generic fallback)\nexport function trace<TArgs extends unknown[], TReturn = unknown>(\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - name + function - Specific overloads with TraceContext first\n// Overload 2a: Name + immediate execution sync with context\n// This overload only matches functions that DON'T return functions (factories)\nexport function trace<TReturn = unknown>(\n name: string,\n fn: ExcludeFactoryReturn<(ctx: TraceContext) => TReturn>,\n): TReturn;\n// Overload 2b: Name + factory sync function with no args\nexport function trace<TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => () => TReturn,\n): () => TReturn;\n// Overload 2c: Name + factory sync function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Overload 2d: Name + factory sync function - use conditional type to extract signature\n// This overload allows TypeScript to infer types from the factory function parameter\nexport function trace<\n TFactory extends (ctx: TraceContext) => (...args: unknown[]) => unknown,\n>(name: string, fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 2e: Name + factory sync function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - name + function - Plain function overloads\n// Overload 2f: Name + plain sync function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - options + function - Specific overloads with TraceContext first\n// Overload 3a: Options + immediate execution sync with context\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fn: (ctx: TraceContext) => TReturn,\n): TReturn;\n// Overload 3b: Options + factory sync function with no args\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fnFactory: (ctx: TraceContext) => () => TReturn,\n): () => TReturn;\n// Overload 3c: Options + factory sync function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Overload 3d: Options + factory sync function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - options + function - Plain function overloads\n// Overload 3e: Options + plain sync function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Async overloads - Ordered from most specific to most generic\n\n// Single argument - Specific async overloads with TraceContext first\n// Overload 4a: Immediate execution - async function with context\nexport function trace<TReturn = unknown>(\n fn: (ctx: TraceContext) => Promise<TReturn>,\n): Promise<TReturn>;\n// Overload 4b: Factory async function with no args - non-generic for type inference\nexport function trace(\n fnFactory: (ctx: TraceContext) => () => Promise<unknown>,\n): () => Promise<unknown>;\n// Overload 4c: Factory async function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n// Overload 4d: Factory async function with no args (typed generic)\nexport function trace<TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 4e: Factory async function - use conditional type to extract signature\nexport function trace<\n TFactory extends (\n ctx: TraceContext,\n ) => (...args: unknown[]) => Promise<unknown>,\n>(fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 4f: Generic factory async function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Single argument - Plain async function overloads (no ctx parameter)\n// Overload 4g: Plain async function with no args\nexport function trace<TReturn = unknown>(\n fn: () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 4h: Plain async function (generic fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - name + async function - Specific overloads with TraceContext first\n// Overload 5a: Name + immediate execution async with context\n// This overload only matches functions that DON'T return functions (factories)\nexport function trace<TReturn = unknown>(\n name: string,\n fn: ExcludeFactoryReturn<(ctx: TraceContext) => Promise<TReturn>>,\n): Promise<TReturn>;\n// Overload 5b: Name + factory async function with no args\nexport function trace<TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 5c: Name + factory async function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n// Overload 5d: Name + factory async function - use conditional type to extract signature\n// This overload allows TypeScript to infer types from the factory function parameter\nexport function trace<\n TFactory extends (\n ctx: TraceContext,\n ) => (...args: unknown[]) => Promise<unknown>,\n>(name: string, fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 5e: Name + factory async function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - name + async function - Plain function overloads\n// Overload 5f: Name + plain async function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - options + async function - Specific overloads with TraceContext first\n// Overload 6a: Options + immediate execution async with context\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fn: (ctx: TraceContext) => Promise<TReturn>,\n): Promise<TReturn>;\n// Overload 6b: Options + factory async function with no args\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fnFactory: (ctx: TraceContext) => () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 6c: Options + factory async function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n// Overload 6d: Options + factory async function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - options + async function - Plain function overloads\n// Overload 6e: Options + plain async function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Implementation\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fnOrNameOrOptions:\n | ((...args: TArgs) => TReturn)\n | ((...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn)\n | ((ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => TReturn)\n | ((ctx: TraceContext) => Promise<TReturn>)\n | string\n | TracingOptions<TArgs, TReturn>,\n maybeFn?:\n | ((...args: TArgs) => TReturn)\n | ((...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn)\n | ((ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => TReturn)\n | ((ctx: TraceContext) => Promise<TReturn>),\n): WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn> {\n // Handle: trace(fn) - single argument\n if (typeof fnOrNameOrOptions === 'function') {\n // Check if it's immediate execution pattern: (ctx) => result\n if (\n looksLikeTraceFactory(fnOrNameOrOptions as GenericFunction) &&\n !isFactoryReturningFunction(\n fnOrNameOrOptions as (ctx: TraceContext) => unknown,\n )\n ) {\n // Immediate execution pattern\n return executeImmediately(\n fnOrNameOrOptions as (ctx: TraceContext) => TReturn | Promise<TReturn>,\n {},\n ) as WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn>;\n }\n // Factory pattern or plain function\n return wrapFactoryWithTracing(\n fnOrNameOrOptions as (...args: TArgs) => TReturn,\n {} as TracingOptions<TArgs, TReturn>,\n );\n }\n\n // Handle: trace(name, fn) or trace(options, fn) - two arguments\n if (typeof fnOrNameOrOptions === 'string') {\n if (!maybeFn) {\n throw new Error('trace(name, fn): fn is required');\n }\n // Check if it's immediate execution pattern\n if (\n looksLikeTraceFactory(maybeFn as GenericFunction) &&\n !isFactoryReturningFunction(maybeFn as (ctx: TraceContext) => unknown)\n ) {\n // Immediate execution pattern with name\n return executeImmediately(\n maybeFn as (ctx: TraceContext) => TReturn | Promise<TReturn>,\n { name: fnOrNameOrOptions },\n ) as WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn>;\n }\n return wrapFactoryWithTracing(\n maybeFn as (...args: TArgs) => TReturn,\n { name: fnOrNameOrOptions } as TracingOptions<TArgs, TReturn>,\n );\n }\n\n // Handle: trace(options, fn)\n if (!maybeFn) {\n throw new Error('trace(options, fn): fn is required');\n }\n\n // Check if it's immediate execution pattern\n if (\n looksLikeTraceFactory(maybeFn as GenericFunction) &&\n !isFactoryReturningFunction(maybeFn as (ctx: TraceContext) => unknown)\n ) {\n // Immediate execution pattern with options\n return executeImmediately(\n maybeFn as (ctx: TraceContext) => TReturn | Promise<TReturn>,\n fnOrNameOrOptions as TracingOptions<unknown[], unknown>,\n ) as WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn>;\n }\n\n return wrapFactoryWithTracing(\n maybeFn as (...args: TArgs) => TReturn,\n fnOrNameOrOptions as TracingOptions<TArgs, TReturn>,\n );\n}\n\n/**\n * Approach 2: withTracing() - Middleware-style composable wrapper\n *\n * Returns a HOF that wraps functions with tracing.\n * Perfect for composition and reusable configuration.\n *\n * @example Standard usage\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Composable\n * ```typescript\n * const trace = withTracing({ serviceName: 'user' })\n *\n * export const createUser = trace(ctx => async (data) => { })\n * export const updateUser = trace(ctx => async (id, data) => { })\n * ```\n *\n * @example With other middleware\n * ```typescript\n * export const createUser = compose(\n * withAuth({ role: 'admin' }),\n * withTracing({ name: 'user.create' }),\n * withRateLimit({ max: 100 })\n * )(ctx => async (data) => { })\n * ```\n */\nexport function withTracing<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(\n options: TracingOptions<TArgs, TReturn> = {},\n): (\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n) => (...args: TArgs) => TReturn | Promise<TReturn> {\n return (\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n ): WrappedFunction<TArgs, TReturn> =>\n wrapFactoryWithTracing<TArgs, TReturn>(fnFactory, options);\n}\n\n/**\n * Approach 3: instrument() - Batch auto-instrumentation\n *\n * Instrument an entire module/object at once.\n * Closest to @Instrumented decorator pattern.\n *\n * @example Basic usage\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * sampler: new AdaptiveSampler()\n * })\n * // → Traced as \"user.createUser\", \"user.updateUser\", \"user.deleteUser\"\n * ```\n *\n * @example Per-function overrides\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * overrides: {\n * deleteUser: {\n * sampler: new AlwaysSampler(),\n * withMetrics: true\n * }\n * }\n * })\n * ```\n *\n * @example Skip functions\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * _internal: async () => { }, // Auto-skipped (_-prefix)\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * skip: [/^test/, (key) => key.includes('debug')]\n * })\n * ```\n */\nexport function instrument<T extends Record<string, InstrumentableFunction>>(\n options: InstrumentOptions<T>,\n): T {\n const { functions, ...tracingOptions } = options;\n const instrumented: Partial<T> = {};\n\n for (const key of Object.keys(functions)) {\n const typedKey = key as keyof T;\n const fn = functions[typedKey];\n\n // Skip if not a function or undefined - just pass through the value\n if (!fn || typeof fn !== 'function') {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Only instrument own enumerable async functions\n // Check if should skip\n if (shouldSkip(key, fn, tracingOptions.skip)) {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Merge base options with per-function overrides\n const fnOptions: TracingOptions = {\n ...tracingOptions,\n ...tracingOptions.overrides?.[key],\n // If no explicit name, use key as function name\n name: tracingOptions.overrides?.[key]?.name,\n };\n\n // Bind function to original object to preserve 'this' context\n // This ensures methods can access state on the original object\n const boundFn = fn.bind(functions);\n\n // Convert plain function to factory pattern for trace()\n // For instrument(), we create a factory that ignores ctx and returns the original function\n const fnFactory = (ctx: TraceContext) => {\n void ctx;\n return boundFn;\n };\n\n // Wrap with tracing (sync or async based on implementation)\n instrumented[typedKey] = wrapFactoryWithTracing(\n fnFactory,\n fnOptions,\n key,\n ) as T[typeof typedKey];\n }\n\n return instrumented as T;\n}\n\n/**\n * Options for span() function\n */\nexport interface SpanOptions {\n /** Span name */\n name: string;\n /** Attributes to set on the span */\n attributes?: Record<string, string | number | boolean>;\n}\n\n/**\n * Execute a function within a named span\n *\n * Useful for adding tracing to specific code blocks without wrapping\n * the entire function. Supports both synchronous and asynchronous functions.\n *\n * Mirrors `trace()`: pass a span name as the first argument for the common\n * case, or full `SpanOptions` when you need to attach attributes.\n *\n * @example\n * ```typescript\n * // Name shorthand\n * await span('payment.charge', async (span) => {\n * await chargeCustomer(order);\n * })\n *\n * // Full options when attributes are needed\n * await span(\n * { name: 'payment.charge', attributes: { amount: order.total } },\n * async (span) => {\n * await chargeCustomer(order);\n * },\n * )\n *\n * // Sync\n * const total = span('calculateTotal', (span) => {\n * return items.reduce((sum, item) => sum + item.price, 0);\n * })\n * ```\n */\n// Overloads — sync first (more specific match), then async.\n// Each shape is offered with a string name OR a full SpanOptions object so\n// span() aligns with trace()'s argument flexibility.\nexport function span<T = unknown>(name: string, fn: (span: Span) => T): T;\nexport function span<T = unknown>(\n name: string,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => T,\n): T;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\n// Implementation\nexport function span<T = unknown>(\n nameOrOptions: string | SpanOptions,\n fn: (span: Span) => T | Promise<T>,\n): T | Promise<T> {\n const options: SpanOptions =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n const config = getConfig();\n const tracer = config.tracer;\n const { name, attributes } = options;\n\n const executeSpan = (span: Span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(name, () => {\n try {\n // Set attributes\n if (attributes) {\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute(key, value);\n }\n }\n\n const result = fn(span);\n\n // Check if result is a Promise\n if (result instanceof Promise) {\n return result\n .then((resolved) => {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return resolved;\n })\n .catch((error) => {\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n });\n } else {\n // Synchronous function\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n }\n } catch (error) {\n // Synchronous error handling\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n }\n });\n };\n\n const parentContext = getActiveContextWithBaggage();\n const result = tracer.startActiveSpan(name, {}, parentContext, executeSpan);\n\n // tracer.startActiveSpan might return a Promise even for sync callbacks\n // Check if it's a Promise and handle accordingly\n if (result instanceof Promise) {\n return result;\n }\n\n return result as T;\n}\n\n/**\n * Options for withNewContext() function\n */\nexport interface WithNewContextOptions<T = unknown> {\n /** Function to execute in new root context */\n fn: () => Promise<T>;\n}\n\n/**\n * Execute a function in a new root context (prevents span propagation)\n *\n * Useful when you want to start a completely new trace without\n * parent-child relationships.\n *\n * @example\n * ```typescript\n * async function handleWebhook(payload: WebhookPayload) {\n * // This creates a new root trace, not connected to the HTTP request trace\n * await withNewContext({\n * fn: async () => {\n * await trace(ctx => async () => {\n * await processWebhookPayload(payload)\n * })()\n * }\n * })\n * }\n * ```\n */\nexport async function withNewContext<T = unknown>(\n options: WithNewContextOptions<T>,\n): Promise<T> {\n const { fn } = options;\n const config = getConfig();\n const tracer = config.tracer;\n\n // Start a new root span (breaks trace propagation)\n return tracer.startActiveSpan('root', { root: true }, async (span) => {\n try {\n const result = await fn();\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n });\n}\n\n/**\n * Options for withBaggage() function\n */\nexport interface WithBaggageOptions<T = unknown> {\n /** Baggage entries to set (key-value pairs) */\n baggage: Record<string, string>;\n /** Function to execute with the updated baggage */\n fn: () => T | Promise<T>;\n}\n\n/**\n * Execute a function with updated baggage entries\n *\n * Baggage is immutable in OpenTelemetry, so this helper creates a new context\n * with the specified baggage entries and runs the function within that context.\n * All child spans created within the function will inherit the baggage.\n *\n * @example Setting baggage for downstream services\n * ```typescript\n * import { trace, withBaggage } from 'autotel';\n *\n * export const createOrder = trace((ctx) => async (order: Order) => {\n * // Set baggage that will be propagated to downstream HTTP calls\n * return await withBaggage({\n * baggage: {\n * 'tenant.id': order.tenantId,\n * 'user.id': order.userId,\n * },\n * fn: async () => {\n * // This HTTP call will include the baggage in headers\n * await fetch('/api/charge', {\n * method: 'POST',\n * body: JSON.stringify(order),\n * });\n * },\n * });\n * });\n * ```\n *\n * @example Using with existing baggage\n * ```typescript\n * export const processOrder = trace((ctx) => async (order: Order) => {\n * // Read existing baggage\n * const tenantId = ctx.getBaggage('tenant.id');\n *\n * // Add additional baggage entries\n * return await withBaggage({\n * baggage: {\n * 'order.id': order.id,\n * 'order.amount': String(order.amount),\n * },\n * fn: async () => {\n * await charge(order);\n * },\n * });\n * });\n * ```\n */\nexport function withBaggage<T = unknown>(\n options: WithBaggageOptions<T>,\n): T | Promise<T> {\n const { baggage: baggageEntries, fn } = options;\n const currentContext = context.active();\n\n // Get existing baggage or create new\n let updatedBaggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n\n // Set all baggage entries\n for (const [key, value] of Object.entries(baggageEntries)) {\n updatedBaggage = updatedBaggage.setEntry(key, { value });\n }\n\n // Create new context with updated baggage\n const newContext = propagation.setBaggage(currentContext, updatedBaggage);\n\n // Sync contextStorage so nested traces (via getActiveContextWithBaggage) see the baggage.\n // Use run() instead of enterWith() to properly scope the context changes.\n const ctxStorage = getContextStorage();\n const previousStored = ctxStorage.getStore();\n const baggageEnrichedStored = previousStored\n ? { value: propagation.setBaggage(previousStored.value, updatedBaggage) }\n : { value: newContext };\n\n // Run the function within the new context, scoped properly\n const result = previousStored\n ? ctxStorage.run(baggageEnrichedStored, () => context.with(newContext, fn))\n : context.with(newContext, fn);\n\n if (result instanceof Promise) {\n // For async operations, ensure context is restored after the promise settles\n return result.then(\n (value) => {\n // Restore original context before resolving\n if (previousStored) {\n return ctxStorage.run(previousStored, () => value);\n }\n return value;\n },\n (error) => {\n // Restore original context before rejecting\n if (previousStored) {\n return ctxStorage.run(previousStored, () => {\n throw error;\n });\n }\n throw error;\n },\n );\n }\n\n // Sync function - context automatically restored when scope exits\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,iCAAiB,IAAI,IAAgC;AAC3D,MAAM,iBAAiB;;;;AAKvB,SAAS,oBAA4B;CACnC,MAAM,0BAA0B,MAAM;CACtC,MAAM,kBAAkB;CAGxB,MAAM,yBAAQ,IADE,MAAM,qBACN,EAAC,CAAC,SAAS;CAE3B,MAAM,kBAAkB;CACxB,OAAO;AACT;;;;;;;;;;;;AAaA,SAAS,kBAAkB,OAAyC;CAClE,MAAM,QAAQ,MAAM,MAAM,IAAI;CAC9B,IAAI,uBAAuB;CAE3B,KAAK,MAAM,QAAQ,OAAO;EAGxB,IACE,KAAK,SAAS,4BAA4B,KAC1C,KAAK,SAAS,4BAA4B,KAC1C,KAAK,SAAS,eAAe,KAC7B,KAAK,SAAS,eAAe,GAE7B;EAMF,MAAM,QACJ,KAAK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SAAS,KAAK,EAAE,MAAM,CAAC;CAIzD,MAAM,aAAa,YAAY,WAAW,gBAAgB,cAAc;CAIxE,MAAM,aAAa,kBAAkB;CACrC,MAAM,iBAAiB,WAAW,SAAS;CAC3C,MAAM,wBAAwB,iBAC1B,EAAE,OAAO,YAAY,WAAW,eAAe,OAAO,cAAc,EAAE,IACtE,EAAE,OAAO,WAAW;CAGxB,MAAM,SAAS,iBACX,WAAW,IAAI,6BAA6B,QAAQ,KAAK,YAAY,EAAE,CAAC,IACxE,QAAQ,KAAK,YAAY,EAAE;CAE/B,IAAI,kBAAkB,SAEpB,OAAO,OAAO,MACX,UAAU;EAET,IAAI,gBACF,OAAO,WAAW,IAAI,sBAAsB,KAAK;EAEnD,OAAO;CACT,IACC,UAAU;EAET,IAAI,gBACF,OAAO,WAAW,IAAI,sBAAsB;GAC1C,MAAM;EACR,CAAC;EAEH,MAAM;CACR,CACF;CAIF,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-CX0aG1Uh.d.ts","names":[],"sources":["../src/attributes/types.ts","../src/attributes/builders.ts","../src/attributes/validators.ts","../src/attributes/attachers.ts","../src/attributes/domains.ts","../src/attributes/utils.ts"],"mappings":";;;;;UAOiB,SAAA;EACf,EAAA;EACA,KAAA;EACA,IAAA;EACA,QAAA;EACA,IAAA;EACA,KAAA;AAAA;AAAA,UAGe,YAAA;EACf,EAAA;EACA,UAAU;AAAA;AAAA,UAGK,WAAA;EACf,EAAA;EACA,YAAA;EACA,eAAA;EACA,SAAA;AAAA;AAAA,UAGe,eAAA;EACf,MAAA;EACA,KAAA;EACA,UAAA;EACA,QAAA;EACA,WAAA;EACA,YAAA;EACA,WAAA;AAAA;AAAA,UAGe,eAAA;EACf,MAAA;EACA,GAAA;EACA,UAAA;AAAA;AAAA,UAGe,OAAA;EACf,MAAA;EAbA;EAeA,IAAA;EAbA;EAeA,SAAA;EACA,SAAA;EACA,cAAA;EACA,SAAA;EACA,YAAA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Ae,IAAA,GAAO,YAAA,EACtB,IAAA,EADkC,OAAA,EAElC,UAAA,GAD+B,eAAA;;;AHvD1B;AAGP;;;;AAEY;AAGZ;;;;;;;;;AAIW;AAGX;iBGkEgB,oBAAA,CACd,QAAA,EAAU,QAAA,EACV,IAAA,EADkB,YAAA,GAEjB,QAAA;AAAA,iBAKa,QAAA,CACd,aAAA,EAAe,IAAA,GAAO,YAAA,EACtB,IAAA;EACE,IAAA,GAFgC,SAAA;EAGhC,OAAA,GADkC,YAAA;EAElC,MAAA,GADwC,WAAA;AAAA,GAG1C,UAAA,GAFwC,eAAA;AAAA,iBAwB1B,OAAA,CACd,aAAA,EAAe,IAAA,GAAO,YAAA,EACtB,IAAA,EADkC,eAAA;EAEhC,QAAA;AAAA,GAEF,UAAA,GAHuC,eAAA;AAAA,iBAWzB,QAAA,CACd,aAAA,EAAe,IAAA,GAAO,YAAA,EACtB,IAAA,EADkC,UAAA,EAElC,UAAA,GADkC,eAAA;AAAA,iBAOpB,YAAA,CACd,aAAA,EAAe,IAAA,GAAO,YAAA,EACtB,IAAA,EADkC,cAAA,EAElC,UAAA,GADsC,eAAA;;;;;;;iBCnJxB,WAAA,CACd,aAAA,EADyB,YAAA,EAEzB,MAAA;EACE,IAAA,GAFoD,SAAA;EAGpD,OAAA,GADkC,YAAA;EAElC,MAAA;EACA,KAAA;EACA,UAAA;EACA,QAAA;AAAA,GAEF,UAAA,GAN0C,eAAA;;;KCGvC,eAAA;EACH,aAAA,GAAgB,KAAA,EAAO,MAAM,SAAS,gBAAA;AAAA;AAAA,iBAGxB,UAAA,IACX,QAAA,EAAU,KAAA,CAAM,MAAA,iCAClB,MAAA;AAAA,iBAUa,iBAAA,CACd,IAAA,EAAM,eAAA,EACN,KAAA,EAAO,MAAA,mBACP,MAAA,GAAS,eAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-DIWZFKUS.d.cts","names":[],"sources":["../src/attributes/types.ts","../src/attributes/builders.ts","../src/attributes/validators.ts","../src/attributes/attachers.ts","../src/attributes/domains.ts","../src/attributes/utils.ts"],"mappings":";;;;;UAOiB,SAAA;EACf,EAAA;EACA,KAAA;EACA,IAAA;EACA,QAAA;EACA,IAAA;EACA,KAAA;AAAA;AAAA,UAGe,YAAA;EACf,EAAA;EACA,UAAU;AAAA;AAAA,UAGK,WAAA;EACf,EAAA;EACA,YAAA;EACA,eAAA;EACA,SAAA;AAAA;AAAA,UAGe,eAAA;EACf,MAAA;EACA,KAAA;EACA,UAAA;EACA,QAAA;EACA,WAAA;EACA,YAAA;EACA,WAAA;AAAA;AAAA,UAGe,eAAA;EACf,MAAA;EACA,GAAA;EACA,UAAA;AAAA;AAAA,UAGe,OAAA;EACf,MAAA;EAbA;EAeA,IAAA;EAbA;EAeA,SAAA;EACA,SAAA;EACA,cAAA;EACA,SAAA;EACA,YAAA;EACA,SAAA;EACA,cAAA;EACA,YAAA;AAAA;AAAA,UAGe,YAAA;EACf,IAAA;EACA,QAAA;EACA,OAAA;AAAA;AAAA,UAGe,YAAA;EACf,YAAA;EACA,eAAA;EACA,WAAA;EACA,QAAA;EACA,SAAA;EACA,YAAA;AAAA;AAAA,UAGe,UAAA;EACf,IAAA;EACA,OAAA;EACA,UAAA;EACA,IAAA;AAAA;AAAA,UAGe,gBAAA;EACf,GAAA;EACA,QAAA;EACA,OAAA;AAAA;AAAA,UAGe,cAAA;EACf,MAAA;EACA,WAAA;EACA,SAAA;EACA,SAAA;EACA,cAAA;AAAA;AAAA,UAGe,UAAA;EACf,QAAA;EACA,SAAA;EACA,MAAA;EACA,gBAAA;EACA,QAAA;AAAA;AAAA,UAGe,kBAAA;EACf,OAAA;EACA,IAAA;EACA,aAAA;AAAA;AAAA,UAGe,QAAA;EACf,MAAA;EACA,IAAA;EACA,IAAA;EACA,KAAA;EACA,QAAA;AAAA;AAAA,UAGe,SAAA;EACf,OAAA;EACA,OAAA;EACA,IAAA;AAAA;AAAA,UAGe,YAAA;EACf,GAAA;EACA,c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ADsC,eAAA;;;;;;;iBCnJxB,WAAA,CACd,aAAA,EADyB,YAAA,EAEzB,MAAA;EACE,IAAA,GAFoD,SAAA;EAGpD,OAAA,GADkC,YAAA;EAElC,MAAA;EACA,KAAA;EACA,UAAA;EACA,QAAA;AAAA,GAEF,UAAA,GAN0C,eAAA;;;KCGvC,eAAA;EACH,aAAA,GAAgB,KAAA,EAAO,MAAM,SAAS,gBAAA;AAAA;AAAA,iBAGxB,UAAA,IACX,QAAA,EAAU,KAAA,CAAM,MAAA,iCAClB,MAAA;AAAA,iBAUa,iBAAA,CACd,IAAA,EAAM,eAAA,EACN,KAAA,EAAO,MAAA,mBACP,MAAA,GAAS,eAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"init-CNp-ee80.d.cts","names":[],"sources":["../src/validation.ts","../src/redact-values.ts","../src/events-config.ts","../src/devtools.ts","../src/init.ts"],"mappings":";;;;;;;;;;;;;;;UAYiB,gBAAA;;EAEf,kBAAA;;EAEA,qBAAA;EAJe;EAMf,uBAAA;;EAEA,iBAAA;EANA;EAQA,eAAA;EAJA;EAMA,iBAAA,EAAmB,MAAM;AAAA;;;KCff,cAAA,IAAkB,KAAa;AAAA,iBAC3B,oBAAA,CACd,MAAA,EAAQ,uBAAA,GAA0B,uBAAA,GACjC,cAAA;;;;;;;;;;;;;;;;;;ADAH;;;;UEQiB,eAAA;EFJf;EEMA,OAAA;EFFA;EEIA,MAAA;EFAA;EEEA,aAAA;EFFyB;EEIzB,WAAA;;EAEA,WAAA;AAAA;ADrBF;;;AAAA,KC2BY,gBAAA,wBAAwC,KAAa;AD3BtB;AAC3C;;AAD2C,UCgC1B,uBAAA;ED9BP;;;;ECmCR,KAAA;EDnCQ;;;;ECyCR,IAAA;EDxCe;;;;EC8Cf,MAAA;EAtC8B;;;;EA4C9B,OAAA;EAtCA;;;;EA4CA,QAAA;EAlCU;;;;AAAqD;AAKjE;;;;;;;;;;EA8CE,SAAA,GAAY,MAAM,SAAS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;;;;;;;;;;;;;;;;;;;;;;;EAwDZ,iBAAA;IACE,OAAA;IAEA,MAAA,GAAS,MAAA;IAET,aAAA;IAEA,QAAA;IAEA,aAAA,IACE,IAAA,0CAA8C,YAAA;IAGhD,yBAAA;IAEA,UAAA,GAAa,uBAAA;;;;;;IAMb,IAAA,GAAO,uBAAA;IAEP,KAAA,GAAQ,uBAAA;IAER,YAAA,GAAe,uBAAA;;;;;IAKf,MAAA;EAAA;;;;;;;;EAUF,MAAA;;;;;;;EAQA,QAAA;AAAA;;;;;;iBAwBc,UAAA;;;;iBAOA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0OA,IAAA,CAAK,GAAkB,EAAb,aAAa;;;;iBAorBvB,aAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"init-Ch6t7MNI.js","names":["otelContext","OTLPTraceExporterHTTP","OTLPMetricExporterHTTP","OTLPLogExporterHTTP"],"sources":["../src/posthog-logs.ts","../src/baggage-span-processor.ts","../src/redact-values.ts","../src/env-config.ts","../src/devtools.ts","../src/init.ts"],"sourcesContent":["import type { LogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { safeRequire } from './node-require';\nimport type { StringRedactor } from './redact-values';\n\nexport class RedactingLogRecordProcessor implements LogRecordProcessor {\n constructor(\n private wrapped: LogRecordProcessor,\n private redact: StringRedactor,\n ) {}\n\n onEmit(logRecord: any, context?: any): void {\n if (logRecord.body && typeof logRecord.body === 'string') {\n logRecord.body = this.redact(logRecord.body);\n }\n if (logRecord.attributes) {\n for (const [key, value] of Object.entries(logRecord.attributes)) {\n if (typeof value === 'string') {\n logRecord.attributes[key] = this.redact(value);\n } else if (Array.isArray(value)) {\n logRecord.attributes[key] = value.map((item: unknown) =>\n typeof item === 'string' ? this.redact(item) : item,\n );\n }\n }\n }\n this.wrapped.onEmit(logRecord, context);\n }\n\n shutdown(): Promise<void> {\n return this.wrapped.shutdown();\n }\n\n forceFlush(): Promise<void> {\n return this.wrapped.forceFlush();\n }\n}\n\nexport interface PostHogConfig {\n /** OTLP logs endpoint URL (e.g., https://us.i.posthog.com/i/v1/logs?token=phc_xxx) */\n url: string;\n}\n\n/**\n * Build log record processors for PostHog OTLP logs integration.\n *\n * Resolution order:\n * 1. config.url if provided\n * 2. POSTHOG_LOGS_URL env var\n * 3. Empty array (disabled)\n */\nexport function buildPostHogLogProcessors(\n config: PostHogConfig | undefined,\n stringRedactor?: StringRedactor | null,\n): LogRecordProcessor[] {\n const url = config?.url || process.env.POSTHOG_LOGS_URL;\n if (!url) return [];\n\n const sdkLogs = safeRequire<{\n BatchLogRecordProcessor: new (exporter: unknown) => LogRecordProcessor;\n }>('@opentelemetry/sdk-logs');\n\n const exporterModule = safeRequire<{\n OTLPLogExporter: new (config: { url: string }) => unknown;\n }>('@opentelemetry/exporter-logs-otlp-http');\n\n if (!sdkLogs || !exporterModule) return [];\n\n const exporter = new exporterModule.OTLPLogExporter({ url });\n let processor: LogRecordProcessor = new sdkLogs.BatchLogRecordProcessor(\n exporter,\n );\n if (stringRedactor) {\n processor = new RedactingLogRecordProcessor(processor, stringRedactor);\n }\n\n return [processor];\n}\n","/**\n * Span processor that copies baggage entries to span attributes\n *\n * This makes baggage visible in trace UIs without manual attribute setting.\n * Enabled via init({ baggage: true }) or init({ baggage: 'custom-prefix' })\n */\n\nimport type { Span, Context } from '@opentelemetry/api';\nimport { propagation, context as otelContext } from '@opentelemetry/api';\nimport type { SpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { requireModule } from './node-require';\n\nexport interface BaggageSpanProcessorOptions {\n /**\n * Prefix for baggage attributes\n * @default 'baggage.'\n */\n prefix?: string;\n}\n\n/**\n * Span processor that automatically copies baggage entries to span attributes\n *\n * This makes baggage visible in trace UIs (Jaeger, Grafana, DataDog, etc.)\n * without manually calling ctx.setAttribute() for each baggage entry.\n *\n * @example Enable in init()\n * ```typescript\n * init({\n * service: 'my-app',\n * baggage: true // Uses default 'baggage.' prefix\n * });\n *\n * // Now baggage automatically appears as span attributes\n * await withBaggage({\n * baggage: { 'tenant.id': 't1', 'user.id': 'u1' },\n * fn: async () => {\n * // Span has baggage.tenant.id and baggage.user.id attributes!\n * }\n * });\n * ```\n *\n * @example Custom prefix\n * ```typescript\n * init({\n * service: 'my-app',\n * baggage: 'ctx' // Uses 'ctx.' prefix\n * });\n * // Creates attributes: ctx.tenant.id, ctx.user.id\n * ```\n */\nexport class BaggageSpanProcessor implements SpanProcessor {\n private readonly prefix: string;\n\n constructor(options: BaggageSpanProcessorOptions = {}) {\n this.prefix = options.prefix ?? 'baggage.';\n }\n\n onStart(span: Span, parentContext: Context): void {\n // Read baggage from parentContext first (spans created with explicit context)\n // Then fall back to active context (spans created without explicit context)\n // Also check getActiveContextWithBaggage() to see baggage set via ctx.setBaggage()\n let baggage = propagation.getBaggage(parentContext);\n if (!baggage) {\n baggage = propagation.getBaggage(otelContext.active());\n }\n // Check stored context from ctx.setBaggage() if still no baggage\n if (!baggage) {\n try {\n const { getActiveContextWithBaggage } = requireModule<{\n getActiveContextWithBaggage: () => Context;\n }>('./trace-context');\n const storedContext = getActiveContextWithBaggage();\n baggage = propagation.getBaggage(storedContext);\n } catch {\n // Fallback if trace-context isn't available\n }\n }\n if (!baggage) return;\n\n // Copy all baggage entries to span attributes\n for (const [key, entry] of baggage.getAllEntries()) {\n span.setAttribute(`${this.prefix}${key}`, entry.value);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onEnd(_span: ReadableSpan): void {\n // No-op - required by SpanProcessor interface\n }\n\n async shutdown(): Promise<void> {\n // No-op\n }\n\n async forceFlush(): Promise<void> {\n // No-op\n }\n}\n","/** Standalone string redaction for use outside the span processor pipeline. */\n\nimport {\n REDACTOR_PRESETS,\n type AttributeRedactorConfig,\n type AttributeRedactorPreset,\n type ValuePatternConfig,\n} from './attribute-redacting-processor';\n\nexport type StringRedactor = (value: string) => string;\nexport function createStringRedactor(\n config: AttributeRedactorConfig | AttributeRedactorPreset,\n): StringRedactor {\n const resolved =\n typeof config === 'string' ? REDACTOR_PRESETS[config] : config;\n const valuePatterns: ValuePatternConfig[] = resolved.valuePatterns ?? [];\n const defaultReplacement = resolved.replacement ?? '[REDACTED]';\n\n return (value: string): string => {\n let result = value;\n for (const { pattern, replacement, mask } of valuePatterns) {\n pattern.lastIndex = 0;\n // Smart masks (e.g. email → a***@***.com) take precedence over the\n // static replacement so callers see the same output as the\n // span-attribute redactor does.\n if (mask) {\n result = result.replaceAll(pattern, (match) => mask(match));\n } else {\n result = result.replaceAll(pattern, replacement ?? defaultReplacement);\n }\n }\n return result;\n };\n}\n","/**\n * Standard OpenTelemetry environment variables\n */\nimport type { Sampler as OtelSampler } from '@opentelemetry/sdk-trace-base';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace-base';\n\nexport interface OtelEnvVars {\n OTEL_SERVICE_NAME?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: 'http' | 'grpc';\n OTEL_TRACES_SAMPLER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n}\n\n/**\n * Parsed resource attributes as key-value pairs\n */\nexport interface ResourceAttributes {\n [key: string]: string;\n}\n\n/**\n * Parsed OTLP headers as key-value pairs\n */\nexport interface OtlpHeaders {\n [key: string]: string;\n}\n\n/**\n * Environment-resolved configuration (subset of AutotelConfig)\n * Defined locally to avoid circular dependency with init.ts\n */\nexport interface EnvConfig {\n service?: string;\n endpoint?: string;\n protocol?: 'http' | 'grpc';\n headers?: Record<string, string>;\n resourceAttributes?: Record<string, string>;\n otelSampler?: OtelSampler;\n}\n\n/**\n * Validate URL format\n */\nfunction isValidUrl(urlString: string): boolean {\n try {\n const url = new URL(urlString);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve OpenTelemetry environment variables from process.env\n */\nexport function resolveOtelEnv(): OtelEnvVars {\n const env: OtelEnvVars = {};\n\n // OTEL_SERVICE_NAME - optional string\n if (process.env.OTEL_SERVICE_NAME) {\n const value = process.env.OTEL_SERVICE_NAME.trim();\n if (value) {\n env.OTEL_SERVICE_NAME = value;\n }\n }\n\n // OTEL_EXPORTER_OTLP_ENDPOINT - optional URL\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n const value = process.env.OTEL_EXPORTER_OTLP_ENDPOINT.trim();\n if (value && isValidUrl(value)) {\n env.OTEL_EXPORTER_OTLP_ENDPOINT = value;\n }\n }\n\n // OTEL_EXPORTER_OTLP_HEADERS - optional string\n if (process.env.OTEL_EXPORTER_OTLP_HEADERS) {\n const value = process.env.OTEL_EXPORTER_OTLP_HEADERS.trim();\n if (value) {\n env.OTEL_EXPORTER_OTLP_HEADERS = value;\n }\n }\n\n // OTEL_RESOURCE_ATTRIBUTES - optional string\n if (process.env.OTEL_RESOURCE_ATTRIBUTES) {\n const value = process.env.OTEL_RESOURCE_ATTRIBUTES.trim();\n if (value) {\n env.OTEL_RESOURCE_ATTRIBUTES = value;\n }\n }\n\n // OTEL_EXPORTER_OTLP_PROTOCOL - optional enum ('http' | 'grpc')\n if (process.env.OTEL_EXPORTER_OTLP_PROTOCOL) {\n const value = process.env.OTEL_EXPORTER_OTLP_PROTOCOL.trim().toLowerCase();\n if (value === 'http' || value === 'grpc') {\n env.OTEL_EXPORTER_OTLP_PROTOCOL = value;\n }\n }\n\n if (process.env.OTEL_TRACES_SAMPLER) {\n const value = process.env.OTEL_TRACES_SAMPLER.trim();\n if (value) {\n env.OTEL_TRACES_SAMPLER = value;\n }\n }\n\n if (process.env.OTEL_TRACES_SAMPLER_ARG) {\n const value = process.env.OTEL_TRACES_SAMPLER_ARG.trim();\n if (value) {\n env.OTEL_TRACES_SAMPLER_ARG = value;\n }\n }\n\n return env;\n}\n\nfunction parseRatioSamplerArg(\n samplerName: string,\n samplerArg: string | undefined,\n): number {\n if (samplerArg === undefined) {\n return 1.0;\n }\n\n const ratio = Number(samplerArg);\n if (!Number.isFinite(ratio) || ratio < 0 || ratio > 1) {\n console.error(\n `[autotel] Invalid OTEL_TRACES_SAMPLER_ARG=\"${samplerArg}\" for ${samplerName}. Expected a number in [0..1]. Falling back to 1.0.`,\n );\n return 1.0;\n }\n\n return ratio;\n}\n\nfunction warnOnUnusedSamplerArg(\n samplerName: string,\n samplerArg: string | undefined,\n): void {\n if (samplerArg !== undefined) {\n console.error(\n `[autotel] OTEL_TRACES_SAMPLER_ARG is not used by OTEL_TRACES_SAMPLER=\"${samplerName}\". Ignoring value \"${samplerArg}\".`,\n );\n }\n}\n\nexport function createSamplerFromEnv(\n env: Pick<OtelEnvVars, 'OTEL_TRACES_SAMPLER' | 'OTEL_TRACES_SAMPLER_ARG'>,\n): OtelSampler | undefined {\n const samplerName = env.OTEL_TRACES_SAMPLER;\n if (!samplerName) {\n return undefined;\n }\n\n switch (samplerName) {\n case 'always_on':\n warnOnUnusedSamplerArg(samplerName, env.OTEL_TRACES_SAMPLER_ARG);\n return new AlwaysOnSampler();\n case 'always_off':\n warnOnUnusedSamplerArg(samplerName, env.OTEL_TRACES_SAMPLER_ARG);\n return new AlwaysOffSampler();\n case 'traceidratio':\n return new TraceIdRatioBasedSampler(\n parseRatioSamplerArg(samplerName, env.OTEL_TRACES_SAMPLER_ARG),\n );\n case 'parentbased_always_on':\n warnOnUnusedSamplerArg(samplerName, env.OTEL_TRACES_SAMPLER_ARG);\n return new ParentBasedSampler({ root: new AlwaysOnSampler() });\n case 'parentbased_always_off':\n warnOnUnusedSamplerArg(samplerName, env.OTEL_TRACES_SAMPLER_ARG);\n return new ParentBasedSampler({ root: new AlwaysOffSampler() });\n case 'parentbased_traceidratio':\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(\n parseRatioSamplerArg(samplerName, env.OTEL_TRACES_SAMPLER_ARG),\n ),\n });\n case 'jaeger_remote':\n case 'parentbased_jaeger_remote':\n case 'xray':\n console.error(\n `[autotel] OTEL_TRACES_SAMPLER=\"${samplerName}\" is not supported yet by autotel. Falling back to the next sampler source.`,\n );\n return undefined;\n default:\n console.error(\n `[autotel] Unknown OTEL_TRACES_SAMPLER=\"${samplerName}\". Falling back to the next sampler source.`,\n );\n return undefined;\n }\n}\n\n/**\n * Parse OTEL_RESOURCE_ATTRIBUTES from comma-separated key=value pairs\n * Example: \"service.version=1.0.0,deployment.environment=production\"\n */\nexport function parseResourceAttributes(\n input: string | undefined,\n): ResourceAttributes {\n if (!input || input.trim() === '') {\n return {};\n }\n\n const attributes: ResourceAttributes = {};\n const pairs = input.split(',');\n\n for (const pair of pairs) {\n const trimmedPair = pair.trim();\n if (!trimmedPair) continue;\n\n const equalIndex = trimmedPair.indexOf('=');\n if (equalIndex === -1) {\n // Invalid format, skip this pair\n continue;\n }\n\n const key = trimmedPair.slice(0, equalIndex).trim();\n const value = trimmedPair.slice(equalIndex + 1).trim();\n\n if (key && value) {\n attributes[key] = value;\n }\n }\n\n return attributes;\n}\n\n/**\n * Parse OTEL_EXPORTER_OTLP_HEADERS from comma-separated key=value pairs\n * Example: \"api-key=secret123,x-custom-header=value\"\n */\nexport function parseOtlpHeaders(input: string | undefined): OtlpHeaders {\n if (!input || input.trim() === '') {\n return {};\n }\n\n const headers: OtlpHeaders = {};\n const pairs = input.split(',');\n\n for (const pair of pairs) {\n const trimmedPair = pair.trim();\n if (!trimmedPair) continue;\n\n const equalIndex = trimmedPair.indexOf('=');\n if (equalIndex === -1) {\n // Invalid format, skip this pair\n continue;\n }\n\n const key = trimmedPair.slice(0, equalIndex).trim();\n const value = trimmedPair.slice(equalIndex + 1).trim();\n\n if (key && value) {\n headers[key] = value;\n }\n }\n\n return headers;\n}\n\n/**\n * Convert resolved environment variables to config\n */\nexport function envToConfig(env: OtelEnvVars): EnvConfig {\n const config: EnvConfig = {};\n\n if (env.OTEL_SERVICE_NAME) {\n config.service = env.OTEL_SERVICE_NAME;\n }\n\n if (env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n config.endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;\n }\n\n if (env.OTEL_EXPORTER_OTLP_PROTOCOL) {\n config.protocol = env.OTEL_EXPORTER_OTLP_PROTOCOL;\n }\n\n if (env.OTEL_EXPORTER_OTLP_HEADERS) {\n config.headers = parseOtlpHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);\n }\n\n const resourceAttrs = parseResourceAttributes(env.OTEL_RESOURCE_ATTRIBUTES);\n if (Object.keys(resourceAttrs).length > 0) {\n config.resourceAttributes = resourceAttrs;\n }\n\n const sampler = createSamplerFromEnv(env);\n if (sampler) {\n config.otelSampler = sampler;\n }\n\n return config;\n}\n\n/**\n * Main function to resolve config from environment variables\n */\nexport function resolveConfigFromEnv(): EnvConfig {\n const env = resolveOtelEnv();\n return envToConfig(env);\n}\n","export interface AutotelDevtoolsConfig {\n enabled?: boolean;\n endpoint?: string;\n embedded?: boolean;\n host?: string;\n port?: number;\n verbose?: boolean;\n}\n\nexport interface ResolvedAutotelDevtoolsConfig {\n enabled: boolean;\n endpoint?: string;\n embedded: boolean;\n host: string;\n port: number;\n verbose: boolean;\n}\n\nconst defaultHost = '127.0.0.1';\nconst defaultPort = 4318;\n\nexport function resolveDevtoolsConfig(\n config: boolean | AutotelDevtoolsConfig | undefined,\n): ResolvedAutotelDevtoolsConfig {\n if (!config) {\n return {\n enabled: false,\n endpoint: undefined,\n embedded: false,\n host: defaultHost,\n port: defaultPort,\n verbose: false,\n };\n }\n\n if (config === true) {\n return {\n enabled: true,\n endpoint: `http://${defaultHost}:${defaultPort}`,\n embedded: false,\n host: defaultHost,\n port: defaultPort,\n verbose: false,\n };\n }\n\n const enabled = config.enabled ?? true;\n const host = config.host ?? defaultHost;\n const port = config.port ?? defaultPort;\n const endpoint = config.endpoint ?? `http://${host}:${port}`;\n\n return {\n enabled,\n endpoint: enabled ? endpoint : undefined,\n embedded: enabled && (config.embedded ?? false),\n host,\n port,\n verbose: config.verbose ?? false,\n };\n}\n","/**\n * Simplified initialization for autotel\n *\n * Single init() function with sensible defaults.\n * Replaces initInstrumentation() and separate events config.\n */\n\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport type { NodeSDKConfiguration } from '@opentelemetry/sdk-node';\nimport {\n BatchSpanProcessor,\n type SpanProcessor,\n SimpleSpanProcessor,\n ConsoleSpanExporter,\n SamplingDecision,\n type SpanExporter,\n type Sampler as OtelSampler,\n type SamplingResult,\n} from '@opentelemetry/sdk-trace-base';\nimport {\n resourceFromAttributes,\n type Resource,\n} from '@opentelemetry/resources';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Sampler, SamplingPreset } from './sampling';\nimport { samplingPresets, resolveSamplingPreset } from './sampling';\nimport type { EventSubscriber } from './event-subscriber';\nimport type { Logger } from './logger';\nimport type { Attributes, Context, SpanKind, Link } from '@opentelemetry/api';\nimport type { ValidationConfig } from './validation';\nimport {\n PeriodicExportingMetricReader,\n type MetricReader,\n} from '@opentelemetry/sdk-metrics';\nimport { OTLPMetricExporter as OTLPMetricExporterHTTP } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { OTLPTraceExporter as OTLPTraceExporterHTTP } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPLogExporter as OTLPLogExporterHTTP } from '@opentelemetry/exporter-logs-otlp-http';\nimport type { PushMetricExporter } from '@opentelemetry/sdk-metrics';\nimport {\n BatchLogRecordProcessor,\n type LogRecordExporter,\n type LogRecordProcessor,\n} from '@opentelemetry/sdk-logs';\nimport {\n buildPostHogLogProcessors,\n RedactingLogRecordProcessor,\n} from './posthog-logs';\nimport { TailSamplingSpanProcessor } from './tail-sampling-processor';\nimport { BaggageSpanProcessor } from './baggage-span-processor';\nimport {\n FilteringSpanProcessor,\n type SpanFilterPredicate,\n} from './filtering-span-processor';\nimport {\n SpanNameNormalizingProcessor,\n type SpanNameNormalizerConfig,\n} from './span-name-normalizer';\nimport {\n AttributeRedactingProcessor,\n normalizeAttributeRedactorConfig,\n type AttributeRedactorConfig,\n type AttributeRedactorPreset,\n} from './attribute-redacting-processor';\nimport { createStringRedactor, type StringRedactor } from './redact-values';\nimport { PrettyConsoleExporter } from './pretty-console-exporter';\nimport { resolveConfigFromEnv } from './env-config';\nimport { loadYamlConfig } from './yaml-config';\nimport { requireModule, safeRequire } from './node-require';\nimport {\n CanonicalLogLineProcessor,\n type CanonicalLogLineOptions,\n} from './processors/canonical-log-line-processor';\nimport type { EventsConfig } from './events-config';\nimport { resolveDevtoolsConfig, type AutotelDevtoolsConfig } from './devtools';\n\n/**\n * Silent logger (no-op) - used as default when user doesn't provide one.\n * Internal autotel logs are silent by default to avoid spam.\n * Users can import { autotelLogger } from 'autotel/logger' to create their own.\n */\nconst silentLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n debug: () => {},\n};\n\n/**\n * Adapts an Autotel Sampler to the OTel SDK Sampler interface.\n */\nfunction toOtelSampler(sampler: Sampler): OtelSampler {\n return {\n shouldSample(\n _context: Context,\n _traceId: string,\n spanName: string,\n _spanKind: SpanKind,\n _attributes: Attributes,\n links: Link[],\n ): SamplingResult {\n const shouldTrace = sampler.shouldSample({\n operationName: spanName,\n args: [],\n links,\n });\n return {\n decision: shouldTrace\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n },\n toString(): string {\n return `AutotelSamplerAdapter`;\n },\n };\n}\n\n// Type imports for exporters\ntype OTLPExporterConfig = {\n url?: string;\n headers?: Record<string, string>;\n timeoutMillis?: number;\n concurrencyLimit?: number;\n};\n\n// Lazy-load gRPC exporters (optional peer dependencies)\nlet OTLPTraceExporterGRPC:\n | (new (config: OTLPExporterConfig) => SpanExporter)\n | undefined;\nlet OTLPMetricExporterGRPC:\n | (new (config: OTLPExporterConfig) => PushMetricExporter)\n | undefined;\nlet OTLPLogExporterGRPC:\n | (new (config: OTLPExporterConfig) => LogRecordExporter)\n | undefined;\n\n/**\n * Helper: Lazy-load gRPC trace exporter\n */\nfunction loadGRPCTraceExporter(): new (\n config: OTLPExporterConfig,\n) => SpanExporter {\n if (OTLPTraceExporterGRPC) return OTLPTraceExporterGRPC;\n\n try {\n // Dynamic import for optional peer dependency\n const grpcModule = requireModule<{\n OTLPTraceExporter: new (config: OTLPExporterConfig) => SpanExporter;\n }>('@opentelemetry/exporter-trace-otlp-grpc');\n OTLPTraceExporterGRPC = grpcModule.OTLPTraceExporter;\n return OTLPTraceExporterGRPC;\n } catch {\n throw new Error(\n 'gRPC trace exporter not found. Install @opentelemetry/exporter-trace-otlp-grpc',\n );\n }\n}\n\n/**\n * Helper: Lazy-load gRPC metric exporter\n */\nfunction loadGRPCMetricExporter(): new (\n config: OTLPExporterConfig,\n) => PushMetricExporter {\n if (OTLPMetricExporterGRPC) return OTLPMetricExporterGRPC;\n\n try {\n // Dynamic import for optional peer dependency\n const grpcModule = requireModule<{\n OTLPMetricExporter: new (\n config: OTLPExporterConfig,\n ) => PushMetricExporter;\n }>('@opentelemetry/exporter-metrics-otlp-grpc');\n OTLPMetricExporterGRPC = grpcModule.OTLPMetricExporter;\n return OTLPMetricExporterGRPC;\n } catch {\n throw new Error(\n 'gRPC metric exporter not found. Install @opentelemetry/exporter-metrics-otlp-grpc',\n );\n }\n}\n\n/**\n * Helper: Create trace exporter based on protocol\n */\nfunction createTraceExporter(\n protocol: 'http' | 'grpc',\n config: OTLPExporterConfig,\n): SpanExporter {\n if (protocol === 'grpc') {\n const Exporter = loadGRPCTraceExporter();\n return new Exporter(config);\n }\n\n // Default: HTTP\n return new OTLPTraceExporterHTTP(config);\n}\n\n/**\n * Helper: Create metric exporter based on protocol\n */\nfunction createMetricExporter(\n protocol: 'http' | 'grpc',\n config: OTLPExporterConfig,\n): PushMetricExporter {\n if (protocol === 'grpc') {\n const Exporter = loadGRPCMetricExporter();\n return new Exporter(config);\n }\n\n // Default: HTTP\n return new OTLPMetricExporterHTTP(config);\n}\n\n/**\n * Helper: Lazy-load gRPC log exporter\n */\nfunction loadGRPCLogExporter(): new (\n config: OTLPExporterConfig,\n) => LogRecordExporter {\n if (OTLPLogExporterGRPC) return OTLPLogExporterGRPC;\n\n try {\n const grpcModule = requireModule<{\n OTLPLogExporter: new (config: OTLPExporterConfig) => LogRecordExporter;\n }>('@opentelemetry/exporter-logs-otlp-grpc');\n OTLPLogExporterGRPC = grpcModule.OTLPLogExporter;\n return OTLPLogExporterGRPC;\n } catch {\n throw new Error(\n 'gRPC log exporter not found. Install @opentelemetry/exporter-logs-otlp-grpc',\n );\n }\n}\n\n/**\n * Helper: Create log exporter based on protocol\n */\nfunction createLogExporter(\n protocol: 'http' | 'grpc',\n config: OTLPExporterConfig,\n): LogRecordExporter {\n if (protocol === 'grpc') {\n const Exporter = loadGRPCLogExporter();\n return new Exporter(config);\n }\n\n // Default: HTTP\n return new OTLPLogExporterHTTP(config);\n}\n\n/**\n * Helper: Resolve protocol from config and environment\n */\nfunction resolveProtocol(configProtocol?: 'http' | 'grpc'): 'http' | 'grpc' {\n // 1. Check config parameter (highest priority)\n if (configProtocol === 'grpc' || configProtocol === 'http') {\n return configProtocol;\n }\n\n // 2. Check OTEL_EXPORTER_OTLP_PROTOCOL env var\n const envProtocol = process.env.OTEL_EXPORTER_OTLP_PROTOCOL;\n if (envProtocol === 'grpc') return 'grpc';\n if (envProtocol === 'http/protobuf' || envProtocol === 'http') return 'http';\n\n // 3. Default to HTTP\n return 'http';\n}\n\n/**\n * Helper: Adjust endpoint URL for protocol\n * gRPC exporters don't need the /v1/traces or /v1/metrics path\n * HTTP exporters need the full path\n */\nfunction formatEndpointUrl(\n endpoint: string,\n signal: 'traces' | 'metrics' | 'logs',\n protocol: 'http' | 'grpc',\n): string {\n if (protocol === 'grpc') {\n // gRPC: strip any paths, return base endpoint\n return endpoint.replace(/\\/(v1\\/)?(traces|metrics|logs)$/, '');\n }\n\n // HTTP: append signal path if not present\n if (!endpoint.endsWith(`/v1/${signal}`)) {\n return `${endpoint}/v1/${signal}`;\n }\n\n return endpoint;\n}\n\n// Built-in logger is created dynamically in init() with service name\n\nexport interface AutotelConfig {\n /** Service name (required) */\n service: string;\n\n /**\n * Local developer UX for autotel-devtools.\n *\n * - `true`: send traces, metrics, and logs to `http://127.0.0.1:4318`\n * - `{ embedded: true }`: attempt to start `autotel-devtools` automatically\n *\n * When enabled:\n * - `endpoint` defaults to the local devtools URL\n * - `logs` default to `true` unless explicitly set\n *\n * This keeps production config unchanged while making local debugging\n * effectively zero-config.\n */\n devtools?: boolean | AutotelDevtoolsConfig;\n\n /** Event subscribers - bring your own (PostHog, Mixpanel, etc.) */\n subscribers?: EventSubscriber[];\n\n /**\n * Additional OpenTelemetry instrumentations to register (raw OTel classes).\n * Useful when you need custom instrumentation configs or instrumentations\n * not covered by autoInstrumentations.\n *\n * **Important:** If you need custom instrumentation configs (like `requireParentSpan: false`),\n * use EITHER manual instrumentations OR autoInstrumentations, not both for the same library.\n * Manual instrumentations always take precedence over auto-instrumentations.\n *\n * @example Manual instrumentations with custom config\n * ```typescript\n * import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb'\n *\n * init({\n * service: 'my-app',\n * autoInstrumentations: false, // Disable auto-instrumentations\n * instrumentations: [\n * new MongoDBInstrumentation({\n * requireParentSpan: false // Custom config\n * })\n * ]\n * })\n * ```\n *\n * @example Mix auto + manual (auto for most, manual for specific configs)\n * ```typescript\n * import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb'\n *\n * init({\n * service: 'my-app',\n * autoInstrumentations: ['http', 'express'], // Auto for these\n * instrumentations: [\n * new MongoDBInstrumentation({\n * requireParentSpan: false // Manual config for MongoDB\n * })\n * ]\n * })\n * ```\n */\n instrumentations?: NodeSDKConfiguration['instrumentations'];\n\n /**\n * Simple names for auto-instrumentation.\n * Uses @opentelemetry/auto-instrumentations-node (peer dependency).\n *\n * **Important:** If you provide manual instrumentations for the same library,\n * the manual config takes precedence and auto-instrumentation for that library is disabled.\n *\n * @example Enable all auto-instrumentations (simple approach)\n * ```typescript\n * init({\n * service: 'my-app',\n * autoInstrumentations: true // Enable all with defaults\n * })\n * ```\n *\n * @example Enable specific auto-instrumentations\n * ```typescript\n * init({\n * service: 'my-app',\n * autoInstrumentations: ['express', 'pino', 'http']\n * })\n * ```\n *\n * @example Configure specific auto-instrumentations\n * ```typescript\n * init({\n * service: 'my-app',\n * autoInstrumentations: {\n * express: { enabled: true },\n * pino: { enabled: true },\n * http: { enabled: false }\n * }\n * })\n * ```\n *\n * @example Manual config when you need custom settings\n * ```typescript\n * import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb'\n *\n * init({\n * service: 'my-app',\n * autoInstrumentations: false, // Use manual control\n * instrumentations: [\n * new MongoDBInstrumentation({\n * requireParentSpan: false // Custom config not available with auto\n * })\n * ]\n * })\n * ```\n */\n autoInstrumentations?:\n | string[]\n | boolean\n | Record<string, { enabled?: boolean }>;\n\n /**\n * OTLP endpoint for traces/metrics/logs\n * Only used if you don't provide custom exporters/processors\n * @default process.env.OTLP_ENDPOINT || 'http://localhost:4318'\n */\n endpoint?: string;\n\n /**\n * Custom span processors for traces (supports multiple processors)\n * Allows you to use any backend: Jaeger, Zipkin, Datadog, New Relic, etc.\n * If not provided, defaults to OTLP with tail sampling\n *\n * @example Multiple processors\n * ```typescript\n * import { JaegerExporter } from '@opentelemetry/exporter-jaeger'\n * import { BatchSpanProcessor, SimpleSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base'\n *\n * init({\n * service: 'my-app',\n * spanProcessors: [\n * new BatchSpanProcessor(new JaegerExporter()),\n * new SimpleSpanProcessor(new ConsoleSpanExporter()) // Debug alongside production\n * ]\n * })\n * ```\n *\n * @example Single processor\n * ```typescript\n * import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'\n *\n * init({\n * service: 'my-app',\n * spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())]\n * })\n * ```\n */\n spanProcessors?: SpanProcessor[];\n\n /**\n * Custom span processor for traces (single-item alias of spanProcessors)\n * @deprecated Use spanProcessors for consistency with other multi-value config fields\n */\n spanProcessor?: SpanProcessor;\n\n /**\n * Custom span exporters for traces (alternative to spanProcessors, supports multiple exporters)\n * Provide either spanProcessors OR spanExporters, not both\n * Each exporter will be wrapped in TailSamplingSpanProcessor + BatchSpanProcessor\n *\n * @example Multiple exporters\n * ```typescript\n * import { ZipkinExporter } from '@opentelemetry/exporter-zipkin'\n * import { JaegerExporter } from '@opentelemetry/exporter-jaeger'\n *\n * init({\n * service: 'my-app',\n * spanExporters: [\n * new ZipkinExporter({ url: 'http://localhost:9411/api/v2/spans' }),\n * new JaegerExporter() // Send to multiple backends simultaneously\n * ]\n * })\n * ```\n *\n * @example Single exporter\n * ```typescript\n * import { ZipkinExporter } from '@opentelemetry/exporter-zipkin'\n *\n * init({\n * service: 'my-app',\n * spanExporters: [new ZipkinExporter({ url: 'http://localhost:9411/api/v2/spans' })]\n * })\n * ```\n */\n spanExporters?: SpanExporter[];\n\n /**\n * Custom span exporter for traces (single-item alias of spanExporters)\n * @deprecated Use spanExporters for consistency with other multi-value config fields\n */\n spanExporter?: SpanExporter;\n\n /**\n * Custom metric readers (supports multiple readers)\n * Allows sending metrics to multiple backends: OTLP, Prometheus, custom readers\n * Defaults to OTLP metrics exporter when metrics are enabled.\n *\n * @example Multiple metric readers\n * ```typescript\n * import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'\n * import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\n * import { PrometheusExporter } from '@opentelemetry/exporter-prometheus'\n *\n * init({\n * service: 'my-app',\n * metricReaders: [\n * new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n * new PrometheusExporter() // Export to multiple backends\n * ]\n * })\n * ```\n */\n metricReaders?: MetricReader[];\n\n /**\n * Custom metric reader (single-item alias of metricReaders)\n * @deprecated Use metricReaders for consistency with other multi-value config fields\n */\n metricReader?: MetricReader;\n\n /**\n * Custom log record processors. When omitted, logs are not configured.\n */\n logRecordProcessors?: LogRecordProcessor[];\n\n /**\n * Custom log record processor (single-item alias of logRecordProcessors)\n * @deprecated Use logRecordProcessors for consistency with other multi-value config fields\n */\n logRecordProcessor?: LogRecordProcessor;\n\n /**\n * PostHog integration - auto-configures OTLP log exporter.\n *\n * @example\n * ```typescript\n * init({\n * service: 'my-app',\n * posthog: { url: 'https://us.i.posthog.com/i/v1/logs?token=phc_xxx' }\n * });\n * ```\n *\n * Also reads from POSTHOG_LOGS_URL environment variable as fallback.\n */\n posthog?: { url: string };\n\n /** Additional resource attributes to merge with defaults. */\n resourceAttributes?: Attributes;\n\n /** Provide a fully custom Resource to merge (advanced use case). */\n resource?: Resource;\n\n /**\n * Headers for OTLP exporters. Accepts either an object map or\n * a \"key=value\" comma separated string.\n *\n * @example\n * ```typescript\n * init({\n * service: 'my-app',\n * endpoint: 'https://api.honeycomb.io',\n * headers: { 'x-honeycomb-team': 'YOUR_API_KEY' }\n * })\n * ```\n */\n headers?: Record<string, string> | string;\n\n /**\n * OTLP protocol to use for traces, metrics, and logs\n * - 'http': HTTP/protobuf (default, uses port 4318)\n * - 'grpc': gRPC (uses port 4317)\n *\n * Can be overridden with OTEL_EXPORTER_OTLP_PROTOCOL env var.\n *\n * Note: gRPC exporters are optional peer dependencies. Install them with:\n * ```bash\n * pnpm add @opentelemetry/exporter-trace-otlp-grpc @opentelemetry/exporter-metrics-otlp-grpc\n * ```\n *\n * @example HTTP (default)\n * ```typescript\n * init({\n * service: 'my-app',\n * protocol: 'http', // or omit (defaults to http)\n * endpoint: 'http://localhost:4318'\n * })\n * ```\n *\n * @example gRPC\n * ```typescript\n * init({\n * service: 'my-app',\n * protocol: 'grpc',\n * endpoint: 'grpc://localhost:4317'\n * })\n * ```\n *\n * @default 'http'\n */\n protocol?: 'http' | 'grpc';\n\n /**\n * Optional factory to build a customised NodeSDK instance from our defaults.\n */\n sdkFactory?: (defaults: Partial<NodeSDKConfiguration>) => NodeSDK;\n\n /**\n * Infrastructure metrics configuration\n * - true: always enabled (default)\n * - false: always disabled\n * - 'auto': always enabled (same as true)\n *\n * Can be overridden with AUTOTEL_METRICS=on|off env var\n */\n metrics?: boolean | 'auto';\n\n /**\n * OTLP logs configuration\n * - true: auto-configure OTLP log exporter from endpoint\n * - false: disabled (default)\n * - 'auto': same as false (opt-in only)\n *\n * When enabled and an endpoint is configured, autotel will automatically\n * create a BatchLogRecordProcessor with an OTLPLogExporter - no manual\n * imports needed. Works alongside logRecordProcessors (additive).\n *\n * Requires @opentelemetry/sdk-logs and @opentelemetry/exporter-logs-otlp-http\n * (or -grpc) as peer dependencies.\n *\n * Can be overridden with AUTOTEL_LOGS=on|off env var.\n *\n * @example\n * ```typescript\n * init({\n * service: 'my-app',\n * endpoint: 'http://localhost:4318',\n * logs: true,\n * });\n * ```\n */\n logs?: boolean | 'auto';\n\n /** Sampling strategy - takes precedence over `sampling` preset */\n sampler?: Sampler;\n\n /**\n * Sampling preset shorthand — resolves to a pre-configured sampler.\n * If both `sampler` and `sampling` are provided, `sampler` takes precedence.\n *\n * @default 'production' (10% baseline + always-on for errors/slow)\n *\n * **Footgun for one-shot scripts:** the default samples ~90% of spans away,\n * which means a fixture-capture script that emits a single normal span\n * almost always sees zero output. For local debugging and capture use:\n *\n * ```typescript\n * init({\n * service: 'fixture-capture',\n * spanProcessors: [new SimpleSpanProcessor(new InMemorySpanExporter())],\n * sampling: 'development', // capture EVERY span\n * });\n * ```\n *\n * Read `exporter.getFinishedSpans()` **before** calling `shutdown()` —\n * `InMemorySpanExporter.shutdown()` resets state.\n */\n sampling?: SamplingPreset;\n\n /** Service version (default: auto-detect from package.json or '1.0.0') */\n version?: string;\n\n /** Environment (default: process.env.NODE_ENV || 'development') */\n environment?: string;\n\n /**\n * Logger instance for internal autotel diagnostic messages\n *\n * This logger is used by autotel internally to log initialization, warnings,\n * and debug information. Any logger with info/warn/error/debug methods works.\n *\n * **For OTel instrumentation of your application logs**, use the `autoInstrumentations` option:\n * - `autoInstrumentations: ['pino']` - Injects traceId/spanId into Pino logs\n * - `autoInstrumentations: ['winston']` - Injects traceId/spanId into Winston logs\n *\n * Default: silent logger (no-op)\n *\n * @example Pino with OTel instrumentation\n * ```typescript\n * import pino from 'pino'\n * import { init } from 'autotel'\n *\n * const logger = pino({ level: 'info' })\n * init({\n * service: 'my-app',\n * logger, // For autotel's internal logs\n * autoInstrumentations: ['pino'] // For OTel trace context in YOUR logs\n * })\n * ```\n *\n * @example Custom logger for autotel diagnostics\n * ```typescript\n * const logger = {\n * info: (msg, extra) => console.log(msg, extra),\n * warn: (msg, extra) => console.warn(msg, extra),\n * error: (msg, err, extra) => console.error(msg, err, extra),\n * debug: (msg, extra) => console.debug(msg, extra),\n * }\n * init({ service: 'my-app', logger })\n * ```\n */\n logger?: Logger;\n\n /**\n * Flush events queue when root spans end\n * - true: Flush on root span completion (default)\n * - false: Use batching (events flush every 10 seconds automatically)\n *\n * Only flushes on root spans to avoid excessive network calls.\n * Default is true for serverless/short-lived processes. Set to false\n * for long-running services where batching is more efficient.\n */\n flushOnRootSpanEnd?: boolean;\n\n /**\n * Force-flush OpenTelemetry spans on shutdown (default: false)\n *\n * When enabled, spans are force-flushed along with events on root\n * span completion. This is useful for serverless/short-lived processes where\n * spans may not export before the process ends.\n *\n * - true: Force-flush spans on root span completion (~50-200ms latency)\n * - false: Spans export via normal batch processor (default behavior)\n *\n * Only applies when flushOnRootSpanEnd is also enabled.\n *\n * Note: For edge runtimes (Cloudflare Workers, Vercel Edge), use the\n * 'autotel-edge' package instead, which handles this automatically.\n *\n * @example Serverless with force-flush\n * ```typescript\n * init({\n * service: 'my-lambda',\n * flushOnRootSpanEnd: true,\n * forceFlushOnShutdown: true, // Force-flush spans\n * });\n * ```\n */\n forceFlushOnShutdown?: boolean;\n\n /**\n * Automatically copy baggage entries to span attributes\n *\n * When enabled, all baggage entries are automatically added as span attributes,\n * making them visible in trace UIs (Jaeger, Grafana, DataDog, etc.) without\n * manually calling ctx.setAttribute() for each entry.\n *\n * - `true`: adds baggage with 'baggage.' prefix (e.g. baggage.tenant.id)\n * - `string`: uses custom prefix (e.g. 'ctx' → ctx.tenant.id, '' → tenant.id)\n * - `false` or omit: disabled (default)\n *\n * @default false\n *\n * @example Enable with default prefix\n * ```typescript\n * init({\n * service: 'my-app',\n * baggage: true\n * });\n *\n * // Now baggage automatically appears as span attributes\n * await withBaggage({\n * baggage: { 'tenant.id': 't1', 'user.id': 'u1' },\n * fn: async () => {\n * // Span has baggage.tenant.id and baggage.user.id attributes!\n * }\n * });\n * ```\n *\n * @example Custom prefix\n * ```typescript\n * init({\n * service: 'my-app',\n * baggage: 'ctx' // Uses 'ctx.' prefix\n * });\n * // Creates attributes: ctx.tenant.id, ctx.user.id\n * ```\n *\n * @example No prefix\n * ```typescript\n * init({\n * service: 'my-app',\n * baggage: '' // No prefix\n * });\n * // Creates attributes: tenant.id, user.id\n * ```\n */\n baggage?: boolean | string;\n\n /**\n * Validation configuration for events events\n * - Override default sensitive field patterns for redaction\n * - Customize max lengths, nesting depth, etc.\n *\n * @example Disable redaction for development\n * ```typescript\n * init({\n * service: 'my-app',\n * validation: {\n * sensitivePatterns: [] // Disable all redaction\n * }\n * })\n * ```\n *\n * @example Add custom patterns\n * ```typescript\n * init({\n * service: 'my-app',\n * validation: {\n * sensitivePatterns: [\n * /password/i,\n * /apiKey/i,\n * /customSecret/i // Your custom pattern\n * ]\n * }\n * })\n * ```\n */\n validation?: Partial<ValidationConfig>;\n\n /**\n * Events configuration for trace context, correlation IDs, and enrichment\n *\n * Controls how product events integrate with distributed tracing:\n * - `includeTraceContext`: Automatically include trace context in events\n * - `includeLinkedTraceIds`: Include full array of linked trace IDs (for batch/fan-in)\n * - `traceUrl`: Generate clickable trace URLs in events\n * - `enrichFromBaggage`: Auto-enrich events from baggage with guardrails\n *\n * @example Basic trace context\n * ```typescript\n * init({\n * service: 'my-app',\n * events: {\n * includeTraceContext: true\n * }\n * });\n * // Events now include autotel.trace_id, autotel.span_id, autotel.correlation_id\n * ```\n *\n * @example With clickable trace URLs\n * ```typescript\n * init({\n * service: 'my-app',\n * events: {\n * includeTraceContext: true,\n * traceUrl: (ctx) => `https://grafana.internal/explore?traceId=${ctx.traceId}`\n * }\n * });\n * ```\n *\n * @example With baggage enrichment\n * ```typescript\n * init({\n * service: 'my-app',\n * events: {\n * includeTraceContext: true,\n * enrichFromBaggage: {\n * allow: ['tenant.id', 'user.id'],\n * prefix: 'ctx.',\n * maxKeys: 10,\n * maxBytes: 1024\n * }\n * }\n * });\n * ```\n */\n events?: EventsConfig;\n\n /**\n * Debug mode for local span inspection.\n * Enables console output to help you see spans as they're created.\n *\n * - `true`: Raw JSON output (ConsoleSpanExporter)\n * - `'pretty'`: Colorized, hierarchical output (PrettyConsoleExporter)\n * - `false`/undefined: No console output (default)\n *\n * When enabled: Outputs spans to console AND sends to backend (if endpoint/exporter configured)\n *\n * Perfect for progressive development:\n * - Start with debug: 'pretty' (no endpoint) → see traces immediately with nice formatting\n * - Add endpoint later → console + backend, verify before choosing provider\n * - Remove debug in production → backend only, clean production config\n *\n * Can be overridden with AUTOTEL_DEBUG environment variable.\n *\n * @example Pretty debug output (recommended for development)\n * ```typescript\n * init({\n * service: 'my-app',\n * debug: 'pretty' // Colorized, hierarchical output\n * })\n * ```\n *\n * @example Raw JSON output (verbose)\n * ```typescript\n * init({\n * service: 'my-app',\n * debug: true // Raw ConsoleSpanExporter output\n * })\n * ```\n *\n * @example Environment variable\n * ```bash\n * AUTOTEL_DEBUG=pretty node server.js\n * AUTOTEL_DEBUG=true node server.js\n * ```\n */\n debug?: boolean | 'pretty';\n\n /**\n * Filter predicate to drop unwanted spans before processing.\n *\n * Useful for filtering out noisy spans from specific instrumentations\n * (e.g., Next.js internal spans, health check endpoints).\n *\n * The filter runs on completed spans (onEnd), so you have access to:\n * - `span.name` - Span name\n * - `span.attributes` - All span attributes\n * - `span.instrumentationScope` - `{ name, version }` of the instrumentation\n * - `span.status` - Span status code and message\n * - `span.duration` - Span duration as `[seconds, nanoseconds]`\n *\n * Return `true` to keep the span, `false` to drop it.\n *\n * @example Filter out Next.js instrumentation spans\n * ```typescript\n * init({\n * service: 'my-app',\n * spanFilter: (span) => span.instrumentationScope.name !== 'next.js'\n * })\n * ```\n *\n * @example Filter out health check spans\n * ```typescript\n * init({\n * service: 'my-app',\n * spanFilter: (span) => !span.name.includes('/health')\n * })\n * ```\n *\n * @example Complex filtering (multiple conditions)\n * ```typescript\n * init({\n * service: 'my-app',\n * spanFilter: (span) => {\n * // Drop Next.js internal spans\n * if (span.instrumentationScope.name === 'next.js') return false;\n * // Drop health checks\n * if (span.name.includes('/health')) return false;\n * // Drop very short spans (less than 1ms)\n * const [secs, nanos] = span.duration;\n * if (secs === 0 && nanos < 1_000_000) return false;\n * return true;\n * }\n * })\n * ```\n */\n spanFilter?: SpanFilterPredicate;\n\n /**\n * Normalize span names to reduce cardinality from dynamic path segments.\n *\n * High-cardinality span names (e.g., `/users/123/posts/456`) cause issues:\n * - Cost explosions in observability backends\n * - Cardinality limits exceeded\n * - Poor UX when searching/filtering traces\n *\n * The normalizer transforms dynamic segments into placeholders:\n * - `/users/123` → `/users/:id`\n * - `/items/550e8400-e29b-...` → `/items/:uuid`\n *\n * Provide either a custom function or use a built-in preset:\n * - `'rest-api'` - Numeric IDs, UUIDs, ObjectIds, dates, timestamps, emails\n * - `'graphql'` - GraphQL operation name normalization\n * - `'minimal'` - Only numeric IDs and UUIDs\n *\n * @example Custom normalizer function\n * ```typescript\n * init({\n * service: 'my-app',\n * spanNameNormalizer: (name) => {\n * return name\n * .replace(/\\/[0-9]+/g, '/:id')\n * .replace(/\\/[a-f0-9-]{36}/gi, '/:uuid');\n * }\n * })\n * ```\n *\n * @example Using built-in preset\n * ```typescript\n * init({\n * service: 'my-app',\n * spanNameNormalizer: 'rest-api'\n * })\n * ```\n *\n * @example Combining with spanFilter\n * ```typescript\n * init({\n * service: 'my-app',\n * spanNameNormalizer: 'rest-api',\n * spanFilter: (span) => span.instrumentationScope.name !== 'next.js'\n * })\n * ```\n */\n spanNameNormalizer?: SpanNameNormalizerConfig;\n\n /**\n * Automatically redact PII and sensitive data from span attributes before export.\n * Critical for compliance (GDPR, PCI-DSS, HIPAA) and data security.\n *\n * Auto-enabled in production: when this is left unset and the resolved\n * environment is `production`, the `'default'` preset is applied. Override\n * with the `AUTOTEL_REDACT_PII` env var (`off` / `strict` / `pci-dss` / ...)\n * or pass `false` to disable redaction entirely.\n *\n * Can be a preset name, custom configuration, or `false` to disable:\n * - `'default'`: Emails, phones, SSNs, credit cards, sensitive keys (password, secret, token)\n * - `'strict'`: Default + Bearer tokens, JWTs, API keys in values\n * - `'pci-dss'`: Payment card industry focus (credit cards, CVV, card-related keys)\n *\n * @example Use default preset\n * ```typescript\n * init({\n * service: 'my-app',\n * attributeRedactor: 'default'\n * })\n * ```\n *\n * @example Custom patterns\n * ```typescript\n * init({\n * service: 'my-app',\n * attributeRedactor: {\n * keyPatterns: [/password/i, /secret/i],\n * valuePatterns: [\n * { name: 'customerId', pattern: /CUST-\\d{8}/g, replacement: 'CUST-***' }\n * ]\n * }\n * })\n * ```\n *\n * @example Custom redactor function\n * ```typescript\n * init({\n * service: 'my-app',\n * attributeRedactor: {\n * redactor: (key, value) => {\n * if (key === 'user.email' && typeof value === 'string') {\n * return value.replace(/@.+/, '@[REDACTED]');\n * }\n * return value;\n * }\n * }\n * })\n * ```\n */\n attributeRedactor?: AttributeRedactorConfig | AttributeRedactorPreset | false;\n\n /**\n * OpenLLMetry integration for LLM observability.\n * Requires @traceloop/node-server-sdk as an optional peer dependency.\n *\n * @example Enable OpenLLMetry with default settings\n * ```typescript\n * init({\n * service: 'my-app',\n * openllmetry: { enabled: true }\n * })\n * ```\n *\n * @example Enable with custom options\n * ```typescript\n * init({\n * service: 'my-app',\n * openllmetry: {\n * enabled: true,\n * options: {\n * disableBatch: process.env.NODE_ENV !== 'production',\n * apiKey: process.env.TRACELOOP_API_KEY\n * }\n * }\n * })\n * ```\n */\n openllmetry?: {\n enabled: boolean;\n options?: Record<string, unknown>;\n };\n\n /**\n * Canonical log lines - automatically emit spans as wide events (canonical log lines)\n *\n * When enabled, each span (or root span only) is automatically emitted as a\n * comprehensive log record with ALL span attributes. This implements the\n * \"canonical log line\" pattern: one comprehensive event per request with all context.\n *\n * **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 * - Queryable as structured data instead of string search\n *\n * @example Basic usage (one canonical log line per request)\n * ```typescript\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 * 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 */\n canonicalLogLines?: {\n enabled: boolean;\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?: (\n span: import('@opentelemetry/sdk-trace-base').ReadableSpan,\n ) => string;\n /** Whether to include resource attributes (default: true) */\n includeResourceAttributes?: boolean;\n /** Predicate to decide whether to emit (runs after event is built). */\n shouldEmit?: CanonicalLogLineOptions['shouldEmit'];\n /**\n * Declarative tail sampling conditions (OR logic).\n * Ignored when `shouldEmit` is provided.\n * @example keep: [{ status: 500 }, { durationMs: 1000 }]\n */\n keep?: CanonicalLogLineOptions['keep'];\n /** Callback invoked after emit for custom fan-out. */\n drain?: CanonicalLogLineOptions['drain'];\n /** Handler for drain failures. */\n onDrainError?: CanonicalLogLineOptions['onDrainError'];\n /**\n * Pretty-print canonical log lines to console.\n * Defaults to true when NODE_ENV is 'development'.\n */\n pretty?: boolean;\n };\n\n /**\n * Suppress console output while keeping OTel exporters running.\n * Useful for platforms like GCP Cloud Run / AWS Lambda where stdout\n * is managed externally by the platform's log collector.\n *\n * @default false\n */\n silent?: boolean;\n\n /**\n * Minimum log level for internal autotel diagnostic messages.\n * Messages below this level are dropped before processing.\n *\n * @default 'info'\n */\n minLevel?: 'debug' | 'info' | 'warn' | 'error';\n}\n\n// Internal state\nlet initialized = false;\nlet locked = false;\nlet config: AutotelConfig | null = null;\nlet sdk: NodeSDK | null = null;\nlet warnedOnce = false;\nlet logger: Logger = silentLogger; // Silent by default - no spam\nlet validationConfig: Partial<ValidationConfig> | null = null;\nlet eventsConfig: EventsConfig | null = null;\nlet _stringRedactor: StringRedactor | null = null;\nlet _optionalRequire: typeof safeRequire = safeRequire;\nlet _devtoolsClose: (() => Promise<void> | void) | null = null;\n\nconst LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 } as const;\ntype LogLevelKey = keyof typeof LOG_LEVELS;\n\n/**\n * Lock the logger to prevent further `init()` calls.\n * Use this when framework plugins set up instrumentation and you want\n * to prevent accidental re-initialization from user code.\n */\nexport function lockLogger(): void {\n locked = true;\n}\n\n/**\n * Check if the logger has been locked.\n */\nexport function isLoggerLocked(): boolean {\n return locked;\n}\n\nfunction createSilentLogger(): Logger {\n return {\n info: () => {},\n warn: () => {},\n error: () => {},\n debug: () => {},\n };\n}\n\nfunction wrapLogger(\n base: Logger,\n silent: boolean,\n minLevel: LogLevelKey,\n): Logger {\n if (silent) return createSilentLogger();\n const threshold = LOG_LEVELS[minLevel];\n const wrap = (fn: Logger['info'], level: LogLevelKey): Logger['info'] => {\n if (LOG_LEVELS[level] < threshold) {\n return (() => {}) as Logger['info'];\n }\n return ((...args: Parameters<Logger['info']>) =>\n fn(...args)) as Logger['info'];\n };\n return {\n debug: wrap(base.debug, 'debug'),\n info: wrap(base.info, 'info'),\n warn: wrap(base.warn, 'warn'),\n error: wrap(base.error, 'error'),\n };\n}\n\n/**\n * Resolve the effective attribute redactor. Explicit config wins (`false`\n * disables). Otherwise the `AUTOTEL_REDACT_PII` env var controls it, and as a\n * final default PII redaction is auto-enabled in production.\n */\nexport function resolveAttributeRedactor(\n explicit:\n | AttributeRedactorConfig\n | AttributeRedactorPreset\n | false\n | undefined,\n environment: string,\n): AttributeRedactorConfig | AttributeRedactorPreset | undefined {\n if (explicit === false) return undefined;\n if (explicit !== undefined) return explicit;\n\n const flag = process.env.AUTOTEL_REDACT_PII?.trim().toLowerCase();\n if (flag) {\n if (['off', 'false', '0', 'none', 'disabled'].includes(flag)) {\n return undefined;\n }\n if (flag === 'default' || flag === 'strict' || flag === 'pci-dss') {\n return flag;\n }\n if (['on', 'true', '1', 'enabled'].includes(flag)) {\n return 'default';\n }\n }\n\n return environment === 'production' ? 'default' : undefined;\n}\n\nfunction detectEnvironmentAttributes(): Record<string, string> {\n const attrs: Record<string, string> = {};\n\n const commitSha =\n process.env.COMMIT_SHA ||\n process.env.GITHUB_SHA ||\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.CF_PAGES_COMMIT_SHA ||\n process.env.AWS_CODEPIPELINE_EXECUTION_ID;\n if (commitSha) attrs['service.commit.sha'] = commitSha;\n\n const region =\n process.env.VERCEL_REGION ||\n process.env.AWS_REGION ||\n process.env.AWS_DEFAULT_REGION ||\n process.env.FLY_REGION ||\n process.env.CF_REGION ||\n process.env.GOOGLE_CLOUD_REGION;\n if (region) attrs['service.region'] = region;\n\n const version =\n process.env.APP_VERSION ||\n process.env.HEROKU_RELEASE_VERSION ||\n process.env.VERCEL_GIT_COMMIT_REF;\n if (version) attrs['service.deploy.version'] = version;\n\n return attrs;\n}\n\n/**\n * Resolve metrics flag with env var override support\n */\nexport function resolveMetricsFlag(\n configFlag: boolean | 'auto' = 'auto',\n): boolean {\n // 1. Check env var override (highest priority)\n const envFlag = process.env.AUTOTEL_METRICS;\n if (envFlag === 'on' || envFlag === 'true') return true;\n if (envFlag === 'off' || envFlag === 'false') return false;\n\n // 2. Check config flag\n if (configFlag === true) return true;\n if (configFlag === false) return false;\n\n // 3. Default: enabled in all environments (simpler)\n return true;\n}\n\n/**\n * Resolve logs flag with env var override support.\n * Defaults to disabled (opt-in only) to avoid unexpected log export\n * and to preserve the upstream SDK's OTEL_LOGS_EXPORTER handling.\n */\nexport function resolveLogsFlag(\n configFlag: boolean | 'auto' = 'auto',\n): boolean {\n // 1. Check env var override (highest priority)\n const envFlag = process.env.AUTOTEL_LOGS;\n if (envFlag === 'on' || envFlag === 'true') return true;\n if (envFlag === 'off' || envFlag === 'false') return false;\n\n // 2. Check config flag\n if (configFlag === true) return true;\n if (configFlag === false) return false;\n\n // 3. Default: disabled (opt-in only)\n return false;\n}\n\n/**\n * Resolve debug flag with env var override support\n *\n * Supports:\n * - `'pretty'`: Colorized, hierarchical output (PrettyConsoleExporter)\n * - `true` / `'true'` / `'1'`: Raw JSON output (ConsoleSpanExporter)\n * - `false` / `'false'` / `'0'`: Disabled\n */\nexport function resolveDebugFlag(\n configFlag?: boolean | 'pretty',\n): boolean | 'pretty' {\n // 1. Check env var override (highest priority)\n const envFlag = process.env.AUTOTEL_DEBUG;\n if (envFlag === 'pretty') return 'pretty';\n if (envFlag === 'true' || envFlag === '1') return true;\n if (envFlag === 'false' || envFlag === '0') return false;\n\n // 2. Return config flag (defaults to false)\n return configFlag ?? false;\n}\n\nfunction normalizeOtlpHeaders(\n headers?: Record<string, string> | string,\n): Record<string, string> | undefined {\n if (!headers) return undefined;\n if (typeof headers !== 'string') return headers;\n\n const parsed: Record<string, string> = {};\n for (const pair of headers.split(',')) {\n const [key, ...valueParts] = pair.split('=');\n if (!key || valueParts.length === 0) continue;\n parsed[key.trim()] = valueParts.join('=').trim();\n }\n return parsed;\n}\n\n/**\n * Initialize autotel - Write Once, Observe Everywhere\n *\n * Follows OpenTelemetry standards: opinionated defaults with full flexibility\n * Idempotent: multiple calls are safe, last one wins\n *\n * @example Minimal setup (OTLP default)\n * ```typescript\n * init({ service: 'my-app' })\n * ```\n *\n * @example With events (observe in PostHog, Mixpanel, etc.)\n * ```typescript\n * import { PostHogSubscriber } from 'autotel-subscribers/posthog';\n *\n * init({\n * service: 'my-app',\n * subscribers: [new PostHogSubscriber({ apiKey: '...' })]\n * })\n * ```\n *\n * @example Observe in Jaeger\n * ```typescript\n * import { JaegerExporter } from '@opentelemetry/exporter-jaeger'\n *\n * init({\n * service: 'my-app',\n * spanExporter: new JaegerExporter({ endpoint: 'http://localhost:14268/api/traces' })\n * })\n * ```\n *\n * @example Observe in Zipkin\n * ```typescript\n * import { ZipkinExporter } from '@opentelemetry/exporter-zipkin'\n *\n * init({\n * service: 'my-app',\n * spanExporter: new ZipkinExporter({ url: 'http://localhost:9411/api/v2/spans' })\n * })\n * ```\n *\n * @example Observe in Datadog\n * ```typescript\n * import { DatadogSpanProcessor } from '@opentelemetry/exporter-datadog'\n *\n * init({\n * service: 'my-app',\n * spanProcessor: new DatadogSpanProcessor({ ... })\n * })\n * ```\n *\n * @example Console output (dev)\n * ```typescript\n * import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'\n *\n * init({\n * service: 'my-app',\n * spanProcessor: new SimpleSpanProcessor(new ConsoleSpanExporter())\n * })\n * ```\n */\n\nexport function init(cfg: AutotelConfig): void {\n if (locked) {\n return;\n }\n\n // Resolve configs in priority order: explicit > yaml > env > defaults\n const envConfig = resolveConfigFromEnv();\n const yamlConfig = loadYamlConfig() ?? {};\n\n // Merge configs: explicit config > yaml file > env vars > defaults\n const mergedConfig: AutotelConfig = {\n ...envConfig, // Environment variables (lowest priority)\n ...yamlConfig, // YAML file (middle priority)\n ...cfg, // Explicit config (highest priority)\n // Deep merge for resourceAttributes\n resourceAttributes: {\n ...envConfig.resourceAttributes,\n ...yamlConfig.resourceAttributes,\n ...detectEnvironmentAttributes(),\n ...cfg.resourceAttributes,\n },\n // Handle headers merge (can be string or object)\n headers: cfg.headers ?? yamlConfig.headers ?? envConfig.headers,\n } as AutotelConfig;\n\n const resolvedRedactor = resolveAttributeRedactor(\n mergedConfig.attributeRedactor,\n mergedConfig.environment || process.env.NODE_ENV || 'development',\n );\n if (resolvedRedactor === undefined) {\n mergedConfig.attributeRedactor = undefined;\n } else {\n const normalizedRedactor =\n normalizeAttributeRedactorConfig(resolvedRedactor);\n if (!normalizedRedactor) {\n throw new Error('Invalid attributeRedactor config');\n }\n mergedConfig.attributeRedactor = normalizedRedactor;\n }\n\n const devtoolsConfig = resolveDevtoolsConfig(mergedConfig.devtools);\n if (devtoolsConfig.enabled && mergedConfig.logs === undefined) {\n mergedConfig.logs = true;\n }\n\n const silent = mergedConfig.silent ?? false;\n const minLevel = mergedConfig.minLevel ?? 'info';\n const baseLogger = mergedConfig.logger || silentLogger;\n logger = wrapLogger(baseLogger, silent, minLevel);\n\n // Warn if re-initializing (same behavior in all environments)\n if (initialized) {\n logger.warn(\n {},\n '[autotel] init() called again - last config wins. This may cause unexpected behavior.',\n );\n }\n\n config = mergedConfig;\n validationConfig = mergedConfig.validation || null;\n eventsConfig = mergedConfig.events || null;\n\n // Initialize OpenTelemetry\n // Only use endpoint if explicitly configured (no default fallback)\n let endpoint = mergedConfig.endpoint ?? devtoolsConfig.endpoint;\n const otlpHeaders = normalizeOtlpHeaders(mergedConfig.headers);\n const version = mergedConfig.version || detectVersion();\n const environment =\n mergedConfig.environment || process.env.NODE_ENV || 'development';\n const metricsEnabled = resolveMetricsFlag(mergedConfig.metrics);\n const logsEnabled = resolveLogsFlag(mergedConfig.logs);\n\n if (devtoolsConfig.enabled && devtoolsConfig.embedded) {\n const devtoolsModule = _optionalRequire<{\n createDevtools?: (options?: {\n port?: number;\n host?: string;\n verbose?: boolean;\n }) => { port: number; close: () => Promise<void> | void };\n }>('autotel-devtools');\n\n if (devtoolsModule?.createDevtools) {\n const devtoolsInstance = devtoolsModule.createDevtools({\n port: devtoolsConfig.port,\n host: devtoolsConfig.host,\n verbose: devtoolsConfig.verbose,\n });\n _devtoolsClose = devtoolsInstance.close;\n endpoint = `http://${devtoolsConfig.host}:${devtoolsInstance.port}`;\n logger.info(\n {},\n `[autotel] autotel-devtools embedded server started at ${endpoint}`,\n );\n } else {\n logger.warn(\n {},\n '[autotel] devtools.embedded requested but autotel-devtools is not installed. Falling back to endpoint-only mode.',\n );\n }\n }\n\n // Detect hostname for proper Datadog correlation and Service Catalog discovery\n const hostname = detectHostname();\n\n let resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: mergedConfig.service,\n [ATTR_SERVICE_VERSION]: version,\n // Support both old and new OpenTelemetry semantic conventions for environment\n 'deployment.environment': environment, // Deprecated but widely supported\n 'deployment.environment.name': environment, // OTel v1.27.0+ standard\n });\n\n // Add hostname attributes for Datadog Service Catalog and infrastructure correlation\n if (hostname) {\n resource = resource.merge(\n resourceFromAttributes({\n 'host.name': hostname, // OpenTelemetry standard\n 'datadog.host.name': hostname, // Datadog-specific, highest priority for Datadog\n }),\n );\n }\n\n if (mergedConfig.resource) {\n resource = resource.merge(mergedConfig.resource);\n }\n\n if (mergedConfig.resourceAttributes) {\n resource = resource.merge(\n resourceFromAttributes(mergedConfig.resourceAttributes),\n );\n }\n\n // Resolve OTLP protocol (http or grpc)\n const protocol = resolveProtocol(mergedConfig.protocol);\n\n // Backward-compatible singular aliases. Plural forms take precedence when both are provided.\n const configuredSpanProcessors =\n mergedConfig.spanProcessors && mergedConfig.spanProcessors.length > 0\n ? mergedConfig.spanProcessors\n : mergedConfig.spanProcessor\n ? [mergedConfig.spanProcessor]\n : undefined;\n const configuredSpanExporters =\n mergedConfig.spanExporters && mergedConfig.spanExporters.length > 0\n ? mergedConfig.spanExporters\n : mergedConfig.spanExporter\n ? [mergedConfig.spanExporter]\n : undefined;\n const configuredMetricReaders =\n mergedConfig.metricReaders && mergedConfig.metricReaders.length > 0\n ? mergedConfig.metricReaders\n : mergedConfig.metricReader\n ? [mergedConfig.metricReader]\n : undefined;\n const configuredLogRecordProcessors =\n mergedConfig.logRecordProcessors &&\n mergedConfig.logRecordProcessors.length > 0\n ? mergedConfig.logRecordProcessors\n : mergedConfig.logRecordProcessor\n ? [mergedConfig.logRecordProcessor]\n : undefined;\n\n // Build array of span processors (supports multiple)\n let spanProcessors: SpanProcessor[] = [];\n\n if (configuredSpanProcessors && configuredSpanProcessors.length > 0) {\n // User provided custom processors (full control)\n spanProcessors.push(...configuredSpanProcessors);\n } else if (configuredSpanExporters && configuredSpanExporters.length > 0) {\n // User provided custom exporters (wrap each with tail sampling)\n for (const exporter of configuredSpanExporters) {\n spanProcessors.push(\n new TailSamplingSpanProcessor(new BatchSpanProcessor(exporter)),\n );\n }\n } else if (endpoint) {\n // Default: OTLP with tail sampling (only if endpoint is configured)\n const traceExporter = createTraceExporter(protocol, {\n url: formatEndpointUrl(endpoint, 'traces', protocol),\n headers: otlpHeaders,\n });\n\n spanProcessors.push(\n new TailSamplingSpanProcessor(new BatchSpanProcessor(traceExporter)),\n );\n }\n // If no endpoint and no custom processors/exporters, array remains empty\n // SDK will still work but won't export traces\n\n // Add baggage span processor if enabled\n if (mergedConfig.baggage) {\n const prefix =\n typeof mergedConfig.baggage === 'string'\n ? mergedConfig.baggage\n ? `${mergedConfig.baggage}.`\n : ''\n : 'baggage.';\n spanProcessors.push(new BaggageSpanProcessor({ prefix }));\n }\n\n // Apply debug mode configuration\n const debugMode = resolveDebugFlag(mergedConfig.debug);\n\n if (debugMode === 'pretty') {\n // Pretty debug: colorized, hierarchical output\n spanProcessors.push(new SimpleSpanProcessor(new PrettyConsoleExporter()));\n } else if (debugMode === true) {\n // Raw debug: JSON output\n spanProcessors.push(new SimpleSpanProcessor(new ConsoleSpanExporter()));\n }\n\n // Add canonical log line processor BEFORE wrapping processors\n // This ensures it gets wrapped with the same filter/normalizer/redactor as other processors,\n // so canonical logs respect spanFilter (filtered spans aren't logged), spanNameNormalizer\n // (normalized names are used), and attributeRedactor (sensitive data is redacted).\n if (mergedConfig.canonicalLogLines?.enabled) {\n const canonicalOptions: CanonicalLogLineOptions = {\n logger: mergedConfig.canonicalLogLines.logger || mergedConfig.logger,\n rootSpansOnly: mergedConfig.canonicalLogLines.rootSpansOnly,\n minLevel: mergedConfig.canonicalLogLines.minLevel,\n messageFormat: mergedConfig.canonicalLogLines.messageFormat,\n includeResourceAttributes:\n mergedConfig.canonicalLogLines.includeResourceAttributes,\n shouldEmit: mergedConfig.canonicalLogLines.shouldEmit,\n keep: mergedConfig.canonicalLogLines.keep,\n drain: mergedConfig.canonicalLogLines.drain,\n onDrainError: mergedConfig.canonicalLogLines.onDrainError,\n pretty: mergedConfig.canonicalLogLines.pretty,\n };\n spanProcessors.push(new CanonicalLogLineProcessor(canonicalOptions));\n }\n\n // Wrap processors in order: redactor (innermost) → normalizer → filter (outermost)\n // This ensures onEnd() execution order is: filter → normalizer → redactor\n // So filtering sees original attributes, and redaction happens last before export.\n\n // Step 1: Wrap with AttributeRedactingProcessor (innermost - executes last in onEnd)\n if (mergedConfig.attributeRedactor && spanProcessors.length > 0) {\n const redactor = mergedConfig.attributeRedactor;\n spanProcessors = spanProcessors.map(\n (processor) =>\n new AttributeRedactingProcessor(processor, {\n redactor,\n }),\n );\n }\n\n // Store string redactor for use by PostHog log/subscriber paths\n if (mergedConfig.attributeRedactor) {\n _stringRedactor = createStringRedactor(mergedConfig.attributeRedactor);\n }\n\n // Wire string redactor to subscribers that support it (e.g., PostHogSubscriber)\n if (_stringRedactor && mergedConfig.subscribers) {\n for (const subscriber of mergedConfig.subscribers) {\n if (\n 'setStringRedactor' in subscriber &&\n typeof (subscriber as any).setStringRedactor === 'function'\n ) {\n (subscriber as any).setStringRedactor(_stringRedactor);\n }\n }\n }\n\n // Step 2: Wrap with SpanNameNormalizingProcessor (middle)\n // Normalizer runs in onStart(), so span names are normalized before any onEnd processing\n if (mergedConfig.spanNameNormalizer && spanProcessors.length > 0) {\n spanProcessors = spanProcessors.map(\n (processor) =>\n new SpanNameNormalizingProcessor(processor, {\n normalizer: mergedConfig.spanNameNormalizer!,\n }),\n );\n }\n\n // Step 3: Wrap with FilteringSpanProcessor (outermost - executes first in onEnd)\n // Filter sees original (unredacted) attributes, so it can match on sensitive values\n if (mergedConfig.spanFilter && spanProcessors.length > 0) {\n spanProcessors = spanProcessors.map(\n (processor) =>\n new FilteringSpanProcessor(processor, {\n filter: mergedConfig.spanFilter!,\n }),\n );\n }\n\n // Build array of metric readers (supports multiple)\n const metricReaders: MetricReader[] = [];\n\n if (configuredMetricReaders && configuredMetricReaders.length > 0) {\n // User provided custom metric readers\n metricReaders.push(...configuredMetricReaders);\n } else if (metricsEnabled && endpoint) {\n // Default: OTLP metrics exporter (only if endpoint is configured)\n const metricExporter = createMetricExporter(protocol, {\n url: formatEndpointUrl(endpoint, 'metrics', protocol),\n headers: otlpHeaders,\n });\n\n metricReaders.push(\n new PeriodicExportingMetricReader({\n exporter: metricExporter,\n }),\n );\n }\n\n let logRecordProcessors: LogRecordProcessor[] | undefined;\n if (\n configuredLogRecordProcessors &&\n configuredLogRecordProcessors.length > 0\n ) {\n logRecordProcessors = [...configuredLogRecordProcessors];\n }\n\n // Auto-configure OTLP log exporter when logs are enabled and endpoint is set\n if (logsEnabled && endpoint) {\n const logExporter = createLogExporter(protocol, {\n url: formatEndpointUrl(endpoint, 'logs', protocol),\n headers: otlpHeaders,\n });\n\n let processor: LogRecordProcessor = new BatchLogRecordProcessor(\n logExporter,\n );\n if (_stringRedactor) {\n processor = new RedactingLogRecordProcessor(processor, _stringRedactor);\n }\n if (!logRecordProcessors) {\n logRecordProcessors = [];\n }\n logRecordProcessors.push(processor);\n logger.info({}, '[autotel] OTLP log exporter configured');\n }\n\n // PostHog OTLP logs integration\n const posthogProcessors = buildPostHogLogProcessors(\n mergedConfig.posthog,\n _stringRedactor,\n );\n if (posthogProcessors.length > 0) {\n if (!logRecordProcessors) {\n logRecordProcessors = [];\n }\n logRecordProcessors.push(...posthogProcessors);\n logger.info({}, '[autotel] PostHog OTLP logs configured');\n }\n\n // Handle instrumentations: merge manual instrumentations with auto-instrumentations\n let finalInstrumentations: NodeSDKConfiguration['instrumentations'] =\n mergedConfig.instrumentations ? [...mergedConfig.instrumentations] : [];\n\n if (\n mergedConfig.autoInstrumentations !== undefined &&\n mergedConfig.autoInstrumentations !== false\n ) {\n // Check for ESM mode and provide guidance\n const isESM = isESMMode();\n if (isESM) {\n logger.info(\n {},\n '[autotel] ESM mode detected. For auto-instrumentation to work:\\n' +\n ' 1. Install @opentelemetry/auto-instrumentations-node as a direct dependency\\n' +\n ' 2. Import autotel/register FIRST in your instrumentation file\\n' +\n ' 3. Use getNodeAutoInstrumentations() directly instead of autoInstrumentations\\n' +\n ' See: https://github.com/jagreehal/autotel#esm-setup',\n );\n }\n\n try {\n // Detect manual instrumentations to avoid conflicts\n const manualInstrumentationNames = getInstrumentationNames(\n mergedConfig.instrumentations ?? [],\n );\n\n // Warn if both autoInstrumentations and manual instrumentations are provided\n if (manualInstrumentationNames.size > 0) {\n const manualNames = [...manualInstrumentationNames].join(', ');\n logger.info(\n {},\n `[autotel] Detected manual instrumentations (${manualNames}). ` +\n 'These will take precedence over auto-instrumentations. ' +\n 'Tip: Set autoInstrumentations:false if you want full manual control, or remove manual configs to use auto-instrumentations.',\n );\n }\n\n const autoInstrumentations = getAutoInstrumentations(\n mergedConfig.autoInstrumentations,\n manualInstrumentationNames,\n );\n if (autoInstrumentations && autoInstrumentations.length > 0) {\n // Cast to proper type - getNodeAutoInstrumentations returns the correct type\n finalInstrumentations = [\n ...finalInstrumentations,\n ...(autoInstrumentations as NodeSDKConfiguration['instrumentations']),\n ];\n }\n } catch (error) {\n logger.warn(\n {},\n `[autotel] Failed to configure auto-instrumentations: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n const autotelSampler =\n mergedConfig.sampler ??\n (mergedConfig.sampling\n ? resolveSamplingPreset(mergedConfig.sampling)\n : undefined);\n if (autotelSampler) {\n mergedConfig.sampler = autotelSampler;\n }\n const sampler: OtelSampler = autotelSampler\n ? toOtelSampler(autotelSampler)\n : (envConfig.otelSampler ?? toOtelSampler(samplingPresets.production()));\n\n const sdkOptions: Partial<NodeSDKConfiguration> = {\n resource,\n sampler,\n instrumentations: finalInstrumentations,\n };\n\n if (spanProcessors.length > 0) {\n sdkOptions.spanProcessors = spanProcessors;\n }\n\n if (metricReaders.length > 0) {\n sdkOptions.metricReaders = metricReaders;\n }\n\n if (logRecordProcessors && logRecordProcessors.length > 0) {\n sdkOptions.logRecordProcessors = logRecordProcessors;\n }\n\n sdk = mergedConfig.sdkFactory\n ? mergedConfig.sdkFactory(sdkOptions)\n : new NodeSDK(sdkOptions);\n\n if (!sdk) {\n throw new Error('[autotel] sdkFactory must return a NodeSDK instance');\n }\n\n sdk.start();\n\n // Initialize OpenLLMetry if enabled (after SDK starts to reuse tracer provider)\n if (mergedConfig.openllmetry?.enabled) {\n const traceloop = _optionalRequire<{\n initialize?: (options?: Record<string, unknown>) => void;\n }>('@traceloop/node-server-sdk');\n\n if (traceloop) {\n const initOptions: Record<string, unknown> = {\n ...mergedConfig.openllmetry.options,\n };\n\n // Reuse autotel's tracer provider\n try {\n // Type assertion needed as getTracerProvider is not in the public NodeSDK interface\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const tracerProvider = (sdk as any).getTracerProvider();\n initOptions.tracerProvider = tracerProvider;\n } catch {\n // Ignore if tracer provider not available\n }\n\n // Pass span exporter to OpenLLMetry if provided\n if (configuredSpanExporters?.[0]) {\n initOptions.exporter = configuredSpanExporters[0];\n }\n\n if (typeof traceloop.initialize === 'function') {\n traceloop.initialize(initOptions);\n logger.info({}, '[autotel] OpenLLMetry initialized successfully');\n } else {\n logger.warn(\n {},\n '[autotel] OpenLLMetry initialize function not found. Check @traceloop/node-server-sdk version.',\n );\n }\n } else {\n logger.warn(\n {},\n '[autotel] OpenLLMetry enabled but @traceloop/node-server-sdk is not installed. ' +\n 'Install it as a peer dependency to use OpenLLMetry integration.',\n );\n }\n }\n\n initialized = true;\n}\n\n/**\n * Extract instrumentation class names from instrumentation instances\n * Used to detect duplicates between manual and auto instrumentations\n */\nfunction getInstrumentationNames(\n instrumentations: NodeSDKConfiguration['instrumentations'],\n): Set<string> {\n const names = new Set<string>();\n\n if (!instrumentations) return names;\n\n for (const instrumentation of instrumentations) {\n if (instrumentation && typeof instrumentation === 'object') {\n names.add(instrumentation.constructor.name);\n }\n }\n\n return names;\n}\n\n/**\n * Map common instrumentation class names to their package names\n * Used to disable auto-instrumentations when user provides manual configs\n */\nconst INSTRUMENTATION_CLASS_TO_PACKAGE: Record<string, string> = {\n HttpInstrumentation: '@opentelemetry/instrumentation-http',\n HttpsInstrumentation: '@opentelemetry/instrumentation-http',\n ExpressInstrumentation: '@opentelemetry/instrumentation-express',\n FastifyInstrumentation: '@opentelemetry/instrumentation-fastify',\n MongoDBInstrumentation: '@opentelemetry/instrumentation-mongodb',\n MongooseInstrumentation: '@opentelemetry/instrumentation-mongoose',\n PrismaInstrumentation: '@opentelemetry/instrumentation-prisma',\n PinoInstrumentation: '@opentelemetry/instrumentation-pino',\n WinstonInstrumentation: '@opentelemetry/instrumentation-winston',\n RedisInstrumentation: '@opentelemetry/instrumentation-redis',\n GraphQLInstrumentation: '@opentelemetry/instrumentation-graphql',\n GrpcInstrumentation: '@opentelemetry/instrumentation-grpc',\n IORedisInstrumentation: '@opentelemetry/instrumentation-ioredis',\n KnexInstrumentation: '@opentelemetry/instrumentation-knex',\n NestJsInstrumentation: '@opentelemetry/instrumentation-nestjs-core',\n PgInstrumentation: '@opentelemetry/instrumentation-pg',\n MySQLInstrumentation: '@opentelemetry/instrumentation-mysql',\n MySQL2Instrumentation: '@opentelemetry/instrumentation-mysql2',\n};\n\n/**\n * Type for the auto-instrumentations loader function\n * @internal Used for testing injection\n */\nexport type AutoInstrumentationsLoader = (\n config?: Record<string, { enabled?: boolean }>,\n) => unknown[];\n\n/**\n * Detect if we're running in ESM mode\n */\nfunction isESMMode(): boolean {\n // Check if we're in an ESM context by looking for common ESM indicators\n try {\n // In ESM, module.exports doesn't exist in the global scope the same way\n // Also check if the package.json type is \"module\"\n const fs = requireModule<typeof import('node:fs')>('node:fs');\n try {\n const pkg = JSON.parse(\n fs.readFileSync(`${process.cwd()}/package.json`, 'utf8'),\n );\n return pkg.type === 'module';\n } catch {\n return false;\n }\n } catch {\n return false;\n }\n}\n\n/**\n * Lazy-load auto-instrumentations (optional peer dependency)\n * Only loads when integrations config is truthy, avoiding ~40+ package imports at startup.\n */\nfunction loadNodeAutoInstrumentations(): AutoInstrumentationsLoader {\n try {\n const mod = requireModule<{\n getNodeAutoInstrumentations: AutoInstrumentationsLoader;\n }>('@opentelemetry/auto-instrumentations-node');\n return mod.getNodeAutoInstrumentations;\n } catch {\n const isESM = isESMMode();\n const baseMessage = '@opentelemetry/auto-instrumentations-node not found.';\n\n if (isESM) {\n throw new Error(\n `${baseMessage}\\n\\n` +\n 'ESM Setup Required:\\n' +\n '1. Install as a direct dependency: pnpm add @opentelemetry/auto-instrumentations-node\\n' +\n '2. Create instrumentation.mjs with:\\n' +\n \" import 'autotel/register'; // MUST be first!\\n\" +\n \" import { init } from 'autotel';\\n\" +\n \" import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\\n\" +\n ' init({ service: \"my-app\", instrumentations: getNodeAutoInstrumentations() });\\n' +\n '3. Run with: tsx --import ./instrumentation.mjs src/index.ts\\n\\n' +\n 'See: https://github.com/jagreehal/autotel#esm-setup',\n );\n }\n\n throw new Error(\n `${baseMessage} Install it: pnpm add @opentelemetry/auto-instrumentations-node`,\n );\n }\n}\n\n/**\n * Injectable loader for testing. Set to override the default loader.\n * @internal\n */\nlet _autoInstrumentationsLoader: (() => AutoInstrumentationsLoader) | null =\n null;\n\n/**\n * @internal Set custom loader (for testing)\n */\nexport function _setAutoInstrumentationsLoader(\n loader: (() => AutoInstrumentationsLoader) | null,\n): void {\n _autoInstrumentationsLoader = loader;\n}\n\n/**\n * @internal Reset loader to default (for testing cleanup)\n */\nexport function _resetAutoInstrumentationsLoader(): void {\n _autoInstrumentationsLoader = null;\n}\n\n/**\n * Get auto-instrumentations based on simple integration names\n * Excludes instrumentations that are manually provided to avoid conflicts\n */\nfunction getAutoInstrumentations(\n integrations: string[] | boolean | Record<string, { enabled?: boolean }>,\n manualInstrumentationNames: Set<string> = new Set(),\n): unknown[] {\n if (integrations === false) {\n return [];\n }\n\n // Use injected loader if set (for testing), otherwise lazy-load\n const getNodeAutoInstrumentations = _autoInstrumentationsLoader\n ? _autoInstrumentationsLoader()\n : loadNodeAutoInstrumentations();\n\n // Build exclusion config for manual instrumentations\n const exclusionConfig: Record<string, { enabled: boolean }> = {};\n for (const className of manualInstrumentationNames) {\n const packageName = INSTRUMENTATION_CLASS_TO_PACKAGE[className];\n if (packageName) {\n exclusionConfig[packageName] = { enabled: false };\n }\n }\n\n if (integrations === true) {\n // If exclusions exist, pass them to getNodeAutoInstrumentations\n if (Object.keys(exclusionConfig).length > 0) {\n return getNodeAutoInstrumentations(exclusionConfig);\n }\n return getNodeAutoInstrumentations();\n }\n\n if (Array.isArray(integrations)) {\n const config: Record<string, { enabled: boolean }> = { ...exclusionConfig };\n for (const name of integrations) {\n const packageName = `@opentelemetry/instrumentation-${name}`;\n // Don't override exclusions\n if (!exclusionConfig[packageName]) {\n config[packageName] = { enabled: true };\n }\n }\n return getNodeAutoInstrumentations(config);\n }\n\n const config: Record<string, { enabled?: boolean }> = {\n ...exclusionConfig,\n ...integrations,\n };\n\n // Override any integrations that conflict with manual instrumentations\n for (const packageName of Object.keys(exclusionConfig)) {\n const integrationsKey = Object.keys(integrations).find((key) =>\n packageName.includes(key),\n );\n if (integrationsKey) {\n // Manual instrumentation takes precedence\n config[packageName] = { enabled: false };\n }\n }\n\n return getNodeAutoInstrumentations(config);\n}\n\n/**\n * Check if autotel has been initialized\n */\nexport function isInitialized(): boolean {\n return initialized;\n}\n\n/**\n * Get current config (internal use)\n */\nexport function getConfig(): AutotelConfig | null {\n return config;\n}\n\n/**\n * Get current logger (internal use)\n */\nexport function getLogger(): Logger {\n return logger;\n}\n\n/**\n * Get validation config (internal use)\n */\nexport function getValidationConfig(): Partial<ValidationConfig> | null {\n return validationConfig;\n}\n\n/**\n * Get events config (internal use)\n */\nexport function getEventsConfig(): EventsConfig | null {\n return eventsConfig;\n}\n\n/**\n * Warn once if not initialized (same behavior in all environments)\n */\nexport function warnIfNotInitialized(context: string): void {\n if (!initialized && !warnedOnce) {\n logger.warn(\n {},\n `[autotel] ${context} used before init() called. ` +\n 'Call init({ service: \"...\" }) first. See: https://docs.autotel.dev/quickstart',\n );\n warnedOnce = true;\n }\n}\n\n/**\n * Get default sampler\n */\nexport function getDefaultSampler(): Sampler {\n return config?.sampler || samplingPresets.production();\n}\n\n/**\n * Auto-detect version from package.json\n */\nfunction detectVersion(): string {\n try {\n // Try to read package.json from cwd using fs\n const fs = requireModule<typeof import('node:fs')>('node:fs');\n const pkg = JSON.parse(\n fs.readFileSync(`${process.cwd()}/package.json`, 'utf8'),\n );\n return pkg.version || '1.0.0';\n } catch {\n return '1.0.0';\n }\n}\n\n/**\n * Detect hostname for resource attributes.\n * Supports Datadog conventions (DD_HOSTNAME) and falls back to system hostname.\n *\n * Priority order:\n * 1. DD_HOSTNAME environment variable (Datadog convention)\n * 2. HOSTNAME environment variable (common Unix convention)\n * 3. os.hostname() (system hostname)\n *\n * @returns hostname string or undefined if detection fails\n */\nfunction detectHostname(): string | undefined {\n // Priority 1: DD_HOSTNAME (Datadog convention)\n if (process.env.DD_HOSTNAME) {\n return process.env.DD_HOSTNAME;\n }\n\n // Priority 2: HOSTNAME (common in containers and Unix systems)\n if (process.env.HOSTNAME) {\n return process.env.HOSTNAME;\n }\n\n // Priority 3: System hostname\n try {\n const os = requireModule<typeof import('node:os')>('node:os');\n return os.hostname();\n } catch {\n // os module not available (edge runtime, browser, etc.)\n return undefined;\n }\n}\n\n/**\n * Get the string redactor configured via init({ attributeRedactor }).\n * Returns null if no redactor was configured.\n */\nexport function getStringRedactor(): StringRedactor | null {\n return _stringRedactor;\n}\n\n/**\n * @internal Override optional require for deterministic tests.\n */\nexport function _setOptionalRequireForTesting(\n loader: typeof safeRequire,\n): void {\n _optionalRequire = loader;\n}\n\n/**\n * @internal Reset optional require override.\n */\nexport function _resetOptionalRequireForTesting(): void {\n _optionalRequire = safeRequire;\n}\n\n/**\n * @internal Close embedded devtools if running.\n */\nexport async function _closeEmbeddedDevtools(): Promise<void> {\n if (_devtoolsClose) {\n await _devtoolsClose();\n _devtoolsClose = null;\n }\n}\n\n/**\n * @internal Get embedded devtools close handle.\n */\nexport function _getEmbeddedDevtoolsCloseForTesting():\n | (() => Promise<void> | void)\n | null {\n return _devtoolsClose;\n}\n\n/**\n * Get SDK instance (for shutdown)\n */\nexport function getSdk(): NodeSDK | null {\n return sdk;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIA,IAAa,8BAAb,MAAuE;CAE3D;CACA;CAFV,YACE,AAAQ,SACR,AAAQ,QACR;EAFQ;EACA;CACP;CAEH,OAAO,WAAgB,SAAqB;EAC1C,IAAI,UAAU,QAAQ,OAAO,UAAU,SAAS,UAC9C,UAAU,OAAO,KAAK,OAAO,UAAU,IAAI;EAE7C,IAAI,UAAU,YACZ;QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,UAAU,GAC5D,IAAI,OAAO,UAAU,UACnB,UAAU,WAAW,OAAO,KAAK,OAAO,KAAK;QACxC,IAAI,MAAM,QAAQ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