@bymax-one/nest-telemetry 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,375 @@
1
+ 'use strict';
2
+
3
+ // src/sdk/redaction.ts
4
+ var REDACTED_QUERY_VALUE = "[redacted]";
5
+ var URL_QUERY_ATTRIBUTE = "url.query";
6
+ var TARGET_ATTRIBUTES = ["url.full", "http.url", "http.target"];
7
+ var DEFAULT_REDACTED_QUERY_PARAMS = [
8
+ "sig",
9
+ "Signature",
10
+ "AWSAccessKeyId",
11
+ "X-Goog-Signature",
12
+ "X-Amz-Signature",
13
+ "X-Amz-Credential",
14
+ "X-Amz-Security-Token",
15
+ "token",
16
+ "code",
17
+ "access_token",
18
+ "refresh_token",
19
+ "id_token",
20
+ "secret",
21
+ "password",
22
+ "api_key",
23
+ "apikey",
24
+ "key",
25
+ "signature",
26
+ "sas",
27
+ "auth"
28
+ ];
29
+ function buildRedactedQueryParams(extra) {
30
+ return [.../* @__PURE__ */ new Set([...DEFAULT_REDACTED_QUERY_PARAMS, ...extra])];
31
+ }
32
+ function redactSpanUrlQuery(span) {
33
+ if (URL_QUERY_ATTRIBUTE in span.attributes) {
34
+ span.setAttribute(URL_QUERY_ATTRIBUTE, REDACTED_QUERY_VALUE);
35
+ }
36
+ for (const key of TARGET_ATTRIBUTES) {
37
+ const target = span.attributes[key];
38
+ if (typeof target === "string" && target.includes("?")) {
39
+ span.setAttribute(key, target.slice(0, target.indexOf("?")));
40
+ }
41
+ }
42
+ }
43
+ function createUrlQueryRedactor() {
44
+ return {
45
+ onStart: () => void 0,
46
+ onEnding: (span) => {
47
+ redactSpanUrlQuery(span);
48
+ },
49
+ onEnd: () => void 0,
50
+ shutdown: () => Promise.resolve(),
51
+ forceFlush: () => Promise.resolve()
52
+ };
53
+ }
54
+ function serializeRedisCommandName(commandName) {
55
+ return commandName;
56
+ }
57
+
58
+ // src/sdk/ignore-paths.ts
59
+ function ignorePaths(patterns) {
60
+ const stateless = patterns.map(
61
+ (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""))
62
+ );
63
+ return (request) => {
64
+ if (request.url === void 0) {
65
+ return false;
66
+ }
67
+ const cut = request.url.indexOf("?");
68
+ const path = cut === -1 ? request.url : request.url.slice(0, cut);
69
+ return stateless.some((pattern) => pattern.test(path));
70
+ };
71
+ }
72
+
73
+ // src/sdk/handle.ts
74
+ var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
75
+ var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
76
+ var store = globalThis;
77
+ function registerHandle(handle) {
78
+ store[HANDLE_KEY] = handle;
79
+ }
80
+ function currentHandle() {
81
+ return store[HANDLE_KEY];
82
+ }
83
+ function clearHandle() {
84
+ delete store[HANDLE_KEY];
85
+ }
86
+ function pendingStart() {
87
+ return store[PENDING_KEY];
88
+ }
89
+ function setPendingStart(start) {
90
+ store[PENDING_KEY] = start;
91
+ }
92
+ function clearPendingStart() {
93
+ delete store[PENDING_KEY];
94
+ }
95
+ function createHandle(stopSdk) {
96
+ let flush;
97
+ let finished = false;
98
+ const handle = {
99
+ enabled: true,
100
+ get stopping() {
101
+ return flush !== void 0 && !finished;
102
+ },
103
+ shutdown: () => {
104
+ if (finished) {
105
+ return Promise.resolve();
106
+ }
107
+ flush ??= stopSdk().finally(() => {
108
+ finished = true;
109
+ if (currentHandle() === handle) {
110
+ clearHandle();
111
+ }
112
+ });
113
+ return flush;
114
+ }
115
+ };
116
+ return handle;
117
+ }
118
+ async function shutdownTelemetry() {
119
+ await Promise.allSettled([pendingStart()]);
120
+ await currentHandle()?.shutdown();
121
+ }
122
+
123
+ // src/sdk/assembly.ts
124
+ var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
125
+ var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
126
+ var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
127
+ var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
128
+ var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
129
+ var UNKNOWN_SERVICE_NAME = "unknown_service:node";
130
+ var WARNING_OPTIONS = {
131
+ type: "SecurityWarning",
132
+ code: "BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED"
133
+ };
134
+ function planSignals(env) {
135
+ const overrides = {};
136
+ if (env.metricsExporters.length === 0) overrides.metricReaders = [];
137
+ if (env.logsExporters.length === 0) overrides.logRecordProcessors = [];
138
+ return {
139
+ overrides,
140
+ sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
141
+ };
142
+ }
143
+ function nonBlank(value) {
144
+ const trimmed = value?.trim();
145
+ return trimmed === "" ? void 0 : trimmed;
146
+ }
147
+ function buildResourceAttributes(options, env) {
148
+ const attributes = {};
149
+ const name = env.serviceName ?? nonBlank(options.serviceName);
150
+ attributes["service.name"] = name ?? UNKNOWN_SERVICE_NAME;
151
+ const version = nonBlank(options.serviceVersion);
152
+ if (version !== void 0) attributes["service.version"] = version;
153
+ return attributes;
154
+ }
155
+ function buildInstrumentationConfig(options, signals) {
156
+ const instrumentations = options.instrumentations ?? {};
157
+ const overrides = {};
158
+ for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
159
+ if (config !== void 0) overrides[name] = { ...config };
160
+ }
161
+ const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
162
+ const library = {
163
+ [FS_INSTRUMENTATION]: { enabled: instrumentations.fs === true },
164
+ [HTTP_INSTRUMENTATION]: {},
165
+ [PINO_INSTRUMENTATION]: { disableLogSending: !(instrumentations.sendLogs ?? signals.sendLogs) }
166
+ };
167
+ const merged = {};
168
+ for (const name of /* @__PURE__ */ new Set([...Object.keys(library), ...Object.keys(overrides)])) {
169
+ merged[name] = { ...library[name], ...overrides[name] };
170
+ }
171
+ const hostParams = merged[HTTP_INSTRUMENTATION]?.["redactedQueryParams"];
172
+ merged[HTTP_INSTRUMENTATION] = {
173
+ ...merged[HTTP_INSTRUMENTATION],
174
+ redactedQueryParams: buildRedactedQueryParams([
175
+ ...Array.isArray(hostParams) ? hostParams : [],
176
+ ...options.extraRedactedQueryParams ?? []
177
+ ])
178
+ };
179
+ if (options.ignoreIncomingRequest !== void 0) {
180
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
181
+ }
182
+ if (redactRedis) {
183
+ merged[IOREDIS_INSTRUMENTATION] = {
184
+ ...merged[IOREDIS_INSTRUMENTATION],
185
+ dbStatementSerializer: serializeRedisCommandName
186
+ };
187
+ }
188
+ return merged;
189
+ }
190
+ function warnAboutMissingServiceName(options, env) {
191
+ if (env.serviceName === void 0 && nonBlank(options.serviceName) === void 0) {
192
+ process.emitWarning(
193
+ "No service name is set, so spans are exported as unknown_service:node. Set OTEL_SERVICE_NAME or the serviceName option.",
194
+ { type: "Warning", code: "BYMAX_TELEMETRY_SERVICE_NAME_MISSING" }
195
+ );
196
+ }
197
+ }
198
+ function warnAboutUnsafeOptions(options) {
199
+ if (options.unsafe?.disableUrlRedaction === true) {
200
+ process.emitWarning(
201
+ "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
202
+ WARNING_OPTIONS
203
+ );
204
+ }
205
+ if (options.unsafe?.exportProcessCommandArgs === true) {
206
+ process.emitWarning(
207
+ "Process command-line redaction is disabled: process.command_args and process.command_line are exported in the resource, and command-line arguments can carry secrets.",
208
+ WARNING_OPTIONS
209
+ );
210
+ }
211
+ if (options.unsafe?.disableRedisArgumentRedaction === true) {
212
+ process.emitWarning(
213
+ "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
214
+ WARNING_OPTIONS
215
+ );
216
+ }
217
+ }
218
+
219
+ // src/sdk/environment.ts
220
+ function readExporterList(raw) {
221
+ return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
222
+ }
223
+ function readPositiveNumber(raw) {
224
+ const value = Number(raw);
225
+ return Number.isFinite(value) && value > 0 ? value : void 0;
226
+ }
227
+ function readTelemetryEnvironment(source = process.env) {
228
+ const tuning = {};
229
+ const maxQueueSize = readPositiveNumber(source["OTEL_BSP_MAX_QUEUE_SIZE"]);
230
+ if (maxQueueSize !== void 0) tuning.maxQueueSize = maxQueueSize;
231
+ const scheduledDelayMillis = readPositiveNumber(source["OTEL_BSP_SCHEDULE_DELAY"]);
232
+ if (scheduledDelayMillis !== void 0) tuning.scheduledDelayMillis = scheduledDelayMillis;
233
+ const exportTimeoutMillis = readPositiveNumber(source["OTEL_BSP_EXPORT_TIMEOUT"]);
234
+ if (exportTimeoutMillis !== void 0) tuning.exportTimeoutMillis = exportTimeoutMillis;
235
+ const maxExportBatchSize = readPositiveNumber(source["OTEL_BSP_MAX_EXPORT_BATCH_SIZE"]);
236
+ if (maxExportBatchSize !== void 0) tuning.maxExportBatchSize = maxExportBatchSize;
237
+ const serviceName = source["OTEL_SERVICE_NAME"]?.trim();
238
+ const detectors = source["OTEL_NODE_RESOURCE_DETECTORS"];
239
+ return {
240
+ sdkDisabled: source["OTEL_SDK_DISABLED"]?.toLowerCase() === "true",
241
+ serviceName: serviceName === "" ? void 0 : serviceName,
242
+ metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
243
+ logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
244
+ batchSpanProcessor: tuning,
245
+ resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
246
+ };
247
+ }
248
+
249
+ // src/sdk/resource-detectors.ts
250
+ var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
251
+ var NAMED = /* @__PURE__ */ new Map([
252
+ ["process", ["process"]],
253
+ ["host", ["host", "os"]],
254
+ ["os", ["os"]],
255
+ ["service", ["serviceinstance", "env"]],
256
+ ["serviceinstance", ["serviceinstance"]],
257
+ ["env", ["env"]]
258
+ ]);
259
+ var DEFAULT_DETECTORS = [
260
+ "serviceinstance",
261
+ "process",
262
+ "host",
263
+ "os",
264
+ "env"
265
+ ];
266
+ var ALL_DETECTORS = ["host", "os", "serviceinstance", "process", "env"];
267
+ function withoutAttributes(detector, names) {
268
+ return {
269
+ detect: (config) => {
270
+ const detected = detector.detect(config);
271
+ return {
272
+ ...detected,
273
+ // Spreading an absent attribute map yields an empty one, so a detector that found nothing
274
+ // needs no case of its own.
275
+ attributes: Object.fromEntries(
276
+ Object.entries({ ...detected.attributes }).filter(([name]) => !names.includes(name))
277
+ )
278
+ };
279
+ }
280
+ };
281
+ }
282
+ function selectResourceDetectors(selection, detectors, keepCommandLine) {
283
+ const available = keepCommandLine ? detectors : { ...detectors, process: withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES) };
284
+ if (selection?.includes("none") === true && !selection.includes("all")) {
285
+ return [];
286
+ }
287
+ let chosen = DEFAULT_DETECTORS;
288
+ if (selection?.includes("all") === true) {
289
+ chosen = ALL_DETECTORS;
290
+ } else if (selection !== void 0) {
291
+ chosen = selection.flatMap((name) => NAMED.get(name) ?? []);
292
+ }
293
+ return [...new Set(chosen)].map((name) => available[name]);
294
+ }
295
+
296
+ // src/sdk/start.ts
297
+ var DISABLED_HANDLE = {
298
+ enabled: false,
299
+ shutdown: () => Promise.resolve()
300
+ };
301
+ async function startTelemetry(options = {}) {
302
+ const env = readTelemetryEnvironment(options.env);
303
+ if (options.enabled === false || env.sdkDisabled) {
304
+ return DISABLED_HANDLE;
305
+ }
306
+ let running = currentHandle();
307
+ if (running?.stopping === true) {
308
+ await Promise.allSettled([running.shutdown()]);
309
+ running = currentHandle();
310
+ }
311
+ if (running !== void 0) {
312
+ return running;
313
+ }
314
+ const joined = pendingStart();
315
+ if (joined !== void 0) {
316
+ return joined;
317
+ }
318
+ const start = boot(options, env).finally(clearPendingStart);
319
+ setPendingStart(start);
320
+ return start;
321
+ }
322
+ async function loadPackages() {
323
+ const [sdkNode, sdkTrace, autoInstrumentations, exporter, resources] = await Promise.all([
324
+ import('@opentelemetry/sdk-node'),
325
+ import('@opentelemetry/sdk-trace'),
326
+ import('@opentelemetry/auto-instrumentations-node'),
327
+ import('@opentelemetry/exporter-trace-otlp-http'),
328
+ import('@opentelemetry/resources')
329
+ ]);
330
+ return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
331
+ }
332
+ function buildSdk(packages, options, env) {
333
+ const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
334
+ const signals = planSignals(env);
335
+ return new sdkNode.NodeSDK({
336
+ ...signals.overrides,
337
+ resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
338
+ resourceDetectors: selectResourceDetectors(
339
+ env.resourceDetectors,
340
+ {
341
+ env: resources.envDetector,
342
+ host: resources.hostDetector,
343
+ os: resources.osDetector,
344
+ process: resources.processDetector,
345
+ serviceinstance: resources.serviceInstanceIdDetector
346
+ },
347
+ options.unsafe?.exportProcessCommandArgs === true
348
+ ),
349
+ spanProcessors: [
350
+ // Ordered before the batch processor, so each span is redacted in place before it is exported.
351
+ ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
352
+ new sdkTrace.BatchSpanProcessor({
353
+ exporter: new exporter.OTLPTraceExporter(),
354
+ ...env.batchSpanProcessor
355
+ })
356
+ ],
357
+ instrumentations: [
358
+ autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
359
+ ]
360
+ });
361
+ }
362
+ async function boot(options, env) {
363
+ warnAboutUnsafeOptions(options);
364
+ warnAboutMissingServiceName(options, env);
365
+ const sdk = buildSdk(await loadPackages(), options, env);
366
+ sdk.start();
367
+ const handle = createHandle(() => sdk.shutdown());
368
+ registerHandle(handle);
369
+ return handle;
370
+ }
371
+
372
+ exports.DEFAULT_REDACTED_QUERY_PARAMS = DEFAULT_REDACTED_QUERY_PARAMS;
373
+ exports.ignorePaths = ignorePaths;
374
+ exports.shutdownTelemetry = shutdownTelemetry;
375
+ exports.startTelemetry = startTelemetry;
@@ -0,0 +1,153 @@
1
+ import { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';
2
+
3
+ /**
4
+ * @fileoverview Redaction of span data: the span-end processor logic, the query-parameter list
5
+ * for outgoing requests, and the Redis command serializer.
6
+ * @layer sdk
7
+ *
8
+ * Nothing here imports an OpenTelemetry package at runtime; the type imports are erased. A boot
9
+ * with telemetry disabled loads this module, so it must not pull the SDK graph in.
10
+ */
11
+
12
+ /**
13
+ * Query-parameter names redacted from the URL of outgoing requests. Supplying a list to the HTTP
14
+ * instrumentation REPLACES the names it redacts by default, so those are repeated here, first, ahead
15
+ * of the credential-bearing names added on top. A test compares the first seven with the installed
16
+ * instrumentation's own list, so a name it adds later is caught.
17
+ */
18
+ declare const DEFAULT_REDACTED_QUERY_PARAMS: readonly string[];
19
+
20
+ /**
21
+ * @fileoverview Public option and handle types of the SDK entry point.
22
+ * @layer sdk
23
+ */
24
+
25
+ /** The request an incoming-request predicate sees: only its target, as the server received it. */
26
+ interface IncomingRequestTarget {
27
+ /** Path and query of the request, or `undefined` when the instrumentation has no target. */
28
+ readonly url?: string | undefined;
29
+ }
30
+ /**
31
+ * Switches that turn a redaction off. Each one is a literal `true`, so turning redaction off is
32
+ * always an explicit, greppable act, and each one emits a process warning at boot.
33
+ */
34
+ interface UnsafeOptions {
35
+ /**
36
+ * Keeps `url.query`, `url.full`, `http.url` and `http.target` as the instrumentations set them.
37
+ * Only the span-end redaction is switched off: the credential-parameter redaction on outgoing
38
+ * request URLs stays on.
39
+ */
40
+ readonly disableUrlRedaction?: true;
41
+ /** Keeps Redis command arguments in `db.query.text`, including `EVAL` and `EVALSHA` payloads. */
42
+ readonly disableRedisArgumentRedaction?: true;
43
+ /**
44
+ * Keeps `process.command_args` and `process.command_line` in the exported resource. They are
45
+ * removed by default, because command-line arguments are a common carrier of secrets.
46
+ */
47
+ readonly exportProcessCommandArgs?: true;
48
+ }
49
+ /** Instrumentation choices that are the host's policy, with their safe defaults. */
50
+ interface InstrumentationOptions {
51
+ /** File-system instrumentation. Off by default: it floods traces with context-free disk activity. */
52
+ readonly fs?: boolean;
53
+ /**
54
+ * Whether pino's records are forwarded to the OpenTelemetry logs pipeline. Defaults to whether
55
+ * `OTEL_LOGS_EXPORTER` names an exporter that exports logs.
56
+ */
57
+ readonly sendLogs?: boolean;
58
+ /**
59
+ * Per-instrumentation configuration merged over the library's. The redaction settings are applied
60
+ * after the merge and cannot be replaced here: a host list of query parameters is added to the
61
+ * library's, and the Redis serializer is the library's. Turning the Redis one off takes
62
+ * {@link UnsafeOptions}.
63
+ */
64
+ readonly overrides?: InstrumentationConfigMap;
65
+ }
66
+ /** Options of {@link startTelemetry}. Every field is the host's policy; none is required. */
67
+ interface TelemetryOptions {
68
+ /**
69
+ * Starts the SDK unless `false`. The standard `OTEL_SDK_DISABLED=true` switch disables it
70
+ * whatever this says, so an operator can always turn tracing off.
71
+ */
72
+ readonly enabled?: boolean;
73
+ /**
74
+ * Service name. `OTEL_SERVICE_NAME` overrides it when set, and `unknown_service:node`, the
75
+ * OpenTelemetry specification's default, applies when neither names a service.
76
+ */
77
+ readonly serviceName?: string;
78
+ /** Service version. */
79
+ readonly serviceVersion?: string;
80
+ /** Returns `true` for an incoming request that must produce no server span. Defaults to none. */
81
+ readonly ignoreIncomingRequest?: (request: IncomingRequestTarget) => boolean;
82
+ /** Instrumentation choices. */
83
+ readonly instrumentations?: InstrumentationOptions;
84
+ /** Query-parameter names redacted from outgoing request URLs, added to the library's list. */
85
+ readonly extraRedactedQueryParams?: readonly string[];
86
+ /** Explicit opt-outs from redaction. */
87
+ readonly unsafe?: UnsafeOptions;
88
+ /**
89
+ * The environment the library reads, which defaults to the process environment. The OTel SDK
90
+ * reads `OTEL_EXPORTER_OTLP_*` and the sampler variables from the process environment itself.
91
+ */
92
+ readonly env?: NodeJS.ProcessEnv;
93
+ }
94
+ /** What {@link startTelemetry} returns. */
95
+ interface TelemetryHandle {
96
+ /** Whether the SDK was started. */
97
+ readonly enabled: boolean;
98
+ /** Flushes buffered spans and stops the SDK. Resolves immediately when it was never started. */
99
+ shutdown(): Promise<void>;
100
+ }
101
+
102
+ /**
103
+ * @fileoverview Path-based predicate for incoming requests that must produce no span.
104
+ * @layer sdk
105
+ */
106
+
107
+ /**
108
+ * Builds a predicate that matches the path of an incoming request against the patterns.
109
+ *
110
+ * Only the path is compared: the query string is cut first, so an exclusion cannot be switched off
111
+ * by appending a parameter, and a probe path hidden in a query cannot trigger one. A request with no
112
+ * target is not matched: failing open costs a span nobody wanted, where the opposite silently drops
113
+ * the traffic least likely to be well formed. Anchor the patterns at both ends; an unanchored one
114
+ * also matches routes that merely contain the word.
115
+ *
116
+ * @param patterns - Patterns tested against the path alone.
117
+ * @returns A predicate for `TelemetryOptions.ignoreIncomingRequest`.
118
+ */
119
+ declare function ignorePaths(patterns: readonly RegExp[]): (request: IncomingRequestTarget) => boolean;
120
+
121
+ /**
122
+ * @fileoverview The process-wide handle the preload registers and the application drains.
123
+ * @layer sdk
124
+ *
125
+ * The preload and the application are separate module graphs: one loaded through `--import`, the
126
+ * other through the entry point. They share no module state, only `globalThis`, so the handle lives
127
+ * there under a registry symbol that no application key can collide with.
128
+ */
129
+
130
+ /**
131
+ * Flushes and stops the SDK the preload registered, if any.
132
+ *
133
+ * Awaiting this guarantees buffered spans are exported before the process exits, including when
134
+ * another caller started the flush or the start is still in progress. With nothing registered, which is the case when telemetry is
135
+ * disabled, it resolves immediately.
136
+ *
137
+ * @returns A promise that resolves once buffered spans are exported.
138
+ */
139
+ declare function shutdownTelemetry(): Promise<void>;
140
+
141
+ /**
142
+ * Starts the OpenTelemetry SDK, unless it is disabled.
143
+ *
144
+ * The SDK is off when the host passes `enabled: false` or the standard `OTEL_SDK_DISABLED=true`
145
+ * switch is set, whichever the host says. Starting twice returns the handle already running.
146
+ *
147
+ * @param options - The host's policy.
148
+ * @returns The handle, which flushes and stops the SDK.
149
+ */
150
+ declare function startTelemetry(options?: TelemetryOptions): Promise<TelemetryHandle>;
151
+
152
+ export { DEFAULT_REDACTED_QUERY_PARAMS, ignorePaths, shutdownTelemetry, startTelemetry };
153
+ export type { IncomingRequestTarget, InstrumentationOptions, TelemetryHandle, TelemetryOptions, UnsafeOptions };
@@ -0,0 +1,153 @@
1
+ import { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';
2
+
3
+ /**
4
+ * @fileoverview Redaction of span data: the span-end processor logic, the query-parameter list
5
+ * for outgoing requests, and the Redis command serializer.
6
+ * @layer sdk
7
+ *
8
+ * Nothing here imports an OpenTelemetry package at runtime; the type imports are erased. A boot
9
+ * with telemetry disabled loads this module, so it must not pull the SDK graph in.
10
+ */
11
+
12
+ /**
13
+ * Query-parameter names redacted from the URL of outgoing requests. Supplying a list to the HTTP
14
+ * instrumentation REPLACES the names it redacts by default, so those are repeated here, first, ahead
15
+ * of the credential-bearing names added on top. A test compares the first seven with the installed
16
+ * instrumentation's own list, so a name it adds later is caught.
17
+ */
18
+ declare const DEFAULT_REDACTED_QUERY_PARAMS: readonly string[];
19
+
20
+ /**
21
+ * @fileoverview Public option and handle types of the SDK entry point.
22
+ * @layer sdk
23
+ */
24
+
25
+ /** The request an incoming-request predicate sees: only its target, as the server received it. */
26
+ interface IncomingRequestTarget {
27
+ /** Path and query of the request, or `undefined` when the instrumentation has no target. */
28
+ readonly url?: string | undefined;
29
+ }
30
+ /**
31
+ * Switches that turn a redaction off. Each one is a literal `true`, so turning redaction off is
32
+ * always an explicit, greppable act, and each one emits a process warning at boot.
33
+ */
34
+ interface UnsafeOptions {
35
+ /**
36
+ * Keeps `url.query`, `url.full`, `http.url` and `http.target` as the instrumentations set them.
37
+ * Only the span-end redaction is switched off: the credential-parameter redaction on outgoing
38
+ * request URLs stays on.
39
+ */
40
+ readonly disableUrlRedaction?: true;
41
+ /** Keeps Redis command arguments in `db.query.text`, including `EVAL` and `EVALSHA` payloads. */
42
+ readonly disableRedisArgumentRedaction?: true;
43
+ /**
44
+ * Keeps `process.command_args` and `process.command_line` in the exported resource. They are
45
+ * removed by default, because command-line arguments are a common carrier of secrets.
46
+ */
47
+ readonly exportProcessCommandArgs?: true;
48
+ }
49
+ /** Instrumentation choices that are the host's policy, with their safe defaults. */
50
+ interface InstrumentationOptions {
51
+ /** File-system instrumentation. Off by default: it floods traces with context-free disk activity. */
52
+ readonly fs?: boolean;
53
+ /**
54
+ * Whether pino's records are forwarded to the OpenTelemetry logs pipeline. Defaults to whether
55
+ * `OTEL_LOGS_EXPORTER` names an exporter that exports logs.
56
+ */
57
+ readonly sendLogs?: boolean;
58
+ /**
59
+ * Per-instrumentation configuration merged over the library's. The redaction settings are applied
60
+ * after the merge and cannot be replaced here: a host list of query parameters is added to the
61
+ * library's, and the Redis serializer is the library's. Turning the Redis one off takes
62
+ * {@link UnsafeOptions}.
63
+ */
64
+ readonly overrides?: InstrumentationConfigMap;
65
+ }
66
+ /** Options of {@link startTelemetry}. Every field is the host's policy; none is required. */
67
+ interface TelemetryOptions {
68
+ /**
69
+ * Starts the SDK unless `false`. The standard `OTEL_SDK_DISABLED=true` switch disables it
70
+ * whatever this says, so an operator can always turn tracing off.
71
+ */
72
+ readonly enabled?: boolean;
73
+ /**
74
+ * Service name. `OTEL_SERVICE_NAME` overrides it when set, and `unknown_service:node`, the
75
+ * OpenTelemetry specification's default, applies when neither names a service.
76
+ */
77
+ readonly serviceName?: string;
78
+ /** Service version. */
79
+ readonly serviceVersion?: string;
80
+ /** Returns `true` for an incoming request that must produce no server span. Defaults to none. */
81
+ readonly ignoreIncomingRequest?: (request: IncomingRequestTarget) => boolean;
82
+ /** Instrumentation choices. */
83
+ readonly instrumentations?: InstrumentationOptions;
84
+ /** Query-parameter names redacted from outgoing request URLs, added to the library's list. */
85
+ readonly extraRedactedQueryParams?: readonly string[];
86
+ /** Explicit opt-outs from redaction. */
87
+ readonly unsafe?: UnsafeOptions;
88
+ /**
89
+ * The environment the library reads, which defaults to the process environment. The OTel SDK
90
+ * reads `OTEL_EXPORTER_OTLP_*` and the sampler variables from the process environment itself.
91
+ */
92
+ readonly env?: NodeJS.ProcessEnv;
93
+ }
94
+ /** What {@link startTelemetry} returns. */
95
+ interface TelemetryHandle {
96
+ /** Whether the SDK was started. */
97
+ readonly enabled: boolean;
98
+ /** Flushes buffered spans and stops the SDK. Resolves immediately when it was never started. */
99
+ shutdown(): Promise<void>;
100
+ }
101
+
102
+ /**
103
+ * @fileoverview Path-based predicate for incoming requests that must produce no span.
104
+ * @layer sdk
105
+ */
106
+
107
+ /**
108
+ * Builds a predicate that matches the path of an incoming request against the patterns.
109
+ *
110
+ * Only the path is compared: the query string is cut first, so an exclusion cannot be switched off
111
+ * by appending a parameter, and a probe path hidden in a query cannot trigger one. A request with no
112
+ * target is not matched: failing open costs a span nobody wanted, where the opposite silently drops
113
+ * the traffic least likely to be well formed. Anchor the patterns at both ends; an unanchored one
114
+ * also matches routes that merely contain the word.
115
+ *
116
+ * @param patterns - Patterns tested against the path alone.
117
+ * @returns A predicate for `TelemetryOptions.ignoreIncomingRequest`.
118
+ */
119
+ declare function ignorePaths(patterns: readonly RegExp[]): (request: IncomingRequestTarget) => boolean;
120
+
121
+ /**
122
+ * @fileoverview The process-wide handle the preload registers and the application drains.
123
+ * @layer sdk
124
+ *
125
+ * The preload and the application are separate module graphs: one loaded through `--import`, the
126
+ * other through the entry point. They share no module state, only `globalThis`, so the handle lives
127
+ * there under a registry symbol that no application key can collide with.
128
+ */
129
+
130
+ /**
131
+ * Flushes and stops the SDK the preload registered, if any.
132
+ *
133
+ * Awaiting this guarantees buffered spans are exported before the process exits, including when
134
+ * another caller started the flush or the start is still in progress. With nothing registered, which is the case when telemetry is
135
+ * disabled, it resolves immediately.
136
+ *
137
+ * @returns A promise that resolves once buffered spans are exported.
138
+ */
139
+ declare function shutdownTelemetry(): Promise<void>;
140
+
141
+ /**
142
+ * Starts the OpenTelemetry SDK, unless it is disabled.
143
+ *
144
+ * The SDK is off when the host passes `enabled: false` or the standard `OTEL_SDK_DISABLED=true`
145
+ * switch is set, whichever the host says. Starting twice returns the handle already running.
146
+ *
147
+ * @param options - The host's policy.
148
+ * @returns The handle, which flushes and stops the SDK.
149
+ */
150
+ declare function startTelemetry(options?: TelemetryOptions): Promise<TelemetryHandle>;
151
+
152
+ export { DEFAULT_REDACTED_QUERY_PARAMS, ignorePaths, shutdownTelemetry, startTelemetry };
153
+ export type { IncomingRequestTarget, InstrumentationOptions, TelemetryHandle, TelemetryOptions, UnsafeOptions };