autotel 3.0.6 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/attribute-redacting-processor.cjs +0 -1
  2. package/dist/attribute-redacting-processor.js +0 -1
  3. package/dist/attributes.cjs +0 -1
  4. package/dist/attributes.js +0 -1
  5. package/dist/auto.cjs +5 -6
  6. package/dist/auto.cjs.map +1 -1
  7. package/dist/auto.js +3 -4
  8. package/dist/auto.js.map +1 -1
  9. package/dist/business-baggage.cjs +0 -1
  10. package/dist/business-baggage.js +0 -1
  11. package/dist/{chunk-H5YFU4SF.js → chunk-6VVEOLG5.js} +4 -4
  12. package/dist/{chunk-H5YFU4SF.js.map → chunk-6VVEOLG5.js.map} +1 -1
  13. package/dist/{chunk-XCFDXZF3.cjs → chunk-727YZJUB.cjs} +7 -7
  14. package/dist/{chunk-XCFDXZF3.cjs.map → chunk-727YZJUB.cjs.map} +1 -1
  15. package/dist/{chunk-3SDILILG.js → chunk-7NDHLHZK.js} +3 -3
  16. package/dist/{chunk-3SDILILG.js.map → chunk-7NDHLHZK.js.map} +1 -1
  17. package/dist/{chunk-DAZ7EGR4.cjs → chunk-ADZDAWNV.cjs} +17 -17
  18. package/dist/{chunk-DAZ7EGR4.cjs.map → chunk-ADZDAWNV.cjs.map} +1 -1
  19. package/dist/{chunk-NCSMD3TK.cjs → chunk-BGAR6MCX.cjs} +4 -4
  20. package/dist/{chunk-NCSMD3TK.cjs.map → chunk-BGAR6MCX.cjs.map} +1 -1
  21. package/dist/{chunk-OC6X2VIN.cjs → chunk-BTEPYWDF.cjs} +4 -4
  22. package/dist/{chunk-OC6X2VIN.cjs.map → chunk-BTEPYWDF.cjs.map} +1 -1
  23. package/dist/chunk-EQIY6C3X.cjs +25 -0
  24. package/dist/chunk-EQIY6C3X.cjs.map +1 -0
  25. package/dist/{chunk-HLAVN3JR.js → chunk-I7ODAZJL.js} +3 -3
  26. package/dist/{chunk-HLAVN3JR.js.map → chunk-I7ODAZJL.js.map} +1 -1
  27. package/dist/{chunk-Z7VAOK5X.js → chunk-IC4AZUGC.js} +3 -3
  28. package/dist/{chunk-Z7VAOK5X.js.map → chunk-IC4AZUGC.js.map} +1 -1
  29. package/dist/{chunk-BPO2PQ3T.cjs → chunk-ISEHXVMD.cjs} +30 -26
  30. package/dist/chunk-ISEHXVMD.cjs.map +1 -0
  31. package/dist/{chunk-S4S4AINO.js → chunk-JITYRSI4.js} +5 -5
  32. package/dist/{chunk-S4S4AINO.js.map → chunk-JITYRSI4.js.map} +1 -1
  33. package/dist/{chunk-KKGM42RQ.cjs → chunk-KAELJC6T.cjs} +13 -13
  34. package/dist/{chunk-KKGM42RQ.cjs.map → chunk-KAELJC6T.cjs.map} +1 -1
  35. package/dist/{chunk-ZJ5E5OFB.js → chunk-KGBRZ7J5.js} +3 -3
  36. package/dist/{chunk-ZJ5E5OFB.js.map → chunk-KGBRZ7J5.js.map} +1 -1
  37. package/dist/{chunk-33WTKH7X.js → chunk-KPNV2GPW.js} +4 -4
  38. package/dist/chunk-KPNV2GPW.js.map +1 -0
  39. package/dist/{chunk-IRJHH6PH.cjs → chunk-LOTJ7SDI.cjs} +5 -5
  40. package/dist/{chunk-IRJHH6PH.cjs.map → chunk-LOTJ7SDI.cjs.map} +1 -1
  41. package/dist/{chunk-OM4OSBOP.js → chunk-MAITXZFR.js} +4 -4
  42. package/dist/{chunk-OM4OSBOP.js.map → chunk-MAITXZFR.js.map} +1 -1
  43. package/dist/{chunk-DSMSIVTG.js → chunk-MBEHEGQE.js} +3 -3
  44. package/dist/{chunk-DSMSIVTG.js.map → chunk-MBEHEGQE.js.map} +1 -1
  45. package/dist/{chunk-K4UDKM3P.cjs → chunk-NC5BG7B3.cjs} +11 -11
  46. package/dist/{chunk-K4UDKM3P.cjs.map → chunk-NC5BG7B3.cjs.map} +1 -1
  47. package/dist/{chunk-ZDPIWKWD.js → chunk-SIMG4IGE.js} +18 -14
  48. package/dist/chunk-SIMG4IGE.js.map +1 -0
  49. package/dist/{chunk-TY4NXDYR.cjs → chunk-VNMT2TDZ.cjs} +36 -36
  50. package/dist/{chunk-TY4NXDYR.cjs.map → chunk-VNMT2TDZ.cjs.map} +1 -1
  51. package/dist/config.cjs +0 -1
  52. package/dist/config.js +0 -1
  53. package/dist/correlation-id.cjs +12 -13
  54. package/dist/correlation-id.js +4 -5
  55. package/dist/db.cjs +0 -1
  56. package/dist/db.cjs.map +1 -1
  57. package/dist/db.js +0 -1
  58. package/dist/db.js.map +1 -1
  59. package/dist/decorators.cjs +7 -8
  60. package/dist/decorators.cjs.map +1 -1
  61. package/dist/decorators.js +6 -7
  62. package/dist/decorators.js.map +1 -1
  63. package/dist/drain-pipeline.cjs +0 -1
  64. package/dist/drain-pipeline.js +0 -1
  65. package/dist/enrichers.cjs +0 -2
  66. package/dist/enrichers.cjs.map +1 -1
  67. package/dist/enrichers.js +0 -2
  68. package/dist/enrichers.js.map +1 -1
  69. package/dist/event-testing.cjs +0 -1
  70. package/dist/event-testing.js +0 -1
  71. package/dist/event.cjs +8 -9
  72. package/dist/event.js +5 -6
  73. package/dist/exporters.cjs +0 -1
  74. package/dist/exporters.js +0 -1
  75. package/dist/filtering-span-processor.cjs +0 -1
  76. package/dist/filtering-span-processor.js +0 -1
  77. package/dist/functional.cjs +13 -14
  78. package/dist/functional.js +6 -7
  79. package/dist/http.cjs +5 -6
  80. package/dist/http.cjs.map +1 -1
  81. package/dist/http.js +4 -5
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.cjs +82 -83
  84. package/dist/index.cjs.map +1 -1
  85. package/dist/index.d.cts +1 -1
  86. package/dist/index.d.ts +1 -1
  87. package/dist/index.js +14 -15
  88. package/dist/index.js.map +1 -1
  89. package/dist/{init-D6JfWEjL.d.ts → init-BSyIyDs5.d.ts} +36 -1
  90. package/dist/{init-CMuTaFAV.d.cts → init-D9Bxx39e.d.cts} +36 -1
  91. package/dist/instrumentation.cjs +11 -12
  92. package/dist/instrumentation.cjs.map +1 -1
  93. package/dist/instrumentation.js +3 -4
  94. package/dist/instrumentation.js.map +1 -1
  95. package/dist/logger.cjs +0 -1
  96. package/dist/logger.js +0 -1
  97. package/dist/messaging-adapters.cjs +1 -1
  98. package/dist/messaging-adapters.js +1 -1
  99. package/dist/messaging-testing.cjs +0 -2
  100. package/dist/messaging-testing.cjs.map +1 -1
  101. package/dist/messaging-testing.js +0 -2
  102. package/dist/messaging-testing.js.map +1 -1
  103. package/dist/messaging.cjs +10 -11
  104. package/dist/messaging.js +7 -8
  105. package/dist/metric-helpers.cjs +0 -1
  106. package/dist/metric-helpers.js +0 -1
  107. package/dist/metric-testing.cjs +0 -1
  108. package/dist/metric-testing.js +0 -1
  109. package/dist/metric.cjs +0 -1
  110. package/dist/metric.js +0 -1
  111. package/dist/parse-error.cjs +0 -1
  112. package/dist/parse-error.js +0 -1
  113. package/dist/processors.cjs +0 -1
  114. package/dist/processors.js +0 -1
  115. package/dist/sampling.cjs +0 -1
  116. package/dist/sampling.js +0 -1
  117. package/dist/semantic-conventions.cjs +0 -1
  118. package/dist/semantic-conventions.js +0 -1
  119. package/dist/semantic-helpers.cjs +11 -12
  120. package/dist/semantic-helpers.js +7 -8
  121. package/dist/span-name-normalizer.cjs +0 -1
  122. package/dist/span-name-normalizer.js +0 -1
  123. package/dist/tail-sampling-processor.cjs +0 -1
  124. package/dist/tail-sampling-processor.js +0 -1
  125. package/dist/test-span-collector.cjs +1 -1
  126. package/dist/test-span-collector.js +1 -1
  127. package/dist/testing.cjs +0 -1
  128. package/dist/testing.cjs.map +1 -1
  129. package/dist/testing.js +0 -1
  130. package/dist/testing.js.map +1 -1
  131. package/dist/trace-helpers.cjs +14 -15
  132. package/dist/trace-helpers.js +2 -3
  133. package/dist/tracer-provider.cjs +0 -1
  134. package/dist/tracer-provider.js +0 -1
  135. package/dist/webhook.cjs +8 -9
  136. package/dist/webhook.cjs.map +1 -1
  137. package/dist/webhook.js +6 -7
  138. package/dist/webhook.js.map +1 -1
  139. package/dist/workflow-distributed.cjs +8 -9
  140. package/dist/workflow-distributed.cjs.map +1 -1
  141. package/dist/workflow-distributed.js +6 -7
  142. package/dist/workflow-distributed.js.map +1 -1
  143. package/dist/workflow.cjs +11 -12
  144. package/dist/workflow.js +7 -8
  145. package/dist/yaml-config.cjs +5 -6
  146. package/dist/yaml-config.d.cts +1 -1
  147. package/dist/yaml-config.d.ts +1 -1
  148. package/dist/yaml-config.js +2 -3
  149. package/package.json +1 -1
  150. package/src/init.customization.test.ts +80 -0
  151. package/src/init.ts +78 -15
  152. package/src/node-require.ts +7 -5
  153. package/dist/chunk-33WTKH7X.js.map +0 -1
  154. package/dist/chunk-BPO2PQ3T.cjs.map +0 -1
  155. package/dist/chunk-DGUM43GV.js +0 -10
  156. package/dist/chunk-DGUM43GV.js.map +0 -1
  157. package/dist/chunk-JEQ2X3Z6.cjs +0 -12
  158. package/dist/chunk-JEQ2X3Z6.cjs.map +0 -1
  159. package/dist/chunk-YS6C2YJE.cjs +0 -25
  160. package/dist/chunk-YS6C2YJE.cjs.map +0 -1
  161. package/dist/chunk-ZDPIWKWD.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/yaml-config.ts"],"names":["requireModule","path","existsSync","AdaptiveSampler","AlwaysSampler","NeverSampler","RandomSampler","readFileSync"],"mappings":";;;;;;;;;;;AAwCA,SAAS,cAAA,GAA+C;AACtD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAMA,gCAAuD,MAAM,CAAA;AACzE,IAAA,OAAO,GAAA,CAAI,KAAA;AAAA,EACb,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,oDAAoD,CAAA;AAAA,EACtE;AACF;AAmCA,IAAM,eAAA,GAAkB,mDAAA;AAYxB,SAAS,kBAAkB,KAAA,EAAuB;AAChD,EAAA,OAAO,KAAA,CAAM,UAAA;AAAA,IACX,eAAA;AAAA,IACA,CAAC,MAAA,EAAQ,OAAA,EAAiB,Y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,oBAAoB,WAAW,CAAA;AAAA,EACxC,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,KAAA;AAAA,MACN,6CAA6C,QAAQ,CAAA,CAAA,CAAA;AAAA,MACrD;AAAA,KACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAkBO,SAAS,uBACd,QAAA,EACwB;AACxB,EAAA,MAAM,QAAA,GAAWN,qBAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA;AACtC,EAAA,MAAM,OAAA,GAAUM,eAAA,CAAa,QAAA,EAAU,MAAM,CAAA;AAC7C,EAAA,MAAM,YAAY,cAAA,EAAe;AACjC,EAAA,MAAM,OAAA,GAAU,UAAU,OAAO,CAAA;AACjC,EAAA,MAAM,WAAA,GAAc,sBAAsB,OAAO,CAAA;AACjD,EAAA,OAAO,oBAAoB,WAAW,CAAA;AACxC;AAOO,SAAS,aAAA,GAAyB;AACvC,EAAA,OAAO,gBAAe,KAAM,IAAA;AAC9B","file":"chunk-OC6X2VIN.cjs","sourcesContent":["/**\n * YAML configuration loader for autotel\n *\n * Supports:\n * - Auto-discovery of autotel.yaml in cwd\n * - AUTOTEL_CONFIG_FILE env var override\n * - Environment variable substitution: ${env:VAR} and ${env:VAR:-default}\n *\n * @example Auto-discovery\n * ```yaml\n * # autotel.yaml in project root\n * service:\n * name: my-service\n * exporter:\n * endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4318}\n * ```\n *\n * @example Explicit path\n * ```bash\n * AUTOTEL_CONFIG_FILE=./config/otel.yaml tsx --import autotel/auto src/index.ts\n * ```\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { AutotelConfig } from './init';\nimport {\n AdaptiveSampler,\n AlwaysSampler,\n NeverSampler,\n RandomSampler,\n type SamplingPreset,\n} from './sampling';\n\n/**\n * Lazy-load yaml parser (optional peer dependency)\n * Only loads when a YAML config file is actually found\n */\nimport { requireModule } from './node-require';\n\nfunction loadYamlParser(): (content: string) => unknown {\n try {\n const mod = requireModule<{ parse: (content: string) => unknown }>('yaml');\n return mod.parse;\n } catch {\n throw new Error('YAML parser not found. Install with: pnpm add yaml');\n }\n}\n\n/**\n * YAML config structure\n * Maps to AutotelConfig with user-friendly naming\n */\nexport interface YamlConfig {\n service?: {\n name?: string;\n version?: string;\n environment?: string;\n };\n exporter?: {\n endpoint?: string;\n protocol?: 'http' | 'grpc';\n headers?: Record<string, string>;\n };\n resource?: Record<string, string | number | boolean>;\n sampling?: {\n preset?: SamplingPreset;\n type?: 'adaptive' | 'always_on' | 'always_off' | 'ratio';\n ratio?: number;\n baseline_rate?: number;\n always_sample_errors?: boolean;\n always_sample_slow?: boolean;\n slow_threshold_ms?: number;\n };\n autoInstrumentations?: string[] | Record<string, { enabled?: boolean }>;\n debug?: boolean;\n}\n\n/**\n * Environment variable substitution regex\n * Matches ${env:VAR_NAME} and ${env:VAR_NAME:-default}\n */\nconst ENV_VAR_PATTERN = /\\$\\{env:([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g;\n\n/**\n * Substitute ${env:VAR} and ${env:VAR:-default} in a string\n *\n * @param value - String potentially containing env var references\n * @returns String with env vars substituted\n *\n * @example\n * substituteEnvVars('${env:NODE_ENV:-development}')\n * // Returns 'production' if NODE_ENV=production, else 'development'\n */\nfunction substituteEnvVars(value: string): string {\n return value.replaceAll(\n ENV_VAR_PATTERN,\n (_match, varName: string, defaultValue?: string) => {\n const envValue = process.env[varName];\n if (envValue !== undefined) return envValue;\n if (defaultValue !== undefined) return defaultValue;\n console.warn(\n `[autotel] Environment variable ${varName} not set and no default provided`,\n );\n return '';\n },\n );\n}\n\n/**\n * Recursively substitute env vars in an object\n *\n * @param obj - Object to process\n * @returns Object with all string values having env vars substituted\n */\nfunction substituteEnvVarsDeep(obj: unknown): unknown {\n if (typeof obj === 'string') {\n return substituteEnvVars(obj);\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => substituteEnvVarsDeep(item));\n }\n if (obj && typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = substituteEnvVarsDeep(value);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Find YAML config file path\n *\n * Priority:\n * 1. AUTOTEL_CONFIG_FILE env var (explicit path)\n * 2. autotel.yaml in cwd (convention)\n * 3. autotel.yml in cwd (alternative extension)\n *\n * @returns File path if found, null otherwise\n */\nfunction findConfigFile(): string | null {\n // Check env var first (explicit takes priority)\n const envPath = process.env.AUTOTEL_CONFIG_FILE;\n if (envPath) {\n const resolved = path.resolve(envPath);\n if (existsSync(resolved)) return resolved;\n console.warn(`[autotel] Config file not found: ${envPath}`);\n return null;\n }\n\n // Auto-discover autotel.yaml in cwd\n const conventionPath = path.resolve(process.cwd(), 'autotel.yaml');\n if (existsSync(conventionPath)) return conventionPath;\n\n // Also check .yml extension\n const altPath = path.resolve(process.cwd(), 'autotel.yml');\n if (existsSync(altPath)) return altPath;\n\n return null;\n}\n\n/**\n * Convert YAML config structure to AutotelConfig\n *\n * @param yaml - Parsed and env-substituted YAML config\n * @returns Partial AutotelConfig ready for merging\n */\nfunction yamlToAutotelConfig(yaml: YamlConfig): Partial<AutotelConfig> {\n const config: Partial<AutotelConfig> = {};\n\n // Service configuration\n if (yaml.service?.name) config.service = yaml.service.name;\n if (yaml.service?.version) config.version = yaml.service.version;\n if (yaml.service?.environment) config.environment = yaml.service.environment;\n\n // Exporter configuration\n if (yaml.exporter?.endpoint) config.endpoint = yaml.exporter.endpoint;\n if (yaml.exporter?.protocol) config.protocol = yaml.exporter.protocol;\n if (yaml.exporter?.headers) config.headers = yaml.exporter.headers;\n\n // Resource attributes (flattened)\n if (yaml.resource) config.resourceAttributes = yaml.resource;\n\n // Integrations\n if (yaml.autoInstrumentations)\n config.autoInstrumentations = yaml.autoInstrumentations;\n\n // Debug mode\n if (yaml.debug !== undefined) config.debug = yaml.debug;\n\n // Sampling configuration\n if (yaml.sampling?.preset) {\n warnOnIgnoredPresetOverrides(yaml.sampling);\n config.sampling = yaml.sampling.preset;\n } else {\n const sampler = createSamplerFromYaml(yaml.sampling);\n if (sampler) config.sampler = sampler;\n }\n\n return config;\n}\n\nfunction createSamplerFromYaml(\n sampling?: YamlConfig['sampling'],\n): AutotelConfig['sampler'] {\n if (!sampling) return undefined;\n if (sampling.preset) return undefined;\n\n const type = sampling.type ?? 'adaptive';\n\n try {\n switch (type) {\n case 'adaptive': {\n return new AdaptiveSampler({\n baselineSampleRate: sampling.baseline_rate,\n alwaysSampleErrors: sampling.always_sample_errors,\n alwaysSampleSlow: sampling.always_sample_slow,\n slowThresholdMs: sampling.slow_threshold_ms,\n });\n }\n case 'always_on': {\n return new AlwaysSampler();\n }\n case 'always_off': {\n return new NeverSampler();\n }\n case 'ratio': {\n if (sampling.ratio === undefined) {\n console.warn(\n '[autotel] sampling.ratio missing in YAML sampling config. Falling back to adaptive sampler.',\n );\n return new AdaptiveSampler();\n }\n return new RandomSampler(sampling.ratio);\n }\n default: {\n console.warn(\n `[autotel] Unknown sampling type \"${type}\" in YAML config. Falling back to defaults.`,\n );\n return undefined;\n }\n }\n } catch (error) {\n console.warn(\n `[autotel] Failed to configure sampling from YAML: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n }\n}\n\nfunction warnOnIgnoredPresetOverrides(\n sampling: NonNullable<YamlConfig['sampling']>,\n): void {\n const ignoredFields = [\n 'type',\n 'ratio',\n 'baseline_rate',\n 'always_sample_errors',\n 'always_sample_slow',\n 'slow_threshold_ms',\n ].filter((field) => sampling[field as keyof typeof sampling] !== undefined);\n\n if (ignoredFields.length === 0) {\n return;\n }\n\n console.warn(\n `[autotel] sampling.preset=\"${sampling.preset}\" ignores these YAML fields: ${ignoredFields.join(', ')}. ` +\n 'Use the programmatic API with sampler or samplingPresets.*(...) for tuned presets.',\n );\n}\n\n/**\n * Load and parse YAML config file (auto-discovery)\n *\n * Automatically finds and loads autotel.yaml or uses AUTOTEL_CONFIG_FILE.\n * Returns null if no config file found (not an error - YAML config is optional).\n *\n * @returns Partial AutotelConfig or null if no config file found\n *\n * @example\n * const yamlConfig = loadYamlConfig();\n * if (yamlConfig) {\n * init({ ...yamlConfig, debug: true });\n * }\n */\nexport function loadYamlConfig(): Partial<AutotelConfig> | null {\n const filePath = findConfigFile();\n if (!filePath) return null;\n\n try {\n const content = readFileSync(filePath, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n } catch (error) {\n console.error(\n `[autotel] Failed to load YAML config from ${filePath}:`,\n error,\n );\n return null;\n }\n}\n\n/**\n * Load YAML config from a specific file path\n *\n * Unlike loadYamlConfig(), this throws if the file cannot be read.\n *\n * @param filePath - Path to YAML config file\n * @returns Partial AutotelConfig\n * @throws Error if file cannot be read or parsed\n *\n * @example\n * import { loadYamlConfigFromFile } from 'autotel/yaml';\n * import { init } from 'autotel';\n *\n * const config = loadYamlConfigFromFile('./config/otel.yaml');\n * init({ ...config, debug: true });\n */\nexport function loadYamlConfigFromFile(\n filePath: string,\n): Partial<AutotelConfig> {\n const resolved = path.resolve(filePath);\n const content = readFileSync(resolved, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n}\n\n/**\n * Check if a YAML config file exists (without loading it)\n *\n * @returns true if a config file would be found by loadYamlConfig()\n */\nexport function hasYamlConfig(): boolean {\n return findConfigFile() !== null;\n}\n"]}
1
+ {"version":3,"sources":["../src/yaml-config.ts"],"names":["requireModule","path","existsSync","AdaptiveSampler","AlwaysSampler","NeverSampler","RandomSampler","readFileSync"],"mappings":";;;;;;;;;;;AAwCA,SAAS,cAAA,GAA+C;AACtD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAMA,gCAAuD,MAAM,CAAA;AACzE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,EAAe;AAChC,EAAA,IAAI,CAAC,UAAU,OAAO,IAAA;AAEtB,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAUC,eAAA,CAAa,QAAA,EAAU,MAAM,CAAA;AAC7C,IAAA,MAAM,YAAY,cAAA,EAAe;AACjC,IAAA,MAAM,OAAA,GAAU,UAAU,OAAO,CAAA;AACjC,IAAA,MAAM,WAAA,GAAc,sBAAsB,OAAO,CAAA;AACjD,IAAA,OAAO,oBAAoB,WAAW,CAAA;AAAA,EACxC,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,KAAA;AAAA,MACN,6CAA6C,QAAQ,CAAA,CAAA,CAAA;AAAA,MACrD;AAAA,KACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAkBO,SAAS,uBACd,QAAA,EACwB;AACxB,EAAA,MAAM,QAAA,GAAWN,qBAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA;AACtC,EAAA,MAAM,OAAA,GAAUM,eAAA,CAAa,QAAA,EAAU,MAAM,CAAA;AAC7C,EAAA,MAAM,YAAY,cAAA,EAAe;AACjC,EAAA,MAAM,OAAA,GAAU,UAAU,OAAO,CAAA;AACjC,EAAA,MAAM,WAAA,GAAc,sBAAsB,OAAO,CAAA;AACjD,EAAA,OAAO,oBAAoB,WAAW,CAAA;AACxC;AAOO,SAAS,aAAA,GAAyB;AACvC,EAAA,OAAO,gBAAe,KAAM,IAAA;AAC9B","file":"chunk-BTEPYWDF.cjs","sourcesContent":["/**\n * YAML configuration loader for autotel\n *\n * Supports:\n * - Auto-discovery of autotel.yaml in cwd\n * - AUTOTEL_CONFIG_FILE env var override\n * - Environment variable substitution: ${env:VAR} and ${env:VAR:-default}\n *\n * @example Auto-discovery\n * ```yaml\n * # autotel.yaml in project root\n * service:\n * name: my-service\n * exporter:\n * endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4318}\n * ```\n *\n * @example Explicit path\n * ```bash\n * AUTOTEL_CONFIG_FILE=./config/otel.yaml tsx --import autotel/auto src/index.ts\n * ```\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { AutotelConfig } from './init';\nimport {\n AdaptiveSampler,\n AlwaysSampler,\n NeverSampler,\n RandomSampler,\n type SamplingPreset,\n} from './sampling';\n\n/**\n * Lazy-load yaml parser (optional peer dependency)\n * Only loads when a YAML config file is actually found\n */\nimport { requireModule } from './node-require';\n\nfunction loadYamlParser(): (content: string) => unknown {\n try {\n const mod = requireModule<{ parse: (content: string) => unknown }>('yaml');\n return mod.parse;\n } catch {\n throw new Error('YAML parser not found. Install with: pnpm add yaml');\n }\n}\n\n/**\n * YAML config structure\n * Maps to AutotelConfig with user-friendly naming\n */\nexport interface YamlConfig {\n service?: {\n name?: string;\n version?: string;\n environment?: string;\n };\n exporter?: {\n endpoint?: string;\n protocol?: 'http' | 'grpc';\n headers?: Record<string, string>;\n };\n resource?: Record<string, string | number | boolean>;\n sampling?: {\n preset?: SamplingPreset;\n type?: 'adaptive' | 'always_on' | 'always_off' | 'ratio';\n ratio?: number;\n baseline_rate?: number;\n always_sample_errors?: boolean;\n always_sample_slow?: boolean;\n slow_threshold_ms?: number;\n };\n autoInstrumentations?: string[] | Record<string, { enabled?: boolean }>;\n debug?: boolean;\n}\n\n/**\n * Environment variable substitution regex\n * Matches ${env:VAR_NAME} and ${env:VAR_NAME:-default}\n */\nconst ENV_VAR_PATTERN = /\\$\\{env:([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g;\n\n/**\n * Substitute ${env:VAR} and ${env:VAR:-default} in a string\n *\n * @param value - String potentially containing env var references\n * @returns String with env vars substituted\n *\n * @example\n * substituteEnvVars('${env:NODE_ENV:-development}')\n * // Returns 'production' if NODE_ENV=production, else 'development'\n */\nfunction substituteEnvVars(value: string): string {\n return value.replaceAll(\n ENV_VAR_PATTERN,\n (_match, varName: string, defaultValue?: string) => {\n const envValue = process.env[varName];\n if (envValue !== undefined) return envValue;\n if (defaultValue !== undefined) return defaultValue;\n console.warn(\n `[autotel] Environment variable ${varName} not set and no default provided`,\n );\n return '';\n },\n );\n}\n\n/**\n * Recursively substitute env vars in an object\n *\n * @param obj - Object to process\n * @returns Object with all string values having env vars substituted\n */\nfunction substituteEnvVarsDeep(obj: unknown): unknown {\n if (typeof obj === 'string') {\n return substituteEnvVars(obj);\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => substituteEnvVarsDeep(item));\n }\n if (obj && typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = substituteEnvVarsDeep(value);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Find YAML config file path\n *\n * Priority:\n * 1. AUTOTEL_CONFIG_FILE env var (explicit path)\n * 2. autotel.yaml in cwd (convention)\n * 3. autotel.yml in cwd (alternative extension)\n *\n * @returns File path if found, null otherwise\n */\nfunction findConfigFile(): string | null {\n // Check env var first (explicit takes priority)\n const envPath = process.env.AUTOTEL_CONFIG_FILE;\n if (envPath) {\n const resolved = path.resolve(envPath);\n if (existsSync(resolved)) return resolved;\n console.warn(`[autotel] Config file not found: ${envPath}`);\n return null;\n }\n\n // Auto-discover autotel.yaml in cwd\n const conventionPath = path.resolve(process.cwd(), 'autotel.yaml');\n if (existsSync(conventionPath)) return conventionPath;\n\n // Also check .yml extension\n const altPath = path.resolve(process.cwd(), 'autotel.yml');\n if (existsSync(altPath)) return altPath;\n\n return null;\n}\n\n/**\n * Convert YAML config structure to AutotelConfig\n *\n * @param yaml - Parsed and env-substituted YAML config\n * @returns Partial AutotelConfig ready for merging\n */\nfunction yamlToAutotelConfig(yaml: YamlConfig): Partial<AutotelConfig> {\n const config: Partial<AutotelConfig> = {};\n\n // Service configuration\n if (yaml.service?.name) config.service = yaml.service.name;\n if (yaml.service?.version) config.version = yaml.service.version;\n if (yaml.service?.environment) config.environment = yaml.service.environment;\n\n // Exporter configuration\n if (yaml.exporter?.endpoint) config.endpoint = yaml.exporter.endpoint;\n if (yaml.exporter?.protocol) config.protocol = yaml.exporter.protocol;\n if (yaml.exporter?.headers) config.headers = yaml.exporter.headers;\n\n // Resource attributes (flattened)\n if (yaml.resource) config.resourceAttributes = yaml.resource;\n\n // Integrations\n if (yaml.autoInstrumentations)\n config.autoInstrumentations = yaml.autoInstrumentations;\n\n // Debug mode\n if (yaml.debug !== undefined) config.debug = yaml.debug;\n\n // Sampling configuration\n if (yaml.sampling?.preset) {\n warnOnIgnoredPresetOverrides(yaml.sampling);\n config.sampling = yaml.sampling.preset;\n } else {\n const sampler = createSamplerFromYaml(yaml.sampling);\n if (sampler) config.sampler = sampler;\n }\n\n return config;\n}\n\nfunction createSamplerFromYaml(\n sampling?: YamlConfig['sampling'],\n): AutotelConfig['sampler'] {\n if (!sampling) return undefined;\n if (sampling.preset) return undefined;\n\n const type = sampling.type ?? 'adaptive';\n\n try {\n switch (type) {\n case 'adaptive': {\n return new AdaptiveSampler({\n baselineSampleRate: sampling.baseline_rate,\n alwaysSampleErrors: sampling.always_sample_errors,\n alwaysSampleSlow: sampling.always_sample_slow,\n slowThresholdMs: sampling.slow_threshold_ms,\n });\n }\n case 'always_on': {\n return new AlwaysSampler();\n }\n case 'always_off': {\n return new NeverSampler();\n }\n case 'ratio': {\n if (sampling.ratio === undefined) {\n console.warn(\n '[autotel] sampling.ratio missing in YAML sampling config. Falling back to adaptive sampler.',\n );\n return new AdaptiveSampler();\n }\n return new RandomSampler(sampling.ratio);\n }\n default: {\n console.warn(\n `[autotel] Unknown sampling type \"${type}\" in YAML config. Falling back to defaults.`,\n );\n return undefined;\n }\n }\n } catch (error) {\n console.warn(\n `[autotel] Failed to configure sampling from YAML: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n }\n}\n\nfunction warnOnIgnoredPresetOverrides(\n sampling: NonNullable<YamlConfig['sampling']>,\n): void {\n const ignoredFields = [\n 'type',\n 'ratio',\n 'baseline_rate',\n 'always_sample_errors',\n 'always_sample_slow',\n 'slow_threshold_ms',\n ].filter((field) => sampling[field as keyof typeof sampling] !== undefined);\n\n if (ignoredFields.length === 0) {\n return;\n }\n\n console.warn(\n `[autotel] sampling.preset=\"${sampling.preset}\" ignores these YAML fields: ${ignoredFields.join(', ')}. ` +\n 'Use the programmatic API with sampler or samplingPresets.*(...) for tuned presets.',\n );\n}\n\n/**\n * Load and parse YAML config file (auto-discovery)\n *\n * Automatically finds and loads autotel.yaml or uses AUTOTEL_CONFIG_FILE.\n * Returns null if no config file found (not an error - YAML config is optional).\n *\n * @returns Partial AutotelConfig or null if no config file found\n *\n * @example\n * const yamlConfig = loadYamlConfig();\n * if (yamlConfig) {\n * init({ ...yamlConfig, debug: true });\n * }\n */\nexport function loadYamlConfig(): Partial<AutotelConfig> | null {\n const filePath = findConfigFile();\n if (!filePath) return null;\n\n try {\n const content = readFileSync(filePath, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n } catch (error) {\n console.error(\n `[autotel] Failed to load YAML config from ${filePath}:`,\n error,\n );\n return null;\n }\n}\n\n/**\n * Load YAML config from a specific file path\n *\n * Unlike loadYamlConfig(), this throws if the file cannot be read.\n *\n * @param filePath - Path to YAML config file\n * @returns Partial AutotelConfig\n * @throws Error if file cannot be read or parsed\n *\n * @example\n * import { loadYamlConfigFromFile } from 'autotel/yaml';\n * import { init } from 'autotel';\n *\n * const config = loadYamlConfigFromFile('./config/otel.yaml');\n * init({ ...config, debug: true });\n */\nexport function loadYamlConfigFromFile(\n filePath: string,\n): Partial<AutotelConfig> {\n const resolved = path.resolve(filePath);\n const content = readFileSync(resolved, 'utf8');\n const parseYaml = loadYamlParser();\n const rawYaml = parseYaml(content) as YamlConfig;\n const substituted = substituteEnvVarsDeep(rawYaml) as YamlConfig;\n return yamlToAutotelConfig(substituted);\n}\n\n/**\n * Check if a YAML config file exists (without loading it)\n *\n * @returns true if a config file would be found by loadYamlConfig()\n */\nexport function hasYamlConfig(): boolean {\n return findConfigFile() !== null;\n}\n"]}
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ var module$1 = require('module');
4
+
5
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
6
+ // src/node-require.ts
7
+ var nodeRequire = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-EQIY6C3X.cjs', document.baseURI).href)));
8
+ function safeRequire(id) {
9
+ try {
10
+ return nodeRequire(id);
11
+ } catch (error) {
12
+ if (error && error.code === "MODULE_NOT_FOUND") {
13
+ return void 0;
14
+ }
15
+ throw error;
16
+ }
17
+ }
18
+ function requireModule(id) {
19
+ return nodeRequire(id);
20
+ }
21
+
22
+ exports.requireModule = requireModule;
23
+ exports.safeRequire = safeRequire;
24
+ //# sourceMappingURL=chunk-EQIY6C3X.cjs.map
25
+ //# sourceMappingURL=chunk-EQIY6C3X.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node-require.ts"],"names":["createRequire"],"mappings":";;;;;;AAmBA,IAAM,WAAA,GAAcA,sBAAA,CAAc,oQAAe,CAAA;AAmB1C,SAAS,YAAyB,EAAA,EAA2B;AAClE,EAAA,IAAI;AACF,IAAA,OAAO,YAAY,EAAE,CAAA;AAAA,EACvB,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,KAAA,IAAU,KAAA,CAAgC,IAAA,KAAS,kBAAA,EAAoB;AAEzE,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAmBO,SAAS,cAA2B,EAAA,EAAe;AACxD,EAAA,OAAO,YAAY,EAAE,CAAA;AACvB","file":"chunk-EQIY6C3X.cjs","sourcesContent":["/**\n * Cross-format require() helper for CJS and ESM compatibility\n *\n * Provides a synchronous `require()` function that works in both:\n * - CJS builds: Uses native `require`\n * - ESM builds: Uses `createRequire(import.meta.url)`\n *\n * This allows optional peer dependencies and dynamic module loading\n * to work synchronously in both module formats.\n */\n\nimport { createRequire } from 'node:module';\n\n// createRequire(import.meta.url) works in both formats: esbuild/tsup rewrites\n// `import.meta.url` to a working equivalent in CJS output (pathToFileURL of\n// __filename). A previous `typeof require === 'undefined'` ternary did NOT\n// survive bundling — with tsup's code-splitting it was rewritten to use a\n// polyglot `__require` stub that threw \"Dynamic require not supported\" in\n// ESM consumers, breaking optional peers like @traceloop/node-server-sdk.\nconst nodeRequire = createRequire(import.meta.url);\n\n/**\n * Synchronously require a module (works in both CJS and ESM)\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { safeRequire } from './node-require';\n *\n * const traceloop = safeRequire('@traceloop/node-server-sdk');\n * if (traceloop) {\n * traceloop.initialize({ ... });\n * }\n * ```\n */\nexport function safeRequire<T = unknown>(id: string): T | undefined {\n try {\n return nodeRequire(id) as T;\n } catch (error) {\n if (error && (error as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n // Optional dependency missing – return undefined\n return undefined;\n }\n // Any other error is a real bug: rethrow\n throw error;\n }\n}\n\n/**\n * Synchronously require a module (throws if not found)\n *\n * Use this when the module is required (not optional).\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { requireModule } from './node-require';\n *\n * const fs = requireModule<typeof import('node:fs')>('node:fs');\n * const content = fs.readFileSync('file.txt', 'utf8');\n * ```\n */\nexport function requireModule<T = unknown>(id: string): T {\n return nodeRequire(id) as T;\n}\n\n/**\n * Direct access to the nodeRequire function (for advanced use cases)\n */\nexport { nodeRequire };\n"]}
@@ -1,4 +1,4 @@
1
- import { trace } from './chunk-S4S4AINO.js';
1
+ import { trace } from './chunk-JITYRSI4.js';
2
2
 
3
3
  // src/semantic-helpers.ts
4
4
  function traceLLM(config) {
@@ -91,5 +91,5 @@ function traceMessaging(config) {
91
91
  }
92
92
 
93
93
  export { traceDB, traceHTTP, traceLLM, traceMessaging };
94
- //# sourceMappingURL=chunk-HLAVN3JR.js.map
95
- //# sourceMappingURL=chunk-HLAVN3JR.js.map
94
+ //# sourceMappingURL=chunk-I7ODAZJL.js.map
95
+ //# sourceMappingURL=chunk-I7ODAZJL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,MAAA,CAAO,QAAQ,CAAA;AAAA,MACnD;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,C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,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-HLAVN3JR.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,MAAA,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AAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF;AAmGO,SAAS,eACd,MAAA,EACA;AACA,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,kBAAA,EAAoB,MAAA,CAAO,MAAM,CAAA;AAClD,MAAA,IAAI,OAAO,SAAA,EAAW;AACpB,QAAA,GAAA,CAAI,YAAA,CAAa,qBAAA,EAAuB,MAAA,CAAO,SAAS,CAAA;AAAA,MAC1D;AACA,MAAA,IAAI,OAAO,WAAA,EAAa;AACtB,QAAA,GAAA,CAAI,YAAA,CAAa,4BAAA,EAA8B,MAAA,CAAO,WAAW,CAAA;AAAA,MACnE;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-I7ODAZJL.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getValidationConfig, isInitialized, warnIfNotInitialized, getConfig, getEventsConfig, getLogger } from './chunk-ZDPIWKWD.js';
1
+ import { getValidationConfig, isInitialized, warnIfNotInitialized, getConfig, getEventsConfig, getLogger } from './chunk-SIMG4IGE.js';
2
2
  import { getConfig as getConfig$1 } from './chunk-J5QENANM.js';
3
3
  import { SpanStatusCode, trace, context, propagation } from '@opentelemetry/api';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
@@ -1179,5 +1179,5 @@ function getCorrelationStorage() {
1179
1179
  }
1180
1180
 
1181
1181
  export { CORRELATION_ID_BAGGAGE_KEY, createStructuredError, createTraceContext, defineBaggageSchema, enterOrRun, flattenToAttributes, generateCorrelationId, getActiveContextWithBaggage, getContextStorage, getCorrelationId, getCorrelationStorage, getEventQueue, getOrCreateCorrelationId, getStructuredErrorAttributes, recordStructuredError, resetEventQueue, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage, structuredErrorToJSON, toAttributeValue, track, validateEvent };
1182
- //# sourceMappingURL=chunk-Z7VAOK5X.js.map
1183
- //# sourceMappingURL=chunk-Z7VAOK5X.js.map
1182
+ //# sourceMappingURL=chunk-IC4AZUGC.js.map
1183
+ //# sourceMappingURL=chunk-IC4AZUGC.js.map