@c9up/spectrum 0.1.12 → 0.1.14

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 (59) 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 +9 -1
  13. package/dist/SpectrumProvider.d.ts.map +1 -1
  14. package/dist/SpectrumProvider.js +53 -28
  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 +1 -1
  21. package/dist/channels/FileChannel.d.ts.map +1 -1
  22. package/dist/channels/FileChannel.js +39 -9
  23. package/dist/channels/FileChannel.js.map +1 -1
  24. package/dist/configure.d.ts.map +1 -1
  25. package/dist/configure.js +19 -7
  26. package/dist/configure.js.map +1 -1
  27. package/dist/index.d.ts +2 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +2 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/redact.d.ts +29 -0
  32. package/dist/redact.d.ts.map +1 -0
  33. package/dist/redact.js +90 -0
  34. package/dist/redact.js.map +1 -0
  35. package/dist/services/main.d.ts +9 -0
  36. package/dist/services/main.d.ts.map +1 -1
  37. package/dist/services/main.js +11 -0
  38. package/dist/services/main.js.map +1 -1
  39. package/dist/targets.d.ts +6 -1
  40. package/dist/targets.d.ts.map +1 -1
  41. package/dist/targets.js +59 -5
  42. package/dist/targets.js.map +1 -1
  43. package/dist/types.d.ts +38 -1
  44. package/dist/types.d.ts.map +1 -1
  45. package/dist/types.js +33 -6
  46. package/dist/types.js.map +1 -1
  47. package/package.json +4 -2
  48. package/src/Logger.ts +113 -51
  49. package/src/LoggerManager.ts +9 -1
  50. package/src/RustLogBridge.ts +95 -20
  51. package/src/SpectrumProvider.ts +62 -32
  52. package/src/augmentations.ts +32 -0
  53. package/src/channels/FileChannel.ts +43 -9
  54. package/src/configure.ts +19 -7
  55. package/src/index.ts +4 -0
  56. package/src/redact.ts +100 -0
  57. package/src/services/main.ts +12 -0
  58. package/src/targets.ts +78 -12
  59. package/src/types.ts +60 -7
@@ -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;
@@ -1,30 +1,21 @@
1
+ import "./augmentations.js";
1
2
  import { ConsoleChannel } from "./channels/ConsoleChannel.js";
2
3
  import { Logger } from "./Logger.js";
3
4
  import { LoggerManager } from "./LoggerManager.js";
4
- import { setLogger } from "./services/main.js";
5
+ import { clearLogger, getLogger, setLogger } from "./services/main.js";
6
+ import { channelsFromTargets } from "./targets.js";
5
7
  import type {
6
8
  LogChannel,
7
9
  LogConfig,
8
10
  LoggerManagerConfig,
9
11
  LogLevelWithSilent,
10
12
  } from "./types.js";
11
- import { LOG_LEVEL_ORDER } from "./types.js";
12
-
13
- const VALID_LEVELS = new Set<string>([
14
- ...Object.keys(LOG_LEVEL_ORDER),
15
- "silent",
16
- ]);
17
-
18
- function isValidLevel(raw: unknown): raw is LogLevelWithSilent {
19
- return typeof raw === "string" && VALID_LEVELS.has(raw);
20
- }
21
-
22
- function resolveLogLevel(raw: unknown): LogLevelWithSilent {
23
- return isValidLevel(raw) ? raw : "info";
24
- }
13
+ import { isLogLevelWithSilent, logLevel } from "./types.js";
25
14
 
26
15
  /** A channel that owns a resource (e.g. a FileChannel WriteStream) to release on shutdown. */
27
- function hasClose(ch: LogChannel): ch is LogChannel & { close(): void } {
16
+ function hasClose(
17
+ ch: LogChannel,
18
+ ): ch is LogChannel & { close(): void | Promise<void> } {
28
19
  return "close" in ch && typeof ch.close === "function";
29
20
  }
30
21
 
@@ -56,6 +47,9 @@ export interface SpectrumAppContext {
56
47
  }
57
48
 
58
49
  export default class SpectrumProvider {
50
+ /** The logger this provider bound, so shutdown only clears its own. */
51
+ #owned: Logger | undefined;
52
+
59
53
  #channels: LogChannel[] = [];
60
54
 
61
55
  constructor(protected app: SpectrumAppContext) {}
@@ -71,20 +65,42 @@ export default class SpectrumProvider {
71
65
 
72
66
  const manager = new LoggerManager(managerConfig);
73
67
  this.app.container.singleton(Logger, () => manager);
74
- this.app.container.singleton("logger", () => {
75
- return this.app.container.resolve<Logger>(Logger);
76
- });
68
+ // Namespaced by the package that owns it, the way upstream namespaces
69
+ // `lucid.db`, `auth.manager` and `drive.manager` by theirs. The bare
70
+ // token stays bound beside it: it is what every existing
71
+ // `container.make(...)` asks for, and a token is not worth breaking an
72
+ // application over.
73
+ const logger = (): Promise<Logger> =>
74
+ this.app.container.resolve<Logger>(Logger);
75
+ this.app.container.singleton("spectrum.logger", logger);
76
+ this.app.container.singleton("logger", logger);
77
77
  }
78
78
 
79
79
  async boot() {
80
- setLogger(await this.app.container.resolve<Logger>(Logger));
80
+ const logger = await this.app.container.resolve<Logger>(Logger);
81
+ this.#owned = logger;
82
+ setLogger(logger);
81
83
  }
82
84
 
83
- /** Release channel resources (e.g. FileChannel WriteStreams) on shutdown. */
85
+ /**
86
+ * Release channel resources (e.g. FileChannel WriteStreams) on shutdown.
87
+ *
88
+ * AWAITED, and all of them: closing a file channel ends a stream, and ending
89
+ * one is a request rather than a completion. Firing them and returning let
90
+ * the shutdown run on to `process.exit` with the last lines still buffered.
91
+ * `allSettled` so one channel failing to close does not strand the others.
92
+ */
84
93
  async shutdown() {
85
- for (const channel of this.#channels) {
86
- if (hasClose(channel)) channel.close();
87
- }
94
+ // Release the module-level singleton first, while it is still ours: past
95
+ // this point the channels are closing, and a logger reachable through
96
+ // `services/main` would be writing into streams that have ended.
97
+ if (this.#owned !== undefined && getLogger() === this.#owned) clearLogger();
98
+ this.#owned = undefined;
99
+ await Promise.allSettled(
100
+ this.#channels
101
+ .filter((channel) => hasClose(channel))
102
+ .map(async (channel) => channel.close()),
103
+ );
88
104
  }
89
105
 
90
106
  /**
@@ -113,15 +129,29 @@ export default class SpectrumProvider {
113
129
  }
114
130
 
115
131
  #normalizeLogger(cfg: Partial<LogConfig>): LogConfig {
116
- // Honour the configured channels; fall back to a pretty console channel
117
- // only when none are supplied.
118
- const channels =
119
- cfg.channels && cfg.channels.length > 0
120
- ? cfg.channels
121
- : [new ConsoleChannel("pretty")];
122
- const level = isValidLevel(cfg.level)
132
+ const level = isLogLevelWithSilent(cfg.level)
123
133
  ? cfg.level
124
- : resolveLogLevel(process.env.LOG_LEVEL);
134
+ : logLevel(process.env.LOG_LEVEL);
135
+ // An AdonisJS `config/logger.ts` declares its output as
136
+ // `transport.targets`, not as channels. It has to be converted HERE:
137
+ // filling `channels` in with the console fallback below is what stopped
138
+ // the Logger's own conversion from ever running (it only fires when
139
+ // `channels` is absent), so a config that declared a file target reached
140
+ // production writing to a console and nothing to the file it named.
141
+ const channels = this.#channelsFor(cfg, level);
125
142
  return { ...cfg, level, channels };
126
143
  }
144
+
145
+ /** Explicit channels, else the declared targets, else a pretty console. */
146
+ #channelsFor(
147
+ cfg: Partial<LogConfig>,
148
+ level: LogLevelWithSilent,
149
+ ): LogChannel[] {
150
+ if (cfg.channels && cfg.channels.length > 0) return cfg.channels;
151
+ const declared = cfg.transport?.targets;
152
+ if (declared && declared.length > 0) {
153
+ return channelsFromTargets(declared, level);
154
+ }
155
+ return [new ConsoleChannel("pretty")];
156
+ }
127
157
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Teach ream's `ContainerBindings` what `container.make('logger')` returns.
3
+ *
4
+ * ream declares that interface open on purpose: it registers its own entries
5
+ * and expects each package to contribute the one it owns — the comment on the
6
+ * interface names `logger` (spectrum) as exactly this. Nothing filled it in,
7
+ * so resolving by the string token answered `unknown` and every call site had
8
+ * to assert a type it could not prove.
9
+ *
10
+ * Loaded from the package barrel and from the provider, so registering
11
+ * spectrum is enough — an application writes no `declare module` of its own.
12
+ *
13
+ * Type-only, and ream stays an OPTIONAL peer: nothing here reaches a runtime
14
+ * import, and a `declare module` for a specifier that does not resolve is
15
+ * simply inert.
16
+ */
17
+
18
+ // Referenced so the augmentation below resolves the module it augments.
19
+ import type {} from "@c9up/ream/types";
20
+ import type { Logger } from "./Logger.js";
21
+
22
+ declare module "@c9up/ream/types" {
23
+ interface ContainerBindings {
24
+ /** The logger, bound by `SpectrumProvider`. */
25
+ "spectrum.logger": Logger;
26
+ /**
27
+ * The same binding under the name it had before the token carried its
28
+ * package. Kept bound so an existing `container.make(...)` resolves.
29
+ */
30
+ logger: Logger;
31
+ }
32
+ }
@@ -76,7 +76,7 @@ export class FileChannel implements LogChannel {
76
76
  }
77
77
  }
78
78
 
79
- if (this.#currentSize + bytes > this.#maxSize) {
79
+ if (this.#needsRotation(bytes)) {
80
80
  this.#pending.push(line);
81
81
  this.#scheduleRotation();
82
82
  return;
@@ -111,6 +111,23 @@ export class FileChannel implements LogChannel {
111
111
  });
112
112
  }
113
113
 
114
+ /**
115
+ * Whether this line has to wait for a rotation.
116
+ *
117
+ * The empty-file test is what stops an entry LARGER than `maxSizeBytes`
118
+ * from spinning forever: a fresh file starts at zero, so `0 + bytes > max`
119
+ * was still true and the line went back on the buffer, scheduled another
120
+ * rotation, and came back to the same answer — churning through a
121
+ * generation each time and never being written.
122
+ *
123
+ * A log line cannot be split, so an oversized one is written whole into a
124
+ * file of its own and the next line rotates. Bigger than the limit once
125
+ * beats absent.
126
+ */
127
+ #needsRotation(bytes: number): boolean {
128
+ return this.#currentSize > 0 && this.#currentSize + bytes > this.#maxSize;
129
+ }
130
+
114
131
  #scheduleRotation(): void {
115
132
  if (this.#rotating || this.#closed) return;
116
133
  this.#rotating = true;
@@ -129,13 +146,20 @@ export class FileChannel implements LogChannel {
129
146
  const oldest = `${this.#filePath}.${this.#maxFiles - 1}`;
130
147
  await fsp.rm(oldest, { force: true });
131
148
 
149
+ // Shift the numbered generations up, oldest first: .1 → .2, .2 → .3…
150
+ //
151
+ // The i===1 pass used to take the LIVE file rather than `.1`, so `.1`
152
+ // was never written and the rename below found nothing left to move.
153
+ // With maxFiles=3 that kept one generation where two were configured,
154
+ // and every rotation destroyed the one before it.
132
155
  for (let i = this.#maxFiles - 2; i >= 1; i--) {
133
- const from = i === 1 ? this.#filePath : `${this.#filePath}.${i}`;
134
- const to = `${this.#filePath}.${i + 1}`;
135
156
  try {
136
- await fsp.rename(from, to);
157
+ await fsp.rename(
158
+ `${this.#filePath}.${i}`,
159
+ `${this.#filePath}.${i + 1}`,
160
+ );
137
161
  } catch {
138
- // File doesn't exist — skip
162
+ // That generation does not exist yet — skip
139
163
  }
140
164
  }
141
165
 
@@ -164,7 +188,7 @@ export class FileChannel implements LogChannel {
164
188
  const line = this.#pending.shift();
165
189
  if (!line) continue;
166
190
  const bytes = Buffer.byteLength(line, "utf8");
167
- if (this.#currentSize + bytes > this.#maxSize) {
191
+ if (this.#needsRotation(bytes)) {
168
192
  this.#pending.unshift(line);
169
193
  this.#scheduleRotation();
170
194
  return;
@@ -191,14 +215,24 @@ export class FileChannel implements LogChannel {
191
215
  * the flag is set before the flush so nothing the flush triggers can reopen
192
216
  * the file.
193
217
  */
194
- close(): void {
218
+ async close(): Promise<void> {
195
219
  if (this.#closed) return;
196
220
  const pending = this.#pending.splice(0);
197
221
  this.#closed = true;
198
222
  if (this.#stream) {
199
- for (const line of pending) this.#stream.write(line);
200
- this.#stream.end();
223
+ const stream = this.#stream;
224
+ for (const line of pending) stream.write(line);
201
225
  this.#stream = null;
226
+ // AWAIT the flush. `end()` asks the stream to finish; it does not
227
+ // finish it. Returning here let a shutdown run on to `process.exit`
228
+ // with the last lines still buffered — and the last lines are usually
229
+ // the ones explaining why the process is going down.
230
+ await new Promise<void>((resolve) => {
231
+ stream.end(() => resolve());
232
+ // A stream that errors will never emit `finish`, and a shutdown
233
+ // must not hang on a full disk or a revoked permission.
234
+ stream.once("error", () => resolve());
235
+ });
202
236
  return;
203
237
  }
204
238
  // No stream, because a rotation is in flight: it nulls the stream before
package/src/configure.ts CHANGED
@@ -12,15 +12,27 @@ export async function configure(codemods: Codemods): Promise<void> {
12
12
  await codemods.addProvider("@c9up/spectrum/provider");
13
13
  await codemods.writeFile(
14
14
  "config/logger.ts",
15
- `import { ConsoleChannel, defineConfig, type LogLevel } from '@c9up/spectrum'
15
+ `import { defineConfig, logLevel, targets } from '@c9up/spectrum'
16
+
17
+ const inProduction = process.env.NODE_ENV === 'production'
16
18
 
17
19
  export default defineConfig({
18
- // LOG_LEVEL is an untyped env string — narrow it to the LogLevel union so the
19
- // generated config typechecks against defineConfig's strict \`level\`.
20
- level: (process.env.LOG_LEVEL as LogLevel | undefined) ?? 'info',
21
- // Channels are LogChannel instances. Add a FileChannel for disk logs:
22
- // new FileChannel({ path: 'storage/logs/app.log' })
23
- channels: [new ConsoleChannel('pretty')],
20
+ default: 'app',
21
+ loggers: {
22
+ app: {
23
+ enabled: true,
24
+ name: process.env.APP_NAME ?? 'app',
25
+ // LOG_LEVEL comes from outside the program, so it is checked rather than
26
+ // asserted: anything that is not a level reads as 'info'.
27
+ level: logLevel(process.env.LOG_LEVEL),
28
+ transport: {
29
+ targets: targets()
30
+ .pushIf(!inProduction, targets.pretty())
31
+ .pushIf(inProduction, targets.file({ destination: 1 }))
32
+ .toArray(),
33
+ },
34
+ },
35
+ },
24
36
  })
25
37
  `,
26
38
  );
package/src/index.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  * @implements FR54, FR55, FR56, FR57, FR58
5
5
  */
6
6
 
7
+ import "./augmentations.js";
8
+
7
9
  export { ConsoleChannel } from "./channels/ConsoleChannel.js";
8
10
  export { FileChannel } from "./channels/FileChannel.js";
9
11
  export { defineConfig } from "./config.js";
@@ -18,6 +20,7 @@ export type {
18
20
  } from "./targets.js";
19
21
  export { channelsFromTargets, Targets, targets } from "./targets.js";
20
22
  export {
23
+ isLogLevelWithSilent,
21
24
  type LogChannel,
22
25
  type LogConfig,
23
26
  type LogEntry,
@@ -25,5 +28,6 @@ export {
25
28
  type LogLevelWithSilent,
26
29
  type LogSerializer,
27
30
  logEntryExtras,
31
+ logLevel,
28
32
  type RedactOptions,
29
33
  } from "./types.js";
package/src/redact.ts ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Redaction paths, in the syntax pino's `redact` option is written in.
3
+ *
4
+ * Upstream hands those paths to `fast-redact`, so a migrated `config/logger.ts`
5
+ * legitimately contains `req.headers.authorization`, `*.password`,
6
+ * `users[*].token` and `headers["set-cookie"]`. Understanding only the first of
7
+ * those — a literal dot-path — is not a smaller feature: it is a redaction that
8
+ * silently does nothing. The config says the password is censored, and the
9
+ * password is written out in full.
10
+ */
11
+
12
+ /**
13
+ * fast-redact's own tokenizer: a run of characters that is not `.`, `[` or
14
+ * `]`, or anything between a pair of brackets.
15
+ */
16
+ const PATH_TOKEN = /[^.[\]]+|\[(?:.)*?\]/g;
17
+
18
+ /**
19
+ * Split a redaction path into the keys it names.
20
+ *
21
+ * `a["b-c"]` and `a.b-c` name the same key: the brackets and the quotes are
22
+ * notation, not part of the name.
23
+ */
24
+ export function parseRedactPath(path: string): string[] {
25
+ const tokens = path.match(PATH_TOKEN);
26
+ if (!tokens) return [];
27
+ return tokens.map((token) => {
28
+ const inner = token.startsWith("[") ? token.slice(1, -1) : token;
29
+ return inner.replace(/['"`]/g, "");
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Replace everything `tokens` selects with `censor`, without touching the
35
+ * input.
36
+ *
37
+ * Copy-on-write, and the copy is only made once something actually matched —
38
+ * so an entry with no redacted field is passed through by reference, which is
39
+ * the common case on the hot path. The same rule is what keeps the walk
40
+ * honest: a path that names nothing leaves the object exactly as it was
41
+ * instead of inventing the key it was looking for.
42
+ */
43
+ export function redactPath(
44
+ node: unknown,
45
+ tokens: readonly string[],
46
+ censor: string,
47
+ depth = 0,
48
+ ): unknown {
49
+ const segment = tokens[depth];
50
+ if (segment === undefined || node === null || typeof node !== "object") {
51
+ return node;
52
+ }
53
+
54
+ const keys = selectKeys(node, segment);
55
+ if (keys.length === 0) return node;
56
+
57
+ const isLast = depth === tokens.length - 1;
58
+ let copy: Record<string, unknown> | unknown[] | null = null;
59
+ for (const key of keys) {
60
+ const current = readKey(node, key);
61
+ const next = isLast
62
+ ? censor
63
+ : redactPath(current, tokens, censor, depth + 1);
64
+ if (next === current) continue;
65
+ if (!copy) copy = Array.isArray(node) ? [...node] : { ...node };
66
+ writeKey(copy, key, next);
67
+ }
68
+ return copy ?? node;
69
+ }
70
+
71
+ /**
72
+ * The own keys a path segment selects.
73
+ *
74
+ * `*` takes every one of them — on an array too, whose own keys are its
75
+ * indices, which is what makes `users[*].token` reach into a list. Anything
76
+ * else takes that single key, and only if the object really has it: `in` would
77
+ * answer for `toString` and turn a redaction into an invented field.
78
+ */
79
+ function selectKeys(node: object, segment: string): string[] {
80
+ if (segment === "*") return Object.keys(node);
81
+ return Object.hasOwn(node, segment) ? [segment] : [];
82
+ }
83
+
84
+ function readKey(node: object, key: string): unknown {
85
+ const own = Object.getOwnPropertyDescriptor(node, key);
86
+ return own === undefined ? undefined : own.value;
87
+ }
88
+
89
+ function writeKey(
90
+ node: Record<string, unknown> | unknown[],
91
+ key: string,
92
+ value: unknown,
93
+ ): void {
94
+ if (Array.isArray(node)) {
95
+ const index = Number(key);
96
+ if (Number.isInteger(index)) node[index] = value;
97
+ return;
98
+ }
99
+ node[key] = value;
100
+ }
@@ -23,6 +23,18 @@ export function getLogger(): Logger | undefined {
23
23
  return instance;
24
24
  }
25
25
 
26
+ /**
27
+ * @internal Release the singleton, so a shut-down application does not leave a
28
+ * dead logger reachable through `services/main`.
29
+ *
30
+ * The caller checks ownership first (`getLogger() === mine`): two applications
31
+ * share this module in one process, and the one shutting down must not clear
32
+ * what the other has since bound.
33
+ */
34
+ export function clearLogger(): void {
35
+ instance = undefined;
36
+ }
37
+
26
38
  const logger: Logger = new Proxy({} as Logger, {
27
39
  get(_target, prop) {
28
40
  if (!instance) {