autotel 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1946 -0
  3. package/dist/chunk-2LNRY4QK.js +273 -0
  4. package/dist/chunk-2LNRY4QK.js.map +1 -0
  5. package/dist/chunk-3HENGDW2.js +587 -0
  6. package/dist/chunk-3HENGDW2.js.map +1 -0
  7. package/dist/chunk-4OAT42CA.cjs +73 -0
  8. package/dist/chunk-4OAT42CA.cjs.map +1 -0
  9. package/dist/chunk-5GWX5LFW.js +70 -0
  10. package/dist/chunk-5GWX5LFW.js.map +1 -0
  11. package/dist/chunk-5R2M36QB.js +195 -0
  12. package/dist/chunk-5R2M36QB.js.map +1 -0
  13. package/dist/chunk-5ZN622AO.js +73 -0
  14. package/dist/chunk-5ZN622AO.js.map +1 -0
  15. package/dist/chunk-77MSMAUQ.cjs +498 -0
  16. package/dist/chunk-77MSMAUQ.cjs.map +1 -0
  17. package/dist/chunk-ABPEQ6RK.cjs +596 -0
  18. package/dist/chunk-ABPEQ6RK.cjs.map +1 -0
  19. package/dist/chunk-BWYGJKRB.js +95 -0
  20. package/dist/chunk-BWYGJKRB.js.map +1 -0
  21. package/dist/chunk-BZHG5IZ4.js +73 -0
  22. package/dist/chunk-BZHG5IZ4.js.map +1 -0
  23. package/dist/chunk-G7VZBCD6.cjs +35 -0
  24. package/dist/chunk-G7VZBCD6.cjs.map +1 -0
  25. package/dist/chunk-GVLK7YUU.cjs +30 -0
  26. package/dist/chunk-GVLK7YUU.cjs.map +1 -0
  27. package/dist/chunk-HCCXC7XG.js +205 -0
  28. package/dist/chunk-HCCXC7XG.js.map +1 -0
  29. package/dist/chunk-HE6T6FIX.cjs +203 -0
  30. package/dist/chunk-HE6T6FIX.cjs.map +1 -0
  31. package/dist/chunk-KIXWPOCO.cjs +100 -0
  32. package/dist/chunk-KIXWPOCO.cjs.map +1 -0
  33. package/dist/chunk-KVGNW3FC.js +87 -0
  34. package/dist/chunk-KVGNW3FC.js.map +1 -0
  35. package/dist/chunk-LITNXTTT.js +3 -0
  36. package/dist/chunk-LITNXTTT.js.map +1 -0
  37. package/dist/chunk-M4ANN7RL.js +114 -0
  38. package/dist/chunk-M4ANN7RL.js.map +1 -0
  39. package/dist/chunk-NC52UBR2.cjs +32 -0
  40. package/dist/chunk-NC52UBR2.cjs.map +1 -0
  41. package/dist/chunk-NHCNRQD3.cjs +212 -0
  42. package/dist/chunk-NHCNRQD3.cjs.map +1 -0
  43. package/dist/chunk-NZ72VDNY.cjs +4 -0
  44. package/dist/chunk-NZ72VDNY.cjs.map +1 -0
  45. package/dist/chunk-P6JUDYNO.js +57 -0
  46. package/dist/chunk-P6JUDYNO.js.map +1 -0
  47. package/dist/chunk-RJYY7BWX.js +1349 -0
  48. package/dist/chunk-RJYY7BWX.js.map +1 -0
  49. package/dist/chunk-TRI4V5BF.cjs +126 -0
  50. package/dist/chunk-TRI4V5BF.cjs.map +1 -0
  51. package/dist/chunk-UL33I6IS.js +139 -0
  52. package/dist/chunk-UL33I6IS.js.map +1 -0
  53. package/dist/chunk-URRW6M2C.cjs +61 -0
  54. package/dist/chunk-URRW6M2C.cjs.map +1 -0
  55. package/dist/chunk-UY3UYPBZ.cjs +77 -0
  56. package/dist/chunk-UY3UYPBZ.cjs.map +1 -0
  57. package/dist/chunk-W3253FGB.cjs +277 -0
  58. package/dist/chunk-W3253FGB.cjs.map +1 -0
  59. package/dist/chunk-W7LHZVQF.js +26 -0
  60. package/dist/chunk-W7LHZVQF.js.map +1 -0
  61. package/dist/chunk-WBWNM6LB.cjs +1360 -0
  62. package/dist/chunk-WBWNM6LB.cjs.map +1 -0
  63. package/dist/chunk-WFJ7L2RV.js +494 -0
  64. package/dist/chunk-WFJ7L2RV.js.map +1 -0
  65. package/dist/chunk-X4RMFFMR.js +28 -0
  66. package/dist/chunk-X4RMFFMR.js.map +1 -0
  67. package/dist/chunk-Y4Y2S7BM.cjs +92 -0
  68. package/dist/chunk-Y4Y2S7BM.cjs.map +1 -0
  69. package/dist/chunk-YLPNXZFI.cjs +143 -0
  70. package/dist/chunk-YLPNXZFI.cjs.map +1 -0
  71. package/dist/chunk-YTXEZ4SD.cjs +77 -0
  72. package/dist/chunk-YTXEZ4SD.cjs.map +1 -0
  73. package/dist/chunk-Z6ZWNWWR.js +30 -0
  74. package/dist/chunk-Z6ZWNWWR.js.map +1 -0
  75. package/dist/config.cjs +26 -0
  76. package/dist/config.cjs.map +1 -0
  77. package/dist/config.d.cts +75 -0
  78. package/dist/config.d.ts +75 -0
  79. package/dist/config.js +5 -0
  80. package/dist/config.js.map +1 -0
  81. package/dist/db.cjs +233 -0
  82. package/dist/db.cjs.map +1 -0
  83. package/dist/db.d.cts +123 -0
  84. package/dist/db.d.ts +123 -0
  85. package/dist/db.js +228 -0
  86. package/dist/db.js.map +1 -0
  87. package/dist/decorators.cjs +67 -0
  88. package/dist/decorators.cjs.map +1 -0
  89. package/dist/decorators.d.cts +91 -0
  90. package/dist/decorators.d.ts +91 -0
  91. package/dist/decorators.js +65 -0
  92. package/dist/decorators.js.map +1 -0
  93. package/dist/event-subscriber.cjs +6 -0
  94. package/dist/event-subscriber.cjs.map +1 -0
  95. package/dist/event-subscriber.d.cts +116 -0
  96. package/dist/event-subscriber.d.ts +116 -0
  97. package/dist/event-subscriber.js +3 -0
  98. package/dist/event-subscriber.js.map +1 -0
  99. package/dist/event-testing.cjs +21 -0
  100. package/dist/event-testing.cjs.map +1 -0
  101. package/dist/event-testing.d.cts +110 -0
  102. package/dist/event-testing.d.ts +110 -0
  103. package/dist/event-testing.js +4 -0
  104. package/dist/event-testing.js.map +1 -0
  105. package/dist/event.cjs +30 -0
  106. package/dist/event.cjs.map +1 -0
  107. package/dist/event.d.cts +282 -0
  108. package/dist/event.d.ts +282 -0
  109. package/dist/event.js +13 -0
  110. package/dist/event.js.map +1 -0
  111. package/dist/exporters.cjs +17 -0
  112. package/dist/exporters.cjs.map +1 -0
  113. package/dist/exporters.d.cts +1 -0
  114. package/dist/exporters.d.ts +1 -0
  115. package/dist/exporters.js +4 -0
  116. package/dist/exporters.js.map +1 -0
  117. package/dist/functional.cjs +46 -0
  118. package/dist/functional.cjs.map +1 -0
  119. package/dist/functional.d.cts +478 -0
  120. package/dist/functional.d.ts +478 -0
  121. package/dist/functional.js +13 -0
  122. package/dist/functional.js.map +1 -0
  123. package/dist/http.cjs +189 -0
  124. package/dist/http.cjs.map +1 -0
  125. package/dist/http.d.cts +169 -0
  126. package/dist/http.d.ts +169 -0
  127. package/dist/http.js +184 -0
  128. package/dist/http.js.map +1 -0
  129. package/dist/index.cjs +333 -0
  130. package/dist/index.cjs.map +1 -0
  131. package/dist/index.d.cts +758 -0
  132. package/dist/index.d.ts +758 -0
  133. package/dist/index.js +143 -0
  134. package/dist/index.js.map +1 -0
  135. package/dist/instrumentation.cjs +182 -0
  136. package/dist/instrumentation.cjs.map +1 -0
  137. package/dist/instrumentation.d.cts +49 -0
  138. package/dist/instrumentation.d.ts +49 -0
  139. package/dist/instrumentation.js +179 -0
  140. package/dist/instrumentation.js.map +1 -0
  141. package/dist/logger.cjs +19 -0
  142. package/dist/logger.cjs.map +1 -0
  143. package/dist/logger.d.cts +146 -0
  144. package/dist/logger.d.ts +146 -0
  145. package/dist/logger.js +6 -0
  146. package/dist/logger.js.map +1 -0
  147. package/dist/metric-helpers.cjs +31 -0
  148. package/dist/metric-helpers.cjs.map +1 -0
  149. package/dist/metric-helpers.d.cts +13 -0
  150. package/dist/metric-helpers.d.ts +13 -0
  151. package/dist/metric-helpers.js +6 -0
  152. package/dist/metric-helpers.js.map +1 -0
  153. package/dist/metric-testing.cjs +21 -0
  154. package/dist/metric-testing.cjs.map +1 -0
  155. package/dist/metric-testing.d.cts +110 -0
  156. package/dist/metric-testing.d.ts +110 -0
  157. package/dist/metric-testing.js +4 -0
  158. package/dist/metric-testing.js.map +1 -0
  159. package/dist/metric.cjs +26 -0
  160. package/dist/metric.cjs.map +1 -0
  161. package/dist/metric.d.cts +240 -0
  162. package/dist/metric.d.ts +240 -0
  163. package/dist/metric.js +9 -0
  164. package/dist/metric.js.map +1 -0
  165. package/dist/processors.cjs +17 -0
  166. package/dist/processors.cjs.map +1 -0
  167. package/dist/processors.d.cts +1 -0
  168. package/dist/processors.d.ts +1 -0
  169. package/dist/processors.js +4 -0
  170. package/dist/processors.js.map +1 -0
  171. package/dist/sampling.cjs +40 -0
  172. package/dist/sampling.cjs.map +1 -0
  173. package/dist/sampling.d.cts +260 -0
  174. package/dist/sampling.d.ts +260 -0
  175. package/dist/sampling.js +7 -0
  176. package/dist/sampling.js.map +1 -0
  177. package/dist/semantic-helpers.cjs +35 -0
  178. package/dist/semantic-helpers.cjs.map +1 -0
  179. package/dist/semantic-helpers.d.cts +442 -0
  180. package/dist/semantic-helpers.d.ts +442 -0
  181. package/dist/semantic-helpers.js +14 -0
  182. package/dist/semantic-helpers.js.map +1 -0
  183. package/dist/tail-sampling-processor.cjs +13 -0
  184. package/dist/tail-sampling-processor.cjs.map +1 -0
  185. package/dist/tail-sampling-processor.d.cts +27 -0
  186. package/dist/tail-sampling-processor.d.ts +27 -0
  187. package/dist/tail-sampling-processor.js +4 -0
  188. package/dist/tail-sampling-processor.js.map +1 -0
  189. package/dist/testing.cjs +286 -0
  190. package/dist/testing.cjs.map +1 -0
  191. package/dist/testing.d.cts +291 -0
  192. package/dist/testing.d.ts +291 -0
  193. package/dist/testing.js +263 -0
  194. package/dist/testing.js.map +1 -0
  195. package/dist/trace-context-DRZdUvVY.d.cts +181 -0
  196. package/dist/trace-context-DRZdUvVY.d.ts +181 -0
  197. package/dist/trace-helpers.cjs +54 -0
  198. package/dist/trace-helpers.cjs.map +1 -0
  199. package/dist/trace-helpers.d.cts +524 -0
  200. package/dist/trace-helpers.d.ts +524 -0
  201. package/dist/trace-helpers.js +5 -0
  202. package/dist/trace-helpers.js.map +1 -0
  203. package/dist/tracer-provider.cjs +21 -0
  204. package/dist/tracer-provider.cjs.map +1 -0
  205. package/dist/tracer-provider.d.cts +169 -0
  206. package/dist/tracer-provider.d.ts +169 -0
  207. package/dist/tracer-provider.js +4 -0
  208. package/dist/tracer-provider.js.map +1 -0
  209. package/package.json +280 -0
  210. package/src/baggage-span-processor.test.ts +202 -0
  211. package/src/baggage-span-processor.ts +98 -0
  212. package/src/circuit-breaker.test.ts +341 -0
  213. package/src/circuit-breaker.ts +184 -0
  214. package/src/config.test.ts +94 -0
  215. package/src/config.ts +169 -0
  216. package/src/db.test.ts +252 -0
  217. package/src/db.ts +447 -0
  218. package/src/decorators.test.ts +203 -0
  219. package/src/decorators.ts +188 -0
  220. package/src/env-config.test.ts +246 -0
  221. package/src/env-config.ts +158 -0
  222. package/src/event-queue.test.ts +222 -0
  223. package/src/event-queue.ts +203 -0
  224. package/src/event-subscriber.ts +136 -0
  225. package/src/event-testing.ts +197 -0
  226. package/src/event.test.ts +718 -0
  227. package/src/event.ts +556 -0
  228. package/src/exporters.ts +96 -0
  229. package/src/functional.test.ts +1059 -0
  230. package/src/functional.ts +2295 -0
  231. package/src/http.test.ts +487 -0
  232. package/src/http.ts +424 -0
  233. package/src/index.ts +158 -0
  234. package/src/init.customization.test.ts +210 -0
  235. package/src/init.integrations.test.ts +366 -0
  236. package/src/init.openllmetry.test.ts +282 -0
  237. package/src/init.protocol.test.ts +215 -0
  238. package/src/init.ts +1426 -0
  239. package/src/instrumentation.test.ts +108 -0
  240. package/src/instrumentation.ts +308 -0
  241. package/src/logger.test.ts +117 -0
  242. package/src/logger.ts +246 -0
  243. package/src/metric-helpers.ts +47 -0
  244. package/src/metric-testing.ts +197 -0
  245. package/src/metric.ts +434 -0
  246. package/src/metrics.test.ts +205 -0
  247. package/src/operation-context.ts +93 -0
  248. package/src/processors.ts +106 -0
  249. package/src/rate-limiter.test.ts +199 -0
  250. package/src/rate-limiter.ts +98 -0
  251. package/src/sampling.test.ts +513 -0
  252. package/src/sampling.ts +428 -0
  253. package/src/semantic-helpers.test.ts +311 -0
  254. package/src/semantic-helpers.ts +584 -0
  255. package/src/shutdown.test.ts +311 -0
  256. package/src/shutdown.ts +222 -0
  257. package/src/stub.integration.test.ts +361 -0
  258. package/src/tail-sampling-processor.test.ts +226 -0
  259. package/src/tail-sampling-processor.ts +51 -0
  260. package/src/testing.ts +670 -0
  261. package/src/trace-context.ts +470 -0
  262. package/src/trace-helpers.new.test.ts +278 -0
  263. package/src/trace-helpers.test.ts +242 -0
  264. package/src/trace-helpers.ts +690 -0
  265. package/src/tracer-provider.test.ts +183 -0
  266. package/src/tracer-provider.ts +266 -0
  267. package/src/track.test.ts +153 -0
  268. package/src/track.ts +120 -0
  269. package/src/validation.test.ts +306 -0
  270. package/src/validation.ts +239 -0
  271. package/src/variable-name-inference.test.ts +178 -0
  272. package/src/variable-name-inference.ts +242 -0
package/src/http.ts ADDED
@@ -0,0 +1,424 @@
1
+ /**
2
+ * HTTP Instrumentation Helpers
3
+ *
4
+ * Optional import: Not included in main bundle
5
+ * Import from: 'autotel/http'
6
+ *
7
+ * Provides decorators and utilities for HTTP client instrumentation.
8
+ * Works with fetch, axios, and other HTTP clients.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { HttpInstrumented } from 'autotel/http'
13
+ *
14
+ * @HttpInstrumented()
15
+ * class ApiClient {
16
+ * async getUser(id: string) {
17
+ * return fetch(`/api/users/${id}`)
18
+ * }
19
+ * }
20
+ * ```
21
+ */
22
+
23
+ import { SpanStatusCode, context, propagation } from '@opentelemetry/api';
24
+ import { getConfig } from './config';
25
+ import { getActiveContextWithBaggage } from './trace-context';
26
+
27
+ export interface HttpInstrumentedOptions {
28
+ /** Service name for HTTP calls (default: 'http-client') */
29
+ serviceName?: string;
30
+ /** Extract URL from method arguments (default: first arg) */
31
+ urlExtractor?: (args: unknown[]) => string | undefined;
32
+ /** Extract HTTP method from method name or args */
33
+ methodExtractor?: (methodName: string, args: unknown[]) => string;
34
+ /** Add custom attributes to spans */
35
+ attributesFromArgs?: (args: unknown[]) => Record<string, string | number>;
36
+ /** Slow request threshold in milliseconds (adds warning attribute) - default: 3000ms */
37
+ slowRequestThresholdMs?: number;
38
+ }
39
+
40
+ /**
41
+ * Decorator for auto-instrumenting HTTP client methods
42
+ *
43
+ * @example Basic usage
44
+ * ```typescript
45
+ * @HttpInstrumented()
46
+ * class ApiClient {
47
+ * async fetchUser(userId: string) {
48
+ * const res = await fetch(`https://api.example.com/users/${userId}`)
49
+ * return res.json()
50
+ * }
51
+ *
52
+ * async createOrder(order: Order) {
53
+ * const res = await fetch('https://api.example.com/orders', {
54
+ * method: 'POST',
55
+ * body: JSON.stringify(order)
56
+ * })
57
+ * return res.json()
58
+ * }
59
+ * }
60
+ * ```
61
+ *
62
+ * @example Advanced usage with custom extractors
63
+ * ```typescript
64
+ * @HttpInstrumented({
65
+ * serviceName: 'payment-gateway',
66
+ * urlExtractor: (args) => {
67
+ * const config = args[0] as RequestConfig
68
+ * return config.url
69
+ * },
70
+ * attributesFromArgs: (args) => ({
71
+ * 'http.request_id': args[0]?.requestId,
72
+ * 'http.retry_count': args[0]?.retryCount || 0
73
+ * })
74
+ * })
75
+ * class PaymentClient {
76
+ * async charge(config: RequestConfig) {
77
+ * return axios(config)
78
+ * }
79
+ * }
80
+ * ```
81
+ */
82
+ export function HttpInstrumented(options: HttpInstrumentedOptions = {}) {
83
+ const serviceName = options.serviceName || 'http-client';
84
+ const slowRequestThresholdMs = options.slowRequestThresholdMs ?? 3000;
85
+
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-object-type
87
+ return function <T extends { new (...args: any[]): {} }>(
88
+ target: T,
89
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
90
+ _context: ClassDecoratorContext,
91
+ ) {
92
+ return class extends target {
93
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
+ constructor(...args: any[]) {
95
+ super(...args);
96
+
97
+ const proto = target.prototype;
98
+ const methodNames = Object.getOwnPropertyNames(proto).filter(
99
+ (name) =>
100
+ name !== 'constructor' &&
101
+ typeof proto[name] === 'function' &&
102
+ !name.startsWith('_'),
103
+ );
104
+
105
+ for (const methodName of methodNames) {
106
+ const originalMethod = proto[methodName];
107
+
108
+ if (
109
+ originalMethod.constructor.name === 'AsyncFunction' ||
110
+ originalMethod.toString().startsWith('async ')
111
+ ) {
112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
113
+ const wrappedMethod = async (...args: any[]) => {
114
+ const config = getConfig();
115
+ const tracer = config.tracer;
116
+
117
+ const url = options.urlExtractor
118
+ ? options.urlExtractor(args)
119
+ : (args[0] as string | undefined);
120
+
121
+ const method = options.methodExtractor
122
+ ? options.methodExtractor(methodName, args)
123
+ : inferHttpMethod(methodName);
124
+
125
+ const spanName = url
126
+ ? `HTTP ${method} ${extractPath(url)}`
127
+ : `HTTP ${method}`;
128
+
129
+ return tracer.startActiveSpan(spanName, async (span) => {
130
+ const startTime = performance.now();
131
+
132
+ try {
133
+ span.setAttributes({
134
+ 'http.method': method,
135
+ 'http.url': url || 'unknown',
136
+ 'service.name': serviceName,
137
+ 'operation.name': `${serviceName}.${methodName}`,
138
+ });
139
+
140
+ if (url) {
141
+ const urlObj = parseUrl(url);
142
+ span.setAttributes({
143
+ 'http.scheme': urlObj.protocol,
144
+ 'http.host': urlObj.host,
145
+ 'http.target': urlObj.path,
146
+ });
147
+ }
148
+
149
+ if (options.attributesFromArgs) {
150
+ span.setAttributes(options.attributesFromArgs(args));
151
+ }
152
+
153
+ const result = await originalMethod.apply(this, args);
154
+
155
+ const duration = performance.now() - startTime;
156
+
157
+ // Extract status code from response
158
+ const statusCode = extractStatusCode(result);
159
+ if (statusCode) {
160
+ span.setAttribute('http.status_code', statusCode);
161
+
162
+ if (statusCode >= 400) {
163
+ span.setStatus({
164
+ code: SpanStatusCode.ERROR,
165
+ message: `HTTP ${statusCode}`,
166
+ });
167
+ } else {
168
+ span.setStatus({ code: SpanStatusCode.OK });
169
+ }
170
+ } else {
171
+ span.setStatus({ code: SpanStatusCode.OK });
172
+ }
173
+
174
+ span.setAttributes({
175
+ 'http.duration_ms': duration,
176
+ });
177
+
178
+ // Mark slow requests for investigation
179
+ if (duration > slowRequestThresholdMs) {
180
+ span.setAttribute('http.slow_request', true);
181
+ span.setAttribute(
182
+ 'http.slow_request_threshold_ms',
183
+ slowRequestThresholdMs,
184
+ );
185
+ }
186
+
187
+ return result;
188
+ } catch (error) {
189
+ const duration = performance.now() - startTime;
190
+
191
+ span.setStatus({
192
+ code: SpanStatusCode.ERROR,
193
+ message:
194
+ error instanceof Error ? error.message : 'Unknown error',
195
+ });
196
+
197
+ span.setAttributes({
198
+ 'http.duration_ms': duration,
199
+ 'error.type':
200
+ error instanceof Error
201
+ ? error.constructor.name
202
+ : 'Unknown',
203
+ 'error.message':
204
+ error instanceof Error ? error.message : 'Unknown error',
205
+ });
206
+
207
+ throw error;
208
+ } finally {
209
+ span.end();
210
+ }
211
+ });
212
+ };
213
+
214
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
215
+ (this as any)[methodName] = wrappedMethod;
216
+ }
217
+ }
218
+ }
219
+ };
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Helper: Trace a single HTTP request
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * import { traceHttpRequest } from 'autotel/http'
229
+ *
230
+ * const data = await traceHttpRequest(
231
+ * 'GET /api/users',
232
+ * () => fetch('https://api.example.com/users')
233
+ * )
234
+ * ```
235
+ */
236
+ export async function traceHttpRequest<T>(
237
+ spanName: string,
238
+ fn: () => Promise<T>,
239
+ attributes?: Record<string, string | number>,
240
+ ): Promise<T> {
241
+ const config = getConfig();
242
+ const tracer = config.tracer;
243
+
244
+ return tracer.startActiveSpan(spanName, async (span) => {
245
+ try {
246
+ if (attributes) {
247
+ span.setAttributes(attributes);
248
+ }
249
+
250
+ const result = await fn();
251
+ span.setStatus({ code: SpanStatusCode.OK });
252
+ return result;
253
+ } catch (error) {
254
+ span.setStatus({
255
+ code: SpanStatusCode.ERROR,
256
+ message: error instanceof Error ? error.message : 'Unknown error',
257
+ });
258
+ throw error;
259
+ } finally {
260
+ span.end();
261
+ }
262
+ });
263
+ }
264
+
265
+ // Helper functions
266
+
267
+ function inferHttpMethod(methodName: string): string {
268
+ const lower = methodName.toLowerCase();
269
+ if (
270
+ lower.includes('get') ||
271
+ lower.includes('fetch') ||
272
+ lower.includes('list')
273
+ )
274
+ return 'GET';
275
+ if (lower.includes('post') || lower.includes('create')) return 'POST';
276
+ if (lower.includes('put') || lower.includes('update')) return 'PUT';
277
+ if (lower.includes('delete') || lower.includes('remove')) return 'DELETE';
278
+ if (lower.includes('patch')) return 'PATCH';
279
+ return 'GET'; // Default
280
+ }
281
+
282
+ function extractPath(url: string): string {
283
+ try {
284
+ const urlObj = new URL(url);
285
+ return urlObj.pathname;
286
+ } catch {
287
+ // Relative URL or invalid
288
+ return url.split('?')[0] || url;
289
+ }
290
+ }
291
+
292
+ function parseUrl(url: string): {
293
+ protocol: string;
294
+ host: string;
295
+ path: string;
296
+ } {
297
+ try {
298
+ const urlObj = new URL(url);
299
+ return {
300
+ protocol: urlObj.protocol.replace(':', ''),
301
+ host: urlObj.host,
302
+ path: urlObj.pathname + urlObj.search,
303
+ };
304
+ } catch {
305
+ return {
306
+ protocol: 'http',
307
+ host: 'unknown',
308
+ path: url,
309
+ };
310
+ }
311
+ }
312
+
313
+ function extractStatusCode(result: unknown): number | undefined {
314
+ if (result && typeof result === 'object') {
315
+ // Check for Response.status (fetch API)
316
+ if ('status' in result && typeof result.status === 'number') {
317
+ return result.status;
318
+ }
319
+ // Check for statusCode (axios, node http)
320
+ if ('statusCode' in result && typeof result.statusCode === 'number') {
321
+ return result.statusCode;
322
+ }
323
+ }
324
+ return undefined;
325
+ }
326
+
327
+ /**
328
+ * Inject trace context into HTTP headers (for distributed tracing)
329
+ *
330
+ * This includes W3C Trace Context (traceparent, tracestate) and W3C Baggage headers.
331
+ * Uses OpenTelemetry's propagation system for full compatibility.
332
+ *
333
+ * @example
334
+ * ```typescript
335
+ * import { injectTraceContext } from 'autotel/http'
336
+ *
337
+ * const headers = injectTraceContext({
338
+ * 'Content-Type': 'application/json'
339
+ * })
340
+ *
341
+ * fetch('/api/users', { headers })
342
+ * ```
343
+ *
344
+ * @example With baggage
345
+ * ```typescript
346
+ * import { trace, withBaggage, injectTraceContext } from 'autotel'
347
+ *
348
+ * export const createOrder = trace((ctx) => async (order: Order) => {
349
+ * return await withBaggage({
350
+ * baggage: { 'tenant.id': order.tenantId },
351
+ * fn: async () => {
352
+ * const headers = injectTraceContext();
353
+ * // Headers now include 'baggage' header with tenant.id
354
+ * await fetch('/api/charge', { headers });
355
+ * },
356
+ * });
357
+ * });
358
+ * ```
359
+ */
360
+ export function injectTraceContext(
361
+ headers: Record<string, string> = {},
362
+ ): Record<string, string> {
363
+ // Use getActiveContextWithBaggage to check stored context (from baggage setters)
364
+ // This ensures ctx.setBaggage() changes are included in injected headers
365
+ const currentContext = getActiveContextWithBaggage();
366
+
367
+ // Use OpenTelemetry's propagation.inject for full W3C support
368
+ // This includes traceparent, tracestate, and baggage headers
369
+ propagation.inject(currentContext, headers);
370
+
371
+ return headers;
372
+ }
373
+
374
+ /**
375
+ * Extract trace context from HTTP headers (for distributed tracing)
376
+ *
377
+ * This extracts W3C Trace Context (traceparent, tracestate) and W3C Baggage headers.
378
+ * Uses OpenTelemetry's propagation system for full compatibility.
379
+ *
380
+ * Returns a context that can be used with context.with() to run code
381
+ * with the extracted trace context and baggage.
382
+ *
383
+ * @example
384
+ * ```typescript
385
+ * import { extractTraceContext, trace } from 'autotel'
386
+ * import { context } from 'autotel'
387
+ *
388
+ * // In Express middleware
389
+ * app.use((req, res, next) => {
390
+ * const extractedContext = extractTraceContext(req.headers);
391
+ * context.with(extractedContext, () => {
392
+ * next();
393
+ * });
394
+ * });
395
+ * ```
396
+ *
397
+ * @example In a traced function
398
+ * ```typescript
399
+ * export const handleWebhook = trace((ctx) => async (req: Request) => {
400
+ * const extractedContext = extractTraceContext(req.headers);
401
+ * return await context.with(extractedContext, async () => {
402
+ * // Now ctx.getBaggage() will return baggage from the incoming request
403
+ * const tenantId = ctx.getBaggage('tenant.id');
404
+ * await processWebhook(req.body);
405
+ * });
406
+ * });
407
+ * ```
408
+ */
409
+ export function extractTraceContext(
410
+ headers: Record<string, string | string[] | undefined>,
411
+ ): ReturnType<typeof context.active> {
412
+ const carrier: Record<string, string> = {};
413
+
414
+ // Convert headers to flat string format expected by propagation
415
+ for (const [key, value] of Object.entries(headers)) {
416
+ if (value !== undefined) {
417
+ carrier[key] = Array.isArray(value) ? (value[0] ?? '') : value;
418
+ }
419
+ }
420
+
421
+ // Extract context using OpenTelemetry's propagation system
422
+ // Returns a Context that can be used with context.with()
423
+ return propagation.extract(context.active(), carrier);
424
+ }
package/src/index.ts ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * autotel - Simplified OpenTelemetry instrumentation
3
+ *
4
+ * @example Minimal setup
5
+ * ```typescript
6
+ * import { init, trace, track } from 'autotel'
7
+ *
8
+ * init({ service: 'my-app' })
9
+ *
10
+ * export const createUser = trace(ctx => async (data: CreateUserData) => {
11
+ * track('user.signup', { userId: data.id, plan: data.plan })
12
+ * })
13
+ * ```
14
+ *
15
+ * @example With events
16
+ * ```typescript
17
+ * import { init, trace, track } from 'autotel'
18
+ * import { PostHogSubscriber } from 'autotel-subscribers'
19
+ *
20
+ * init({
21
+ * service: 'my-app',
22
+ * subscribers: [new PostHogSubscriber({ apiKey: '...' })]
23
+ * })
24
+ *
25
+ * export const createUser = trace(ctx => async (data: CreateUserData) => {
26
+ * track('user.signup', { userId: data.id })
27
+ * })
28
+ * ```
29
+ */
30
+
31
+ // Core initialization
32
+ export { init, type AutotelConfig } from './init';
33
+
34
+ // Baggage span processor
35
+ export {
36
+ BaggageSpanProcessor,
37
+ type BaggageSpanProcessorOptions,
38
+ } from './baggage-span-processor';
39
+
40
+ // Functional API (re-export for convenience)
41
+ export type {
42
+ TraceContext,
43
+ SpanOptions,
44
+ WithNewContextOptions,
45
+ WithBaggageOptions,
46
+ InstrumentOptions,
47
+ } from './functional';
48
+ export {
49
+ trace,
50
+ instrument,
51
+ withTracing,
52
+ span,
53
+ withNewContext,
54
+ withBaggage,
55
+ ctx,
56
+ } from './functional';
57
+
58
+ // Operation context (for advanced usage)
59
+ export type { OperationContext } from './operation-context';
60
+ export {
61
+ getOperationContext,
62
+ runInOperationContext,
63
+ } from './operation-context';
64
+
65
+ // Global track function
66
+ export { track } from './track';
67
+
68
+ // Graceful shutdown
69
+ export { flush, shutdown } from './shutdown';
70
+
71
+ // Re-export sampling strategies
72
+ export {
73
+ type Sampler,
74
+ type SamplingContext,
75
+ AlwaysSampler,
76
+ NeverSampler,
77
+ RandomSampler,
78
+ AdaptiveSampler,
79
+ UserIdSampler,
80
+ } from './sampling';
81
+
82
+ // Events API
83
+ export { Event, getEvents, resetEvents, type EventsOptions } from './event';
84
+
85
+ // Metrics API
86
+ export {
87
+ Metric,
88
+ getMetrics,
89
+ resetMetrics,
90
+ type MetricsOptions,
91
+ } from './metric';
92
+
93
+ // Meter helpers for custom metrics
94
+ export {
95
+ getMeter,
96
+ createCounter,
97
+ createHistogram,
98
+ createUpDownCounter,
99
+ createObservableGauge,
100
+ } from './metric-helpers';
101
+
102
+ // Tracer helpers for custom spans
103
+ export {
104
+ getTracer,
105
+ getActiveSpan,
106
+ getActiveContext,
107
+ runWithSpan,
108
+ finalizeSpan,
109
+ createDeterministicTraceId,
110
+ flattenMetadata,
111
+ } from './trace-helpers';
112
+
113
+ // Isolated tracer provider support (advanced - for library authors)
114
+ export {
115
+ setAutotelTracerProvider,
116
+ getAutotelTracerProvider,
117
+ getAutotelTracer,
118
+ } from './tracer-provider';
119
+
120
+ // Semantic convention helpers
121
+ export {
122
+ traceLLM,
123
+ traceDB,
124
+ traceHTTP,
125
+ traceMessaging,
126
+ type LLMConfig,
127
+ type DBConfig,
128
+ type HTTPConfig,
129
+ type MessagingConfig,
130
+ } from './semantic-helpers';
131
+
132
+ // Re-export events types
133
+ export type {
134
+ EventSubscriber,
135
+ EventAttributes,
136
+ FunnelStatus,
137
+ OutcomeStatus,
138
+ } from './event-subscriber';
139
+
140
+ // Re-export OpenTelemetry APIs for convenience
141
+ // (Users shouldn't need to import @opentelemetry/api directly)
142
+ // Note: OTel's trace is exported as 'otelTrace' to avoid naming conflict with autotel's trace()
143
+ // Plugin developers can also access it directly: import { otelTrace } from 'autotel'
144
+ export {
145
+ context,
146
+ propagation,
147
+ SpanStatusCode,
148
+ trace as otelTrace,
149
+ } from '@opentelemetry/api';
150
+
151
+ // Re-export common OpenTelemetry types and utilities
152
+ // This allows plugins and apps to use OTel without needing separate @opentelemetry/api installation
153
+ export type { Span, SpanContext, Tracer, Context } from '@opentelemetry/api';
154
+ export { SpanKind } from '@opentelemetry/api';
155
+ // Note: trace exported from functional.ts, context/propagation/SpanStatusCode already exported above
156
+
157
+ // Export typed baggage helper
158
+ export { defineBaggageSchema } from './trace-context';