@iii-dev/observability 0.13.0-next.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1509 @@
1
+ import { SeverityNumber, SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
2
+ import { Resource } from "@opentelemetry/resources";
3
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
4
+ import { randomUUID } from "node:crypto";
5
+ import { SpanKind, SpanKind as SpanKind$1, SpanStatusCode, SpanStatusCode as SpanStatusCode$1, context, metrics, propagation, trace } from "@opentelemetry/api";
6
+ import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
7
+ import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
8
+ import { CompositePropagator, ExportResultCode, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
9
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
10
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
11
+ import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
12
+ import { WebSocket } from "ws";
13
+ import { JsonLogsSerializer, JsonMetricsSerializer, JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
14
+ import { monitorEventLoopDelay, performance } from "node:perf_hooks";
15
+
16
+ //#region src/telemetry-system/baggage-span-processor.ts
17
+ /** DEFAULT_ALLOWLIST drift across languages would break worker chains;
18
+ * lockstep tests in each SDK pin this constant at CI time. */
19
+ const DEFAULT_ALLOWLIST = [
20
+ "iii.session.id",
21
+ "iii.message.id",
22
+ "iii.function.id"
23
+ ];
24
+ var BaggageSpanProcessor = class {
25
+ allowlist;
26
+ constructor(allowlist = DEFAULT_ALLOWLIST) {
27
+ this.allowlist = allowlist;
28
+ }
29
+ onStart(span, parentContext) {
30
+ if (!span.isRecording()) return;
31
+ const baggage = propagation.getBaggage(parentContext);
32
+ if (!baggage) return;
33
+ for (const key of this.allowlist) {
34
+ const entry = baggage.getEntry(key);
35
+ if (entry) span.setAttribute(key, entry.value);
36
+ }
37
+ }
38
+ onEnd(_span) {}
39
+ async shutdown() {}
40
+ async forceFlush() {}
41
+ };
42
+
43
+ //#endregion
44
+ //#region src/telemetry-system/types.ts
45
+ const ATTR_SERVICE_VERSION = "service.version";
46
+ const ATTR_SERVICE_NAMESPACE = "service.namespace";
47
+ const ATTR_SERVICE_INSTANCE_ID = "service.instance.id";
48
+ /** Magic prefixes for binary frames over WebSocket */
49
+ const PREFIX_TRACES = "OTLP";
50
+ const PREFIX_METRICS = "MTRC";
51
+ const PREFIX_LOGS = "LOGS";
52
+ /** Default reconnection configuration */
53
+ const DEFAULT_RECONNECTION_CONFIG = {
54
+ initialDelayMs: 1e3,
55
+ maxDelayMs: 3e4,
56
+ backoffMultiplier: 2,
57
+ jitterFactor: .3,
58
+ maxRetries: -1
59
+ };
60
+ /** Default configuration values for OpenTelemetry initialization. */
61
+ const DEFAULT_OTEL_CONFIG = {
62
+ enabled: true,
63
+ serviceName: "iii-node",
64
+ serviceVersion: "unknown",
65
+ engineWsUrl: "ws://localhost:49134",
66
+ metricsEnabled: true,
67
+ metricsExportIntervalMs: 6e4,
68
+ logsFlushIntervalMs: 100,
69
+ logsBatchSize: 1,
70
+ fetchInstrumentationEnabled: true
71
+ };
72
+ /** Parse a boolean environment variable, recognizing 'false', '0', 'no', 'off' as false. */
73
+ function parseBoolEnv(value, defaultValue) {
74
+ if (value === void 0) return defaultValue;
75
+ const lower = value.toLowerCase();
76
+ return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off";
77
+ }
78
+
79
+ //#endregion
80
+ //#region src/telemetry-system/connection.ts
81
+ /**
82
+ * Shared WebSocket connection for OpenTelemetry exporters.
83
+ */
84
+ /**
85
+ * Shared WebSocket connection for all OTEL exporters (traces, metrics, logs).
86
+ * Uses a single connection with message prefixes to identify signal type.
87
+ */
88
+ var SharedEngineConnection = class SharedEngineConnection {
89
+ static MAX_PENDING_MESSAGES = 1e3;
90
+ ws = null;
91
+ wsUrl;
92
+ connecting = false;
93
+ shuttingDown = false;
94
+ pendingMessages = [];
95
+ reconnectAttempt = 0;
96
+ reconnectTimeout = null;
97
+ config;
98
+ state = "disconnected";
99
+ onConnectedCallbacks = [];
100
+ onFailedCallbacks = [];
101
+ constructor(wsUrl, config = {}) {
102
+ this.wsUrl = wsUrl;
103
+ this.config = {
104
+ ...DEFAULT_RECONNECTION_CONFIG,
105
+ ...config
106
+ };
107
+ this.connect();
108
+ }
109
+ connect() {
110
+ if (this.connecting || this.ws && this.ws.readyState === WebSocket.OPEN) return;
111
+ this.connecting = true;
112
+ this.state = "connecting";
113
+ try {
114
+ this.ws = new WebSocket(this.wsUrl);
115
+ this.ws.on("open", () => {
116
+ this.connecting = false;
117
+ this.state = "connected";
118
+ console.log(`[OTel] Connected to engine at ${this.wsUrl}`);
119
+ if (this.reconnectAttempt > 0) console.log("[OTel] Successfully reconnected");
120
+ this.reconnectAttempt = 0;
121
+ if (this.reconnectTimeout) {
122
+ clearTimeout(this.reconnectTimeout);
123
+ this.reconnectTimeout = null;
124
+ }
125
+ const pending = this.pendingMessages.splice(0, this.pendingMessages.length);
126
+ for (const { frame, callback } of pending) this.ws?.send(frame, (err) => callback?.(err));
127
+ for (const cb of this.onConnectedCallbacks) cb();
128
+ });
129
+ this.ws.on("close", () => {
130
+ this.connecting = false;
131
+ this.ws = null;
132
+ if (this.shuttingDown) {
133
+ this.state = "disconnected";
134
+ console.log("[OTel] Connection closed during shutdown");
135
+ return;
136
+ }
137
+ this.state = "disconnected";
138
+ console.log("[OTel] Disconnected from engine, will reconnect...");
139
+ this.scheduleReconnect();
140
+ });
141
+ this.ws.on("error", (err) => {
142
+ this.connecting = false;
143
+ if (this.shuttingDown) return;
144
+ console.error("[OTel] WebSocket error:", err.message);
145
+ });
146
+ } catch (err) {
147
+ this.connecting = false;
148
+ console.error("[OTel] Connection failed:", err);
149
+ this.scheduleReconnect();
150
+ }
151
+ }
152
+ scheduleReconnect() {
153
+ if (this.config.maxRetries !== -1 && this.reconnectAttempt >= this.config.maxRetries) {
154
+ this.state = "failed";
155
+ console.error(`[OTel] Max retries (${this.config.maxRetries}) reached, giving up`);
156
+ const pending = this.pendingMessages.splice(0, this.pendingMessages.length);
157
+ const failedError = /* @__PURE__ */ new Error("Connection failed after max retries");
158
+ for (const { callback } of pending) callback?.(failedError);
159
+ for (const cb of this.onFailedCallbacks) try {
160
+ cb();
161
+ } catch (err) {
162
+ console.error("[OTel] onFailed callback threw:", err);
163
+ }
164
+ return;
165
+ }
166
+ if (this.reconnectTimeout) return;
167
+ const exponentialDelay = this.config.initialDelayMs * this.config.backoffMultiplier ** this.reconnectAttempt;
168
+ const cappedDelay = Math.min(exponentialDelay, this.config.maxDelayMs);
169
+ const jitter = cappedDelay * this.config.jitterFactor * (2 * Math.random() - 1);
170
+ const delay = Math.max(0, Math.floor(cappedDelay + jitter));
171
+ this.state = "reconnecting";
172
+ console.log(`[OTel] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempt + 1})...`);
173
+ this.reconnectTimeout = setTimeout(() => {
174
+ this.reconnectTimeout = null;
175
+ this.reconnectAttempt++;
176
+ this.connect();
177
+ }, delay);
178
+ }
179
+ /**
180
+ * Send a message with a signal prefix.
181
+ */
182
+ send(prefix, data, callback) {
183
+ const prefixBytes = Buffer.from(prefix, "utf-8");
184
+ const frame = Buffer.concat([prefixBytes, Buffer.from(data)]);
185
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) this.ws.send(frame, callback);
186
+ else {
187
+ if (this.pendingMessages.length >= SharedEngineConnection.MAX_PENDING_MESSAGES) {
188
+ console.warn("[OTel] Pending message queue full, dropping oldest message");
189
+ this.pendingMessages.shift()?.callback?.(/* @__PURE__ */ new Error("Message dropped due to queue overflow"));
190
+ }
191
+ this.pendingMessages.push({
192
+ frame,
193
+ callback
194
+ });
195
+ this.connect();
196
+ }
197
+ }
198
+ /**
199
+ * Register a callback to be called when connected.
200
+ */
201
+ onConnected(callback) {
202
+ this.onConnectedCallbacks.push(callback);
203
+ if (this.state === "connected") callback();
204
+ }
205
+ /**
206
+ * Register a callback to be called when the connection enters the failed
207
+ * terminal state (max retries reached). Exporters use this to drain their
208
+ * own pending queues so in-flight forceFlush() calls do not hang.
209
+ */
210
+ onFailed(callback) {
211
+ this.onFailedCallbacks.push(callback);
212
+ if (this.state === "failed") try {
213
+ callback();
214
+ } catch (err) {
215
+ console.error("[OTel] onFailed callback threw:", err);
216
+ }
217
+ }
218
+ /**
219
+ * Get the current connection state.
220
+ */
221
+ getState() {
222
+ return this.state;
223
+ }
224
+ /**
225
+ * Shutdown the connection.
226
+ */
227
+ async shutdown() {
228
+ this.shuttingDown = true;
229
+ if (this.reconnectTimeout) {
230
+ clearTimeout(this.reconnectTimeout);
231
+ this.reconnectTimeout = null;
232
+ }
233
+ if (this.ws) {
234
+ this.ws.close();
235
+ this.ws = null;
236
+ }
237
+ const pending = this.pendingMessages.splice(0, this.pendingMessages.length);
238
+ const shutdownError = /* @__PURE__ */ new Error("Connection shutdown before message could be sent");
239
+ for (const { callback } of pending) callback?.(shutdownError);
240
+ this.onConnectedCallbacks = [];
241
+ this.onFailedCallbacks = [];
242
+ this.state = "disconnected";
243
+ }
244
+ };
245
+
246
+ //#endregion
247
+ //#region src/telemetry-system/span-exporter.ts
248
+ /**
249
+ * Span exporter for the III Engine.
250
+ */
251
+ /**
252
+ * Span exporter using the shared WebSocket connection.
253
+ */
254
+ var EngineSpanExporter = class EngineSpanExporter {
255
+ static MAX_PENDING_EXPORTS = 100;
256
+ connection;
257
+ pendingExports = [];
258
+ constructor(connection) {
259
+ this.connection = connection;
260
+ this.connection.onConnected(() => this.flushPending());
261
+ this.connection.onFailed(() => this.failPending());
262
+ }
263
+ flushPending() {
264
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
265
+ for (const { spans, resultCallback } of pending) this.sendExport(spans, resultCallback);
266
+ }
267
+ failPending() {
268
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
269
+ const error = /* @__PURE__ */ new Error("Connection failed: dropping queued spans");
270
+ for (const { resultCallback } of pending) resultCallback?.({
271
+ code: ExportResultCode.FAILED,
272
+ error
273
+ });
274
+ }
275
+ sendExport(spans, resultCallback) {
276
+ try {
277
+ const serialized = JsonTraceSerializer.serializeRequest(spans);
278
+ if (!serialized) {
279
+ resultCallback?.({ code: ExportResultCode.SUCCESS });
280
+ return;
281
+ }
282
+ this.connection.send(PREFIX_TRACES, serialized, (err) => {
283
+ if (err) {
284
+ console.error("[OTel] Failed to send spans:", err.message);
285
+ resultCallback?.({
286
+ code: ExportResultCode.FAILED,
287
+ error: err
288
+ });
289
+ } else resultCallback?.({ code: ExportResultCode.SUCCESS });
290
+ });
291
+ } catch (err) {
292
+ console.error("[OTel] Error exporting spans:", err);
293
+ resultCallback?.({
294
+ code: ExportResultCode.FAILED,
295
+ error: err
296
+ });
297
+ }
298
+ }
299
+ doExport(spans, resultCallback) {
300
+ const state = this.connection.getState();
301
+ if (state === "failed") {
302
+ resultCallback({
303
+ code: ExportResultCode.FAILED,
304
+ error: /* @__PURE__ */ new Error("Connection failed: dropping spans")
305
+ });
306
+ return;
307
+ }
308
+ if (state !== "connected") {
309
+ if (this.pendingExports.length >= EngineSpanExporter.MAX_PENDING_EXPORTS) {
310
+ this.pendingExports.shift()?.resultCallback?.({
311
+ code: ExportResultCode.FAILED,
312
+ error: /* @__PURE__ */ new Error("Queue overflow")
313
+ });
314
+ console.warn("[OTel] Spans export queue full, dropped oldest entry");
315
+ }
316
+ this.pendingExports.push({
317
+ spans,
318
+ resultCallback
319
+ });
320
+ return;
321
+ }
322
+ this.sendExport(spans, resultCallback);
323
+ }
324
+ export(spans, resultCallback) {
325
+ this.doExport(spans, resultCallback);
326
+ }
327
+ async shutdown() {
328
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
329
+ const shutdownError = /* @__PURE__ */ new Error("Exporter shutdown before export completed");
330
+ for (const { resultCallback } of pending) resultCallback?.({
331
+ code: ExportResultCode.FAILED,
332
+ error: shutdownError
333
+ });
334
+ }
335
+ async forceFlush() {}
336
+ };
337
+
338
+ //#endregion
339
+ //#region src/telemetry-system/metrics-exporter.ts
340
+ /**
341
+ * Metrics exporter for the III Engine.
342
+ */
343
+ /**
344
+ * Metrics exporter using the shared WebSocket connection.
345
+ */
346
+ var EngineMetricsExporter = class EngineMetricsExporter {
347
+ static MAX_PENDING_EXPORTS = 100;
348
+ connection;
349
+ pendingExports = [];
350
+ constructor(connection) {
351
+ this.connection = connection;
352
+ this.connection.onConnected(() => this.flushPending());
353
+ this.connection.onFailed(() => this.failPending());
354
+ }
355
+ flushPending() {
356
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
357
+ for (const { metrics, resultCallback } of pending) this.sendExport(metrics, resultCallback);
358
+ }
359
+ failPending() {
360
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
361
+ const error = /* @__PURE__ */ new Error("Connection failed: dropping queued metrics");
362
+ for (const { resultCallback } of pending) resultCallback?.({
363
+ code: ExportResultCode.FAILED,
364
+ error
365
+ });
366
+ }
367
+ sendExport(metricsData, resultCallback) {
368
+ try {
369
+ const serialized = JsonMetricsSerializer.serializeRequest(metricsData);
370
+ if (!serialized) {
371
+ resultCallback?.({ code: ExportResultCode.SUCCESS });
372
+ return;
373
+ }
374
+ this.connection.send(PREFIX_METRICS, serialized, (err) => {
375
+ if (err) {
376
+ console.error("[OTel] Failed to send metrics:", err.message);
377
+ resultCallback?.({
378
+ code: ExportResultCode.FAILED,
379
+ error: err
380
+ });
381
+ } else resultCallback?.({ code: ExportResultCode.SUCCESS });
382
+ });
383
+ } catch (err) {
384
+ console.error("[OTel] Error exporting metrics:", err);
385
+ resultCallback?.({
386
+ code: ExportResultCode.FAILED,
387
+ error: err
388
+ });
389
+ }
390
+ }
391
+ doExport(metricsData, resultCallback) {
392
+ const state = this.connection.getState();
393
+ if (state === "failed") {
394
+ resultCallback({
395
+ code: ExportResultCode.FAILED,
396
+ error: /* @__PURE__ */ new Error("Connection failed: dropping metrics")
397
+ });
398
+ return;
399
+ }
400
+ if (state !== "connected") {
401
+ if (this.pendingExports.length >= EngineMetricsExporter.MAX_PENDING_EXPORTS) {
402
+ this.pendingExports.shift()?.resultCallback?.({
403
+ code: ExportResultCode.FAILED,
404
+ error: /* @__PURE__ */ new Error("Queue overflow")
405
+ });
406
+ console.warn("[OTel] Metrics export queue full, dropped oldest entry");
407
+ }
408
+ this.pendingExports.push({
409
+ metrics: metricsData,
410
+ resultCallback
411
+ });
412
+ return;
413
+ }
414
+ this.sendExport(metricsData, resultCallback);
415
+ }
416
+ export(metrics, resultCallback) {
417
+ this.doExport(metrics, resultCallback);
418
+ }
419
+ async shutdown() {
420
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
421
+ const shutdownError = /* @__PURE__ */ new Error("Exporter shutdown before export completed");
422
+ for (const { resultCallback } of pending) resultCallback?.({
423
+ code: ExportResultCode.FAILED,
424
+ error: shutdownError
425
+ });
426
+ }
427
+ async forceFlush() {}
428
+ };
429
+
430
+ //#endregion
431
+ //#region src/telemetry-system/log-exporter.ts
432
+ /**
433
+ * Log exporter for the III Engine.
434
+ */
435
+ /**
436
+ * Log exporter using the shared WebSocket connection.
437
+ */
438
+ var EngineLogExporter = class EngineLogExporter {
439
+ static MAX_PENDING_EXPORTS = 100;
440
+ connection;
441
+ pendingExports = [];
442
+ constructor(connection) {
443
+ this.connection = connection;
444
+ this.connection.onConnected(() => this.flushPending());
445
+ this.connection.onFailed(() => this.failPending());
446
+ }
447
+ flushPending() {
448
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
449
+ for (const { logs, callback } of pending) this.doExport(logs, callback);
450
+ }
451
+ failPending() {
452
+ const pending = this.pendingExports.splice(0, this.pendingExports.length);
453
+ const error = /* @__PURE__ */ new Error("Connection failed: dropping queued logs");
454
+ for (const { callback } of pending) callback({
455
+ code: ExportResultCode.FAILED,
456
+ error
457
+ });
458
+ }
459
+ doExport(logs, resultCallback) {
460
+ const state = this.connection.getState();
461
+ if (state === "failed") {
462
+ resultCallback({
463
+ code: ExportResultCode.FAILED,
464
+ error: /* @__PURE__ */ new Error("Connection failed: dropping logs")
465
+ });
466
+ return;
467
+ }
468
+ if (state !== "connected") {
469
+ if (this.pendingExports.length >= EngineLogExporter.MAX_PENDING_EXPORTS) {
470
+ this.pendingExports.shift()?.callback({
471
+ code: ExportResultCode.FAILED,
472
+ error: /* @__PURE__ */ new Error("Logs export queue full")
473
+ });
474
+ console.warn("[OTel] Logs export queue full, dropped oldest entry");
475
+ }
476
+ this.pendingExports.push({
477
+ logs,
478
+ callback: resultCallback
479
+ });
480
+ return;
481
+ }
482
+ try {
483
+ const serialized = JsonLogsSerializer.serializeRequest(logs);
484
+ if (!serialized) {
485
+ resultCallback({ code: ExportResultCode.SUCCESS });
486
+ return;
487
+ }
488
+ this.connection.send(PREFIX_LOGS, serialized, (err) => {
489
+ if (err) {
490
+ console.error("[OTel] Failed to send logs:", err.message);
491
+ resultCallback({
492
+ code: ExportResultCode.FAILED,
493
+ error: err
494
+ });
495
+ } else resultCallback({ code: ExportResultCode.SUCCESS });
496
+ });
497
+ } catch (err) {
498
+ console.error("[OTel] Error exporting logs:", err);
499
+ resultCallback({
500
+ code: ExportResultCode.FAILED,
501
+ error: err
502
+ });
503
+ }
504
+ }
505
+ export(logs, resultCallback) {
506
+ this.doExport(logs, resultCallback);
507
+ }
508
+ async forceFlush() {}
509
+ async shutdown() {
510
+ for (const { callback } of this.pendingExports) callback({
511
+ code: ExportResultCode.FAILED,
512
+ error: /* @__PURE__ */ new Error("Exporter shutdown")
513
+ });
514
+ this.pendingExports = [];
515
+ }
516
+ };
517
+
518
+ //#endregion
519
+ //#region src/telemetry-system/context.ts
520
+ /**
521
+ * Trace context and baggage propagation utilities.
522
+ */
523
+ /**
524
+ * Extract the current trace ID from the active span context.
525
+ */
526
+ function currentTraceId() {
527
+ const span = trace.getActiveSpan();
528
+ if (span) {
529
+ const spanContext = span.spanContext();
530
+ if (spanContext.traceId && spanContext.traceId !== "00000000000000000000000000000000") return spanContext.traceId;
531
+ }
532
+ }
533
+ /**
534
+ * Extract the current span ID from the active span context.
535
+ */
536
+ function currentSpanId() {
537
+ const span = trace.getActiveSpan();
538
+ if (span) {
539
+ const spanContext = span.spanContext();
540
+ if (spanContext.spanId && spanContext.spanId !== "0000000000000000") return spanContext.spanId;
541
+ }
542
+ }
543
+ /**
544
+ * Inject the current trace context into a W3C traceparent header string.
545
+ */
546
+ function injectTraceparent() {
547
+ const carrier = {};
548
+ propagation.inject(context.active(), carrier);
549
+ return carrier.traceparent;
550
+ }
551
+ /**
552
+ * Extract a trace context from a W3C traceparent header string.
553
+ */
554
+ function extractTraceparent(traceparent) {
555
+ const carrier = { traceparent };
556
+ return propagation.extract(context.active(), carrier);
557
+ }
558
+ /**
559
+ * Inject the current baggage into a W3C baggage header string.
560
+ */
561
+ function injectBaggage() {
562
+ const carrier = {};
563
+ propagation.inject(context.active(), carrier);
564
+ return carrier.baggage;
565
+ }
566
+ /**
567
+ * Extract baggage from a W3C baggage header string.
568
+ */
569
+ function extractBaggage(baggage) {
570
+ const carrier = { baggage };
571
+ return propagation.extract(context.active(), carrier);
572
+ }
573
+ /**
574
+ * Extract both trace context and baggage from their respective headers.
575
+ */
576
+ function extractContext(traceparent, baggage) {
577
+ const carrier = {};
578
+ if (traceparent) carrier.traceparent = traceparent;
579
+ if (baggage) carrier.baggage = baggage;
580
+ return propagation.extract(context.active(), carrier);
581
+ }
582
+ /**
583
+ * Get a baggage entry from the current context.
584
+ */
585
+ function getBaggageEntry(key) {
586
+ return propagation.getBaggage(context.active())?.getEntry(key)?.value;
587
+ }
588
+ /**
589
+ * Set a baggage entry in the current context.
590
+ */
591
+ function setBaggageEntry(key, value) {
592
+ let bag = propagation.getBaggage(context.active()) ?? propagation.createBaggage();
593
+ bag = bag.setEntry(key, { value });
594
+ return propagation.setBaggage(context.active(), bag);
595
+ }
596
+ /**
597
+ * Remove a baggage entry from the current context.
598
+ */
599
+ function removeBaggageEntry(key) {
600
+ const bag = propagation.getBaggage(context.active());
601
+ if (!bag) return context.active();
602
+ const newBag = bag.removeEntry(key);
603
+ return propagation.setBaggage(context.active(), newBag);
604
+ }
605
+ /**
606
+ * Get all baggage entries from the current context.
607
+ */
608
+ function getAllBaggage() {
609
+ const bag = propagation.getBaggage(context.active());
610
+ if (!bag) return {};
611
+ const entries = {};
612
+ for (const [key, entry] of bag.getAllEntries()) entries[key] = entry.value;
613
+ return entries;
614
+ }
615
+
616
+ //#endregion
617
+ //#region src/telemetry-system/fetch-instrumentation.ts
618
+ /**
619
+ * Global fetch auto-instrumentation for the III Node SDK.
620
+ *
621
+ * Patches globalThis.fetch to create OTel CLIENT spans for every HTTP request.
622
+ * Works on all runtimes (Bun, Node.js, Deno) unlike UndiciInstrumentation
623
+ * which only works when fetch is backed by Node.js's undici.
624
+ */
625
+ const textEncoder = new TextEncoder();
626
+ function getBodyByteSize(body) {
627
+ if (body == null) return void 0;
628
+ if (typeof body === "string") return textEncoder.encode(body).byteLength;
629
+ if (body instanceof ArrayBuffer) return body.byteLength;
630
+ if (ArrayBuffer.isView(body)) return body.byteLength;
631
+ if (body instanceof Blob) return body.size;
632
+ if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
633
+ }
634
+ const SAFE_REQUEST_HEADERS$1 = ["content-type", "accept"];
635
+ const SAFE_RESPONSE_HEADERS$1 = ["content-type"];
636
+ let originalFetch = null;
637
+ /**
638
+ * Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.
639
+ */
640
+ function patchGlobalFetch(tracer) {
641
+ if (originalFetch) return;
642
+ originalFetch = globalThis.fetch;
643
+ const capturedFetch = originalFetch;
644
+ globalThis.fetch = async (input, init) => {
645
+ const url = input instanceof Request ? input.url : String(input);
646
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
647
+ let host;
648
+ let scheme;
649
+ let path;
650
+ let port;
651
+ let query;
652
+ try {
653
+ const parsed = new URL(url);
654
+ host = parsed.hostname;
655
+ scheme = parsed.protocol.replace(":", "");
656
+ path = parsed.pathname;
657
+ port = parsed.port ? parseInt(parsed.port, 10) : void 0;
658
+ query = parsed.search ? parsed.search.slice(1) : void 0;
659
+ } catch {}
660
+ const spanAttributes = {
661
+ "http.request.method": method,
662
+ "url.full": url
663
+ };
664
+ if (host) spanAttributes["server.address"] = host;
665
+ if (scheme) {
666
+ spanAttributes["url.scheme"] = scheme;
667
+ spanAttributes["network.protocol.name"] = "http";
668
+ }
669
+ if (path) spanAttributes["url.path"] = path;
670
+ if (port) spanAttributes["server.port"] = port;
671
+ if (query) spanAttributes["url.query"] = query;
672
+ const spanName = path ? `${method} ${path}` : method;
673
+ return tracer.startActiveSpan(spanName, {
674
+ kind: SpanKind$1.CLIENT,
675
+ attributes: spanAttributes
676
+ }, context.active(), async (span) => {
677
+ try {
678
+ const carrier = {};
679
+ propagation.inject(context.active(), carrier);
680
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
681
+ for (const [key, value] of Object.entries(carrier)) headers.set(key, value);
682
+ for (const name of SAFE_REQUEST_HEADERS$1) {
683
+ const value = headers.get(name);
684
+ if (value !== null) span.setAttribute(`http.request.header.${name}`, value);
685
+ }
686
+ const requestBodySize = getBodyByteSize(init?.body ?? (input instanceof Request ? input.body : void 0));
687
+ if (requestBodySize !== void 0) span.setAttribute("http.request.body.size", requestBodySize);
688
+ const response = await capturedFetch(input, {
689
+ ...init,
690
+ headers
691
+ });
692
+ span.setAttribute("http.response.status_code", response.status);
693
+ const contentLength = response.headers.get("content-length");
694
+ if (contentLength !== null) {
695
+ const size = parseInt(contentLength, 10);
696
+ if (!Number.isNaN(size)) span.setAttribute("http.response.body.size", size);
697
+ }
698
+ for (const name of SAFE_RESPONSE_HEADERS$1) {
699
+ const value = response.headers.get(name);
700
+ if (value !== null) span.setAttribute(`http.response.header.${name}`, value);
701
+ }
702
+ if (response.status >= 400) {
703
+ span.setAttribute("error.type", String(response.status));
704
+ span.setStatus({ code: SpanStatusCode.ERROR });
705
+ } else span.setStatus({ code: SpanStatusCode.OK });
706
+ return response;
707
+ } catch (error) {
708
+ span.setAttribute("error.type", error.name ?? "Error");
709
+ span.setStatus({
710
+ code: SpanStatusCode.ERROR,
711
+ message: error.message
712
+ });
713
+ span.recordException(error);
714
+ throw error;
715
+ } finally {
716
+ span.end();
717
+ }
718
+ });
719
+ };
720
+ }
721
+ /**
722
+ * Restore globalThis.fetch to its original implementation.
723
+ */
724
+ function unpatchGlobalFetch() {
725
+ if (originalFetch) {
726
+ globalThis.fetch = originalFetch;
727
+ originalFetch = null;
728
+ }
729
+ }
730
+
731
+ //#endregion
732
+ //#region src/telemetry-system/utils.ts
733
+ /**
734
+ * Parse a numeric environment variable with optional minimum bound.
735
+ */
736
+ function parseNumberEnv(value, minimum = 0) {
737
+ if (value === void 0) return void 0;
738
+ const parsed = Number(value);
739
+ if (!Number.isFinite(parsed) || parsed < minimum) return void 0;
740
+ return parsed;
741
+ }
742
+ /**
743
+ * Parse an integer environment variable with optional minimum bound.
744
+ */
745
+ function parseIntegerEnv(value, minimum = 0) {
746
+ const parsed = parseNumberEnv(value, minimum);
747
+ if (parsed === void 0 || !Number.isInteger(parsed)) return void 0;
748
+ return parsed;
749
+ }
750
+
751
+ //#endregion
752
+ //#region src/telemetry-system/span-ops.ts
753
+ /** High-level span operations so consumers don't need `@opentelemetry/api`. */
754
+ /** Returns `false` when there is no active span or the sampler dropped it. */
755
+ function currentSpanIsRecording() {
756
+ const span = trace.getActiveSpan();
757
+ return span ? span.isRecording() : false;
758
+ }
759
+ /** No-op when the current span is not recording. */
760
+ function setCurrentSpanAttribute(key, value) {
761
+ const span = trace.getActiveSpan();
762
+ if (!span || !span.isRecording()) return;
763
+ span.setAttribute(key, value);
764
+ }
765
+ /** No-op when there is no active span. */
766
+ function setCurrentSpanError(message) {
767
+ const span = trace.getActiveSpan();
768
+ if (!span) return;
769
+ span.setStatus({
770
+ code: SpanStatusCode.ERROR,
771
+ message
772
+ });
773
+ }
774
+ /** No-op when the current span is not recording. */
775
+ function recordSpanEvent(name, attrs) {
776
+ const span = trace.getActiveSpan();
777
+ if (!span || !span.isRecording()) return;
778
+ span.addEvent(name, attrs);
779
+ }
780
+
781
+ //#endregion
782
+ //#region src/telemetry-system/payload.ts
783
+ /** Payload redaction + truncation for invocation event capture. */
784
+ const REDACTED_PLACEHOLDER = "[REDACTED]";
785
+ const TRUNCATION_MARKER = "...\"[TRUNCATED]\"";
786
+ function resolveMaxBytesFromEnv() {
787
+ const raw = process.env.III_TRACE_PAYLOAD_MAX_BYTES;
788
+ if (raw === void 0) return null;
789
+ const trimmed = raw.trim();
790
+ if (trimmed === "" || trimmed.toLowerCase() === "unlimited") return null;
791
+ if (!/^\d+$/.test(trimmed)) return null;
792
+ const parsed = Number(trimmed);
793
+ if (parsed <= 0) return null;
794
+ return parsed;
795
+ }
796
+ const SENSITIVE_FRAGMENTS = [
797
+ "api_key",
798
+ "apikey",
799
+ "api-key",
800
+ "password",
801
+ "secret",
802
+ "credential",
803
+ "authorization",
804
+ "auth_token",
805
+ "access_token",
806
+ "refresh_token",
807
+ "bearer",
808
+ "private_key",
809
+ "client_secret"
810
+ ];
811
+ function isSensitiveKey(key) {
812
+ const lower = key.toLowerCase();
813
+ if (SENSITIVE_FRAGMENTS.some((fragment) => lower.includes(fragment))) return true;
814
+ return lower === "token" || lower.endsWith("_token") || lower.endsWith("-token");
815
+ }
816
+ /** Recursively redact values of sensitive keys. Returns a new value. */
817
+ function redact(value) {
818
+ if (value === null || value === void 0) return value;
819
+ if (Array.isArray(value)) return value.map(redact);
820
+ if (typeof value === "object") {
821
+ const out = {};
822
+ for (const [k, v] of Object.entries(value)) out[k] = isSensitiveKey(k) ? REDACTED_PLACEHOLDER : redact(v);
823
+ return out;
824
+ }
825
+ return value;
826
+ }
827
+ /** Redact then serialize to JSON, optionally capped at `maxBytes`. */
828
+ function redactAndTruncate(value, maxBytes = null) {
829
+ const redacted = redact(value);
830
+ let serialized;
831
+ try {
832
+ serialized = JSON.stringify(redacted) ?? "null";
833
+ } catch {
834
+ serialized = "null";
835
+ }
836
+ if (maxBytes === null || maxBytes === void 0 || maxBytes <= 0) return {
837
+ json: serialized,
838
+ truncated: false
839
+ };
840
+ if (Buffer.byteLength(serialized, "utf8") <= maxBytes) return {
841
+ json: serialized,
842
+ truncated: false
843
+ };
844
+ const markerLen = Buffer.byteLength(TRUNCATION_MARKER, "utf8");
845
+ if (maxBytes <= markerLen) return {
846
+ json: TRUNCATION_MARKER.slice(0, maxBytes),
847
+ truncated: true
848
+ };
849
+ const cap = maxBytes - markerLen;
850
+ const buf = Buffer.from(serialized, "utf8");
851
+ let cut = Math.min(cap, buf.length);
852
+ while (cut > 0 && (buf[cut] & 192) === 128) cut -= 1;
853
+ return {
854
+ json: buf.subarray(0, cut).toString("utf8") + TRUNCATION_MARKER,
855
+ truncated: true
856
+ };
857
+ }
858
+
859
+ //#endregion
860
+ //#region src/telemetry-system/index.ts
861
+ /**
862
+ * OpenTelemetry initialization for the III Node SDK.
863
+ *
864
+ * This module provides trace, metrics, and log export to the III Engine
865
+ * via a shared WebSocket connection using OTLP JSON format.
866
+ */
867
+ /**
868
+ * Normalize an engine WebSocket URL into the dedicated OTEL endpoint.
869
+ * The engine exposes `/otel` for telemetry-only WS connections; routing
870
+ * there keeps this socket out of the worker registry (otherwise it shows
871
+ * up as a ghost null-metadata worker).
872
+ */
873
+ function appendOtelPath(base) {
874
+ const url = new URL(base);
875
+ const path = url.pathname.replace(/\/+$/, "");
876
+ url.pathname = path.endsWith("/otel") ? path : `${path}/otel`;
877
+ return url.toString();
878
+ }
879
+ let sharedConnection = null;
880
+ let tracerProvider = null;
881
+ let meterProvider = null;
882
+ let loggerProvider = null;
883
+ let tracer = null;
884
+ let meter = null;
885
+ let logger = null;
886
+ let serviceName = "iii-node-iii";
887
+ /**
888
+ * Initialize OpenTelemetry with the given configuration.
889
+ * This should be called once at application startup.
890
+ */
891
+ function initOtel(config = {}) {
892
+ if (!(config.enabled ?? parseBoolEnv(process.env.OTEL_ENABLED, DEFAULT_OTEL_CONFIG.enabled))) {
893
+ console.debug("[OTel] OpenTelemetry is disabled. To enable, remove OTEL_ENABLED=false or set enabled: true in config.");
894
+ return;
895
+ }
896
+ serviceName = config.serviceName ?? process.env.OTEL_SERVICE_NAME ?? DEFAULT_OTEL_CONFIG.serviceName;
897
+ const serviceVersion = config.serviceVersion ?? process.env.SERVICE_VERSION ?? DEFAULT_OTEL_CONFIG.serviceVersion;
898
+ const serviceNamespace = config.serviceNamespace ?? process.env.SERVICE_NAMESPACE;
899
+ const serviceInstanceId = config.serviceInstanceId ?? process.env.SERVICE_INSTANCE_ID ?? randomUUID();
900
+ const engineWsUrl = config.engineWsUrl ?? process.env.III_URL ?? DEFAULT_OTEL_CONFIG.engineWsUrl;
901
+ const resourceAttributes = {
902
+ [ATTR_SERVICE_NAME]: serviceName,
903
+ [ATTR_SERVICE_VERSION]: serviceVersion,
904
+ [ATTR_SERVICE_INSTANCE_ID]: serviceInstanceId
905
+ };
906
+ if (serviceNamespace) resourceAttributes[ATTR_SERVICE_NAMESPACE] = serviceNamespace;
907
+ const resource = new Resource(resourceAttributes);
908
+ sharedConnection = new SharedEngineConnection(appendOtelPath(engineWsUrl), config.reconnectionConfig);
909
+ const spanExporter = new EngineSpanExporter(sharedConnection);
910
+ tracerProvider = new NodeTracerProvider({
911
+ resource,
912
+ spanProcessors: [new BaggageSpanProcessor(), new BatchSpanProcessor(spanExporter)]
913
+ });
914
+ propagation.setGlobalPropagator(new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }));
915
+ tracerProvider.register();
916
+ tracer = trace.getTracer(serviceName);
917
+ console.debug(`[OTel] Traces initialized: engine=${engineWsUrl}, service=${serviceName}`);
918
+ if (config.metricsEnabled ?? parseBoolEnv(process.env.OTEL_METRICS_ENABLED, DEFAULT_OTEL_CONFIG.metricsEnabled)) {
919
+ const metricsExporter = new EngineMetricsExporter(sharedConnection);
920
+ const exportIntervalMs = config.metricsExportIntervalMs ?? DEFAULT_OTEL_CONFIG.metricsExportIntervalMs;
921
+ meterProvider = new MeterProvider({
922
+ resource,
923
+ readers: [new PeriodicExportingMetricReader({
924
+ exporter: metricsExporter,
925
+ exportIntervalMillis: exportIntervalMs
926
+ })]
927
+ });
928
+ metrics.setGlobalMeterProvider(meterProvider);
929
+ meter = meterProvider.getMeter(serviceName);
930
+ console.debug(`[OTel] Metrics initialized: interval=${exportIntervalMs}ms`);
931
+ }
932
+ const instrumentations = [...config.instrumentations ?? []];
933
+ if (instrumentations.length > 0) {
934
+ registerInstrumentations({
935
+ instrumentations,
936
+ tracerProvider,
937
+ meterProvider: meterProvider ?? void 0
938
+ });
939
+ console.debug(`[OTel] Instrumentations registered: ${instrumentations.length} total`);
940
+ }
941
+ if (config.fetchInstrumentationEnabled ?? DEFAULT_OTEL_CONFIG.fetchInstrumentationEnabled) {
942
+ patchGlobalFetch(tracer);
943
+ console.debug("[OTel] Global fetch instrumentation enabled");
944
+ }
945
+ const logExporter = new EngineLogExporter(sharedConnection);
946
+ const logsScheduledDelayMillis = config.logsFlushIntervalMs ?? parseNumberEnv(process.env.OTEL_LOGS_FLUSH_INTERVAL_MS, 0) ?? DEFAULT_OTEL_CONFIG.logsFlushIntervalMs;
947
+ const logsMaxExportBatchSize = config.logsBatchSize ?? parseIntegerEnv(process.env.OTEL_LOGS_BATCH_SIZE, 1) ?? DEFAULT_OTEL_CONFIG.logsBatchSize;
948
+ loggerProvider = new LoggerProvider({ resource });
949
+ loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter, {
950
+ scheduledDelayMillis: logsScheduledDelayMillis,
951
+ maxExportBatchSize: logsMaxExportBatchSize
952
+ }));
953
+ logger = loggerProvider.getLogger(serviceName);
954
+ console.debug(`[OTel] Logs initialized: delay=${logsScheduledDelayMillis}ms, batch=${logsMaxExportBatchSize}`);
955
+ }
956
+ /**
957
+ * Shutdown OpenTelemetry, flushing any pending data.
958
+ */
959
+ async function shutdownOtel() {
960
+ if (tracerProvider) {
961
+ await tracerProvider.forceFlush();
962
+ await tracerProvider.shutdown();
963
+ tracerProvider = null;
964
+ }
965
+ if (meterProvider) {
966
+ await meterProvider.forceFlush();
967
+ await meterProvider.shutdown();
968
+ meterProvider = null;
969
+ }
970
+ if (loggerProvider) {
971
+ await loggerProvider.forceFlush();
972
+ await loggerProvider.shutdown();
973
+ loggerProvider = null;
974
+ }
975
+ if (sharedConnection) {
976
+ await sharedConnection.shutdown();
977
+ sharedConnection = null;
978
+ }
979
+ unpatchGlobalFetch();
980
+ tracer = null;
981
+ meter = null;
982
+ logger = null;
983
+ }
984
+ /**
985
+ * Force-flush all OTel providers without tearing them down.
986
+ *
987
+ * Counterpart to {@link shutdownOtel}. Use before short-lived process exits
988
+ * where you want pending spans/metrics/logs delivered but plan to keep using
989
+ * OTel afterwards.
990
+ */
991
+ async function flushOtel() {
992
+ await Promise.all([
993
+ tracerProvider?.forceFlush(),
994
+ meterProvider?.forceFlush(),
995
+ loggerProvider?.forceFlush()
996
+ ].filter(Boolean));
997
+ }
998
+ /**
999
+ * Get the OpenTelemetry tracer instance.
1000
+ */
1001
+ function getTracer() {
1002
+ return tracer;
1003
+ }
1004
+ /**
1005
+ * Get the OpenTelemetry meter instance.
1006
+ */
1007
+ function getMeter() {
1008
+ return meter;
1009
+ }
1010
+ /**
1011
+ * Get the OpenTelemetry logger instance.
1012
+ */
1013
+ function getLogger() {
1014
+ return logger;
1015
+ }
1016
+ /**
1017
+ * Start a new span with the given name and run the callback within it.
1018
+ */
1019
+ async function withSpan(name, options, fn) {
1020
+ if (!tracer) {
1021
+ const noopSpan = {
1022
+ spanContext: () => ({
1023
+ traceId: "",
1024
+ spanId: "",
1025
+ traceFlags: 0
1026
+ }),
1027
+ setAttribute: () => noopSpan,
1028
+ setAttributes: () => noopSpan,
1029
+ addEvent: () => noopSpan,
1030
+ addLink: () => noopSpan,
1031
+ setStatus: () => noopSpan,
1032
+ updateName: () => noopSpan,
1033
+ end: () => {},
1034
+ isRecording: () => false,
1035
+ recordException: () => {},
1036
+ addLinks: () => noopSpan
1037
+ };
1038
+ return fn(noopSpan);
1039
+ }
1040
+ const parentContext = options.traceparent ? extractTraceparent(options.traceparent) : context.active();
1041
+ return tracer.startActiveSpan(name, { kind: options.kind ?? SpanKind.INTERNAL }, parentContext, async (span) => {
1042
+ try {
1043
+ const result = await fn(span);
1044
+ span.setStatus({ code: SpanStatusCode$1.OK });
1045
+ return result;
1046
+ } catch (error) {
1047
+ span.setStatus({
1048
+ code: SpanStatusCode$1.ERROR,
1049
+ message: error.message
1050
+ });
1051
+ span.recordException(error);
1052
+ throw error;
1053
+ } finally {
1054
+ span.end();
1055
+ }
1056
+ });
1057
+ }
1058
+
1059
+ //#endregion
1060
+ //#region src/logger.ts
1061
+ /**
1062
+ * Structured logger that emits logs as OpenTelemetry LogRecords.
1063
+ *
1064
+ * Every log call automatically captures the active trace and span context,
1065
+ * correlating your logs with distributed traces without any manual wiring.
1066
+ * When OTel is not initialized, Logger gracefully falls back to `console.*`.
1067
+ *
1068
+ * Pass structured data as the second argument to any log method. Using an
1069
+ * object of key-value pairs (instead of string interpolation) lets you
1070
+ * filter, aggregate, and build dashboards in your observability backend.
1071
+ *
1072
+ * @example
1073
+ * ```typescript
1074
+ * import { Logger } from 'iii-sdk'
1075
+ *
1076
+ * const logger = new Logger()
1077
+ *
1078
+ * // Basic logging — trace context is injected automatically
1079
+ * logger.info('Worker connected')
1080
+ *
1081
+ * // Structured context for dashboards and alerting
1082
+ * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })
1083
+ * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })
1084
+ * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })
1085
+ * ```
1086
+ */
1087
+ var Logger = class {
1088
+ _otelLogger = null;
1089
+ get otelLogger() {
1090
+ if (!this._otelLogger) this._otelLogger = getLogger();
1091
+ return this._otelLogger;
1092
+ }
1093
+ constructor(traceId, serviceName, spanId) {
1094
+ this.traceId = traceId;
1095
+ this.serviceName = serviceName;
1096
+ this.spanId = spanId;
1097
+ }
1098
+ emit(message, severity, data) {
1099
+ const attributes = {};
1100
+ const traceId = this.traceId ?? currentTraceId();
1101
+ const spanId = this.spanId ?? currentSpanId();
1102
+ if (traceId) attributes.trace_id = traceId;
1103
+ if (spanId) attributes.span_id = spanId;
1104
+ if (this.serviceName) attributes["service.name"] = this.serviceName;
1105
+ if (data !== void 0) attributes["log.data"] = data;
1106
+ if (this.otelLogger) this.otelLogger.emit({
1107
+ severityNumber: severity,
1108
+ body: message,
1109
+ attributes: Object.keys(attributes).length > 0 ? attributes : void 0
1110
+ });
1111
+ else switch (severity) {
1112
+ case SeverityNumber$1.DEBUG:
1113
+ console.debug(message, data);
1114
+ break;
1115
+ case SeverityNumber$1.INFO:
1116
+ console.info(message, data);
1117
+ break;
1118
+ case SeverityNumber$1.WARN:
1119
+ console.warn(message, data);
1120
+ break;
1121
+ case SeverityNumber$1.ERROR:
1122
+ console.error(message, data);
1123
+ break;
1124
+ default: console.log(message, data);
1125
+ }
1126
+ }
1127
+ /**
1128
+ * Log an info-level message.
1129
+ *
1130
+ * @param message - Human-readable log message.
1131
+ * @param data - Structured context attached as OTel log attributes.
1132
+ * Use key-value objects to enable filtering and aggregation in your
1133
+ * observability backend (e.g. Grafana, Datadog, New Relic).
1134
+ *
1135
+ * @example
1136
+ * ```typescript
1137
+ * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })
1138
+ * ```
1139
+ */
1140
+ info(message, data) {
1141
+ this.emit(message, SeverityNumber$1.INFO, data);
1142
+ }
1143
+ /**
1144
+ * Log a warning-level message.
1145
+ *
1146
+ * @param message - Human-readable log message.
1147
+ * @param data - Structured context attached as OTel log attributes.
1148
+ * Use key-value objects to enable filtering and aggregation in your
1149
+ * observability backend (e.g. Grafana, Datadog, New Relic).
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })
1154
+ * ```
1155
+ */
1156
+ warn(message, data) {
1157
+ this.emit(message, SeverityNumber$1.WARN, data);
1158
+ }
1159
+ /**
1160
+ * Log an error-level message.
1161
+ *
1162
+ * @param message - Human-readable log message.
1163
+ * @param data - Structured context attached as OTel log attributes.
1164
+ * Use key-value objects to enable filtering and aggregation in your
1165
+ * observability backend (e.g. Grafana, Datadog, New Relic).
1166
+ *
1167
+ * @example
1168
+ * ```typescript
1169
+ * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })
1170
+ * ```
1171
+ */
1172
+ error(message, data) {
1173
+ this.emit(message, SeverityNumber$1.ERROR, data);
1174
+ }
1175
+ /**
1176
+ * Log a debug-level message.
1177
+ *
1178
+ * @param message - Human-readable log message.
1179
+ * @param data - Structured context attached as OTel log attributes.
1180
+ * Use key-value objects to enable filtering and aggregation in your
1181
+ * observability backend (e.g. Grafana, Datadog, New Relic).
1182
+ *
1183
+ * @example
1184
+ * ```typescript
1185
+ * logger.debug('Cache lookup', { key: 'user:42', hit: false })
1186
+ * ```
1187
+ */
1188
+ debug(message, data) {
1189
+ this.emit(message, SeverityNumber$1.DEBUG, data);
1190
+ }
1191
+ };
1192
+
1193
+ //#endregion
1194
+ //#region src/http-instrumentation.ts
1195
+ const SAFE_REQUEST_HEADERS = ["content-type", "accept"];
1196
+ const SAFE_RESPONSE_HEADERS = ["content-type"];
1197
+ /**
1198
+ * Execute a fetch request inside an OTel CLIENT span.
1199
+ *
1200
+ * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into
1201
+ * outgoing headers, records HTTP semantic-convention attributes, and sets
1202
+ * ERROR span status for HTTP responses with status >= 400 or network errors.
1203
+ */
1204
+ async function executeTracedRequest(input, init) {
1205
+ const tracer = init?.tracer ?? trace.getTracer("iii-node-sdk");
1206
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
1207
+ let url;
1208
+ try {
1209
+ url = new URL(rawUrl);
1210
+ } catch {
1211
+ url = null;
1212
+ }
1213
+ const method = (init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET") ?? "GET").toUpperCase();
1214
+ const name = url?.pathname ? `${method} ${url.pathname}` : method;
1215
+ return tracer.startActiveSpan(name, {
1216
+ kind: SpanKind$1.CLIENT,
1217
+ attributes: {
1218
+ "http.request.method": method,
1219
+ "url.full": url?.toString() ?? rawUrl,
1220
+ "network.protocol.name": "http",
1221
+ ...url ? {
1222
+ "server.address": url.hostname,
1223
+ "url.scheme": url.protocol.replace(":", ""),
1224
+ "url.path": url.pathname
1225
+ } : {},
1226
+ ...url?.port ? { "server.port": Number(url.port) } : {},
1227
+ ...url?.search ? { "url.query": url.search.slice(1) } : {}
1228
+ }
1229
+ }, async (span) => {
1230
+ try {
1231
+ const baseHeaders = typeof input === "object" && "headers" in input ? input.headers : void 0;
1232
+ const headers = new Headers(baseHeaders);
1233
+ if (init?.headers) for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v);
1234
+ const carrier = {};
1235
+ propagation.inject(context.active(), carrier);
1236
+ for (const [k, v] of Object.entries(carrier)) headers.set(k, v);
1237
+ for (const h of SAFE_REQUEST_HEADERS) {
1238
+ const v = headers.get(h);
1239
+ if (v) span.setAttribute(`http.request.header.${h}`, v);
1240
+ }
1241
+ const response = await fetch(input, {
1242
+ ...init,
1243
+ headers
1244
+ });
1245
+ span.setAttribute("http.response.status_code", response.status);
1246
+ const cl = response.headers.get("content-length");
1247
+ if (cl) span.setAttribute("http.response.body.size", Number(cl));
1248
+ for (const h of SAFE_RESPONSE_HEADERS) {
1249
+ const v = response.headers.get(h);
1250
+ if (v) span.setAttribute(`http.response.header.${h}`, v);
1251
+ }
1252
+ if (response.status >= 400) {
1253
+ span.setStatus({
1254
+ code: SpanStatusCode.ERROR,
1255
+ message: String(response.status)
1256
+ });
1257
+ span.setAttribute("error.type", String(response.status));
1258
+ } else span.setStatus({ code: SpanStatusCode.OK });
1259
+ return response;
1260
+ } catch (err) {
1261
+ const error = err;
1262
+ span.recordException(error);
1263
+ span.setStatus({
1264
+ code: SpanStatusCode.ERROR,
1265
+ message: error.message
1266
+ });
1267
+ span.setAttribute("error.type", error.name);
1268
+ throw err;
1269
+ } finally {
1270
+ span.end();
1271
+ }
1272
+ });
1273
+ }
1274
+
1275
+ //#endregion
1276
+ //#region src/worker-metrics.ts
1277
+ /**
1278
+ * Worker metrics collection for the III Node SDK.
1279
+ *
1280
+ * Collects CPU, memory, and event loop metrics for worker health monitoring.
1281
+ * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate
1282
+ * event loop lag measurements.
1283
+ */
1284
+ /**
1285
+ * Collects worker resource metrics including CPU, memory, and event loop lag.
1286
+ *
1287
+ * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop
1288
+ * delay measurements instead of manual `setImmediate` timing.
1289
+ *
1290
+ * @example
1291
+ * ```typescript
1292
+ * const collector = new WorkerMetricsCollector()
1293
+ *
1294
+ * // Collect metrics periodically
1295
+ * setInterval(() => {
1296
+ * const metrics = collector.collect()
1297
+ * console.log('CPU:', metrics.cpu_percent, '%')
1298
+ * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')
1299
+ * }, 5000)
1300
+ *
1301
+ * // Clean up when done
1302
+ * collector.stopMonitoring()
1303
+ * ```
1304
+ */
1305
+ var WorkerMetricsCollector = class {
1306
+ startTime;
1307
+ lastCpuUsage;
1308
+ lastCpuTime;
1309
+ eventLoopHistogram = null;
1310
+ /**
1311
+ * Creates a new WorkerMetricsCollector instance.
1312
+ *
1313
+ * @param options - Configuration options
1314
+ */
1315
+ constructor(options = {}) {
1316
+ this.startTime = Date.now();
1317
+ this.lastCpuUsage = process.cpuUsage();
1318
+ this.lastCpuTime = performance.now();
1319
+ this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20);
1320
+ }
1321
+ /**
1322
+ * Starts the event loop delay histogram monitoring.
1323
+ *
1324
+ * @param resolutionMs - Histogram resolution in milliseconds
1325
+ */
1326
+ startEventLoopMonitoring(resolutionMs) {
1327
+ this.eventLoopHistogram = monitorEventLoopDelay({ resolution: Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 });
1328
+ this.eventLoopHistogram.enable();
1329
+ }
1330
+ /**
1331
+ * Stops the event loop monitoring and releases resources.
1332
+ * Should be called when the collector is no longer needed.
1333
+ */
1334
+ stopMonitoring() {
1335
+ if (this.eventLoopHistogram) {
1336
+ this.eventLoopHistogram.disable();
1337
+ this.eventLoopHistogram = null;
1338
+ }
1339
+ }
1340
+ /**
1341
+ * Collects current worker metrics.
1342
+ *
1343
+ * This method calculates CPU usage since the last collection,
1344
+ * reads memory usage, and gets event loop delay statistics.
1345
+ * The event loop histogram is reset after each collection for
1346
+ * accurate per-interval measurements.
1347
+ *
1348
+ * @returns Current worker metrics snapshot
1349
+ */
1350
+ collect() {
1351
+ const memoryUsage = process.memoryUsage();
1352
+ const cpuUsage = process.cpuUsage();
1353
+ const now = performance.now();
1354
+ const cpuDelta = {
1355
+ user: cpuUsage.user - this.lastCpuUsage.user,
1356
+ system: cpuUsage.system - this.lastCpuUsage.system
1357
+ };
1358
+ const timeDelta = (now - this.lastCpuTime) * 1e3;
1359
+ const cpuPercent = timeDelta > 0 ? (cpuDelta.user + cpuDelta.system) / timeDelta * 100 : 0;
1360
+ this.lastCpuUsage = cpuUsage;
1361
+ this.lastCpuTime = now;
1362
+ let eventLoopLagMs = 0;
1363
+ if (this.eventLoopHistogram) {
1364
+ eventLoopLagMs = this.eventLoopHistogram.mean / 1e6;
1365
+ this.eventLoopHistogram.reset();
1366
+ }
1367
+ return {
1368
+ memory_heap_used: memoryUsage.heapUsed,
1369
+ memory_heap_total: memoryUsage.heapTotal,
1370
+ memory_rss: memoryUsage.rss,
1371
+ memory_external: memoryUsage.external,
1372
+ cpu_user_micros: cpuUsage.user,
1373
+ cpu_system_micros: cpuUsage.system,
1374
+ cpu_percent: Math.min(cpuPercent, 100),
1375
+ event_loop_lag_ms: eventLoopLagMs,
1376
+ uptime_seconds: Math.floor((Date.now() - this.startTime) / 1e3),
1377
+ timestamp_ms: Date.now(),
1378
+ runtime: "node"
1379
+ };
1380
+ }
1381
+ };
1382
+
1383
+ //#endregion
1384
+ //#region src/otel-worker-gauges.ts
1385
+ let registeredGauges = false;
1386
+ let metricsCollector = null;
1387
+ let registeredMeter = null;
1388
+ let registeredBatchCallback = null;
1389
+ let registeredObservables = [];
1390
+ function registerWorkerGauges(meter, options) {
1391
+ if (registeredGauges) return;
1392
+ const { workerId, workerName } = options;
1393
+ const baseAttributes = {
1394
+ "worker.id": workerId,
1395
+ ...workerName && { "worker.name": workerName }
1396
+ };
1397
+ metricsCollector = new WorkerMetricsCollector();
1398
+ const memoryHeapUsed = meter.createObservableGauge("iii.worker.memory.heap_used", {
1399
+ description: "Worker heap memory used in bytes",
1400
+ unit: "bytes"
1401
+ });
1402
+ const memoryHeapTotal = meter.createObservableGauge("iii.worker.memory.heap_total", {
1403
+ description: "Worker total heap memory in bytes",
1404
+ unit: "bytes"
1405
+ });
1406
+ const memoryRss = meter.createObservableGauge("iii.worker.memory.rss", {
1407
+ description: "Worker resident set size in bytes",
1408
+ unit: "bytes"
1409
+ });
1410
+ const memoryExternal = meter.createObservableGauge("iii.worker.memory.external", {
1411
+ description: "Worker external memory in bytes",
1412
+ unit: "bytes"
1413
+ });
1414
+ const cpuPercent = meter.createObservableGauge("iii.worker.cpu.percent", {
1415
+ description: "Worker CPU usage percentage",
1416
+ unit: "%"
1417
+ });
1418
+ const cpuUserMicros = meter.createObservableGauge("iii.worker.cpu.user_micros", {
1419
+ description: "Worker CPU user time in microseconds",
1420
+ unit: "us"
1421
+ });
1422
+ const cpuSystemMicros = meter.createObservableGauge("iii.worker.cpu.system_micros", {
1423
+ description: "Worker CPU system time in microseconds",
1424
+ unit: "us"
1425
+ });
1426
+ const eventLoopLag = meter.createObservableGauge("iii.worker.event_loop.lag_ms", {
1427
+ description: "Worker event loop lag in milliseconds",
1428
+ unit: "ms"
1429
+ });
1430
+ const uptimeSeconds = meter.createObservableGauge("iii.worker.uptime_seconds", {
1431
+ description: "Worker uptime in seconds",
1432
+ unit: "s"
1433
+ });
1434
+ const batchCallback = (observableResult) => {
1435
+ if (!metricsCollector) return;
1436
+ const metrics = metricsCollector.collect();
1437
+ if (metrics.memory_heap_used !== void 0) observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes);
1438
+ if (metrics.memory_heap_total !== void 0) observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes);
1439
+ if (metrics.memory_rss !== void 0) observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes);
1440
+ if (metrics.memory_external !== void 0) observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes);
1441
+ if (metrics.cpu_percent !== void 0) observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes);
1442
+ if (metrics.cpu_user_micros !== void 0) observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes);
1443
+ if (metrics.cpu_system_micros !== void 0) observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes);
1444
+ if (metrics.event_loop_lag_ms !== void 0) observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes);
1445
+ if (metrics.uptime_seconds !== void 0) observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes);
1446
+ };
1447
+ meter.addBatchObservableCallback(batchCallback, [
1448
+ memoryHeapUsed,
1449
+ memoryHeapTotal,
1450
+ memoryRss,
1451
+ memoryExternal,
1452
+ cpuPercent,
1453
+ cpuUserMicros,
1454
+ cpuSystemMicros,
1455
+ eventLoopLag,
1456
+ uptimeSeconds
1457
+ ]);
1458
+ registeredMeter = meter;
1459
+ registeredBatchCallback = batchCallback;
1460
+ registeredObservables = [
1461
+ memoryHeapUsed,
1462
+ memoryHeapTotal,
1463
+ memoryRss,
1464
+ memoryExternal,
1465
+ cpuPercent,
1466
+ cpuUserMicros,
1467
+ cpuSystemMicros,
1468
+ eventLoopLag,
1469
+ uptimeSeconds
1470
+ ];
1471
+ registeredGauges = true;
1472
+ }
1473
+ function stopWorkerGauges() {
1474
+ if (registeredMeter && registeredBatchCallback) registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables);
1475
+ if (metricsCollector) {
1476
+ metricsCollector.stopMonitoring();
1477
+ metricsCollector = null;
1478
+ }
1479
+ registeredMeter = null;
1480
+ registeredBatchCallback = null;
1481
+ registeredObservables = [];
1482
+ registeredGauges = false;
1483
+ }
1484
+
1485
+ //#endregion
1486
+ //#region src/utils.ts
1487
+ /**
1488
+ * Safely stringify a value, handling circular references, BigInt, and other edge cases.
1489
+ * Returns "[unserializable]" if serialization fails for any reason.
1490
+ */
1491
+ function safeStringify(value) {
1492
+ const seen = /* @__PURE__ */ new WeakSet();
1493
+ try {
1494
+ return JSON.stringify(value, (_key, val) => {
1495
+ if (typeof val === "bigint") return val.toString();
1496
+ if (val !== null && typeof val === "object") {
1497
+ if (seen.has(val)) return "[Circular]";
1498
+ seen.add(val);
1499
+ }
1500
+ return val;
1501
+ }) ?? "[unserializable]";
1502
+ } catch {
1503
+ return "[unserializable]";
1504
+ }
1505
+ }
1506
+
1507
+ //#endregion
1508
+ export { BaggageSpanProcessor, DEFAULT_ALLOWLIST, Logger, REDACTED_PLACEHOLDER, SeverityNumber, SpanKind, WorkerMetricsCollector, currentSpanId, currentSpanIsRecording, currentTraceId, executeTracedRequest, extractBaggage, extractContext, extractTraceparent, flushOtel, getAllBaggage, getBaggageEntry, getLogger, getMeter, getTracer, initOtel, injectBaggage, injectTraceparent, patchGlobalFetch, recordSpanEvent, redact, redactAndTruncate, registerWorkerGauges, removeBaggageEntry, resolveMaxBytesFromEnv, safeStringify, setBaggageEntry, setCurrentSpanAttribute, setCurrentSpanError, shutdownOtel, stopWorkerGauges, unpatchGlobalFetch, withSpan };
1509
+ //# sourceMappingURL=index.mjs.map