@bymax-one/nest-telemetry 1.0.8 → 1.0.10

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/CHANGELOG.md CHANGED
@@ -8,7 +8,76 @@ The `release.yml` workflow extracts the section matching the pushed `vX.Y.Z` tag
8
8
  as the GitHub Release body, so each released version needs a matching `## [X.Y.Z]`
9
9
  heading here.
10
10
 
11
- ## [Unreleased]
11
+ ## [1.0.10] - 2026-11-21
12
+
13
+ ### Fixed
14
+
15
+ - **An option of the wrong kind is refused, and no longer read as something it is not.** The string `'false'`, a
16
+ number or an object for `instrumentations.sendLogs` was truthy and turned the export of log records on, which
17
+ sends data off the host; the string `'true'` for an `unsafe` flag was dropped without a word; a string for
18
+ `extraRedactedQueryParams` was spread into its characters and a number threw a `TypeError` out of the start.
19
+ `startTelemetry` now rejects with an error whose `code` is `BYMAX_TELEMETRY_OPTION_INVALID` and whose `option`
20
+ names the option, before any SDK is started. `shutdownTimeoutMs` keeps its documented fallback.
21
+ - **The settings of an `instrumentations.overrides` entry that decide what leaves the host are checked too.** An
22
+ override was spread over the library's configuration unchecked, so `{ disableLogSending: 0 }` for the pino
23
+ instrumentation turned log sending on and a non-boolean `enabled` replaced the one the library forces. Each
24
+ entry is now copied once; `enabled` and `disableLogSending` must be booleans, `redactedQueryParams` an array
25
+ of strings, every setting named `...Hook` a function, an entry holds at most 1000 settings, and a `__proto__` key is refused. The error names
26
+ `instrumentations.overrides[]` and never the instrumentation or the value.
27
+ - **Each option of a call is read once.** A getter could make a warning and the effect of the call disagree. A
28
+ call now reads each option once, checks its kind, and works from the copy.
29
+
30
+ ### Documentation
31
+
32
+ - **The README says a failed start starts no new SDK.** It said "no SDK started and no handle left", which is
33
+ wrong for a later call that finds an SDK already running; it now says that the failed start starts no new SDK
34
+ and that a first start leaves no handle.
35
+ - **The README lists the ranges of the peers that are not OpenTelemetry packages**, as `package.json` declares
36
+ them, and its CPU item no longer says "that handler".
37
+
38
+ ### Apply to a derived backend
39
+
40
+ A configuration that passed a value of the wrong kind used to be accepted and now fails at start with
41
+ `BYMAX_TELEMETRY_OPTION_INVALID`. Look for a string such as `'false'` in `instrumentations.sendLogs` or an `unsafe`
42
+ flag (read from an environment variable without converting it), a single string for `extraRedactedQueryParams`
43
+ (pass `['name']`), a non-boolean `enabled` or `disableLogSending`, a non-array `redactedQueryParams` or a non-function `...Hook` inside an `overrides` entry, and a list, map or entry of more than 1000 items. Nothing else changes: a plain value of
44
+ the documented kind behaves as before.
45
+
46
+ ## [1.0.9] - 2026-11-20
47
+
48
+ ### Fixed
49
+
50
+ - **The start reads `unsafe` and `instrumentations` once, each field once, and `ignoreIncomingRequest` once.** The
51
+ warning about turned-off redactions, the SDK build and the instrumentation config each read `unsafe` (and its
52
+ fields), the winston transport warning and the config each read `instrumentations`, and the config read
53
+ `ignoreIncomingRequest` twice, so an option object with a getter, on the option or on one of its fields, could
54
+ make a warning and the effect disagree: a first read of `{}` gave no warning while the host id, the process
55
+ command line and the raw URL were exported. The start now copies both options into a plain object, reading each
56
+ field once, and every step works from the copy. This replaces the per-step reads that 1.0.8 described.
57
+ - **An option that throws when read can no longer leave a started SDK without a handle.** `shutdownTimeoutMs` was
58
+ read after the SDK had started, so a getter that threw there made the start reject while the SDK kept running
59
+ and nothing could stop it. It is read before the start now, with the other options, and every position at which
60
+ an operation on the options fails ends in that error with no SDK started.
61
+
62
+ ### Documentation
63
+
64
+ - **The README says that the sampler ratio warning does not repeat a blank value.** It repeats the value only when
65
+ it is not blank; a blank one is called blank.
66
+ - **1.0.7's note on a rejecting `TELEMETRY_LOGGER` is superseded.** It says a rejection is dropped silently; since
67
+ 1.0.8 the report goes to the Nest logger (a failed flush) or to a process warning (a shutdown timeout, a failed
68
+ export), and the README's logger paragraph says so. The README also says that starting twice returns the running
69
+ handle unless `enabled: false`, which returns a disabled one.
70
+ - **The README says what `startTelemetry` rejects with.** The error that was thrown, as it was thrown: there is no
71
+ library error class for a start. When an option cannot be read, the start ends with that error, with no SDK
72
+ started and no handle left.
73
+
74
+ ### Apply to a derived backend
75
+
76
+ The public declarations did not change. A derived backend acts on this behaviour:
77
+
78
+ 1. An options object whose `unsafe` or `instrumentations` is a getter, or whose fields are getters (a computed or lazy
79
+ option), is now read once, each field once, for the whole start, so the redaction warning and the redaction the
80
+ SDK applies come from the same values. An option that answers differently on each read no longer splits them.
12
81
 
13
82
  ## [1.0.8] - 2026-11-20
14
83
 
@@ -375,6 +444,8 @@ First release.
375
444
  - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
376
445
  application, with planted secrets absent from the exported body and negative controls.
377
446
 
447
+ [1.0.10]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.10
448
+ [1.0.9]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.9
378
449
  [1.0.8]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.8
379
450
  [1.0.7]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.7
380
451
  [1.0.6]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.6
package/README.md CHANGED
@@ -156,7 +156,7 @@ const telemetry = await startTelemetry({
156
156
  await telemetry.shutdown()
157
157
  ```
158
158
 
159
- This package installs no signal handler and shows none, because handling signals belongs to the application: a `SIGTERM` listener replaces Node's default termination, so it has to end the process itself once its work is done. `startTelemetry` resolves to a handle with `enabled` and `shutdown()`. Starting twice returns the handle already running, including across two copies of the module (an ES-module preload and a CommonJS application share the handle through `globalThis`). A later call that passes options is told they were ignored, and `enabled: false` against a running SDK is told it does not stop it: `shutdownTelemetry()` does.
159
+ This package installs no signal handler and shows none, because handling signals belongs to the application: a `SIGTERM` listener replaces Node's default termination, so it has to end the process itself once its work is done. `startTelemetry` resolves to a handle with `enabled` and `shutdown()`. Starting twice returns the handle already running (unless `enabled: false`, which returns a disabled handle), including across two copies of the module (an ES-module preload and a CommonJS application share the handle through `globalThis`). A later call that passes options is told they were ignored, and `enabled: false` against a running SDK is told it does not stop it: `shutdownTelemetry()` does.
160
160
 
161
161
  ---
162
162
 
@@ -216,7 +216,7 @@ The start emits these warnings:
216
216
  | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. The warning names the error's code and package in the same way. |
217
217
  | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
218
218
  | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
219
- | `BYMAX_TELEMETRY_OPTIONS_IGNORED` | A `startTelemetry` call reached an SDK that was already running, so its options were ignored, or `enabled: false` did not stop it. Any defined option counts, `env` included. |
219
+ | `BYMAX_TELEMETRY_OPTIONS_IGNORED` | A `startTelemetry` call reached an SDK that was already running, so its options were ignored, or `enabled: false` did not stop it. Any option that is neither `undefined` nor `null` counts, `env` included. |
220
220
  | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
221
221
  | `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` | The final flush did not finish within `shutdownTimeoutMs`. Shutdown resolved without it, and spans still queued may be lost. With `TelemetryModule` and a bound `TELEMETRY_LOGGER`, it is reported through `errorStructured` under `TRACING_SHUTDOWN_TIMEOUT` instead. |
222
222
  | `BYMAX_TELEMETRY_EXPORT_FAILED` | A span export failed, so the batch was dropped. The warning names the exporter and a short error code, never the payload or the endpoint, and repeats at most once a minute. With `TelemetryModule` and a bound `TELEMETRY_LOGGER` that has `warnStructured`, it is reported through it under `TRACING_EXPORT_FAILED` instead. |
@@ -225,12 +225,14 @@ The start emits these warnings:
225
225
  | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING` | Log forwarding is on and winston is installed, but `@opentelemetry/winston-transport` cannot be resolved from the winston instrumentation, so winston records are not forwarded. Install it as a direct dependency of the application, or ignore the warning when your application never creates a winston logger or `OTEL_LOGS_EXPORTER` is `none`. |
226
226
  | `BYMAX_TELEMETRY_BSP_VALUE_IGNORED` | An `OTEL_BSP_SCHEDULE_DELAY` or `OTEL_BSP_EXPORT_TIMEOUT` above 2147483647 ms was ignored, because a timer cannot hold it and Node would clamp it to 1 ms. The default applies. |
227
227
 
228
- The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it.
228
+ An option of the wrong kind is refused before anything starts: `startTelemetry` rejects with an error whose `code` is `BYMAX_TELEMETRY_OPTION_INVALID` and whose `option` names it, such as `instrumentations.sendLogs`. The message says what the option must be and never repeats the value. A boolean option (`enabled`, `instrumentations.fs`, `instrumentations.sendLogs` and each `unsafe` flag) must be a boolean, so the string `'false'` is refused and not read as true; `serviceName` and `serviceVersion` must be strings, `ignoreIncomingRequest` a function, and `unsafe`, `instrumentations`, `instrumentations.overrides` and `env` objects. `extraRedactedQueryParams` must be an array of at most 1000 strings, and `instrumentations.overrides` an object of at most 1000 entries that are each an object. Inside an override, `enabled` and `disableLogSending` must be booleans, `redactedQueryParams` an array of at most 1000 strings, every setting whose name ends in `Hook` a function, an entry holds at most 1000 settings, and a key named `__proto__` is refused; any other setting, a function that is not a hook included, is passed on as the host wrote it. The error names the setting as `instrumentations.overrides[].enabled` and never the instrumentation or the value. `null` and `undefined` mean the option was not given. `shutdownTimeoutMs` is not refused: a value that is not a number in range means the default. Each option of a call is read once, so what a warning says and what the call does come from the same read.
229
+
230
+ The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it. It rejects with the error that was thrown, as it was thrown, and only a refused option carries a code, so an option whose getter throws (or a proxy that fails an operation) ends the start with that error and starts no new SDK, so a first start leaves no handle either. A later call that finds an SDK already running can also reject, while it reads the options of the call; the running SDK and its handle are not touched.
229
231
 
230
232
  ### What is traced
231
233
 
232
234
  - **Load order matters only for modules your application loads itself.** The core `http` module is patched even when the preload runs after it. A client such as `ioredis` is patched only if the preload ran before the application required it. Measured: an application that required `ioredis` first exported no `ioredis` span.
233
- - **`ioredis` commands are traced only under an active span; node-redis commands are not.** The `ioredis` instrumentation defaults to `requireParentSpan: true`, so a command issued outside any request produces no span. The node-redis (`redis`) instrumentation defaults to `false`, so it traces a command with no request around it too. Measured with `redis` 5 and 6.
235
+ - **`ioredis` commands are traced only under an active span; node-redis commands are not.** The `ioredis` instrumentation defaults to `requireParentSpan: true`, so a command issued outside any request produces no span. The node-redis (`redis`) instrumentation defaults to `false`, so it traces a command with no request around it too. Measured as of 2026-11-13 with `redis` 5 and 6; the proofs in this repository run `redis` 6.
234
236
  - **`fs` instrumentation is off by default**, because it floods traces with disk activity that has no context. Turn it on with `instrumentations.fs`.
235
237
 
236
238
  ### Forwarding log records
@@ -281,18 +283,18 @@ Awaiting `shutdown()` or `shutdownTelemetry()` means the spans were exported, wh
281
283
 
282
284
  The wait is bounded. A collector that accepts a connection and never answers would otherwise hold shutdown for the exporter's own timeout, ten seconds by default, so a flush that has not finished within `shutdownTimeoutMs` (5 seconds unless set, at most 120 seconds) stops holding the caller: shutdown emits `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and resolves. The flush keeps running in the background and a failure after the deadline is dropped. Spans still queued at that point may be lost.
283
285
 
284
- A start after a shutdown in the same process is refused: `startTelemetry` rejects, with an error that says to start once per process (in a test suite, once in a global setup), and the process emits `BYMAX_TELEMETRY_RESTART_UNSUPPORTED`. Auto-instrumented spans can never resume after a shutdown, because the modules the first start instrumented are already patched against its tracer provider; spans created through the API could, but a half-working restart is refused on purpose. Measured with an in-process HTTP request and one manual span per run: after a restart that released the API globals, the manual span was exported and the HTTP spans were not. The preload turns the refusal into a `BYMAX_TELEMETRY_START_FAILED` warning and the application still boots.
286
+ A start after a shutdown in the same process is refused: `startTelemetry` rejects, with an error that says to start once per process (in a test suite, once in a global setup), and the process emits `BYMAX_TELEMETRY_RESTART_UNSUPPORTED`. Auto-instrumented spans can never resume after a shutdown, because the modules the first start instrumented are already patched against its tracer provider; spans created through the API could, but a half-working restart is refused on purpose. Measured as of 2026-11-13, in runs that are not part of this repository, with an in-process HTTP request and one manual span per run: after a restart that released the API globals, the manual span was exported and the HTTP spans were not. The preload turns the refusal into a `BYMAX_TELEMETRY_START_FAILED` warning and the application still boots.
285
287
 
286
288
  ---
287
289
 
288
290
  ## 🏭 Production
289
291
 
290
- Every figure here was measured on one laptop, with Node 24 and a handler that does nothing but answer. Read them as orders of magnitude for your own measurement to confirm, not as promises.
292
+ Every measured figure here was taken on one laptop, with Node 24, as of 2026-11-13; no script in this repository reproduces them. Read them as orders of magnitude for your own measurement to confirm, not as promises.
291
293
 
292
- - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty or only whitespace, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when one was given, the value (a blank value is called blank, not unset). The SDK matches the sampler name exactly: `always_on`, `always_off`, `traceidratio`, `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, in lower case and without surrounding whitespace. Any other value, `TraceIdRatio` included, is replaced by its default and samples every trace; when the value differs from one of those names only in letter case or surrounding whitespace, the start warns once with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value. A name that is not one of those up to case and whitespace, such as `xyz` or a misspelling like `always_offf`, is not warned about: it samples every trace as well, so check the spelling of the variable. It reads the process environment, as the SDK does, and not the `env` option.
294
+ - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty or only whitespace, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when a non-blank value was given, the value (cut to 40 characters, with control, separator and invisible characters written as escapes) (a blank value is called blank, not unset, and is not repeated). The SDK matches the sampler name exactly: `always_on`, `always_off`, `traceidratio`, `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, in lower case and without surrounding whitespace. Any other value, `TraceIdRatio` included, is replaced by its default and samples every trace; when the value differs from one of those names only in letter case or surrounding whitespace, the start warns once with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value. A name that is not one of those up to case and whitespace, such as `xyz` or a misspelling like `always_offf`, is not warned about: it samples every trace as well, so check the spelling of the variable. It reads the process environment, as the SDK does, and not the `env` option.
293
295
  - **TLS to the collector.** Against a collector whose certificate Node does not trust, every export failed with `self-signed certificate`. Setting `OTEL_EXPORTER_OTLP_CERTIFICATE` to the CA file, or `NODE_EXTRA_CA_CERTS`, exported all 2,000 spans in the same setup.
294
296
  - **A collector that is down.** The batch is dropped and the library emits `BYMAX_TELEMETRY_EXPORT_FAILED`, at most once a minute. Shutdown stops waiting at `shutdownTimeoutMs`, 5 seconds by default. Before that deadline existed, shutdown against a closed port took 7,048 ms and 7,214 ms in two runs.
295
- - **CPU.** One process, 4 runs per mode, median CPU time per request: 25 µs without the library, 26 µs with it loaded and disabled, 58 µs with a healthy collector (range 35 to 66) and 43 µs with the collector down (range 26 to 65). The extra cost in that handler is roughly 10 to 40 µs per request, and a handler that does real I/O dilutes it. The same configuration varied by up to a factor of two between runs.
297
+ - **CPU.** One process, 4 runs per mode, median CPU time per request: 25 µs without the library, 26 µs with it loaded and disabled, 58 µs with a healthy collector (range 35 to 66) and 43 µs with the collector down (range 26 to 65). The extra cost is roughly 10 to 40 µs per request, and a handler that does real I/O dilutes it. The same configuration varied by up to a factor of two between runs.
296
298
  - **Memory.** After 10 seconds idle, RSS was 61 to 63 MB without the library and with it disabled, 83 to 95 MB with a healthy collector and 142 to 160 MB with the collector unreachable. Under sustained load with the collector unreachable, the default settings reached between about 195 and 310 MB in one 90-second run.
297
299
  - **Small containers.** `node --max-semi-space-size=8` is an optional V8 lever that shrinks the young generation. Under the same unreachable-collector load, RSS had a median of 138 MB (maximum 158) against about 195 to 310 MB for the default settings. The memory figures are one run each, so they are noisy, and a setting of 4 did not do better than 8 (RSS levelled at about 220 MB). At 1,000 requests per second against an unreachable collector, p99 latency over three runs each was 3.6 to 7.3 ms with the default settings and 4.8 to 6.8 ms with 8, so no cost showed at that load. The extra memory with the collector down is most likely churn from failed exports, which was not measured separately.
298
300
 
@@ -310,6 +312,8 @@ Every `@opentelemetry/*` package is an optional peer. The `0.x` packages break b
310
312
  | `@opentelemetry/resources` | `^3.1.0` |
311
313
  | `@opentelemetry/auto-instrumentations-node` | `^0.83.0` |
312
314
 
315
+ The optional peers that are not OpenTelemetry packages are `@bymax-one/nest-core` `^1.1.0`, `prom-client` `^15.0.0`, `@nestjs/common` `^11.0.16`, `@nestjs/core` `^11.1.18`, `reflect-metadata` `^0.2.0` and `rxjs` `^7.8.0`.
316
+
313
317
  A caret on a `0.x` version allows patch releases only, so each OpenTelemetry minor needs a release of this package to widen the range. That is a human decision: a weekly job runs the unit and end-to-end suites, the build and the tarball checks against the newest release of every OpenTelemetry package, ignoring the lockfile, and opens an issue when they fail. A range is widened in a pull request after the job passes against the new generation. Dependabot groups the OpenTelemetry packages, so they move as one set.
314
318
 
315
319
  ---
@@ -444,7 +448,7 @@ pnpm check:runtime # packed-tarball consumer proofs
444
448
  | `InstrumentationOptions` | type | `fs`, `sendLogs` and `overrides` |
445
449
  | `IncomingRequestTarget` | type | What an incoming-request predicate sees: the request `url` |
446
450
 
447
- `ignorePaths` copies each pattern without its `g` and `y` flags, which would keep state between calls. Anchor the patterns at both ends, with no nested quantifiers: an unanchored one also matches routes that merely contain the word, and `/^\/(a+)+$/` took 2.5 s and 5.5 s in two runs on a 28-character path, and the time grows exponentially with the length.
451
+ `ignorePaths` copies each pattern without its `g` and `y` flags, which would keep state between calls. Anchor the patterns at both ends, with no nested quantifiers: an unanchored one also matches routes that merely contain the word, and `/^\/(a+)+$/` took 2.5 s and 5.5 s in two runs on a 28-character path (as of 2026-11-13, not a test; the tests pin the refusal of a path over 2,048 characters), and the time grows exponentially with the length.
448
452
 
449
453
  ### Register: `@bymax-one/nest-telemetry/register`
450
454
 
@@ -475,7 +479,7 @@ No exports. `node --import @bymax-one/nest-telemetry/register` registers the loa
475
479
 
476
480
  ## 🚫 What This Library Does NOT Do
477
481
 
478
- By design, the following are out of scope:
482
+ By design, the following are out of scope. The attribute names below are the ones the instrumentations recorded as of 2026-11-13; only the mysql2 behaviour has a canary in the proofs, so check the others against the versions you install:
479
483
 
480
484
  - ❌ **Redact secrets in the URL path** — only the query string is removed. A path such as `/reset/<token>` is exported as it is
481
485
  - ❌ **Redact SQL text with inline literals** — database instrumentations record the statement, and values written into it are exported. A value bound to a placeholder is not recorded by `instrumentation-mysql2` 0.71, measured with mysql2 2.3.3, 3.0.0, 3.9.0 and 3.24.6; a canary in the proofs fails if that stops being true
@@ -490,7 +494,7 @@ By design, the following are out of scope:
490
494
  - ❌ **Redact baggage**
491
495
  - ❌ **Redact request and response bodies, or HTTP headers** — they are not captured by default, and they are not redacted if you enable capturing them
492
496
  - ❌ **Redact attributes your own code sets**
493
- - ❌ **Redact log records forwarded through `OTEL_LOGS_EXPORTER`** — the library redacts spans, and a log record is exported as the logger produced it, so redact in the logger. Measured with `@bymax-one/nest-logger` 1.4.16, which redacts before it hands the record over: a password and a nested token never reached the collector, and the `[REDACTED]` marker did. A plain pino logger with no redaction exported its password
497
+ - ❌ **Redact log records forwarded through `OTEL_LOGS_EXPORTER`** — the library redacts spans, and a log record is exported as the logger produced it, so redact in the logger. Measured as of 2026-11-13, in a run that is not part of this repository, with `@bymax-one/nest-logger` 1.4.16, which redacts before it hands the record over: a password and a nested token never reached the collector, and the `[REDACTED]` marker did. A plain pino logger with no redaction exported its password
494
498
  - ❌ **Choose a sampler** — configure `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`
495
499
  - ❌ **Run a collector or a backend** — point `OTEL_EXPORTER_OTLP_ENDPOINT` at one
496
500
  - ❌ **Decide your span names** — those come from the instrumentations and from your code
@@ -95,6 +95,107 @@ function describeFailure(error) {
95
95
  }
96
96
  }
97
97
 
98
+ // src/sdk/option-kinds.ts
99
+ var MAX_OPTION_ENTRIES = 1e3;
100
+ var TelemetryOptionError = class extends Error {
101
+ /**
102
+ * @param option - The option that was refused.
103
+ * @param expected - What the option must be.
104
+ */
105
+ constructor(option, expected) {
106
+ super(`The ${option} option must be ${expected}, so the start was refused.`);
107
+ /** The stable code of this error. */
108
+ this.code = "BYMAX_TELEMETRY_OPTION_INVALID";
109
+ this.name = "TelemetryOptionError";
110
+ this.option = option;
111
+ }
112
+ };
113
+ function isGiven(value) {
114
+ return value !== void 0 && value !== null;
115
+ }
116
+ function requireBoolean(option, value) {
117
+ if (!isGiven(value)) return void 0;
118
+ if (typeof value !== "boolean") throw new TelemetryOptionError(option, "a boolean");
119
+ return value;
120
+ }
121
+ function requireString(option, value) {
122
+ if (!isGiven(value)) return void 0;
123
+ if (typeof value !== "string") throw new TelemetryOptionError(option, "a string");
124
+ return value;
125
+ }
126
+ function requireFunction(option, value) {
127
+ if (!isGiven(value)) return void 0;
128
+ if (typeof value !== "function") throw new TelemetryOptionError(option, "a function");
129
+ return value;
130
+ }
131
+ function requireObject(option, value) {
132
+ if (value === void 0 || value === null) return void 0;
133
+ if (typeof value !== "object" || Array.isArray(value)) {
134
+ throw new TelemetryOptionError(option, "an object");
135
+ }
136
+ return value;
137
+ }
138
+ function settleStringList(option, value) {
139
+ if (!isGiven(value)) return void 0;
140
+ if (!Array.isArray(value)) throw new TelemetryOptionError(option, "an array of strings");
141
+ const length = value.length;
142
+ if (typeof length !== "number" || !Number.isInteger(length) || length < 0) {
143
+ throw new TelemetryOptionError(option, "an array of strings");
144
+ }
145
+ if (length > MAX_OPTION_ENTRIES) {
146
+ throw new TelemetryOptionError(option, `an array of at most ${MAX_OPTION_ENTRIES} strings`);
147
+ }
148
+ const copy = [];
149
+ for (let index = 0; index < length; index++) {
150
+ const item = value[index];
151
+ if (typeof item !== "string") throw new TelemetryOptionError(option, "an array of strings");
152
+ copy.push(item);
153
+ }
154
+ return copy;
155
+ }
156
+ var OVERRIDE_PATH = "instrumentations.overrides[]";
157
+ function refuseProtoKey(key) {
158
+ if (key === "__proto__") throw new TelemetryOptionError(OVERRIDE_PATH, "free of a __proto__ key");
159
+ }
160
+ function settleOverrideEntry(entry) {
161
+ const settings = Object.entries(entry);
162
+ if (settings.length > MAX_OPTION_ENTRIES) {
163
+ throw new TelemetryOptionError(
164
+ OVERRIDE_PATH,
165
+ `an object of at most ${MAX_OPTION_ENTRIES} settings`
166
+ );
167
+ }
168
+ const copy = {};
169
+ for (const [key, setting] of settings) {
170
+ refuseProtoKey(key);
171
+ let settled = setting;
172
+ if (key === "enabled" || key === "disableLogSending") {
173
+ settled = requireBoolean(`${OVERRIDE_PATH}.${key}`, setting);
174
+ } else if (key === "redactedQueryParams") {
175
+ settled = settleStringList(`${OVERRIDE_PATH}.${key}`, setting);
176
+ } else if (key.endsWith("Hook")) {
177
+ settled = requireFunction(`${OVERRIDE_PATH}.<a hook>`, setting);
178
+ }
179
+ if (isGiven(settled)) copy[key] = settled;
180
+ }
181
+ return copy;
182
+ }
183
+ function settleOverrides(option, value) {
184
+ const map = requireObject(option, value);
185
+ if (map === void 0) return void 0;
186
+ const entries = Object.entries(map);
187
+ if (entries.length > MAX_OPTION_ENTRIES) {
188
+ throw new TelemetryOptionError(option, `an object of at most ${MAX_OPTION_ENTRIES} entries`);
189
+ }
190
+ const copy = {};
191
+ for (const [name, entry] of entries) {
192
+ refuseProtoKey(name);
193
+ const config = requireObject(option, entry);
194
+ if (config !== void 0) copy[name] = settleOverrideEntry(config);
195
+ }
196
+ return copy;
197
+ }
198
+
98
199
  // src/sdk/redaction.ts
99
200
  var REDACTED_QUERY_VALUE = "[redacted]";
100
201
  var URL_QUERY_ATTRIBUTE = "url.query";
@@ -206,13 +307,13 @@ function readEachOption(options) {
206
307
  env: options.env
207
308
  };
208
309
  }
209
- function definedEntries(config) {
210
- return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
211
- }
212
310
  function nonBlank(value) {
213
311
  const trimmed = value?.trim();
214
312
  return trimmed === "" ? void 0 : trimmed;
215
313
  }
314
+ function settleService(options) {
315
+ return { serviceName: options.serviceName, serviceVersion: options.serviceVersion };
316
+ }
216
317
  function buildResourceAttributes(options, env) {
217
318
  const attributes = {};
218
319
  const name = env.serviceName ?? nonBlank(options.serviceName);
@@ -221,11 +322,29 @@ function buildResourceAttributes(options, env) {
221
322
  if (version !== void 0) attributes["service.version"] = version;
222
323
  return attributes;
223
324
  }
325
+ function settleUnsafe(unsafe) {
326
+ const flags = requireObject("unsafe", unsafe);
327
+ const flag = (name) => requireBoolean(`unsafe.${name}`, flags?.[name]) === true;
328
+ return {
329
+ disableUrlRedaction: flag("disableUrlRedaction"),
330
+ disableRedisArgumentRedaction: flag("disableRedisArgumentRedaction"),
331
+ exportProcessCommandArgs: flag("exportProcessCommandArgs"),
332
+ exportHostId: flag("exportHostId")
333
+ };
334
+ }
335
+ function settleInstrumentations(instrumentations) {
336
+ const read = requireObject("instrumentations", instrumentations);
337
+ return {
338
+ fs: requireBoolean("instrumentations.fs", read?.fs),
339
+ sendLogs: requireBoolean("instrumentations.sendLogs", read?.sendLogs),
340
+ overrides: settleOverrides("instrumentations.overrides", read?.overrides)
341
+ };
342
+ }
224
343
  function buildInstrumentationConfig(options, signals) {
225
- const instrumentations = options.instrumentations ?? {};
344
+ const instrumentations = settleInstrumentations(options.instrumentations);
226
345
  const overrides = {};
227
346
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
228
- if (isPresent(config)) overrides[name] = definedEntries(config);
347
+ overrides[name] = config;
229
348
  }
230
349
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
231
350
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -248,8 +367,9 @@ function buildInstrumentationConfig(options, signals) {
248
367
  ...options.extraRedactedQueryParams ?? []
249
368
  ])
250
369
  };
251
- if (isPresent(options.ignoreIncomingRequest)) {
252
- merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
370
+ const ignoreIncomingRequest = options.ignoreIncomingRequest;
371
+ if (isPresent(ignoreIncomingRequest)) {
372
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = ignoreIncomingRequest;
253
373
  }
254
374
  if (redactRedis) {
255
375
  for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
@@ -497,6 +617,26 @@ function selectResourceDetectors(selection, detectors, keeps) {
497
617
  }
498
618
  return [...new Set(chosen)].map((name) => available[name]);
499
619
  }
620
+
621
+ // src/sdk/settle-options.ts
622
+ function settleOptions(options) {
623
+ const read = readEachOption(options);
624
+ const settled = {
625
+ enabled: requireBoolean("enabled", read.enabled),
626
+ serviceName: requireString("serviceName", read.serviceName),
627
+ serviceVersion: requireString("serviceVersion", read.serviceVersion),
628
+ ignoreIncomingRequest: requireFunction("ignoreIncomingRequest", read.ignoreIncomingRequest),
629
+ instrumentations: isGiven(read.instrumentations) ? settleInstrumentations(read.instrumentations) : void 0,
630
+ extraRedactedQueryParams: settleStringList(
631
+ "extraRedactedQueryParams",
632
+ read.extraRedactedQueryParams
633
+ ),
634
+ unsafe: isGiven(read.unsafe) ? settleUnsafe(read.unsafe) : void 0,
635
+ shutdownTimeoutMs: read.shutdownTimeoutMs,
636
+ env: requireObject("env", read.env)
637
+ };
638
+ return Object.fromEntries(Object.entries(settled).filter(([, value]) => isGiven(value)));
639
+ }
500
640
  var TRANSPORT = "@opentelemetry/winston-transport";
501
641
  var BUNDLE = "@opentelemetry/auto-instrumentations-node";
502
642
  var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
@@ -532,9 +672,10 @@ var DISABLED_HANDLE = {
532
672
  shutdown: () => Promise.resolve()
533
673
  };
534
674
  async function startTelemetry(options = {}) {
535
- const env = readTelemetryEnvironment(options.env ?? void 0);
536
- if (options.enabled === false || env.sdkDisabled) {
537
- if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
675
+ const settled = settleOptions(options);
676
+ const env = readTelemetryEnvironment(settled.env);
677
+ if (settled.enabled === false || env.sdkDisabled) {
678
+ if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(settled);
538
679
  return DISABLED_HANDLE;
539
680
  }
540
681
  let running = currentHandle();
@@ -543,12 +684,12 @@ async function startTelemetry(options = {}) {
543
684
  running = currentHandle();
544
685
  }
545
686
  if (running !== void 0) {
546
- warnAboutIgnoredOptions(options);
687
+ warnAboutIgnoredOptions(settled);
547
688
  return running;
548
689
  }
549
690
  const joined = pendingStart();
550
691
  if (joined !== void 0) {
551
- warnAboutIgnoredOptions(options);
692
+ warnAboutIgnoredOptions(settled);
552
693
  return joined;
553
694
  }
554
695
  if (hasStopped()) {
@@ -558,7 +699,7 @@ async function startTelemetry(options = {}) {
558
699
  });
559
700
  throw new Error(RESTART_MESSAGE);
560
701
  }
561
- const start = boot(options, env).finally(clearPendingStart);
702
+ const start = boot(settled, env).finally(clearPendingStart);
562
703
  setPendingStart(start);
563
704
  return start;
564
705
  }
@@ -572,13 +713,13 @@ async function loadPackages() {
572
713
  ]);
573
714
  return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
574
715
  }
575
- function buildSdk(packages, options, env) {
716
+ function buildSdk(packages, options, env, read) {
576
717
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
577
718
  const signals = planSignals(env);
578
- const unsafe = options.unsafe;
719
+ const { instrumentations, unsafe, service } = read;
579
720
  return new sdkNode.NodeSDK({
580
721
  ...signals.overrides,
581
- resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
722
+ resource: resources.resourceFromAttributes(buildResourceAttributes(service, env)),
582
723
  resourceDetectors: selectResourceDetectors(
583
724
  env.resourceDetectors,
584
725
  {
@@ -602,20 +743,34 @@ function buildSdk(packages, options, env) {
602
743
  })
603
744
  ],
604
745
  instrumentations: [
605
- autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
746
+ autoInstrumentations.getNodeAutoInstrumentations(
747
+ buildInstrumentationConfig(
748
+ {
749
+ instrumentations,
750
+ unsafe,
751
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
752
+ ignoreIncomingRequest: options.ignoreIncomingRequest
753
+ },
754
+ signals
755
+ )
756
+ )
606
757
  ]
607
758
  });
608
759
  }
609
760
  async function boot(options, env) {
610
- warnAboutUnsafeOptions(options);
611
- warnAboutMissingServiceName(options, env);
761
+ const unsafe = settleUnsafe(options.unsafe);
762
+ const instrumentations = settleInstrumentations(options.instrumentations);
763
+ const service = settleService(options);
764
+ warnAboutUnsafeOptions({ unsafe });
765
+ warnAboutMissingServiceName(service, env);
612
766
  warnAboutOversizedTimers(env);
613
767
  warnAboutSamplerName(readSamplerNearMiss());
614
768
  warnAboutSamplerRatio(readRatioSampler());
615
- warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
616
- const sdk = buildSdk(await loadPackages(), options, env);
769
+ warnAboutMissingWinstonTransport(instrumentations.sendLogs ?? planSignals(env).sendLogs);
770
+ const shutdownTimeoutMs = options.shutdownTimeoutMs;
771
+ const sdk = buildSdk(await loadPackages(), options, env, { instrumentations, unsafe, service });
617
772
  sdk.start();
618
- const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
773
+ const handle = createHandle(() => sdk.shutdown(), shutdownTimeoutMs);
619
774
  registerHandle(handle);
620
775
  return handle;
621
776
  }
@@ -166,6 +166,107 @@ async function shutdownTelemetry() {
166
166
  await currentHandle()?.shutdown();
167
167
  }
168
168
 
169
+ // src/sdk/option-kinds.ts
170
+ var MAX_OPTION_ENTRIES = 1e3;
171
+ var TelemetryOptionError = class extends Error {
172
+ /**
173
+ * @param option - The option that was refused.
174
+ * @param expected - What the option must be.
175
+ */
176
+ constructor(option, expected) {
177
+ super(`The ${option} option must be ${expected}, so the start was refused.`);
178
+ /** The stable code of this error. */
179
+ this.code = "BYMAX_TELEMETRY_OPTION_INVALID";
180
+ this.name = "TelemetryOptionError";
181
+ this.option = option;
182
+ }
183
+ };
184
+ function isGiven(value) {
185
+ return value !== void 0 && value !== null;
186
+ }
187
+ function requireBoolean(option, value) {
188
+ if (!isGiven(value)) return void 0;
189
+ if (typeof value !== "boolean") throw new TelemetryOptionError(option, "a boolean");
190
+ return value;
191
+ }
192
+ function requireString(option, value) {
193
+ if (!isGiven(value)) return void 0;
194
+ if (typeof value !== "string") throw new TelemetryOptionError(option, "a string");
195
+ return value;
196
+ }
197
+ function requireFunction(option, value) {
198
+ if (!isGiven(value)) return void 0;
199
+ if (typeof value !== "function") throw new TelemetryOptionError(option, "a function");
200
+ return value;
201
+ }
202
+ function requireObject(option, value) {
203
+ if (value === void 0 || value === null) return void 0;
204
+ if (typeof value !== "object" || Array.isArray(value)) {
205
+ throw new TelemetryOptionError(option, "an object");
206
+ }
207
+ return value;
208
+ }
209
+ function settleStringList(option, value) {
210
+ if (!isGiven(value)) return void 0;
211
+ if (!Array.isArray(value)) throw new TelemetryOptionError(option, "an array of strings");
212
+ const length = value.length;
213
+ if (typeof length !== "number" || !Number.isInteger(length) || length < 0) {
214
+ throw new TelemetryOptionError(option, "an array of strings");
215
+ }
216
+ if (length > MAX_OPTION_ENTRIES) {
217
+ throw new TelemetryOptionError(option, `an array of at most ${MAX_OPTION_ENTRIES} strings`);
218
+ }
219
+ const copy = [];
220
+ for (let index = 0; index < length; index++) {
221
+ const item = value[index];
222
+ if (typeof item !== "string") throw new TelemetryOptionError(option, "an array of strings");
223
+ copy.push(item);
224
+ }
225
+ return copy;
226
+ }
227
+ var OVERRIDE_PATH = "instrumentations.overrides[]";
228
+ function refuseProtoKey(key) {
229
+ if (key === "__proto__") throw new TelemetryOptionError(OVERRIDE_PATH, "free of a __proto__ key");
230
+ }
231
+ function settleOverrideEntry(entry) {
232
+ const settings = Object.entries(entry);
233
+ if (settings.length > MAX_OPTION_ENTRIES) {
234
+ throw new TelemetryOptionError(
235
+ OVERRIDE_PATH,
236
+ `an object of at most ${MAX_OPTION_ENTRIES} settings`
237
+ );
238
+ }
239
+ const copy = {};
240
+ for (const [key, setting] of settings) {
241
+ refuseProtoKey(key);
242
+ let settled = setting;
243
+ if (key === "enabled" || key === "disableLogSending") {
244
+ settled = requireBoolean(`${OVERRIDE_PATH}.${key}`, setting);
245
+ } else if (key === "redactedQueryParams") {
246
+ settled = settleStringList(`${OVERRIDE_PATH}.${key}`, setting);
247
+ } else if (key.endsWith("Hook")) {
248
+ settled = requireFunction(`${OVERRIDE_PATH}.<a hook>`, setting);
249
+ }
250
+ if (isGiven(settled)) copy[key] = settled;
251
+ }
252
+ return copy;
253
+ }
254
+ function settleOverrides(option, value) {
255
+ const map = requireObject(option, value);
256
+ if (map === void 0) return void 0;
257
+ const entries = Object.entries(map);
258
+ if (entries.length > MAX_OPTION_ENTRIES) {
259
+ throw new TelemetryOptionError(option, `an object of at most ${MAX_OPTION_ENTRIES} entries`);
260
+ }
261
+ const copy = {};
262
+ for (const [name, entry] of entries) {
263
+ refuseProtoKey(name);
264
+ const config = requireObject(option, entry);
265
+ if (config !== void 0) copy[name] = settleOverrideEntry(config);
266
+ }
267
+ return copy;
268
+ }
269
+
169
270
  // src/sdk/assembly.ts
170
271
  var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
171
272
  var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
@@ -206,13 +307,13 @@ function readEachOption(options) {
206
307
  env: options.env
207
308
  };
208
309
  }
209
- function definedEntries(config) {
210
- return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
211
- }
212
310
  function nonBlank(value) {
213
311
  const trimmed = value?.trim();
214
312
  return trimmed === "" ? void 0 : trimmed;
215
313
  }
314
+ function settleService(options) {
315
+ return { serviceName: options.serviceName, serviceVersion: options.serviceVersion };
316
+ }
216
317
  function buildResourceAttributes(options, env) {
217
318
  const attributes = {};
218
319
  const name = env.serviceName ?? nonBlank(options.serviceName);
@@ -221,11 +322,29 @@ function buildResourceAttributes(options, env) {
221
322
  if (version !== void 0) attributes["service.version"] = version;
222
323
  return attributes;
223
324
  }
325
+ function settleUnsafe(unsafe) {
326
+ const flags = requireObject("unsafe", unsafe);
327
+ const flag = (name) => requireBoolean(`unsafe.${name}`, flags?.[name]) === true;
328
+ return {
329
+ disableUrlRedaction: flag("disableUrlRedaction"),
330
+ disableRedisArgumentRedaction: flag("disableRedisArgumentRedaction"),
331
+ exportProcessCommandArgs: flag("exportProcessCommandArgs"),
332
+ exportHostId: flag("exportHostId")
333
+ };
334
+ }
335
+ function settleInstrumentations(instrumentations) {
336
+ const read = requireObject("instrumentations", instrumentations);
337
+ return {
338
+ fs: requireBoolean("instrumentations.fs", read?.fs),
339
+ sendLogs: requireBoolean("instrumentations.sendLogs", read?.sendLogs),
340
+ overrides: settleOverrides("instrumentations.overrides", read?.overrides)
341
+ };
342
+ }
224
343
  function buildInstrumentationConfig(options, signals) {
225
- const instrumentations = options.instrumentations ?? {};
344
+ const instrumentations = settleInstrumentations(options.instrumentations);
226
345
  const overrides = {};
227
346
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
228
- if (isPresent(config)) overrides[name] = definedEntries(config);
347
+ overrides[name] = config;
229
348
  }
230
349
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
231
350
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -248,8 +367,9 @@ function buildInstrumentationConfig(options, signals) {
248
367
  ...options.extraRedactedQueryParams ?? []
249
368
  ])
250
369
  };
251
- if (isPresent(options.ignoreIncomingRequest)) {
252
- merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
370
+ const ignoreIncomingRequest = options.ignoreIncomingRequest;
371
+ if (isPresent(ignoreIncomingRequest)) {
372
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = ignoreIncomingRequest;
253
373
  }
254
374
  if (redactRedis) {
255
375
  for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
@@ -506,6 +626,26 @@ function selectResourceDetectors(selection, detectors, keeps) {
506
626
  }
507
627
  return [...new Set(chosen)].map((name) => available[name]);
508
628
  }
629
+
630
+ // src/sdk/settle-options.ts
631
+ function settleOptions(options) {
632
+ const read = readEachOption(options);
633
+ const settled = {
634
+ enabled: requireBoolean("enabled", read.enabled),
635
+ serviceName: requireString("serviceName", read.serviceName),
636
+ serviceVersion: requireString("serviceVersion", read.serviceVersion),
637
+ ignoreIncomingRequest: requireFunction("ignoreIncomingRequest", read.ignoreIncomingRequest),
638
+ instrumentations: isGiven(read.instrumentations) ? settleInstrumentations(read.instrumentations) : void 0,
639
+ extraRedactedQueryParams: settleStringList(
640
+ "extraRedactedQueryParams",
641
+ read.extraRedactedQueryParams
642
+ ),
643
+ unsafe: isGiven(read.unsafe) ? settleUnsafe(read.unsafe) : void 0,
644
+ shutdownTimeoutMs: read.shutdownTimeoutMs,
645
+ env: requireObject("env", read.env)
646
+ };
647
+ return Object.fromEntries(Object.entries(settled).filter(([, value]) => isGiven(value)));
648
+ }
509
649
  var TRANSPORT = "@opentelemetry/winston-transport";
510
650
  var BUNDLE = "@opentelemetry/auto-instrumentations-node";
511
651
  var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
@@ -541,9 +681,10 @@ var DISABLED_HANDLE = {
541
681
  shutdown: () => Promise.resolve()
542
682
  };
543
683
  async function startTelemetry(options = {}) {
544
- const env = readTelemetryEnvironment(options.env ?? void 0);
545
- if (options.enabled === false || env.sdkDisabled) {
546
- if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
684
+ const settled = settleOptions(options);
685
+ const env = readTelemetryEnvironment(settled.env);
686
+ if (settled.enabled === false || env.sdkDisabled) {
687
+ if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(settled);
547
688
  return DISABLED_HANDLE;
548
689
  }
549
690
  let running = currentHandle();
@@ -552,12 +693,12 @@ async function startTelemetry(options = {}) {
552
693
  running = currentHandle();
553
694
  }
554
695
  if (running !== void 0) {
555
- warnAboutIgnoredOptions(options);
696
+ warnAboutIgnoredOptions(settled);
556
697
  return running;
557
698
  }
558
699
  const joined = pendingStart();
559
700
  if (joined !== void 0) {
560
- warnAboutIgnoredOptions(options);
701
+ warnAboutIgnoredOptions(settled);
561
702
  return joined;
562
703
  }
563
704
  if (hasStopped()) {
@@ -567,7 +708,7 @@ async function startTelemetry(options = {}) {
567
708
  });
568
709
  throw new Error(RESTART_MESSAGE);
569
710
  }
570
- const start = boot(options, env).finally(clearPendingStart);
711
+ const start = boot(settled, env).finally(clearPendingStart);
571
712
  setPendingStart(start);
572
713
  return start;
573
714
  }
@@ -581,13 +722,13 @@ async function loadPackages() {
581
722
  ]);
582
723
  return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
583
724
  }
584
- function buildSdk(packages, options, env) {
725
+ function buildSdk(packages, options, env, read) {
585
726
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
586
727
  const signals = planSignals(env);
587
- const unsafe = options.unsafe;
728
+ const { instrumentations, unsafe, service } = read;
588
729
  return new sdkNode.NodeSDK({
589
730
  ...signals.overrides,
590
- resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
731
+ resource: resources.resourceFromAttributes(buildResourceAttributes(service, env)),
591
732
  resourceDetectors: selectResourceDetectors(
592
733
  env.resourceDetectors,
593
734
  {
@@ -611,20 +752,34 @@ function buildSdk(packages, options, env) {
611
752
  })
612
753
  ],
613
754
  instrumentations: [
614
- autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
755
+ autoInstrumentations.getNodeAutoInstrumentations(
756
+ buildInstrumentationConfig(
757
+ {
758
+ instrumentations,
759
+ unsafe,
760
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
761
+ ignoreIncomingRequest: options.ignoreIncomingRequest
762
+ },
763
+ signals
764
+ )
765
+ )
615
766
  ]
616
767
  });
617
768
  }
618
769
  async function boot(options, env) {
619
- warnAboutUnsafeOptions(options);
620
- warnAboutMissingServiceName(options, env);
770
+ const unsafe = settleUnsafe(options.unsafe);
771
+ const instrumentations = settleInstrumentations(options.instrumentations);
772
+ const service = settleService(options);
773
+ warnAboutUnsafeOptions({ unsafe });
774
+ warnAboutMissingServiceName(service, env);
621
775
  warnAboutOversizedTimers(env);
622
776
  warnAboutSamplerName(readSamplerNearMiss());
623
777
  warnAboutSamplerRatio(readRatioSampler());
624
- warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
625
- const sdk = buildSdk(await loadPackages(), options, env);
778
+ warnAboutMissingWinstonTransport(instrumentations.sendLogs ?? planSignals(env).sendLogs);
779
+ const shutdownTimeoutMs = options.shutdownTimeoutMs;
780
+ const sdk = buildSdk(await loadPackages(), options, env, { instrumentations, unsafe, service });
626
781
  sdk.start();
627
- const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
782
+ const handle = createHandle(() => sdk.shutdown(), shutdownTimeoutMs);
628
783
  registerHandle(handle);
629
784
  return handle;
630
785
  }
@@ -164,6 +164,107 @@ async function shutdownTelemetry() {
164
164
  await currentHandle()?.shutdown();
165
165
  }
166
166
 
167
+ // src/sdk/option-kinds.ts
168
+ var MAX_OPTION_ENTRIES = 1e3;
169
+ var TelemetryOptionError = class extends Error {
170
+ /**
171
+ * @param option - The option that was refused.
172
+ * @param expected - What the option must be.
173
+ */
174
+ constructor(option, expected) {
175
+ super(`The ${option} option must be ${expected}, so the start was refused.`);
176
+ /** The stable code of this error. */
177
+ this.code = "BYMAX_TELEMETRY_OPTION_INVALID";
178
+ this.name = "TelemetryOptionError";
179
+ this.option = option;
180
+ }
181
+ };
182
+ function isGiven(value) {
183
+ return value !== void 0 && value !== null;
184
+ }
185
+ function requireBoolean(option, value) {
186
+ if (!isGiven(value)) return void 0;
187
+ if (typeof value !== "boolean") throw new TelemetryOptionError(option, "a boolean");
188
+ return value;
189
+ }
190
+ function requireString(option, value) {
191
+ if (!isGiven(value)) return void 0;
192
+ if (typeof value !== "string") throw new TelemetryOptionError(option, "a string");
193
+ return value;
194
+ }
195
+ function requireFunction(option, value) {
196
+ if (!isGiven(value)) return void 0;
197
+ if (typeof value !== "function") throw new TelemetryOptionError(option, "a function");
198
+ return value;
199
+ }
200
+ function requireObject(option, value) {
201
+ if (value === void 0 || value === null) return void 0;
202
+ if (typeof value !== "object" || Array.isArray(value)) {
203
+ throw new TelemetryOptionError(option, "an object");
204
+ }
205
+ return value;
206
+ }
207
+ function settleStringList(option, value) {
208
+ if (!isGiven(value)) return void 0;
209
+ if (!Array.isArray(value)) throw new TelemetryOptionError(option, "an array of strings");
210
+ const length = value.length;
211
+ if (typeof length !== "number" || !Number.isInteger(length) || length < 0) {
212
+ throw new TelemetryOptionError(option, "an array of strings");
213
+ }
214
+ if (length > MAX_OPTION_ENTRIES) {
215
+ throw new TelemetryOptionError(option, `an array of at most ${MAX_OPTION_ENTRIES} strings`);
216
+ }
217
+ const copy = [];
218
+ for (let index = 0; index < length; index++) {
219
+ const item = value[index];
220
+ if (typeof item !== "string") throw new TelemetryOptionError(option, "an array of strings");
221
+ copy.push(item);
222
+ }
223
+ return copy;
224
+ }
225
+ var OVERRIDE_PATH = "instrumentations.overrides[]";
226
+ function refuseProtoKey(key) {
227
+ if (key === "__proto__") throw new TelemetryOptionError(OVERRIDE_PATH, "free of a __proto__ key");
228
+ }
229
+ function settleOverrideEntry(entry) {
230
+ const settings = Object.entries(entry);
231
+ if (settings.length > MAX_OPTION_ENTRIES) {
232
+ throw new TelemetryOptionError(
233
+ OVERRIDE_PATH,
234
+ `an object of at most ${MAX_OPTION_ENTRIES} settings`
235
+ );
236
+ }
237
+ const copy = {};
238
+ for (const [key, setting] of settings) {
239
+ refuseProtoKey(key);
240
+ let settled = setting;
241
+ if (key === "enabled" || key === "disableLogSending") {
242
+ settled = requireBoolean(`${OVERRIDE_PATH}.${key}`, setting);
243
+ } else if (key === "redactedQueryParams") {
244
+ settled = settleStringList(`${OVERRIDE_PATH}.${key}`, setting);
245
+ } else if (key.endsWith("Hook")) {
246
+ settled = requireFunction(`${OVERRIDE_PATH}.<a hook>`, setting);
247
+ }
248
+ if (isGiven(settled)) copy[key] = settled;
249
+ }
250
+ return copy;
251
+ }
252
+ function settleOverrides(option, value) {
253
+ const map = requireObject(option, value);
254
+ if (map === void 0) return void 0;
255
+ const entries = Object.entries(map);
256
+ if (entries.length > MAX_OPTION_ENTRIES) {
257
+ throw new TelemetryOptionError(option, `an object of at most ${MAX_OPTION_ENTRIES} entries`);
258
+ }
259
+ const copy = {};
260
+ for (const [name, entry] of entries) {
261
+ refuseProtoKey(name);
262
+ const config = requireObject(option, entry);
263
+ if (config !== void 0) copy[name] = settleOverrideEntry(config);
264
+ }
265
+ return copy;
266
+ }
267
+
167
268
  // src/sdk/assembly.ts
168
269
  var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
169
270
  var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
@@ -204,13 +305,13 @@ function readEachOption(options) {
204
305
  env: options.env
205
306
  };
206
307
  }
207
- function definedEntries(config) {
208
- return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
209
- }
210
308
  function nonBlank(value) {
211
309
  const trimmed = value?.trim();
212
310
  return trimmed === "" ? void 0 : trimmed;
213
311
  }
312
+ function settleService(options) {
313
+ return { serviceName: options.serviceName, serviceVersion: options.serviceVersion };
314
+ }
214
315
  function buildResourceAttributes(options, env) {
215
316
  const attributes = {};
216
317
  const name = env.serviceName ?? nonBlank(options.serviceName);
@@ -219,11 +320,29 @@ function buildResourceAttributes(options, env) {
219
320
  if (version !== void 0) attributes["service.version"] = version;
220
321
  return attributes;
221
322
  }
323
+ function settleUnsafe(unsafe) {
324
+ const flags = requireObject("unsafe", unsafe);
325
+ const flag = (name) => requireBoolean(`unsafe.${name}`, flags?.[name]) === true;
326
+ return {
327
+ disableUrlRedaction: flag("disableUrlRedaction"),
328
+ disableRedisArgumentRedaction: flag("disableRedisArgumentRedaction"),
329
+ exportProcessCommandArgs: flag("exportProcessCommandArgs"),
330
+ exportHostId: flag("exportHostId")
331
+ };
332
+ }
333
+ function settleInstrumentations(instrumentations) {
334
+ const read = requireObject("instrumentations", instrumentations);
335
+ return {
336
+ fs: requireBoolean("instrumentations.fs", read?.fs),
337
+ sendLogs: requireBoolean("instrumentations.sendLogs", read?.sendLogs),
338
+ overrides: settleOverrides("instrumentations.overrides", read?.overrides)
339
+ };
340
+ }
222
341
  function buildInstrumentationConfig(options, signals) {
223
- const instrumentations = options.instrumentations ?? {};
342
+ const instrumentations = settleInstrumentations(options.instrumentations);
224
343
  const overrides = {};
225
344
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
226
- if (isPresent(config)) overrides[name] = definedEntries(config);
345
+ overrides[name] = config;
227
346
  }
228
347
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
229
348
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -246,8 +365,9 @@ function buildInstrumentationConfig(options, signals) {
246
365
  ...options.extraRedactedQueryParams ?? []
247
366
  ])
248
367
  };
249
- if (isPresent(options.ignoreIncomingRequest)) {
250
- merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
368
+ const ignoreIncomingRequest = options.ignoreIncomingRequest;
369
+ if (isPresent(ignoreIncomingRequest)) {
370
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = ignoreIncomingRequest;
251
371
  }
252
372
  if (redactRedis) {
253
373
  for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
@@ -504,6 +624,26 @@ function selectResourceDetectors(selection, detectors, keeps) {
504
624
  }
505
625
  return [...new Set(chosen)].map((name) => available[name]);
506
626
  }
627
+
628
+ // src/sdk/settle-options.ts
629
+ function settleOptions(options) {
630
+ const read = readEachOption(options);
631
+ const settled = {
632
+ enabled: requireBoolean("enabled", read.enabled),
633
+ serviceName: requireString("serviceName", read.serviceName),
634
+ serviceVersion: requireString("serviceVersion", read.serviceVersion),
635
+ ignoreIncomingRequest: requireFunction("ignoreIncomingRequest", read.ignoreIncomingRequest),
636
+ instrumentations: isGiven(read.instrumentations) ? settleInstrumentations(read.instrumentations) : void 0,
637
+ extraRedactedQueryParams: settleStringList(
638
+ "extraRedactedQueryParams",
639
+ read.extraRedactedQueryParams
640
+ ),
641
+ unsafe: isGiven(read.unsafe) ? settleUnsafe(read.unsafe) : void 0,
642
+ shutdownTimeoutMs: read.shutdownTimeoutMs,
643
+ env: requireObject("env", read.env)
644
+ };
645
+ return Object.fromEntries(Object.entries(settled).filter(([, value]) => isGiven(value)));
646
+ }
507
647
  var TRANSPORT = "@opentelemetry/winston-transport";
508
648
  var BUNDLE = "@opentelemetry/auto-instrumentations-node";
509
649
  var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
@@ -539,9 +679,10 @@ var DISABLED_HANDLE = {
539
679
  shutdown: () => Promise.resolve()
540
680
  };
541
681
  async function startTelemetry(options = {}) {
542
- const env = readTelemetryEnvironment(options.env ?? void 0);
543
- if (options.enabled === false || env.sdkDisabled) {
544
- if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
682
+ const settled = settleOptions(options);
683
+ const env = readTelemetryEnvironment(settled.env);
684
+ if (settled.enabled === false || env.sdkDisabled) {
685
+ if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(settled);
545
686
  return DISABLED_HANDLE;
546
687
  }
547
688
  let running = currentHandle();
@@ -550,12 +691,12 @@ async function startTelemetry(options = {}) {
550
691
  running = currentHandle();
551
692
  }
552
693
  if (running !== void 0) {
553
- warnAboutIgnoredOptions(options);
694
+ warnAboutIgnoredOptions(settled);
554
695
  return running;
555
696
  }
556
697
  const joined = pendingStart();
557
698
  if (joined !== void 0) {
558
- warnAboutIgnoredOptions(options);
699
+ warnAboutIgnoredOptions(settled);
559
700
  return joined;
560
701
  }
561
702
  if (hasStopped()) {
@@ -565,7 +706,7 @@ async function startTelemetry(options = {}) {
565
706
  });
566
707
  throw new Error(RESTART_MESSAGE);
567
708
  }
568
- const start = boot(options, env).finally(clearPendingStart);
709
+ const start = boot(settled, env).finally(clearPendingStart);
569
710
  setPendingStart(start);
570
711
  return start;
571
712
  }
@@ -579,13 +720,13 @@ async function loadPackages() {
579
720
  ]);
580
721
  return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
581
722
  }
582
- function buildSdk(packages, options, env) {
723
+ function buildSdk(packages, options, env, read) {
583
724
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
584
725
  const signals = planSignals(env);
585
- const unsafe = options.unsafe;
726
+ const { instrumentations, unsafe, service } = read;
586
727
  return new sdkNode.NodeSDK({
587
728
  ...signals.overrides,
588
- resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
729
+ resource: resources.resourceFromAttributes(buildResourceAttributes(service, env)),
589
730
  resourceDetectors: selectResourceDetectors(
590
731
  env.resourceDetectors,
591
732
  {
@@ -609,20 +750,34 @@ function buildSdk(packages, options, env) {
609
750
  })
610
751
  ],
611
752
  instrumentations: [
612
- autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
753
+ autoInstrumentations.getNodeAutoInstrumentations(
754
+ buildInstrumentationConfig(
755
+ {
756
+ instrumentations,
757
+ unsafe,
758
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
759
+ ignoreIncomingRequest: options.ignoreIncomingRequest
760
+ },
761
+ signals
762
+ )
763
+ )
613
764
  ]
614
765
  });
615
766
  }
616
767
  async function boot(options, env) {
617
- warnAboutUnsafeOptions(options);
618
- warnAboutMissingServiceName(options, env);
768
+ const unsafe = settleUnsafe(options.unsafe);
769
+ const instrumentations = settleInstrumentations(options.instrumentations);
770
+ const service = settleService(options);
771
+ warnAboutUnsafeOptions({ unsafe });
772
+ warnAboutMissingServiceName(service, env);
619
773
  warnAboutOversizedTimers(env);
620
774
  warnAboutSamplerName(readSamplerNearMiss());
621
775
  warnAboutSamplerRatio(readRatioSampler());
622
- warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
623
- const sdk = buildSdk(await loadPackages(), options, env);
776
+ warnAboutMissingWinstonTransport(instrumentations.sendLogs ?? planSignals(env).sendLogs);
777
+ const shutdownTimeoutMs = options.shutdownTimeoutMs;
778
+ const sdk = buildSdk(await loadPackages(), options, env, { instrumentations, unsafe, service });
624
779
  sdk.start();
625
- const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
780
+ const handle = createHandle(() => sdk.shutdown(), shutdownTimeoutMs);
626
781
  registerHandle(handle);
627
782
  return handle;
628
783
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-telemetry",
3
- "version": "1.0.8",
3
+ "version": "1.0.10",
4
4
  "description": "OpenTelemetry tracing for NestJS 11 and plain Node: starts the SDK before your app loads, redacts secrets from spans by default, and flushes on shutdown. Optional peers, zero cost when disabled.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",