autotel 2.26.2 → 3.0.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 (144) hide show
  1. package/README.md +29 -19
  2. package/dist/attributes.d.cts +3 -3
  3. package/dist/attributes.d.ts +3 -3
  4. package/dist/business-baggage.d.cts +1 -1
  5. package/dist/business-baggage.d.ts +1 -1
  6. package/dist/{chunk-YN7USLHW.js → chunk-3QMFLJHJ.js} +11 -10
  7. package/dist/chunk-3QMFLJHJ.js.map +1 -0
  8. package/dist/{chunk-BJ2XPN77.js → chunk-4DAG3RFS.js} +4 -4
  9. package/dist/{chunk-BJ2XPN77.js.map → chunk-4DAG3RFS.js.map} +1 -1
  10. package/dist/chunk-4P6ZOARG.cjs +33 -0
  11. package/dist/chunk-4P6ZOARG.cjs.map +1 -0
  12. package/dist/{chunk-U54FTVFH.js → chunk-7HNQYHK4.js} +3 -3
  13. package/dist/{chunk-U54FTVFH.js.map → chunk-7HNQYHK4.js.map} +1 -1
  14. package/dist/chunk-CJ4PD2TZ.cjs +1207 -0
  15. package/dist/chunk-CJ4PD2TZ.cjs.map +1 -0
  16. package/dist/{chunk-HPUGKUMZ.js → chunk-DAAJLUTO.js} +13 -640
  17. package/dist/chunk-DAAJLUTO.js.map +1 -0
  18. package/dist/{chunk-B3ZHLLMP.js → chunk-DSMSIVTG.js} +2 -2
  19. package/dist/chunk-DSMSIVTG.js.map +1 -0
  20. package/dist/{chunk-6YGUN7IY.cjs → chunk-DWOBIBLY.cjs} +18 -17
  21. package/dist/chunk-DWOBIBLY.cjs.map +1 -0
  22. package/dist/{chunk-QC5MNKVF.js → chunk-IUDXKLS4.js} +13 -12
  23. package/dist/chunk-IUDXKLS4.js.map +1 -0
  24. package/dist/{chunk-OBWXM4NN.cjs → chunk-KHGA4OST.cjs} +15 -14
  25. package/dist/chunk-KHGA4OST.cjs.map +1 -0
  26. package/dist/chunk-KIL5CUN6.js +31 -0
  27. package/dist/chunk-KIL5CUN6.js.map +1 -0
  28. package/dist/{chunk-YEVCD6DR.cjs → chunk-L7JDUDJD.cjs} +7 -7
  29. package/dist/{chunk-YEVCD6DR.cjs.map → chunk-L7JDUDJD.cjs.map} +1 -1
  30. package/dist/{chunk-UTZR7P7E.cjs → chunk-MOK3E54E.cjs} +29 -659
  31. package/dist/chunk-MOK3E54E.cjs.map +1 -0
  32. package/dist/{chunk-GML3FBOT.cjs → chunk-NCSMD3TK.cjs} +2 -2
  33. package/dist/chunk-NCSMD3TK.cjs.map +1 -0
  34. package/dist/chunk-QG3U5ONP.js +1183 -0
  35. package/dist/chunk-QG3U5ONP.js.map +1 -0
  36. package/dist/chunk-SEO6NAQT.js +14 -0
  37. package/dist/chunk-SEO6NAQT.js.map +1 -0
  38. package/dist/chunk-VQTCQKHQ.cjs +17 -0
  39. package/dist/chunk-VQTCQKHQ.cjs.map +1 -0
  40. package/dist/{chunk-WZOKY3PW.cjs → chunk-ZSABTI3C.cjs} +8 -8
  41. package/dist/{chunk-WZOKY3PW.cjs.map → chunk-ZSABTI3C.cjs.map} +1 -1
  42. package/dist/correlation-id.cjs +22 -10
  43. package/dist/correlation-id.js +14 -2
  44. package/dist/decorators.cjs +5 -6
  45. package/dist/decorators.cjs.map +1 -1
  46. package/dist/decorators.d.cts +1 -1
  47. package/dist/decorators.d.ts +1 -1
  48. package/dist/decorators.js +4 -5
  49. package/dist/decorators.js.map +1 -1
  50. package/dist/event.cjs +6 -7
  51. package/dist/event.js +3 -4
  52. package/dist/functional.cjs +11 -12
  53. package/dist/functional.d.cts +1 -1
  54. package/dist/functional.d.ts +1 -1
  55. package/dist/functional.js +4 -5
  56. package/dist/http.cjs +13 -2
  57. package/dist/http.cjs.map +1 -1
  58. package/dist/http.js +12 -1
  59. package/dist/http.js.map +1 -1
  60. package/dist/index.cjs +134 -243
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.d.cts +23 -8
  63. package/dist/index.d.ts +23 -8
  64. package/dist/index.js +52 -176
  65. package/dist/index.js.map +1 -1
  66. package/dist/messaging-adapters.d.cts +1 -1
  67. package/dist/messaging-adapters.d.ts +1 -1
  68. package/dist/messaging-testing.d.cts +1 -1
  69. package/dist/messaging-testing.d.ts +1 -1
  70. package/dist/messaging.cjs +9 -9
  71. package/dist/messaging.d.cts +1 -1
  72. package/dist/messaging.d.ts +1 -1
  73. package/dist/messaging.js +6 -6
  74. package/dist/semantic-helpers.cjs +9 -10
  75. package/dist/semantic-helpers.d.cts +1 -1
  76. package/dist/semantic-helpers.d.ts +1 -1
  77. package/dist/semantic-helpers.js +5 -6
  78. package/dist/{trace-context-t5X1AP-e.d.ts → trace-context-DbGKd1Rn.d.cts} +18 -5
  79. package/dist/{trace-context-t5X1AP-e.d.cts → trace-context-DbGKd1Rn.d.ts} +18 -5
  80. package/dist/trace-helpers.cjs +13 -13
  81. package/dist/trace-helpers.d.cts +2 -2
  82. package/dist/trace-helpers.d.ts +2 -2
  83. package/dist/trace-helpers.js +1 -1
  84. package/dist/{utils-CbUkl8r1.d.cts → utils-BahBCFtJ.d.cts} +1 -1
  85. package/dist/{utils-Buel3cj0.d.ts → utils-CLKwaUlG.d.ts} +1 -1
  86. package/dist/webhook.cjs +19 -10
  87. package/dist/webhook.cjs.map +1 -1
  88. package/dist/webhook.d.cts +1 -1
  89. package/dist/webhook.d.ts +1 -1
  90. package/dist/webhook.js +18 -9
  91. package/dist/webhook.js.map +1 -1
  92. package/dist/workflow-distributed.cjs +23 -19
  93. package/dist/workflow-distributed.cjs.map +1 -1
  94. package/dist/workflow-distributed.d.cts +1 -1
  95. package/dist/workflow-distributed.d.ts +1 -1
  96. package/dist/workflow-distributed.js +21 -17
  97. package/dist/workflow-distributed.js.map +1 -1
  98. package/dist/workflow.cjs +10 -10
  99. package/dist/workflow.d.cts +1 -1
  100. package/dist/workflow.d.ts +1 -1
  101. package/dist/workflow.js +6 -6
  102. package/package.json +38 -38
  103. package/skills/autotel-core/SKILL.md +2 -0
  104. package/skills/autotel-events/SKILL.md +2 -0
  105. package/skills/autotel-frameworks/SKILL.md +2 -0
  106. package/skills/autotel-instrumentation/SKILL.md +2 -0
  107. package/skills/autotel-request-logging/SKILL.md +2 -0
  108. package/skills/autotel-structured-errors/SKILL.md +2 -0
  109. package/src/correlated-events.test.ts +151 -0
  110. package/src/correlated-events.ts +47 -0
  111. package/src/functional.ts +2 -0
  112. package/src/gen-ai-events.ts +14 -5
  113. package/src/index.ts +20 -4
  114. package/src/messaging.ts +10 -9
  115. package/src/request-logger.ts +4 -3
  116. package/src/structured-error.test.ts +83 -1
  117. package/src/structured-error.ts +9 -2
  118. package/src/trace-context.ts +39 -11
  119. package/src/trace-helpers.ts +2 -2
  120. package/src/trace-hybrid.test.ts +42 -0
  121. package/src/trace-hybrid.ts +37 -0
  122. package/src/webhook.ts +16 -7
  123. package/src/workflow-distributed.ts +18 -13
  124. package/src/workflow.ts +7 -6
  125. package/dist/chunk-6YGUN7IY.cjs.map +0 -1
  126. package/dist/chunk-B3ZHLLMP.js.map +0 -1
  127. package/dist/chunk-BBBWDIYQ.js +0 -211
  128. package/dist/chunk-BBBWDIYQ.js.map +0 -1
  129. package/dist/chunk-D5LMF53P.cjs +0 -150
  130. package/dist/chunk-D5LMF53P.cjs.map +0 -1
  131. package/dist/chunk-GML3FBOT.cjs.map +0 -1
  132. package/dist/chunk-HPUGKUMZ.js.map +0 -1
  133. package/dist/chunk-HZ3FYBJG.cjs +0 -217
  134. package/dist/chunk-HZ3FYBJG.cjs.map +0 -1
  135. package/dist/chunk-JSNUWSBH.cjs +0 -62
  136. package/dist/chunk-JSNUWSBH.cjs.map +0 -1
  137. package/dist/chunk-OBWXM4NN.cjs.map +0 -1
  138. package/dist/chunk-QC5MNKVF.js.map +0 -1
  139. package/dist/chunk-S4OFEXLA.js +0 -53
  140. package/dist/chunk-S4OFEXLA.js.map +0 -1
  141. package/dist/chunk-UTZR7P7E.cjs.map +0 -1
  142. package/dist/chunk-WD4RP6IV.js +0 -146
  143. package/dist/chunk-WD4RP6IV.js.map +0 -1
  144. package/dist/chunk-YN7USLHW.js.map +0 -1
@@ -0,0 +1,1207 @@
1
+ 'use strict';
2
+
3
+ var chunk563EL6O6_cjs = require('./chunk-563EL6O6.cjs');
4
+ var chunkESLWRGAG_cjs = require('./chunk-ESLWRGAG.cjs');
5
+ var api = require('@opentelemetry/api');
6
+ var async_hooks = require('async_hooks');
7
+
8
+ // src/flatten-attributes.ts
9
+ function toAttributeValue(value) {
10
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
11
+ return value;
12
+ }
13
+ if (Array.isArray(value)) {
14
+ if (value.every((v) => typeof v === "string") || value.every((v) => typeof v === "number") || value.every((v) => typeof v === "boolean")) {
15
+ return value;
16
+ }
17
+ try {
18
+ return JSON.stringify(value);
19
+ } catch {
20
+ return "<serialization-failed>";
21
+ }
22
+ }
23
+ if (value instanceof Date) {
24
+ return value.toISOString();
25
+ }
26
+ if (value instanceof Error) {
27
+ return value.message;
28
+ }
29
+ return void 0;
30
+ }
31
+ function flattenToAttributes(fields, prefix = "") {
32
+ const out = {};
33
+ const seen = /* @__PURE__ */ new WeakSet();
34
+ function flatten(obj, currentPrefix) {
35
+ for (const [key, value] of Object.entries(obj)) {
36
+ if (value == null) continue;
37
+ const nextKey = currentPrefix ? `${currentPrefix}.${key}` : key;
38
+ const attr = toAttributeValue(value);
39
+ if (attr !== void 0) {
40
+ out[nextKey] = attr;
41
+ continue;
42
+ }
43
+ if (typeof value === "object" && value.constructor === Object) {
44
+ if (seen.has(value)) {
45
+ out[nextKey] = "<circular-reference>";
46
+ continue;
47
+ }
48
+ seen.add(value);
49
+ flatten(value, nextKey);
50
+ continue;
51
+ }
52
+ try {
53
+ out[nextKey] = JSON.stringify(value);
54
+ } catch {
55
+ out[nextKey] = "<serialization-failed>";
56
+ }
57
+ }
58
+ }
59
+ flatten(fields, prefix);
60
+ return out;
61
+ }
62
+
63
+ // src/structured-error.ts
64
+ var internalKey = /* @__PURE__ */ Symbol.for("autotel.error.internal");
65
+ function createStructuredError(input) {
66
+ const error = new Error(input.message, {
67
+ cause: input.cause
68
+ });
69
+ error.name = input.name ?? "StructuredError";
70
+ if (input.why !== void 0) error.why = input.why;
71
+ if (input.fix !== void 0) error.fix = input.fix;
72
+ if (input.link !== void 0) error.link = input.link;
73
+ if (input.code !== void 0) error.code = input.code;
74
+ if (input.status !== void 0) error.status = input.status;
75
+ if (input.details !== void 0) error.details = input.details;
76
+ if (input.internal !== void 0) {
77
+ Object.defineProperty(error, internalKey, {
78
+ value: input.internal,
79
+ enumerable: false,
80
+ writable: false,
81
+ configurable: true
82
+ });
83
+ }
84
+ Object.defineProperty(error, "internal", {
85
+ get() {
86
+ return this[internalKey];
87
+ },
88
+ enumerable: false,
89
+ configurable: true
90
+ });
91
+ error.toString = () => {
92
+ const lines = [`${error.name}: ${error.message}`];
93
+ if (error.why) lines.push(` Why: ${error.why}`);
94
+ if (error.fix) lines.push(` Fix: ${error.fix}`);
95
+ if (error.link) lines.push(` Link: ${error.link}`);
96
+ if (error.code !== void 0) lines.push(` Code: ${error.code}`);
97
+ if (error.status !== void 0) lines.push(` Status: ${error.status}`);
98
+ if (error.cause) {
99
+ const cause = error.cause;
100
+ lines.push(` Caused by: ${cause.name}: ${cause.message}`);
101
+ }
102
+ return lines.join("\n");
103
+ };
104
+ return error;
105
+ }
106
+ function structuredErrorToJSON(error) {
107
+ const result = {
108
+ name: error.name,
109
+ message: error.message
110
+ };
111
+ if (error.status !== void 0) result.status = error.status;
112
+ if (error.why || error.fix || error.link) {
113
+ result.data = {
114
+ ...error.why && { why: error.why },
115
+ ...error.fix && { fix: error.fix },
116
+ ...error.link && { link: error.link }
117
+ };
118
+ }
119
+ if (error.code !== void 0) result.code = error.code;
120
+ if (error.details) result.details = error.details;
121
+ if (error.cause instanceof Error) {
122
+ result.cause = { name: error.cause.name, message: error.cause.message };
123
+ }
124
+ return result;
125
+ }
126
+ function getStructuredErrorAttributes(error) {
127
+ const structured = error;
128
+ const attributes = {
129
+ "error.type": error.name || "Error",
130
+ "error.message": error.message
131
+ };
132
+ if (error.stack) attributes["error.stack"] = error.stack;
133
+ if (structured.why) attributes["error.why"] = structured.why;
134
+ if (structured.fix) attributes["error.fix"] = structured.fix;
135
+ if (structured.link) attributes["error.link"] = structured.link;
136
+ if (structured.code !== void 0) {
137
+ attributes["error.code"] = typeof structured.code === "string" ? structured.code : String(structured.code);
138
+ }
139
+ if (structured.status !== void 0) {
140
+ attributes["error.status"] = structured.status;
141
+ }
142
+ if (structured.details) {
143
+ Object.assign(
144
+ attributes,
145
+ flattenToAttributes(structured.details, "error.details")
146
+ );
147
+ }
148
+ return attributes;
149
+ }
150
+ function recordStructuredError(ctx, error) {
151
+ const maybeRecordException = ctx.recordException;
152
+ if (typeof maybeRecordException === "function") {
153
+ maybeRecordException(error);
154
+ }
155
+ ctx.setStatus({
156
+ code: api.SpanStatusCode.ERROR,
157
+ message: error.message
158
+ });
159
+ ctx.setAttributes(getStructuredErrorAttributes(error));
160
+ }
161
+
162
+ // src/rate-limiter.ts
163
+ var TokenBucketRateLimiter = class {
164
+ tokens;
165
+ maxTokens;
166
+ refillRate;
167
+ // tokens per millisecond
168
+ lastRefill;
169
+ constructor(config) {
170
+ this.maxTokens = config.burstCapacity || config.maxEventsPerSecond * 2;
171
+ this.tokens = this.maxTokens;
172
+ this.refillRate = config.maxEventsPerSecond / 1e3;
173
+ this.lastRefill = Date.now();
174
+ }
175
+ /**
176
+ * Try to consume a token (allow an event)
177
+ * Returns true if allowed, false if rate limit exceeded
178
+ */
179
+ tryConsume(count = 1) {
180
+ this.refill();
181
+ if (this.tokens >= count) {
182
+ this.tokens -= count;
183
+ return true;
184
+ }
185
+ return false;
186
+ }
187
+ /**
188
+ * Wait until a token is available (async rate limiting)
189
+ * Returns a promise that resolves when the event can be processed
190
+ */
191
+ async waitForToken(count = 1) {
192
+ this.refill();
193
+ if (this.tokens >= count) {
194
+ this.tokens -= count;
195
+ return;
196
+ }
197
+ const tokensNeeded = count - this.tokens;
198
+ const waitMs = Math.ceil(tokensNeeded / this.refillRate);
199
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
200
+ return this.waitForToken(count);
201
+ }
202
+ /**
203
+ * Refill tokens based on elapsed time
204
+ */
205
+ refill() {
206
+ const now = Date.now();
207
+ const elapsed = now - this.lastRefill;
208
+ const tokensToAdd = elapsed * this.refillRate;
209
+ this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
210
+ this.lastRefill = now;
211
+ }
212
+ /**
213
+ * Get current available tokens (for testing/debugging)
214
+ */
215
+ getAvailableTokens() {
216
+ this.refill();
217
+ return Math.floor(this.tokens);
218
+ }
219
+ /**
220
+ * Reset the rate limiter (for testing)
221
+ */
222
+ reset() {
223
+ this.tokens = this.maxTokens;
224
+ this.lastRefill = Date.now();
225
+ }
226
+ };
227
+
228
+ // src/event-queue.ts
229
+ var DEFAULT_CONFIG = {
230
+ maxSize: 5e4,
231
+ batchSize: 100,
232
+ flushInterval: 1e4,
233
+ maxRetries: 3,
234
+ rateLimit: {
235
+ maxEventsPerSecond: 100,
236
+ burstCapacity: 200
237
+ }
238
+ };
239
+ function getSubscriberName(subscriber) {
240
+ if (subscriber.name) {
241
+ return subscriber.name.toLowerCase();
242
+ }
243
+ const className = subscriber.constructor?.name || "unknown";
244
+ return className.replace(/Subscriber$/i, "").toLowerCase();
245
+ }
246
+ var EventQueue = class {
247
+ queue = [];
248
+ flushTimer = null;
249
+ config;
250
+ subscribers;
251
+ rateLimiter;
252
+ flushPromise = null;
253
+ isShuttingDown = false;
254
+ // Metrics
255
+ metrics = null;
256
+ // Observable callback cleanup functions
257
+ observableCleanups = [];
258
+ // Subscriber health tracking (for observable gauges)
259
+ subscriberHealthy = /* @__PURE__ */ new Map();
260
+ constructor(subscribers, config) {
261
+ this.subscribers = subscribers;
262
+ this.config = { ...DEFAULT_CONFIG, ...config };
263
+ this.rateLimiter = this.config.rateLimit ? new TokenBucketRateLimiter(this.config.rateLimit) : null;
264
+ for (const subscriber of subscribers) {
265
+ const name = getSubscriberName(subscriber);
266
+ this.subscriberHealthy.set(name, true);
267
+ }
268
+ this.initMetrics();
269
+ }
270
+ /**
271
+ * Initialize OTel metrics for queue observability
272
+ */
273
+ initMetrics() {
274
+ const runtimeConfig = chunkESLWRGAG_cjs.getConfig();
275
+ const meter = runtimeConfig.meter;
276
+ const queueSize = meter.createObservableGauge(
277
+ "autotel.event_delivery.queue.size",
278
+ {
279
+ description: "Current number of events in the delivery queue",
280
+ unit: "count"
281
+ }
282
+ );
283
+ const queueSizeCallback = (observableResult) => {
284
+ observableResult.observe(this.queue.length);
285
+ };
286
+ queueSize.addCallback(queueSizeCallback);
287
+ this.observableCleanups.push(
288
+ () => queueSize.removeCallback(queueSizeCallback)
289
+ );
290
+ const oldestAge = meter.createObservableGauge(
291
+ "autotel.event_delivery.queue.oldest_age_ms",
292
+ {
293
+ description: "Age of the oldest event in the queue in milliseconds",
294
+ unit: "ms"
295
+ }
296
+ );
297
+ const oldestAgeCallback = (observableResult) => {
298
+ if (this.queue.length > 0) {
299
+ const oldest = this.queue[0];
300
+ const ageMs = Date.now() - oldest.timestamp;
301
+ observableResult.observe(ageMs);
302
+ } else {
303
+ observableResult.observe(0);
304
+ }
305
+ };
306
+ oldestAge.addCallback(oldestAgeCallback);
307
+ this.observableCleanups.push(
308
+ () => oldestAge.removeCallback(oldestAgeCallback)
309
+ );
310
+ const delivered = meter.createCounter(
311
+ "autotel.event_delivery.queue.delivered",
312
+ {
313
+ description: "Number of events successfully delivered to subscribers",
314
+ unit: "count"
315
+ }
316
+ );
317
+ const failed = meter.createCounter("autotel.event_delivery.queue.failed", {
318
+ description: "Number of events that failed delivery after all retry attempts",
319
+ unit: "count"
320
+ });
321
+ const dropped = meter.createCounter(
322
+ "autotel.event_delivery.queue.dropped",
323
+ {
324
+ description: "Number of events dropped from the queue",
325
+ unit: "count"
326
+ }
327
+ );
328
+ const latency = meter.createHistogram(
329
+ "autotel.event_delivery.queue.latency_ms",
330
+ {
331
+ description: "Event delivery latency from enqueue to successful send",
332
+ unit: "ms"
333
+ }
334
+ );
335
+ const subscriberHealth = meter.createObservableGauge(
336
+ "autotel.event_delivery.subscriber.health",
337
+ {
338
+ description: "Subscriber health status (1=healthy, 0=unhealthy)",
339
+ unit: "1"
340
+ }
341
+ );
342
+ const subscriberHealthCallback = (observableResult) => {
343
+ for (const [subscriberName, isHealthy] of this.subscriberHealthy) {
344
+ observableResult.observe(isHealthy ? 1 : 0, {
345
+ subscriber: subscriberName
346
+ });
347
+ }
348
+ };
349
+ subscriberHealth.addCallback(subscriberHealthCallback);
350
+ this.observableCleanups.push(
351
+ () => subscriberHealth.removeCallback(subscriberHealthCallback)
352
+ );
353
+ this.metrics = {
354
+ queueSize,
355
+ oldestAge,
356
+ delivered,
357
+ failed,
358
+ dropped,
359
+ latency,
360
+ subscriberHealth
361
+ };
362
+ }
363
+ /**
364
+ * Record a dropped event with reason and emit debug breadcrumb
365
+ */
366
+ recordDropped(reason, event, subscriberName) {
367
+ const attrs = { reason };
368
+ if (subscriberName) {
369
+ attrs.subscriber = subscriberName;
370
+ }
371
+ this.metrics?.dropped.add(1, attrs);
372
+ const logLevel = reason === "payload_invalid" ? "error" : "warn";
373
+ const logger = chunk563EL6O6_cjs.getLogger();
374
+ if (logLevel === "error") {
375
+ logger.error(
376
+ {
377
+ eventName: event?.name,
378
+ subscriber: subscriberName,
379
+ reason,
380
+ correlationId: event?._correlationId,
381
+ traceId: event?._traceId
382
+ },
383
+ `[autotel] Event dropped: ${reason}`
384
+ );
385
+ } else {
386
+ logger.warn(
387
+ {
388
+ eventName: event?.name,
389
+ subscriber: subscriberName,
390
+ reason,
391
+ correlationId: event?._correlationId,
392
+ traceId: event?._traceId
393
+ },
394
+ `[autotel] Event dropped: ${reason}`
395
+ );
396
+ }
397
+ }
398
+ /**
399
+ * Record permanent delivery failure (after all retries exhausted)
400
+ * Increments failed counter and logs error
401
+ */
402
+ recordFailed(event, subscriberName, error) {
403
+ this.metrics?.failed.add(1, { subscriber: subscriberName });
404
+ this.subscriberHealthy.set(subscriberName, false);
405
+ chunk563EL6O6_cjs.getLogger().error(
406
+ {
407
+ eventName: event.name,
408
+ subscriber: subscriberName,
409
+ correlationId: event._correlationId,
410
+ traceId: event._traceId,
411
+ err: error
412
+ },
413
+ `[autotel] Event delivery failed after all retries`
414
+ );
415
+ }
416
+ /**
417
+ * Mark subscriber as unhealthy on transient failure (without incrementing failed counter)
418
+ * Used during retry attempts - only recordFailed should increment the counter
419
+ */
420
+ markSubscriberUnhealthy(subscriberName) {
421
+ this.subscriberHealthy.set(subscriberName, false);
422
+ }
423
+ /**
424
+ * Record successful delivery
425
+ */
426
+ recordDelivered(event, subscriberName, startTime) {
427
+ const latencyMs = Date.now() - startTime;
428
+ this.metrics?.delivered.add(1, { subscriber: subscriberName });
429
+ this.metrics?.latency.record(latencyMs, { subscriber: subscriberName });
430
+ this.subscriberHealthy.set(subscriberName, true);
431
+ }
432
+ /**
433
+ * Enqueue an event for sending
434
+ *
435
+ * Backpressure policy:
436
+ * - Drops oldest event and logs warning if queue is full (same behavior in all environments)
437
+ */
438
+ enqueue(event) {
439
+ if (this.isShuttingDown) {
440
+ this.recordDropped("shutdown", event);
441
+ return;
442
+ }
443
+ if (this.queue.length >= this.config.maxSize) {
444
+ const droppedEvent = this.queue.shift();
445
+ this.recordDropped("rate_limit", droppedEvent);
446
+ chunk563EL6O6_cjs.getLogger().warn(
447
+ {
448
+ droppedEvent: droppedEvent?.name
449
+ },
450
+ `[autotel] Events queue full (${this.config.maxSize} events). Dropping oldest event. Events are being produced faster than they can be sent. Check your subscribers or reduce tracking frequency.`
451
+ );
452
+ }
453
+ const enrichedEvent = {
454
+ ...event,
455
+ _correlationId: event._correlationId || getOrCreateCorrelationId()
456
+ };
457
+ this.queue.push(enrichedEvent);
458
+ this.scheduleBatchFlush();
459
+ }
460
+ /**
461
+ * Schedule a batch flush if not already scheduled
462
+ */
463
+ scheduleBatchFlush() {
464
+ if (this.flushTimer || this.flushPromise) return;
465
+ this.flushTimer = setTimeout(() => {
466
+ this.flushTimer = null;
467
+ void this.flushBatch();
468
+ }, this.config.flushInterval);
469
+ }
470
+ /**
471
+ * Flush a batch of events
472
+ * Uses promise-based concurrency control to prevent race conditions
473
+ */
474
+ async flushBatch() {
475
+ if (this.queue.length === 0) return;
476
+ if (this.flushPromise) {
477
+ await this.flushPromise;
478
+ return;
479
+ }
480
+ this.flushPromise = this.doFlushBatch();
481
+ try {
482
+ await this.flushPromise;
483
+ } finally {
484
+ this.flushPromise = null;
485
+ if (this.queue.length > 0) {
486
+ this.scheduleBatchFlush();
487
+ }
488
+ }
489
+ }
490
+ /**
491
+ * Internal flush implementation
492
+ */
493
+ async doFlushBatch() {
494
+ const batch = this.queue.splice(0, this.config.batchSize);
495
+ await this.sendWithRetry(batch, this.config.maxRetries);
496
+ }
497
+ /**
498
+ * Send events with exponential backoff retry
499
+ * Tracks per-event, per-subscriber failures so failed counter reflects actual failed deliveries.
500
+ * On retry, only failed (event, subscriber) pairs are re-sent to avoid double-counting delivered.
501
+ */
502
+ async sendWithRetry(events, retriesLeft, subscribersByEventIndex) {
503
+ const failedDeliveries = await this.sendToSubscribers(
504
+ events,
505
+ subscribersByEventIndex
506
+ );
507
+ if (failedDeliveries.length > 0) {
508
+ if (retriesLeft > 0) {
509
+ const failedEventIndices = new Set(
510
+ failedDeliveries.map((f) => f.eventIndex)
511
+ );
512
+ const failedEventIndicesOrdered = [...failedEventIndices].sort(
513
+ (a, b) => a - b
514
+ );
515
+ const eventsToRetry = failedEventIndicesOrdered.map(
516
+ (i) => events[i]
517
+ );
518
+ const failedSubscribersByRetryIndex = /* @__PURE__ */ new Map();
519
+ for (let j = 0; j < failedEventIndicesOrdered.length; j++) {
520
+ const origIndex = failedEventIndicesOrdered[j];
521
+ const set = /* @__PURE__ */ new Set();
522
+ for (const { eventIndex, subscriberName } of failedDeliveries) {
523
+ if (eventIndex === origIndex) set.add(subscriberName);
524
+ }
525
+ failedSubscribersByRetryIndex.set(j, set);
526
+ }
527
+ const delay = Math.pow(2, this.config.maxRetries - retriesLeft) * 1e3;
528
+ await new Promise((resolve) => setTimeout(resolve, delay));
529
+ return this.sendWithRetry(
530
+ eventsToRetry,
531
+ retriesLeft - 1,
532
+ failedSubscribersByRetryIndex
533
+ );
534
+ } else {
535
+ for (const { eventIndex, subscriberName, error } of failedDeliveries) {
536
+ const event = events[eventIndex];
537
+ if (event) this.recordFailed(event, subscriberName, error);
538
+ }
539
+ const failedSubscriberNames = [
540
+ ...new Set(failedDeliveries.map((f) => f.subscriberName))
541
+ ];
542
+ chunk563EL6O6_cjs.getLogger().error(
543
+ {
544
+ failedSubscribers: failedSubscriberNames,
545
+ retriesAttempted: this.config.maxRetries
546
+ },
547
+ "[autotel] Failed to send events after retries"
548
+ );
549
+ }
550
+ }
551
+ }
552
+ /**
553
+ * Send events to configured subscribers with rate limiting and metrics.
554
+ * When subscribersByEventIndex is provided (retry path), only those subscribers are tried per event.
555
+ * Returns per-event, per-subscriber failures (empty if all succeeded).
556
+ */
557
+ async sendToSubscribers(events, subscribersByEventIndex) {
558
+ const failedDeliveries = [];
559
+ const sendOne = async (event, eventIndex) => {
560
+ const subscriberNames = subscribersByEventIndex?.get(eventIndex);
561
+ const failures = await this.sendEventToSubscribers(
562
+ event,
563
+ subscriberNames ?? void 0
564
+ );
565
+ for (const failure of failures) {
566
+ failedDeliveries.push({
567
+ eventIndex,
568
+ subscriberName: failure.subscriberName,
569
+ error: failure.error
570
+ });
571
+ }
572
+ };
573
+ if (!this.rateLimiter) {
574
+ for (let i = 0; i < events.length; i++) {
575
+ const event = events[i];
576
+ if (event) await sendOne(event, i);
577
+ }
578
+ return failedDeliveries;
579
+ }
580
+ for (let i = 0; i < events.length; i++) {
581
+ await this.rateLimiter.waitForToken();
582
+ const event = events[i];
583
+ if (event) await sendOne(event, i);
584
+ }
585
+ return failedDeliveries;
586
+ }
587
+ /**
588
+ * Send a single event to subscribers.
589
+ * - When subscriberNames is undefined (initial attempt): send to all subscribers.
590
+ * - When subscriberNames is provided (retry): send only to those subscribers (never re-send to healthy ones).
591
+ * Returns list of subscribers that failed (empty if all succeeded).
592
+ */
593
+ async sendEventToSubscribers(event, subscriberNames) {
594
+ const startTime = event.timestamp;
595
+ const failures = [];
596
+ const subscribersToTry = subscriberNames === void 0 ? this.subscribers : this.subscribers.filter(
597
+ (s) => subscriberNames.has(getSubscriberName(s))
598
+ );
599
+ const results = await Promise.allSettled(
600
+ subscribersToTry.map(async (subscriber) => {
601
+ const subscriberName = getSubscriberName(subscriber);
602
+ try {
603
+ await subscriber.trackEvent(event.name, event.attributes, {
604
+ autotel: event.autotel
605
+ });
606
+ this.recordDelivered(event, subscriberName, startTime);
607
+ return { subscriberName, success: true };
608
+ } catch (error) {
609
+ this.markSubscriberUnhealthy(subscriberName);
610
+ return {
611
+ subscriberName,
612
+ success: false,
613
+ error: error instanceof Error ? error : void 0
614
+ };
615
+ }
616
+ })
617
+ );
618
+ for (const result of results) {
619
+ if (result.status === "fulfilled" && !result.value.success) {
620
+ failures.push({
621
+ subscriberName: result.value.subscriberName,
622
+ error: result.value.error
623
+ });
624
+ }
625
+ }
626
+ return failures;
627
+ }
628
+ /**
629
+ * Flush all remaining events. Queue remains usable after flush (e.g. for
630
+ * auto-flush at root span end). Use shutdown() when tearing down the queue.
631
+ */
632
+ async flush() {
633
+ if (this.flushTimer) {
634
+ clearTimeout(this.flushTimer);
635
+ this.flushTimer = null;
636
+ }
637
+ if (this.flushPromise) {
638
+ await this.flushPromise;
639
+ }
640
+ while (this.queue.length > 0) {
641
+ await this.doFlushBatch();
642
+ }
643
+ }
644
+ /**
645
+ * Flush remaining events and permanently disable the queue (reject new events).
646
+ * Use for process/SDK shutdown; use flush() for periodic or span-end drain.
647
+ */
648
+ async shutdown() {
649
+ this.isShuttingDown = true;
650
+ await this.flush();
651
+ }
652
+ /**
653
+ * Cleanup observable metric callbacks to prevent memory leaks
654
+ * Call this when destroying the EventQueue instance
655
+ */
656
+ cleanup() {
657
+ for (const cleanupFn of this.observableCleanups) {
658
+ try {
659
+ cleanupFn();
660
+ } catch {
661
+ }
662
+ }
663
+ this.observableCleanups = [];
664
+ }
665
+ /**
666
+ * Get queue size (for testing/debugging)
667
+ */
668
+ size() {
669
+ return this.queue.length;
670
+ }
671
+ /**
672
+ * Get subscriber health status (for testing/debugging)
673
+ */
674
+ getSubscriberHealth() {
675
+ return new Map(this.subscriberHealthy);
676
+ }
677
+ /**
678
+ * Check if a specific subscriber is healthy
679
+ */
680
+ isSubscriberHealthy(subscriberName) {
681
+ return this.subscriberHealthy.get(subscriberName.toLowerCase()) ?? true;
682
+ }
683
+ /**
684
+ * Manually mark a subscriber as healthy or unhealthy
685
+ * (used for circuit breaker integration)
686
+ */
687
+ setSubscriberHealth(subscriberName, healthy) {
688
+ this.subscriberHealthy.set(subscriberName.toLowerCase(), healthy);
689
+ }
690
+ };
691
+
692
+ // src/validation.ts
693
+ var DEFAULT_CONFIG2 = {
694
+ maxEventNameLength: 100,
695
+ maxAttributeKeyLength: 100,
696
+ maxAttributeValueLength: 1e3,
697
+ maxAttributeCount: 50,
698
+ maxNestingDepth: 3,
699
+ sensitivePatterns: [
700
+ /password/i,
701
+ /secret/i,
702
+ /token/i,
703
+ /api[_-]?key/i,
704
+ /access[_-]?key/i,
705
+ /private[_-]?key/i,
706
+ /auth/i,
707
+ /credential/i,
708
+ /ssn/i,
709
+ /credit[_-]?card/i
710
+ ]
711
+ };
712
+ var ValidationError = class extends Error {
713
+ constructor(message) {
714
+ super(message);
715
+ this.name = "ValidationError";
716
+ }
717
+ };
718
+ function validateEventName(eventName, config = DEFAULT_CONFIG2) {
719
+ if (typeof eventName !== "string") {
720
+ throw new ValidationError(
721
+ `Event name must be a string, got ${typeof eventName}`
722
+ );
723
+ }
724
+ const trimmed = eventName.trim();
725
+ if (trimmed.length === 0) {
726
+ throw new ValidationError("Event name cannot be empty");
727
+ }
728
+ if (trimmed.length > config.maxEventNameLength) {
729
+ throw new ValidationError(
730
+ `Event name too long (${trimmed.length} chars). Max: ${config.maxEventNameLength}`
731
+ );
732
+ }
733
+ if (!/^[a-zA-Z0-9._-]+$/.test(trimmed)) {
734
+ throw new ValidationError(
735
+ `Event name contains invalid characters: "${trimmed}". Use only letters, numbers, dots, underscores, and hyphens.`
736
+ );
737
+ }
738
+ return trimmed;
739
+ }
740
+ function validateAttributes(attributes, config = DEFAULT_CONFIG2) {
741
+ if (attributes === void 0 || attributes === null) {
742
+ return void 0;
743
+ }
744
+ if (typeof attributes !== "object" || Array.isArray(attributes)) {
745
+ throw new ValidationError("Attributes must be an object");
746
+ }
747
+ const keys = Object.keys(attributes);
748
+ if (keys.length > config.maxAttributeCount) {
749
+ throw new ValidationError(
750
+ `Too many attributes (${keys.length}). Max: ${config.maxAttributeCount}`
751
+ );
752
+ }
753
+ const sanitized = {};
754
+ for (const key of keys) {
755
+ if (key.length > config.maxAttributeKeyLength) {
756
+ throw new ValidationError(
757
+ `Attribute key too long: "${key.slice(0, 20)}..." (${key.length} chars). Max: ${config.maxAttributeKeyLength}`
758
+ );
759
+ }
760
+ const isSensitive = config.sensitivePatterns.some(
761
+ (pattern) => pattern.test(key)
762
+ );
763
+ if (isSensitive) {
764
+ sanitized[key] = "[REDACTED]";
765
+ continue;
766
+ }
767
+ const value = attributes[key];
768
+ sanitized[key] = sanitizeValue(value, config, 1);
769
+ }
770
+ return sanitized;
771
+ }
772
+ function sanitizeValue(value, config, depth) {
773
+ if (depth > config.maxNestingDepth) {
774
+ return "[MAX_DEPTH_EXCEEDED]";
775
+ }
776
+ if (value === null || value === void 0) {
777
+ return value;
778
+ }
779
+ if (typeof value === "string") {
780
+ if (value.length > config.maxAttributeValueLength) {
781
+ return value.slice(0, config.maxAttributeValueLength) + "...";
782
+ }
783
+ return value;
784
+ }
785
+ if (typeof value === "number" || typeof value === "boolean") {
786
+ return value;
787
+ }
788
+ if (Array.isArray(value)) {
789
+ return value.map((item) => sanitizeValue(item, config, depth + 1));
790
+ }
791
+ if (typeof value === "object") {
792
+ try {
793
+ JSON.stringify(value);
794
+ const sanitized = {};
795
+ for (const key in value) {
796
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
797
+ const isSensitive = config.sensitivePatterns.some(
798
+ (pattern) => pattern.test(key)
799
+ );
800
+ if (isSensitive) {
801
+ sanitized[key] = "[REDACTED]";
802
+ } else {
803
+ sanitized[key] = sanitizeValue(
804
+ value[key],
805
+ config,
806
+ depth + 1
807
+ );
808
+ }
809
+ }
810
+ }
811
+ return sanitized;
812
+ } catch {
813
+ return "[CIRCULAR]";
814
+ }
815
+ }
816
+ return `[${typeof value}]`;
817
+ }
818
+ function validateEvent(eventName, attributes, config) {
819
+ const fullConfig = { ...DEFAULT_CONFIG2, ...config };
820
+ return {
821
+ eventName: validateEventName(eventName, fullConfig),
822
+ attributes: validateAttributes(attributes, fullConfig)
823
+ };
824
+ }
825
+
826
+ // src/track.ts
827
+ var eventsQueue = null;
828
+ function buildAutotelContext(span) {
829
+ const eventsConfig = chunk563EL6O6_cjs.getEventsConfig();
830
+ const config = chunk563EL6O6_cjs.getConfig();
831
+ const correlationId = getOrCreateCorrelationId();
832
+ if (!eventsConfig?.includeTraceContext) {
833
+ return {
834
+ correlation_id: correlationId
835
+ };
836
+ }
837
+ const autotelContext = {
838
+ correlation_id: correlationId
839
+ };
840
+ const spanContext = span?.spanContext();
841
+ if (spanContext) {
842
+ autotelContext.trace_id = spanContext.traceId;
843
+ autotelContext.span_id = spanContext.spanId;
844
+ autotelContext.trace_flags = spanContext.traceFlags.toString(16).padStart(2, "0");
845
+ const traceState = spanContext.traceState;
846
+ if (traceState) {
847
+ try {
848
+ if (typeof traceState.serialize === "function") {
849
+ const traceStateStr = traceState.serialize();
850
+ if (traceStateStr) {
851
+ autotelContext.trace_state = traceStateStr;
852
+ }
853
+ }
854
+ } catch {
855
+ }
856
+ }
857
+ if (eventsConfig.traceUrl && config) {
858
+ const traceUrl = eventsConfig.traceUrl({
859
+ traceId: spanContext.traceId,
860
+ spanId: spanContext.spanId,
861
+ correlationId,
862
+ serviceName: config.service,
863
+ environment: config.environment
864
+ });
865
+ if (traceUrl) {
866
+ autotelContext.trace_url = traceUrl;
867
+ }
868
+ }
869
+ } else {
870
+ if (eventsConfig.traceUrl && config) {
871
+ const traceUrl = eventsConfig.traceUrl({
872
+ correlationId,
873
+ serviceName: config.service,
874
+ environment: config.environment
875
+ });
876
+ if (traceUrl) {
877
+ autotelContext.trace_url = traceUrl;
878
+ }
879
+ }
880
+ }
881
+ return autotelContext;
882
+ }
883
+ function getOrCreateQueue() {
884
+ if (!chunk563EL6O6_cjs.isInitialized()) {
885
+ chunk563EL6O6_cjs.warnIfNotInitialized("track()");
886
+ return null;
887
+ }
888
+ if (!eventsQueue) {
889
+ const config = chunk563EL6O6_cjs.getConfig();
890
+ if (!config?.subscribers || config.subscribers.length === 0) {
891
+ return null;
892
+ }
893
+ eventsQueue = new EventQueue(config.subscribers);
894
+ }
895
+ return eventsQueue;
896
+ }
897
+ function track(event, data) {
898
+ const queue = getOrCreateQueue();
899
+ if (!queue) return;
900
+ const validationConfig = chunk563EL6O6_cjs.getValidationConfig();
901
+ const validated = validateEvent(event, data, validationConfig || void 0);
902
+ const span = api.trace.getActiveSpan();
903
+ const enrichedData = span ? {
904
+ ...validated.attributes,
905
+ traceId: span.spanContext().traceId,
906
+ spanId: span.spanContext().spanId
907
+ } : validated.attributes;
908
+ const autotelContext = buildAutotelContext(span);
909
+ queue.enqueue({
910
+ name: validated.eventName,
911
+ attributes: enrichedData,
912
+ timestamp: Date.now(),
913
+ autotel: autotelContext
914
+ });
915
+ }
916
+ function getEventQueue() {
917
+ return eventsQueue;
918
+ }
919
+ function resetEventQueue() {
920
+ eventsQueue = null;
921
+ }
922
+
923
+ // src/trace-context.ts
924
+ var contextStorage = new async_hooks.AsyncLocalStorage();
925
+ function getContextStorage() {
926
+ return contextStorage;
927
+ }
928
+ function getActiveContextWithBaggage() {
929
+ const stored = contextStorage.getStore()?.value;
930
+ return stored ?? api.context.active();
931
+ }
932
+ function enterOrRun(storage, value) {
933
+ const existingStore = storage.getStore();
934
+ if (existingStore) {
935
+ existingStore.value = value;
936
+ return;
937
+ }
938
+ const boxedValue = { value };
939
+ try {
940
+ storage.enterWith(boxedValue);
941
+ } catch {
942
+ storage.run(boxedValue, () => {
943
+ });
944
+ }
945
+ }
946
+ function updateActiveContext(newContext) {
947
+ enterOrRun(contextStorage, newContext);
948
+ const contextWithManager = api.context;
949
+ const manager = contextWithManager._getContextManager?.();
950
+ if (!manager) return;
951
+ const asyncLocal = manager._asyncLocalStorage ?? void 0;
952
+ if (asyncLocal?.enterWith) {
953
+ asyncLocal.enterWith(newContext);
954
+ return;
955
+ }
956
+ if (typeof manager.with === "function") {
957
+ manager.with(newContext, () => {
958
+ });
959
+ }
960
+ }
961
+ function createTraceContext(span) {
962
+ const spanContext = span.spanContext();
963
+ const existingStored = contextStorage.getStore()?.value;
964
+ if (!existingStored) {
965
+ const activeContext = api.context.active();
966
+ enterOrRun(contextStorage, activeContext);
967
+ }
968
+ const baggageHelpers = {
969
+ getBaggage(key) {
970
+ const activeCtx = api.context.active();
971
+ let baggage = api.propagation.getBaggage(activeCtx);
972
+ if (!baggage) {
973
+ const storedContext = contextStorage.getStore()?.value;
974
+ if (storedContext) {
975
+ baggage = api.propagation.getBaggage(storedContext);
976
+ }
977
+ }
978
+ return baggage?.getEntry(key)?.value;
979
+ },
980
+ setBaggage(key, value) {
981
+ const activeCtx = api.context.active();
982
+ const storedContext = contextStorage.getStore()?.value;
983
+ const currentContext = storedContext ?? activeCtx;
984
+ const baggage = api.propagation.getBaggage(currentContext) ?? api.propagation.createBaggage();
985
+ const updated = baggage.setEntry(key, { value });
986
+ const newContext = api.propagation.setBaggage(currentContext, updated);
987
+ updateActiveContext(newContext);
988
+ return value;
989
+ },
990
+ deleteBaggage(key) {
991
+ const activeCtx = api.context.active();
992
+ const storedContext = contextStorage.getStore()?.value;
993
+ const currentContext = storedContext ?? activeCtx;
994
+ const baggage = api.propagation.getBaggage(currentContext);
995
+ if (baggage) {
996
+ const updated = baggage.removeEntry(key);
997
+ const newContext = api.propagation.setBaggage(currentContext, updated);
998
+ updateActiveContext(newContext);
999
+ }
1000
+ },
1001
+ getAllBaggage() {
1002
+ const activeCtx = api.context.active();
1003
+ let baggage = api.propagation.getBaggage(activeCtx);
1004
+ if (!baggage) {
1005
+ const storedContext = contextStorage.getStore()?.value;
1006
+ if (storedContext) {
1007
+ baggage = api.propagation.getBaggage(storedContext);
1008
+ }
1009
+ }
1010
+ if (!baggage) {
1011
+ return /* @__PURE__ */ new Map();
1012
+ }
1013
+ const entries = /* @__PURE__ */ new Map();
1014
+ for (const [key, entry] of baggage.getAllEntries()) {
1015
+ entries.set(key, entry);
1016
+ }
1017
+ return entries;
1018
+ },
1019
+ // Typed baggage helpers (used by defineBaggageSchema)
1020
+ getTypedBaggage: ((namespace) => {
1021
+ const activeCtx = api.context.active();
1022
+ let baggage = api.propagation.getBaggage(activeCtx);
1023
+ if (!baggage) {
1024
+ const storedContext = contextStorage.getStore()?.value;
1025
+ if (storedContext) {
1026
+ baggage = api.propagation.getBaggage(storedContext);
1027
+ }
1028
+ }
1029
+ if (!baggage) return;
1030
+ const prefix = namespace ? `${namespace}.` : "";
1031
+ const result = {};
1032
+ for (const [key, entry] of baggage.getAllEntries()) {
1033
+ if (namespace && key.startsWith(prefix)) {
1034
+ const fieldName = key.slice(prefix.length);
1035
+ result[fieldName] = entry.value;
1036
+ } else if (!namespace) {
1037
+ result[key] = entry.value;
1038
+ }
1039
+ }
1040
+ return Object.keys(result).length > 0 ? result : void 0;
1041
+ }),
1042
+ setTypedBaggage: ((namespace, value) => {
1043
+ const activeCtx = api.context.active();
1044
+ const storedContext = contextStorage.getStore()?.value;
1045
+ const currentContext = storedContext ?? activeCtx;
1046
+ let baggage = api.propagation.getBaggage(currentContext) ?? api.propagation.createBaggage();
1047
+ const prefix = namespace ? `${namespace}.` : "";
1048
+ for (const [key, val] of Object.entries(value)) {
1049
+ if (val !== void 0) {
1050
+ const baggageKey = `${prefix}${key}`;
1051
+ baggage = baggage.setEntry(baggageKey, { value: String(val) });
1052
+ }
1053
+ }
1054
+ const newContext = api.propagation.setBaggage(currentContext, baggage);
1055
+ updateActiveContext(newContext);
1056
+ })
1057
+ };
1058
+ const traceCtx = {
1059
+ traceId: spanContext.traceId,
1060
+ spanId: spanContext.spanId,
1061
+ correlationId: spanContext.traceId.slice(0, 16),
1062
+ setAttribute: span.setAttribute.bind(span),
1063
+ setAttributes: span.setAttributes.bind(span),
1064
+ setStatus: span.setStatus.bind(span),
1065
+ recordException: span.recordException.bind(span),
1066
+ addEvent: span.addEvent.bind(span),
1067
+ addLink: span.addLink.bind(span),
1068
+ addLinks: span.addLinks.bind(span),
1069
+ updateName: span.updateName.bind(span),
1070
+ isRecording: span.isRecording.bind(span),
1071
+ recordError: (error) => {
1072
+ const err = error instanceof Error ? error : new Error(String(error));
1073
+ recordStructuredError(traceCtx, err);
1074
+ },
1075
+ track: (event, data) => {
1076
+ track(event, data);
1077
+ },
1078
+ ...baggageHelpers
1079
+ };
1080
+ return traceCtx;
1081
+ }
1082
+ function defineBaggageSchema(namespace) {
1083
+ return {
1084
+ /**
1085
+ * Get typed baggage from context
1086
+ * @param ctx - Trace context
1087
+ * @returns Partial baggage object or undefined if no baggage is set
1088
+ */
1089
+ get: (ctx) => {
1090
+ if (!ctx.getTypedBaggage) return void 0;
1091
+ return ctx.getTypedBaggage(namespace);
1092
+ },
1093
+ /**
1094
+ * Set typed baggage in context
1095
+ *
1096
+ * Note: For proper scoping across async boundaries, use the `with` method instead
1097
+ *
1098
+ * @param ctx - Trace context
1099
+ * @param value - Partial baggage object to set
1100
+ */
1101
+ set: (ctx, value) => {
1102
+ if (!ctx.setTypedBaggage) return;
1103
+ ctx.setTypedBaggage(namespace, value);
1104
+ },
1105
+ /**
1106
+ * Run a function with typed baggage properly scoped
1107
+ *
1108
+ * This is the recommended way to set baggage as it ensures proper
1109
+ * scoping across async boundaries.
1110
+ *
1111
+ * @param ctx - Trace context (can be omitted, will use active context)
1112
+ * @param value - Partial baggage object to set
1113
+ * @param fn - Function to execute with the baggage
1114
+ */
1115
+ with: (ctxOrValue, valueOrFn, maybeFn) => {
1116
+ const value = maybeFn ? valueOrFn : ctxOrValue;
1117
+ const fn = maybeFn || valueOrFn;
1118
+ const prefix = namespace ? `${namespace}.` : "";
1119
+ const flatBaggage = {};
1120
+ for (const [key, val] of Object.entries(value)) {
1121
+ if (val !== void 0) {
1122
+ flatBaggage[`${prefix}${key}`] = String(val);
1123
+ }
1124
+ }
1125
+ const currentContext = api.context.active();
1126
+ let baggage = api.propagation.getBaggage(currentContext) ?? api.propagation.createBaggage();
1127
+ for (const [key, val] of Object.entries(flatBaggage)) {
1128
+ baggage = baggage.setEntry(key, { value: val });
1129
+ }
1130
+ const newContext = api.propagation.setBaggage(currentContext, baggage);
1131
+ return api.context.with(newContext, fn);
1132
+ }
1133
+ };
1134
+ }
1135
+
1136
+ // src/correlation-id.ts
1137
+ var correlationStorage = new async_hooks.AsyncLocalStorage();
1138
+ var CORRELATION_ID_BAGGAGE_KEY = "autotel.correlation_id";
1139
+ function generateCorrelationId() {
1140
+ const bytes = new Uint8Array(8);
1141
+ crypto.getRandomValues(bytes);
1142
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
1143
+ }
1144
+ function getCorrelationId() {
1145
+ const storedId = correlationStorage.getStore()?.value;
1146
+ if (storedId) {
1147
+ return storedId;
1148
+ }
1149
+ const activeContext = api.context.active();
1150
+ const baggage = api.propagation.getBaggage(activeContext);
1151
+ const baggageEntry = baggage?.getEntry(CORRELATION_ID_BAGGAGE_KEY);
1152
+ if (baggageEntry?.value) {
1153
+ return baggageEntry.value;
1154
+ }
1155
+ const span = api.trace.getActiveSpan();
1156
+ if (span) {
1157
+ const spanContext = span.spanContext();
1158
+ return spanContext.traceId.slice(0, 16);
1159
+ }
1160
+ return void 0;
1161
+ }
1162
+ function getOrCreateCorrelationId() {
1163
+ return getCorrelationId() ?? generateCorrelationId();
1164
+ }
1165
+ function runWithCorrelationId(correlationId, fn) {
1166
+ return correlationStorage.run({ value: correlationId }, fn);
1167
+ }
1168
+ function setCorrelationId(correlationId) {
1169
+ enterOrRun(correlationStorage, correlationId);
1170
+ }
1171
+ function setCorrelationIdInBaggage(correlationId) {
1172
+ const activeContext = api.context.active();
1173
+ let baggage = api.propagation.getBaggage(activeContext) ?? api.propagation.createBaggage();
1174
+ baggage = baggage.setEntry(CORRELATION_ID_BAGGAGE_KEY, {
1175
+ value: correlationId
1176
+ });
1177
+ return api.propagation.setBaggage(activeContext, baggage);
1178
+ }
1179
+ function getCorrelationStorage() {
1180
+ return correlationStorage;
1181
+ }
1182
+
1183
+ exports.CORRELATION_ID_BAGGAGE_KEY = CORRELATION_ID_BAGGAGE_KEY;
1184
+ exports.createStructuredError = createStructuredError;
1185
+ exports.createTraceContext = createTraceContext;
1186
+ exports.defineBaggageSchema = defineBaggageSchema;
1187
+ exports.enterOrRun = enterOrRun;
1188
+ exports.flattenToAttributes = flattenToAttributes;
1189
+ exports.generateCorrelationId = generateCorrelationId;
1190
+ exports.getActiveContextWithBaggage = getActiveContextWithBaggage;
1191
+ exports.getContextStorage = getContextStorage;
1192
+ exports.getCorrelationId = getCorrelationId;
1193
+ exports.getCorrelationStorage = getCorrelationStorage;
1194
+ exports.getEventQueue = getEventQueue;
1195
+ exports.getOrCreateCorrelationId = getOrCreateCorrelationId;
1196
+ exports.getStructuredErrorAttributes = getStructuredErrorAttributes;
1197
+ exports.recordStructuredError = recordStructuredError;
1198
+ exports.resetEventQueue = resetEventQueue;
1199
+ exports.runWithCorrelationId = runWithCorrelationId;
1200
+ exports.setCorrelationId = setCorrelationId;
1201
+ exports.setCorrelationIdInBaggage = setCorrelationIdInBaggage;
1202
+ exports.structuredErrorToJSON = structuredErrorToJSON;
1203
+ exports.toAttributeValue = toAttributeValue;
1204
+ exports.track = track;
1205
+ exports.validateEvent = validateEvent;
1206
+ //# sourceMappingURL=chunk-CJ4PD2TZ.cjs.map
1207
+ //# sourceMappingURL=chunk-CJ4PD2TZ.cjs.map