autotel 4.2.2 → 4.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/{attributes-CmYpdqCN.js → attributes-B7wix2VG.js} +2 -2
  2. package/dist/{attributes-CmYpdqCN.js.map → attributes-B7wix2VG.js.map} +1 -1
  3. package/dist/{attributes-PZ5doLgw.cjs → attributes-aDmJYral.cjs} +2 -2
  4. package/dist/{attributes-PZ5doLgw.cjs.map → attributes-aDmJYral.cjs.map} +1 -1
  5. package/dist/attributes.cjs +1 -1
  6. package/dist/attributes.js +1 -1
  7. package/dist/auto.cjs +3 -3
  8. package/dist/auto.js +1 -1
  9. package/dist/{canonical-log-line-processor--RlFDHhm.cjs → canonical-log-line-processor-CcrDi6TO.cjs} +2 -2
  10. package/dist/{canonical-log-line-processor--RlFDHhm.cjs.map → canonical-log-line-processor-CcrDi6TO.cjs.map} +1 -1
  11. package/dist/{canonical-log-line-processor-DbBQT5vY.js → canonical-log-line-processor-FLezvFCB.js} +2 -2
  12. package/dist/{canonical-log-line-processor-DbBQT5vY.js.map → canonical-log-line-processor-FLezvFCB.js.map} +1 -1
  13. package/dist/correlation-id.cjs +1 -1
  14. package/dist/correlation-id.js +1 -1
  15. package/dist/decorators.cjs +1 -1
  16. package/dist/decorators.js +1 -1
  17. package/dist/diagnostics.cjs +1 -1
  18. package/dist/drain-pipeline.cjs +8 -2
  19. package/dist/drain-pipeline.cjs.map +1 -1
  20. package/dist/drain-pipeline.js +8 -2
  21. package/dist/drain-pipeline.js.map +1 -1
  22. package/dist/{event-531asIM6.js → event-BEm5IJ8U.js} +3 -3
  23. package/dist/{event-531asIM6.js.map → event-BEm5IJ8U.js.map} +1 -1
  24. package/dist/{event-CcZYwp50.cjs → event-rzA1X5h3.cjs} +4 -4
  25. package/dist/{event-CcZYwp50.cjs.map → event-rzA1X5h3.cjs.map} +1 -1
  26. package/dist/event.cjs +1 -1
  27. package/dist/event.js +1 -1
  28. package/dist/{functional-C8B0Qa7o.cjs → functional-BCtxvYir.cjs} +9 -9
  29. package/dist/{functional-C8B0Qa7o.cjs.map → functional-BCtxvYir.cjs.map} +1 -1
  30. package/dist/{functional-r-AUIRy_.js → functional-CrAq8Az8.js} +4 -4
  31. package/dist/{functional-r-AUIRy_.js.map → functional-CrAq8Az8.js.map} +1 -1
  32. package/dist/functional.cjs +1 -1
  33. package/dist/functional.js +1 -1
  34. package/dist/http.cjs +1 -1
  35. package/dist/http.js +1 -1
  36. package/dist/index.cjs +17 -14
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.js +12 -9
  39. package/dist/index.js.map +1 -1
  40. package/dist/{init-BS2JVkrL.js → init-BvBB45-T.js} +4 -4
  41. package/dist/{init-BS2JVkrL.js.map → init-BvBB45-T.js.map} +1 -1
  42. package/dist/{init-BXiuPK6j.cjs → init-BxJEJ9Tn.cjs} +5 -5
  43. package/dist/{init-BXiuPK6j.cjs.map → init-BxJEJ9Tn.cjs.map} +1 -1
  44. package/dist/instrumentation.cjs +4 -4
  45. package/dist/instrumentation.cjs.map +1 -1
  46. package/dist/instrumentation.js +3 -3
  47. package/dist/instrumentation.js.map +1 -1
  48. package/dist/logger-thMPLpOG.cjs +487 -0
  49. package/dist/logger-thMPLpOG.cjs.map +1 -0
  50. package/dist/logger.cjs +8 -236
  51. package/dist/messaging.cjs +1 -1
  52. package/dist/messaging.js +1 -1
  53. package/dist/{node-require-CZ_PU448.cjs → node-require-PFqDihze.cjs} +3 -3
  54. package/dist/{node-require-CZ_PU448.cjs.map → node-require-PFqDihze.cjs.map} +1 -1
  55. package/dist/{operation-context-D6LDf4W_.cjs → operation-context-hzKbTKnt.cjs} +3 -3
  56. package/dist/{operation-context-D6LDf4W_.cjs.map → operation-context-hzKbTKnt.cjs.map} +1 -1
  57. package/dist/processors.cjs +1 -1
  58. package/dist/processors.js +1 -1
  59. package/dist/register.cjs +2 -2
  60. package/dist/semantic-helpers.cjs +1 -1
  61. package/dist/semantic-helpers.js +1 -1
  62. package/dist/{stable-hash-brKISGf1.cjs → stable-hash-CS9BxvVQ.cjs} +3 -3
  63. package/dist/{stable-hash-brKISGf1.cjs.map → stable-hash-CS9BxvVQ.cjs.map} +1 -1
  64. package/dist/test-span-collector.cjs.map +1 -1
  65. package/dist/test-span-collector.d.cts.map +1 -1
  66. package/dist/test-span-collector.d.ts.map +1 -1
  67. package/dist/test-span-collector.js.map +1 -1
  68. package/dist/testing.cjs +4 -2
  69. package/dist/testing.cjs.map +1 -1
  70. package/dist/testing.js +4 -2
  71. package/dist/testing.js.map +1 -1
  72. package/dist/trace-helpers.cjs +1 -1
  73. package/dist/{track-COUuU48p.js → track-D7O7oIZa.js} +9 -5
  74. package/dist/{track-COUuU48p.js.map → track-D7O7oIZa.js.map} +1 -1
  75. package/dist/{track-Cb3Q4QmS.cjs → track-eovhCJ-I.cjs} +11 -7
  76. package/dist/{track-Cb3Q4QmS.cjs.map → track-eovhCJ-I.cjs.map} +1 -1
  77. package/dist/validate.cjs +1 -1
  78. package/dist/webhook.cjs +1 -1
  79. package/dist/webhook.js +1 -1
  80. package/dist/workflow-distributed.cjs +1 -1
  81. package/dist/workflow-distributed.js +1 -1
  82. package/dist/workflow.cjs +3 -3
  83. package/dist/workflow.js +1 -1
  84. package/dist/yaml-config.cjs +4 -4
  85. package/package.json +40 -40
  86. package/dist/logger.cjs.map +0 -1
  87. /package/dist/{chunk-C_NdSu1c.cjs → rolldown-runtime-C_NdSu1c.cjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.cjs","names":["processDetector","hostDetector","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","requireModule","TailSamplingSpanProcessor","BatchSpanProcessor","OTLPTraceExporter","NodeSDK","PeriodicExportingMetricReader","OTLPMetricExporter","BatchLogRecordProcessor","OTLPLogExporter"],"sources":["../src/instrumentation.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { TailSamplingSpanProcessor } from './tail-sampling-processor';\nimport { getLogger } from './init';\nimport {\n resourceFromAttributes,\n detectResources,\n processDetector,\n hostDetector,\n type Resource,\n type ResourceDetector,\n} from '@opentelemetry/resources';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions/incubating';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { requireModule } from './node-require';\n\n/**\n * Parse OTLP headers string into object format\n * @param headersString - Headers as \"key1=value1,key2=value2\" or \"Authorization=Basic ...\"\n * @returns Headers object for OTLP exporters\n */\nfunction parseOtlpHeaders(headersString?: string): Record<string, string> {\n if (!headersString) return {};\n\n const headers: Record<string, string> = {};\n const pairs = headersString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n headers[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return headers;\n}\n\n/**\n * Parse resource attributes string into object format\n * @param attributesString - Attributes as \"key1=value1,key2=value2\"\n * @returns Resource attributes object\n */\nfunction parseResourceAttributes(\n attributesString?: string,\n): Record<string, string> {\n if (!attributesString) return {};\n\n const attributes: Record<string, string> = {};\n const pairs = attributesString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n attributes[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return attributes;\n}\n\nexport interface InstrumentationConfig {\n serviceName: string;\n serviceVersion?: string;\n deploymentEnvironment?: string;\n otlpEndpoint?: string;\n /** Headers for authentication (e.g., Grafana Cloud, Honeycomb) */\n headers?: string;\n /** Resource attributes as comma-separated key=value pairs */\n resourceAttributes?: string;\n /** Enable async resource detection for process/host info (default: false) */\n detectResources?: boolean;\n /**\n * Use selective instrumentation instead of full auto-instrumentation\n * **Default: true** (performance-first)\n *\n * When true, auto-instrumentation is disabled. You can manually add\n * specific instrumentations via the `instrumentations` field.\n * This reduces overhead from ~81% to near-zero based on Platformatic benchmarks.\n *\n * Set to false to enable full auto-instrumentation (not recommended for production).\n *\n * @see https://blogger.platformatic.dev/the-hidden-cost-of-context\n */\n selectiveInstrumentation?: boolean;\n\n /**\n * Custom instrumentations to use (only when selectiveInstrumentation is true)\n * @example\n * ```typescript\n * import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'\n *\n * initInstrumentation({\n * serviceName: 'api',\n * selectiveInstrumentation: true,\n * instrumentations: [new HttpInstrumentation()]\n * })\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n instrumentations?: any[];\n}\n\n/**\n * Initialize OpenTelemetry instrumentation with OTLP exporters\n *\n * This sets up:\n * - Traces (OTLP HTTP)\n * - Metrics (OTLP HTTP)\n * - Logs (OTLP HTTP)\n * - Auto-instrumentation for common Node.js libraries\n *\n * @example\n * // Call this at the very start of your application\n * import { initInstrumentation } from '@your-org/otel-decorators'\n *\n * initInstrumentation({\n * serviceName: 'my-service' }\n * serviceVersion: '1.0.0',\n * deploymentEnvironment: 'production',\n * otlpEndpoint: 'http://localhost:4318'\n * })\n *\n * // Or with async resource detection (top-level await required)\n * await initInstrumentation({\n * serviceName: 'my-service' }\n * detectResources: true\n * })\n */\n// Enables graceful shutdown and prevents SDK leaks on hot-reload\nlet currentSDK: NodeSDK | null = null;\nlet shutdownHandlerRegistered = false;\n\n/**\n * Shutdown the OpenTelemetry SDK gracefully\n * Call this before process exit or during hot-reloads\n */\nexport async function shutdownInstrumentation(sdk?: NodeSDK): Promise<void> {\n const sdkToShutdown = sdk || currentSDK;\n if (!sdkToShutdown) {\n getLogger().warn({}, 'No SDK to shutdown');\n return;\n }\n\n try {\n await sdkToShutdown.shutdown();\n getLogger().info({}, 'OpenTelemetry terminated successfully');\n if (sdkToShutdown === currentSDK) {\n currentSDK = null;\n }\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Error terminating OpenTelemetry',\n );\n throw error;\n }\n}\n\nexport async function initInstrumentation(\n config: InstrumentationConfig,\n): Promise<NodeSDK> {\n // Prevents resource leaks on hot-reload or multiple init calls\n if (currentSDK) {\n getLogger().info(\n {},\n 'Shutting down existing OpenTelemetry SDK before reinitializing...',\n );\n await shutdownInstrumentation(currentSDK);\n }\n\n // Parse headers and resource attributes\n const otlpHeaders = parseOtlpHeaders(config.headers);\n const customResourceAttributes = parseResourceAttributes(\n config.resourceAttributes,\n );\n\n let resource: Resource;\n\n // Dynamically load optional resource detectors\n const detectors: ResourceDetector[] = [processDetector, hostDetector];\n try {\n const awsDetectors = await import('@opentelemetry/resource-detector-aws');\n detectors.push(\n awsDetectors.awsEc2Detector,\n awsDetectors.awsEcsDetector,\n awsDetectors.awsEksDetector,\n );\n } catch {\n // ignore\n }\n try {\n const gcpDetectors = await import('@opentelemetry/resource-detector-gcp');\n detectors.push(gcpDetectors.gcpDetector);\n } catch {\n // ignore\n }\n try {\n const containerDetectors =\n await import('@opentelemetry/resource-detector-container');\n detectors.push(containerDetectors.containerDetector);\n } catch {\n // ignore\n }\n\n if (config.detectResources) {\n const detectedResource = await detectResources({\n detectors,\n });\n\n resource = detectedResource.merge(\n resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n }),\n );\n } else {\n resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n });\n }\n\n // Default to selective (near-zero overhead) vs full auto (~81% overhead)\n // Lazy-load to avoid importing ~40+ packages at module evaluation time\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let instrumentations: any[] = config.instrumentations || [];\n if (config.selectiveInstrumentation === false) {\n const mod = requireModule<{\n getNodeAutoInstrumentations: () => unknown[];\n }>('@opentelemetry/auto-instrumentations-node');\n instrumentations = [mod.getNodeAutoInstrumentations()];\n }\n\n const traceExporter = new OTLPTraceExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/traces`,\n headers: otlpHeaders,\n });\n\n // Enables tail sampling via autotel.sampling.tail.keep attribute\n const spanProcessor = new TailSamplingSpanProcessor(\n new BatchSpanProcessor(traceExporter),\n );\n\n const sdk = new NodeSDK({\n resource,\n spanProcessor, // Use our wrapped processor instead of traceExporter directly\n metricReader: new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/metrics`,\n headers: otlpHeaders,\n }),\n }),\n logRecordProcessors: [\n new BatchLogRecordProcessor(\n new OTLPLogExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/logs`,\n headers: otlpHeaders,\n }),\n ),\n ],\n instrumentations,\n });\n\n try {\n await sdk.start();\n getLogger().info({}, 'OpenTelemetry instrumentation started successfully');\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Failed to start OpenTelemetry SDK',\n );\n throw error;\n }\n\n // Track current SDK for shutdown handler\n currentSDK = sdk;\n\n if (!shutdownHandlerRegistered) {\n shutdownHandlerRegistered = true;\n\n const shutdownHandler = () => {\n shutdownInstrumentation()\n .then(() => {\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(0);\n })\n .catch((error) => {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Shutdown error',\n );\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1);\n });\n };\n\n process.on('SIGTERM', shutd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/B,KAAK,GAAG,OAAO,gBAAgB,wBAAwB;GACvD,SAAS;EACX,CAAC,EACH,CAAC;EACD,qBAAqB,CACnB,IAAIC,gDACF,IAAIC,uDAAgB;GAClB,KAAK,GAAG,OAAO,gBAAgB,wBAAwB;GACvD,SAAS;EACX,CAAC,CACH,CACF;EACA;CACF,CAAC;CAED,IAAI;EACF,MAAM,IAAI,MAAM;EAChB,uBAAU,CAAC,CAAC,KAAK,CAAC,GAAG,oDAAoD;CAC3E,SAAS,OAAO;EACd,uBAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,mCACF;EACA,MAAM;CACR;CAGA,aAAa;CAEb,IAAI,CAAC,2BAA2B;EAC9B,4BAA4B;EAE5B,MAAM,wBAAwB;GAC5B,wBAAwB,CAAC,CACtB,WAAW;IAEV,QAAQ,KAAK,CAAC;GAChB,CAAC,CAAC,CACD,OAAO,UAAU;IAChB,uBAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,gBACF;IAEA,QAAQ,KAAK,CAAC;GAChB,CAAC;EACL;EAEA,QAAQ,GAAG,WAAW,eAAe;EACrC,QAAQ,GAAG,UAAU,eAAe;CACtC;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"instrumentation.cjs","names":["processDetector","hostDetector","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","requireModule","TailSamplingSpanProcessor","BatchSpanProcessor","OTLPTraceExporter","NodeSDK","PeriodicExportingMetricReader","OTLPMetricExporter","BatchLogRecordProcessor","OTLPLogExporter"],"sources":["../src/instrumentation.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { TailSamplingSpanProcessor } from './tail-sampling-processor';\nimport { getLogger } from './init';\nimport {\n resourceFromAttributes,\n detectResources,\n processDetector,\n hostDetector,\n type Resource,\n type ResourceDetector,\n} from '@opentelemetry/resources';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions/incubating';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { requireModule } from './node-require';\n\n/**\n * Parse OTLP headers string into object format\n * @param headersString - Headers as \"key1=value1,key2=value2\" or \"Authorization=Basic ...\"\n * @returns Headers object for OTLP exporters\n */\nfunction parseOtlpHeaders(headersString?: string): Record<string, string> {\n if (!headersString) return {};\n\n const headers: Record<string, string> = {};\n const pairs = headersString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n headers[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return headers;\n}\n\n/**\n * Parse resource attributes string into object format\n * @param attributesString - Attributes as \"key1=value1,key2=value2\"\n * @returns Resource attributes object\n */\nfunction parseResourceAttributes(\n attributesString?: string,\n): Record<string, string> {\n if (!attributesString) return {};\n\n const attributes: Record<string, string> = {};\n const pairs = attributesString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n attributes[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return attributes;\n}\n\nexport interface InstrumentationConfig {\n serviceName: string;\n serviceVersion?: string;\n deploymentEnvironment?: string;\n otlpEndpoint?: string;\n /** Headers for authentication (e.g., Grafana Cloud, Honeycomb) */\n headers?: string;\n /** Resource attributes as comma-separated key=value pairs */\n resourceAttributes?: string;\n /** Enable async resource detection for process/host info (default: false) */\n detectResources?: boolean;\n /**\n * Use selective instrumentation instead of full auto-instrumentation\n * **Default: true** (performance-first)\n *\n * When true, auto-instrumentation is disabled. You can manually add\n * specific instrumentations via the `instrumentations` field.\n * This reduces overhead from ~81% to near-zero based on Platformatic benchmarks.\n *\n * Set to false to enable full auto-instrumentation (not recommended for production).\n *\n * @see https://blogger.platformatic.dev/the-hidden-cost-of-context\n */\n selectiveInstrumentation?: boolean;\n\n /**\n * Custom instrumentations to use (only when selectiveInstrumentation is true)\n * @example\n * ```typescript\n * import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'\n *\n * initInstrumentation({\n * serviceName: 'api',\n * selectiveInstrumentation: true,\n * instrumentations: [new HttpInstrumentation()]\n * })\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n instrumentations?: any[];\n}\n\n/**\n * Initialize OpenTelemetry instrumentation with OTLP exporters\n *\n * This sets up:\n * - Traces (OTLP HTTP)\n * - Metrics (OTLP HTTP)\n * - Logs (OTLP HTTP)\n * - Auto-instrumentation for common Node.js libraries\n *\n * @example\n * // Call this at the very start of your application\n * import { initInstrumentation } from '@your-org/otel-decorators'\n *\n * initInstrumentation({\n * serviceName: 'my-service' }\n * serviceVersion: '1.0.0',\n * deploymentEnvironment: 'production',\n * otlpEndpoint: 'http://localhost:4318'\n * })\n *\n * // Or with async resource detection (top-level await required)\n * await initInstrumentation({\n * serviceName: 'my-service' }\n * detectResources: true\n * })\n */\n// Enables graceful shutdown and prevents SDK leaks on hot-reload\nlet currentSDK: NodeSDK | null = null;\nlet shutdownHandlerRegistered = false;\n\n/**\n * Shutdown the OpenTelemetry SDK gracefully\n * Call this before process exit or during hot-reloads\n */\nexport async function shutdownInstrumentation(sdk?: NodeSDK): Promise<void> {\n const sdkToShutdown = sdk || currentSDK;\n if (!sdkToShutdown) {\n getLogger().warn({}, 'No SDK to shutdown');\n return;\n }\n\n try {\n await sdkToShutdown.shutdown();\n getLogger().info({}, 'OpenTelemetry terminated successfully');\n if (sdkToShutdown === currentSDK) {\n currentSDK = null;\n }\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Error terminating OpenTelemetry',\n );\n throw error;\n }\n}\n\nexport async function initInstrumentation(\n config: InstrumentationConfig,\n): Promise<NodeSDK> {\n // Prevents resource leaks on hot-reload or multiple init calls\n if (currentSDK) {\n getLogger().info(\n {},\n 'Shutting down existing OpenTelemetry SDK before reinitializing...',\n );\n await shutdownInstrumentation(currentSDK);\n }\n\n // Parse headers and resource attributes\n const otlpHeaders = parseOtlpHeaders(config.headers);\n const customResourceAttributes = parseResourceAttributes(\n config.resourceAttributes,\n );\n\n let resource: Resource;\n\n // Dynamically load optional resource detectors\n const detectors: ResourceDetector[] = [processDetector, hostDetector];\n try {\n const awsDetectors = await import('@opentelemetry/resource-detector-aws');\n detectors.push(\n awsDetectors.awsEc2Detector,\n awsDetectors.awsEcsDetector,\n awsDetectors.awsEksDetector,\n );\n } catch {\n // ignore\n }\n try {\n const gcpDetectors = await import('@opentelemetry/resource-detector-gcp');\n detectors.push(gcpDetectors.gcpDetector);\n } catch {\n // ignore\n }\n try {\n const containerDetectors =\n await import('@opentelemetry/resource-detector-container');\n detectors.push(containerDetectors.containerDetector);\n } catch {\n // ignore\n }\n\n if (config.detectResources) {\n const detectedResource = await detectResources({\n detectors,\n });\n\n resource = detectedResource.merge(\n resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n }),\n );\n } else {\n resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n });\n }\n\n // Default to selective (near-zero overhead) vs full auto (~81% overhead)\n // Lazy-load to avoid importing ~40+ packages at module evaluation time\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let instrumentations: any[] = config.instrumentations || [];\n if (config.selectiveInstrumentation === false) {\n const mod = requireModule<{\n getNodeAutoInstrumentations: () => unknown[];\n }>('@opentelemetry/auto-instrumentations-node');\n instrumentations = [mod.getNodeAutoInstrumentations()];\n }\n\n const traceExporter = new OTLPTraceExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/traces`,\n headers: otlpHeaders,\n });\n\n // Enables tail sampling via autotel.sampling.tail.keep attribute\n const spanProcessor = new TailSamplingSpanProcessor(\n new BatchSpanProcessor(traceExporter),\n );\n\n const sdk = new NodeSDK({\n resource,\n spanProcessor, // Use our wrapped processor instead of traceExporter directly\n metricReader: new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/metrics`,\n headers: otlpHeaders,\n }),\n }),\n logRecordProcessors: [\n new BatchLogRecordProcessor({\n exporter: new OTLPLogExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/logs`,\n headers: otlpHeaders,\n }),\n }),\n ],\n instrumentations,\n });\n\n try {\n await sdk.start();\n getLogger().info({}, 'OpenTelemetry instrumentation started successfully');\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Failed to start OpenTelemetry SDK',\n );\n throw error;\n }\n\n // Track current SDK for shutdown handler\n currentSDK = sdk;\n\n if (!shutdownHandlerRegistered) {\n shutdownHandlerRegistered = true;\n\n const shutdownHandler = () => {\n shutdownInstrumentation()\n .then(() => {\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(0);\n })\n .catch((error) => {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Shutdown error',\n );\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1);\n });\n };\n\n process.on('SIGTERM', shutdownHandler);\n process.on('SIGINT', shutdownHandler);\n }\n\n return sdk;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,SAAS,iBAAiB,eAAgD;CACxE,IAAI,CAAC,eAAe,OAAO,CAAC;CAE5B,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OAAO,gBAAgB,wBAAwB;GACvD,SAAS;EACX,CAAC,EACH,CAAC,CACH;EACA;CACF,CAAC;CAED,IAAI;EACF,MAAM,IAAI,MAAM;EAChB,uBAAU,CAAC,CAAC,KAAK,CAAC,GAAG,oDAAoD;CAC3E,SAAS,OAAO;EACd,uBAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,mCACF;EACA,MAAM;CACR;CAGA,aAAa;CAEb,IAAI,CAAC,2BAA2B;EAC9B,4BAA4B;EAE5B,MAAM,wBAAwB;GAC5B,wBAAwB,CAAC,CACtB,WAAW;IAEV,QAAQ,KAAK,CAAC;GAChB,CAAC,CAAC,CACD,OAAO,UAAU;IAChB,uBAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,gBACF;IAEA,QAAQ,KAAK,CAAC;GAChB,CAAC;EACL;EAEA,QAAQ,GAAG,WAAW,eAAe;EACrC,QAAQ,GAAG,UAAU,eAAe;CACtC;CAEA,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { t as requireModule } from "./node-require-vROmTeJ8.js";
2
- import { i as getLogger } from "./init-BS2JVkrL.js";
2
+ import { i as getLogger } from "./init-BvBB45-T.js";
3
3
  import { TailSamplingSpanProcessor } from "./tail-sampling-processor.js";
4
4
  import { NodeSDK } from "@opentelemetry/sdk-node";
5
5
  import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
@@ -135,10 +135,10 @@ async function initInstrumentation(config) {
135
135
  url: `${config.otlpEndpoint || "http://localhost:4318"}/v1/metrics`,
136
136
  headers: otlpHeaders
137
137
  }) }),
138
- logRecordProcessors: [new BatchLogRecordProcessor(new OTLPLogExporter({
138
+ logRecordProcessors: [new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({
139
139
  url: `${config.otlpEndpoint || "http://localhost:4318"}/v1/logs`,
140
140
  headers: otlpHeaders
141
- }))],
141
+ }) })],
142
142
  instrumentations
143
143
  });
144
144
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":[],"sources":["../src/instrumentation.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { TailSamplingSpanProcessor } from './tail-sampling-processor';\nimport { getLogger } from './init';\nimport {\n resourceFromAttributes,\n detectResources,\n processDetector,\n hostDetector,\n type Resource,\n type ResourceDetector,\n} from '@opentelemetry/resources';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions/incubating';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { requireModule } from './node-require';\n\n/**\n * Parse OTLP headers string into object format\n * @param headersString - Headers as \"key1=value1,key2=value2\" or \"Authorization=Basic ...\"\n * @returns Headers object for OTLP exporters\n */\nfunction parseOtlpHeaders(headersString?: string): Record<string, string> {\n if (!headersString) return {};\n\n const headers: Record<string, string> = {};\n const pairs = headersString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n headers[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return headers;\n}\n\n/**\n * Parse resource attributes string into object format\n * @param attributesString - Attributes as \"key1=value1,key2=value2\"\n * @returns Resource attributes object\n */\nfunction parseResourceAttributes(\n attributesString?: string,\n): Record<string, string> {\n if (!attributesString) return {};\n\n const attributes: Record<string, string> = {};\n const pairs = attributesString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n attributes[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return attributes;\n}\n\nexport interface InstrumentationConfig {\n serviceName: string;\n serviceVersion?: string;\n deploymentEnvironment?: string;\n otlpEndpoint?: string;\n /** Headers for authentication (e.g., Grafana Cloud, Honeycomb) */\n headers?: string;\n /** Resource attributes as comma-separated key=value pairs */\n resourceAttributes?: string;\n /** Enable async resource detection for process/host info (default: false) */\n detectResources?: boolean;\n /**\n * Use selective instrumentation instead of full auto-instrumentation\n * **Default: true** (performance-first)\n *\n * When true, auto-instrumentation is disabled. You can manually add\n * specific instrumentations via the `instrumentations` field.\n * This reduces overhead from ~81% to near-zero based on Platformatic benchmarks.\n *\n * Set to false to enable full auto-instrumentation (not recommended for production).\n *\n * @see https://blogger.platformatic.dev/the-hidden-cost-of-context\n */\n selectiveInstrumentation?: boolean;\n\n /**\n * Custom instrumentations to use (only when selectiveInstrumentation is true)\n * @example\n * ```typescript\n * import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'\n *\n * initInstrumentation({\n * serviceName: 'api',\n * selectiveInstrumentation: true,\n * instrumentations: [new HttpInstrumentation()]\n * })\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n instrumentations?: any[];\n}\n\n/**\n * Initialize OpenTelemetry instrumentation with OTLP exporters\n *\n * This sets up:\n * - Traces (OTLP HTTP)\n * - Metrics (OTLP HTTP)\n * - Logs (OTLP HTTP)\n * - Auto-instrumentation for common Node.js libraries\n *\n * @example\n * // Call this at the very start of your application\n * import { initInstrumentation } from '@your-org/otel-decorators'\n *\n * initInstrumentation({\n * serviceName: 'my-service' }\n * serviceVersion: '1.0.0',\n * deploymentEnvironment: 'production',\n * otlpEndpoint: 'http://localhost:4318'\n * })\n *\n * // Or with async resource detection (top-level await required)\n * await initInstrumentation({\n * serviceName: 'my-service' }\n * detectResources: true\n * })\n */\n// Enables graceful shutdown and prevents SDK leaks on hot-reload\nlet currentSDK: NodeSDK | null = null;\nlet shutdownHandlerRegistered = false;\n\n/**\n * Shutdown the OpenTelemetry SDK gracefully\n * Call this before process exit or during hot-reloads\n */\nexport async function shutdownInstrumentation(sdk?: NodeSDK): Promise<void> {\n const sdkToShutdown = sdk || currentSDK;\n if (!sdkToShutdown) {\n getLogger().warn({}, 'No SDK to shutdown');\n return;\n }\n\n try {\n await sdkToShutdown.shutdown();\n getLogger().info({}, 'OpenTelemetry terminated successfully');\n if (sdkToShutdown === currentSDK) {\n currentSDK = null;\n }\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Error terminating OpenTelemetry',\n );\n throw error;\n }\n}\n\nexport async function initInstrumentation(\n config: InstrumentationConfig,\n): Promise<NodeSDK> {\n // Prevents resource leaks on hot-reload or multiple init calls\n if (currentSDK) {\n getLogger().info(\n {},\n 'Shutting down existing OpenTelemetry SDK before reinitializing...',\n );\n await shutdownInstrumentation(currentSDK);\n }\n\n // Parse headers and resource attributes\n const otlpHeaders = parseOtlpHeaders(config.headers);\n const customResourceAttributes = parseResourceAttributes(\n config.resourceAttributes,\n );\n\n let resource: Resource;\n\n // Dynamically load optional resource detectors\n const detectors: ResourceDetector[] = [processDetector, hostDetector];\n try {\n const awsDetectors = await import('@opentelemetry/resource-detector-aws');\n detectors.push(\n awsDetectors.awsEc2Detector,\n awsDetectors.awsEcsDetector,\n awsDetectors.awsEksDetector,\n );\n } catch {\n // ignore\n }\n try {\n const gcpDetectors = await import('@opentelemetry/resource-detector-gcp');\n detectors.push(gcpDetectors.gcpDetector);\n } catch {\n // ignore\n }\n try {\n const containerDetectors =\n await import('@opentelemetry/resource-detector-container');\n detectors.push(containerDetectors.containerDetector);\n } catch {\n // ignore\n }\n\n if (config.detectResources) {\n const detectedResource = await detectResources({\n detectors,\n });\n\n resource = detectedResource.merge(\n resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n }),\n );\n } else {\n resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n });\n }\n\n // Default to selective (near-zero overhead) vs full auto (~81% overhead)\n // Lazy-load to avoid importing ~40+ packages at module evaluation time\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let instrumentations: any[] = config.instrumentations || [];\n if (config.selectiveInstrumentation === false) {\n const mod = requireModule<{\n getNodeAutoInstrumentations: () => unknown[];\n }>('@opentelemetry/auto-instrumentations-node');\n instrumentations = [mod.getNodeAutoInstrumentations()];\n }\n\n const traceExporter = new OTLPTraceExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/traces`,\n headers: otlpHeaders,\n });\n\n // Enables tail sampling via autotel.sampling.tail.keep attribute\n const spanProcessor = new TailSamplingSpanProcessor(\n new BatchSpanProcessor(traceExporter),\n );\n\n const sdk = new NodeSDK({\n resource,\n spanProcessor, // Use our wrapped processor instead of traceExporter directly\n metricReader: new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/metrics`,\n headers: otlpHeaders,\n }),\n }),\n logRecordProcessors: [\n new BatchLogRecordProcessor(\n new OTLPLogExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/logs`,\n headers: otlpHeaders,\n }),\n ),\n ],\n instrumentations,\n });\n\n try {\n await sdk.start();\n getLogger().info({}, 'OpenTelemetry instrumentation started successfully');\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Failed to start OpenTelemetry SDK',\n );\n throw error;\n }\n\n // Track current SDK for shutdown handler\n currentSDK = sdk;\n\n if (!shutdownHandlerRegistered) {\n shutdownHandlerRegistered = true;\n\n const shutdownHandler = () => {\n shutdownInstrumentation()\n .then(() => {\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(0);\n })\n .catch((error) => {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Shutdown error',\n );\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1);\n });\n };\n\n process.on('SIGTERM', shutdownHandler);\n process.on('SIGINT', shutdownHandler);\n }\n\n return sdk;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,SAAS,iBAAiB,eAAgD;CACxE,IAAI,CAAC,eAAe,OAAO,CAAC;CAE5B,MAAM,UAAkC,CAAC;CACzC,MAAM,QAAQ,cAAc,MAAM,GAAG;CAErC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,CAAC,KAAK,GAAG,cAAc,KAAK,MAAM,GAAG;EAC3C,IAAI,OAAO,WAAW,SAAS,GAC7B,QAAQ,IAAI,KAAK,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,KAAK;CAEpD;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,wBACP,kBACwB;CACxB,IAAI,CAAC,kBAAkB,OAAO,CAAC;CAE/B,MAAM,aAAqC,CAAC;CAC5C,MAAM,QAAQ,iBAAiB,MAAM,GAAG;CAExC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,CAAC,KAAK,GAAG,cAAc,KAAK,MAAM,GAAG;EAC3C,IAAI,OAAO,WAAW,SAAS,GAC7B,WAAW,IAAI,KAAK,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,KAAK;CAEvD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAI,aAA6B;AACjC,IAAI,4BAA4B;;;;;AAMhC,eAAsB,wBAAwB,KAA8B;CAC1E,MAAM,gBAAgB,OAAO;CAC7B,IAAI,CAAC,eAAe;EAClB,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,oBAAoB;EACzC;CACF;CAEA,IAAI;EACF,MAAM,cAAc,SAAS;EAC7B,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,uCAAuC;EAC5D,IAAI,k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wBAAwB;EACvD,SAAS;CACX,CAIqC,CAAC,CACtC;CAEA,MAAM,MAAM,IAAI,QAAQ;EACtB;EACA;EACA,cAAc,IAAI,8BAA8B,EAC9C,UAAU,IAAI,mBAAmB;GAC/B,KAAK,GAAG,OAAO,gBAAgB,wBAAwB;GACvD,SAAS;EACX,CAAC,EACH,CAAC;EACD,qBAAqB,CACnB,IAAI,wBACF,IAAI,gBAAgB;GAClB,KAAK,GAAG,OAAO,gBAAgB,wBAAwB;GACvD,SAAS;EACX,CAAC,CACH,CACF;EACA;CACF,CAAC;CAED,IAAI;EACF,MAAM,IAAI,MAAM;EAChB,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,oDAAoD;CAC3E,SAAS,OAAO;EACd,UAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,mCACF;EACA,MAAM;CACR;CAGA,aAAa;CAEb,IAAI,CAAC,2BAA2B;EAC9B,4BAA4B;EAE5B,MAAM,wBAAwB;GAC5B,wBAAwB,CAAC,CACtB,WAAW;IAEV,QAAQ,KAAK,CAAC;GAChB,CAAC,CAAC,CACD,OAAO,UAAU;IAChB,UAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,gBACF;IAEA,QAAQ,KAAK,CAAC;GAChB,CAAC;EACL;EAEA,QAAQ,GAAG,WAAW,eAAe;EACrC,QAAQ,GAAG,UAAU,eAAe;CACtC;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"instrumentation.js","names":[],"sources":["../src/instrumentation.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { TailSamplingSpanProcessor } from './tail-sampling-processor';\nimport { getLogger } from './init';\nimport {\n resourceFromAttributes,\n detectResources,\n processDetector,\n hostDetector,\n type Resource,\n type ResourceDetector,\n} from '@opentelemetry/resources';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions/incubating';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { requireModule } from './node-require';\n\n/**\n * Parse OTLP headers string into object format\n * @param headersString - Headers as \"key1=value1,key2=value2\" or \"Authorization=Basic ...\"\n * @returns Headers object for OTLP exporters\n */\nfunction parseOtlpHeaders(headersString?: string): Record<string, string> {\n if (!headersString) return {};\n\n const headers: Record<string, string> = {};\n const pairs = headersString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n headers[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return headers;\n}\n\n/**\n * Parse resource attributes string into object format\n * @param attributesString - Attributes as \"key1=value1,key2=value2\"\n * @returns Resource attributes object\n */\nfunction parseResourceAttributes(\n attributesString?: string,\n): Record<string, string> {\n if (!attributesString) return {};\n\n const attributes: Record<string, string> = {};\n const pairs = attributesString.split(',');\n\n for (const pair of pairs) {\n const [key, ...valueParts] = pair.split('=');\n if (key && valueParts.length > 0) {\n attributes[key.trim()] = valueParts.join('=').trim();\n }\n }\n\n return attributes;\n}\n\nexport interface InstrumentationConfig {\n serviceName: string;\n serviceVersion?: string;\n deploymentEnvironment?: string;\n otlpEndpoint?: string;\n /** Headers for authentication (e.g., Grafana Cloud, Honeycomb) */\n headers?: string;\n /** Resource attributes as comma-separated key=value pairs */\n resourceAttributes?: string;\n /** Enable async resource detection for process/host info (default: false) */\n detectResources?: boolean;\n /**\n * Use selective instrumentation instead of full auto-instrumentation\n * **Default: true** (performance-first)\n *\n * When true, auto-instrumentation is disabled. You can manually add\n * specific instrumentations via the `instrumentations` field.\n * This reduces overhead from ~81% to near-zero based on Platformatic benchmarks.\n *\n * Set to false to enable full auto-instrumentation (not recommended for production).\n *\n * @see https://blogger.platformatic.dev/the-hidden-cost-of-context\n */\n selectiveInstrumentation?: boolean;\n\n /**\n * Custom instrumentations to use (only when selectiveInstrumentation is true)\n * @example\n * ```typescript\n * import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'\n *\n * initInstrumentation({\n * serviceName: 'api',\n * selectiveInstrumentation: true,\n * instrumentations: [new HttpInstrumentation()]\n * })\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n instrumentations?: any[];\n}\n\n/**\n * Initialize OpenTelemetry instrumentation with OTLP exporters\n *\n * This sets up:\n * - Traces (OTLP HTTP)\n * - Metrics (OTLP HTTP)\n * - Logs (OTLP HTTP)\n * - Auto-instrumentation for common Node.js libraries\n *\n * @example\n * // Call this at the very start of your application\n * import { initInstrumentation } from '@your-org/otel-decorators'\n *\n * initInstrumentation({\n * serviceName: 'my-service' }\n * serviceVersion: '1.0.0',\n * deploymentEnvironment: 'production',\n * otlpEndpoint: 'http://localhost:4318'\n * })\n *\n * // Or with async resource detection (top-level await required)\n * await initInstrumentation({\n * serviceName: 'my-service' }\n * detectResources: true\n * })\n */\n// Enables graceful shutdown and prevents SDK leaks on hot-reload\nlet currentSDK: NodeSDK | null = null;\nlet shutdownHandlerRegistered = false;\n\n/**\n * Shutdown the OpenTelemetry SDK gracefully\n * Call this before process exit or during hot-reloads\n */\nexport async function shutdownInstrumentation(sdk?: NodeSDK): Promise<void> {\n const sdkToShutdown = sdk || currentSDK;\n if (!sdkToShutdown) {\n getLogger().warn({}, 'No SDK to shutdown');\n return;\n }\n\n try {\n await sdkToShutdown.shutdown();\n getLogger().info({}, 'OpenTelemetry terminated successfully');\n if (sdkToShutdown === currentSDK) {\n currentSDK = null;\n }\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Error terminating OpenTelemetry',\n );\n throw error;\n }\n}\n\nexport async function initInstrumentation(\n config: InstrumentationConfig,\n): Promise<NodeSDK> {\n // Prevents resource leaks on hot-reload or multiple init calls\n if (currentSDK) {\n getLogger().info(\n {},\n 'Shutting down existing OpenTelemetry SDK before reinitializing...',\n );\n await shutdownInstrumentation(currentSDK);\n }\n\n // Parse headers and resource attributes\n const otlpHeaders = parseOtlpHeaders(config.headers);\n const customResourceAttributes = parseResourceAttributes(\n config.resourceAttributes,\n );\n\n let resource: Resource;\n\n // Dynamically load optional resource detectors\n const detectors: ResourceDetector[] = [processDetector, hostDetector];\n try {\n const awsDetectors = await import('@opentelemetry/resource-detector-aws');\n detectors.push(\n awsDetectors.awsEc2Detector,\n awsDetectors.awsEcsDetector,\n awsDetectors.awsEksDetector,\n );\n } catch {\n // ignore\n }\n try {\n const gcpDetectors = await import('@opentelemetry/resource-detector-gcp');\n detectors.push(gcpDetectors.gcpDetector);\n } catch {\n // ignore\n }\n try {\n const containerDetectors =\n await import('@opentelemetry/resource-detector-container');\n detectors.push(containerDetectors.containerDetector);\n } catch {\n // ignore\n }\n\n if (config.detectResources) {\n const detectedResource = await detectResources({\n detectors,\n });\n\n resource = detectedResource.merge(\n resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n }),\n );\n } else {\n resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',\n 'deployment.environment': config.deploymentEnvironment || 'development',\n ...customResourceAttributes, // Merge custom resource attributes\n });\n }\n\n // Default to selective (near-zero overhead) vs full auto (~81% overhead)\n // Lazy-load to avoid importing ~40+ packages at module evaluation time\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let instrumentations: any[] = config.instrumentations || [];\n if (config.selectiveInstrumentation === false) {\n const mod = requireModule<{\n getNodeAutoInstrumentations: () => unknown[];\n }>('@opentelemetry/auto-instrumentations-node');\n instrumentations = [mod.getNodeAutoInstrumentations()];\n }\n\n const traceExporter = new OTLPTraceExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/traces`,\n headers: otlpHeaders,\n });\n\n // Enables tail sampling via autotel.sampling.tail.keep attribute\n const spanProcessor = new TailSamplingSpanProcessor(\n new BatchSpanProcessor(traceExporter),\n );\n\n const sdk = new NodeSDK({\n resource,\n spanProcessor, // Use our wrapped processor instead of traceExporter directly\n metricReader: new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/metrics`,\n headers: otlpHeaders,\n }),\n }),\n logRecordProcessors: [\n new BatchLogRecordProcessor({\n exporter: new OTLPLogExporter({\n url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/logs`,\n headers: otlpHeaders,\n }),\n }),\n ],\n instrumentations,\n });\n\n try {\n await sdk.start();\n getLogger().info({}, 'OpenTelemetry instrumentation started successfully');\n } catch (error) {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Failed to start OpenTelemetry SDK',\n );\n throw error;\n }\n\n // Track current SDK for shutdown handler\n currentSDK = sdk;\n\n if (!shutdownHandlerRegistered) {\n shutdownHandlerRegistered = true;\n\n const shutdownHandler = () => {\n shutdownInstrumentation()\n .then(() => {\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(0);\n })\n .catch((error) => {\n getLogger().error(\n {\n err: error instanceof Error ? error : undefined,\n },\n 'Shutdown error',\n );\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1);\n });\n };\n\n process.on('SIGTERM', shutdownHandler);\n process.on('SIGINT', shutdownHandler);\n }\n\n return sdk;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,SAAS,iBAAiB,eAAgD;CACxE,IAAI,CAAC,eAAe,OAAO,CAAC;CAE5B,MAAM,UAAkC,CAAC;CACzC,MAAM,Q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EACX,CAAC,EACH,CAAC,CACH;EACA;CACF,CAAC;CAED,IAAI;EACF,MAAM,IAAI,MAAM;EAChB,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,oDAAoD;CAC3E,SAAS,OAAO;EACd,UAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,mCACF;EACA,MAAM;CACR;CAGA,aAAa;CAEb,IAAI,CAAC,2BAA2B;EAC9B,4BAA4B;EAE5B,MAAM,wBAAwB;GAC5B,wBAAwB,CAAC,CACtB,WAAW;IAEV,QAAQ,KAAK,CAAC;GAChB,CAAC,CAAC,CACD,OAAO,UAAU;IAChB,UAAU,CAAC,CAAC,MACV,EACE,KAAK,iBAAiB,QAAQ,QAAQ,OACxC,GACA,gBACF;IAEA,QAAQ,KAAK,CAAC;GAChB,CAAC;EACL;EAEA,QAAQ,GAAG,WAAW,eAAe;EACrC,QAAQ,GAAG,UAAU,eAAe;CACtC;CAEA,OAAO;AACT"}
@@ -0,0 +1,487 @@
1
+ const require_config = require('./config.cjs');
2
+ let _opentelemetry_api = require("@opentelemetry/api");
3
+
4
+ //#region src/autotel-logger.ts
5
+ /**
6
+ * Zero-dependency structured logger for autotel
7
+ *
8
+ * This logger provides:
9
+ * - Structured JSON logging (production) or pretty print (development)
10
+ * - Auto trace context injection (traceId, spanId, correlationId)
11
+ * - Dynamic log level control (per-request via OTel context)
12
+ * - Level support (debug, info, warn, error, none)
13
+ * - Zero additional dependencies (uses @opentelemetry/api, already a dep)
14
+ *
15
+ * Uses Pino-compatible signature supporting both patterns:
16
+ * - `log.info('simple message')` - string-only
17
+ * - `log.info({ userId: '123' }, 'message')` - object first with optional message
18
+ *
19
+ * Used as the default fallback when users don't provide Pino/Bunyan.
20
+ * Can also be used directly: import { createBuiltinLogger } from 'autotel/logger'
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * import { createBuiltinLogger, runWithLogLevel } from 'autotel/logger';
25
+ *
26
+ * const log = createBuiltinLogger('my-service');
27
+ *
28
+ * // Simple message (no metadata)
29
+ * log.info('Server started');
30
+ *
31
+ * // With metadata (Pino-style: object first, message second)
32
+ * log.info({ userId: '123' }, 'User created');
33
+ * // Output: {"level":"info","service":"my-service","msg":"User created","userId":"123","traceId":"..."}
34
+ *
35
+ * // Dynamic log level per-request
36
+ * runWithLogLevel('debug', () => {
37
+ * log.debug('This will log even if default level is "info"');
38
+ * });
39
+ * ```
40
+ */
41
+ /**
42
+ * Context key for storing active log level (enables per-request log levels)
43
+ */
44
+ const LOG_LEVEL_KEY = (0, _opentelemetry_api.createContextKey)("autotel-log-level");
45
+ /**
46
+ * Get the active log level from context (if set)
47
+ * Falls back to undefined if no log level is set in context
48
+ */
49
+ function getActiveLogLevel() {
50
+ return _opentelemetry_api.context.active().getValue(LOG_LEVEL_KEY);
51
+ }
52
+ /**
53
+ * Run a function with a specific log level
54
+ * The log level is stored in OpenTelemetry context and applies to all logger calls within the callback
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * // Enable debug logging for a specific request
59
+ * runWithLogLevel('debug', () => {
60
+ * log.debug('This will be logged');
61
+ * processRequest();
62
+ * });
63
+ *
64
+ * // Disable logging temporarily
65
+ * runWithLogLevel('none', () => {
66
+ * log.info('This will NOT be logged');
67
+ * });
68
+ * ```
69
+ */
70
+ function runWithLogLevel(level, callback) {
71
+ const ctx = _opentelemetry_api.context.active().setValue(LOG_LEVEL_KEY, level);
72
+ return _opentelemetry_api.context.with(ctx, callback);
73
+ }
74
+ /**
75
+ * Get current trace context from active span
76
+ * Returns null if no active span exists
77
+ */
78
+ function getTraceContextInternal() {
79
+ const span = _opentelemetry_api.trace.getActiveSpan();
80
+ if (!span) return null;
81
+ const ctx = span.spanContext();
82
+ return {
83
+ traceId: ctx.traceId,
84
+ spanId: ctx.spanId,
85
+ correlationId: ctx.traceId.slice(0, 16)
86
+ };
87
+ }
88
+ /**
89
+ * Helper to get trace context (useful for BYOL - Bring Your Own Logger)
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * import bunyan from 'bunyan';
94
+ * import { getTraceContext } from 'autotel/logger';
95
+ *
96
+ * const bunyanLogger = bunyan.createLogger({ name: 'myapp' });
97
+ * const ctx = getTraceContext();
98
+ * bunyanLogger.info({ ...ctx, email: 'test@example.com' }, 'Creating user');
99
+ * ```
100
+ */
101
+ function getTraceContext() {
102
+ return getTraceContextInternal();
103
+ }
104
+ /**
105
+ * Create a lightweight structured logger
106
+ *
107
+ * @param service - Service name for logging
108
+ * @param options - Optional configuration
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const log = createBuiltinLogger('user-service');
113
+ *
114
+ * log.info('Creating user', { email: 'test@example.com' });
115
+ * // Output: {"level":"info","service":"user-service","msg":"Creating user",
116
+ * // "email":"test@example.com","traceId":"...","spanId":"..."}
117
+ *
118
+ * // Dynamic log level control per-request
119
+ * runWithLogLevel('debug', () => {
120
+ * log.debug('This will be logged even if logger was created with level: "info"');
121
+ * });
122
+ * ```
123
+ */
124
+ function createBuiltinLogger(service, options) {
125
+ const defaultLevel = options?.level || "info";
126
+ const pretty = options?.pretty || false;
127
+ const levelPriority = {
128
+ none: -1,
129
+ debug: 0,
130
+ info: 1,
131
+ warn: 2,
132
+ error: 3
133
+ };
134
+ const shouldLog = (level) => {
135
+ const activeLevel = getActiveLogLevel() ?? defaultLevel;
136
+ if (activeLevel === "none") return false;
137
+ return levelPriority[level] >= levelPriority[activeLevel];
138
+ };
139
+ const log = (level, msg, attrs) => {
140
+ if (!shouldLog(level)) return;
141
+ const ctx = getTraceContextInternal();
142
+ const logEntry = {
143
+ level,
144
+ service,
145
+ msg,
146
+ ...attrs,
147
+ ...ctx,
148
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
149
+ };
150
+ if (pretty) {
151
+ const traceInfo = ctx ? ` [${ctx.traceId.slice(0, 8)}.../${ctx.spanId.slice(0, 8)}...]` : "";
152
+ console.log(`[${level.toUpperCase()}]${traceInfo} ${service}: ${msg}`, attrs || "");
153
+ } else console.log(JSON.stringify(logEntry));
154
+ };
155
+ const createLogMethod = (level) => {
156
+ return (extraOrMessage, message) => {
157
+ if (typeof extraOrMessage === "string") if (message !== void 0 && typeof message === "object") {
158
+ if (process.env.NODE_ENV !== "production") console.warn(`[autotel] Legacy logger pattern detected: logger.${level}('message', metadata). Autotel recommends Pino signature: logger.${level}({ ...metadata }, 'message'). Auto-swapping arguments for compatibility.`);
159
+ log(level, extraOrMessage, message);
160
+ } else log(level, extraOrMessage);
161
+ else log(level, message || "", extraOrMessage);
162
+ };
163
+ };
164
+ return {
165
+ info: createLogMethod("info"),
166
+ warn: createLogMethod("warn"),
167
+ debug: createLogMethod("debug"),
168
+ error: (extraOrMessage, message) => {
169
+ if (typeof extraOrMessage === "string") {
170
+ if (message instanceof Error) {
171
+ if (process.env.NODE_ENV !== "production") console.warn("[autotel] Legacy logger pattern detected: logger.error('message', error). Autotel recommends Pino signature: logger.error({ err: error }, 'message'). Auto-swapping arguments for compatibility.");
172
+ log("error", extraOrMessage, {
173
+ error: message.message,
174
+ stack: message.stack,
175
+ name: message.name
176
+ });
177
+ return;
178
+ }
179
+ if (message !== void 0 && typeof message === "object") {
180
+ if (process.env.NODE_ENV !== "production") console.warn("[autotel] Legacy logger pattern detected: logger.error('message', metadata). Autotel recommends Pino signature: logger.error({ ...metadata }, 'message'). Auto-swapping arguments for compatibility.");
181
+ const { err, ...rest } = message;
182
+ let errorAttrs = rest;
183
+ if (err instanceof Error) errorAttrs = {
184
+ error: err.message,
185
+ stack: err.stack,
186
+ name: err.name,
187
+ ...rest
188
+ };
189
+ else if (err !== void 0) errorAttrs = {
190
+ err,
191
+ ...rest
192
+ };
193
+ log("error", extraOrMessage, errorAttrs);
194
+ return;
195
+ }
196
+ log("error", extraOrMessage);
197
+ return;
198
+ }
199
+ const { err, ...rest } = extraOrMessage;
200
+ let errorAttrs = rest;
201
+ if (err instanceof Error) errorAttrs = {
202
+ error: err.message,
203
+ stack: err.stack,
204
+ name: err.name,
205
+ ...rest
206
+ };
207
+ else if (err !== void 0) errorAttrs = {
208
+ err,
209
+ ...rest
210
+ };
211
+ log("error", message || "", errorAttrs);
212
+ }
213
+ };
214
+ }
215
+ /**
216
+ * Pino-like factory function for creating an autotel logger
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * import { autotelLogger } from 'autotel/logger';
221
+ *
222
+ * const log = autotelLogger();
223
+ *
224
+ * // Simple message
225
+ * log.info('Server started');
226
+ *
227
+ * // With metadata (Pino-style: object first, message second)
228
+ * log.info({ userId: '123' }, 'User created');
229
+ *
230
+ * // With options
231
+ * const devLog = autotelLogger({ service: 'my-app', level: 'debug', pretty: true });
232
+ * ```
233
+ */
234
+ function autotelLogger(options) {
235
+ return createBuiltinLogger(options?.service || "app", {
236
+ level: options?.level,
237
+ pretty: options?.pretty
238
+ });
239
+ }
240
+
241
+ //#endregion
242
+ //#region src/logger.ts
243
+ /**
244
+ * Logger types and utilities for autotel
245
+ *
246
+ * **Zero-Config Option:** Don't provide a logger to `init()` and autotel uses
247
+ * a built-in structured JSON logger with automatic trace context injection.
248
+ *
249
+ * **BYOL (Bring Your Own Logger):** Pass Pino or Bunyan to `init()` for
250
+ * automatic instrumentation with trace context and OTLP log export.
251
+ *
252
+ * ## Logger Signature
253
+ *
254
+ * Autotel v2.10+ uses **Pino's signature**: `logger.info({ metadata }, 'message')`.
255
+ *
256
+ * ### Backward Compatibility
257
+ *
258
+ * The built-in logger auto-detects legacy Winston-style calls and swaps arguments:
259
+ * ```typescript
260
+ * // Legacy (auto-detected and handled)
261
+ * logger.info('User created', { userId: '123' });
262
+ * // → Internally treated as: logger.info({ userId: '123' }, 'User created')
263
+ * // → Logs warning in development, works silently in production
264
+ * ```
265
+ *
266
+ * ### Recommended Usage
267
+ *
268
+ * ```typescript
269
+ * // ✅ Pino-style (preferred)
270
+ * logger.info({ userId: '123' }, 'User created');
271
+ *
272
+ * // ✅ Simple message (no metadata)
273
+ * logger.info('Server started');
274
+ * ```
275
+ *
276
+ * **Note:** If you BYOL (bring your own logger), it must use Pino signature.
277
+ * Winston and other `(message, meta)` loggers are NOT compatible.
278
+ * For Winston, use `@opentelemetry/instrumentation-winston` instead.
279
+ *
280
+ * @example Zero-config (uses built-in logger)
281
+ * ```typescript
282
+ * import { init } from 'autotel';
283
+ *
284
+ * init({ service: 'my-app' });
285
+ * // Internal logs: {"level":"info","service":"my-app","msg":"...","traceId":"..."}
286
+ * ```
287
+ *
288
+ * @example Using built-in logger directly
289
+ * ```typescript
290
+ * import { createBuiltinLogger, runWithLogLevel } from 'autotel/logger';
291
+ *
292
+ * const log = createBuiltinLogger('my-service');
293
+ *
294
+ * // Simple message (no metadata)
295
+ * log.info('Server started');
296
+ *
297
+ * // With metadata (Pino-style: object first, message second)
298
+ * log.info({ userId: '123' }, 'User created');
299
+ * // Output: {"level":"info","service":"my-service","msg":"User created","userId":"123","traceId":"..."}
300
+ *
301
+ * // Dynamic log level per-request
302
+ * runWithLogLevel('debug', () => {
303
+ * log.debug('Debug info for this request only');
304
+ * });
305
+ * ```
306
+ *
307
+ * @example Using Pino (recommended for production, auto-instrumented)
308
+ * ```typescript
309
+ * import pino from 'pino'; // npm install pino
310
+ * import { init } from 'autotel';
311
+ *
312
+ * const logger = pino({ level: 'info' });
313
+ * init({ service: 'my-app', logger });
314
+ *
315
+ * // Logs automatically include traceId/spanId and export via OTLP!
316
+ * logger.info({ userId: '123' }, 'User created');
317
+ * ```
318
+ *
319
+ * @example Using Bunyan (auto-instrumented, same signature as Pino)
320
+ * ```typescript
321
+ * import bunyan from 'bunyan'; // npm install bunyan @opentelemetry/instrumentation-bunyan
322
+ * import { init } from 'autotel';
323
+ * import { BunyanInstrumentation } from '@opentelemetry/instrumentation-bunyan';
324
+ *
325
+ * const logger = bunyan.createLogger({ name: 'my-app' });
326
+ * init({
327
+ * service: 'my-app',
328
+ * logger,
329
+ * instrumentations: [new BunyanInstrumentation()]
330
+ * });
331
+ * ```
332
+ *
333
+ * @example Custom logger (MUST use Pino-compatible signature)
334
+ * ```typescript
335
+ * // ⚠️ Your custom logger MUST accept (object, message?) signature
336
+ * const logger = {
337
+ * info: (extra, msg) => console.log(msg || '', extra),
338
+ * warn: (extra, msg) => console.warn(msg || '', extra),
339
+ * error: (extra, msg) => console.error(msg || '', extra),
340
+ * debug: (extra, msg) => console.debug(msg || '', extra),
341
+ * };
342
+ * init({ service: 'my-app', logger });
343
+ * ```
344
+ *
345
+ * @example BYOL helper: inject trace context into any logger
346
+ * ```typescript
347
+ * import bunyan from 'bunyan';
348
+ * import { getTraceContext } from 'autotel/logger';
349
+ *
350
+ * const bunyanLogger = bunyan.createLogger({ name: 'myapp' });
351
+ * const ctx = getTraceContext();
352
+ * bunyanLogger.info({ ...ctx, userId: '123' }, 'Creating user');
353
+ * ```
354
+ */
355
+ /**
356
+ * Log level constants
357
+ */
358
+ const LOG_LEVEL = {
359
+ DEBUG: "debug",
360
+ INFO: "info",
361
+ WARN: "warn",
362
+ ERROR: "error"
363
+ };
364
+ /**
365
+ * TS5+ Standard Decorator for logging and tracing operations
366
+ * Uses TC39 Stage 3 decorator syntax
367
+ *
368
+ * This is the traditional per-method decorator approach.
369
+ * For zero-boilerplate solution, see @Instrumented class decorator.
370
+ *
371
+ * @example
372
+ * // Simple usage (Pino-style: object first, message second)
373
+ * class OrderService {
374
+ * constructor(private readonly deps: { log: Logger }) {}
375
+ *
376
+ * @LoggedOperation('order.create')
377
+ * async createOrder(data: CreateOrderData) {
378
+ * // ✅ Correct Pino-style logging
379
+ * this.deps.log.info({ orderId: data.id }, 'Creating order');
380
+ * }
381
+ * }
382
+ *
383
+ * // Advanced usage (future-proof for options)
384
+ * @LoggedOperation({ operationName: 'order.create' })
385
+ * async createOrder(data: CreateOrderData) { }
386
+ */
387
+ function LoggedOperation(operationNameOrOptions) {
388
+ const operationName = typeof operationNameOrOptions === "string" ? operationNameOrOptions : operationNameOrOptions.operationName;
389
+ return function(originalMethod, context) {
390
+ const methodName = String(context.name);
391
+ return async function(...args) {
392
+ const log = this.deps?.log;
393
+ const startTime = performance.now();
394
+ return require_config.getConfig().tracer.startActiveSpan(operationName, async (span) => {
395
+ try {
396
+ log?.info({
397
+ operation: operationName,
398
+ method: methodName,
399
+ args
400
+ }, "Operation started");
401
+ const result = await originalMethod.apply(this, args);
402
+ const duration = performance.now() - startTime;
403
+ log?.info({
404
+ operation: operationName,
405
+ method: methodName,
406
+ duration
407
+ }, "Operation completed");
408
+ span.setStatus({ code: _opentelemetry_api.SpanStatusCode.OK });
409
+ span.setAttributes({
410
+ "operation.name": operationName,
411
+ "operation.method": methodName,
412
+ "operation.duration": duration,
413
+ "operation.success": true
414
+ });
415
+ return result;
416
+ } catch (error) {
417
+ const duration = performance.now() - startTime;
418
+ log?.error({
419
+ err: error instanceof Error ? error : void 0,
420
+ operation: operationName,
421
+ method: methodName,
422
+ duration
423
+ }, "Operation failed");
424
+ span.setStatus({
425
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
426
+ message: error instanceof Error ? error.message : "Unknown error"
427
+ });
428
+ span.setAttributes({
429
+ "operation.name": operationName,
430
+ "operation.method": methodName,
431
+ "operation.duration": duration,
432
+ "operation.success": false,
433
+ "error.type": error instanceof Error ? error.constructor.name : "Unknown"
434
+ });
435
+ throw error;
436
+ } finally {
437
+ span.end();
438
+ }
439
+ });
440
+ };
441
+ };
442
+ }
443
+
444
+ //#endregion
445
+ Object.defineProperty(exports, 'LOG_LEVEL', {
446
+ enumerable: true,
447
+ get: function () {
448
+ return LOG_LEVEL;
449
+ }
450
+ });
451
+ Object.defineProperty(exports, 'LoggedOperation', {
452
+ enumerable: true,
453
+ get: function () {
454
+ return LoggedOperation;
455
+ }
456
+ });
457
+ Object.defineProperty(exports, 'autotelLogger', {
458
+ enumerable: true,
459
+ get: function () {
460
+ return autotelLogger;
461
+ }
462
+ });
463
+ Object.defineProperty(exports, 'createBuiltinLogger', {
464
+ enumerable: true,
465
+ get: function () {
466
+ return createBuiltinLogger;
467
+ }
468
+ });
469
+ Object.defineProperty(exports, 'getActiveLogLevel', {
470
+ enumerable: true,
471
+ get: function () {
472
+ return getActiveLogLevel;
473
+ }
474
+ });
475
+ Object.defineProperty(exports, 'getTraceContext', {
476
+ enumerable: true,
477
+ get: function () {
478
+ return getTraceContext;
479
+ }
480
+ });
481
+ Object.defineProperty(exports, 'runWithLogLevel', {
482
+ enumerable: true,
483
+ get: function () {
484
+ return runWithLogLevel;
485
+ }
486
+ });
487
+ //# sourceMappingURL=logger-thMPLpOG.cjs.map