@c9up/spectrum 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +30 -7
  2. package/dist/Logger.d.ts +14 -4
  3. package/dist/Logger.d.ts.map +1 -1
  4. package/dist/Logger.js +83 -49
  5. package/dist/Logger.js.map +1 -1
  6. package/dist/LoggerManager.d.ts.map +1 -1
  7. package/dist/LoggerManager.js +7 -1
  8. package/dist/LoggerManager.js.map +1 -1
  9. package/dist/RustLogBridge.d.ts.map +1 -1
  10. package/dist/RustLogBridge.js +76 -16
  11. package/dist/RustLogBridge.js.map +1 -1
  12. package/dist/SpectrumProvider.d.ts +1 -0
  13. package/dist/SpectrumProvider.d.ts.map +1 -1
  14. package/dist/SpectrumProvider.js +30 -21
  15. package/dist/SpectrumProvider.js.map +1 -1
  16. package/dist/augmentations.d.ts +29 -0
  17. package/dist/augmentations.d.ts.map +1 -0
  18. package/dist/augmentations.js +18 -0
  19. package/dist/augmentations.js.map +1 -0
  20. package/dist/channels/FileChannel.d.ts.map +1 -1
  21. package/dist/channels/FileChannel.js +26 -6
  22. package/dist/channels/FileChannel.js.map +1 -1
  23. package/dist/configure.d.ts.map +1 -1
  24. package/dist/configure.js +19 -7
  25. package/dist/configure.js.map +1 -1
  26. package/dist/index.d.ts +2 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +2 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/redact.d.ts +29 -0
  31. package/dist/redact.d.ts.map +1 -0
  32. package/dist/redact.js +90 -0
  33. package/dist/redact.js.map +1 -0
  34. package/dist/targets.d.ts +6 -1
  35. package/dist/targets.d.ts.map +1 -1
  36. package/dist/targets.js +59 -5
  37. package/dist/targets.js.map +1 -1
  38. package/dist/types.d.ts +28 -1
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/types.js +33 -6
  41. package/dist/types.js.map +1 -1
  42. package/package.json +4 -2
  43. package/src/Logger.ts +113 -51
  44. package/src/LoggerManager.ts +9 -1
  45. package/src/RustLogBridge.ts +95 -20
  46. package/src/SpectrumProvider.ts +34 -25
  47. package/src/augmentations.ts +32 -0
  48. package/src/channels/FileChannel.ts +30 -6
  49. package/src/configure.ts +19 -7
  50. package/src/index.ts +4 -0
  51. package/src/redact.ts +100 -0
  52. package/src/targets.ts +78 -12
  53. package/src/types.ts +50 -7
package/dist/types.d.ts CHANGED
@@ -6,11 +6,30 @@ import type { TransportTargetOptions } from "./targets.js";
6
6
  export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
7
7
  /** A configured level, including pino's `silent` (disables all output). */
8
8
  export type LogLevelWithSilent = LogLevel | "silent";
9
+ /**
10
+ * The numeric value of each level, on pino's scale.
11
+ *
12
+ * Only the ORDER matters to the comparisons here, but the numbers are what
13
+ * `logger.levels` and `logger.levelNumber` hand back, and those are read
14
+ * against the ecosystem's values: an `info` line is 30 everywhere upstream
15
+ * reaches, so it is 30 here.
16
+ */
9
17
  export declare const LOG_LEVEL_ORDER: Record<LogLevel, number>;
10
18
  /** Threshold for the `silent` level — nothing is ever above it. */
11
19
  export declare const SILENT_THRESHOLD: number;
12
20
  /** Numeric threshold for a configured level (`silent` → +Infinity). */
13
21
  export declare function levelThreshold(level: LogLevelWithSilent): number;
22
+ /** Whether a value is a level a config may name. */
23
+ export declare function isLogLevelWithSilent(value: unknown): value is LogLevelWithSilent;
24
+ /**
25
+ * Narrow an untyped level — `process.env.LOG_LEVEL`, a CLI flag — to one the
26
+ * config can name, falling back to `info`.
27
+ *
28
+ * Without it a config file has to assert the env string into the union, and an
29
+ * assertion is the wrong tool for a value that comes from outside the program:
30
+ * it claims to know what it cannot. This checks.
31
+ */
32
+ export declare function logLevel(raw: unknown, fallback?: LogLevelWithSilent): LogLevelWithSilent;
14
33
  export interface LogEntry {
15
34
  level: LogLevel;
16
35
  message: string;
@@ -46,7 +65,15 @@ export interface RedactOptions {
46
65
  * / pino, with spectrum divergences called out inline.
47
66
  */
48
67
  export interface LogConfig {
49
- /** Turn the logger off while keeping its API callable (no-op). Default: true. */
68
+ /**
69
+ * Turn the logger off while keeping its API callable (no-op). Default: true.
70
+ *
71
+ * Named deviation: upstream reads this as `!!config.enabled`, so a config
72
+ * that never writes it has a logger that silently logs nothing. That only
73
+ * works because upstream's own generated config always writes `enabled:
74
+ * true` — a default that turns the feature off is a trap for every config
75
+ * written by hand.
76
+ */
50
77
  enabled?: boolean;
51
78
  /** Optional logger name (assigned by the manager when omitted). */
52
79
  name?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAC3D;;;GAGG;AAEH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;AAE/E,2EAA2E;AAC3E,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAErD,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,CAOpD,CAAC;AAEF,mEAAmE;AACnE,eAAO,MAAM,gBAAgB,QAA2B,CAAC;AAEzD,uEAAuE;AACvE,wBAAgB,cAAc,CAAC,KAAK,EAAE,kBAAkB,GAAG,MAAM,CAEhE;AAED,MAAM,WAAW,QAAQ;IACxB,KAAK,EAAE,QAAQ,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B;;;OAGG;IACH,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACvB;AAED,YAAY,EAAE,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AAa,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;AAExD,+CAA+C;AAC/C,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,mEAAmE;IACnE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAC3B,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,UAAU,EAAE,CAAC;IACxB;;;;;OAKG;IACH,SAAS,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,SAAS,sBAAsB,EAAE,CAAA;KAAE,CAAC;IAC5D,wDAAwD;IACxD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;IAC7C,uEAAuE;IACvE,MAAM,CAAC,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC;IAClC,oEAAoE;IACpE,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CAC5C;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CACnC;AAWD,mFAAmF;AACnF,wBAAgB,cAAc,CAAC,KAAK,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMvE"}
package/dist/types.js CHANGED
@@ -1,10 +1,18 @@
1
+ /**
2
+ * The numeric value of each level, on pino's scale.
3
+ *
4
+ * Only the ORDER matters to the comparisons here, but the numbers are what
5
+ * `logger.levels` and `logger.levelNumber` hand back, and those are read
6
+ * against the ecosystem's values: an `info` line is 30 everywhere upstream
7
+ * reaches, so it is 30 here.
8
+ */
1
9
  export const LOG_LEVEL_ORDER = {
2
- trace: 0,
3
- debug: 1,
4
- info: 2,
5
- warn: 3,
6
- error: 4,
7
- fatal: 5,
10
+ trace: 10,
11
+ debug: 20,
12
+ info: 30,
13
+ warn: 40,
14
+ error: 50,
15
+ fatal: 60,
8
16
  };
9
17
  /** Threshold for the `silent` level — nothing is ever above it. */
10
18
  export const SILENT_THRESHOLD = Number.POSITIVE_INFINITY;
@@ -12,6 +20,25 @@ export const SILENT_THRESHOLD = Number.POSITIVE_INFINITY;
12
20
  export function levelThreshold(level) {
13
21
  return level === "silent" ? SILENT_THRESHOLD : LOG_LEVEL_ORDER[level];
14
22
  }
23
+ const CONFIGURED_LEVELS = new Set([
24
+ ...Object.keys(LOG_LEVEL_ORDER),
25
+ "silent",
26
+ ]);
27
+ /** Whether a value is a level a config may name. */
28
+ export function isLogLevelWithSilent(value) {
29
+ return typeof value === "string" && CONFIGURED_LEVELS.has(value);
30
+ }
31
+ /**
32
+ * Narrow an untyped level — `process.env.LOG_LEVEL`, a CLI flag — to one the
33
+ * config can name, falling back to `info`.
34
+ *
35
+ * Without it a config file has to assert the env string into the union, and an
36
+ * assertion is the wrong tool for a value that comes from outside the program:
37
+ * it claims to know what it cannot. This checks.
38
+ */
39
+ export function logLevel(raw, fallback = "info") {
40
+ return isLogLevelWithSilent(raw) ? raw : fallback;
41
+ }
15
42
  const RESERVED_ENTRY_KEYS = new Set([
16
43
  "level",
17
44
  "message",
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,eAAe,GAA6B;IACxD,KAAK,EAAE,CAAC;IACR,KAAK,EAAE,CAAC;IACR,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;IACR,KAAK,EAAE,CAAC;CACR,CAAC;AAEF,mEAAmE;AACnE,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,C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MAAM,CAAC,IAAI,CAAC,eAAe,CAAC;IAC/B,QAAQ;CACR,CAAC,CAAC;AAEH,oDAAoD;AACpD,MAAM,UAAU,oBAAoB,CACnC,KAAc;IAEd,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAClE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CACvB,GAAY,EACZ,WAA+B,MAAM;IAErC,OAAO,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;AACnD,CAAC;AAiFD,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAS;IAC3C,OAAO;IACP,SAAS;IACT,QAAQ;IACR,eAAe;IACf,WAAW;IACX,MAAM;CACN,CAAC,CAAC;AAEH,mFAAmF;AACnF,MAAM,UAAU,cAAc,CAAC,KAAe;IAC7C,MAAM,MAAM,GAA4B,EAAE,CAAC;IAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACtC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c9up/spectrum",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "Spectrum — structured logging for the Ream framework",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,7 +33,9 @@
33
33
  },
34
34
  "devDependencies": {
35
35
  "@biomejs/biome": "^2.4.10",
36
+ "@c9up/ream": "^0.2.0",
36
37
  "@types/node": "^22.19.15",
38
+ "@vitest/coverage-v8": "^4.1.2",
37
39
  "typescript": "^6.0.2",
38
40
  "vitest": "^4.1.2"
39
41
  },
@@ -62,7 +64,7 @@
62
64
  "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
63
65
  "build": "tsc -p tsconfig.build.json",
64
66
  "test": "vitest run",
65
- "lint": "biome check src/",
67
+ "lint": "biome check src/ tests/",
66
68
  "test:coverage": "vitest run --coverage",
67
69
  "typecheck": "tsc --noEmit"
68
70
  }
package/src/Logger.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { format } from "node:util";
17
+ import { parseRedactPath, redactPath } from "./redact.js";
17
18
  import { sanitizeLogValue } from "./sanitize.js";
18
19
  import { channelsFromTargets } from "./targets.js";
19
20
  import type {
@@ -44,15 +45,51 @@ function isMergeableObject(value: unknown): value is Record<string, unknown> {
44
45
  );
45
46
  }
46
47
 
48
+ /** How far down a `cause` chain to follow before calling it a cycle. */
49
+ const MAX_CAUSE_DEPTH = 8;
50
+
47
51
  /**
48
- * Serialize an Error into a plain `{ name, message, stack }` — the pino `err`
49
- * serializer parity. Non-Error values pass through untouched.
52
+ * Serialize an Error the way pino's `err` serializer does. Non-Error values
53
+ * pass through untouched.
54
+ *
55
+ * `{ name, message, stack }` threw away everything the error was carrying.
56
+ * `err.code` is usually the one field a log search is keyed on, and the `cause`
57
+ * of a wrapped error is the half that says what actually failed — both were
58
+ * dropped, silently, by a serializer whose job is to keep them.
50
59
  */
51
- function serializeError(value: unknown): unknown {
52
- if (value instanceof Error) {
53
- return { name: value.name, message: value.message, stack: value.stack };
60
+ function serializeError(value: unknown, depth = 0): unknown {
61
+ if (!(value instanceof Error)) return value;
62
+
63
+ // Own ENUMERABLE properties only, which on an Error means the ones it was
64
+ // given: `message`, `stack` and `name` are not among them.
65
+ const out: Record<string, unknown> = { ...value };
66
+ for (const [key, nested] of Object.entries(out)) {
67
+ if (nested instanceof Error && depth < MAX_CAUSE_DEPTH) {
68
+ out[key] = serializeError(nested, depth + 1);
69
+ }
70
+ }
71
+
72
+ // Upstream reads the constructor rather than `name`, so a subclass that
73
+ // never assigns `this.name` is still reported as itself, and it names the
74
+ // field `type` — which is what an Adonis log pipeline reads.
75
+ out.type =
76
+ typeof value.constructor === "function"
77
+ ? value.constructor.name
78
+ : value.name;
79
+ out.message = value.message;
80
+ out.stack = value.stack;
81
+ if (value instanceof AggregateError && Array.isArray(value.errors)) {
82
+ out.aggregateErrors = value.errors.map((each) =>
83
+ depth < MAX_CAUSE_DEPTH ? serializeError(each, depth + 1) : String(each),
84
+ );
85
+ }
86
+ if (value.cause !== undefined) {
87
+ out.cause =
88
+ depth < MAX_CAUSE_DEPTH
89
+ ? serializeError(value.cause, depth + 1)
90
+ : "[cause chain too deep]";
54
91
  }
55
- return value;
92
+ return out;
56
93
  }
57
94
 
58
95
  const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
@@ -60,36 +97,22 @@ const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
60
97
  error: serializeError,
61
98
  };
62
99
 
63
- /**
64
- * Copy-on-write redaction of a single dot-path. Never mutates the input; only
65
- * the objects along the path are shallow-copied.
66
- */
67
- function redactPath(
68
- obj: Record<string, unknown>,
69
- path: string,
70
- censor: string,
71
- ): Record<string, unknown> {
72
- const dot = path.indexOf(".");
73
- const head = dot === -1 ? path : path.slice(0, dot);
74
- if (!(head in obj)) return obj;
75
-
76
- const copy: Record<string, unknown> = { ...obj };
77
- if (dot === -1) {
78
- copy[head] = censor;
79
- } else {
80
- const child = copy[head];
81
- if (isMergeableObject(child)) {
82
- copy[head] = redactPath(child, path.slice(dot + 1), censor);
83
- }
84
- }
85
- return copy;
86
- }
87
-
88
100
  export class Logger {
89
101
  #config: LogConfig;
90
102
  #module: string;
91
103
  #correlationId?: string;
92
104
  #bindings: Record<string, unknown>;
105
+ /**
106
+ * This instance's level, when it has been set on the instance.
107
+ *
108
+ * The config object is shared by reference with the parent, every sibling
109
+ * child and the manager, so writing the level into it made
110
+ * `child.level = 'debug'` turn on debug for the whole application. pino
111
+ * keeps the level on the logger; so does this.
112
+ */
113
+ #level?: LogLevelWithSilent;
114
+ /** `config.redact` compiled once, as pino compiles its redactor once. */
115
+ readonly #redactPaths: string[][];
93
116
 
94
117
  constructor(
95
118
  config: LogConfig,
@@ -103,11 +126,21 @@ export class Logger {
103
126
  // specific statement of intent.
104
127
  this.#config =
105
128
  config.channels === undefined && config.transport?.targets !== undefined
106
- ? { ...config, channels: channelsFromTargets(config.transport.targets) }
129
+ ? {
130
+ ...config,
131
+ channels: channelsFromTargets(
132
+ config.transport.targets,
133
+ config.level,
134
+ ),
135
+ }
107
136
  : config;
108
137
  this.#module = module;
109
138
  this.#correlationId = correlationId;
110
139
  this.#bindings = bindings;
140
+ const redact = this.#config.redact;
141
+ const paths =
142
+ redact === undefined ? [] : Array.isArray(redact) ? redact : redact.paths;
143
+ this.#redactPaths = paths.map(parseRedactPath);
111
144
  }
112
145
 
113
146
  /** Whether the logger is enabled. When false every log call is a no-op. */
@@ -115,13 +148,13 @@ export class Logger {
115
148
  return this.#config.enabled !== false;
116
149
  }
117
150
 
118
- /** The configured level for this logger. */
151
+ /** The level this logger is at. */
119
152
  get level(): LogLevelWithSilent {
120
- return this.#config.level ?? "info";
153
+ return this.#level ?? this.#config.level ?? "info";
121
154
  }
122
155
 
123
156
  set level(level: LogLevelWithSilent) {
124
- this.#config.level = level;
157
+ this.#level = level;
125
158
  }
126
159
 
127
160
  /** Numeric value of the current level (`silent` → +Infinity). */
@@ -150,9 +183,22 @@ export class Logger {
150
183
  /**
151
184
  * Run `callback` only when `level` is enabled — useful to guard expensive
152
185
  * log-data computation.
186
+ *
187
+ * An async callback's promise is HANDED BACK, as upstream hands it back.
188
+ * Swallowing it turned a rejection inside the guarded block into an
189
+ * unhandled rejection with no caller able to await it.
153
190
  */
154
- ifLevelEnabled(level: LogLevel, callback: (logger: this) => void): void {
155
- if (this.isLevelEnabled(level)) callback(this);
191
+ ifLevelEnabled(
192
+ level: LogLevel,
193
+ callback: (logger: this) => Promise<void>,
194
+ ): Promise<void> | undefined;
195
+ ifLevelEnabled(level: LogLevel, callback: (logger: this) => void): void;
196
+ ifLevelEnabled(
197
+ level: LogLevel,
198
+ callback: (logger: this) => unknown,
199
+ ): unknown {
200
+ if (this.isLevelEnabled(level)) return callback(this);
201
+ return undefined;
156
202
  }
157
203
 
158
204
  /**
@@ -166,15 +212,21 @@ export class Logger {
166
212
  const nextModule = typeof module === "string" ? module : this.#module;
167
213
  const nextCorrelation =
168
214
  typeof correlationId === "string" ? correlationId : this.#correlationId;
169
- return new Logger(this.#config, nextModule, nextCorrelation, {
215
+ const child = new Logger(this.#config, nextModule, nextCorrelation, {
170
216
  ...this.#bindings,
171
217
  ...rest,
172
218
  });
219
+ // A child starts where its parent stands now, and moves on its own
220
+ // afterwards — pino's semantics, and the reason the level cannot live
221
+ // in the config the two of them share.
222
+ if (this.#level !== undefined) child.level = this.#level;
223
+ return child;
173
224
  }
174
225
 
175
- /** Current bindings (child bindings + module/correlationId conventions). */
226
+ /** Current bindings (logger name + child bindings + module/correlationId). */
176
227
  bindings(): Record<string, unknown> {
177
228
  const out: Record<string, unknown> = {
229
+ ...(this.#config.name !== undefined ? { name: this.#config.name } : {}),
178
230
  ...this.#bindings,
179
231
  module: this.#module,
180
232
  };
@@ -238,12 +290,18 @@ export class Logger {
238
290
  this.#write("fatal", arg0, rest);
239
291
  }
240
292
 
241
- /** No-op — pino API-surface parity for the `silent` level. */
293
+ /**
294
+ * No-op — the `silent` level exists so a call site can be written and stay
295
+ * written. It takes the same arguments as every other level, because
296
+ * upstream's does and switching a call to it must not stop compiling.
297
+ */
298
+ silent(mergingObject: unknown, message?: string, ...values: unknown[]): void;
299
+ silent(message: string, ...values: unknown[]): void;
242
300
  silent(): void {}
243
301
 
244
302
  /** Resolve the numeric threshold for this logger + module. */
245
303
  #threshold(): number {
246
- const raw = this.#config.modules?.[this.#module] ?? this.#config.level;
304
+ const raw = this.#config.modules?.[this.#module] ?? this.level;
247
305
  if (raw === "silent") return levelThreshold("silent");
248
306
  if (typeof raw === "string" && isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
249
307
  return LOG_LEVEL_ORDER.info;
@@ -302,18 +360,17 @@ export class Logger {
302
360
  }
303
361
 
304
362
  #applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
363
+ if (this.#redactPaths.length === 0) return bag;
305
364
  const redact = this.#config.redact;
306
- if (!redact) return bag;
307
- const paths = Array.isArray(redact) ? redact : redact.paths;
308
- if (paths.length === 0) return bag;
309
- const censor = Array.isArray(redact)
310
- ? "[Redacted]"
311
- : (redact.censor ?? "[Redacted]");
312
- let out = bag;
313
- for (const path of paths) {
314
- out = redactPath(out, path, censor);
365
+ const censor =
366
+ redact === undefined || Array.isArray(redact)
367
+ ? "[Redacted]"
368
+ : (redact.censor ?? "[Redacted]");
369
+ let out: unknown = bag;
370
+ for (const tokens of this.#redactPaths) {
371
+ out = redactPath(out, tokens, censor);
315
372
  }
316
- return out;
373
+ return isMergeableObject(out) ? out : bag;
317
374
  }
318
375
 
319
376
  #write(level: LogLevel, arg0: unknown, rest: unknown[]): void {
@@ -323,6 +380,11 @@ export class Logger {
323
380
  const { message, mergingObject } = this.#resolveArgs(arg0, rest);
324
381
 
325
382
  let bag: Record<string, unknown> = {
383
+ // The name a multi-logger config gave this logger. It was assigned by
384
+ // the manager and then read by nothing, so two loggers writing to the
385
+ // same destination produced lines with no way to tell them apart.
386
+ // pino carries it as a binding; a merging object still wins over it.
387
+ ...(this.#config.name !== undefined ? { name: this.#config.name } : {}),
326
388
  ...this.#bindings,
327
389
  ...(mergingObject ?? {}),
328
390
  };
@@ -13,7 +13,15 @@ export class LoggerManager extends Logger {
13
13
  #loggers: Map<string, Logger> = new Map();
14
14
 
15
15
  constructor(config: LoggerManagerConfig) {
16
- super(config.loggers[config.default]);
16
+ const selected = config.loggers[config.default];
17
+ if (selected === undefined) {
18
+ // Naming a logger that is not in `loggers` used to build a manager
19
+ // around undefined and fail on the first line written.
20
+ throw new Error(
21
+ `[spectrum] config.logger names '${config.default}', which is not in \`loggers\`. Declared: ${Object.keys(config.loggers).join(", ") || "(none)"}.`,
22
+ );
23
+ }
24
+ super(selected);
17
25
  this.#config = config;
18
26
  }
19
27
 
@@ -30,13 +30,22 @@ export function parseRustLog(line: string): LogEntry | null {
30
30
  FATAL: "fatal",
31
31
  };
32
32
 
33
- const level = levelMap[match[1].toUpperCase()];
33
+ // All three groups are required by the pattern, so a match carries them.
34
+ const [, rawLevel, rawModule, rawMessage] = match;
35
+ if (
36
+ rawLevel === undefined ||
37
+ rawModule === undefined ||
38
+ rawMessage === undefined
39
+ ) {
40
+ return null;
41
+ }
42
+ const level = levelMap[rawLevel.toUpperCase()];
34
43
  if (!level) return null;
35
44
 
36
45
  return {
37
46
  level,
38
- message: match[3],
39
- module: match[2].replace(/_/g, "-"),
47
+ message: rawMessage,
48
+ module: rawModule.replace(/_/g, "-"),
40
49
  timestamp: new Date().toISOString(),
41
50
  };
42
51
  }
@@ -53,9 +62,61 @@ export function parseRustLog(line: string): LogEntry | null {
53
62
  * // ... Rust crates emit to stderr
54
63
  * bridge.stop()
55
64
  */
65
+ /**
66
+ * `process.stderr.write` exactly as it was found, so `stop()` puts THAT back.
67
+ *
68
+ * Storing a bound copy instead meant every start wrapped the previous stop's
69
+ * restoration in one more `bind`, so a process that started and stopped the
70
+ * bridge repeatedly grew a chain of wrappers around its own stderr.
71
+ */
56
72
  let activeOriginalWrite: typeof process.stderr.write | undefined;
57
73
  let activeBridge: { stop: () => void } | undefined;
58
74
 
75
+ /** The flush callback `stream.write(chunk, encoding?, callback?)` may carry. */
76
+ type WriteCallback = (error?: Error | null) => void;
77
+
78
+ function isWriteCallback(value: unknown): value is WriteCallback {
79
+ return typeof value === "function";
80
+ }
81
+
82
+ const BUFFER_ENCODINGS = new Set<string>([
83
+ "ascii",
84
+ "utf8",
85
+ "utf-8",
86
+ "utf16le",
87
+ "utf-16le",
88
+ "ucs2",
89
+ "ucs-2",
90
+ "base64",
91
+ "base64url",
92
+ "latin1",
93
+ "binary",
94
+ "hex",
95
+ ]);
96
+
97
+ function isBufferEncoding(value: unknown): value is BufferEncoding {
98
+ return typeof value === "string" && BUFFER_ENCODINGS.has(value);
99
+ }
100
+
101
+ /**
102
+ * Hand a chunk to the real `process.stderr.write`, callback included.
103
+ *
104
+ * The callback is the whole point of the indirection. It is the stream's
105
+ * promise that the chunk is out, and callers wait on it; a bridge that returns
106
+ * `true` without ever calling it leaves them waiting forever.
107
+ */
108
+ function passThrough(
109
+ write: typeof process.stderr.write,
110
+ chunk: string | Uint8Array,
111
+ encoding: BufferEncoding | undefined,
112
+ done: WriteCallback | undefined,
113
+ ): boolean {
114
+ // `encoding` stays in its own position even when absent: Node reads an
115
+ // `undefined` encoding as "the stream's default", and passing it keeps the
116
+ // callback in the slot the three-argument form expects.
117
+ return write.call(process.stderr, chunk, encoding, done);
118
+ }
119
+
59
120
  export function createRustLogBridge(channels: LogChannel[]): {
60
121
  start: () => void;
61
122
  stop: () => void;
@@ -66,27 +127,38 @@ export function createRustLogBridge(channels: LogChannel[]): {
66
127
  start() {
67
128
  if (activeBridge === bridge) return;
68
129
  if (activeBridge) {
69
- const prev = activeOriginalWrite;
130
+ // `stop()` has already restored it; say so through the restored
131
+ // write rather than through the one about to be installed.
70
132
  activeBridge.stop();
71
- if (prev) {
72
- process.stderr.write = prev as typeof process.stderr.write;
73
- prev(
74
- "[Spectrum] RustLogBridge replaced — previous bridge stopped. Only one bridge can be active per process.\n" as never,
75
- );
76
- }
133
+ process.stderr.write(
134
+ "[Spectrum] RustLogBridge replaced — previous bridge stopped. Only one bridge can be active per process.\n",
135
+ );
77
136
  }
78
137
 
79
- activeOriginalWrite = process.stderr.write.bind(process.stderr);
138
+ activeOriginalWrite = process.stderr.write;
80
139
  activeBridge = bridge;
81
140
 
82
- process.stderr.write = ((
141
+ // Written in the shape the stream's own `write` is declared in, so it
142
+ // can be installed without asserting that it fits.
143
+ process.stderr.write = (
83
144
  chunk: string | Uint8Array,
84
- ...args: unknown[]
85
- ) => {
145
+ encodingOrCallback?: BufferEncoding | WriteCallback,
146
+ callback?: WriteCallback,
147
+ ): boolean => {
86
148
  const origWrite = activeOriginalWrite;
87
149
  if (!origWrite) return true;
150
+ const encoding = isBufferEncoding(encodingOrCallback)
151
+ ? encodingOrCallback
152
+ : undefined;
153
+ // `write(chunk, callback)` puts the callback where the encoding
154
+ // would be.
155
+ const done = isWriteCallback(callback)
156
+ ? callback
157
+ : isWriteCallback(encodingOrCallback)
158
+ ? encodingOrCallback
159
+ : undefined;
88
160
  if (bridgingDepth > 0) {
89
- return origWrite(chunk as never, ...(args as []));
161
+ return passThrough(origWrite, chunk, encoding, done);
90
162
  }
91
163
 
92
164
  const str =
@@ -129,22 +201,25 @@ export function createRustLogBridge(channels: LogChannel[]): {
129
201
 
130
202
  // Preserve original chunk when we didn't intercept any Rust logs.
131
203
  if (!hadRustLog) {
132
- return origWrite(chunk as never, ...(args as []));
204
+ return passThrough(origWrite, chunk, encoding, done);
133
205
  }
134
206
 
207
+ // Something was consumed, so the chunk cannot go out verbatim.
208
+ // What is left still carries the caller's callback; when nothing
209
+ // is left, it is called here rather than dropped.
135
210
  if (passthrough) {
136
- origWrite(passthrough);
211
+ return passThrough(origWrite, passthrough, undefined, done);
137
212
  }
213
+ done?.();
138
214
 
139
215
  return true;
140
- }) as typeof process.stderr.write;
216
+ };
141
217
  },
142
218
 
143
219
  stop() {
144
220
  if (activeBridge !== bridge) return;
145
221
  if (activeOriginalWrite) {
146
- process.stderr.write =
147
- activeOriginalWrite as typeof process.stderr.write;
222
+ process.stderr.write = activeOriginalWrite;
148
223
  activeOriginalWrite = undefined;
149
224
  }
150
225
  activeBridge = undefined;