@iii-dev/observability 0.19.4-alpha.2 → 0.19.4-alpha.4
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/README.md +3 -1
- package/dist/index.cjs +7 -488
- package/dist/index.d.cts +1 -244
- package/dist/index.d.mts +1 -244
- package/dist/index.mjs +2 -454
- package/dist/internal.cjs +8 -4
- package/dist/internal.d.cts +1 -2
- package/dist/internal.d.mts +1 -2
- package/dist/internal.mjs +2 -2
- package/package.json +2 -14
- package/dist/index-Cb4IHzbB.d.cts +0 -177
- package/dist/index-opxepmJp.d.mts +0 -177
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/telemetry-system-BFMV9aXn.cjs +0 -1305
- package/dist/telemetry-system-BFMV9aXn.cjs.map +0 -1
- package/dist/telemetry-system-BORUEH-H.mjs +0 -1126
- package/dist/telemetry-system-BORUEH-H.mjs.map +0 -1
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
import { AttributeValue, Attributes, Context, Meter as Meter$1, Span as Span$1, SpanKind, Tracer as Tracer$1 } from "@opentelemetry/api";
|
|
2
|
-
import { Logger, SeverityNumber } from "@opentelemetry/api-logs";
|
|
3
|
-
import { Instrumentation } from "@opentelemetry/instrumentation";
|
|
4
|
-
import { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
5
|
-
|
|
6
|
-
//#region src/telemetry-system/types.d.ts
|
|
7
|
-
/** Configuration for WebSocket reconnection behavior */
|
|
8
|
-
interface ReconnectionConfig {
|
|
9
|
-
/** Starting delay in milliseconds (default: 1000ms) */
|
|
10
|
-
initialDelayMs: number;
|
|
11
|
-
/** Maximum delay cap in milliseconds (default: 30000ms) */
|
|
12
|
-
maxDelayMs: number;
|
|
13
|
-
/** Exponential backoff multiplier (default: 2) */
|
|
14
|
-
backoffMultiplier: number;
|
|
15
|
-
/** Random jitter factor 0-1 (default: 0.3) */
|
|
16
|
-
jitterFactor: number;
|
|
17
|
-
/** Maximum retry attempts, -1 for infinite (default: -1) */
|
|
18
|
-
maxRetries: number;
|
|
19
|
-
}
|
|
20
|
-
/** Configuration for OpenTelemetry initialization. */
|
|
21
|
-
interface OtelConfig {
|
|
22
|
-
/** Whether OpenTelemetry export is enabled. Defaults to true. Set to false or OTEL_ENABLED=false/0/no/off to disable. */
|
|
23
|
-
enabled?: boolean;
|
|
24
|
-
/** The service name to report. Defaults to OTEL_SERVICE_NAME or "iii-node". */
|
|
25
|
-
serviceName?: string;
|
|
26
|
-
/** The service version to report. Defaults to SERVICE_VERSION env var or "unknown". */
|
|
27
|
-
serviceVersion?: string;
|
|
28
|
-
/** The service namespace to report. Defaults to SERVICE_NAMESPACE env var. */
|
|
29
|
-
serviceNamespace?: string;
|
|
30
|
-
/** The service instance ID to report. Defaults to SERVICE_INSTANCE_ID env var or auto-generated UUID. */
|
|
31
|
-
serviceInstanceId?: string;
|
|
32
|
-
/** III Engine WebSocket URL. Defaults to III_URL or "ws://localhost:49134". */
|
|
33
|
-
engineWsUrl?: string;
|
|
34
|
-
/** OpenTelemetry instrumentations to register (e.g., PrismaInstrumentation). */
|
|
35
|
-
instrumentations?: Instrumentation[];
|
|
36
|
-
/** Whether OpenTelemetry metrics export is enabled. Defaults to true. Set to false or OTEL_METRICS_ENABLED=false/0/no/off to disable. */
|
|
37
|
-
metricsEnabled?: boolean;
|
|
38
|
-
/** Metrics export interval in milliseconds. Defaults to 60000 (60 seconds). */
|
|
39
|
-
metricsExportIntervalMs?: number;
|
|
40
|
-
/**
|
|
41
|
-
* Span processor flush delay in milliseconds. Defaults to 100ms. This is how
|
|
42
|
-
* long an ended span waits in the batch buffer before it is flushed to the
|
|
43
|
-
* engine — the OpenTelemetry default of 5000ms is what makes traces appear
|
|
44
|
-
* seconds after the action. Env override: OTEL_SPANS_FLUSH_INTERVAL_MS.
|
|
45
|
-
*/
|
|
46
|
-
spansFlushIntervalMs?: number;
|
|
47
|
-
/** Log processor flush delay in milliseconds. Defaults to 100ms. Env override: OTEL_LOGS_FLUSH_INTERVAL_MS. */
|
|
48
|
-
logsFlushIntervalMs?: number;
|
|
49
|
-
/** Maximum number of log records exported per batch. Defaults to 1. */
|
|
50
|
-
logsBatchSize?: number;
|
|
51
|
-
/** Whether to auto-instrument globalThis.fetch calls. Defaults to true. Works on Node.js, Bun, and Deno. Set to false to disable. */
|
|
52
|
-
fetchInstrumentationEnabled?: boolean;
|
|
53
|
-
/** Optional reconnection configuration for the WebSocket connection. */
|
|
54
|
-
reconnectionConfig?: Partial<ReconnectionConfig>;
|
|
55
|
-
}
|
|
56
|
-
//#endregion
|
|
57
|
-
//#region src/telemetry-system/context.d.ts
|
|
58
|
-
/**
|
|
59
|
-
* Extract the current trace ID from the active span context.
|
|
60
|
-
*/
|
|
61
|
-
declare function currentTraceId(): string | undefined;
|
|
62
|
-
/**
|
|
63
|
-
* Extract the current span ID from the active span context.
|
|
64
|
-
*/
|
|
65
|
-
declare function currentSpanId(): string | undefined;
|
|
66
|
-
/**
|
|
67
|
-
* Inject the current trace context into a W3C traceparent header string.
|
|
68
|
-
*/
|
|
69
|
-
declare function injectTraceparent(): string | undefined;
|
|
70
|
-
/**
|
|
71
|
-
* Extract a trace context from a W3C traceparent header string.
|
|
72
|
-
*/
|
|
73
|
-
declare function extractTraceparent(traceparent: string): Context;
|
|
74
|
-
/**
|
|
75
|
-
* Inject the current baggage into a W3C baggage header string.
|
|
76
|
-
*/
|
|
77
|
-
declare function injectBaggage(): string | undefined;
|
|
78
|
-
/**
|
|
79
|
-
* Extract baggage from a W3C baggage header string.
|
|
80
|
-
*/
|
|
81
|
-
declare function extractBaggage(baggage: string): Context;
|
|
82
|
-
/**
|
|
83
|
-
* Extract both trace context and baggage from their respective headers.
|
|
84
|
-
*/
|
|
85
|
-
declare function extractContext(traceparent?: string, baggage?: string): Context;
|
|
86
|
-
/**
|
|
87
|
-
* Get a baggage entry from the current context.
|
|
88
|
-
*/
|
|
89
|
-
declare function getBaggageEntry(key: string): string | undefined;
|
|
90
|
-
/**
|
|
91
|
-
* Set a baggage entry in the current context.
|
|
92
|
-
*/
|
|
93
|
-
declare function setBaggageEntry(key: string, value: string): Context;
|
|
94
|
-
/**
|
|
95
|
-
* Remove a baggage entry from the current context.
|
|
96
|
-
*/
|
|
97
|
-
declare function removeBaggageEntry(key: string): Context;
|
|
98
|
-
/**
|
|
99
|
-
* Get all baggage entries from the current context.
|
|
100
|
-
*/
|
|
101
|
-
declare function getAllBaggage(): Record<string, string>;
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/telemetry-system/baggage-span-processor.d.ts
|
|
104
|
-
/** DEFAULT_ALLOWLIST drift across languages would break worker chains;
|
|
105
|
-
* lockstep tests in each SDK pin this constant at CI time. */
|
|
106
|
-
declare const DEFAULT_ALLOWLIST: readonly string[];
|
|
107
|
-
declare class BaggageSpanProcessor implements SpanProcessor {
|
|
108
|
-
private readonly allowlist;
|
|
109
|
-
constructor(allowlist?: readonly string[]);
|
|
110
|
-
onStart(span: Span, parentContext: Context): void;
|
|
111
|
-
onEnd(_span: ReadableSpan): void;
|
|
112
|
-
shutdown(): Promise<void>;
|
|
113
|
-
forceFlush(): Promise<void>;
|
|
114
|
-
}
|
|
115
|
-
//#endregion
|
|
116
|
-
//#region src/telemetry-system/span-ops.d.ts
|
|
117
|
-
/** Returns `false` when there is no active span or the sampler dropped it. */
|
|
118
|
-
declare function currentSpanIsRecording(): boolean;
|
|
119
|
-
/** No-op when the current span is not recording. */
|
|
120
|
-
declare function setCurrentSpanAttribute(key: string, value: AttributeValue): void;
|
|
121
|
-
/** No-op when there is no active span. */
|
|
122
|
-
declare function setCurrentSpanError(message: string): void;
|
|
123
|
-
/** No-op when the current span is not recording. */
|
|
124
|
-
declare function recordSpanEvent(name: string, attrs?: Attributes): void;
|
|
125
|
-
//#endregion
|
|
126
|
-
//#region src/telemetry-system/payload.d.ts
|
|
127
|
-
/** Payload redaction + truncation for invocation event capture. */
|
|
128
|
-
declare const REDACTED_PLACEHOLDER = "[REDACTED]";
|
|
129
|
-
declare function resolveMaxBytesFromEnv(): number | null;
|
|
130
|
-
/** Recursively redact values of sensitive keys. Returns a new value. */
|
|
131
|
-
declare function redact(value: unknown): unknown;
|
|
132
|
-
/** Redact then serialize to JSON, optionally capped at `maxBytes`. */
|
|
133
|
-
declare function redactAndTruncate(value: unknown, maxBytes?: number | null): {
|
|
134
|
-
json: string;
|
|
135
|
-
truncated: boolean;
|
|
136
|
-
};
|
|
137
|
-
//#endregion
|
|
138
|
-
//#region src/telemetry-system/index.d.ts
|
|
139
|
-
/**
|
|
140
|
-
* Initialize OpenTelemetry with the given configuration.
|
|
141
|
-
* This should be called once at application startup.
|
|
142
|
-
*/
|
|
143
|
-
declare function initOtel(config?: OtelConfig): void;
|
|
144
|
-
/**
|
|
145
|
-
* Shutdown OpenTelemetry, flushing any pending data.
|
|
146
|
-
*/
|
|
147
|
-
declare function shutdownOtel(): Promise<void>;
|
|
148
|
-
/**
|
|
149
|
-
* Force-flush all OTel providers without tearing them down.
|
|
150
|
-
*
|
|
151
|
-
* Counterpart to {@link shutdownOtel}. Use before short-lived process exits
|
|
152
|
-
* where you want pending spans/metrics/logs delivered but plan to keep using
|
|
153
|
-
* OTel afterwards.
|
|
154
|
-
*/
|
|
155
|
-
declare function flushOtel(): Promise<void>;
|
|
156
|
-
/**
|
|
157
|
-
* Get the OpenTelemetry tracer instance.
|
|
158
|
-
*/
|
|
159
|
-
declare function getTracer(): Tracer$1 | null;
|
|
160
|
-
/**
|
|
161
|
-
* Get the OpenTelemetry meter instance.
|
|
162
|
-
*/
|
|
163
|
-
declare function getMeter(): Meter$1 | null;
|
|
164
|
-
/**
|
|
165
|
-
* Get the OpenTelemetry logger instance.
|
|
166
|
-
*/
|
|
167
|
-
declare function getLogger(): Logger | null;
|
|
168
|
-
/**
|
|
169
|
-
* Start a new span with the given name and run the callback within it.
|
|
170
|
-
*/
|
|
171
|
-
declare function withSpan<T>(name: string, options: {
|
|
172
|
-
kind?: SpanKind;
|
|
173
|
-
traceparent?: string;
|
|
174
|
-
}, fn: (span: Span$1) => Promise<T>): Promise<T>;
|
|
175
|
-
//#endregion
|
|
176
|
-
export { injectTraceparent as A, currentTraceId as C, getAllBaggage as D, extractTraceparent as E, setBaggageEntry as M, OtelConfig as N, getBaggageEntry as O, ReconnectionConfig as P, currentSpanId as S, extractContext as T, recordSpanEvent as _, flushOtel as a, BaggageSpanProcessor as b, getTracer as c, withSpan as d, REDACTED_PLACEHOLDER as f, currentSpanIsRecording as g, resolveMaxBytesFromEnv as h, Span$1 as i, removeBaggageEntry as j, injectBaggage as k, initOtel as l, redactAndTruncate as m, Meter$1 as n, getLogger as o, redact as p, SeverityNumber as r, getMeter as s, Logger as t, shutdownOtel as u, setCurrentSpanAttribute as v, extractBaggage as w, DEFAULT_ALLOWLIST as x, setCurrentSpanError as y };
|
|
177
|
-
//# sourceMappingURL=index-Cb4IHzbB.d.cts.map
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
import { Logger, SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
|
|
2
|
-
import { AttributeValue, Attributes, Context, Meter as Meter$1, Span as Span$1, SpanKind as SpanKind$1, Tracer as Tracer$1 } from "@opentelemetry/api";
|
|
3
|
-
import { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
4
|
-
import { Instrumentation } from "@opentelemetry/instrumentation";
|
|
5
|
-
|
|
6
|
-
//#region src/telemetry-system/types.d.ts
|
|
7
|
-
/** Configuration for WebSocket reconnection behavior */
|
|
8
|
-
interface ReconnectionConfig {
|
|
9
|
-
/** Starting delay in milliseconds (default: 1000ms) */
|
|
10
|
-
initialDelayMs: number;
|
|
11
|
-
/** Maximum delay cap in milliseconds (default: 30000ms) */
|
|
12
|
-
maxDelayMs: number;
|
|
13
|
-
/** Exponential backoff multiplier (default: 2) */
|
|
14
|
-
backoffMultiplier: number;
|
|
15
|
-
/** Random jitter factor 0-1 (default: 0.3) */
|
|
16
|
-
jitterFactor: number;
|
|
17
|
-
/** Maximum retry attempts, -1 for infinite (default: -1) */
|
|
18
|
-
maxRetries: number;
|
|
19
|
-
}
|
|
20
|
-
/** Configuration for OpenTelemetry initialization. */
|
|
21
|
-
interface OtelConfig {
|
|
22
|
-
/** Whether OpenTelemetry export is enabled. Defaults to true. Set to false or OTEL_ENABLED=false/0/no/off to disable. */
|
|
23
|
-
enabled?: boolean;
|
|
24
|
-
/** The service name to report. Defaults to OTEL_SERVICE_NAME or "iii-node". */
|
|
25
|
-
serviceName?: string;
|
|
26
|
-
/** The service version to report. Defaults to SERVICE_VERSION env var or "unknown". */
|
|
27
|
-
serviceVersion?: string;
|
|
28
|
-
/** The service namespace to report. Defaults to SERVICE_NAMESPACE env var. */
|
|
29
|
-
serviceNamespace?: string;
|
|
30
|
-
/** The service instance ID to report. Defaults to SERVICE_INSTANCE_ID env var or auto-generated UUID. */
|
|
31
|
-
serviceInstanceId?: string;
|
|
32
|
-
/** III Engine WebSocket URL. Defaults to III_URL or "ws://localhost:49134". */
|
|
33
|
-
engineWsUrl?: string;
|
|
34
|
-
/** OpenTelemetry instrumentations to register (e.g., PrismaInstrumentation). */
|
|
35
|
-
instrumentations?: Instrumentation[];
|
|
36
|
-
/** Whether OpenTelemetry metrics export is enabled. Defaults to true. Set to false or OTEL_METRICS_ENABLED=false/0/no/off to disable. */
|
|
37
|
-
metricsEnabled?: boolean;
|
|
38
|
-
/** Metrics export interval in milliseconds. Defaults to 60000 (60 seconds). */
|
|
39
|
-
metricsExportIntervalMs?: number;
|
|
40
|
-
/**
|
|
41
|
-
* Span processor flush delay in milliseconds. Defaults to 100ms. This is how
|
|
42
|
-
* long an ended span waits in the batch buffer before it is flushed to the
|
|
43
|
-
* engine — the OpenTelemetry default of 5000ms is what makes traces appear
|
|
44
|
-
* seconds after the action. Env override: OTEL_SPANS_FLUSH_INTERVAL_MS.
|
|
45
|
-
*/
|
|
46
|
-
spansFlushIntervalMs?: number;
|
|
47
|
-
/** Log processor flush delay in milliseconds. Defaults to 100ms. Env override: OTEL_LOGS_FLUSH_INTERVAL_MS. */
|
|
48
|
-
logsFlushIntervalMs?: number;
|
|
49
|
-
/** Maximum number of log records exported per batch. Defaults to 1. */
|
|
50
|
-
logsBatchSize?: number;
|
|
51
|
-
/** Whether to auto-instrument globalThis.fetch calls. Defaults to true. Works on Node.js, Bun, and Deno. Set to false to disable. */
|
|
52
|
-
fetchInstrumentationEnabled?: boolean;
|
|
53
|
-
/** Optional reconnection configuration for the WebSocket connection. */
|
|
54
|
-
reconnectionConfig?: Partial<ReconnectionConfig>;
|
|
55
|
-
}
|
|
56
|
-
//#endregion
|
|
57
|
-
//#region src/telemetry-system/context.d.ts
|
|
58
|
-
/**
|
|
59
|
-
* Extract the current trace ID from the active span context.
|
|
60
|
-
*/
|
|
61
|
-
declare function currentTraceId(): string | undefined;
|
|
62
|
-
/**
|
|
63
|
-
* Extract the current span ID from the active span context.
|
|
64
|
-
*/
|
|
65
|
-
declare function currentSpanId(): string | undefined;
|
|
66
|
-
/**
|
|
67
|
-
* Inject the current trace context into a W3C traceparent header string.
|
|
68
|
-
*/
|
|
69
|
-
declare function injectTraceparent(): string | undefined;
|
|
70
|
-
/**
|
|
71
|
-
* Extract a trace context from a W3C traceparent header string.
|
|
72
|
-
*/
|
|
73
|
-
declare function extractTraceparent(traceparent: string): Context;
|
|
74
|
-
/**
|
|
75
|
-
* Inject the current baggage into a W3C baggage header string.
|
|
76
|
-
*/
|
|
77
|
-
declare function injectBaggage(): string | undefined;
|
|
78
|
-
/**
|
|
79
|
-
* Extract baggage from a W3C baggage header string.
|
|
80
|
-
*/
|
|
81
|
-
declare function extractBaggage(baggage: string): Context;
|
|
82
|
-
/**
|
|
83
|
-
* Extract both trace context and baggage from their respective headers.
|
|
84
|
-
*/
|
|
85
|
-
declare function extractContext(traceparent?: string, baggage?: string): Context;
|
|
86
|
-
/**
|
|
87
|
-
* Get a baggage entry from the current context.
|
|
88
|
-
*/
|
|
89
|
-
declare function getBaggageEntry(key: string): string | undefined;
|
|
90
|
-
/**
|
|
91
|
-
* Set a baggage entry in the current context.
|
|
92
|
-
*/
|
|
93
|
-
declare function setBaggageEntry(key: string, value: string): Context;
|
|
94
|
-
/**
|
|
95
|
-
* Remove a baggage entry from the current context.
|
|
96
|
-
*/
|
|
97
|
-
declare function removeBaggageEntry(key: string): Context;
|
|
98
|
-
/**
|
|
99
|
-
* Get all baggage entries from the current context.
|
|
100
|
-
*/
|
|
101
|
-
declare function getAllBaggage(): Record<string, string>;
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/telemetry-system/baggage-span-processor.d.ts
|
|
104
|
-
/** DEFAULT_ALLOWLIST drift across languages would break worker chains;
|
|
105
|
-
* lockstep tests in each SDK pin this constant at CI time. */
|
|
106
|
-
declare const DEFAULT_ALLOWLIST: readonly string[];
|
|
107
|
-
declare class BaggageSpanProcessor implements SpanProcessor {
|
|
108
|
-
private readonly allowlist;
|
|
109
|
-
constructor(allowlist?: readonly string[]);
|
|
110
|
-
onStart(span: Span, parentContext: Context): void;
|
|
111
|
-
onEnd(_span: ReadableSpan): void;
|
|
112
|
-
shutdown(): Promise<void>;
|
|
113
|
-
forceFlush(): Promise<void>;
|
|
114
|
-
}
|
|
115
|
-
//#endregion
|
|
116
|
-
//#region src/telemetry-system/span-ops.d.ts
|
|
117
|
-
/** Returns `false` when there is no active span or the sampler dropped it. */
|
|
118
|
-
declare function currentSpanIsRecording(): boolean;
|
|
119
|
-
/** No-op when the current span is not recording. */
|
|
120
|
-
declare function setCurrentSpanAttribute(key: string, value: AttributeValue): void;
|
|
121
|
-
/** No-op when there is no active span. */
|
|
122
|
-
declare function setCurrentSpanError(message: string): void;
|
|
123
|
-
/** No-op when the current span is not recording. */
|
|
124
|
-
declare function recordSpanEvent(name: string, attrs?: Attributes): void;
|
|
125
|
-
//#endregion
|
|
126
|
-
//#region src/telemetry-system/payload.d.ts
|
|
127
|
-
/** Payload redaction + truncation for invocation event capture. */
|
|
128
|
-
declare const REDACTED_PLACEHOLDER = "[REDACTED]";
|
|
129
|
-
declare function resolveMaxBytesFromEnv(): number | null;
|
|
130
|
-
/** Recursively redact values of sensitive keys. Returns a new value. */
|
|
131
|
-
declare function redact(value: unknown): unknown;
|
|
132
|
-
/** Redact then serialize to JSON, optionally capped at `maxBytes`. */
|
|
133
|
-
declare function redactAndTruncate(value: unknown, maxBytes?: number | null): {
|
|
134
|
-
json: string;
|
|
135
|
-
truncated: boolean;
|
|
136
|
-
};
|
|
137
|
-
//#endregion
|
|
138
|
-
//#region src/telemetry-system/index.d.ts
|
|
139
|
-
/**
|
|
140
|
-
* Initialize OpenTelemetry with the given configuration.
|
|
141
|
-
* This should be called once at application startup.
|
|
142
|
-
*/
|
|
143
|
-
declare function initOtel(config?: OtelConfig): void;
|
|
144
|
-
/**
|
|
145
|
-
* Shutdown OpenTelemetry, flushing any pending data.
|
|
146
|
-
*/
|
|
147
|
-
declare function shutdownOtel(): Promise<void>;
|
|
148
|
-
/**
|
|
149
|
-
* Force-flush all OTel providers without tearing them down.
|
|
150
|
-
*
|
|
151
|
-
* Counterpart to {@link shutdownOtel}. Use before short-lived process exits
|
|
152
|
-
* where you want pending spans/metrics/logs delivered but plan to keep using
|
|
153
|
-
* OTel afterwards.
|
|
154
|
-
*/
|
|
155
|
-
declare function flushOtel(): Promise<void>;
|
|
156
|
-
/**
|
|
157
|
-
* Get the OpenTelemetry tracer instance.
|
|
158
|
-
*/
|
|
159
|
-
declare function getTracer(): Tracer$1 | null;
|
|
160
|
-
/**
|
|
161
|
-
* Get the OpenTelemetry meter instance.
|
|
162
|
-
*/
|
|
163
|
-
declare function getMeter(): Meter$1 | null;
|
|
164
|
-
/**
|
|
165
|
-
* Get the OpenTelemetry logger instance.
|
|
166
|
-
*/
|
|
167
|
-
declare function getLogger(): Logger | null;
|
|
168
|
-
/**
|
|
169
|
-
* Start a new span with the given name and run the callback within it.
|
|
170
|
-
*/
|
|
171
|
-
declare function withSpan<T>(name: string, options: {
|
|
172
|
-
kind?: SpanKind$1;
|
|
173
|
-
traceparent?: string;
|
|
174
|
-
}, fn: (span: Span$1) => Promise<T>): Promise<T>;
|
|
175
|
-
//#endregion
|
|
176
|
-
export { injectTraceparent as A, currentTraceId as C, getAllBaggage as D, extractTraceparent as E, setBaggageEntry as M, OtelConfig as N, getBaggageEntry as O, ReconnectionConfig as P, currentSpanId as S, extractContext as T, recordSpanEvent as _, flushOtel as a, BaggageSpanProcessor as b, getTracer as c, withSpan as d, REDACTED_PLACEHOLDER as f, currentSpanIsRecording as g, resolveMaxBytesFromEnv as h, Span$1 as i, removeBaggageEntry as j, injectBaggage as k, initOtel as l, redactAndTruncate as m, Meter$1 as n, getLogger as o, redact as p, SeverityNumber$1 as r, getMeter as s, Logger as t, shutdownOtel as u, setCurrentSpanAttribute as v, extractBaggage as w, DEFAULT_ALLOWLIST as x, setCurrentSpanError as y };
|
|
177
|
-
//# sourceMappingURL=index-opxepmJp.d.mts.map
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["getOtelLogger","currentTraceId","currentSpanId","SeverityNumber","trace","SpanKind","otelContext","SpanStatusCode","performance"],"sources":["../src/logger.ts","../src/http-instrumentation.ts","../src/worker-metrics.ts","../src/otel-worker-gauges.ts","../src/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging — trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,oCAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAWC,yCAAgB;EAChD,MAAM,SAAS,KAAK,UAAUC,wCAAe;AAE7C,MAAI,QACF,YAAW,WAAW;AAExB,MAAI,OACF,YAAW,UAAU;AAEvB,MAAI,KAAK,YACP,YAAW,kBAAkB,KAA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AInF,OAAM,2BAA2B,eAAe;EAC9C;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;AAED,oBAAmB;;AAGrB,SAAgB,mBAAyB;AAEvC,KAAI,mBAAmB,wBACrB,iBAAgB,8BAA8B,yBAAyB,sBAAsB;AAG/F,KAAI,kBAAkB;AACpB,mBAAiB,gBAAgB;AACjC,qBAAmB;;AAGrB,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;ACjJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["getOtelLogger","SeverityNumber","otelContext"],"sources":["../src/logger.ts","../src/http-instrumentation.ts","../src/worker-metrics.ts","../src/otel-worker-gauges.ts","../src/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging — trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,WAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAW,gBAAgB;EAChD,MAAM,SAAS,KAAK,UAAU,eAAe;AAE7C,MAAI,QACF,YAAW,WA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