autotel 4.1.0 → 4.2.1

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 (253) hide show
  1. package/dist/auto.cjs +5 -3
  2. package/dist/auto.cjs.map +1 -1
  3. package/dist/auto.js +3 -3
  4. package/dist/auto.js.map +1 -1
  5. package/dist/chunk-C_NdSu1c.cjs +34 -0
  6. package/dist/correlation-id.cjs +1 -1
  7. package/dist/correlation-id.d.cts.map +1 -1
  8. package/dist/correlation-id.d.ts.map +1 -1
  9. package/dist/correlation-id.js +1 -1
  10. package/dist/decorators.cjs +1 -1
  11. package/dist/decorators.js +1 -1
  12. package/dist/{event-ByBTV9M2.js → event-531asIM6.js} +4 -4
  13. package/dist/{event-ByBTV9M2.js.map → event-531asIM6.js.map} +1 -1
  14. package/dist/{event-BhHREDJk.cjs → event-CcZYwp50.cjs} +4 -4
  15. package/dist/{event-BhHREDJk.cjs.map → event-CcZYwp50.cjs.map} +1 -1
  16. package/dist/event.cjs +1 -1
  17. package/dist/event.js +1 -1
  18. package/dist/{functional-zpzNLhky.cjs → functional-C8B0Qa7o.cjs} +10 -7
  19. package/dist/functional-C8B0Qa7o.cjs.map +1 -0
  20. package/dist/{functional-DtI0u4vx.js → functional-r-AUIRy_.js} +9 -9
  21. package/dist/functional-r-AUIRy_.js.map +1 -0
  22. package/dist/functional.cjs +1 -1
  23. package/dist/functional.js +1 -1
  24. package/dist/http.cjs +1 -1
  25. package/dist/http.js +1 -1
  26. package/dist/index.cjs +15 -13
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts.map +1 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +14 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/{init-D-jnNMix.js → init-BS2JVkrL.js} +2 -2
  33. package/dist/{init-D-jnNMix.js.map → init-BS2JVkrL.js.map} +1 -1
  34. package/dist/{init-BX7AmFRl.cjs → init-BXiuPK6j.cjs} +3 -3
  35. package/dist/{init-BX7AmFRl.cjs.map → init-BXiuPK6j.cjs.map} +1 -1
  36. package/dist/instrumentation.cjs +2 -2
  37. package/dist/instrumentation.js +2 -2
  38. package/dist/logger.cjs +236 -8
  39. package/dist/logger.cjs.map +1 -0
  40. package/dist/messaging.cjs +1 -1
  41. package/dist/messaging.js +1 -1
  42. package/dist/{node-require-DF5QBX6z.cjs → node-require-CZ_PU448.cjs} +6 -4
  43. package/dist/node-require-CZ_PU448.cjs.map +1 -0
  44. package/dist/{node-require-Db1oDpLj.js → node-require-vROmTeJ8.js} +5 -5
  45. package/dist/node-require-vROmTeJ8.js.map +1 -0
  46. package/dist/{operation-context-C-2hmmtP.js → operation-context-CKBoA4Qy.js} +3 -3
  47. package/dist/operation-context-CKBoA4Qy.js.map +1 -0
  48. package/dist/{operation-context-n4_obUwq.cjs → operation-context-D6LDf4W_.cjs} +3 -1
  49. package/dist/operation-context-D6LDf4W_.cjs.map +1 -0
  50. package/dist/register.cjs +3 -1
  51. package/dist/register.cjs.map +1 -1
  52. package/dist/register.js +2 -2
  53. package/dist/register.js.map +1 -1
  54. package/dist/semantic-helpers.cjs +1 -1
  55. package/dist/semantic-helpers.js +1 -1
  56. package/dist/{stable-hash-Cg5cT34Q.js → stable-hash-ChFBIhNt.js} +3 -3
  57. package/dist/stable-hash-ChFBIhNt.js.map +1 -0
  58. package/dist/{stable-hash-BNTMrmdB.cjs → stable-hash-brKISGf1.cjs} +4 -2
  59. package/dist/stable-hash-brKISGf1.cjs.map +1 -0
  60. package/dist/trace-context-Cijqoi6e.d.cts.map +1 -1
  61. package/dist/trace-context-Cijqoi6e.d.ts.map +1 -1
  62. package/dist/trace-helpers.cjs +1 -1
  63. package/dist/trace-helpers.js +1 -1
  64. package/dist/{track-wc0HafS_.js → track-COUuU48p.js} +5 -5
  65. package/dist/track-COUuU48p.js.map +1 -0
  66. package/dist/{track-D59FfpL0.cjs → track-Cb3Q4QmS.cjs} +4 -2
  67. package/dist/track-Cb3Q4QmS.cjs.map +1 -0
  68. package/dist/validate.cjs +1 -1
  69. package/dist/validate.js +1 -1
  70. package/dist/webhook.cjs +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/workflow-distributed.cjs +1 -1
  73. package/dist/workflow-distributed.js +1 -1
  74. package/dist/workflow.cjs +3 -1
  75. package/dist/workflow.cjs.map +1 -1
  76. package/dist/workflow.d.cts.map +1 -1
  77. package/dist/workflow.d.ts.map +1 -1
  78. package/dist/workflow.js +3 -3
  79. package/dist/workflow.js.map +1 -1
  80. package/dist/yaml-config.cjs +233 -4
  81. package/dist/yaml-config.cjs.map +1 -0
  82. package/dist/yaml-config.d.cts.map +1 -1
  83. package/dist/yaml-config.d.ts.map +1 -1
  84. package/dist/yaml-config.js +8 -7
  85. package/dist/yaml-config.js.map +1 -1
  86. package/package.json +1 -2
  87. package/dist/functional-DtI0u4vx.js.map +0 -1
  88. package/dist/functional-zpzNLhky.cjs.map +0 -1
  89. package/dist/logger-thMPLpOG.cjs +0 -487
  90. package/dist/logger-thMPLpOG.cjs.map +0 -1
  91. package/dist/node-require-DF5QBX6z.cjs.map +0 -1
  92. package/dist/node-require-Db1oDpLj.js.map +0 -1
  93. package/dist/operation-context-C-2hmmtP.js.map +0 -1
  94. package/dist/operation-context-n4_obUwq.cjs.map +0 -1
  95. package/dist/stable-hash-BNTMrmdB.cjs.map +0 -1
  96. package/dist/stable-hash-Cg5cT34Q.js.map +0 -1
  97. package/dist/track-D59FfpL0.cjs.map +0 -1
  98. package/dist/track-wc0HafS_.js.map +0 -1
  99. package/dist/yaml-config-Ck2uB0Dp.cjs +0 -273
  100. package/dist/yaml-config-Ck2uB0Dp.cjs.map +0 -1
  101. package/src/attribute-redacting-processor.test.ts +0 -763
  102. package/src/attribute-redacting-processor.ts +0 -621
  103. package/src/attributes/attachers.ts +0 -161
  104. package/src/attributes/builders.ts +0 -529
  105. package/src/attributes/domains.ts +0 -42
  106. package/src/attributes/index.ts +0 -81
  107. package/src/attributes/registry.ts +0 -323
  108. package/src/attributes/types.ts +0 -211
  109. package/src/attributes/utils.ts +0 -64
  110. package/src/attributes/validators.ts +0 -266
  111. package/src/attributes.test.ts +0 -292
  112. package/src/auto.ts +0 -67
  113. package/src/autotel-logger.test.ts +0 -548
  114. package/src/autotel-logger.ts +0 -364
  115. package/src/baggage-span-processor.test.ts +0 -202
  116. package/src/baggage-span-processor.ts +0 -100
  117. package/src/business-baggage.test.ts +0 -500
  118. package/src/business-baggage.ts +0 -669
  119. package/src/circuit-breaker.test.ts +0 -341
  120. package/src/circuit-breaker.ts +0 -184
  121. package/src/config.test.ts +0 -94
  122. package/src/config.ts +0 -172
  123. package/src/correlated-events.test.ts +0 -151
  124. package/src/correlated-events.ts +0 -47
  125. package/src/correlation-id.test.ts +0 -163
  126. package/src/correlation-id.ts +0 -206
  127. package/src/db.test.ts +0 -252
  128. package/src/db.ts +0 -447
  129. package/src/decorators.test.ts +0 -153
  130. package/src/decorators.ts +0 -188
  131. package/src/define-event.test.ts +0 -41
  132. package/src/define-event.ts +0 -58
  133. package/src/devtools.ts +0 -60
  134. package/src/drain-pipeline.test.ts +0 -68
  135. package/src/drain-pipeline.ts +0 -199
  136. package/src/drain-toolkit.test.ts +0 -113
  137. package/src/drain-toolkit.ts +0 -129
  138. package/src/enricher-toolkit.test.ts +0 -67
  139. package/src/enricher-toolkit.ts +0 -79
  140. package/src/enrichers.test.ts +0 -150
  141. package/src/enrichers.ts +0 -145
  142. package/src/env-config.test.ts +0 -323
  143. package/src/env-config.ts +0 -309
  144. package/src/error-catalog.test.ts +0 -133
  145. package/src/error-catalog.ts +0 -262
  146. package/src/event-queue.test.ts +0 -864
  147. package/src/event-queue.ts +0 -699
  148. package/src/event-subscriber.ts +0 -262
  149. package/src/event-testing.ts +0 -197
  150. package/src/event.test.ts +0 -1104
  151. package/src/event.ts +0 -988
  152. package/src/events-config.ts +0 -235
  153. package/src/exporters.ts +0 -165
  154. package/src/filtering-span-processor.test.ts +0 -281
  155. package/src/filtering-span-processor.ts +0 -111
  156. package/src/flatten-attributes.test.ts +0 -76
  157. package/src/flatten-attributes.ts +0 -80
  158. package/src/functional.strict-types.typecheck.ts +0 -53
  159. package/src/functional.test.ts +0 -1464
  160. package/src/functional.ts +0 -2539
  161. package/src/functional.types.test.ts +0 -135
  162. package/src/hook.mjs +0 -15
  163. package/src/http.test.ts +0 -485
  164. package/src/http.ts +0 -424
  165. package/src/index.ts +0 -433
  166. package/src/init-auto-redactor.test.ts +0 -53
  167. package/src/init-redactor.test.ts +0 -8
  168. package/src/init.customization.test.ts +0 -665
  169. package/src/init.integrations.test.ts +0 -399
  170. package/src/init.openllmetry.test.ts +0 -194
  171. package/src/init.protocol.test.ts +0 -215
  172. package/src/init.ts +0 -2439
  173. package/src/instrumentation.test.ts +0 -108
  174. package/src/instrumentation.ts +0 -319
  175. package/src/logger.test.ts +0 -125
  176. package/src/logger.ts +0 -341
  177. package/src/messaging-adapters.test.ts +0 -595
  178. package/src/messaging-adapters.ts +0 -583
  179. package/src/messaging-testing.test.ts +0 -573
  180. package/src/messaging-testing.ts +0 -935
  181. package/src/messaging.test.ts +0 -1646
  182. package/src/messaging.ts +0 -2245
  183. package/src/metric-helpers.ts +0 -47
  184. package/src/metric-testing.ts +0 -197
  185. package/src/metric.ts +0 -446
  186. package/src/metrics.test.ts +0 -241
  187. package/src/node-require.ts +0 -123
  188. package/src/operation-context.ts +0 -93
  189. package/src/parse-error.test.ts +0 -73
  190. package/src/parse-error.ts +0 -112
  191. package/src/posthog-logs.test.ts +0 -115
  192. package/src/posthog-logs.ts +0 -77
  193. package/src/pretty-console-exporter.test.ts +0 -545
  194. package/src/pretty-console-exporter.ts +0 -413
  195. package/src/pretty-log-formatter.test.ts +0 -123
  196. package/src/pretty-log-formatter.ts +0 -210
  197. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  198. package/src/processors/canonical-log-line-processor.ts +0 -396
  199. package/src/processors.ts +0 -152
  200. package/src/rate-limiter.test.ts +0 -199
  201. package/src/rate-limiter.ts +0 -98
  202. package/src/redact-values.test.ts +0 -90
  203. package/src/redact-values.ts +0 -34
  204. package/src/register.ts +0 -37
  205. package/src/request-logger.test.ts +0 -545
  206. package/src/request-logger.ts +0 -342
  207. package/src/sampling.test.ts +0 -1060
  208. package/src/sampling.ts +0 -737
  209. package/src/security-schema.test.ts +0 -45
  210. package/src/security-schema.ts +0 -107
  211. package/src/semantic-conventions.ts +0 -15
  212. package/src/semantic-helpers.test.ts +0 -226
  213. package/src/semantic-helpers.ts +0 -438
  214. package/src/shutdown.test.ts +0 -364
  215. package/src/shutdown.ts +0 -246
  216. package/src/span-name-normalizer.test.ts +0 -377
  217. package/src/span-name-normalizer.ts +0 -213
  218. package/src/stable-hash.ts +0 -27
  219. package/src/structured-error.test.ts +0 -191
  220. package/src/structured-error.ts +0 -157
  221. package/src/stub.integration.test.ts +0 -361
  222. package/src/tail-sampling-processor.test.ts +0 -230
  223. package/src/tail-sampling-processor.ts +0 -55
  224. package/src/test-span-collector.test.ts +0 -234
  225. package/src/test-span-collector.ts +0 -150
  226. package/src/testing.ts +0 -705
  227. package/src/trace-context.test.ts +0 -73
  228. package/src/trace-context.ts +0 -567
  229. package/src/trace-helpers.new.test.ts +0 -278
  230. package/src/trace-helpers.test.ts +0 -290
  231. package/src/trace-helpers.ts +0 -710
  232. package/src/trace-hybrid.test.ts +0 -42
  233. package/src/trace-hybrid.ts +0 -37
  234. package/src/tracer-provider.test.ts +0 -183
  235. package/src/tracer-provider.ts +0 -266
  236. package/src/track.test.ts +0 -154
  237. package/src/track.ts +0 -216
  238. package/src/validate.test.ts +0 -287
  239. package/src/validate.ts +0 -307
  240. package/src/validation-attributes.ts +0 -43
  241. package/src/validation.test.ts +0 -330
  242. package/src/validation.ts +0 -246
  243. package/src/variable-name-inference.test.ts +0 -178
  244. package/src/variable-name-inference.ts +0 -242
  245. package/src/webhook.test.ts +0 -649
  246. package/src/webhook.ts +0 -637
  247. package/src/workflow-distributed.test.ts +0 -786
  248. package/src/workflow-distributed.ts +0 -916
  249. package/src/workflow.async-safety.integration.test.ts +0 -345
  250. package/src/workflow.test.ts +0 -647
  251. package/src/workflow.ts +0 -810
  252. package/src/yaml-config.test.ts +0 -373
  253. package/src/yaml-config.ts +0 -351
package/src/http.ts DELETED
@@ -1,424 +0,0 @@
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
- }