autotel 2.25.2 → 2.25.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +152 -1
  2. package/dist/attributes.d.cts +2 -2
  3. package/dist/attributes.d.ts +2 -2
  4. package/dist/auto.cjs +6 -6
  5. package/dist/auto.js +4 -4
  6. package/dist/{chunk-QUW4I2OI.js → chunk-3ZLYWPMY.js} +3 -3
  7. package/dist/{chunk-QUW4I2OI.js.map → chunk-3ZLYWPMY.js.map} +1 -1
  8. package/dist/{chunk-BGVKKL2N.cjs → chunk-7FIGORWI.cjs} +46 -2
  9. package/dist/chunk-7FIGORWI.cjs.map +1 -0
  10. package/dist/{chunk-MNMLCLHH.cjs → chunk-AQXPGGQK.cjs} +5 -5
  11. package/dist/{chunk-MNMLCLHH.cjs.map → chunk-AQXPGGQK.cjs.map} +1 -1
  12. package/dist/{chunk-4KGC5N3J.cjs → chunk-FXKB7EPR.cjs} +13 -13
  13. package/dist/{chunk-4KGC5N3J.cjs.map → chunk-FXKB7EPR.cjs.map} +1 -1
  14. package/dist/{chunk-4SCBD22Z.js → chunk-IFKDBL65.js} +3 -3
  15. package/dist/{chunk-4SCBD22Z.js.map → chunk-IFKDBL65.js.map} +1 -1
  16. package/dist/{chunk-JVICEM6W.cjs → chunk-ITYASFHQ.cjs} +91 -19
  17. package/dist/chunk-ITYASFHQ.cjs.map +1 -0
  18. package/dist/{chunk-IKRHEUS7.js → chunk-JM63D22M.js} +10 -10
  19. package/dist/{chunk-IKRHEUS7.js.map → chunk-JM63D22M.js.map} +1 -1
  20. package/dist/{chunk-GVLK7YUU.cjs → chunk-KZEC4CHV.cjs} +6 -4
  21. package/dist/chunk-KZEC4CHV.cjs.map +1 -0
  22. package/dist/{chunk-VXLEJWLY.js → chunk-MNBAXRVG.js} +89 -17
  23. package/dist/chunk-MNBAXRVG.js.map +1 -0
  24. package/dist/{chunk-6YIDHH2S.cjs → chunk-OFPZULMQ.cjs} +32 -10
  25. package/dist/chunk-OFPZULMQ.cjs.map +1 -0
  26. package/dist/{chunk-UKUYBUFQ.cjs → chunk-OWXXS4JB.cjs} +7 -7
  27. package/dist/{chunk-UKUYBUFQ.cjs.map → chunk-OWXXS4JB.cjs.map} +1 -1
  28. package/dist/{chunk-77PLEJ54.js → chunk-PKXD2RMI.js} +4 -4
  29. package/dist/{chunk-77PLEJ54.js.map → chunk-PKXD2RMI.js.map} +1 -1
  30. package/dist/{chunk-RWOVNF3V.cjs → chunk-RMGSBMQF.cjs} +36 -36
  31. package/dist/chunk-RMGSBMQF.cjs.map +1 -0
  32. package/dist/{chunk-YTGF4L2C.js → chunk-RUD7KS4R.js} +27 -5
  33. package/dist/chunk-RUD7KS4R.js.map +1 -0
  34. package/dist/{chunk-KUSYIHW7.js → chunk-VVYSQXQL.js} +3 -3
  35. package/dist/{chunk-KUSYIHW7.js.map → chunk-VVYSQXQL.js.map} +1 -1
  36. package/dist/{chunk-XND7WBVX.js → chunk-VYA6QDNA.js} +43 -3
  37. package/dist/chunk-VYA6QDNA.js.map +1 -0
  38. package/dist/{chunk-L627YSSP.cjs → chunk-WOWTZ4EB.cjs} +9 -9
  39. package/dist/{chunk-L627YSSP.cjs.map → chunk-WOWTZ4EB.cjs.map} +1 -1
  40. package/dist/{chunk-X4RMFFMR.js → chunk-XDKK53OL.js} +6 -4
  41. package/dist/chunk-XDKK53OL.js.map +1 -0
  42. package/dist/decorators.cjs +5 -5
  43. package/dist/decorators.js +5 -5
  44. package/dist/event.cjs +8 -8
  45. package/dist/event.js +5 -5
  46. package/dist/functional.cjs +12 -12
  47. package/dist/functional.js +5 -5
  48. package/dist/index.cjs +71 -51
  49. package/dist/index.d.cts +4 -4
  50. package/dist/index.d.ts +4 -4
  51. package/dist/index.js +13 -13
  52. package/dist/{init-Q4uIQKbq.d.cts → init-CIzpC5kZ.d.cts} +9 -2
  53. package/dist/{init-ls4xSZe5.d.ts → init-C_PiC_Su.d.ts} +9 -2
  54. package/dist/instrumentation.cjs +12 -12
  55. package/dist/instrumentation.cjs.map +1 -1
  56. package/dist/instrumentation.js +4 -4
  57. package/dist/instrumentation.js.map +1 -1
  58. package/dist/messaging-adapters.d.cts +1 -1
  59. package/dist/messaging-adapters.d.ts +1 -1
  60. package/dist/messaging.cjs +9 -9
  61. package/dist/messaging.d.cts +1 -1
  62. package/dist/messaging.d.ts +1 -1
  63. package/dist/messaging.js +6 -6
  64. package/dist/metric-helpers.d.cts +1 -1
  65. package/dist/metric-helpers.d.ts +1 -1
  66. package/dist/sampling.cjs +26 -10
  67. package/dist/sampling.d.cts +49 -1
  68. package/dist/sampling.d.ts +49 -1
  69. package/dist/sampling.js +1 -1
  70. package/dist/semantic-helpers.cjs +10 -10
  71. package/dist/semantic-helpers.js +6 -6
  72. package/dist/tail-sampling-processor.cjs +6 -2
  73. package/dist/tail-sampling-processor.d.cts +2 -2
  74. package/dist/tail-sampling-processor.d.ts +2 -2
  75. package/dist/tail-sampling-processor.js +5 -1
  76. package/dist/trace-helpers.d.cts +1 -1
  77. package/dist/trace-helpers.d.ts +1 -1
  78. package/dist/{utils-D1trOLNm.d.ts → utils-Buel3cj0.d.ts} +1 -1
  79. package/dist/{utils-DuNJfXSH.d.cts → utils-CbUkl8r1.d.cts} +1 -1
  80. package/dist/webhook.cjs +6 -6
  81. package/dist/webhook.js +5 -5
  82. package/dist/workflow-distributed.cjs +7 -7
  83. package/dist/workflow-distributed.js +5 -5
  84. package/dist/workflow.cjs +10 -10
  85. package/dist/workflow.js +6 -6
  86. package/dist/yaml-config.cjs +5 -5
  87. package/dist/yaml-config.d.cts +5 -4
  88. package/dist/yaml-config.d.ts +5 -4
  89. package/dist/yaml-config.js +2 -2
  90. package/package.json +1 -1
  91. package/src/env-config.test.ts +77 -0
  92. package/src/env-config.ts +106 -0
  93. package/src/functional.ts +13 -7
  94. package/src/index.ts +6 -0
  95. package/src/init.customization.test.ts +61 -0
  96. package/src/init.integrations.test.ts +6 -1
  97. package/src/init.ts +23 -13
  98. package/src/instrumentation.ts +1 -1
  99. package/src/sampling.test.ts +96 -3
  100. package/src/sampling.ts +90 -0
  101. package/src/tail-sampling-processor.test.ts +26 -22
  102. package/src/tail-sampling-processor.ts +8 -4
  103. package/src/yaml-config.test.ts +71 -0
  104. package/src/yaml-config.ts +32 -2
  105. package/dist/chunk-6YIDHH2S.cjs.map +0 -1
  106. package/dist/chunk-BGVKKL2N.cjs.map +0 -1
  107. package/dist/chunk-GVLK7YUU.cjs.map +0 -1
  108. package/dist/chunk-JVICEM6W.cjs.map +0 -1
  109. package/dist/chunk-RWOVNF3V.cjs.map +0 -1
  110. package/dist/chunk-VXLEJWLY.js.map +0 -1
  111. package/dist/chunk-X4RMFFMR.js.map +0 -1
  112. package/dist/chunk-XND7WBVX.js.map +0 -1
  113. package/dist/chunk-YTGF4L2C.js.map +0 -1
package/README.md CHANGED
@@ -36,6 +36,12 @@ Replace `NODE_OPTIONS` and 30+ lines of SDK boilerplate with `init()`, wrap func
36
36
  - [LLM Observability with OpenLLMetry](#llm-observability-with-openllmetry)
37
37
  - [Installation](#installation)
38
38
  - [Usage](#usage)
39
+ - [Sampling](#sampling)
40
+ - [Preset Shorthand](#preset-shorthand)
41
+ - [Tuned Presets](#tuned-presets)
42
+ - [YAML Configuration](#yaml-configuration)
43
+ - [Precedence Rules](#precedence-rules)
44
+ - [Tail-Sampling Attributes](#tail-sampling-attributes)
39
45
  - [Core Building Blocks](#core-building-blocks)
40
46
  - [trace()](#trace)
41
47
  - [span()](#span)
@@ -163,6 +169,14 @@ Defaults:
163
169
  - Version: auto-detected from `package.json`
164
170
  - Events auto-flush when the root span finishes
165
171
 
172
+ Sampling presets:
173
+
174
+ - Simple path: `sampling: 'development' | 'errors-only' | 'production' | 'off'`
175
+ - Advanced path: `samplingPresets.development()`, `samplingPresets.errorsOnly()`, `samplingPresets.production({...})`, `samplingPresets.off()`
176
+ - Precedence is always `sampler > sampling > default`
177
+ - If you use YAML `sampling.preset`, extra tuning fields in that same block are ignored. Use the programmatic API with `sampler` or `samplingPresets.production({...})` when you need overrides.
178
+ - Tail-sampling hint attributes use the `autotel.*` namespace, for example `autotel.sampling.tail.keep`. This is intentional: OpenTelemetry does not define an official semantic-convention key for these internal hints, so autotel uses library-prefixed custom attributes rather than inventing fake `otel.*` semconv keys.
179
+
166
180
  ### 3. Instrument code with `trace()`
167
181
 
168
182
  ```typescript
@@ -322,6 +336,122 @@ All LLM spans will appear alongside your application traces in your observabilit
322
336
  - Evaluation loops
323
337
  - Working examples in `apps/example-ai-agent`
324
338
 
339
+ ## Sampling
340
+
341
+ Autotel defaults to production-ready adaptive sampling: a 10% baseline, with errors and slow requests kept automatically.
342
+
343
+ ### Preset Shorthand
344
+
345
+ Use the `sampling` field on `init()` when you want the shortest path:
346
+
347
+ ```typescript
348
+ import { init } from 'autotel';
349
+
350
+ init({
351
+ service: 'checkout-api',
352
+ sampling: 'production',
353
+ });
354
+ ```
355
+
356
+ Available string presets:
357
+
358
+ - `'development'`: keep everything
359
+ - `'errors-only'`: drop healthy baseline traffic, keep errors
360
+ - `'production'`: 10% baseline plus errors and slow traces
361
+ - `'off'`: disable sampling entirely
362
+
363
+ String presets intentionally use kebab-case. For example, the string form is `sampling: 'errors-only'`.
364
+
365
+ ### Tuned Presets
366
+
367
+ Use `samplingPresets` when you want preset behavior with tuned thresholds or rates:
368
+
369
+ ```typescript
370
+ import { init, samplingPresets } from 'autotel';
371
+
372
+ init({
373
+ service: 'checkout-api',
374
+ sampler: samplingPresets.production({
375
+ baselineSampleRate: 0.05,
376
+ slowThresholdMs: 500,
377
+ }),
378
+ });
379
+ ```
380
+
381
+ Factory names intentionally use JavaScript-style camelCase. For example, the factory form is `samplingPresets.errorsOnly()`.
382
+
383
+ ### YAML Configuration
384
+
385
+ Use `sampling.preset` for the simple YAML path:
386
+
387
+ ```yaml
388
+ sampling:
389
+ preset: production
390
+ ```
391
+
392
+ If you need tuned sampling in YAML today, prefer the explicit sampler config block:
393
+
394
+ ```yaml
395
+ sampling:
396
+ type: adaptive
397
+ baseline_rate: 0.05
398
+ always_sample_errors: true
399
+ always_sample_slow: true
400
+ slow_threshold_ms: 500
401
+ ```
402
+
403
+ When `sampling.preset` is set, other keys in the same YAML sampling block are ignored and autotel will warn. Use the programmatic API with `sampler` or `samplingPresets.production({...})` for tuned presets.
404
+
405
+ ### Precedence Rules
406
+
407
+ Sampling always resolves in this order:
408
+
409
+ ```text
410
+ sampler > sampling > default
411
+ ```
412
+
413
+ That means:
414
+
415
+ - `sampler` always wins if you provide both
416
+ - `sampling` is the simple preset shorthand
417
+ - OpenTelemetry env vars such as `OTEL_TRACES_SAMPLER` are used after explicit config and YAML
418
+ - default behavior is `samplingPresets.production()`
419
+
420
+ Example:
421
+
422
+ ```typescript
423
+ import { init, NeverSampler } from 'autotel';
424
+
425
+ init({
426
+ service: 'checkout-api',
427
+ sampler: new NeverSampler(),
428
+ sampling: 'development', // ignored because sampler wins
429
+ });
430
+ ```
431
+
432
+ For OpenTelemetry SDK compatibility, autotel also reads `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`.
433
+
434
+ Supported values:
435
+
436
+ - `always_on`
437
+ - `always_off`
438
+ - `traceidratio`
439
+ - `parentbased_always_on`
440
+ - `parentbased_always_off`
441
+ - `parentbased_traceidratio`
442
+
443
+ Currently unsupported and ignored with an error log:
444
+
445
+ - `jaeger_remote`
446
+ - `parentbased_jaeger_remote`
447
+ - `xray`
448
+
449
+ ### Tail-Sampling Attributes
450
+
451
+ Autotel uses internal span attributes such as `autotel.sampling.tail.keep` and `autotel.sampling.tail.evaluated` to communicate tail-sampling decisions.
452
+
453
+ These use the `autotel.*` namespace intentionally. OpenTelemetry does not define an official semantic-convention key for these internal hints, so autotel uses library-prefixed custom attributes rather than inventing fake `otel.*` semantic convention keys.
454
+
325
455
  ## Core Building Blocks
326
456
 
327
457
  ### trace()
@@ -1851,7 +1981,8 @@ init({
1851
1981
  endpoint?: string;
1852
1982
  protocol?: 'http' | 'grpc'; // OTLP protocol (default: 'http')
1853
1983
  metrics?: boolean | 'auto';
1854
- sampler?: Sampler;
1984
+ sampler?: Sampler; // explicit sampler, highest precedence
1985
+ sampling?: 'development' | 'errors-only' | 'production' | 'off'; // preset shorthand
1855
1986
  version?: string;
1856
1987
  environment?: string;
1857
1988
  baggage?: boolean | string; // Auto-copy baggage to span attributes
@@ -1875,6 +2006,26 @@ init({
1875
2006
  });
1876
2007
  ```
1877
2008
 
2009
+ **Sampling Configuration:**
2010
+
2011
+ ```typescript
2012
+ import { init, samplingPresets } from 'autotel';
2013
+
2014
+ init({
2015
+ service: 'my-app',
2016
+ sampling: 'production',
2017
+ });
2018
+
2019
+ init({
2020
+ service: 'my-app',
2021
+ sampler: samplingPresets.production({ baselineSampleRate: 0.05 }),
2022
+ });
2023
+ ```
2024
+
2025
+ - Use `sampling` for the simple preset path.
2026
+ - Use `sampler` for advanced customization.
2027
+ - Precedence is always `sampler > sampling > default`.
2028
+
1878
2029
  **Event Subscribers:**
1879
2030
 
1880
2031
  Configure event subscribers globally to send product events to PostHog, Mixpanel, Amplitude, etc.:
@@ -1,5 +1,5 @@
1
- import { U as UserAttrs, S as SessionAttrs, A as AttributePolicy } from './utils-DuNJfXSH.cjs';
2
- export { p as AttributeGuardrails, J as ClientAttrs, C as CloudAttrs, Q as CodeAttrs, z as ContainerAttrs, t as DBAttrs, L as DeploymentAttrs, D as DeviceAttrs, E as ErrorAttrs, V as ExceptionAttrs, B as FaaSAttrs, F as FeatureFlagAttrs, G as GenAIAttrs, I as GraphQLAttrs, q as HTTPClientAttrs, H as HTTPServerAttrs, K as K8sAttrs, M as MessagingAttrs, N as NetworkAttrs, O as OTelAttrs, P as PeerAttrs, y as ProcessAttrs, R as RPCAttrs, w as ServerAddressAttrs, u as ServiceAttrs, W as TLSAttrs, T as ThreadAttrs, x as URLAttrs, a as attrs, n as autoRedactPII, l as checkDeprecatedAttribute, e as dbClient, o as defaultGuardrails, d as httpClient, h as httpServer, i as identify, j as mergeAttrs, m as mergeServiceResource, r as request, k as safeSetAttributes, c as setDevice, f as setError, g as setException, b as setSession, s as setUser, v as validateAttribute } from './utils-DuNJfXSH.cjs';
1
+ import { U as UserAttrs, S as SessionAttrs, A as AttributePolicy } from './utils-CbUkl8r1.cjs';
2
+ export { a as AttributeGuardrails, C as ClientAttrs, b as CloudAttrs, c as CodeAttrs, d as ContainerAttrs, D as DBAttrs, e as DeploymentAttrs, f as DeviceAttrs, E as ErrorAttrs, g as ExceptionAttrs, F as FaaSAttrs, h as FeatureFlagAttrs, G as GenAIAttrs, i as GraphQLAttrs, H as HTTPClientAttrs, j as HTTPServerAttrs, K as K8sAttrs, M as MessagingAttrs, N as NetworkAttrs, O as OTelAttrs, P as PeerAttrs, k as ProcessAttrs, R as RPCAttrs, l as ServerAddressAttrs, m as ServiceAttrs, T as TLSAttrs, n as ThreadAttrs, o as URLAttrs, p as attrs, q as autoRedactPII, r as checkDeprecatedAttribute, s as dbClient, t as defaultGuardrails, u as httpClient, v as httpServer, w as identify, x as mergeAttrs, y as mergeServiceResource, z as request, B as safeSetAttributes, I as setDevice, J as setError, L as setException, Q as setSession, V as setUser, W as validateAttribute } from './utils-CbUkl8r1.cjs';
3
3
  import { T as TraceContext } from './trace-context-t5X1AP-e.cjs';
4
4
  import '@opentelemetry/api';
5
5
  import '@opentelemetry/resources';
@@ -1,5 +1,5 @@
1
- import { U as UserAttrs, S as SessionAttrs, A as AttributePolicy } from './utils-D1trOLNm.js';
2
- export { p as AttributeGuardrails, J as ClientAttrs, C as CloudAttrs, Q as CodeAttrs, z as ContainerAttrs, t as DBAttrs, L as DeploymentAttrs, D as DeviceAttrs, E as ErrorAttrs, V as ExceptionAttrs, B as FaaSAttrs, F as FeatureFlagAttrs, G as GenAIAttrs, I as GraphQLAttrs, q as HTTPClientAttrs, H as HTTPServerAttrs, K as K8sAttrs, M as MessagingAttrs, N as NetworkAttrs, O as OTelAttrs, P as PeerAttrs, y as ProcessAttrs, R as RPCAttrs, w as ServerAddressAttrs, u as ServiceAttrs, W as TLSAttrs, T as ThreadAttrs, x as URLAttrs, a as attrs, n as autoRedactPII, l as checkDeprecatedAttribute, e as dbClient, o as defaultGuardrails, d as httpClient, h as httpServer, i as identify, j as mergeAttrs, m as mergeServiceResource, r as request, k as safeSetAttributes, c as setDevice, f as setError, g as setException, b as setSession, s as setUser, v as validateAttribute } from './utils-D1trOLNm.js';
1
+ import { U as UserAttrs, S as SessionAttrs, A as AttributePolicy } from './utils-Buel3cj0.js';
2
+ export { a as AttributeGuardrails, C as ClientAttrs, b as CloudAttrs, c as CodeAttrs, d as ContainerAttrs, D as DBAttrs, e as DeploymentAttrs, f as DeviceAttrs, E as ErrorAttrs, g as ExceptionAttrs, F as FaaSAttrs, h as FeatureFlagAttrs, G as GenAIAttrs, i as GraphQLAttrs, H as HTTPClientAttrs, j as HTTPServerAttrs, K as K8sAttrs, M as MessagingAttrs, N as NetworkAttrs, O as OTelAttrs, P as PeerAttrs, k as ProcessAttrs, R as RPCAttrs, l as ServerAddressAttrs, m as ServiceAttrs, T as TLSAttrs, n as ThreadAttrs, o as URLAttrs, p as attrs, q as autoRedactPII, r as checkDeprecatedAttribute, s as dbClient, t as defaultGuardrails, u as httpClient, v as httpServer, w as identify, x as mergeAttrs, y as mergeServiceResource, z as request, B as safeSetAttributes, I as setDevice, J as setError, L as setException, Q as setSession, V as setUser, W as validateAttribute } from './utils-Buel3cj0.js';
3
3
  import { T as TraceContext } from './trace-context-t5X1AP-e.js';
4
4
  import '@opentelemetry/api';
5
5
  import '@opentelemetry/resources';
package/dist/auto.cjs CHANGED
@@ -1,15 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var chunkJVICEM6W_cjs = require('./chunk-JVICEM6W.cjs');
4
- var chunk6YIDHH2S_cjs = require('./chunk-6YIDHH2S.cjs');
5
- require('./chunk-GVLK7YUU.cjs');
3
+ var chunkITYASFHQ_cjs = require('./chunk-ITYASFHQ.cjs');
4
+ var chunkOFPZULMQ_cjs = require('./chunk-OFPZULMQ.cjs');
5
+ require('./chunk-KZEC4CHV.cjs');
6
6
  require('./chunk-ZNMBW67B.cjs');
7
7
  require('./chunk-IOYFAFHJ.cjs');
8
8
  require('./chunk-ELW34S4C.cjs');
9
9
  require('./chunk-CU6IDACR.cjs');
10
10
  require('./chunk-6S5RUKU3.cjs');
11
11
  require('./chunk-YS6C2YJE.cjs');
12
- require('./chunk-BGVKKL2N.cjs');
12
+ require('./chunk-7FIGORWI.cjs');
13
13
  require('./chunk-AZ24DJAG.cjs');
14
14
  require('./chunk-ESLWRGAG.cjs');
15
15
  require('./chunk-YREV3LGG.cjs');
@@ -20,10 +20,10 @@ var importInTheMiddle = require('import-in-the-middle');
20
20
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
21
  var { registerOptions } = importInTheMiddle.createAddHookMessageChannel();
22
22
  module$1.register("import-in-the-middle/hook.mjs", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('auto.cjs', document.baseURI).href)), registerOptions);
23
- var yamlConfig = chunk6YIDHH2S_cjs.loadYamlConfig();
23
+ var yamlConfig = chunkOFPZULMQ_cjs.loadYamlConfig();
24
24
  var autoInstrumentationsEnv = process.env.AUTOTEL_INTEGRATIONS;
25
25
  var autoInstrumentations = autoInstrumentationsEnv === "true" ? true : autoInstrumentationsEnv ? autoInstrumentationsEnv.split(",").map((s) => s.trim()) : yamlConfig?.autoInstrumentations ?? ["http", "express"];
26
- chunkJVICEM6W_cjs.init({
26
+ chunkITYASFHQ_cjs.init({
27
27
  service: yamlConfig?.service ?? process.env.OTEL_SERVICE_NAME ?? "unknown-service",
28
28
  debug: yamlConfig?.debug ?? process.env.AUTOTEL_DEBUG === "true",
29
29
  autoInstrumentations
package/dist/auto.js CHANGED
@@ -1,13 +1,13 @@
1
- import { init } from './chunk-VXLEJWLY.js';
2
- import { loadYamlConfig } from './chunk-YTGF4L2C.js';
3
- import './chunk-X4RMFFMR.js';
1
+ import { init } from './chunk-MNBAXRVG.js';
2
+ import { loadYamlConfig } from './chunk-RUD7KS4R.js';
3
+ import './chunk-XDKK53OL.js';
4
4
  import './chunk-WGWSHJ2N.js';
5
5
  import './chunk-GYR5K654.js';
6
6
  import './chunk-SNINLBEE.js';
7
7
  import './chunk-6UQRVUN3.js';
8
8
  import './chunk-3QXBFGKP.js';
9
9
  import './chunk-33WTKH7X.js';
10
- import './chunk-XND7WBVX.js';
10
+ import './chunk-VYA6QDNA.js';
11
11
  import './chunk-B33XPEKY.js';
12
12
  import './chunk-J5QENANM.js';
13
13
  import './chunk-HA2WBOGQ.js';
@@ -1,4 +1,4 @@
1
- import { trace } from './chunk-IKRHEUS7.js';
1
+ import { trace } from './chunk-JM63D22M.js';
2
2
 
3
3
  // src/semantic-helpers.ts
4
4
  function traceLLM(config) {
@@ -91,5 +91,5 @@ function traceMessaging(config) {
91
91
  }
92
92
 
93
93
  export { traceDB, traceHTTP, traceLLM, traceMessaging };
94
- //# sourceMappingURL=chunk-QUW4I2OI.js.map
95
- //# sourceMappingURL=chunk-QUW4I2OI.js.map
94
+ //# sourceMappingURL=chunk-3ZLYWPMY.js.map
95
+ //# sourceMappingURL=chunk-3ZLYWPMY.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CA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Aa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF;AAmGO,SAAS,eACd,MAAA,EACA;AACA,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,kBAAA,EAAoB,MAAA,CAAO,MAAM,CAAA;AAClD,MAAA,IAAI,OAAO,SAAA,EAAW;AACpB,QAAA,GAAA,CAAI,YAAA,CAAa,qBAAA,EAAuB,MAAA,CAAO,SAAS,CAAA;AAAA,MAC1D;AACA,MAAA,IAAI,OAAO,WAAA,EAAa;AACtB,QAAA,GAAA,CAAI,YAAA,CAAa,4BAAA,EAA8B,MAAA,CAAO,WAAW,CAAA;AAAA,MACnE;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-QUW4I2OI.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,MAAA,CAAO,QAAQ,CAAA;AAAA,MACnD;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF;AAqGO,SAAS,QAA0C,MAAA,EAAkB;AAC1E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,O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AAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-3ZLYWPMY.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
@@ -3,6 +3,8 @@
3
3
  var api = require('@opentelemetry/api');
4
4
 
5
5
  // src/sampling.ts
6
+ var AUTOTEL_SAMPLING_TAIL_KEEP = "autotel.sampling.tail.keep";
7
+ var AUTOTEL_SAMPLING_TAIL_EVALUATED = "autotel.sampling.tail.evaluated";
6
8
  var RandomSampler = class {
7
9
  constructor(sampleRate) {
8
10
  this.sampleRate = sampleRate;
@@ -242,6 +244,44 @@ var FeatureFlagSampler = class {
242
244
  }
243
245
  }
244
246
  };
247
+ var samplingPresets = {
248
+ /** Capture everything — best for local development and debugging */
249
+ development: () => new AlwaysSampler(),
250
+ /** Only bad outcomes — zero baseline, errors always kept */
251
+ errorsOnly: () => new AdaptiveSampler({
252
+ baselineSampleRate: 0,
253
+ alwaysSampleErrors: true
254
+ }),
255
+ /**
256
+ * Balanced production defaults — 10% baseline + errors + slow traces.
257
+ * Pass overrides to tune (uses the same option names as AdaptiveSampler).
258
+ */
259
+ production: (overrides) => new AdaptiveSampler({
260
+ baselineSampleRate: 0.1,
261
+ alwaysSampleErrors: true,
262
+ alwaysSampleSlow: true,
263
+ slowThresholdMs: 1e3,
264
+ ...overrides
265
+ }),
266
+ /** Disable sampling entirely */
267
+ off: () => new NeverSampler()
268
+ };
269
+ function resolveSamplingPreset(preset) {
270
+ switch (preset) {
271
+ case "development":
272
+ return samplingPresets.development();
273
+ case "errors-only":
274
+ return samplingPresets.errorsOnly();
275
+ case "production":
276
+ return samplingPresets.production();
277
+ case "off":
278
+ return samplingPresets.off();
279
+ default:
280
+ throw new Error(
281
+ `Unknown sampling preset: "${preset}". Valid presets: development, errors-only, production, off`
282
+ );
283
+ }
284
+ }
245
285
  function createLinkFromHeaders(headers, attributes) {
246
286
  const traceparent = headers.traceparent || headers["traceparent"];
247
287
  if (!traceparent) {
@@ -299,6 +339,8 @@ function isValidSpanContext(spanContext) {
299
339
  return spanContext.traceId !== "00000000000000000000000000000000" && spanContext.spanId !== "0000000000000000";
300
340
  }
301
341
 
342
+ exports.AUTOTEL_SAMPLING_TAIL_EVALUATED = AUTOTEL_SAMPLING_TAIL_EVALUATED;
343
+ exports.AUTOTEL_SAMPLING_TAIL_KEEP = AUTOTEL_SAMPLING_TAIL_KEEP;
302
344
  exports.AdaptiveSampler = AdaptiveSampler;
303
345
  exports.AlwaysSampler = AlwaysSampler;
304
346
  exports.CompositeSampler = CompositeSampler;
@@ -308,5 +350,7 @@ exports.RandomSampler = RandomSampler;
308
350
  exports.UserIdSampler = UserIdSampler;
309
351
  exports.createLinkFromHeaders = createLinkFromHeaders;
310
352
  exports.extractLinksFromBatch = extractLinksFromBatch;
311
- //# sourceMappingURL=chunk-BGVKKL2N.cjs.map
312
- //# sourceMappingURL=chunk-BGVKKL2N.cjs.map
353
+ exports.resolveSamplingPreset = resolveSamplingPreset;
354
+ exports.samplingPresets = samplingPresets;
355
+ //# sourceMappingURL=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,CAAA;AAAA,IACrC,QAAA,EAAU;AAAA,GACZ;AACF;AAKA,SAAS,mBACP,WAAA,EACyD;AACzD,EAAA,IAAI,CAAC,aAAa,OAAO,KAAA;AAGzB,EAAA,OACE,WAAA,CAAY,OAAA,KAAY,kCAAA,IACxB,WAAA,CAAY,MAAA,KAAW,kBAAA;AAE3B","file":"chunk-7FIGORWI.cjs","sourcesContent":["/**\n * Sampling Strategies\n *\n * Provides intelligent sampling beyond simple random rates.\n * Helps reduce telemetry costs while capturing critical data.\n *\n * Key strategies:\n * - Always trace errors and slow requests (critical for debugging)\n * - Sample by user ID for consistent request tracing\n * - Adaptive sampling based on load\n * - Sample by feature flags for A/B testing correlation\n *\n * @example\n * ```typescript\n * import { AlwaysOnErrorSampler, UserIdSampler } from './sampling'\n *\n * @Instrumented({\n * serviceName: 'user',\n * sampler: new AlwaysOnErrorSampler(0.1) // 10% baseline, 100% on errors\n * })\n * class UserService { }\n * ```\n */\n\nimport type { Link, Attributes } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport { type Logger } from './logger';\n\n/**\n * Tail sampling attribute keys (autotel-internal, not OTel semconv)\n */\nexport const AUTOTEL_SAMPLING_TAIL_KEEP = 'autotel.sampling.tail.keep';\nexport const AUTOTEL_SAMPLING_TAIL_EVALUATED =\n 'autotel.sampling.tail.evaluated';\n\n/**\n * Sampler interface - return true to trace, false to skip\n */\nexport interface Sampler {\n /**\n * Decide whether to trace this operation\n *\n * @param context - Sampling context\n * @returns true to trace, false to skip\n */\n shouldSample(context: SamplingContext): boolean;\n\n /**\n * Whether this sampler needs tail sampling (post-execution decision)\n * If true, spans are always created and shouldKeepTrace() is called after execution\n *\n * @returns true if this sampler needs to evaluate after operation completes\n */\n needsTailSampling?(): boolean;\n\n /**\n * Re-evaluate sampling decision after operation completes (tail sampling)\n * Only called if needsTailSampling() returns true\n *\n * @param context - Sampling context\n * @param result - Operation result\n * @returns true if this trace should be kept, false to drop it\n */\n shouldKeepTrace?(context: SamplingContext, result: OperationResult): boolean;\n}\n\n/**\n * Context information for sampling decisions\n */\nexport interface SamplingContext {\n /** Operation name */\n operationName: string;\n /** Method arguments (for extracting user IDs, etc.) */\n args: unknown[];\n /** Optional metadata (e.g., feature flags, request headers) */\n metadata?: Record<string, unknown>;\n /** Optional span links for links-based sampling */\n links?: Link[];\n}\n\n/**\n * Result of a trace operation (for post-execution sampling)\n */\nexport interface OperationResult {\n /** Whether the operation succeeded */\n success: boolean;\n /** Duration in milliseconds */\n duration: number;\n /** Error if operation failed */\n error?: Error;\n}\n\n/**\n * Simple random sampler\n *\n * @example\n * ```typescript\n * new RandomSampler(0.1) // Sample 10% of requests\n * ```\n */\nexport class RandomSampler implements Sampler {\n constructor(private readonly sampleRate: number) {\n if (sampleRate < 0 || sampleRate > 1) {\n throw new Error('Sample rate must be between 0 and 1');\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n shouldSample(_context: SamplingContext): boolean {\n return Math.random() < this.sampleRate;\n }\n}\n\n/**\n * Always sample (100% tracing)\n */\nexport class AlwaysSampler implements Sampler {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n shouldSample(_context: SamplingContext): boolean {\n return true;\n }\n}\n\n/**\n * Never sample (0% tracing)\n */\nexport class NeverSampler implements Sampler {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n shouldSample(_context: SamplingContext): boolean {\n return false;\n }\n}\n\n/**\n * Adaptive sampler that always traces errors and slow requests\n *\n * This is the recommended sampler for production use.\n * It ensures you never miss critical issues while keeping costs down.\n *\n * Strategy:\n * - Always trace errors (critical for debugging)\n * - Always trace slow requests (performance issues)\n * - Use baseline sample rate for successful fast requests\n *\n * **IMPORTANT - Tail Sampling Requirement:**\n * This sampler uses tail sampling (makes decisions AFTER execution).\n * You MUST use TailSamplingSpanProcessor for it to work correctly:\n *\n * - If using initInstrumentation(): TailSamplingSpanProcessor is auto-configured\n * - If using custom TracerProvider: You MUST manually register TailSamplingSpanProcessor\n *\n * Without TailSamplingSpanProcessor, ALL spans are exported (defeating the cost savings).\n *\n * @see TailSamplingSpanProcessor\n * @see README.md \"Tail Sampling with Custom Providers\" section\n *\n * @example\n * ```typescript\n * new AdaptiveSampler({\n * baselineSampleRate: 0.1, // 10% of normal requests\n * slowThresholdMs: 1000, // Requests > 1s are \"slow\"\n * alwaysSampleErrors: true, // Always trace errors\n * alwaysSampleSlow: true // Always trace slow requests\n * })\n * ```\n */\nexport class AdaptiveSampler implements Sampler {\n private baselineSampleRate: number;\n private slowThresholdMs: number;\n private alwaysSampleErrors: boolean;\n private alwaysSampleSlow: boolean;\n private linksBased: boolean;\n private linksRate: number;\n private logger?: Logger;\n\n // Track whether we should sample this request\n private readonly samplingDecisions = new WeakMap<unknown[], boolean>();\n // Track operation results to enable post-execution decision\n private readonly operationResults = new WeakMap<unknown[], OperationResult>();\n\n constructor(\n options: {\n baselineSampleRate?: number;\n slowThresholdMs?: number;\n alwaysSampleErrors?: boolean;\n alwaysSampleSlow?: boolean;\n /** Enable links-based sampling for event-driven architectures */\n linksBased?: boolean;\n /** Sampling rate for spans linked to sampled spans (0.0-1.0) */\n linksRate?: number;\n logger?: Logger;\n } = {},\n ) {\n this.baselineSampleRate = options.baselineSampleRate ?? 0.1;\n this.slowThresholdMs = options.slowThresholdMs ?? 1000;\n this.alwaysSampleErrors = options.alwaysSampleErrors ?? true;\n this.alwaysSampleSlow = options.alwaysSampleSlow ?? true;\n this.linksBased = options.linksBased ?? false;\n this.linksRate = options.linksRate ?? 1;\n this.logger = options.logger;\n\n if (this.baselineSampleRate < 0 || this.baselineSampleRate > 1) {\n throw new Error('Baseline sample rate must be between 0 and 1');\n }\n if (this.linksRate < 0 || this.linksRate > 1) {\n throw new Error('Links rate must be between 0 and 1');\n }\n }\n\n needsTailSampling(): boolean {\n // AdaptiveSampler ALWAYS needs tail sampling to implement error/slow capture\n return true;\n }\n\n shouldSample(context: SamplingContext): boolean {\n // For tail sampling, we optimistically create spans for all requests\n // The real decision happens in shouldKeepTrace() after execution\n // We still store the baseline decision for shouldKeepTrace() to use\n const baselineDecision = Math.random() < this.baselineSampleRate;\n this.samplingDecisions.set(context.args, baselineDecision);\n\n // Always return true to create the span (tail sampling will decide if we keep it)\n return true;\n }\n\n /**\n * Check if any links point to sampled spans.\n *\n * A span is considered linked to a sampled span if any of its links\n * have trace_flags with the sampled bit set (0x01).\n *\n * @param links - Array of span links to check\n * @returns true if any linked span is sampled, false otherwise\n */\n hasSampledLink(links: Link[]): boolean {\n if (!links || links.length === 0) {\n return false;\n }\n return links.some(\n (link) =>\n link.context && (link.context.traceFlags & TraceFlags.SAMPLED) !== 0,\n );\n }\n\n /**\n * Re-evaluate sampling decision after operation completes\n *\n * This allows us to always capture errors and slow requests,\n * even if they weren't initially sampled.\n *\n * @param context - Sampling context\n * @param result - Operation result\n * @returns true if this operation should be kept (not discarded)\n */\n shouldKeepTrace(context: SamplingContext, result: OperationResult): boolean {\n const baselineDecision = this.samplingDecisions.get(context.args) ?? false;\n\n // Always keep errors\n if (this.alwaysSampleErrors && !result.success) {\n if (!baselineDecision) {\n this.logger?.debug(\n {\n operation: context.operationName,\n error: result.error?.message,\n },\n 'Adaptive sampling: Keeping error trace',\n );\n }\n return true;\n }\n\n // Always keep slow requests\n if (this.alwaysSampleSlow && result.duration >= this.slowThresholdMs) {\n if (!baselineDecision) {\n this.logger?.debug(\n {\n operation: context.operationName,\n duration: result.duration,\n },\n 'Adaptive sampling: Keeping slow trace',\n );\n }\n return true;\n }\n\n // Check for sampled links (links-based sampling for event-driven systems)\n if (\n this.linksBased &&\n context.links &&\n this.hasSampledLink(context.links)\n ) {\n // Use linksRate to decide whether to keep the linked span\n const keepLinked = Math.random() < this.linksRate;\n if (keepLinked && !baselineDecision) {\n this.logger?.debug(\n {\n operation: context.operationName,\n linkCount: context.links.length,\n },\n 'Adaptive sampling: Keeping trace due to sampled link',\n );\n }\n return keepLinked;\n }\n\n // Otherwise, use baseline decision\n return baselineDecision;\n }\n}\n\n/**\n * User-based sampler for consistent tracing\n *\n * Always samples requests from specific user IDs.\n * Useful for debugging specific user issues or monitoring VIP users.\n *\n * @example\n * ```typescript\n * new UserIdSampler({\n * baselineSampleRate: 0.01, // 1% of normal users\n * alwaysSampleUsers: ['vip_123'], // Always trace VIP users\n * extractUserId: (args) => args[0]?.userId // Extract user ID from first arg\n * })\n * ```\n */\nexport class UserIdSampler implements Sampler {\n private baselineSampleRate: number;\n private alwaysSampleUsers: Set<string>;\n private extractUserId: (args: unknown[]) => string | undefined;\n private logger?: Logger;\n\n constructor(options: {\n baselineSampleRate?: number;\n alwaysSampleUsers?: string[];\n extractUserId: (args: unknown[]) => string | undefined;\n logger?: Logger;\n }) {\n this.baselineSampleRate = options.baselineSampleRate ?? 0.1;\n this.alwaysSampleUsers = new Set(options.alwaysSampleUsers || []);\n this.extractUserId = options.extractUserId;\n this.logger = options.logger;\n }\n\n shouldSample(context: SamplingContext): boolean {\n const userId = this.extractUserId(context.args);\n\n // Always sample specific users\n if (userId && this.alwaysSampleUsers.has(userId)) {\n this.logger?.debug(\n {\n operation: context.operationName,\n userId,\n },\n 'Sampling user request',\n );\n return true;\n }\n\n // For consistent per-user sampling, hash the user ID\n if (userId) {\n const hash = this.hashString(userId);\n return hash < this.baselineSampleRate;\n }\n\n // Fallback to random sampling if no user ID\n return Math.random() < this.baselineSampleRate;\n }\n\n /**\n * Add user IDs to always-sample list\n */\n addAlwaysSampleUsers(...userIds: string[]): void {\n for (const userId of userIds) {\n this.alwaysSampleUsers.add(userId);\n }\n }\n\n /**\n * Remove user IDs from always-sample list\n */\n removeAlwaysSampleUsers(...userIds: string[]): void {\n for (const userId of userIds) {\n this.alwaysSampleUsers.delete(userId);\n }\n }\n\n /**\n * Simple hash function for consistent user sampling\n */\n private hashString(str: string): number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.codePointAt(i) ?? 0;\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return Math.abs(hash) / 2_147_483_647; // Normalize to 0-1\n }\n}\n\n/**\n * Composite sampler that combines multiple samplers\n *\n * Samples if ANY of the child samplers returns true.\n *\n * @example\n * ```typescript\n * new CompositeSampler([\n * new UserIdSampler({ extractUserId: (args) => args[0]?.userId }),\n * new AdaptiveSampler({ baselineSampleRate: 0.1 })\n * ])\n * ```\n */\nexport class CompositeSampler implements Sampler {\n constructor(private readonly samplers: Sampler[]) {\n if (samplers.length === 0) {\n throw new Error('CompositeSampler requires at least one child sampler');\n }\n }\n\n shouldSample(context: SamplingContext): boolean {\n return this.samplers.some((sampler) => sampler.shouldSample(context));\n }\n}\n\n/**\n * Feature flag sampler\n *\n * Always samples requests with specific feature flags enabled.\n * Perfect for correlating A/B test experiments with metrics.\n *\n * @example\n * ```typescript\n * new FeatureFlagSampler({\n * baselineSampleRate: 0.01,\n * alwaysSampleFlags: ['new_checkout', 'experimental_ui'],\n * extractFlags: (args, metadata) => metadata?.featureFlags\n * })\n * ```\n */\nexport class FeatureFlagSampler implements Sampler {\n private baselineSampleRate: number;\n private alwaysSampleFlags: Set<string>;\n private extractFlags: (\n args: unknown[],\n metadata?: Record<string, unknown>,\n ) => string[] | undefined;\n private logger?: Logger;\n\n constructor(options: {\n baselineSampleRate?: number;\n alwaysSampleFlags?: string[];\n extractFlags: (\n args: unknown[],\n metadata?: Record<string, unknown>,\n ) => string[] | undefined;\n logger?: Logger;\n }) {\n this.baselineSampleRate = options.baselineSampleRate ?? 0.1;\n this.alwaysSampleFlags = new Set(options.alwaysSampleFlags || []);\n this.extractFlags = options.extractFlags;\n this.logger = options.logger;\n }\n\n shouldSample(context: SamplingContext): boolean {\n const flags = this.extractFlags(context.args, context.metadata);\n\n // Always sample if any monitored flag is enabled\n if (flags && flags.some((flag) => this.alwaysSampleFlags.has(flag))) {\n this.logger?.debug(\n {\n operation: context.operationName,\n flags,\n },\n 'Sampling feature flag request',\n );\n return true;\n }\n\n // Fallback to random sampling\n return Math.random() < this.baselineSampleRate;\n }\n\n /**\n * Add feature flags to always-sample list\n */\n addAlwaysSampleFlags(...flags: string[]): void {\n for (const flag of flags) {\n this.alwaysSampleFlags.add(flag);\n }\n }\n\n /**\n * Remove feature flags from always-sample list\n */\n removeAlwaysSampleFlags(...flags: string[]): void {\n for (const flag of flags) {\n this.alwaysSampleFlags.delete(flag);\n }\n }\n}\n\n// ============================================================================\n// Sampling Presets\n// ============================================================================\n\n/**\n * Named sampling presets for common environments.\n * Use with `init({ sampling: 'production' })` or directly via factories.\n */\nexport type SamplingPreset =\n | 'development'\n | 'errors-only'\n | 'production'\n | 'off';\n\n/**\n * Sampling preset factories.\n *\n * For most users, the string shorthand on `init()` is simpler:\n * ```typescript\n * init({ service: 'my-app', sampling: 'production' })\n * ```\n *\n * Use factories when you need to customize:\n * ```typescript\n * init({ service: 'my-app', sampler: samplingPresets.production({ baselineSampleRate: 0.05 }) })\n * ```\n */\nexport const samplingPresets = {\n /** Capture everything — best for local development and debugging */\n development: () => new AlwaysSampler(),\n\n /** Only bad outcomes — zero baseline, errors always kept */\n errorsOnly: () =>\n new AdaptiveSampler({\n baselineSampleRate: 0,\n alwaysSampleErrors: true,\n }),\n\n /**\n * Balanced production defaults — 10% baseline + errors + slow traces.\n * Pass overrides to tune (uses the same option names as AdaptiveSampler).\n */\n production: (overrides?: {\n baselineSampleRate?: number;\n slowThresholdMs?: number;\n alwaysSampleErrors?: boolean;\n alwaysSampleSlow?: boolean;\n }) =>\n new AdaptiveSampler({\n baselineSampleRate: 0.1,\n alwaysSampleErrors: true,\n alwaysSampleSlow: true,\n slowThresholdMs: 1000,\n ...overrides,\n }),\n\n /** Disable sampling entirely */\n off: () => new NeverSampler(),\n};\n\n/**\n * Resolve a preset string to a Sampler instance.\n * Used internally by `init()` when `sampling` string is provided.\n *\n * @throws Error if preset is not recognized\n */\nexport function resolveSamplingPreset(preset: SamplingPreset): Sampler {\n switch (preset) {\n case 'development':\n return samplingPresets.development();\n case 'errors-only':\n return samplingPresets.errorsOnly();\n case 'production':\n return samplingPresets.production();\n case 'off':\n return samplingPresets.off();\n default:\n throw new Error(\n `Unknown sampling preset: \"${preset}\". Valid presets: development, errors-only, production, off`,\n );\n }\n}\n\n// ============================================================================\n// Link Helper Functions\n// ============================================================================\n\n/**\n * Create a Link from W3C trace context headers (e.g., from a message queue).\n *\n * This is useful for message consumers that need to link to the producer span.\n * The headers should contain at least a `traceparent` header in W3C format.\n *\n * @param headers - Dictionary containing traceparent/tracestate headers\n * @param attributes - Optional attributes for the link\n * @returns Link object if context could be extracted, null otherwise\n *\n * @example\n * ```typescript\n * // In a Kafka consumer\n * const headers = { traceparent: '00-abc123...-def456...-01' };\n * const link = createLinkFromHeaders(headers);\n * if (link) {\n * // Use with tracer.startActiveSpan options or ctx.addLink()\n * tracer.startActiveSpan('process.message', { links: [link] }, span => { ... });\n * }\n * ```\n */\nexport function createLinkFromHeaders(\n headers: Record<string, string>,\n attributes?: Attributes,\n): Link | null {\n // Parse W3C traceparent header directly for reliability\n // Format: version-traceId-spanId-traceFlags (e.g., 00-abc123...-def456...-01)\n const traceparent = headers.traceparent || headers['traceparent'];\n if (!traceparent) {\n return null;\n }\n\n const spanContext = parseTraceparent(traceparent);\n if (!spanContext || !isValidSpanContext(spanContext)) {\n return null;\n }\n\n return {\n context: spanContext,\n attributes: attributes ?? {},\n };\n}\n\n/**\n * Extract Links from a batch of messages for fan-in scenarios.\n *\n * Useful for batch processing where multiple producer spans should be linked.\n * This enables tracing causality in event-driven architectures where a single\n * consumer processes messages from multiple producers.\n *\n * @param messages - List of message objects\n * @param headersKey - Key in each message containing trace headers (default: 'headers')\n * @returns List of Link objects for all valid trace contexts\n *\n * @example\n * ```typescript\n * // Processing a batch of SQS/Kafka messages\n * const messages = [\n * { body: '...', headers: { traceparent: '...' } },\n * { body: '...', headers: { traceparent: '...' } },\n * ];\n * const links = extractLinksFromBatch(messages);\n *\n * tracer.startActiveSpan('process.batch', { links }, span => {\n * for (const msg of messages) {\n * processMessage(msg);\n * }\n * });\n * ```\n */\nexport function extractLinksFromBatch(\n messages: Array<{ [key: string]: unknown }>,\n headersKey: string = 'headers',\n): Link[] {\n const links: Link[] = [];\n\n for (const msg of messages) {\n const msgHeaders = msg[headersKey];\n if (msgHeaders && typeof msgHeaders === 'object' && msgHeaders !== null) {\n const link = createLinkFromHeaders(msgHeaders as Record<string, string>, {\n 'messaging.batch.message_index': links.length,\n });\n if (link) {\n links.push(link);\n }\n }\n }\n\n return links;\n}\n\n/**\n * Parse W3C traceparent header into SpanContext\n * Format: version-traceId-spanId-traceFlags (e.g., 00-abc123...-def456...-01)\n *\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\nfunction parseTraceparent(\n traceparent: string,\n): import('@opentelemetry/api').SpanContext | null {\n // W3C traceparent format: version-traceId-parentId-traceFlags\n // Example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01\n const TRACEPARENT_REGEX =\n /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;\n\n const match = traceparent.match(TRACEPARENT_REGEX);\n if (!match || match.length < 5) {\n return null;\n }\n\n const version = match[1];\n const traceId = match[2];\n const spanId = match[3];\n const flags = match[4];\n\n // Validate all parts are present (TypeScript narrowing)\n if (!version || !traceId || !spanId || !flags) {\n return null;\n }\n\n // Version 00 is currently the only version, but we should be forward compatible\n if (version === 'ff') {\n // Version ff is invalid according to spec\n return null;\n }\n\n return {\n traceId,\n spanId,\n traceFlags: Number.parseInt(flags, 16),\n isRemote: true,\n };\n}\n\n/**\n * Check if a SpanContext is valid (has non-zero trace and span IDs)\n */\nfunction isValidSpanContext(\n spanContext: import('@opentelemetry/api').SpanContext | null,\n): spanContext is import('@opentelemetry/api').SpanContext {\n if (!spanContext) return false;\n // TraceId should not be all zeros (00000000000000000000000000000000)\n // SpanId should not be all zeros (0000000000000000)\n return (\n spanContext.traceId !== '00000000000000000000000000000000' &&\n spanContext.spanId !== '0000000000000000'\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkRWOVNF3V_cjs = require('./chunk-RWOVNF3V.cjs');
3
+ var chunkRMGSBMQF_cjs = require('./chunk-RMGSBMQF.cjs');
4
4
  var chunkGML3FBOT_cjs = require('./chunk-GML3FBOT.cjs');
5
5
  var async_hooks = require('async_hooks');
6
6
 
@@ -9,7 +9,7 @@ var workflowContextStorage = new async_hooks.AsyncLocalStorage();
9
9
  function traceWorkflow(config) {
10
10
  const spanName = `workflow.${config.name}`;
11
11
  return (fnFactory) => {
12
- return chunkRWOVNF3V_cjs.trace(spanName, (baseCtx) => {
12
+ return chunkRMGSBMQF_cjs.trace(spanName, (baseCtx) => {
13
13
  return async (...args) => {
14
14
  const workflowId = typeof config.workflowId === "function" ? config.workflowId(...args) : config.workflowId;
15
15
  const ctx = createWorkflowContext(baseCtx, config.name, workflowId);
@@ -61,7 +61,7 @@ function traceWorkflow(config) {
61
61
  function traceStep(config) {
62
62
  return (fn) => {
63
63
  const spanName = `step.${config.name}`;
64
- return chunkRWOVNF3V_cjs.trace(spanName, (baseCtx) => {
64
+ return chunkRMGSBMQF_cjs.trace(spanName, (baseCtx) => {
65
65
  return async (...args) => {
66
66
  const workflowCtx = workflowContextStorage.getStore() ?? null;
67
67
  const ctx = createStepContext(baseCtx, config, workflowCtx);
@@ -339,5 +339,5 @@ exports.getCurrentWorkflowContext = getCurrentWorkflowContext;
339
339
  exports.isInWorkflow = isInWorkflow;
340
340
  exports.traceStep = traceStep;
341
341
  exports.traceWorkflow = traceWorkflow;
342
- //# sourceMappingURL=chunk-MNMLCLHH.cjs.map
343
- //# sourceMappingURL=chunk-MNMLCLHH.cjs.map
342
+ //# sourceMappingURL=chunk-AQXPGGQK.cjs.map
343
+ //# sourceMappingURL=chunk-AQXPGGQK.cjs.map