autotel 6.0.0 → 6.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/dist/analysis.cjs +1 -2
- package/dist/analysis.d.cts +1 -2
- package/dist/analysis.d.ts +1 -2
- package/dist/analysis.js +1 -2
- package/dist/attribute-redacting-processor-Pk7lAzWd.d.cts +1 -2
- package/dist/attribute-redacting-processor-Pk7lAzWd.d.ts +1 -2
- package/dist/attribute-redacting-processor.cjs +1 -2
- package/dist/attribute-redacting-processor.js +1 -2
- package/dist/attributes-B7wix2VG.js +1 -2
- package/dist/attributes-aDmJYral.cjs +1 -2
- package/dist/auto.cjs +2 -3
- package/dist/auto.js +2 -3
- package/dist/business-baggage.cjs +1 -2
- package/dist/business-baggage.d.cts +1 -2
- package/dist/business-baggage.d.ts +1 -2
- package/dist/business-baggage.js +1 -2
- package/dist/canonical-log-line-processor-B4WgG-VS.d.cts +1 -2
- package/dist/canonical-log-line-processor-CL_J7gb5.d.ts +1 -2
- package/dist/canonical-log-line-processor-DOjb6Kxy.cjs +1 -2
- package/dist/canonical-log-line-processor-mKABvGP0.js +1 -2
- package/dist/config.cjs +1 -2
- package/dist/config.d.cts +1 -2
- package/dist/config.d.ts +1 -2
- package/dist/config.js +1 -2
- package/dist/correlated-events-Bzh5y-UB.js +1 -2
- package/dist/correlated-events-kSwLo3mi.cjs +1 -2
- package/dist/correlation-id.cjs +1 -1
- package/dist/correlation-id.d.cts +1 -2
- package/dist/correlation-id.d.ts +1 -2
- package/dist/correlation-id.js +1 -1
- package/dist/db.cjs +1 -2
- package/dist/db.d.cts +1 -2
- package/dist/db.d.ts +1 -2
- package/dist/db.js +1 -2
- package/dist/decorators.cjs +2 -3
- package/dist/decorators.d.cts +1 -2
- package/dist/decorators.d.ts +1 -2
- package/dist/decorators.js +2 -3
- package/dist/define-event-B2z1SBe7.d.ts +1 -2
- package/dist/define-event-CGG048HE.d.cts +1 -2
- package/dist/diagnostics.cjs +1 -2
- package/dist/diagnostics.d.cts +1 -2
- package/dist/diagnostics.d.ts +1 -2
- package/dist/diagnostics.js +1 -2
- package/dist/drain-pipeline.cjs +11 -3
- package/dist/drain-pipeline.d.cts +6 -2
- package/dist/drain-pipeline.d.ts +6 -2
- package/dist/drain-pipeline.js +11 -3
- package/dist/enrichers.cjs +1 -2
- package/dist/enrichers.d.cts +1 -2
- package/dist/enrichers.d.ts +1 -2
- package/dist/enrichers.js +1 -2
- package/dist/event-subscriber-CWh8sTGh.d.cts +1 -2
- package/dist/event-subscriber-CWh8sTGh.d.ts +1 -2
- package/dist/event-testing-CA2mIx1E.d.ts +1 -2
- package/dist/event-testing-D0qWfqAy.d.cts +1 -2
- package/dist/event-testing.cjs +1 -2
- package/dist/event-testing.js +1 -2
- package/dist/event.cjs +1 -1
- package/dist/event.d.cts +1 -2
- package/dist/event.d.ts +1 -2
- package/dist/event.js +1 -1
- package/dist/exporters.d.cts +1 -2
- package/dist/exporters.d.ts +1 -2
- package/dist/filtering-span-processor-BpDagWNa.d.cts +1 -2
- package/dist/filtering-span-processor-BpDagWNa.d.ts +1 -2
- package/dist/filtering-span-processor.cjs +1 -2
- package/dist/filtering-span-processor.js +1 -2
- package/dist/{functional-DcLBuCPz.cjs → functional-D545J0Ba.cjs} +2 -3
- package/dist/{functional-BnDUxnSl.js → functional-DYAZiYxr.js} +2 -3
- package/dist/functional.cjs +1 -1
- package/dist/functional.d.cts +1 -2
- package/dist/functional.d.ts +1 -2
- package/dist/functional.js +1 -1
- package/dist/http.cjs +2 -3
- package/dist/http.d.cts +1 -2
- package/dist/http.d.ts +1 -2
- package/dist/http.js +2 -3
- package/dist/index-BPcxVucm.d.cts +1 -2
- package/dist/index-DolOVX6F.d.ts +1 -2
- package/dist/index.cjs +13 -6
- package/dist/index.d.cts +5 -3
- package/dist/index.d.ts +5 -3
- package/dist/index.js +13 -6
- package/dist/{init-D6n2diBy.d.ts → init-BHp-kqLJ.d.ts} +12 -4
- package/dist/{init-XzXzrarP.d.cts → init-BoIYyB6Q.d.cts} +12 -4
- package/dist/{init-C3RApHKJ.cjs → init-CzNFWUd8.cjs} +38 -5
- package/dist/{init-R-gSEXkJ.js → init-DDkh2brw.js} +38 -5
- package/dist/instrumentation.cjs +2 -3
- package/dist/instrumentation.d.cts +1 -2
- package/dist/instrumentation.d.ts +1 -2
- package/dist/instrumentation.js +2 -3
- package/dist/logger-CN4xpzMd.d.cts +1 -2
- package/dist/logger-CN4xpzMd.d.ts +1 -2
- package/dist/logger-D3Ej3DII.js +1 -2
- package/dist/logger-thMPLpOG.cjs +1 -2
- package/dist/messaging-adapters.cjs +1 -2
- package/dist/messaging-adapters.d.cts +1 -2
- package/dist/messaging-adapters.d.ts +1 -2
- package/dist/messaging-adapters.js +1 -2
- package/dist/messaging-testing.cjs +1 -2
- package/dist/messaging-testing.d.cts +1 -2
- package/dist/messaging-testing.d.ts +1 -2
- package/dist/messaging-testing.js +1 -2
- package/dist/messaging.cjs +2 -3
- package/dist/messaging.d.cts +1 -2
- package/dist/messaging.d.ts +1 -2
- package/dist/messaging.js +2 -3
- package/dist/metric-helpers.cjs +1 -2
- package/dist/metric-helpers.d.cts +1 -2
- package/dist/metric-helpers.d.ts +1 -2
- package/dist/metric-helpers.js +1 -2
- package/dist/metric-testing-CWm6UhaR.d.ts +1 -2
- package/dist/metric-testing-CpvP3ZIa.d.cts +1 -2
- package/dist/metric-testing.cjs +1 -2
- package/dist/metric-testing.js +1 -2
- package/dist/metric.cjs +1 -2
- package/dist/metric.d.cts +1 -2
- package/dist/metric.d.ts +1 -2
- package/dist/metric.js +1 -2
- package/dist/node-require-PFqDihze.cjs +1 -2
- package/dist/node-require-vROmTeJ8.js +1 -2
- package/dist/parse-error.cjs +1 -2
- package/dist/parse-error.d.cts +1 -2
- package/dist/parse-error.d.ts +1 -2
- package/dist/parse-error.js +1 -2
- package/dist/pretty-console-exporter-CMzlrRNg.cjs +1 -2
- package/dist/pretty-console-exporter-DqKl_q9z.js +1 -2
- package/dist/register.cjs +1 -2
- package/dist/register.js +1 -2
- package/dist/registry-DVSmWg6Y.js +1 -2
- package/dist/registry-DYgvb62e.cjs +1 -2
- package/dist/sampling-BR9fkSwx.d.cts +1 -2
- package/dist/sampling-CP3e7-Yr.d.ts +1 -2
- package/dist/sampling.cjs +1 -2
- package/dist/sampling.js +1 -2
- package/dist/security-schema.cjs +1 -2
- package/dist/security-schema.d.cts +1 -2
- package/dist/security-schema.d.ts +1 -2
- package/dist/security-schema.js +1 -2
- package/dist/semantic-conventions-FhSxv-bK.d.cts +1 -2
- package/dist/semantic-conventions-FhSxv-bK.d.ts +1 -2
- package/dist/semantic-conventions.cjs +1 -2
- package/dist/semantic-conventions.js +1 -2
- package/dist/semantic-helpers.cjs +2 -3
- package/dist/semantic-helpers.d.cts +1 -2
- package/dist/semantic-helpers.d.ts +1 -2
- package/dist/semantic-helpers.js +2 -3
- package/dist/slo.cjs +1 -2
- package/dist/slo.d.cts +1 -2
- package/dist/slo.d.ts +1 -2
- package/dist/slo.js +1 -2
- package/dist/span-name-normalizer-CN1-8C76.d.cts +1 -2
- package/dist/span-name-normalizer-CN1-8C76.d.ts +1 -2
- package/dist/span-name-normalizer.cjs +1 -2
- package/dist/span-name-normalizer.js +1 -2
- package/dist/stable-hash-CS9BxvVQ.cjs +1 -2
- package/dist/stable-hash-ChFBIhNt.js +1 -2
- package/dist/structured-error-9--cxBay.js +1 -2
- package/dist/structured-error-CHg7DoIQ.cjs +1 -2
- package/dist/tail-sampling-processor.cjs +1 -2
- package/dist/tail-sampling-processor.d.cts +1 -2
- package/dist/tail-sampling-processor.d.ts +1 -2
- package/dist/tail-sampling-processor.js +1 -2
- package/dist/test-span-collector.cjs +1 -2
- package/dist/test-span-collector.d.cts +1 -2
- package/dist/test-span-collector.d.ts +1 -2
- package/dist/test-span-collector.js +1 -2
- package/dist/testing.cjs +1 -2
- package/dist/testing.d.cts +1 -2
- package/dist/testing.d.ts +1 -2
- package/dist/testing.js +1 -2
- package/dist/trace-context-IuyoPyNq.d.cts +1 -2
- package/dist/trace-context-IuyoPyNq.d.ts +1 -2
- package/dist/trace-factory-validation-BjVAinz6.js +1 -2
- package/dist/trace-factory-validation-Dc8epn87.cjs +1 -2
- package/dist/trace-helpers.cjs +1 -2
- package/dist/trace-helpers.d.cts +1 -2
- package/dist/trace-helpers.d.ts +1 -2
- package/dist/trace-helpers.js +1 -2
- package/dist/tracer-provider.cjs +1 -2
- package/dist/tracer-provider.d.cts +1 -2
- package/dist/tracer-provider.d.ts +1 -2
- package/dist/tracer-provider.js +1 -2
- package/dist/validate.cjs +1 -2
- package/dist/validate.d.cts +1 -2
- package/dist/validate.d.ts +1 -2
- package/dist/validate.js +1 -2
- package/dist/validation-attributes.cjs +1 -2
- package/dist/validation-attributes.d.cts +1 -2
- package/dist/validation-attributes.d.ts +1 -2
- package/dist/validation-attributes.js +1 -2
- package/dist/webhook.cjs +2 -3
- package/dist/webhook.d.cts +1 -2
- package/dist/webhook.d.ts +1 -2
- package/dist/webhook.js +2 -3
- package/dist/workflow-distributed.cjs +2 -3
- package/dist/workflow-distributed.d.cts +1 -2
- package/dist/workflow-distributed.d.ts +1 -2
- package/dist/workflow-distributed.js +2 -3
- package/dist/workflow.cjs +2 -3
- package/dist/workflow.d.cts +1 -2
- package/dist/workflow.d.ts +1 -2
- package/dist/workflow.js +2 -3
- package/dist/yaml-config.cjs +1 -2
- package/dist/yaml-config.d.cts +4 -5
- package/dist/yaml-config.d.ts +4 -5
- package/dist/yaml-config.js +1 -2
- package/package.json +47 -32
- package/dist/analysis.cjs.map +0 -1
- package/dist/analysis.d.cts.map +0 -1
- package/dist/analysis.d.ts.map +0 -1
- package/dist/analysis.js.map +0 -1
- package/dist/attribute-redacting-processor-Pk7lAzWd.d.cts.map +0 -1
- package/dist/attribute-redacting-processor-Pk7lAzWd.d.ts.map +0 -1
- package/dist/attribute-redacting-processor.cjs.map +0 -1
- package/dist/attribute-redacting-processor.js.map +0 -1
- package/dist/attributes-B7wix2VG.js.map +0 -1
- package/dist/attributes-aDmJYral.cjs.map +0 -1
- package/dist/auto.cjs.map +0 -1
- package/dist/auto.js.map +0 -1
- package/dist/business-baggage.cjs.map +0 -1
- package/dist/business-baggage.d.cts.map +0 -1
- package/dist/business-baggage.d.ts.map +0 -1
- package/dist/business-baggage.js.map +0 -1
- package/dist/canonical-log-line-processor-B4WgG-VS.d.cts.map +0 -1
- package/dist/canonical-log-line-processor-CL_J7gb5.d.ts.map +0 -1
- package/dist/canonical-log-line-processor-DOjb6Kxy.cjs.map +0 -1
- package/dist/canonical-log-line-processor-mKABvGP0.js.map +0 -1
- package/dist/config.cjs.map +0 -1
- package/dist/config.d.cts.map +0 -1
- package/dist/config.d.ts.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/correlated-events-Bzh5y-UB.js.map +0 -1
- package/dist/correlated-events-kSwLo3mi.cjs.map +0 -1
- package/dist/correlation-id.d.cts.map +0 -1
- package/dist/correlation-id.d.ts.map +0 -1
- package/dist/db.cjs.map +0 -1
- package/dist/db.d.cts.map +0 -1
- package/dist/db.d.ts.map +0 -1
- package/dist/db.js.map +0 -1
- package/dist/decorators.cjs.map +0 -1
- package/dist/decorators.d.cts.map +0 -1
- package/dist/decorators.d.ts.map +0 -1
- package/dist/decorators.js.map +0 -1
- package/dist/define-event-B2z1SBe7.d.ts.map +0 -1
- package/dist/define-event-CGG048HE.d.cts.map +0 -1
- package/dist/diagnostics.cjs.map +0 -1
- package/dist/diagnostics.d.cts.map +0 -1
- package/dist/diagnostics.d.ts.map +0 -1
- package/dist/diagnostics.js.map +0 -1
- package/dist/drain-pipeline.cjs.map +0 -1
- package/dist/drain-pipeline.d.cts.map +0 -1
- package/dist/drain-pipeline.d.ts.map +0 -1
- package/dist/drain-pipeline.js.map +0 -1
- package/dist/enrichers.cjs.map +0 -1
- package/dist/enrichers.d.cts.map +0 -1
- package/dist/enrichers.d.ts.map +0 -1
- package/dist/enrichers.js.map +0 -1
- package/dist/event-subscriber-CWh8sTGh.d.cts.map +0 -1
- package/dist/event-subscriber-CWh8sTGh.d.ts.map +0 -1
- package/dist/event-testing-CA2mIx1E.d.ts.map +0 -1
- package/dist/event-testing-D0qWfqAy.d.cts.map +0 -1
- package/dist/event-testing.cjs.map +0 -1
- package/dist/event-testing.js.map +0 -1
- package/dist/event.d.cts.map +0 -1
- package/dist/event.d.ts.map +0 -1
- package/dist/exporters.d.cts.map +0 -1
- package/dist/exporters.d.ts.map +0 -1
- package/dist/filtering-span-processor-BpDagWNa.d.cts.map +0 -1
- package/dist/filtering-span-processor-BpDagWNa.d.ts.map +0 -1
- package/dist/filtering-span-processor.cjs.map +0 -1
- package/dist/filtering-span-processor.js.map +0 -1
- package/dist/functional-BnDUxnSl.js.map +0 -1
- package/dist/functional-DcLBuCPz.cjs.map +0 -1
- package/dist/functional.d.cts.map +0 -1
- package/dist/functional.d.ts.map +0 -1
- package/dist/http.cjs.map +0 -1
- package/dist/http.d.cts.map +0 -1
- package/dist/http.d.ts.map +0 -1
- package/dist/http.js.map +0 -1
- package/dist/index-BPcxVucm.d.cts.map +0 -1
- package/dist/index-DolOVX6F.d.ts.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/init-C3RApHKJ.cjs.map +0 -1
- package/dist/init-D6n2diBy.d.ts.map +0 -1
- package/dist/init-R-gSEXkJ.js.map +0 -1
- package/dist/init-XzXzrarP.d.cts.map +0 -1
- package/dist/instrumentation.cjs.map +0 -1
- package/dist/instrumentation.d.cts.map +0 -1
- package/dist/instrumentation.d.ts.map +0 -1
- package/dist/instrumentation.js.map +0 -1
- package/dist/logger-CN4xpzMd.d.cts.map +0 -1
- package/dist/logger-CN4xpzMd.d.ts.map +0 -1
- package/dist/logger-D3Ej3DII.js.map +0 -1
- package/dist/logger-thMPLpOG.cjs.map +0 -1
- package/dist/messaging-adapters.cjs.map +0 -1
- package/dist/messaging-adapters.d.cts.map +0 -1
- package/dist/messaging-adapters.d.ts.map +0 -1
- package/dist/messaging-adapters.js.map +0 -1
- package/dist/messaging-testing.cjs.map +0 -1
- package/dist/messaging-testing.d.cts.map +0 -1
- package/dist/messaging-testing.d.ts.map +0 -1
- package/dist/messaging-testing.js.map +0 -1
- package/dist/messaging.cjs.map +0 -1
- package/dist/messaging.d.cts.map +0 -1
- package/dist/messaging.d.ts.map +0 -1
- package/dist/messaging.js.map +0 -1
- package/dist/metric-helpers.cjs.map +0 -1
- package/dist/metric-helpers.d.cts.map +0 -1
- package/dist/metric-helpers.d.ts.map +0 -1
- package/dist/metric-helpers.js.map +0 -1
- package/dist/metric-testing-CWm6UhaR.d.ts.map +0 -1
- package/dist/metric-testing-CpvP3ZIa.d.cts.map +0 -1
- package/dist/metric-testing.cjs.map +0 -1
- package/dist/metric-testing.js.map +0 -1
- package/dist/metric.cjs.map +0 -1
- package/dist/metric.d.cts.map +0 -1
- package/dist/metric.d.ts.map +0 -1
- package/dist/metric.js.map +0 -1
- package/dist/node-require-PFqDihze.cjs.map +0 -1
- package/dist/node-require-vROmTeJ8.js.map +0 -1
- package/dist/parse-error.cjs.map +0 -1
- package/dist/parse-error.d.cts.map +0 -1
- package/dist/parse-error.d.ts.map +0 -1
- package/dist/parse-error.js.map +0 -1
- package/dist/pretty-console-exporter-CMzlrRNg.cjs.map +0 -1
- package/dist/pretty-console-exporter-DqKl_q9z.js.map +0 -1
- package/dist/register.cjs.map +0 -1
- package/dist/register.js.map +0 -1
- package/dist/registry-DVSmWg6Y.js.map +0 -1
- package/dist/registry-DYgvb62e.cjs.map +0 -1
- package/dist/sampling-BR9fkSwx.d.cts.map +0 -1
- package/dist/sampling-CP3e7-Yr.d.ts.map +0 -1
- package/dist/sampling.cjs.map +0 -1
- package/dist/sampling.js.map +0 -1
- package/dist/security-schema.cjs.map +0 -1
- package/dist/security-schema.d.cts.map +0 -1
- package/dist/security-schema.d.ts.map +0 -1
- package/dist/security-schema.js.map +0 -1
- package/dist/semantic-conventions-FhSxv-bK.d.cts.map +0 -1
- package/dist/semantic-conventions-FhSxv-bK.d.ts.map +0 -1
- package/dist/semantic-conventions.cjs.map +0 -1
- package/dist/semantic-conventions.js.map +0 -1
- package/dist/semantic-helpers.cjs.map +0 -1
- package/dist/semantic-helpers.d.cts.map +0 -1
- package/dist/semantic-helpers.d.ts.map +0 -1
- package/dist/semantic-helpers.js.map +0 -1
- package/dist/slo.cjs.map +0 -1
- package/dist/slo.d.cts.map +0 -1
- package/dist/slo.d.ts.map +0 -1
- package/dist/slo.js.map +0 -1
- package/dist/span-name-normalizer-CN1-8C76.d.cts.map +0 -1
- package/dist/span-name-normalizer-CN1-8C76.d.ts.map +0 -1
- package/dist/span-name-normalizer.cjs.map +0 -1
- package/dist/span-name-normalizer.js.map +0 -1
- package/dist/stable-hash-CS9BxvVQ.cjs.map +0 -1
- package/dist/stable-hash-ChFBIhNt.js.map +0 -1
- package/dist/structured-error-9--cxBay.js.map +0 -1
- package/dist/structured-error-CHg7DoIQ.cjs.map +0 -1
- package/dist/tail-sampling-processor.cjs.map +0 -1
- package/dist/tail-sampling-processor.d.cts.map +0 -1
- package/dist/tail-sampling-processor.d.ts.map +0 -1
- package/dist/tail-sampling-processor.js.map +0 -1
- package/dist/test-span-collector.cjs.map +0 -1
- package/dist/test-span-collector.d.cts.map +0 -1
- package/dist/test-span-collector.d.ts.map +0 -1
- package/dist/test-span-collector.js.map +0 -1
- package/dist/testing.cjs.map +0 -1
- package/dist/testing.d.cts.map +0 -1
- package/dist/testing.d.ts.map +0 -1
- package/dist/testing.js.map +0 -1
- package/dist/trace-context-IuyoPyNq.d.cts.map +0 -1
- package/dist/trace-context-IuyoPyNq.d.ts.map +0 -1
- package/dist/trace-factory-validation-BjVAinz6.js.map +0 -1
- package/dist/trace-factory-validation-Dc8epn87.cjs.map +0 -1
- package/dist/trace-helpers.cjs.map +0 -1
- package/dist/trace-helpers.d.cts.map +0 -1
- package/dist/trace-helpers.d.ts.map +0 -1
- package/dist/trace-helpers.js.map +0 -1
- package/dist/tracer-provider.cjs.map +0 -1
- package/dist/tracer-provider.d.cts.map +0 -1
- package/dist/tracer-provider.d.ts.map +0 -1
- package/dist/tracer-provider.js.map +0 -1
- package/dist/validate.cjs.map +0 -1
- package/dist/validate.d.cts.map +0 -1
- package/dist/validate.d.ts.map +0 -1
- package/dist/validate.js.map +0 -1
- package/dist/validation-attributes.cjs.map +0 -1
- package/dist/validation-attributes.d.cts.map +0 -1
- package/dist/validation-attributes.d.ts.map +0 -1
- package/dist/validation-attributes.js.map +0 -1
- package/dist/webhook.cjs.map +0 -1
- package/dist/webhook.d.cts.map +0 -1
- package/dist/webhook.d.ts.map +0 -1
- package/dist/webhook.js.map +0 -1
- package/dist/workflow-distributed.cjs.map +0 -1
- package/dist/workflow-distributed.d.cts.map +0 -1
- package/dist/workflow-distributed.d.ts.map +0 -1
- package/dist/workflow-distributed.js.map +0 -1
- package/dist/workflow.cjs.map +0 -1
- package/dist/workflow.d.cts.map +0 -1
- package/dist/workflow.d.ts.map +0 -1
- package/dist/workflow.js.map +0 -1
- package/dist/yaml-config.cjs.map +0 -1
- package/dist/yaml-config.d.cts.map +0 -1
- package/dist/yaml-config.d.ts.map +0 -1
- package/dist/yaml-config.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"functional-BnDUxnSl.js","names":["getInitConfig","otelTrace","trace"],"sources":["../src/variable-name-inference.ts","../src/functional.ts"],"sourcesContent":["/**\n * Variable Name Inference Utility\n *\n * Attempts to infer variable names from const/export const assignments\n * by analyzing the call stack and parsing source code.\n *\n * This is a best-effort approach with graceful degradation - if inference\n * fails for any reason, it returns undefined without breaking the application.\n */\n\n// namespace imports for browser-bundler compat — see node-require.ts\nimport * as nodeFs from 'node:fs';\nimport * as nodeUrl from 'node:url';\n\ninterface CallLocation {\n file: string;\n line: number;\n column: number;\n}\n\n/**\n * LRU Cache for inferred variable names\n * Key: \"file:line\" (e.g., \"/path/to/file.ts:42\")\n * Value: inferred variable name or undefined\n */\nconst inferenceCache = new Map<string, string | undefined>();\nconst MAX_CACHE_SIZE = 50;\n\n/**\n * Captures the current call stack\n */\nfunction captureStackTrace(): string {\n const originalStackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 10; // Only need first few frames\n\n const err = new Error('Stack trace capture');\n const stack = err.stack || '';\n\n Error.stackTraceLimit = originalStackTraceLimit;\n return stack;\n}\n\n/**\n * Parses the stack trace to find where trace() was called\n *\n * Stack trace format (Node.js):\n * at functionName (file:line:column)\n * at file:line:column\n *\n * We skip frames until we find one that's NOT in functional.ts or this file.\n * We also need to skip one additional frame (the trace/span/instrument function itself)\n * to get to the actual user code.\n */\nfunction parseCallLocation(stack: string): CallLocation | undefined {\n const lines = stack.split('\\n');\n let skippedExternalFrame = false;\n\n for (const line of lines) {\n // Skip if line contains this file or functional.ts (internal frames)\n // Be specific about the filename to avoid matching test files\n if (\n line.includes('variable-name-inference.ts') ||\n line.includes('variable-name-inference.js') ||\n line.includes('functional.ts') ||\n line.includes('functional.js')\n ) {\n continue;\n }\n\n // Match various stack trace formats\n // Format 1: at functionName (file:line:column)\n // Format 2: at file:line:column\n const match =\n line.match(/at\\s+(?:.*\\s+)?\\(?([^:]+):(\\d+):(\\d+)\\)?/) ||\n line.match(/^.*?([^:]+):(\\d+):(\\d+)/);\n\n if (match) {\n let filePath = match[1]!.trim();\n\n // Handle file:// URLs (convert to paths)\n if (filePath.startsWith('file://')) {\n try {\n filePath = nodeUrl.fileURLToPath(filePath);\n } catch {\n continue;\n }\n }\n\n // Skip the first external frame (the trace/span function itself)\n // We want the frame where the user CALLS trace(), not inside trace()\n if (!skippedExternalFrame) {\n skippedExternalFrame = true;\n continue;\n }\n\n return {\n file: filePath,\n line: Number.parseInt(match[2]!, 10),\n column: Number.parseInt(match[3]!, 10),\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Reads a specific line from a source file\n */\nfunction readSourceLine(\n filePath: string,\n lineNumber: number,\n): string | undefined {\n try {\n // Check if we can access the file system (not available in edge runtimes)\n if (typeof nodeFs.readFileSync !== 'function') {\n return undefined;\n }\n\n const content = nodeFs.readFileSync(filePath, 'utf8');\n const lines = content.split('\\n');\n\n // Line numbers are 1-based\n return lines[lineNumber - 1];\n } catch {\n // File doesn't exist, permission denied, or other error\n return undefined;\n }\n}\n\n/**\n * Extracts variable name from source code line using regex patterns\n *\n * Supported patterns:\n * - const varName = anyFunction(\n * - export const varName = anyFunction(\n * - let varName = anyFunction(\n * - var varName = anyFunction(\n *\n * Note: This won't work with destructuring assignments or complex patterns\n */\nfunction extractVariableName(sourceLine: string): string | undefined {\n // Remove leading/trailing whitespace\n const trimmed = sourceLine.trim();\n\n // Pattern: (export)? (const|let|var) varName = anyFunctionCall(\n // We match any function call, not just trace(), to support wrapper functions\n const patterns = [\n // export const varName = anyFunction(\n /export\\s+const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // const varName = anyFunction(\n /const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export let varName = anyFunction(\n /export\\s+let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // let varName = anyFunction(\n /let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export var varName = anyFunction(\n /export\\s+var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // var varName = anyFunction(\n /var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n ];\n\n for (const pattern of patterns) {\n const match = trimmed.match(pattern);\n if (match && match[1]) {\n return match[1];\n }\n }\n\n return undefined;\n}\n\n/**\n * Adds an entry to the cache with LRU eviction\n */\nfunction cacheInference(key: string, value: string | undefined): void {\n // If cache is full, remove oldest entry (first entry in Map)\n if (inferenceCache.size >= MAX_CACHE_SIZE) {\n const firstKey = inferenceCache.keys().next().value;\n if (firstKey) {\n inferenceCache.delete(firstKey);\n }\n }\n\n inferenceCache.set(key, value);\n}\n\n/**\n * Main entry point: Attempts to infer the variable name from the call stack\n *\n * This function:\n * 1. Captures the call stack\n * 2. Parses it to find where trace() was called (file + line)\n * 3. Reads that line from the source file\n * 4. Extracts the variable name using regex\n *\n * Returns undefined if inference fails at any step (graceful degradation).\n * Results are cached to avoid repeated file I/O.\n *\n * @returns The inferred variable name, or undefined if inference failed\n */\nexport function inferVariableNameFromCallStack(): string | undefined {\n try {\n // Capture stack trace\n const stack = captureStackTrace();\n\n // Parse stack to find trace() call location\n const callLocation = parseCallLocation(stack);\n if (!callLocation) {\n return undefined;\n }\n\n // Check cache\n const cacheKey = `${callLocation.file}:${callLocation.line}`;\n if (inferenceCache.has(cacheKey)) {\n return inferenceCache.get(cacheKey);\n }\n\n // Read source line\n const sourceLine = readSourceLine(callLocation.file, callLocation.line);\n if (!sourceLine) {\n return undefined;\n }\n\n // Extract variable name\n const variableName = extractVariableName(sourceLine);\n\n // Cache result (even if undefined, to avoid repeated failed attempts)\n cacheInference(cacheKey, variableName);\n\n return variableName;\n } catch {\n // Graceful degradation - don't break the app if inference fails\n return undefined;\n }\n}\n\n/**\n * Clears the inference cache (useful for testing)\n */\nexport function clearInferenceCache(): void {\n inferenceCache.clear();\n}\n","/**\n * Functional API for non-class code\n *\n * Three approaches for different use cases:\n * 1. trace() - Zero-ceremony HOF for single functions\n * 2. withTracing() - Middleware-style composable wrapper\n * 3. instrument() - Batch auto-instrumentation for modules\n *\n * @example trace() - Single function\n * ```typescript\n * export const createUser = trace(async (data) => {\n * getActiveTraceContext()?.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example withTracing() - Composable middleware\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example instrument() - Batch instrumentation\n * ```typescript\n * export default instrument({\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { }\n * }, { serviceName: 'user' })\n * ```\n */\n\nimport {\n SpanStatusCode,\n trace as otelTrace,\n context,\n propagation,\n type Span,\n type Counter,\n type Histogram,\n type Attributes,\n} from '@opentelemetry/api';\nimport { getConfig } from './config';\nimport { getConfig as getInitConfig, getSdk } from './init';\nimport { getForceFlushableProvider } from './tracer-provider';\nimport {\n type Sampler,\n type SamplingContext,\n AlwaysSampler,\n AUTOTEL_SAMPLING_TAIL_KEEP,\n AUTOTEL_SAMPLING_TAIL_EVALUATED,\n AUTOTEL_SAMPLING_RATE,\n} from './sampling';\nimport { getEventQueue } from './track';\nimport type { TraceContext } from './trace-context';\nimport {\n createTraceContext,\n getActiveContextWithBaggage,\n getContextStorage,\n} from './trace-context';\nimport { setSpanName } from './trace-helpers';\nimport { runInOperationContext } from './operation-context';\nimport { inferVariableNameFromCallStack } from './variable-name-inference';\n\n/**\n * Complete trace context containing trace identifiers and span methods\n *\n * The ctx parameter in trace() functions provides:\n * - traceId, spanId, correlationId from the active span\n * - Span manipulation methods (setAttribute, setAttributes, setStatus, recordException)\n *\n * For custom context, access it directly in your functions (standard OpenTelemetry pattern).\n *\n * @example\n * ```typescript\n * import { trace } from 'autotel'\n *\n * export const createUser = withTracing({})((ctx) => async (data: CreateUserData) => {\n * // Get custom context directly (standard OTel approach)\n * const userId = getCurrentUserId()\n * const tenantId = getCurrentTenant()\n *\n * // Use ctx for span operations and trace IDs\n * ctx.setAttribute('user.id', data.id)\n * ctx.setAttribute('user.tenant', tenantId)\n * console.log(ctx.traceId) // Trace IDs available\n * })\n * ```\n */\nexport type { TraceContext } from './trace-context';\n\nlet unknownSpanNameWarningEmitted = false;\n\ntype WrappedFunction<TArgs extends unknown[], TReturn> = (\n ...args: TArgs\n) => TReturn | Promise<TReturn>;\n\nfunction resolveVariableName(\n named: InstrumentableFunction,\n variableName?: string,\n): string | undefined {\n const suppliedFunctionName = inferFunctionName(named);\n const callStackVariableName = suppliedFunctionName\n ? undefined\n : inferVariableNameFromCallStack();\n return variableName || suppliedFunctionName || callStackVariableName;\n}\n\n/**\n * Wrap an explicit context factory `(ctx) => (...args) => result`.\n * Used by {@link withTracing}; the input is a factory by contract, so there is\n * no plain-vs-factory detection. The factory is never invoked at construction\n * time — only when the wrapper is called.\n */\nfunction wrapFactoryWithTracing<TArgs extends unknown[], TReturn>(\n factory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n const effectiveVariableName = resolveVariableName(\n factory as InstrumentableFunction,\n variableName,\n );\n return wrapWithTracingSync(\n factory,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Wrap a plain function `(...args) => result`. Used by {@link trace} and\n * {@link instrument}: the function receives its real arguments and no context\n * is injected. Reach the active span via {@link getActiveTraceContext} inside\n * the body (or any helper it calls).\n */\nfunction wrapPlainWithTracing<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n const effectiveVariableName = resolveVariableName(\n fn as InstrumentableFunction,\n variableName,\n );\n const factory = (_ctx: TraceContext) => fn;\n return wrapWithTracingSync(\n factory,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Common options for functional tracing\n */\nexport interface TracingOptions<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> {\n /**\n * Span name (highest priority)\n * If provided, this is used as the span name\n */\n name?: string;\n\n /**\n * Service name (used to compose final span name)\n * If name not provided, span name becomes: ${serviceName}.${functionName}\n */\n serviceName?: string;\n\n /**\n * Sampling strategy\n * @default AlwaysSampler\n */\n sampler?: Sampler;\n\n /**\n * Enable metrics collection (counter, histogram)\n * @default false\n */\n withMetrics?: boolean;\n\n /**\n * Extract attributes from function arguments\n */\n attributesFromArgs?: (args: TArgs) => Record<string, unknown>;\n\n /**\n * Extract attributes from function result\n */\n attributesFromResult?: (result: TReturn) => Record<string, unknown>;\n\n /**\n * Capture the function arguments onto the span as `autotel.input`\n * (JSON, truncated). One arg is captured directly; multiple are captured as\n * an array. Off by default — opt in per call. Tools (visualizers, devtools)\n * read this alongside `ai.toolCall.args` to show function I/O uniformly.\n * Avoid on args with secrets/PII, or pair with a redacting processor.\n */\n captureInput?: boolean;\n\n /**\n * Capture the function return value onto the span as `autotel.output`\n * (JSON, truncated). Off by default. Same caveats as {@link captureInput}.\n */\n captureOutput?: boolean;\n\n /**\n * Start a new root span instead of creating a child\n * Useful for serverless entry points\n * @default false\n */\n startNewRoot?: boolean;\n\n /**\n * Flush events queue when span ends\n * Only flushes on root spans (to avoid excessive flushing)\n * @default true\n */\n flushOnRootSpanEnd?: boolean;\n\n /**\n * Span kind for semantic convention compliance\n * Used for messaging (PRODUCER/CONSUMER), HTTP (CLIENT/SERVER), etc.\n * @default SpanKind.INTERNAL\n */\n spanKind?: import('@opentelemetry/api').SpanKind;\n\n /**\n * Classify a thrown value as a real error. Return `false` to treat the throw\n * as expected control flow: the span is marked OK, no exception is recorded,\n * and the value is rethrown untouched. Use this for framework control-flow\n * signals that propagate via `throw` but are not failures — e.g. TanStack\n * Router / Next.js `redirect()` and `notFound()`.\n * @default every throw is treated as an error\n */\n isError?: (error: unknown) => boolean;\n}\n\n/**\n * Options for instrument() batch instrumentation\n */\nexport interface InstrumentOptions<\n T extends Record<string, AnyInstrumentable> = Record<\n string,\n AnyInstrumentable\n >,\n> extends TracingOptions {\n /** Object whose function properties should be instrumented */\n functions: T;\n /**\n * Per-function configuration overrides\n */\n overrides?: Record<string, Partial<TracingOptions>>;\n\n /**\n * Functions to skip (won't be instrumented)\n * Supports:\n * - String keys: 'functionName'\n * - RegExp: /^_internal/\n * - Predicate: (key, fn) => boolean\n *\n * By default, functions starting with _ are skipped\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[];\n}\n\n/**\n * Options for instrumenting one function with an explicit stable key.\n */\nexport interface SingleInstrumentOptions<\n TFunction extends AnyInstrumentable = AnyInstrumentable,\n> extends TracingOptions {\n /** Stable function key used for span naming */\n key: string;\n /** Function to instrument */\n fn: TFunction;\n}\n\n// Maximum error message length to prevent span bloat\nconst MAX_ERROR_MESSAGE_LENGTH = 500;\n\nfunction createDummyCtx<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> {\n // `recordException` / `addEvent` are no-op shims kept for the same\n // compatibility window as `createTraceContext` (see trace-context.ts).\n return {\n traceId: '',\n spanId: '',\n correlationId: '',\n setAttribute: () => {},\n setAttributes: () => {},\n setStatus: () => {},\n recordException: () => {},\n addEvent: () => {},\n addLink: () => {},\n addLinks: () => {},\n updateName: () => {},\n isRecording: () => false,\n getBaggage: () => {},\n setBaggage: () => '',\n deleteBaggage: () => {},\n getAllBaggage: () => new Map(),\n } as unknown as TraceContext<TBaggage>;\n}\n\n/** Attribute keys for opt-in function I/O capture (see TracingOptions). */\nconst AUTOTEL_INPUT_ATTR = 'autotel.input';\nconst AUTOTEL_OUTPUT_ATTR = 'autotel.output';\nconst CAPTURE_MAX_CHARS = 4096;\n\n/** JSON-serialize a captured value, defensively (truncate, swallow cycles). */\nfunction serializeCapture(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n try {\n const json = typeof value === 'string' ? value : JSON.stringify(value);\n if (json === undefined) return undefined;\n return json.length > CAPTURE_MAX_CHARS\n ? `${json.slice(0, CAPTURE_MAX_CHARS)}…[truncated]`\n : json;\n } catch {\n return undefined;\n }\n}\n\n/** `autotel.input` from args (single arg captured directly, else the array). */\nfunction captureInputAttrs(\n args: unknown[],\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(args.length === 1 ? args[0] : args);\n return s === undefined ? {} : { [AUTOTEL_INPUT_ATTR]: s };\n}\n\n/** `autotel.output` from the return value. */\nfunction captureOutputAttrs(\n result: unknown,\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(result);\n return s === undefined ? {} : { [AUTOTEL_OUTPUT_ATTR]: s };\n}\n\n// Symbol to prevent double-instrumentation (idempotency flag)\nconst INSTRUMENTED_SYMBOL = Symbol.for('autotel.functional.instrumented');\n\ntype InstrumentedFlag = {\n [INSTRUMENTED_SYMBOL]?: true;\n};\n\nfunction hasInstrumentationFlag(value: unknown): value is InstrumentedFlag {\n return (\n (typeof value === 'function' || typeof value === 'object') &&\n value !== null &&\n Boolean((value as InstrumentedFlag)[INSTRUMENTED_SYMBOL])\n );\n}\n\n/**\n * Truncate error message to prevent span bloat\n */\nfunction truncateErrorMessage(message: string): string {\n if (message.length <= MAX_ERROR_MESSAGE_LENGTH) {\n return message;\n }\n return `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}... (truncated)`;\n}\n\n/** Per-invocation state the terminal span handlers close over. */\ninterface SpanFinalizeContext {\n span: Span;\n spanName: string;\n duration: number;\n callCounter?: Counter;\n durationHistogram?: Histogram;\n handleTailSampling: (\n success: boolean,\n duration: number,\n error?: Error,\n ) => void;\n /** Extra attributes to merge (e.g. captured args); absent on immediate-exec paths. */\n extraAttributes?: Attributes;\n}\n\n/**\n * Terminal handling for a value thrown by a traced function. Shared by all four\n * `trace()` execution paths (immediate + wrapper, sync + async) so the outcome\n * rules live in exactly one place. Ends the span; the caller flushes (await/void)\n * and rethrows.\n *\n * If `isError` classifies the throw as expected control flow — e.g. a framework\n * `redirect()` / `notFound()` signal — it is recorded as a success outcome with\n * an OK status and no exception. Otherwise it is recorded as an error.\n */\nfunction finalizeThrownSpan(\n error: unknown,\n isError: ((error: unknown) => boolean) | undefined,\n ctx: SpanFinalizeContext,\n): void {\n const {\n span,\n spanName,\n duration,\n callCounter,\n durationHistogram,\n handleTailSampling,\n extraAttributes,\n } = ctx;\n\n const baseAttributes: Attributes = {\n ...extraAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n };\n\n if (isError && !isError(error)) {\n callCounter?.add(1, { operation: spanName, status: 'success' });\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({ ...baseAttributes, 'operation.success': true });\n handleTailSampling(true, duration);\n span.end();\n return;\n }\n\n callCounter?.add(1, { operation: spanName, status: 'error' });\n durationHistogram?.record(duration, { operation: spanName, status: 'error' });\n\n const truncatedMessage = truncateErrorMessage(\n error instanceof Error ? error.message : 'Unknown error',\n );\n\n span.setStatus({ code: SpanStatusCode.ERROR, message: truncatedMessage });\n span.setAttributes({\n ...baseAttributes,\n 'operation.success': false,\n error: true,\n 'exception.type': error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n const thrown = error instanceof Error ? error : new Error(String(error));\n span.recordException(thrown);\n // Samplers read result.error, so hand them a real Error rather than\n // whatever the code threw.\n handleTailSampling(false, duration, thrown);\n span.end();\n}\n\ntype InstrumentableFunction<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> = ((...args: TArgs) => TReturn | Promise<TReturn>) & {\n displayName?: string;\n name?: string;\n};\n\n/**\n * Constraint alias for `instrument()` and friends. `never[]` parameters make\n * every concretely-typed function (e.g. `(name: string) => Promise<User>`)\n * satisfy the constraint under `strictFunctionTypes` without resorting to\n * `any`. Use ONLY in constraint positions — the concrete `T` is still\n * inferred from the actual argument, so call-site argument and return types\n * are fully preserved.\n */\ntype AnyInstrumentable = ((...args: never[]) => unknown) & {\n displayName?: string;\n name?: string;\n};\n\n/**\n * Try to infer function name from function properties\n * Checks for displayName, name, or other metadata that might be set\n */\nfunction inferFunctionName<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(fn: InstrumentableFunction<TArgs, TReturn>): string | undefined {\n // Check for displayName property (sometimes set by bundlers)\n const displayName = (fn as { displayName?: string }).displayName;\n if (displayName) {\n return displayName;\n }\n\n // Check function.name (works for named functions and modern arrow function assignment)\n // Note: Empty string is falsy, so this handles both undefined and ''\n if (fn.name && fn.name !== 'anonymous' && fn.name !== '') {\n return fn.name;\n }\n\n // Try to extract name from function source (for function declarations)\n const source = Function.prototype.toString.call(fn);\n const match = source.match(/function\\s+([^(\\s]+)/);\n if (match && match[1] && match[1] !== 'anonymous') {\n return match[1];\n }\n\n return undefined;\n}\n\n/**\n * Determine span name using priority:\n * 1. Explicit name option\n * 2. serviceName + functionName\n * 3. Inferred from function/variable name (including stack trace fallback)\n * 4. Fallback to 'unknown'\n */\nfunction getSpanName<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fn: InstrumentableFunction<TArgs, TReturn>,\n variableName?: string,\n): string {\n // 1. Explicit name\n if (options.name) {\n return options.name;\n }\n\n // 2. Try variable name, function name, or function properties\n let fnName = variableName || inferFunctionName(fn);\n\n // Default to 'anonymous' if still no name\n fnName = fnName || 'anonymous';\n\n // 2. serviceName + functionName\n if (options.serviceName) {\n return `${options.serviceName}.${fnName}`;\n }\n\n // 3. Inferred from function name\n if (fnName && fnName !== 'anonymous') {\n return fnName;\n }\n\n // 4. Fallback\n const initConfig = getInitConfig();\n if (\n typeof process !== 'undefined' &&\n process.env.NODE_ENV !== 'production' &&\n !unknownSpanNameWarningEmitted &&\n initConfig?.logger?.warn\n ) {\n unknownSpanNameWarningEmitted = true;\n initConfig.logger.warn(\n {},\n '[autotel] Span name resolved to \"unknown\". Pass an explicit name, for example trace(\"operation.name\", fn).',\n );\n }\n return 'unknown';\n}\n\n/**\n * Check if function should be skipped\n */\nfunction shouldSkip(\n key: string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n fn: Function,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[],\n): boolean {\n // Default: skip functions starting with _\n if (key.startsWith('_')) {\n return true;\n }\n\n if (!skip || skip.length === 0) {\n return false;\n }\n\n for (const rule of skip) {\n if (typeof rule === 'string' && key === rule) {\n return true;\n } else if (rule instanceof RegExp && rule.test(key)) {\n return true;\n } else if (typeof rule === 'function' && rule(key, fn)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Get current trace context value (internal helper)\n *\n * Returns base context (trace IDs) + span methods from the active span.\n */\nfunction getCtxValue<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> | null {\n const activeSpan = otelTrace.getActiveSpan();\n if (!activeSpan) return null;\n\n // Use shared utility to create trace context\n return createTraceContext<TBaggage>(activeSpan);\n}\n\n/**\n * Get the autotel {@link TraceContext} for the currently active span.\n *\n * This is the ambient accessor for the functional API: instead of threading a\n * `ctx` parameter through a factory, call this inside any traced function (or a\n * helper it calls) to reach `setAttribute`, `setUser`, `getBaggage`, and the\n * rest of the context surface. Returns `undefined` when no span is active.\n *\n * @example\n * ```typescript\n * const getUser = trace('getUser', async (id: string) => {\n * getActiveTraceContext()?.setAttribute('user.id', id);\n * return db.users.find(id);\n * });\n * ```\n *\n * @see getActiveSpan for the raw OpenTelemetry span\n * @see getRequestLogger which reads the active context when called with no args\n */\nexport function getActiveTraceContext<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> | undefined {\n return getCtxValue<TBaggage>() ?? undefined;\n}\n\n/**\n * Context object that lazily evaluates the active span on property access\n *\n * Access trace context directly without function call syntax.\n *\n * @example\n * ```typescript\n * import { trace, ctx } from 'autotel'\n *\n * export const createUser = trace(async (data) => {\n * // Direct property access - no function call!\n * if (ctx.traceId) {\n * ctx.setAttribute('user.id', data.id)\n * console.log('Trace:', ctx.traceId)\n * }\n * })\n * ```\n */\nexport const ctx = new Proxy({} as TraceContext, {\n get(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return ctxValue[prop as keyof typeof ctxValue];\n },\n\n has(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return false;\n }\n return prop in ctxValue;\n },\n\n ownKeys() {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return [];\n }\n return Object.keys(ctxValue);\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return Object.getOwnPropertyDescriptor(ctxValue, prop);\n },\n});\n\n/**\n * Build the root-operation flush policy once and reuse it for wrapped and\n * immediate execution. Async operations await this function; sync operations\n * trigger it without blocking.\n */\nfunction createRootTelemetryFlusher(\n options: Pick<TracingOptions, 'flushOnRootSpanEnd'>,\n isRootSpan: boolean,\n): () => Promise<void> {\n const initConfig = getInitConfig();\n const shouldFlush =\n options.flushOnRootSpanEnd ?? initConfig?.flushOnRootSpanEnd ?? true;\n const shouldFlushSpans = initConfig?.forceFlushOnShutdown ?? false;\n\n return async () => {\n if (!shouldFlush || !isRootSpan) return;\n\n try {\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n await queue.flush();\n }\n\n if (shouldFlushSpans) {\n const tracerProvider = getForceFlushableProvider(getSdk());\n await tracerProvider?.forceFlush();\n }\n } catch (error) {\n const logger = getInitConfig()?.logger;\n logger?.error?.(\n { err: error instanceof Error ? error : undefined },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n };\n}\n\n/**\n * Give every root operation its own baggage context without replacing a\n * caller's existing scope. AsyncLocalStorage keeps the scope alive until an\n * async result settles and restores the previous store afterwards.\n */\nfunction runWithTraceContextStorage<TResult>(fn: () => TResult): TResult {\n const storage = getContextStorage();\n if (storage.getStore()) return fn();\n return storage.run({ value: context.active() }, fn);\n}\n\n/**\n * Core tracing wrapper for sync functions (internal implementation)\n */\nfunction wrapWithTracingSync<TArgs extends unknown[], TReturn>(\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n // Idempotency check: if already instrumented, return as-is\n if (hasInstrumentationFlag(fnFactory)) {\n // If already instrumented, we need to extract the original factory\n // For now, we'll just proceed - this edge case is handled by the wrapped function check\n }\n\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n // Annotate as Sampler so the optional hooks stay visible. Inference would\n // narrow to AlwaysSampler and hide them behind `in` checks.\n const sampler: Sampler = options.sampler || new AlwaysSampler();\n\n const spanName = getSpanName(\n options,\n fnFactory as unknown as InstrumentableFunction<TArgs, TReturn>,\n variableName,\n );\n\n // Metrics setup (if enabled)\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n // Return wrapped function\n function wrappedFunction(\n this: unknown,\n ...args: TArgs\n ): TReturn | Promise<TReturn> {\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args,\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n // Read the rate next to the decision that produced it: a windowed sampler\n // can move on to a new rate before the span closes.\n const sampleRate = sampler.sampleRate?.(samplingContext);\n const needsTailSampling = sampler.needsTailSampling?.() ?? false;\n\n // If not sampling and no tail sampling, execute without tracing\n if (!shouldSample && !needsTailSampling) {\n const fn = fnFactory(createDummyCtx());\n return fn.call(this, ...args);\n }\n\n const startTime = performance.now();\n\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const flushRootTelemetry = createRootTelemetryFlusher(options, isRootSpan);\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n (span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(spanName, () =>\n runWithTraceContextStorage(() => {\n let shouldKeepSpan = true;\n\n // Store span name for trace context helpers\n setSpanName(span, spanName);\n\n // Only worth recording when the sampler actually dropped events.\n if (sampleRate !== undefined && sampleRate > 1) {\n span.setAttribute(AUTOTEL_SAMPLING_RATE, sampleRate);\n }\n\n // Create trace context for this span using shared utility\n const ctxValue = createTraceContext(span);\n\n // Get the actual function from the factory\n const fn = fnFactory(ctxValue);\n\n // Extract attributes only when actually tracing\n // This avoids expensive preprocessing when sampling rejects the trace\n const argsAttributes: Attributes = {\n ...captureInputAttrs(args, options.captureInput),\n ...(options.attributesFromArgs\n ? options.attributesFromArgs(args)\n : {}),\n } as Attributes;\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: Error,\n ) => {\n if (needsTailSampling && sampler.shouldKeepTrace) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n const onSuccess = (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n const resultAttributes = {\n ...captureOutputAttrs(result, options.captureOutput),\n ...(options.attributesFromResult\n ? options.attributesFromResult(result)\n : {}),\n };\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n ...argsAttributes,\n ...resultAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n return result;\n };\n\n const onError = (error: unknown): never => {\n finalizeThrownSpan(error, options.isError, {\n span,\n spanName,\n duration: performance.now() - startTime,\n callCounter,\n durationHistogram,\n handleTailSampling,\n extraAttributes: argsAttributes,\n });\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n const result = context.with(getActiveContextWithBaggage(), () =>\n fn.call(this, ...args),\n );\n\n if (result instanceof Promise) {\n return result.then(\n async (value) => {\n const completed = onSuccess(value);\n await flushRootTelemetry();\n return completed;\n },\n async (error) => {\n try {\n return onError(error);\n } finally {\n await flushRootTelemetry();\n }\n },\n );\n }\n\n const completed = onSuccess(result);\n void flushRootTelemetry();\n return completed;\n } catch (error) {\n try {\n return onError(error);\n } finally {\n void flushRootTelemetry();\n }\n }\n }),\n );\n },\n );\n }\n\n // Mark as instrumented to prevent double-wrapping\n (wrappedFunction as InstrumentedFlag)[INSTRUMENTED_SYMBOL] = true;\n\n Object.defineProperty(wrappedFunction, 'name', {\n value: variableName || 'trace',\n configurable: true,\n });\n\n return wrappedFunction as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Approach 1: trace() - Zero-ceremony HOF\n *\n * Wrap a plain function with automatic tracing. The function receives its real\n * arguments; no context parameter is injected. Use\n * {@link getActiveTraceContext} inside the function, or use {@link withTracing}\n * for the explicit `(ctx) => (...args) => result` factory form.\n *\n * @example Auto-inferred name - Plain function\n * ```typescript\n * export const createUser = trace(async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"createUser\"\n * ```\n *\n * @example Ambient context access\n * ```typescript\n * export const createUser = trace(async (data) => {\n * getActiveTraceContext()?.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Custom name - Plain function\n * ```typescript\n * export const createUser = trace('user.create', async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"user.create\"\n * ```\n *\n * @example Explicit factory context with withTracing()\n * ```typescript\n * export const createUser = withTracing({ name: 'user.create' })((ctx) => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Full options - Plain function\n * ```typescript\n * export const createUser = trace({\n * name: 'user.create',\n * sampler: new AdaptiveSampler(),\n * withMetrics: true\n * }, async (data) => {\n * return await db.users.create(data)\n * })\n * ```\n *\n */\n// Plain-function overloads. `trace()` always wraps a plain function that\n// receives its real arguments; it never injects a context parameter and never\n// inspects the function. Reach the active span via getActiveTraceContext()\n// inside the body. For the explicit `(ctx) => (args) => result` factory form,\n// use withTracing(). `TReturn` captures the return type verbatim, so async\n// functions infer `(...args) => Promise<...>` with no separate overload.\n\n// trace(fn)\nexport function trace<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// trace(name, fn)\nexport function trace<TArgs extends unknown[], TReturn>(\n name: string,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// trace(options, fn)\nexport function trace<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Implementation\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fnOrNameOrOptions:\n | ((...args: TArgs) => TReturn)\n | ((...args: TArgs) => Promise<TReturn>)\n | string\n | TracingOptions<TArgs, TReturn>,\n maybeFn?:\n ((...args: TArgs) => TReturn) | ((...args: TArgs) => Promise<TReturn>),\n): WrappedFunction<TArgs, TReturn> {\n // trace(fn) - the function is plain; it receives its real arguments and no\n // context is injected. Reach the active span via getActiveTraceContext().\n if (typeof fnOrNameOrOptions === 'function') {\n return wrapPlainWithTracing(\n fnOrNameOrOptions as (...args: TArgs) => TReturn,\n {} as TracingOptions<TArgs, TReturn>,\n );\n }\n\n // trace(name, fn) or trace(options, fn)\n if (!maybeFn) {\n throw new Error('trace(name|options, fn): fn is required');\n }\n\n const options: TracingOptions<TArgs, TReturn> =\n typeof fnOrNameOrOptions === 'string'\n ? ({ name: fnOrNameOrOptions } as TracingOptions<TArgs, TReturn>)\n : fnOrNameOrOptions;\n\n return wrapPlainWithTracing(maybeFn as (...args: TArgs) => TReturn, options);\n}\n\n/**\n * Approach 2: withTracing() - Middleware-style composable wrapper\n *\n * Returns a HOF that wraps functions with tracing.\n * Perfect for composition and reusable configuration.\n *\n * @example Standard usage\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Composable\n * ```typescript\n * const tracer = withTracing({ serviceName: 'user' })\n *\n * export const createUser = tracer(ctx => async (data) => { })\n * export const updateUser = tracer(ctx => async (id, data) => { })\n * ```\n *\n * @example With other middleware\n * ```typescript\n * export const createUser = compose(\n * withAuth({ role: 'admin' }),\n * withTracing({ name: 'user.create' }),\n * withRateLimit({ max: 100 })\n * )(ctx => async (data) => { })\n * ```\n */\nexport function withTracing<\n TCfgArgs extends unknown[] = unknown[],\n TCfgReturn = unknown,\n>(options: TracingOptions<TCfgArgs, TCfgReturn> = {}) {\n return <TArgs extends TCfgArgs, TReturn extends TCfgReturn>(\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n ): WrappedFunction<TArgs, TReturn> =>\n wrapFactoryWithTracing<TArgs, TReturn>(fnFactory, options);\n}\n\n/**\n * Approach 3: instrument() - Batch auto-instrumentation\n *\n * Instrument an entire module/object at once.\n * Closest to @Instrumented decorator pattern.\n *\n * @example Basic usage\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * sampler: new AdaptiveSampler()\n * })\n * // → Traced as \"user.createUser\", \"user.updateUser\", \"user.deleteUser\"\n * ```\n *\n * @example Per-function overrides\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * overrides: {\n * deleteUser: {\n * sampler: new AlwaysSampler(),\n * withMetrics: true\n * }\n * }\n * })\n * ```\n *\n * @example Skip functions\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * _internal: async () => { }, // Auto-skipped (_-prefix)\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * skip: [/^test/, (key) => key.includes('debug')]\n * })\n * ```\n */\nexport function instrument<TFunction extends AnyInstrumentable>(\n options: SingleInstrumentOptions<TFunction>,\n): TFunction;\nexport function instrument<T extends Record<string, AnyInstrumentable>>(\n options: InstrumentOptions<T>,\n): T;\nexport function instrument<\n T extends Record<string, AnyInstrumentable>,\n TFunction extends AnyInstrumentable,\n>(\n options: InstrumentOptions<T> | SingleInstrumentOptions<TFunction>,\n): T | TFunction {\n if (!options || typeof options !== 'object') {\n throw new TypeError(\n 'instrument: expected { key, fn } or { functions: { name: fn } }',\n );\n }\n\n if ('key' in options || 'fn' in options) {\n const { key, fn, ...tracingOptions } =\n options as SingleInstrumentOptions<TFunction>;\n if (typeof key !== 'string' || key.trim() === '') {\n throw new TypeError(\n 'instrument: \"key\" must be a non-empty string in the { key, fn } form',\n );\n }\n if (typeof fn !== 'function') {\n throw new TypeError(\n 'instrument: \"fn\" must be a function in the { key, fn } form',\n );\n }\n return wrapPlainWithTracing(fn, tracingOptions, key) as TFunction;\n }\n\n const { functions, ...tracingOptions } = options as InstrumentOptions<T>;\n if (!functions || typeof functions !== 'object') {\n throw new TypeError(\n 'instrument: expected { key, fn } or { functions: { name: fn } }',\n );\n }\n const instrumented: Partial<T> = {};\n\n for (const key of Object.keys(functions)) {\n const typedKey = key as keyof T;\n const fn = functions[typedKey];\n\n // Skip if not a function or undefined - just pass through the value\n if (!fn || typeof fn !== 'function') {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Only instrument own enumerable async functions\n // Check if should skip\n if (shouldSkip(key, fn, tracingOptions.skip)) {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Merge base options with per-function overrides\n const fnOptions: TracingOptions = {\n ...tracingOptions,\n ...tracingOptions.overrides?.[key],\n // If no explicit name, use key as function name\n name: tracingOptions.overrides?.[key]?.name,\n };\n\n // Bind function to original object to preserve 'this' context\n // This ensures methods can access state on the original object\n const boundFn = fn.bind(functions);\n\n // Convert plain function to factory pattern for trace()\n // For instrument(), we create a factory that ignores ctx and returns the original function\n const fnFactory = (ctx: TraceContext) => {\n void ctx;\n return boundFn;\n };\n\n // Wrap with tracing (sync or async based on implementation)\n instrumented[typedKey] = wrapFactoryWithTracing(\n fnFactory,\n fnOptions,\n key,\n ) as unknown as T[typeof typedKey];\n }\n\n return instrumented as T;\n}\n\n/**\n * Options for span() function\n */\nexport interface SpanOptions {\n /** Span name */\n name: string;\n /** Attributes to set on the span */\n attributes?: Record<string, string | number | boolean>;\n /** OpenTelemetry span kind */\n spanKind?: import('@opentelemetry/api').SpanKind;\n}\n\n/**\n * Execute a function within a named span\n *\n * Useful for adding tracing to specific code blocks without wrapping\n * the entire function. Supports both synchronous and asynchronous functions.\n *\n * Mirrors `trace()`: pass a span name as the first argument for the common\n * case, or full `SpanOptions` when you need to attach attributes.\n *\n * @example\n * ```typescript\n * // Name shorthand\n * await span('payment.charge', async (span) => {\n * await chargeCustomer(order);\n * })\n *\n * // Full options when attributes are needed\n * await span(\n * { name: 'payment.charge', attributes: { amount: order.total } },\n * async (span) => {\n * await chargeCustomer(order);\n * },\n * )\n *\n * // Sync\n * const total = span('calculateTotal', (span) => {\n * return items.reduce((sum, item) => sum + item.price, 0);\n * })\n * ```\n */\n// Overloads — sync first (more specific match), then async.\n// Each shape is offered with a string name OR a full SpanOptions object so\n// span() aligns with trace()'s argument flexibility.\nexport function span<T = unknown>(name: string, fn: (span: Span) => T): T;\nexport function span<T = unknown>(\n name: string,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => T,\n): T;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\n// Implementation\nexport function span<T = unknown>(\n nameOrOptions: string | SpanOptions,\n fn: (span: Span) => T | Promise<T>,\n): T | Promise<T> {\n const options: SpanOptions =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n const config = getConfig();\n const tracer = config.tracer;\n const { name, attributes, spanKind } = options;\n\n const executeSpan = (span: Span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(name, () => {\n try {\n // Set attributes\n if (attributes) {\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute(key, value);\n }\n }\n\n const result = fn(span);\n\n // Check if result is a Promise\n if (result instanceof Promise) {\n return result\n .then((resolved) => {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return resolved;\n })\n .catch((error) => {\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n });\n } else {\n // Synchronous function\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n }\n } catch (error) {\n // Synchronous error handling\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n }\n });\n };\n\n const parentContext = getActiveContextWithBaggage();\n const result = tracer.startActiveSpan(\n name,\n spanKind === undefined ? {} : { kind: spanKind },\n parentContext,\n executeSpan,\n );\n\n // tracer.startActiveSpan might return a Promise even for sync callbacks\n // Check if it's a Promise and handle accordingly\n if (result instanceof Promise) {\n return result;\n }\n\n return result as T;\n}\n\n/**\n * Options for withNewContext() function\n */\nexport interface WithNewContextOptions<T = unknown> {\n /** Function to execute in new root context */\n fn: () => Promise<T>;\n}\n\n/**\n * Execute a function in a new root context (prevents span propagation)\n *\n * Useful when you want to start a completely new trace without\n * parent-child relationships.\n *\n * @example\n * ```typescript\n * async function handleWebhook(payload: WebhookPayload) {\n * // This creates a new root trace, not connected to the HTTP request trace\n * await withNewContext({\n * fn: async () => {\n * await span('webhook.process', async () => {\n * await processWebhookPayload(payload)\n * })\n * }\n * })\n * }\n * ```\n */\nexport async function withNewContext<T = unknown>(\n options: WithNewContextOptions<T>,\n): Promise<T> {\n const { fn } = options;\n const config = getConfig();\n const tracer = config.tracer;\n\n // Start a new root span (breaks trace propagation)\n return tracer.startActiveSpan('root', { root: true }, async (span) => {\n try {\n const result = await fn();\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n });\n}\n\n/**\n * Options for withBaggage() function\n */\nexport interface WithBaggageOptions<T = unknown> {\n /** Baggage entries to set (key-value pairs) */\n baggage: Record<string, string>;\n /** Function to execute with the updated baggage */\n fn: () => T | Promise<T>;\n}\n\n/**\n * Execute a function with updated baggage entries\n *\n * Baggage is immutable in OpenTelemetry, so this helper creates a new context\n * with the specified baggage entries and runs the function within that context.\n * All child spans created within the function will inherit the baggage.\n *\n * @example Setting baggage for downstream services\n * ```typescript\n * import { withTracing, withBaggage } from 'autotel';\n *\n * export const createOrder = withTracing({ name: 'order.create' })((ctx) => async (order: Order) => {\n * // Set baggage that will be propagated to downstream HTTP calls\n * return await withBaggage({\n * baggage: {\n * 'tenant.id': order.tenantId,\n * 'user.id': order.userId,\n * },\n * fn: async () => {\n * // This HTTP call will include the baggage in headers\n * await fetch('/api/charge', {\n * method: 'POST',\n * body: JSON.stringify(order),\n * });\n * },\n * });\n * });\n * ```\n *\n * @example Using with existing baggage\n * ```typescript\n * export const processOrder = withTracing({ name: 'order.process' })((ctx) => async (order: Order) => {\n * // Read existing baggage\n * const tenantId = ctx.getBaggage('tenant.id');\n *\n * // Add additional baggage entries\n * return await withBaggage({\n * baggage: {\n * 'order.id': order.id,\n * 'order.amount': String(order.amount),\n * },\n * fn: async () => {\n * await charge(order);\n * },\n * });\n * });\n * ```\n */\nexport function withBaggage<T = unknown>(\n options: WithBaggageOptions<T>,\n): T | Promise<T> {\n const { baggage: baggageEntries, fn } = options;\n const currentContext = context.active();\n\n // Get existing baggage or create new\n let updatedBaggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n\n // Set all baggage entries\n for (const [key, value] of Object.entries(baggageEntries)) {\n updatedBaggage = updatedBaggage.setEntry(key, { value });\n }\n\n // Create new context with updated baggage\n const newContext = propagation.setBaggage(currentContext, updatedBaggage);\n\n // Sync contextStorage so nested traces (via getActiveContextWithBaggage) see the baggage.\n // Use run() instead of enterWith() to properly scope the context changes.\n const ctxStorage = getContextStorage();\n const previousStored = ctxStorage.getStore();\n const baggageEnrichedStored = previousStored\n ? { value: propagation.setBaggage(previousStored.value, updatedBaggage) }\n : { value: newContext };\n\n // Run the function within the new context, scoped properly\n const result = previousStored\n ? ctxStorage.run(baggageEnrichedStored, () => context.with(newContext, fn))\n : context.with(newContext, fn);\n\n if (result instanceof Promise) {\n // For async operations, ensure context is restored after the promise settles\n return result.then(\n (value) => {\n // Restore original context before resolving\n if (previousStored) {\n return ctxStorage.run(previousStored, () => value);\n }\n return value;\n },\n (error) => {\n // Restore original context before rejecting\n if (previousStored) {\n return ctxStorage.run(previousStored, () => {\n throw error;\n });\n }\n throw error;\n },\n );\n }\n\n // Sync function - context automatically restored when scope exits\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,iCAAiB,IAAI,IAAgC;AAC3D,MAAM,iBAAiB;;;;AAKvB,SAAS,oBAA4B;CACnC,MAAM,0BAA0B,MAAM;CACtC,MAAM,kBAAkB;CAGxB,MAAM,yBAAQ,IADE,MAAM,qBACN,EAAC,CAAC,SAAS;CAE3B,MAAM,kBAAkB;CACxB,OAAO;AACT;;;;;;;;;;;;AAaA,SAAS,kBAAkB,OAAyC;CAClE,MAAM,QAAQ,MAAM,MAAM,IAAI;CAC9B,IAAI,uBAAuB;CAE3B,KAAK,MAAM,QAAQ,OAAO;EAGxB,IACE,KAAK,SAAS,4BAA4B,KAC1C,KAAK,SAAS,4BAA4B,KAC1C,KAAK,SAAS,eAAe,KAC7B,KAAK,SAAS,eAAe,GAE7B;EAMF,MAAM,QACJ,KAAK,MAAM,0CAA0C,KACrD,KAAK,MAAM,yBAAyB;EAEtC,IAAI,OAAO;GACT,IAAI,WAAW,MAAM,EAAE,CAAE,KAAK;GAG9B,IAAI,SAAS,WAAW,SAAS,GAC/B,IAAI;IACF,WAAW,QAAQ,cAAc,QAAQ;GAC3C,QAAQ;IACN;GACF;GAKF,IAAI,CAAC,sBAAsB;IACzB,uBAAuB;IACvB;GACF;GAEA,OAAO;IACL,MAAM;IACN,MAAM,OAAO,SAAS,MAAM,IAAK,EAAE;IACnC,QAAQ,OAAO,SAAS,MAAM,IAAK,EAAE;GACvC;EACF;CACF;AAGF;;;;AAKA,SAAS,eACP,UACA,YACoB;CACpB,IAAI;EAEF,IAAI,OAAO,OAAO,iBAAiB,YACjC;EAOF,OAJgB,OAAO,aAAa,UAAU,MAC1B,CAAC,CAAC,MAAM,IAGjB,CAAC,CAAC,aAAa;CAC5B,QAAQ;EAEN;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AiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAC1D;GACA,KAAK,UAAU,EAAE,MAAM,eAAe,MAAM,CAAC;GAC7C,MAAM;EACR,UAAU;GACR,KAAK,IAAI;EACX;CACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,YACd,SACgB;CAChB,MAAM,EAAE,SAAS,gBAAgB,OAAO;CACxC,MAAM,iBAAiB,QAAQ,OAAO;CAGtC,IAAI,iBACF,YAAY,WAAW,cAAc,KAAK,YAAY,cAAc;CAGtE,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACtD,iBAAiB,eAAe,SAAS,KAAK,EAAE,MAAM,CAAC;CAIzD,MAAM,aAAa,YAAY,WAAW,gBAAgB,cAAc;CAIxE,MAAM,aAAa,kBAAkB;CACrC,MAAM,iBAAiB,WAAW,SAAS;CAC3C,MAAM,wBAAwB,iBAC1B,EAAE,OAAO,YAAY,WAAW,eAAe,OAAO,cAAc,EAAE,IACtE,EAAE,OAAO,WAAW;CAGxB,MAAM,SAAS,iBACX,WAAW,IAAI,6BAA6B,QAAQ,KAAK,YAAY,EAAE,CAAC,IACxE,QAAQ,KAAK,YAAY,EAAE;CAE/B,IAAI,kBAAkB,SAEpB,OAAO,OAAO,MACX,UAAU;EAET,IAAI,gBACF,OAAO,WAAW,IAAI,sBAAsB,KAAK;EAEnD,OAAO;CACT,IACC,UAAU;EAET,IAAI,gBACF,OAAO,WAAW,IAAI,sBAAsB;GAC1C,MAAM;EACR,CAAC;EAEH,MAAM;CACR,CACF;CAIF,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"functional-DcLBuCPz.cjs","names":["nodeUrl","nodeFs","SpanStatusCode","getInitConfig","otelTrace","createTraceContext","getEventQueue","getForceFlushableProvider","getSdk","getContextStorage","context","getConfig","AlwaysSampler","getActiveContextWithBaggage","runInOperationContext","AUTOTEL_SAMPLING_RATE","AUTOTEL_SAMPLING_TAIL_KEEP","AUTOTEL_SAMPLING_TAIL_EVALUATED","propagation"],"sources":["../src/variable-name-inference.ts","../src/functional.ts"],"sourcesContent":["/**\n * Variable Name Inference Utility\n *\n * Attempts to infer variable names from const/export const assignments\n * by analyzing the call stack and parsing source code.\n *\n * This is a best-effort approach with graceful degradation - if inference\n * fails for any reason, it returns undefined without breaking the application.\n */\n\n// namespace imports for browser-bundler compat — see node-require.ts\nimport * as nodeFs from 'node:fs';\nimport * as nodeUrl from 'node:url';\n\ninterface CallLocation {\n file: string;\n line: number;\n column: number;\n}\n\n/**\n * LRU Cache for inferred variable names\n * Key: \"file:line\" (e.g., \"/path/to/file.ts:42\")\n * Value: inferred variable name or undefined\n */\nconst inferenceCache = new Map<string, string | undefined>();\nconst MAX_CACHE_SIZE = 50;\n\n/**\n * Captures the current call stack\n */\nfunction captureStackTrace(): string {\n const originalStackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 10; // Only need first few frames\n\n const err = new Error('Stack trace capture');\n const stack = err.stack || '';\n\n Error.stackTraceLimit = originalStackTraceLimit;\n return stack;\n}\n\n/**\n * Parses the stack trace to find where trace() was called\n *\n * Stack trace format (Node.js):\n * at functionName (file:line:column)\n * at file:line:column\n *\n * We skip frames until we find one that's NOT in functional.ts or this file.\n * We also need to skip one additional frame (the trace/span/instrument function itself)\n * to get to the actual user code.\n */\nfunction parseCallLocation(stack: string): CallLocation | undefined {\n const lines = stack.split('\\n');\n let skippedExternalFrame = false;\n\n for (const line of lines) {\n // Skip if line contains this file or functional.ts (internal frames)\n // Be specific about the filename to avoid matching test files\n if (\n line.includes('variable-name-inference.ts') ||\n line.includes('variable-name-inference.js') ||\n line.includes('functional.ts') ||\n line.includes('functional.js')\n ) {\n continue;\n }\n\n // Match various stack trace formats\n // Format 1: at functionName (file:line:column)\n // Format 2: at file:line:column\n const match =\n line.match(/at\\s+(?:.*\\s+)?\\(?([^:]+):(\\d+):(\\d+)\\)?/) ||\n line.match(/^.*?([^:]+):(\\d+):(\\d+)/);\n\n if (match) {\n let filePath = match[1]!.trim();\n\n // Handle file:// URLs (convert to paths)\n if (filePath.startsWith('file://')) {\n try {\n filePath = nodeUrl.fileURLToPath(filePath);\n } catch {\n continue;\n }\n }\n\n // Skip the first external frame (the trace/span function itself)\n // We want the frame where the user CALLS trace(), not inside trace()\n if (!skippedExternalFrame) {\n skippedExternalFrame = true;\n continue;\n }\n\n return {\n file: filePath,\n line: Number.parseInt(match[2]!, 10),\n column: Number.parseInt(match[3]!, 10),\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Reads a specific line from a source file\n */\nfunction readSourceLine(\n filePath: string,\n lineNumber: number,\n): string | undefined {\n try {\n // Check if we can access the file system (not available in edge runtimes)\n if (typeof nodeFs.readFileSync !== 'function') {\n return undefined;\n }\n\n const content = nodeFs.readFileSync(filePath, 'utf8');\n const lines = content.split('\\n');\n\n // Line numbers are 1-based\n return lines[lineNumber - 1];\n } catch {\n // File doesn't exist, permission denied, or other error\n return undefined;\n }\n}\n\n/**\n * Extracts variable name from source code line using regex patterns\n *\n * Supported patterns:\n * - const varName = anyFunction(\n * - export const varName = anyFunction(\n * - let varName = anyFunction(\n * - var varName = anyFunction(\n *\n * Note: This won't work with destructuring assignments or complex patterns\n */\nfunction extractVariableName(sourceLine: string): string | undefined {\n // Remove leading/trailing whitespace\n const trimmed = sourceLine.trim();\n\n // Pattern: (export)? (const|let|var) varName = anyFunctionCall(\n // We match any function call, not just trace(), to support wrapper functions\n const patterns = [\n // export const varName = anyFunction(\n /export\\s+const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // const varName = anyFunction(\n /const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export let varName = anyFunction(\n /export\\s+let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // let varName = anyFunction(\n /let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export var varName = anyFunction(\n /export\\s+var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // var varName = anyFunction(\n /var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n ];\n\n for (const pattern of patterns) {\n const match = trimmed.match(pattern);\n if (match && match[1]) {\n return match[1];\n }\n }\n\n return undefined;\n}\n\n/**\n * Adds an entry to the cache with LRU eviction\n */\nfunction cacheInference(key: string, value: string | undefined): void {\n // If cache is full, remove oldest entry (first entry in Map)\n if (inferenceCache.size >= MAX_CACHE_SIZE) {\n const firstKey = inferenceCache.keys().next().value;\n if (firstKey) {\n inferenceCache.delete(firstKey);\n }\n }\n\n inferenceCache.set(key, value);\n}\n\n/**\n * Main entry point: Attempts to infer the variable name from the call stack\n *\n * This function:\n * 1. Captures the call stack\n * 2. Parses it to find where trace() was called (file + line)\n * 3. Reads that line from the source file\n * 4. Extracts the variable name using regex\n *\n * Returns undefined if inference fails at any step (graceful degradation).\n * Results are cached to avoid repeated file I/O.\n *\n * @returns The inferred variable name, or undefined if inference failed\n */\nexport function inferVariableNameFromCallStack(): string | undefined {\n try {\n // Capture stack trace\n const stack = captureStackTrace();\n\n // Parse stack to find trace() call location\n const callLocation = parseCallLocation(stack);\n if (!callLocation) {\n return undefined;\n }\n\n // Check cache\n const cacheKey = `${callLocation.file}:${callLocation.line}`;\n if (inferenceCache.has(cacheKey)) {\n return inferenceCache.get(cacheKey);\n }\n\n // Read source line\n const sourceLine = readSourceLine(callLocation.file, callLocation.line);\n if (!sourceLine) {\n return undefined;\n }\n\n // Extract variable name\n const variableName = extractVariableName(sourceLine);\n\n // Cache result (even if undefined, to avoid repeated failed attempts)\n cacheInference(cacheKey, variableName);\n\n return variableName;\n } catch {\n // Graceful degradation - don't break the app if inference fails\n return undefined;\n }\n}\n\n/**\n * Clears the inference cache (useful for testing)\n */\nexport function clearInferenceCache(): void {\n inferenceCache.clear();\n}\n","/**\n * Functional API for non-class code\n *\n * Three approaches for different use cases:\n * 1. trace() - Zero-ceremony HOF for single functions\n * 2. withTracing() - Middleware-style composable wrapper\n * 3. instrument() - Batch auto-instrumentation for modules\n *\n * @example trace() - Single function\n * ```typescript\n * export const createUser = trace(async (data) => {\n * getActiveTraceContext()?.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example withTracing() - Composable middleware\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example instrument() - Batch instrumentation\n * ```typescript\n * export default instrument({\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { }\n * }, { serviceName: 'user' })\n * ```\n */\n\nimport {\n SpanStatusCode,\n trace as otelTrace,\n context,\n propagation,\n type Span,\n type Counter,\n type Histogram,\n type Attributes,\n} from '@opentelemetry/api';\nimport { getConfig } from './config';\nimport { getConfig as getInitConfig, getSdk } from './init';\nimport { getForceFlushableProvider } from './tracer-provider';\nimport {\n type Sampler,\n type SamplingContext,\n AlwaysSampler,\n AUTOTEL_SAMPLING_TAIL_KEEP,\n AUTOTEL_SAMPLING_TAIL_EVALUATED,\n AUTOTEL_SAMPLING_RATE,\n} from './sampling';\nimport { getEventQueue } from './track';\nimport type { TraceContext } from './trace-context';\nimport {\n createTraceContext,\n getActiveContextWithBaggage,\n getContextStorage,\n} from './trace-context';\nimport { setSpanName } from './trace-helpers';\nimport { runInOperationContext } from './operation-context';\nimport { inferVariableNameFromCallStack } from './variable-name-inference';\n\n/**\n * Complete trace context containing trace identifiers and span methods\n *\n * The ctx parameter in trace() functions provides:\n * - traceId, spanId, correlationId from the active span\n * - Span manipulation methods (setAttribute, setAttributes, setStatus, recordException)\n *\n * For custom context, access it directly in your functions (standard OpenTelemetry pattern).\n *\n * @example\n * ```typescript\n * import { trace } from 'autotel'\n *\n * export const createUser = withTracing({})((ctx) => async (data: CreateUserData) => {\n * // Get custom context directly (standard OTel approach)\n * const userId = getCurrentUserId()\n * const tenantId = getCurrentTenant()\n *\n * // Use ctx for span operations and trace IDs\n * ctx.setAttribute('user.id', data.id)\n * ctx.setAttribute('user.tenant', tenantId)\n * console.log(ctx.traceId) // Trace IDs available\n * })\n * ```\n */\nexport type { TraceContext } from './trace-context';\n\nlet unknownSpanNameWarningEmitted = false;\n\ntype WrappedFunction<TArgs extends unknown[], TReturn> = (\n ...args: TArgs\n) => TReturn | Promise<TReturn>;\n\nfunction resolveVariableName(\n named: InstrumentableFunction,\n variableName?: string,\n): string | undefined {\n const suppliedFunctionName = inferFunctionName(named);\n const callStackVariableName = suppliedFunctionName\n ? undefined\n : inferVariableNameFromCallStack();\n return variableName || suppliedFunctionName || callStackVariableName;\n}\n\n/**\n * Wrap an explicit context factory `(ctx) => (...args) => result`.\n * Used by {@link withTracing}; the input is a factory by contract, so there is\n * no plain-vs-factory detection. The factory is never invoked at construction\n * time — only when the wrapper is called.\n */\nfunction wrapFactoryWithTracing<TArgs extends unknown[], TReturn>(\n factory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n const effectiveVariableName = resolveVariableName(\n factory as InstrumentableFunction,\n variableName,\n );\n return wrapWithTracingSync(\n factory,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Wrap a plain function `(...args) => result`. Used by {@link trace} and\n * {@link instrument}: the function receives its real arguments and no context\n * is injected. Reach the active span via {@link getActiveTraceContext} inside\n * the body (or any helper it calls).\n */\nfunction wrapPlainWithTracing<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n const effectiveVariableName = resolveVariableName(\n fn as InstrumentableFunction,\n variableName,\n );\n const factory = (_ctx: TraceContext) => fn;\n return wrapWithTracingSync(\n factory,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Common options for functional tracing\n */\nexport interface TracingOptions<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> {\n /**\n * Span name (highest priority)\n * If provided, this is used as the span name\n */\n name?: string;\n\n /**\n * Service name (used to compose final span name)\n * If name not provided, span name becomes: ${serviceName}.${functionName}\n */\n serviceName?: string;\n\n /**\n * Sampling strategy\n * @default AlwaysSampler\n */\n sampler?: Sampler;\n\n /**\n * Enable metrics collection (counter, histogram)\n * @default false\n */\n withMetrics?: boolean;\n\n /**\n * Extract attributes from function arguments\n */\n attributesFromArgs?: (args: TArgs) => Record<string, unknown>;\n\n /**\n * Extract attributes from function result\n */\n attributesFromResult?: (result: TReturn) => Record<string, unknown>;\n\n /**\n * Capture the function arguments onto the span as `autotel.input`\n * (JSON, truncated). One arg is captured directly; multiple are captured as\n * an array. Off by default — opt in per call. Tools (visualizers, devtools)\n * read this alongside `ai.toolCall.args` to show function I/O uniformly.\n * Avoid on args with secrets/PII, or pair with a redacting processor.\n */\n captureInput?: boolean;\n\n /**\n * Capture the function return value onto the span as `autotel.output`\n * (JSON, truncated). Off by default. Same caveats as {@link captureInput}.\n */\n captureOutput?: boolean;\n\n /**\n * Start a new root span instead of creating a child\n * Useful for serverless entry points\n * @default false\n */\n startNewRoot?: boolean;\n\n /**\n * Flush events queue when span ends\n * Only flushes on root spans (to avoid excessive flushing)\n * @default true\n */\n flushOnRootSpanEnd?: boolean;\n\n /**\n * Span kind for semantic convention compliance\n * Used for messaging (PRODUCER/CONSUMER), HTTP (CLIENT/SERVER), etc.\n * @default SpanKind.INTERNAL\n */\n spanKind?: import('@opentelemetry/api').SpanKind;\n\n /**\n * Classify a thrown value as a real error. Return `false` to treat the throw\n * as expected control flow: the span is marked OK, no exception is recorded,\n * and the value is rethrown untouched. Use this for framework control-flow\n * signals that propagate via `throw` but are not failures — e.g. TanStack\n * Router / Next.js `redirect()` and `notFound()`.\n * @default every throw is treated as an error\n */\n isError?: (error: unknown) => boolean;\n}\n\n/**\n * Options for instrument() batch instrumentation\n */\nexport interface InstrumentOptions<\n T extends Record<string, AnyInstrumentable> = Record<\n string,\n AnyInstrumentable\n >,\n> extends TracingOptions {\n /** Object whose function properties should be instrumented */\n functions: T;\n /**\n * Per-function configuration overrides\n */\n overrides?: Record<string, Partial<TracingOptions>>;\n\n /**\n * Functions to skip (won't be instrumented)\n * Supports:\n * - String keys: 'functionName'\n * - RegExp: /^_internal/\n * - Predicate: (key, fn) => boolean\n *\n * By default, functions starting with _ are skipped\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[];\n}\n\n/**\n * Options for instrumenting one function with an explicit stable key.\n */\nexport interface SingleInstrumentOptions<\n TFunction extends AnyInstrumentable = AnyInstrumentable,\n> extends TracingOptions {\n /** Stable function key used for span naming */\n key: string;\n /** Function to instrument */\n fn: TFunction;\n}\n\n// Maximum error message length to prevent span bloat\nconst MAX_ERROR_MESSAGE_LENGTH = 500;\n\nfunction createDummyCtx<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> {\n // `recordException` / `addEvent` are no-op shims kept for the same\n // compatibility window as `createTraceContext` (see trace-context.ts).\n return {\n traceId: '',\n spanId: '',\n correlationId: '',\n setAttribute: () => {},\n setAttributes: () => {},\n setStatus: () => {},\n recordException: () => {},\n addEvent: () => {},\n addLink: () => {},\n addLinks: () => {},\n updateName: () => {},\n isRecording: () => false,\n getBaggage: () => {},\n setBaggage: () => '',\n deleteBaggage: () => {},\n getAllBaggage: () => new Map(),\n } as unknown as TraceContext<TBaggage>;\n}\n\n/** Attribute keys for opt-in function I/O capture (see TracingOptions). */\nconst AUTOTEL_INPUT_ATTR = 'autotel.input';\nconst AUTOTEL_OUTPUT_ATTR = 'autotel.output';\nconst CAPTURE_MAX_CHARS = 4096;\n\n/** JSON-serialize a captured value, defensively (truncate, swallow cycles). */\nfunction serializeCapture(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n try {\n const json = typeof value === 'string' ? value : JSON.stringify(value);\n if (json === undefined) return undefined;\n return json.length > CAPTURE_MAX_CHARS\n ? `${json.slice(0, CAPTURE_MAX_CHARS)}…[truncated]`\n : json;\n } catch {\n return undefined;\n }\n}\n\n/** `autotel.input` from args (single arg captured directly, else the array). */\nfunction captureInputAttrs(\n args: unknown[],\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(args.length === 1 ? args[0] : args);\n return s === undefined ? {} : { [AUTOTEL_INPUT_ATTR]: s };\n}\n\n/** `autotel.output` from the return value. */\nfunction captureOutputAttrs(\n result: unknown,\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(result);\n return s === undefined ? {} : { [AUTOTEL_OUTPUT_ATTR]: s };\n}\n\n// Symbol to prevent double-instrumentation (idempotency flag)\nconst INSTRUMENTED_SYMBOL = Symbol.for('autotel.functional.instrumented');\n\ntype InstrumentedFlag = {\n [INSTRUMENTED_SYMBOL]?: true;\n};\n\nfunction hasInstrumentationFlag(value: unknown): value is InstrumentedFlag {\n return (\n (typeof value === 'function' || typeof value === 'object') &&\n value !== null &&\n Boolean((value as InstrumentedFlag)[INSTRUMENTED_SYMBOL])\n );\n}\n\n/**\n * Truncate error message to prevent span bloat\n */\nfunction truncateErrorMessage(message: string): string {\n if (message.length <= MAX_ERROR_MESSAGE_LENGTH) {\n return message;\n }\n return `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}... (truncated)`;\n}\n\n/** Per-invocation state the terminal span handlers close over. */\ninterface SpanFinalizeContext {\n span: Span;\n spanName: string;\n duration: number;\n callCounter?: Counter;\n durationHistogram?: Histogram;\n handleTailSampling: (\n success: boolean,\n duration: number,\n error?: Error,\n ) => void;\n /** Extra attributes to merge (e.g. captured args); absent on immediate-exec paths. */\n extraAttributes?: Attributes;\n}\n\n/**\n * Terminal handling for a value thrown by a traced function. Shared by all four\n * `trace()` execution paths (immediate + wrapper, sync + async) so the outcome\n * rules live in exactly one place. Ends the span; the caller flushes (await/void)\n * and rethrows.\n *\n * If `isError` classifies the throw as expected control flow — e.g. a framework\n * `redirect()` / `notFound()` signal — it is recorded as a success outcome with\n * an OK status and no exception. Otherwise it is recorded as an error.\n */\nfunction finalizeThrownSpan(\n error: unknown,\n isError: ((error: unknown) => boolean) | undefined,\n ctx: SpanFinalizeContext,\n): void {\n const {\n span,\n spanName,\n duration,\n callCounter,\n durationHistogram,\n handleTailSampling,\n extraAttributes,\n } = ctx;\n\n const baseAttributes: Attributes = {\n ...extraAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n };\n\n if (isError && !isError(error)) {\n callCounter?.add(1, { operation: spanName, status: 'success' });\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({ ...baseAttributes, 'operation.success': true });\n handleTailSampling(true, duration);\n span.end();\n return;\n }\n\n callCounter?.add(1, { operation: spanName, status: 'error' });\n durationHistogram?.record(duration, { operation: spanName, status: 'error' });\n\n const truncatedMessage = truncateErrorMessage(\n error instanceof Error ? error.message : 'Unknown error',\n );\n\n span.setStatus({ code: SpanStatusCode.ERROR, message: truncatedMessage });\n span.setAttributes({\n ...baseAttributes,\n 'operation.success': false,\n error: true,\n 'exception.type': error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n const thrown = error instanceof Error ? error : new Error(String(error));\n span.recordException(thrown);\n // Samplers read result.error, so hand them a real Error rather than\n // whatever the code threw.\n handleTailSampling(false, duration, thrown);\n span.end();\n}\n\ntype InstrumentableFunction<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> = ((...args: TArgs) => TReturn | Promise<TReturn>) & {\n displayName?: string;\n name?: string;\n};\n\n/**\n * Constraint alias for `instrument()` and friends. `never[]` parameters make\n * every concretely-typed function (e.g. `(name: string) => Promise<User>`)\n * satisfy the constraint under `strictFunctionTypes` without resorting to\n * `any`. Use ONLY in constraint positions — the concrete `T` is still\n * inferred from the actual argument, so call-site argument and return types\n * are fully preserved.\n */\ntype AnyInstrumentable = ((...args: never[]) => unknown) & {\n displayName?: string;\n name?: string;\n};\n\n/**\n * Try to infer function name from function properties\n * Checks for displayName, name, or other metadata that might be set\n */\nfunction inferFunctionName<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(fn: InstrumentableFunction<TArgs, TReturn>): string | undefined {\n // Check for displayName property (sometimes set by bundlers)\n const displayName = (fn as { displayName?: string }).displayName;\n if (displayName) {\n return displayName;\n }\n\n // Check function.name (works for named functions and modern arrow function assignment)\n // Note: Empty string is falsy, so this handles both undefined and ''\n if (fn.name && fn.name !== 'anonymous' && fn.name !== '') {\n return fn.name;\n }\n\n // Try to extract name from function source (for function declarations)\n const source = Function.prototype.toString.call(fn);\n const match = source.match(/function\\s+([^(\\s]+)/);\n if (match && match[1] && match[1] !== 'anonymous') {\n return match[1];\n }\n\n return undefined;\n}\n\n/**\n * Determine span name using priority:\n * 1. Explicit name option\n * 2. serviceName + functionName\n * 3. Inferred from function/variable name (including stack trace fallback)\n * 4. Fallback to 'unknown'\n */\nfunction getSpanName<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fn: InstrumentableFunction<TArgs, TReturn>,\n variableName?: string,\n): string {\n // 1. Explicit name\n if (options.name) {\n return options.name;\n }\n\n // 2. Try variable name, function name, or function properties\n let fnName = variableName || inferFunctionName(fn);\n\n // Default to 'anonymous' if still no name\n fnName = fnName || 'anonymous';\n\n // 2. serviceName + functionName\n if (options.serviceName) {\n return `${options.serviceName}.${fnName}`;\n }\n\n // 3. Inferred from function name\n if (fnName && fnName !== 'anonymous') {\n return fnName;\n }\n\n // 4. Fallback\n const initConfig = getInitConfig();\n if (\n typeof process !== 'undefined' &&\n process.env.NODE_ENV !== 'production' &&\n !unknownSpanNameWarningEmitted &&\n initConfig?.logger?.warn\n ) {\n unknownSpanNameWarningEmitted = true;\n initConfig.logger.warn(\n {},\n '[autotel] Span name resolved to \"unknown\". Pass an explicit name, for example trace(\"operation.name\", fn).',\n );\n }\n return 'unknown';\n}\n\n/**\n * Check if function should be skipped\n */\nfunction shouldSkip(\n key: string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n fn: Function,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[],\n): boolean {\n // Default: skip functions starting with _\n if (key.startsWith('_')) {\n return true;\n }\n\n if (!skip || skip.length === 0) {\n return false;\n }\n\n for (const rule of skip) {\n if (typeof rule === 'string' && key === rule) {\n return true;\n } else if (rule instanceof RegExp && rule.test(key)) {\n return true;\n } else if (typeof rule === 'function' && rule(key, fn)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Get current trace context value (internal helper)\n *\n * Returns base context (trace IDs) + span methods from the active span.\n */\nfunction getCtxValue<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> | null {\n const activeSpan = otelTrace.getActiveSpan();\n if (!activeSpan) return null;\n\n // Use shared utility to create trace context\n return createTraceContext<TBaggage>(activeSpan);\n}\n\n/**\n * Get the autotel {@link TraceContext} for the currently active span.\n *\n * This is the ambient accessor for the functional API: instead of threading a\n * `ctx` parameter through a factory, call this inside any traced function (or a\n * helper it calls) to reach `setAttribute`, `setUser`, `getBaggage`, and the\n * rest of the context surface. Returns `undefined` when no span is active.\n *\n * @example\n * ```typescript\n * const getUser = trace('getUser', async (id: string) => {\n * getActiveTraceContext()?.setAttribute('user.id', id);\n * return db.users.find(id);\n * });\n * ```\n *\n * @see getActiveSpan for the raw OpenTelemetry span\n * @see getRequestLogger which reads the active context when called with no args\n */\nexport function getActiveTraceContext<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> | undefined {\n return getCtxValue<TBaggage>() ?? undefined;\n}\n\n/**\n * Context object that lazily evaluates the active span on property access\n *\n * Access trace context directly without function call syntax.\n *\n * @example\n * ```typescript\n * import { trace, ctx } from 'autotel'\n *\n * export const createUser = trace(async (data) => {\n * // Direct property access - no function call!\n * if (ctx.traceId) {\n * ctx.setAttribute('user.id', data.id)\n * console.log('Trace:', ctx.traceId)\n * }\n * })\n * ```\n */\nexport const ctx = new Proxy({} as TraceContext, {\n get(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return ctxValue[prop as keyof typeof ctxValue];\n },\n\n has(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return false;\n }\n return prop in ctxValue;\n },\n\n ownKeys() {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return [];\n }\n return Object.keys(ctxValue);\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return Object.getOwnPropertyDescriptor(ctxValue, prop);\n },\n});\n\n/**\n * Build the root-operation flush policy once and reuse it for wrapped and\n * immediate execution. Async operations await this function; sync operations\n * trigger it without blocking.\n */\nfunction createRootTelemetryFlusher(\n options: Pick<TracingOptions, 'flushOnRootSpanEnd'>,\n isRootSpan: boolean,\n): () => Promise<void> {\n const initConfig = getInitConfig();\n const shouldFlush =\n options.flushOnRootSpanEnd ?? initConfig?.flushOnRootSpanEnd ?? true;\n const shouldFlushSpans = initConfig?.forceFlushOnShutdown ?? false;\n\n return async () => {\n if (!shouldFlush || !isRootSpan) return;\n\n try {\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n await queue.flush();\n }\n\n if (shouldFlushSpans) {\n const tracerProvider = getForceFlushableProvider(getSdk());\n await tracerProvider?.forceFlush();\n }\n } catch (error) {\n const logger = getInitConfig()?.logger;\n logger?.error?.(\n { err: error instanceof Error ? error : undefined },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n };\n}\n\n/**\n * Give every root operation its own baggage context without replacing a\n * caller's existing scope. AsyncLocalStorage keeps the scope alive until an\n * async result settles and restores the previous store afterwards.\n */\nfunction runWithTraceContextStorage<TResult>(fn: () => TResult): TResult {\n const storage = getContextStorage();\n if (storage.getStore()) return fn();\n return storage.run({ value: context.active() }, fn);\n}\n\n/**\n * Core tracing wrapper for sync functions (internal implementation)\n */\nfunction wrapWithTracingSync<TArgs extends unknown[], TReturn>(\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n // Idempotency check: if already instrumented, return as-is\n if (hasInstrumentationFlag(fnFactory)) {\n // If already instrumented, we need to extract the original factory\n // For now, we'll just proceed - this edge case is handled by the wrapped function check\n }\n\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n // Annotate as Sampler so the optional hooks stay visible. Inference would\n // narrow to AlwaysSampler and hide them behind `in` checks.\n const sampler: Sampler = options.sampler || new AlwaysSampler();\n\n const spanName = getSpanName(\n options,\n fnFactory as unknown as InstrumentableFunction<TArgs, TReturn>,\n variableName,\n );\n\n // Metrics setup (if enabled)\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n // Return wrapped function\n function wrappedFunction(\n this: unknown,\n ...args: TArgs\n ): TReturn | Promise<TReturn> {\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args,\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n // Read the rate next to the decision that produced it: a windowed sampler\n // can move on to a new rate before the span closes.\n const sampleRate = sampler.sampleRate?.(samplingContext);\n const needsTailSampling = sampler.needsTailSampling?.() ?? false;\n\n // If not sampling and no tail sampling, execute without tracing\n if (!shouldSample && !needsTailSampling) {\n const fn = fnFactory(createDummyCtx());\n return fn.call(this, ...args);\n }\n\n const startTime = performance.now();\n\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const flushRootTelemetry = createRootTelemetryFlusher(options, isRootSpan);\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n (span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(spanName, () =>\n runWithTraceContextStorage(() => {\n let shouldKeepSpan = true;\n\n // Store span name for trace context helpers\n setSpanName(span, spanName);\n\n // Only worth recording when the sampler actually dropped events.\n if (sampleRate !== undefined && sampleRate > 1) {\n span.setAttribute(AUTOTEL_SAMPLING_RATE, sampleRate);\n }\n\n // Create trace context for this span using shared utility\n const ctxValue = createTraceContext(span);\n\n // Get the actual function from the factory\n const fn = fnFactory(ctxValue);\n\n // Extract attributes only when actually tracing\n // This avoids expensive preprocessing when sampling rejects the trace\n const argsAttributes: Attributes = {\n ...captureInputAttrs(args, options.captureInput),\n ...(options.attributesFromArgs\n ? options.attributesFromArgs(args)\n : {}),\n } as Attributes;\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: Error,\n ) => {\n if (needsTailSampling && sampler.shouldKeepTrace) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n const onSuccess = (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n const resultAttributes = {\n ...captureOutputAttrs(result, options.captureOutput),\n ...(options.attributesFromResult\n ? options.attributesFromResult(result)\n : {}),\n };\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n ...argsAttributes,\n ...resultAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n return result;\n };\n\n const onError = (error: unknown): never => {\n finalizeThrownSpan(error, options.isError, {\n span,\n spanName,\n duration: performance.now() - startTime,\n callCounter,\n durationHistogram,\n handleTailSampling,\n extraAttributes: argsAttributes,\n });\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n const result = context.with(getActiveContextWithBaggage(), () =>\n fn.call(this, ...args),\n );\n\n if (result instanceof Promise) {\n return result.then(\n async (value) => {\n const completed = onSuccess(value);\n await flushRootTelemetry();\n return completed;\n },\n async (error) => {\n try {\n return onError(error);\n } finally {\n await flushRootTelemetry();\n }\n },\n );\n }\n\n const completed = onSuccess(result);\n void flushRootTelemetry();\n return completed;\n } catch (error) {\n try {\n return onError(error);\n } finally {\n void flushRootTelemetry();\n }\n }\n }),\n );\n },\n );\n }\n\n // Mark as instrumented to prevent double-wrapping\n (wrappedFunction as InstrumentedFlag)[INSTRUMENTED_SYMBOL] = true;\n\n Object.defineProperty(wrappedFunction, 'name', {\n value: variableName || 'trace',\n configurable: true,\n });\n\n return wrappedFunction as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Approach 1: trace() - Zero-ceremony HOF\n *\n * Wrap a plain function with automatic tracing. The function receives its real\n * arguments; no context parameter is injected. Use\n * {@link getActiveTraceContext} inside the function, or use {@link withTracing}\n * for the explicit `(ctx) => (...args) => result` factory form.\n *\n * @example Auto-inferred name - Plain function\n * ```typescript\n * export const createUser = trace(async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"createUser\"\n * ```\n *\n * @example Ambient context access\n * ```typescript\n * export const createUser = trace(async (data) => {\n * getActiveTraceContext()?.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Custom name - Plain function\n * ```typescript\n * export const createUser = trace('user.create', async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"user.create\"\n * ```\n *\n * @example Explicit factory context with withTracing()\n * ```typescript\n * export const createUser = withTracing({ name: 'user.create' })((ctx) => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Full options - Plain function\n * ```typescript\n * export const createUser = trace({\n * name: 'user.create',\n * sampler: new AdaptiveSampler(),\n * withMetrics: true\n * }, async (data) => {\n * return await db.users.create(data)\n * })\n * ```\n *\n */\n// Plain-function overloads. `trace()` always wraps a plain function that\n// receives its real arguments; it never injects a context parameter and never\n// inspects the function. Reach the active span via getActiveTraceContext()\n// inside the body. For the explicit `(ctx) => (args) => result` factory form,\n// use withTracing(). `TReturn` captures the return type verbatim, so async\n// functions infer `(...args) => Promise<...>` with no separate overload.\n\n// trace(fn)\nexport function trace<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// trace(name, fn)\nexport function trace<TArgs extends unknown[], TReturn>(\n name: string,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// trace(options, fn)\nexport function trace<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Implementation\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fnOrNameOrOptions:\n | ((...args: TArgs) => TReturn)\n | ((...args: TArgs) => Promise<TReturn>)\n | string\n | TracingOptions<TArgs, TReturn>,\n maybeFn?:\n ((...args: TArgs) => TReturn) | ((...args: TArgs) => Promise<TReturn>),\n): WrappedFunction<TArgs, TReturn> {\n // trace(fn) - the function is plain; it receives its real arguments and no\n // context is injected. Reach the active span via getActiveTraceContext().\n if (typeof fnOrNameOrOptions === 'function') {\n return wrapPlainWithTracing(\n fnOrNameOrOptions as (...args: TArgs) => TReturn,\n {} as TracingOptions<TArgs, TReturn>,\n );\n }\n\n // trace(name, fn) or trace(options, fn)\n if (!maybeFn) {\n throw new Error('trace(name|options, fn): fn is required');\n }\n\n const options: TracingOptions<TArgs, TReturn> =\n typeof fnOrNameOrOptions === 'string'\n ? ({ name: fnOrNameOrOptions } as TracingOptions<TArgs, TReturn>)\n : fnOrNameOrOptions;\n\n return wrapPlainWithTracing(maybeFn as (...args: TArgs) => TReturn, options);\n}\n\n/**\n * Approach 2: withTracing() - Middleware-style composable wrapper\n *\n * Returns a HOF that wraps functions with tracing.\n * Perfect for composition and reusable configuration.\n *\n * @example Standard usage\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Composable\n * ```typescript\n * const tracer = withTracing({ serviceName: 'user' })\n *\n * export const createUser = tracer(ctx => async (data) => { })\n * export const updateUser = tracer(ctx => async (id, data) => { })\n * ```\n *\n * @example With other middleware\n * ```typescript\n * export const createUser = compose(\n * withAuth({ role: 'admin' }),\n * withTracing({ name: 'user.create' }),\n * withRateLimit({ max: 100 })\n * )(ctx => async (data) => { })\n * ```\n */\nexport function withTracing<\n TCfgArgs extends unknown[] = unknown[],\n TCfgReturn = unknown,\n>(options: TracingOptions<TCfgArgs, TCfgReturn> = {}) {\n return <TArgs extends TCfgArgs, TReturn extends TCfgReturn>(\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n ): WrappedFunction<TArgs, TReturn> =>\n wrapFactoryWithTracing<TArgs, TReturn>(fnFactory, options);\n}\n\n/**\n * Approach 3: instrument() - Batch auto-instrumentation\n *\n * Instrument an entire module/object at once.\n * Closest to @Instrumented decorator pattern.\n *\n * @example Basic usage\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * sampler: new AdaptiveSampler()\n * })\n * // → Traced as \"user.createUser\", \"user.updateUser\", \"user.deleteUser\"\n * ```\n *\n * @example Per-function overrides\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * overrides: {\n * deleteUser: {\n * sampler: new AlwaysSampler(),\n * withMetrics: true\n * }\n * }\n * })\n * ```\n *\n * @example Skip functions\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * _internal: async () => { }, // Auto-skipped (_-prefix)\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * skip: [/^test/, (key) => key.includes('debug')]\n * })\n * ```\n */\nexport function instrument<TFunction extends AnyInstrumentable>(\n options: SingleInstrumentOptions<TFunction>,\n): TFunction;\nexport function instrument<T extends Record<string, AnyInstrumentable>>(\n options: InstrumentOptions<T>,\n): T;\nexport function instrument<\n T extends Record<string, AnyInstrumentable>,\n TFunction extends AnyInstrumentable,\n>(\n options: InstrumentOptions<T> | SingleInstrumentOptions<TFunction>,\n): T | TFunction {\n if (!options || typeof options !== 'object') {\n throw new TypeError(\n 'instrument: expected { key, fn } or { functions: { name: fn } }',\n );\n }\n\n if ('key' in options || 'fn' in options) {\n const { key, fn, ...tracingOptions } =\n options as SingleInstrumentOptions<TFunction>;\n if (typeof key !== 'string' || key.trim() === '') {\n throw new TypeError(\n 'instrument: \"key\" must be a non-empty string in the { key, fn } form',\n );\n }\n if (typeof fn !== 'function') {\n throw new TypeError(\n 'instrument: \"fn\" must be a function in the { key, fn } form',\n );\n }\n return wrapPlainWithTracing(fn, tracingOptions, key) as TFunction;\n }\n\n const { functions, ...tracingOptions } = options as InstrumentOptions<T>;\n if (!functions || typeof functions !== 'object') {\n throw new TypeError(\n 'instrument: expected { key, fn } or { functions: { name: fn } }',\n );\n }\n const instrumented: Partial<T> = {};\n\n for (const key of Object.keys(functions)) {\n const typedKey = key as keyof T;\n const fn = functions[typedKey];\n\n // Skip if not a function or undefined - just pass through the value\n if (!fn || typeof fn !== 'function') {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Only instrument own enumerable async functions\n // Check if should skip\n if (shouldSkip(key, fn, tracingOptions.skip)) {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Merge base options with per-function overrides\n const fnOptions: TracingOptions = {\n ...tracingOptions,\n ...tracingOptions.overrides?.[key],\n // If no explicit name, use key as function name\n name: tracingOptions.overrides?.[key]?.name,\n };\n\n // Bind function to original object to preserve 'this' context\n // This ensures methods can access state on the original object\n const boundFn = fn.bind(functions);\n\n // Convert plain function to factory pattern for trace()\n // For instrument(), we create a factory that ignores ctx and returns the original function\n const fnFactory = (ctx: TraceContext) => {\n void ctx;\n return boundFn;\n };\n\n // Wrap with tracing (sync or async based on implementation)\n instrumented[typedKey] = wrapFactoryWithTracing(\n fnFactory,\n fnOptions,\n key,\n ) as unknown as T[typeof typedKey];\n }\n\n return instrumented as T;\n}\n\n/**\n * Options for span() function\n */\nexport interface SpanOptions {\n /** Span name */\n name: string;\n /** Attributes to set on the span */\n attributes?: Record<string, string | number | boolean>;\n /** OpenTelemetry span kind */\n spanKind?: import('@opentelemetry/api').SpanKind;\n}\n\n/**\n * Execute a function within a named span\n *\n * Useful for adding tracing to specific code blocks without wrapping\n * the entire function. Supports both synchronous and asynchronous functions.\n *\n * Mirrors `trace()`: pass a span name as the first argument for the common\n * case, or full `SpanOptions` when you need to attach attributes.\n *\n * @example\n * ```typescript\n * // Name shorthand\n * await span('payment.charge', async (span) => {\n * await chargeCustomer(order);\n * })\n *\n * // Full options when attributes are needed\n * await span(\n * { name: 'payment.charge', attributes: { amount: order.total } },\n * async (span) => {\n * await chargeCustomer(order);\n * },\n * )\n *\n * // Sync\n * const total = span('calculateTotal', (span) => {\n * return items.reduce((sum, item) => sum + item.price, 0);\n * })\n * ```\n */\n// Overloads — sync first (more specific match), then async.\n// Each shape is offered with a string name OR a full SpanOptions object so\n// span() aligns with trace()'s argument flexibility.\nexport function span<T = unknown>(name: string, fn: (span: Span) => T): T;\nexport function span<T = unknown>(\n name: string,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => T,\n): T;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\n// Implementation\nexport function span<T = unknown>(\n nameOrOptions: string | SpanOptions,\n fn: (span: Span) => T | Promise<T>,\n): T | Promise<T> {\n const options: SpanOptions =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n const config = getConfig();\n const tracer = config.tracer;\n const { name, attributes, spanKind } = options;\n\n const executeSpan = (span: Span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(name, () => {\n try {\n // Set attributes\n if (attributes) {\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute(key, value);\n }\n }\n\n const result = fn(span);\n\n // Check if result is a Promise\n if (result instanceof Promise) {\n return result\n .then((resolved) => {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return resolved;\n })\n .catch((error) => {\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n });\n } else {\n // Synchronous function\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n }\n } catch (error) {\n // Synchronous error handling\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n }\n });\n };\n\n const parentContext = getActiveContextWithBaggage();\n const result = tracer.startActiveSpan(\n name,\n spanKind === undefined ? {} : { kind: spanKind },\n parentContext,\n executeSpan,\n );\n\n // tracer.startActiveSpan might return a Promise even for sync callbacks\n // Check if it's a Promise and handle accordingly\n if (result instanceof Promise) {\n return result;\n }\n\n return result as T;\n}\n\n/**\n * Options for withNewContext() function\n */\nexport interface WithNewContextOptions<T = unknown> {\n /** Function to execute in new root context */\n fn: () => Promise<T>;\n}\n\n/**\n * Execute a function in a new root context (prevents span propagation)\n *\n * Useful when you want to start a completely new trace without\n * parent-child relationships.\n *\n * @example\n * ```typescript\n * async function handleWebhook(payload: WebhookPayload) {\n * // This creates a new root trace, not connected to the HTTP request trace\n * await withNewContext({\n * fn: async () => {\n * await span('webhook.process', async () => {\n * await processWebhookPayload(payload)\n * })\n * }\n * })\n * }\n * ```\n */\nexport async function withNewContext<T = unknown>(\n options: WithNewContextOptions<T>,\n): Promise<T> {\n const { fn } = options;\n const config = getConfig();\n const tracer = config.tracer;\n\n // Start a new root span (breaks trace propagation)\n return tracer.startActiveSpan('root', { root: true }, async (span) => {\n try {\n const result = await fn();\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n });\n}\n\n/**\n * Options for withBaggage() function\n */\nexport interface WithBaggageOptions<T = unknown> {\n /** Baggage entries to set (key-value pairs) */\n baggage: Record<string, string>;\n /** Function to execute with the updated baggage */\n fn: () => T | Promise<T>;\n}\n\n/**\n * Execute a function with updated baggage entries\n *\n * Baggage is immutable in OpenTelemetry, so this helper creates a new context\n * with the specified baggage entries and runs the function within that context.\n * All child spans created within the function will inherit the baggage.\n *\n * @example Setting baggage for downstream services\n * ```typescript\n * import { withTracing, withBaggage } from 'autotel';\n *\n * export const createOrder = withTracing({ name: 'order.create' })((ctx) => async (order: Order) => {\n * // Set baggage that will be propagated to downstream HTTP calls\n * return await withBaggage({\n * baggage: {\n * 'tenant.id': order.tenantId,\n * 'user.id': order.userId,\n * },\n * fn: async () => {\n * // This HTTP call will include the baggage in headers\n * await fetch('/api/charge', {\n * method: 'POST',\n * body: JSON.stringify(order),\n * });\n * },\n * });\n * });\n * ```\n *\n * @example Using with existing baggage\n * ```typescript\n * export const processOrder = withTracing({ name: 'order.process' })((ctx) => async (order: Order) => {\n * // Read existing baggage\n * const tenantId = ctx.getBaggage('tenant.id');\n *\n * // Add additional baggage entries\n * return await withBaggage({\n * baggage: {\n * 'order.id': order.id,\n * 'order.amount': String(order.amount),\n * },\n * fn: async () => {\n * await charge(order);\n * },\n * });\n * });\n * ```\n */\nexport function withBaggage<T = unknown>(\n options: WithBaggageOptions<T>,\n): T | Promise<T> {\n const { baggage: baggageEntries, fn } = options;\n const currentContext = context.active();\n\n // Get existing baggage or create new\n let updatedBaggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n\n // Set all baggage entries\n for (const [key, value] of Object.entries(baggageEntries)) {\n updatedBaggage = updatedBaggage.setEntry(key, { value });\n }\n\n // Create new context with updated baggage\n const newContext = propagation.setBaggage(currentContext, updatedBaggage);\n\n // Sync contextStorage so nested traces (via getActiveContextWithBaggage) see the baggage.\n // Use run() instead of enterWith() to properly scope the context changes.\n const ctxStorage = getContextStorage();\n const previousStored = ctxStorage.getStore();\n const baggageEnrichedStored = previousStored\n ? { value: propagation.setBaggage(previousStored.value, updatedBaggage) }\n : { value: newContext };\n\n // Run the function within the new context, scoped properly\n const result = previousStored\n ? ctxStorage.run(baggageEnrichedStored, () => context.with(newContext, fn))\n : context.with(newContext, fn);\n\n if (result instanceof Promise) {\n // For async operations, ensure context is restored after the promise settles\n return result.then(\n (value) => {\n // Restore original context before resolving\n if (previousStored) {\n return ctxStorage.run(previousStored, () => value);\n }\n return value;\n },\n (error) => {\n // Restore original context before rejecting\n if (previousStored) {\n return ctxStorage.run(previousStored, () => {\n throw error;\n });\n }\n throw error;\n },\n );\n }\n\n // Sync function - context automatically restored when scope exits\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,iCAAiB,IAAI,IAAgC;AAC3D,MAAM,iBAAiB;;;;AAKvB,SAAS,oBAA4B;CACnC,MAAM,0BAA0B,MAAM;CACtC,MAAM,kBAAkB;CAGxB,MAAM,yBAAQ,IADE,MAAM,qBACN,EAAC,CAAC,SAAS;CAE3B,MAAM,kBAAkB;CACxB,OAAO;AACT;;;;;;;;;;;;AAaA,SAAS,kBAAkB,OAAyC;CAClE,MAAM,QAAQ,MAAM,MAAM,IAAI;CAC9B,IAAI,uBAAuB;CAE3B,KAAK,MAAM,QAAQ,OAAO;EAGxB,IACE,KAAK,SAAS,4BAA4B,KAC1C,KAAK,SAAS,4BAA4B,KAC1C,KAAK,SAAS,eAAe,KAC7B,KAAK,SAAS,eAAe,GAE7B;EAMF,MAAM,QACJ,KAAK,MAAM,0CAA0C,KACrD,KAAK,MAAM,yBAAyB;EAEtC,IAAI,OAAO;GACT,IAAI,WAAW,MAAM,EAAE,CAAE,KAAK;GAG9B,IAAI,SAAS,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b,wCAAwC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoC1B,KAAK,aAAa,cAAc,KAAK,MAAM,SAAS,IAAI;iBACxD,KAAK,aACnB,cACA,KAAK,MAAM,SAAS,QAAQ,KAC3B,QAAQ;iBACK,KAAK,aACnB,SAAS,aACT,KAAK,MAAM,SAAS,IACnB;iBACa,KAAK,aACnB,SAAS,aACT,KAAK,MAAM,SAAS,QAAQ,KAC3B,QAAQ;;;;UAmGM,sBAAsB;;EAErC,UAAU,QAAQ;;;;;;;;;;;;;;;;;;;;;;iBAuBE,eAAe,aACnC,SAAS,sBAAsB,KAC9B,QAAQ;;;;UA0BM,mBAAmB;;EAElC,SAAS;;EAET,UAAU,IAAI,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmDR,YAAY,aAC1B,SAAS,mBAAmB,KAC3B,IAAI,QAAQ"}
|
package/dist/http.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http.cjs","names":["getConfig","SpanStatusCode","getActiveContextWithBaggage","propagation","context"],"sources":["../src/http.ts"],"sourcesContent":["/**\n * HTTP Instrumentation Helpers\n *\n * Optional import: Not included in main bundle\n * Import from: 'autotel/http'\n *\n * Provides decorators and utilities for HTTP client instrumentation.\n * Works with fetch, axios, and other HTTP clients.\n *\n * @example\n * ```typescript\n * import { HttpInstrumented } from 'autotel/http'\n *\n * @HttpInstrumented()\n * class ApiClient {\n * async getUser(id: string) {\n * return fetch(`/api/users/${id}`)\n * }\n * }\n * ```\n */\n\nimport { SpanStatusCode, context, propagation } from '@opentelemetry/api';\nimport { getConfig } from './config';\nimport { getActiveContextWithBaggage } from './trace-context';\n\nexport interface HttpInstrumentedOptions {\n /** Service name for HTTP calls (default: 'http-client') */\n serviceName?: string;\n /** Extract URL from method arguments (default: first arg) */\n urlExtractor?: (args: unknown[]) => string | undefined;\n /** Extract HTTP method from method name or args */\n methodExtractor?: (methodName: string, args: unknown[]) => string;\n /** Add custom attributes to spans */\n attributesFromArgs?: (args: unknown[]) => Record<string, string | number>;\n /** Slow request threshold in milliseconds (adds warning attribute) - default: 3000ms */\n slowRequestThresholdMs?: number;\n}\n\n/**\n * Decorator for auto-instrumenting HTTP client methods\n *\n * @example Basic usage\n * ```typescript\n * @HttpInstrumented()\n * class ApiClient {\n * async fetchUser(userId: string) {\n * const res = await fetch(`https://api.example.com/users/${userId}`)\n * return res.json()\n * }\n *\n * async createOrder(order: Order) {\n * const res = await fetch('https://api.example.com/orders', {\n * method: 'POST',\n * body: JSON.stringify(order)\n * })\n * return res.json()\n * }\n * }\n * ```\n *\n * @example Advanced usage with custom extractors\n * ```typescript\n * @HttpInstrumented({\n * serviceName: 'payment-gateway',\n * urlExtractor: (args) => {\n * const config = args[0] as RequestConfig\n * return config.url\n * },\n * attributesFromArgs: (args) => ({\n * 'http.request_id': args[0]?.requestId,\n * 'http.retry_count': args[0]?.retryCount || 0\n * })\n * })\n * class PaymentClient {\n * async charge(config: RequestConfig) {\n * return axios(config)\n * }\n * }\n * ```\n */\nexport function HttpInstrumented(options: HttpInstrumentedOptions = {}) {\n const serviceName = options.serviceName || 'http-client';\n const slowRequestThresholdMs = options.slowRequestThresholdMs ?? 3000;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-object-type\n return function <T extends { new (...args: any[]): {} }>(\n target: T,\n _context: ClassDecoratorContext,\n ) {\n return class extends target {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(...args: any[]) {\n super(...args);\n\n const proto = target.prototype;\n const methodNames = Object.getOwnPropertyNames(proto).filter(\n (name) =>\n name !== 'constructor' &&\n typeof proto[name] === 'function' &&\n !name.startsWith('_'),\n );\n\n for (const methodName of methodNames) {\n const originalMethod = proto[methodName];\n\n if (\n originalMethod.constructor.name === 'AsyncFunction' ||\n originalMethod.toString().startsWith('async ')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wrappedMethod = async (...args: any[]) => {\n const config = getConfig();\n const tracer = config.tracer;\n\n const url = options.urlExtractor\n ? options.urlExtractor(args)\n : (args[0] as string | undefined);\n\n const method = options.methodExtractor\n ? options.methodExtractor(methodName, args)\n : inferHttpMethod(methodName);\n\n const spanName = url\n ? `HTTP ${method} ${extractPath(url)}`\n : `HTTP ${method}`;\n\n return tracer.startActiveSpan(spanName, async (span) => {\n const startTime = performance.now();\n\n try {\n span.setAttributes({\n 'http.method': method,\n 'http.url': url || 'unknown',\n 'service.name': serviceName,\n 'operation.name': `${serviceName}.${methodName}`,\n });\n\n if (url) {\n const urlObj = parseUrl(url);\n span.setAttributes({\n 'http.scheme': urlObj.protocol,\n 'http.host': urlObj.host,\n 'http.target': urlObj.path,\n });\n }\n\n if (options.attributesFromArgs) {\n span.setAttributes(options.attributesFromArgs(args));\n }\n\n const result = await originalMethod.apply(this, args);\n\n const duration = performance.now() - startTime;\n\n // Extract status code from response\n const statusCode = extractStatusCode(result);\n if (statusCode) {\n span.setAttribute('http.status_code', statusCode);\n\n if (statusCode >= 400) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${statusCode}`,\n });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n\n span.setAttributes({\n 'http.duration_ms': duration,\n });\n\n // Mark slow requests for investigation\n if (duration > slowRequestThresholdMs) {\n span.setAttribute('http.slow_request', true);\n span.setAttribute(\n 'http.slow_request_threshold_ms',\n slowRequestThresholdMs,\n );\n }\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message:\n error instanceof Error ? error.message : 'Unknown error',\n });\n\n span.setAttributes({\n 'http.duration_ms': duration,\n 'error.type':\n error instanceof Error\n ? error.constructor.name\n : 'Unknown',\n 'error.message':\n error instanceof Error ? error.message : 'Unknown error',\n });\n\n throw error;\n } finally {\n span.end();\n }\n });\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any)[methodName] = wrappedMethod;\n }\n }\n }\n };\n };\n}\n\n/**\n * Helper: Trace a single HTTP request\n *\n * @example\n * ```typescript\n * import { traceHttpRequest } from 'autotel/http'\n *\n * const data = await traceHttpRequest(\n * 'GET /api/users',\n * () => fetch('https://api.example.com/users')\n * )\n * ```\n */\nexport async function traceHttpRequest<T>(\n spanName: string,\n fn: () => Promise<T>,\n attributes?: Record<string, string | number>,\n): Promise<T> {\n const config = getConfig();\n const tracer = config.tracer;\n\n return tracer.startActiveSpan(spanName, async (span) => {\n try {\n if (attributes) {\n span.setAttributes(attributes);\n }\n\n const result = await fn();\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n throw error;\n } finally {\n span.end();\n }\n });\n}\n\n// Helper functions\n\nfunction inferHttpMethod(methodName: string): string {\n const lower = methodName.toLowerCase();\n if (\n lower.includes('get') ||\n lower.includes('fetch') ||\n lower.includes('list')\n )\n return 'GET';\n if (lower.includes('post') || lower.includes('create')) return 'POST';\n if (lower.includes('put') || lower.includes('update')) return 'PUT';\n if (lower.includes('delete') || lower.includes('remove')) return 'DELETE';\n if (lower.includes('patch')) return 'PATCH';\n return 'GET'; // Default\n}\n\nfunction extractPath(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.pathname;\n } catch {\n // Relative URL or invalid\n return url.split('?')[0] || url;\n }\n}\n\nfunction parseUrl(url: string): {\n protocol: string;\n host: string;\n path: string;\n} {\n try {\n const urlObj = new URL(url);\n return {\n protocol: urlObj.protocol.replace(':', ''),\n host: urlObj.host,\n path: urlObj.pathname + urlObj.search,\n };\n } catch {\n return {\n protocol: 'http',\n host: 'unknown',\n path: url,\n };\n }\n}\n\nfunction extractStatusCode(result: unknown): number | undefined {\n if (result && typeof result === 'object') {\n // Check for Response.status (fetch API)\n if ('status' in result && typeof result.status === 'number') {\n return result.status;\n }\n // Check for statusCode (axios, node http)\n if ('statusCode' in result && typeof result.statusCode === 'number') {\n return result.statusCode;\n }\n }\n return undefined;\n}\n\n/**\n * Inject trace context into HTTP headers (for distributed tracing)\n *\n * This includes W3C Trace Context (traceparent, tracestate) and W3C Baggage headers.\n * Uses OpenTelemetry's propagation system for full compatibility.\n *\n * @example\n * ```typescript\n * import { injectTraceContext } from 'autotel/http'\n *\n * const headers = injectTraceContext({\n * 'Content-Type': 'application/json'\n * })\n *\n * fetch('/api/users', { headers })\n * ```\n *\n * @example With baggage\n * ```typescript\n * import { trace, withTracing, withBaggage, injectTraceContext } from 'autotel'\n *\n * export const createOrder = withTracing({})((ctx) => async (order: Order) => {\n * return await withBaggage({\n * baggage: { 'tenant.id': order.tenantId },\n * fn: async () => {\n * const headers = injectTraceContext();\n * // Headers now include 'baggage' header with tenant.id\n * await fetch('/api/charge', { headers });\n * },\n * });\n * });\n * ```\n */\nexport function injectTraceContext(\n headers: Record<string, string> = {},\n): Record<string, string> {\n // Use getActiveContextWithBaggage to check stored context (from baggage setters)\n // This ensures ctx.setBaggage() changes are included in injected headers\n const currentContext = getActiveContextWithBaggage();\n\n // Use OpenTelemetry's propagation.inject for full W3C support\n // This includes traceparent, tracestate, and baggage headers\n propagation.inject(currentContext, headers);\n\n return headers;\n}\n\n/**\n * Extract trace context from HTTP headers (for distributed tracing)\n *\n * This extracts W3C Trace Context (traceparent, tracestate) and W3C Baggage headers.\n * Uses OpenTelemetry's propagation system for full compatibility.\n *\n * Returns a context that can be used with context.with() to run code\n * with the extracted trace context and baggage.\n *\n * @example\n * ```typescript\n * import { extractTraceContext, trace, withTracing } from 'autotel'\n * import { context } from 'autotel'\n *\n * // In Express middleware\n * app.use((req, res, next) => {\n * const extractedContext = extractTraceContext(req.headers);\n * context.with(extractedContext, () => {\n * next();\n * });\n * });\n * ```\n *\n * @example In a traced function\n * ```typescript\n * export const handleWebhook = withTracing({})((ctx) => async (req: Request) => {\n * const extractedContext = extractTraceContext(req.headers);\n * return await context.with(extractedContext, async () => {\n * // Now ctx.getBaggage() will return baggage from the incoming request\n * const tenantId = ctx.getBaggage('tenant.id');\n * await processWebhook(req.body);\n * });\n * });\n * ```\n */\nexport function extractTraceContext(\n headers: Record<string, string | string[] | undefined>,\n): ReturnType<typeof context.active> {\n const carrier: Record<string, string> = {};\n\n // Convert headers to flat string format expected by propagation\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined) {\n carrier[key] = Array.isArray(value) ? (value[0] ?? '') : value;\n }\n }\n\n // Extract context using OpenTelemetry's propagation system\n // Returns a Context that can be used with context.with()\n return propagation.extract(context.active(), carrier);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,iBAAiB,UAAmC,CAAC,GAAG;CACtE,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,yBAAyB,QAAQ,0BAA0B;CAGjE,OAAO,SACL,QACA,UACA;EACA,OAAO,cAAc,OAAO;GAE1B,YAAY,GAAG,MAAa;IAC1B,MAAM,GAAG,IAAI;IAEb,MAAM,QAAQ,OAAO;IACrB,MAAM,cAAc,OAAO,oBAAoB,KAAK,CAAC,CAAC,QACnD,SACC,SAAS,iBACT,OAAO,MAAM,UAAU,cACvB,CAAC,KAAK,WAAW,GAAG,CACxB;IAEA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,iBAAiB,MAAM;KAE7B,IACE,eAAe,YAAY,SAAS,mBACpC,eAAe,SAAS,CAAC,CAAC,WAAW,QAAQ,GAC7C;MAEA,MAAM,gBAAgB,OAAO,GAAG,SAAgB;OAE9C,MAAM,SADSA,yBACK,CAAC,CAAC;OAEtB,MAAM,MAAM,QAAQ,eAChB,QAAQ,aAAa,IAAI,IACxB,KAAK;OAEV,MAAM,SAAS,QAAQ,kBACnB,QAAQ,gBAAgB,YAAY,IAAI,IACxC,gBAAgB,UAAU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;;;;iBAwHK,mBACd,UAAS,yBACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Ca,oBACd,SAAS,gDACR,kBAAkB,QAAQ"}
|
package/dist/http.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.ts","names":[],"sources":["../src/http.ts"],"mappings":";;UA0BiB;;EAEf;;EAEA,gBAAgB;;EAEhB,mBAAmB,oBAAoB;;EAEvC,sBAAsB,oBAAoB;;EAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6Cc,iBAAiB,UAAS,2BAKvB;UAAoB;GACnC,QAAQ,GACR,UAAU;UAIa;IA+H1B;;;;;;;;;;;;;;iBAeqB,iBAAiB,GACrC,kBACA,UAAU,QAAQ,IAClB,aAAa,kCACZ,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwHK,mBACd,UAAS,yBACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Ca,oBACd,SAAS,gDACR,kBAAkB,QAAQ"}
|
package/dist/http.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","names":[],"sources":["../src/http.ts"],"sourcesContent":["/**\n * HTTP Instrumentation Helpers\n *\n * Optional import: Not included in main bundle\n * Import from: 'autotel/http'\n *\n * Provides decorators and utilities for HTTP client instrumentation.\n * Works with fetch, axios, and other HTTP clients.\n *\n * @example\n * ```typescript\n * import { HttpInstrumented } from 'autotel/http'\n *\n * @HttpInstrumented()\n * class ApiClient {\n * async getUser(id: string) {\n * return fetch(`/api/users/${id}`)\n * }\n * }\n * ```\n */\n\nimport { SpanStatusCode, context, propagation } from '@opentelemetry/api';\nimport { getConfig } from './config';\nimport { getActiveContextWithBaggage } from './trace-context';\n\nexport interface HttpInstrumentedOptions {\n /** Service name for HTTP calls (default: 'http-client') */\n serviceName?: string;\n /** Extract URL from method arguments (default: first arg) */\n urlExtractor?: (args: unknown[]) => string | undefined;\n /** Extract HTTP method from method name or args */\n methodExtractor?: (methodName: string, args: unknown[]) => string;\n /** Add custom attributes to spans */\n attributesFromArgs?: (args: unknown[]) => Record<string, string | number>;\n /** Slow request threshold in milliseconds (adds warning attribute) - default: 3000ms */\n slowRequestThresholdMs?: number;\n}\n\n/**\n * Decorator for auto-instrumenting HTTP client methods\n *\n * @example Basic usage\n * ```typescript\n * @HttpInstrumented()\n * class ApiClient {\n * async fetchUser(userId: string) {\n * const res = await fetch(`https://api.example.com/users/${userId}`)\n * return res.json()\n * }\n *\n * async createOrder(order: Order) {\n * const res = await fetch('https://api.example.com/orders', {\n * method: 'POST',\n * body: JSON.stringify(order)\n * })\n * return res.json()\n * }\n * }\n * ```\n *\n * @example Advanced usage with custom extractors\n * ```typescript\n * @HttpInstrumented({\n * serviceName: 'payment-gateway',\n * urlExtractor: (args) => {\n * const config = args[0] as RequestConfig\n * return config.url\n * },\n * attributesFromArgs: (args) => ({\n * 'http.request_id': args[0]?.requestId,\n * 'http.retry_count': args[0]?.retryCount || 0\n * })\n * })\n * class PaymentClient {\n * async charge(config: RequestConfig) {\n * return axios(config)\n * }\n * }\n * ```\n */\nexport function HttpInstrumented(options: HttpInstrumentedOptions = {}) {\n const serviceName = options.serviceName || 'http-client';\n const slowRequestThresholdMs = options.slowRequestThresholdMs ?? 3000;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-object-type\n return function <T extends { new (...args: any[]): {} }>(\n target: T,\n _context: ClassDecoratorContext,\n ) {\n return class extends target {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(...args: any[]) {\n super(...args);\n\n const proto = target.prototype;\n const methodNames = Object.getOwnPropertyNames(proto).filter(\n (name) =>\n name !== 'constructor' &&\n typeof proto[name] === 'function' &&\n !name.startsWith('_'),\n );\n\n for (const methodName of methodNames) {\n const originalMethod = proto[methodName];\n\n if (\n originalMethod.constructor.name === 'AsyncFunction' ||\n originalMethod.toString().startsWith('async ')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wrappedMethod = async (...args: any[]) => {\n const config = getConfig();\n const tracer = config.tracer;\n\n const url = options.urlExtractor\n ? options.urlExtractor(args)\n : (args[0] as string | undefined);\n\n const method = options.methodExtractor\n ? options.methodExtractor(methodName, args)\n : inferHttpMethod(methodName);\n\n const spanName = url\n ? `HTTP ${method} ${extractPath(url)}`\n : `HTTP ${method}`;\n\n return tracer.startActiveSpan(spanName, async (span) => {\n const startTime = performance.now();\n\n try {\n span.setAttributes({\n 'http.method': method,\n 'http.url': url || 'unknown',\n 'service.name': serviceName,\n 'operation.name': `${serviceName}.${methodName}`,\n });\n\n if (url) {\n const urlObj = parseUrl(url);\n span.setAttributes({\n 'http.scheme': urlObj.protocol,\n 'http.host': urlObj.host,\n 'http.target': urlObj.path,\n });\n }\n\n if (options.attributesFromArgs) {\n span.setAttributes(options.attributesFromArgs(args));\n }\n\n const result = await originalMethod.apply(this, args);\n\n const duration = performance.now() - startTime;\n\n // Extract status code from response\n const statusCode = extractStatusCode(result);\n if (statusCode) {\n span.setAttribute('http.status_code', statusCode);\n\n if (statusCode >= 400) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${statusCode}`,\n });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n\n span.setAttributes({\n 'http.duration_ms': duration,\n });\n\n // Mark slow requests for investigation\n if (duration > slowRequestThresholdMs) {\n span.setAttribute('http.slow_request', true);\n span.setAttribute(\n 'http.slow_request_threshold_ms',\n slowRequestThresholdMs,\n );\n }\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message:\n error instanceof Error ? error.message : 'Unknown error',\n });\n\n span.setAttributes({\n 'http.duration_ms': duration,\n 'error.type':\n error instanceof Error\n ? error.constructor.name\n : 'Unknown',\n 'error.message':\n error instanceof Error ? error.message : 'Unknown error',\n });\n\n throw error;\n } finally {\n span.end();\n }\n });\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any)[methodName] = wrappedMethod;\n }\n }\n }\n };\n };\n}\n\n/**\n * Helper: Trace a single HTTP request\n *\n * @example\n * ```typescript\n * import { traceHttpRequest } from 'autotel/http'\n *\n * const data = await traceHttpRequest(\n * 'GET /api/users',\n * () => fetch('https://api.example.com/users')\n * )\n * ```\n */\nexport async function traceHttpRequest<T>(\n spanName: string,\n fn: () => Promise<T>,\n attributes?: Record<string, string | number>,\n): Promise<T> {\n const config = getConfig();\n const tracer = config.tracer;\n\n return tracer.startActiveSpan(spanName, async (span) => {\n try {\n if (attributes) {\n span.setAttributes(attributes);\n }\n\n const result = await fn();\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n throw error;\n } finally {\n span.end();\n }\n });\n}\n\n// Helper functions\n\nfunction inferHttpMethod(methodName: string): string {\n const lower = methodName.toLowerCase();\n if (\n lower.includes('get') ||\n lower.includes('fetch') ||\n lower.includes('list')\n )\n return 'GET';\n if (lower.includes('post') || lower.includes('create')) return 'POST';\n if (lower.includes('put') || lower.includes('update')) return 'PUT';\n if (lower.includes('delete') || lower.includes('remove')) return 'DELETE';\n if (lower.includes('patch')) return 'PATCH';\n return 'GET'; // Default\n}\n\nfunction extractPath(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.pathname;\n } catch {\n // Relative URL or invalid\n return url.split('?')[0] || url;\n }\n}\n\nfunction parseUrl(url: string): {\n protocol: string;\n host: string;\n path: string;\n} {\n try {\n const urlObj = new URL(url);\n return {\n protocol: urlObj.protocol.replace(':', ''),\n host: urlObj.host,\n path: urlObj.pathname + urlObj.search,\n };\n } catch {\n return {\n protocol: 'http',\n host: 'unknown',\n path: url,\n };\n }\n}\n\nfunction extractStatusCode(result: unknown): number | undefined {\n if (result && typeof result === 'object') {\n // Check for Response.status (fetch API)\n if ('status' in result && typeof result.status === 'number') {\n return result.status;\n }\n // Check for statusCode (axios, node http)\n if ('statusCode' in result && typeof result.statusCode === 'number') {\n return result.statusCode;\n }\n }\n return undefined;\n}\n\n/**\n * Inject trace context into HTTP headers (for distributed tracing)\n *\n * This includes W3C Trace Context (traceparent, tracestate) and W3C Baggage headers.\n * Uses OpenTelemetry's propagation system for full compatibility.\n *\n * @example\n * ```typescript\n * import { injectTraceContext } from 'autotel/http'\n *\n * const headers = injectTraceContext({\n * 'Content-Type': 'application/json'\n * })\n *\n * fetch('/api/users', { headers })\n * ```\n *\n * @example With baggage\n * ```typescript\n * import { trace, withTracing, withBaggage, injectTraceContext } from 'autotel'\n *\n * export const createOrder = withTracing({})((ctx) => async (order: Order) => {\n * return await withBaggage({\n * baggage: { 'tenant.id': order.tenantId },\n * fn: async () => {\n * const headers = injectTraceContext();\n * // Headers now include 'baggage' header with tenant.id\n * await fetch('/api/charge', { headers });\n * },\n * });\n * });\n * ```\n */\nexport function injectTraceContext(\n headers: Record<string, string> = {},\n): Record<string, string> {\n // Use getActiveContextWithBaggage to check stored context (from baggage setters)\n // This ensures ctx.setBaggage() changes are included in injected headers\n const currentContext = getActiveContextWithBaggage();\n\n // Use OpenTelemetry's propagation.inject for full W3C support\n // This includes traceparent, tracestate, and baggage headers\n propagation.inject(currentContext, headers);\n\n return headers;\n}\n\n/**\n * Extract trace context from HTTP headers (for distributed tracing)\n *\n * This extracts W3C Trace Context (traceparent, tracestate) and W3C Baggage headers.\n * Uses OpenTelemetry's propagation system for full compatibility.\n *\n * Returns a context that can be used with context.with() to run code\n * with the extracted trace context and baggage.\n *\n * @example\n * ```typescript\n * import { extractTraceContext, trace, withTracing } from 'autotel'\n * import { context } from 'autotel'\n *\n * // In Express middleware\n * app.use((req, res, next) => {\n * const extractedContext = extractTraceContext(req.headers);\n * context.with(extractedContext, () => {\n * next();\n * });\n * });\n * ```\n *\n * @example In a traced function\n * ```typescript\n * export const handleWebhook = withTracing({})((ctx) => async (req: Request) => {\n * const extractedContext = extractTraceContext(req.headers);\n * return await context.with(extractedContext, async () => {\n * // Now ctx.getBaggage() will return baggage from the incoming request\n * const tenantId = ctx.getBaggage('tenant.id');\n * await processWebhook(req.body);\n * });\n * });\n * ```\n */\nexport function extractTraceContext(\n headers: Record<string, string | string[] | undefined>,\n): ReturnType<typeof context.active> {\n const carrier: Record<string, string> = {};\n\n // Convert headers to flat string format expected by propagation\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined) {\n carrier[key] = Array.isArray(value) ? (value[0] ?? '') : value;\n }\n }\n\n // Extract context using OpenTelemetry's propagation system\n // Returns a Context that can be used with context.with()\n return propagation.extract(context.active(), carrier);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,iBAAiB,UAAmC,CAAC,GAAG;CACtE,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,yBAAyB,QAAQ,0BAA0B;CAGjE,OAAO,SACL,QACA,UACA;EACA,OAAO,cAAc,OAAO;GAE1B,YAAY,GAAG,MAAa;IAC1B,MAAM,GAAG,IAAI;IAEb,MAAM,QAAQ,OAAO;IACrB,MAAM,cAAc,OAAO,oBAAoB,KAAK,CAAC,CAAC,QACnD,SACC,SAAS,iBACT,OAAO,MAAM,UAAU,cACvB,CAAC,KAAK,WAAW,GAAG,CACxB;IAEA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,iBAAiB,MAAM;KAE7B,IACE,eAAe,YAAY,SAAS,mBACpC,eAAe,SAAS,CAAC,CAAC,WAAW,QAAQ,GAC7C;MAEA,MAAM,gBAAgB,OAAO,GAAG,SAAgB;OAE9C,MAAM,SADS,UACK,CAAC,CAAC;OAEtB,MAAM,MAAM,QAAQ,eAChB,QAAQ,aAAa,IAAI,IACxB,KAAK;OAEV,MAAM,SAA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,OAAO;GACL,UAAU,OAAO,SAAS,QAAQ,KAAK,EAAE;GACzC,MAAM,OAAO;GACb,MAAM,OAAO,WAAW,OAAO;EACjC;CACF,QAAQ;EACN,OAAO;GACL,UAAU;GACV,MAAM;GACN,MAAM;EACR;CACF;AACF;AAEA,SAAS,kBAAkB,QAAqC;CAC9D,IAAI,UAAU,OAAO,WAAW,UAAU;EAExC,IAAI,YAAY,UAAU,OAAO,OAAO,WAAW,UACjD,OAAO,OAAO;EAGhB,IAAI,gBAAgB,UAAU,OAAO,OAAO,eAAe,UACzD,OAAO,OAAO;CAElB;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,mBACd,UAAkC,CAAC,GACX;CAGxB,MAAM,iBAAiB,4BAA4B;CAInD,YAAY,OAAO,gBAAgB,OAAO;CAE1C,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,oBACd,SACmC;CACnC,MAAM,UAAkC,CAAC;CAGzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,IAAI,UAAU,QACZ,QAAQ,OAAO,MAAM,QAAQ,KAAK,IAAK,MAAM,MAAM,KAAM;CAM7D,OAAO,YAAY,QAAQ,QAAQ,OAAO,GAAG,OAAO;AACtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-BPcxVucm.d.cts","names":[],"sources":["../src/attributes/types.ts","../src/attributes/builders.ts","../src/attributes/validators.ts","../src/attributes/attachers.ts","../src/attributes/domains.ts","../src/attributes/utils.ts"],"mappings":";;;;UAOiB;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;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C,SAAA;;;aACA,SAAA;;;aACI,aAAA;;;aACA,aAAA;;;aACF,WAAA;;;;;aAIO,kBAAA;;;aAGT,SAAA;;;aACG,YAAA;;;aACF,UAAA;;;;;;;;;;;UCvgBJ;;EAEf;;EAGA;;EAGA;;EAGA;;EAGA,qBAAqB;;UAGN;EACf,aAAa;;EAEb,qBAAqB;;iBA0CP,kBACd,aACA,gBACA,SAAQ;iBAsIM,yBACd,aACA,SAAQ;iBAqCM,cACd,YAAY,yBACZ,SAAQ,kBACP;iBAUa,qBAAqB;;;iBCnPrB,QACd,eAAe,OAAO,cACtB,MADsB,WAEtB,aADwB;iBAOV,WACd,eAAe,OAAO,cACtB,MADsB,cAEtB,aADwB;iBAOV,UACd,eAAe,OAAO,cACtB,MADsB,aAEtB,aADwB;iBAOV,WACd,eAAe,OAAO,cACtB,MADsB,iBAEtB,aADwB;iBAaV,WACd,eAAe,OAAO,cACtB,MADsB,iBAEtB,aADwB;iBAOV,SACd,eAAe,OAAO,cACtB,MADsB,SAEtB,aADwB;;;;;;;;;;;;;;;;;;;;iBA0BV,qBACd,UAAU,UACV,MADU,eAET;iBAKa,SACd,eAAe,OAAO,cACtB;EACE,OAFoB;EAGpB,UADyB;EAEzB,SAD4B;GAG9B,aAF6B;iBAwBf,QACd,eAAe,OAAO,cACtB,MADsB;EAEpB;GAEF,aAHwB;iBAWV,SACd,eAAe,OAAO,cACtB,MADsB,YAEtB,aADwB;iBAOV,aACd,eAAe,OAAO,cACtB,MADsB,gBAEtB,aADwB;;;;;;;iBCnJV,YACd,eADc,cAEd;EACE,OAFwC;EAGxC,UADyB;EAEzB;EACA;EACA;EACA;GAEF,aAN8B;;;KCG3B;EACH,gBAAgB,OAAO,eAAe;;iBAGxB,cACX,UAAU,MAAM,uCAClB;iBAUa,kBACd,MAAM,iBACN,OAAO,yBACP,SAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-DolOVX6F.d.ts","names":[],"sources":["../src/attributes/types.ts","../src/attributes/builders.ts","../src/attributes/validators.ts","../src/attributes/attachers.ts","../src/attributes/domains.ts","../src/attributes/utils.ts"],"mappings":";;;;UAOiB;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;;;;cC/IW;;aAEG,KAAA;;;aACG,QAAA;;;aACD,OAAA;;;aACI,WAAA;;;aACJ,OAAA;;;aACC,QAAA;;;aAEF,OAAA,MAAA,cAAS;;;aAcV,KAAA;;;aACQ,aAAA;;;aAEP,OAAA,MAAA,iBAAY;;;aAUb,KAAA;;;aACU,eAAA;;;aAGG,kBAAA;;;aAGN,YAAA;;;aAEN,OAAA,MAAA,gBAAW;;;;eAeN,SAAA;;;eACQ,iBAAA;;;eAGH,cAAA;;;eAGP,OAAA;;;eACI,WAAA;;;;;eAME,aAAA;;;eAGN,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cACtB,MADsB,gBAEtB,aADwB;;;;;;;iBCnJV,YACd,eADc,cAEd;EACE,OAFwC;EAGxC,UADyB;EAEzB;EACA;EACA;EACA;GAEF,aAN8B;;;KCG3B;EACH,gBAAgB,OAAO,eAAe;;iBAGxB,cACX,UAAU,MAAM,uCAClB;iBAUa,kBACd,MAAM,iBACN,OAAO,yBACP,SAAS"}
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["otelTraceApi","autotelTraceFn","hashJson","mergeInto","nodeAsyncHooks","otelTrace","createTraceContext","flattenToAttributes","createStructuredError"],"sources":["../src/trace-hybrid.ts","../src/define-event.ts","../src/request-logger.ts","../src/error-catalog.ts","../src/drain-toolkit.ts","../src/enricher-toolkit.ts"],"sourcesContent":["/**\n * Hybrid `trace` export: callable like autotel's `trace(fn)`, AND exposes the\n * full `@opentelemetry/api` `TraceAPI` surface (`trace.getActiveSpan()`,\n * `trace.getTracer()`, …) so existing OTel code \"just works\" when imported\n * from `autotel`.\n *\n * Implementation: `Object.assign` mutates the autotel `trace` function to\n * attach the OTel TraceAPI methods. Because every reference to `trace` across\n * autotel resolves to the same function instance, this is a one-time, global\n * augmentation.\n */\n\nimport { trace as otelTraceApi } from '@opentelemetry/api';\nimport { trace as autotelTraceFn } from './functional';\n\nconst otelMethods = {\n // Class methods on TraceAPI — bind to the singleton.\n setGlobalTracerProvider:\n otelTraceApi.setGlobalTracerProvider.bind(otelTraceApi),\n getTracerProvider: otelTraceApi.getTracerProvider.bind(otelTraceApi),\n getTracer: otelTraceApi.getTracer.bind(otelTraceApi),\n disable: otelTraceApi.disable.bind(otelTraceApi),\n // Instance fields on TraceAPI — already standalone, copy by reference.\n wrapSpanContext: otelTraceApi.wrapSpanContext,\n isSpanContextValid: otelTraceApi.isSpanContextValid,\n deleteSpan: otelTraceApi.deleteSpan,\n getSpan: otelTraceApi.getSpan,\n getActiveSpan: otelTraceApi.getActiveSpan,\n getSpanContext: otelTraceApi.getSpanContext,\n setSpan: otelTraceApi.setSpan,\n setSpanContext: otelTraceApi.setSpanContext,\n};\n\nexport const trace: typeof autotelTraceFn & typeof otelTraceApi = Object.assign(\n autotelTraceFn,\n otelMethods,\n) as typeof autotelTraceFn & typeof otelTraceApi;\n","import { track } from './track';\nimport { hashJson } from './stable-hash';\nimport type { EventSchemaMetadata } from './event-subscriber';\n\ntype SafeParseResult<T> =\n { success: true; data: T } | { success: false; error: unknown };\n\nexport interface SchemaLike<T> {\n safeParse(input: unknown): SafeParseResult<T>;\n}\n\nexport interface DefineEventOptions<S> {\n toJsonSchema?: (schema: S) => unknown;\n}\n\nexport interface DefinedEvent<Name extends string, Payload> {\n readonly name: Name;\n readonly schemaMetadata?: EventSchemaMetadata;\n track(payload: Payload): void;\n}\n\nexport function defineEvent<\n Name extends string,\n Payload,\n S extends SchemaLike<Payload>,\n>(\n name: Name,\n schema: S,\n options: DefineEventOptions<S> = {},\n): DefinedEvent<Name, Payload> {\n const jsonSchema = options.toJsonSchema?.(schema);\n const schemaMetadata = jsonSchema\n ? {\n source: 'zod' as const,\n jsonSchema,\n hash: hashJson(jsonSchema),\n }\n : undefined;\n\n return {\n name,\n schemaMetadata,\n track(payload: Payload) {\n const parsed = schema.safeParse(payload);\n if (!parsed.success) {\n throw new Error(\n `Invalid payload for event \"${name}\". Schema validation failed.`,\n );\n }\n track(\n name,\n parsed.data,\n schemaMetadata ? { schema: schemaMetadata } : undefined,\n );\n },\n };\n}\n","// namespace import for browser-bundler compat — see node-require.ts\nimport * as nodeAsyncHooks from 'node:async_hooks';\nimport { trace as otelTrace } from '@opentelemetry/api';\nimport type { TraceContext } from './trace-context';\nimport { createTraceContext } from './trace-context';\nimport { recordStructuredError } from './structured-error';\nimport { flattenToAttributes } from './flatten-attributes';\nimport { emitCorrelatedEvent } from './correlated-events';\n\nconst POST_EMIT_FORK_HINT =\n \"For intentional background work tied to this request, use log.fork('label', fn) when available.\";\n\nfunction warnPostEmit(method: string, detail: string): void {\n console.warn(\n `[autotel] ${method} called after the wide event was emitted — ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`,\n );\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key in source) {\n const sourceVal = source[key];\n if (sourceVal === undefined) continue;\n const targetVal = target[key];\n if (\n sourceVal !== null &&\n typeof sourceVal === 'object' &&\n !Array.isArray(sourceVal) &&\n targetVal !== null &&\n typeof targetVal === 'object' &&\n !Array.isArray(targetVal)\n ) {\n mergeInto(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>,\n );\n } else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n target[key] = [...targetVal, ...sourceVal];\n } else {\n target[key] = sourceVal;\n }\n }\n}\n\nconst requestContextStore =\n new nodeAsyncHooks.AsyncLocalStorage<TraceContext>();\n\nexport function runWithRequestContext<T>(ctx: TraceContext, fn: () => T): T {\n return requestContextStore.run(ctx, fn);\n}\n\nexport interface RequestLogger {\n set(fields: Record<string, unknown>): void;\n info(message: string, fields?: Record<string, unknown>): void;\n warn(message: string, fields?: Record<string, unknown>): void;\n error(error: Error | string, fields?: Record<string, unknown>): void;\n getContext(): Record<string, unknown>;\n emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot;\n fork(\n label: string,\n fn: () => void | Promise<void>,\n options?: ForkOptions,\n ): void;\n}\n\nexport interface RequestLogSnapshot {\n timestamp: string;\n traceId: string;\n spanId: string;\n correlationId: string;\n context: Record<string, unknown>;\n}\n\nexport interface RequestLoggerOptions {\n /** Callback invoked by emitNow() for manual fan-out. */\n onEmit?: (snapshot: RequestLogSnapshot) => void | Promise<void>;\n}\n\n/**\n * Optional lifecycle hooks for adapters that need to track child loggers\n * spawned by `log.fork()` (e.g. active logger maps in framework integrations).\n */\nexport interface ForkLifecycle {\n /** Called after the child logger is created, before `fn` runs. */\n onChildEnter?: (child: RequestLogger) => void;\n /** Called after the child has finished (emit + drain), success or failure. */\n onChildExit?: (child: RequestLogger) => void;\n}\n\nexport interface ForkOptions {\n lifecycle?: ForkLifecycle;\n}\n\nfunction resolveContext(ctx?: TraceContext): TraceContext {\n if (ctx) return ctx;\n\n const stored = requestContextStore.getStore();\n if (stored) return stored;\n\n const span = otelTrace.getActiveSpan();\n if (!span) {\n throw new Error(\n '[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext().',\n );\n }\n return createTraceContext(span);\n}\n\nexport function getRequestLogger(\n ctx?: TraceContext,\n options?: RequestLoggerOptions,\n): RequestLogger {\n const activeContext = resolveContext(ctx);\n const contextState: Record<string, unknown> = {};\n let emitted = false;\n let lastSnapshot: RequestLogSnapshot | null = null;\n\n const addLogEvent = (\n level: 'info' | 'warn' | 'error',\n message: string,\n fields?: Record<string, unknown>,\n ) => {\n const attrs = fields ? flattenToAttributes(fields) : undefined;\n emitCorrelatedEvent(activeContext, `log.${level}`, {\n message,\n ...attrs,\n });\n };\n\n const sealCheck = (method: string, keys: string[]): void => {\n if (emitted) {\n warnPostEmit(\n method,\n `Keys dropped: ${keys.length > 0 ? keys.join(', ') : '(empty)'}.`,\n );\n }\n };\n\n return {\n set(fields: Record<string, unknown>) {\n sealCheck('log.set()', Object.keys(fields));\n if (emitted) return;\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n },\n\n info(message: string, fields?: Record<string, unknown>) {\n const keys = fields\n ? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]\n : ['message'];\n sealCheck('log.info()', keys);\n if (emitted) return;\n addLogEvent('info', message, fields);\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n },\n\n warn(message: string, fields?: Record<string, unknown>) {\n const keys = fields\n ? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]\n : ['message'];\n sealCheck('log.warn()', keys);\n if (emitted) return;\n addLogEvent('warn', message, fields);\n activeContext.setAttribute('autotel.log.level', 'warn');\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n },\n\n error(error: Error | string, fields?: Record<string, unknown>) {\n const keys = fields ? [...Object.keys(fields), 'error'] : ['error'];\n sealCheck('log.error()', keys);\n if (emitted) return;\n const err = typeof error === 'string' ? new Error(error) : error;\n recordStructuredError(activeContext, err);\n addLogEvent('error', err.message, fields);\n\n if (fields) {\n mergeInto(contextState, fields);\n activeContext.setAttributes(flattenToAttributes(fields));\n }\n activeContext.setAttribute('autotel.log.level', 'error');\n },\n\n getContext() {\n return { ...contextState };\n },\n\n emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot {\n if (emitted) {\n warnPostEmit('log.emitNow()', 'Ignoring duplicate emit.');\n return lastSnapshot as RequestLogSnapshot;\n }\n\n const mergedContext = {\n ...contextState,\n ...overrides,\n };\n const flattened = flattenToAttributes(mergedContext);\n activeContext.setAttributes(flattened);\n\n const snapshot: RequestLogSnapshot = {\n timestamp: new Date().toISOString(),\n traceId: activeContext.traceId,\n spanId: activeContext.spanId,\n correlationId: activeContext.correlationId,\n context: mergedContext,\n };\n\n emitCorrelatedEvent(activeContext, 'log.emit.manual', {\n ...flattened,\n });\n\n if (options?.onEmit) {\n Promise.resolve(options.onEmit(snapshot)).catch((error) => {\n console.warn('[autotel] request logger onEmit failed:', error);\n });\n }\n\n emitted = true;\n lastSnapshot = snapshot;\n return snapshot;\n },\n\n fork(\n label: string,\n fn: () => void | Promise<void>,\n forkOptions?: ForkOptions,\n ): void {\n const parentRequestId = activeContext.correlationId;\n if (typeof parentRequestId !== 'string' || parentRequestId.length === 0) {\n throw new Error(\n '[autotel] log.fork() requires the parent logger to have a correlationId. ' +\n 'Ensure the request was created by autotel middleware.',\n );\n }\n\n const tracer = otelTrace.getTracer('autotel.request-logger');\n const lifecycle = forkOptions?.lifecycle;\n void tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {\n const childContext: TraceContext = {\n ...createTraceContext(childSpan),\n correlationId: crypto.randomUUID(),\n };\n\n requestContextStore.run(childContext, () => {\n const childLog = getRequestLogger(childContext);\n childLog.set({\n operation: label,\n _parentCorrelationId: parentRequestId,\n });\n\n lifecycle?.onChildEnter?.(childLog);\n\n void Promise.resolve()\n .then(() => fn())\n .then(() => {\n childLog.emitNow();\n })\n .catch((error_: unknown) => {\n const error =\n error_ instanceof Error ? error_ : new Error(String(error_));\n childLog.error(error);\n childLog.emitNow();\n })\n .finally(() => {\n try {\n lifecycle?.onChildExit?.(childLog);\n } catch (hookError) {\n console.warn(\n '[autotel] fork onChildExit hook threw:',\n hookError,\n );\n }\n childSpan.end();\n });\n });\n });\n },\n };\n}\n\n/**\n * Returns `true` when a request-logger context can be resolved without throwing —\n * i.e. an explicit `ctx` was provided, a `runWithRequestContext()` scope is active,\n * or there is an active OpenTelemetry span.\n *\n * Use this to branch on observability availability instead of wrapping\n * {@link getRequestLogger} in try/catch.\n */\nexport function hasRequestContext(ctx?: TraceContext): boolean {\n if (ctx) return true;\n if (requestContextStore.getStore()) return true;\n return otelTrace.getActiveSpan() != null;\n}\n\n/**\n * Like {@link getRequestLogger}, but returns `null` instead of throwing when no\n * request context is available. Intended for best-effort instrumentation where a\n * missing telemetry context must never crash business logic.\n */\nexport function getRequestLoggerSafe(\n ctx?: TraceContext,\n options?: RequestLoggerOptions,\n): RequestLogger | null {\n if (!hasRequestContext(ctx)) return null;\n return getRequestLogger(ctx, options);\n}\n\n/**\n * A no-op {@link RequestLogger} whose methods do nothing. Used as a fallback by\n * best-effort instrumentation so wrapped handlers can run un-instrumented without\n * branching on logger presence.\n */\nexport function createNoopRequestLogger(): RequestLogger {\n const snapshot = (): RequestLogSnapshot => ({\n timestamp: new Date().toISOString(),\n traceId: '',\n spanId: '',\n correlationId: '',\n context: {},\n });\n\n return {\n set() {},\n info() {},\n warn() {},\n error() {},\n getContext() {\n return {};\n },\n emitNow() {\n return snapshot();\n },\n fork(_label, fn) {\n void Promise.resolve().then(() => fn());\n },\n };\n}\n","/**\n * Typed error and audit catalogs.\n *\n * Group related errors into one catalog and get a refactor-safe builder per\n * code, with autocomplete at every call site and typed message parameters.\n *\n * @example\n * ```typescript\n * import { defineErrorCatalog } from 'autotel';\n *\n * export const billing = defineErrorCatalog('billing', {\n * PAYMENT_DECLINED: {\n * status: 402,\n * message: 'Card declined',\n * why: 'The issuer rejected the charge',\n * fix: 'Try a different payment method',\n * },\n * INSUFFICIENT_FUNDS: {\n * status: 402,\n * message: ({ available, required }: { available: number; required: number }) =>\n * `Insufficient funds: $${available} of $${required}`,\n * },\n * });\n *\n * throw billing.PAYMENT_DECLINED({ cause: stripeError });\n * throw billing.INSUFFICIENT_FUNDS({ available: 5, required: 100 });\n *\n * // In a catch block — refactor-safe, no magic strings:\n * if (billing.PAYMENT_DECLINED.match(err)) { ... }\n * ```\n */\n\nimport {\n createStructuredError,\n type StructuredError,\n} from './structured-error';\n\nconst catalogCodeKey = Symbol.for('autotel.catalog.code');\n\n/** Definition of a single error in a catalog. */\nexport interface ErrorCatalogEntry {\n /**\n * Human-readable message. Use a function to interpolate typed parameters;\n * the parameter type flows through to the call site.\n */\n message: string | ((params: never) => string);\n /** HTTP status to surface to clients. */\n status?: number;\n /** Stable error code. Defaults to `${namespace}.${KEY}`. */\n code?: string | number;\n /** Why it happened. A function receives the same params as `message`. */\n why?: string | ((params: never) => string);\n /** What the caller should do next. */\n fix?: string;\n /** Docs or runbook link. */\n link?: string;\n /** Error name. Defaults to the catalog key. */\n name?: string;\n}\n\n/** Per-call options passed alongside (or instead of) typed params. */\nexport interface ErrorBuildOptions {\n cause?: unknown;\n details?: Record<string, unknown>;\n /** Backend-only context. Never serialized to clients. */\n internal?: Record<string, unknown>;\n}\n\ntype ParamsOf<E> = E extends { message: (params: infer P) => string }\n ? P\n : E extends { why: (params: infer P) => string }\n ? P\n : void;\n\ntype BuilderArgs<E extends ErrorCatalogEntry> =\n ParamsOf<E> extends void\n ? [options?: ErrorBuildOptions]\n : [params: ParamsOf<E>, options?: ErrorBuildOptions];\n\n/** A callable error factory produced by {@link defineErrorCatalog}. */\nexport interface ErrorBuilder<E extends ErrorCatalogEntry> {\n (...args: BuilderArgs<E>): StructuredError;\n /** Stable code assigned to every error from this entry. */\n readonly code: string | number;\n /** True when `error` was produced by this catalog entry. */\n match(error: unknown): boolean;\n}\n\nexport type ErrorCatalog<T extends Record<string, ErrorCatalogEntry>> = {\n readonly [K in keyof T]: ErrorBuilder<T[K]>;\n};\n\nfunction readCatalogCode(error: unknown): string | number | undefined {\n if (error === null || typeof error !== 'object') return undefined;\n return (error as Record<symbol, unknown>)[catalogCodeKey] as\n string | number | undefined;\n}\n\n/** True when `error` was produced by any autotel error catalog. */\nexport function isCatalogError(error: unknown): error is StructuredError {\n return readCatalogCode(error) !== undefined;\n}\n\n/** Returns the catalog code of `error`, or `undefined` if it has none. */\nexport function getCatalogCode(error: unknown): string | number | undefined {\n return readCatalogCode(error);\n}\n\n/**\n * Define a typed error catalog. Returns an object whose keys are error\n * builders. Each builder produces a {@link StructuredError} carrying the\n * entry's message, status, code, why, fix, and link.\n */\nexport function defineErrorCatalog<\n const T extends Record<string, ErrorCatalogEntry>,\n>(namespace: string, entries: T): ErrorCatalog<T> {\n const catalog: Record<string, ErrorBuilder<ErrorCatalogEntry>> = {};\n\n for (const [key, entry] of Object.entries(entries) as [\n string,\n ErrorCatalogEntry,\n ][]) {\n const code = entry.code ?? `${namespace}.${key}`;\n const usesParams =\n typeof entry.message === 'function' || typeof entry.why === 'function';\n\n const builder = ((\n paramsOrOptions?: unknown,\n maybeOptions?: ErrorBuildOptions,\n ): StructuredError => {\n const params = usesParams ? paramsOrOptions : undefined;\n const options = (usesParams ? maybeOptions : paramsOrOptions) as\n ErrorBuildOptions | undefined;\n\n const message =\n typeof entry.message === 'function'\n ? (entry.message as (p: unknown) => string)(params)\n : entry.message;\n const why =\n typeof entry.why === 'function'\n ? (entry.why as (p: unknown) => string)(params)\n : entry.why;\n\n const error = createStructuredError({\n message,\n name: entry.name ?? key,\n code,\n ...(entry.status === undefined ? {} : { status: entry.status }),\n ...(why === undefined ? {} : { why }),\n ...(entry.fix === undefined ? {} : { fix: entry.fix }),\n ...(entry.link === undefined ? {} : { link: entry.link }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n ...(options?.details === undefined ? {} : { details: options.details }),\n ...(options?.internal === undefined\n ? {}\n : { internal: options.internal }),\n });\n\n Object.defineProperty(error, catalogCodeKey, {\n value: code,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n\n return error;\n }) as ErrorBuilder<ErrorCatalogEntry>;\n\n Object.defineProperty(builder, 'code', {\n value: code,\n enumerable: true,\n });\n Object.defineProperty(builder, 'match', {\n value: (error: unknown): boolean => readCatalogCode(error) === code,\n enumerable: false,\n });\n\n catalog[key] = builder;\n }\n\n return Object.freeze(catalog) as ErrorCatalog<T>;\n}\n\n/** Severity of an audit action. */\nexport type AuditSeverity = 'info' | 'warn' | 'critical';\n\n/** Definition of a single action in an audit catalog. */\nexport interface AuditCatalogEntry {\n /** Human-readable description. Use a function for typed params. */\n message?: string | ((params: never) => string);\n /** Stable action name. Defaults to `${namespace}.${KEY}`. */\n action?: string;\n /** Severity of the action. Defaults to `'info'`. */\n severity?: AuditSeverity;\n}\n\n/** A resolved audit action descriptor produced by an audit catalog. */\nexport interface AuditAction {\n readonly action: string;\n readonly severity: AuditSeverity;\n readonly message?: string;\n}\n\ntype AuditDescriptorArgs<E extends AuditCatalogEntry> =\n ParamsOf<E> extends void ? [] : [params: ParamsOf<E>];\n\n/** A callable audit-action descriptor produced by {@link defineAuditCatalog}. */\nexport interface AuditDescriptor<E extends AuditCatalogEntry> {\n (...args: AuditDescriptorArgs<E>): AuditAction;\n readonly action: string;\n readonly severity: AuditSeverity;\n}\n\nexport type AuditCatalog<T extends Record<string, AuditCatalogEntry>> = {\n readonly [K in keyof T]: AuditDescriptor<T[K]>;\n};\n\n/**\n * Define a typed audit catalog. Returns typed action descriptors you can pass\n * to `track()` or audit helpers without scattering magic strings.\n */\nexport function defineAuditCatalog<\n const T extends Record<string, AuditCatalogEntry>,\n>(namespace: string, entries: T): AuditCatalog<T> {\n const catalog: Record<string, AuditDescriptor<AuditCatalogEntry>> = {};\n\n for (const [key, entry] of Object.entries(entries) as [\n string,\n AuditCatalogEntry,\n ][]) {\n const action = entry.action ?? `${namespace}.${key}`;\n const severity: AuditSeverity = entry.severity ?? 'info';\n\n const descriptor = ((params?: unknown): AuditAction => {\n const message =\n typeof entry.message === 'function'\n ? (entry.message as (p: unknown) => string)(params)\n : entry.message;\n return Object.freeze({\n action,\n severity,\n ...(message === undefined ? {} : { message }),\n });\n }) as AuditDescriptor<AuditCatalogEntry>;\n\n Object.defineProperty(descriptor, 'action', {\n value: action,\n enumerable: true,\n });\n Object.defineProperty(descriptor, 'severity', {\n value: severity,\n enumerable: true,\n });\n\n catalog[key] = descriptor;\n }\n\n return Object.freeze(catalog) as AuditCatalog<T>;\n}\n","export interface DrainOptions<TContext, TConfig, TPayload = TContext> {\n /** Stable identifier used in error logs. */\n name: string;\n /** Return null to skip draining (e.g. missing API key in dev). */\n resolve: () => TConfig | null | Promise<TConfig | null>;\n /** Transform contexts into payloads. Defaults to identity. */\n transform?: (contexts: TContext[]) => TPayload[];\n /** Transport implementation. */\n send: (payloads: TPayload[], config: TConfig) => Promise<void>;\n}\n\nexport interface HttpDrainRequest {\n url: string;\n headers: Record<string, string>;\n body: string;\n}\n\nexport interface HttpDrainOptions<\n TContext,\n TConfig,\n TPayload = TContext,\n> extends Omit<DrainOptions<TContext, TConfig, TPayload>, 'send'> {\n encode: (payloads: TPayload[], config: TConfig) => HttpDrainRequest | null;\n timeoutMs?: number;\n retries?: number;\n resolveTimeoutMs?: (config: TConfig) => number | undefined;\n resolveRetries?: (config: TConfig) => number | undefined;\n}\n\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_RETRIES = 2;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nasync function postWithRetry(options: {\n name: string;\n request: HttpDrainRequest;\n timeoutMs: number;\n retries: number;\n}): Promise<void> {\n const { name, request, timeoutMs, retries } = options;\n const attempts = Math.max(1, retries);\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n timeout.unref?.();\n try {\n const response = await fetch(request.url, {\n method: 'POST',\n headers: request.headers,\n body: request.body,\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new Error(\n `[autotel/${name}] HTTP ${response.status} draining ${request.url}`,\n );\n }\n return;\n } catch (error) {\n lastError = error;\n if (attempt < attempts) {\n await delay(100 * attempt);\n }\n } finally {\n clearTimeout(timeout);\n }\n }\n\n throw lastError;\n}\n\nexport function defineDrain<TContext, TConfig, TPayload = TContext>(\n options: DrainOptions<TContext, TConfig, TPayload>,\n): (ctx: TContext | TContext[]) => Promise<void> {\n return async (ctx: TContext | TContext[]) => {\n const contexts = Array.isArray(ctx) ? ctx : [ctx];\n if (contexts.length === 0) return;\n\n const config = await options.resolve();\n if (!config) return;\n\n const payloads = options.transform\n ? options.transform(contexts)\n : (contexts as unknown as TPayload[]);\n\n if (payloads.length === 0) return;\n\n try {\n await options.send(payloads, config);\n } catch (error) {\n console.error(`[autotel/${options.name}] drain failed:`, error);\n }\n };\n}\n\nexport function defineHttpDrain<TContext, TConfig, TPayload = TContext>(\n options: HttpDrainOptions<TContext, TConfig, TPayload>,\n): (ctx: TContext | TContext[]) => Promise<void> {\n return defineDrain<TContext, TConfig, TPayload>({\n name: options.name,\n resolve: options.resolve,\n transform: options.transform,\n send: async (payloads, config) => {\n const request = options.encode(payloads, config);\n if (!request) return;\n const timeoutMs =\n options.resolveTimeoutMs?.(config) ??\n options.timeoutMs ??\n DEFAULT_TIMEOUT_MS;\n const retries =\n options.resolveRetries?.(config) ?? options.retries ?? DEFAULT_RETRIES;\n\n await postWithRetry({\n name: options.name,\n request,\n timeoutMs,\n retries,\n });\n },\n });\n}\n","export interface EnrichContext<TEvent extends Record<string, unknown>> {\n event: TEvent;\n request?: {\n method?: string;\n path?: string;\n requestId?: string;\n };\n response?: {\n status?: number;\n };\n headers?: Record<string, string>;\n}\n\nexport interface EnricherDefinition<\n TEvent extends Record<string, unknown>,\n TValue extends object,\n> {\n /** Stable identifier used in error logs. */\n name: string;\n /** Top-level field to merge computed values into. */\n field: keyof TEvent & string;\n /** Return undefined to skip enrichment. */\n compute: (ctx: EnrichContext<TEvent>) => TValue | undefined;\n}\n\nexport interface EnricherOptions {\n /** Replace existing field value instead of merge. Default false. */\n overwrite?: boolean;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key in source) {\n const sourceVal = source[key];\n if (sourceVal === undefined) continue;\n const targetVal = target[key];\n if (isPlainObject(sourceVal) && isPlainObject(targetVal)) {\n mergeInto(targetVal, sourceVal);\n } else {\n target[key] = sourceVal;\n }\n }\n}\n\nexport function defineEnricher<\n TEvent extends Record<string, unknown>,\n TValue extends object,\n>(\n def: EnricherDefinition<TEvent, TValue>,\n options: EnricherOptions = {},\n): (ctx: EnrichContext<TEvent>) => void {\n return (ctx: EnrichContext<TEvent>) => {\n let computed: TValue | undefined;\n try {\n computed = def.compute(ctx);\n } catch (error) {\n console.error(`[autotel/${def.name}] enrich failed:`, error);\n return;\n }\n\n if (!computed) return;\n\n if (options.overwrite || !isPlainObject(ctx.event[def.field])) {\n (ctx.event as Record<string, unknown>)[def.field] = computed;\n return;\n }\n\n mergeInto(\n ctx.event[def.field] as unknown as Record<string, unknown>,\n computed as unknown as Record<string, unknown>,\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;CAElB,yBACEA,yBAAa,wBAAwB,KAAKA,wBA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