@c9up/spectrum 0.1.11 → 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 (54) 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 +8 -0
  21. package/dist/channels/FileChannel.d.ts.map +1 -1
  22. package/dist/channels/FileChannel.js +79 -7
  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/targets.d.ts +6 -1
  36. package/dist/targets.d.ts.map +1 -1
  37. package/dist/targets.js +59 -5
  38. package/dist/targets.js.map +1 -1
  39. package/dist/types.d.ts +28 -1
  40. package/dist/types.d.ts.map +1 -1
  41. package/dist/types.js +33 -6
  42. package/dist/types.js.map +1 -1
  43. package/package.json +4 -2
  44. package/src/Logger.ts +113 -51
  45. package/src/LoggerManager.ts +9 -1
  46. package/src/RustLogBridge.ts +95 -20
  47. package/src/SpectrumProvider.ts +34 -25
  48. package/src/augmentations.ts +32 -0
  49. package/src/channels/FileChannel.ts +80 -7
  50. package/src/configure.ts +19 -7
  51. package/src/index.ts +4 -0
  52. package/src/redact.ts +100 -0
  53. package/src/targets.ts +78 -12
  54. package/src/types.ts +50 -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,27 +1,16 @@
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
5
  import { 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
16
  function hasClose(ch: LogChannel): ch is LogChannel & { close(): void } {
@@ -71,9 +60,15 @@ export default class SpectrumProvider {
71
60
 
72
61
  const manager = new LoggerManager(managerConfig);
73
62
  this.app.container.singleton(Logger, () => manager);
74
- this.app.container.singleton("logger", () => {
75
- return this.app.container.resolve<Logger>(Logger);
76
- });
63
+ // Namespaced by the package that owns it, the way upstream namespaces
64
+ // `lucid.db`, `auth.manager` and `drive.manager` by theirs. The bare
65
+ // token stays bound beside it: it is what every existing
66
+ // `container.make(...)` asks for, and a token is not worth breaking an
67
+ // application over.
68
+ const logger = (): Promise<Logger> =>
69
+ this.app.container.resolve<Logger>(Logger);
70
+ this.app.container.singleton("spectrum.logger", logger);
71
+ this.app.container.singleton("logger", logger);
77
72
  }
78
73
 
79
74
  async boot() {
@@ -113,15 +108,29 @@ export default class SpectrumProvider {
113
108
  }
114
109
 
115
110
  #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)
111
+ const level = isLogLevelWithSilent(cfg.level)
123
112
  ? cfg.level
124
- : resolveLogLevel(process.env.LOG_LEVEL);
113
+ : logLevel(process.env.LOG_LEVEL);
114
+ // An AdonisJS `config/logger.ts` declares its output as
115
+ // `transport.targets`, not as channels. It has to be converted HERE:
116
+ // filling `channels` in with the console fallback below is what stopped
117
+ // the Logger's own conversion from ever running (it only fires when
118
+ // `channels` is absent), so a config that declared a file target reached
119
+ // production writing to a console and nothing to the file it named.
120
+ const channels = this.#channelsFor(cfg, level);
125
121
  return { ...cfg, level, channels };
126
122
  }
123
+
124
+ /** Explicit channels, else the declared targets, else a pretty console. */
125
+ #channelsFor(
126
+ cfg: Partial<LogConfig>,
127
+ level: LogLevelWithSilent,
128
+ ): LogChannel[] {
129
+ if (cfg.channels && cfg.channels.length > 0) return cfg.channels;
130
+ const declared = cfg.transport?.targets;
131
+ if (declared && declared.length > 0) {
132
+ return channelsFromTargets(declared, level);
133
+ }
134
+ return [new ConsoleChannel("pretty")];
135
+ }
127
136
  }
@@ -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
+ }
@@ -28,6 +28,14 @@ export class FileChannel implements LogChannel {
28
28
  #currentSize = 0;
29
29
  #dirReady = false;
30
30
  #rotating = false;
31
+ /**
32
+ * Terminal once `close()` has run.
33
+ *
34
+ * Nulling the stream was not enough: `write()` reopens a null stream, and so
35
+ * does a rotation, so a line written after close silently reopened the file
36
+ * and appended to it. A closed channel stays closed.
37
+ */
38
+ #closed = false;
31
39
  #pending: string[] = [];
32
40
 
33
41
  constructor(config: FileChannelConfig) {
@@ -37,6 +45,7 @@ export class FileChannel implements LogChannel {
37
45
  }
38
46
 
39
47
  write(entry: LogEntry): void {
48
+ if (this.#closed) return;
40
49
  const line = `${JSON.stringify(entry)}\n`;
41
50
  const bytes = Buffer.byteLength(line, "utf8");
42
51
 
@@ -67,7 +76,7 @@ export class FileChannel implements LogChannel {
67
76
  }
68
77
  }
69
78
 
70
- if (this.#currentSize + bytes > this.#maxSize) {
79
+ if (this.#needsRotation(bytes)) {
71
80
  this.#pending.push(line);
72
81
  this.#scheduleRotation();
73
82
  return;
@@ -80,6 +89,8 @@ export class FileChannel implements LogChannel {
80
89
  }
81
90
 
82
91
  #openStream(): void {
92
+ // A rotation in flight when `close()` lands must not bring the file back.
93
+ if (this.#closed) return;
83
94
  // mkdirSync + statSync only on first open (boot) — never on the hot path.
84
95
  // The fast write path goes straight through this.#stream.write() (non-blocking).
85
96
  if (!this.#dirReady) {
@@ -100,8 +111,25 @@ export class FileChannel implements LogChannel {
100
111
  });
101
112
  }
102
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
+
103
131
  #scheduleRotation(): void {
104
- if (this.#rotating) return;
132
+ if (this.#rotating || this.#closed) return;
105
133
  this.#rotating = true;
106
134
  queueMicrotask(() => {
107
135
  this.#rotate().finally(() => {
@@ -118,13 +146,20 @@ export class FileChannel implements LogChannel {
118
146
  const oldest = `${this.#filePath}.${this.#maxFiles - 1}`;
119
147
  await fsp.rm(oldest, { force: true });
120
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.
121
155
  for (let i = this.#maxFiles - 2; i >= 1; i--) {
122
- const from = i === 1 ? this.#filePath : `${this.#filePath}.${i}`;
123
- const to = `${this.#filePath}.${i + 1}`;
124
156
  try {
125
- await fsp.rename(from, to);
157
+ await fsp.rename(
158
+ `${this.#filePath}.${i}`,
159
+ `${this.#filePath}.${i + 1}`,
160
+ );
126
161
  } catch {
127
- // File doesn't exist — skip
162
+ // That generation does not exist yet — skip
128
163
  }
129
164
  }
130
165
 
@@ -153,7 +188,7 @@ export class FileChannel implements LogChannel {
153
188
  const line = this.#pending.shift();
154
189
  if (!line) continue;
155
190
  const bytes = Buffer.byteLength(line, "utf8");
156
- if (this.#currentSize + bytes > this.#maxSize) {
191
+ if (this.#needsRotation(bytes)) {
157
192
  this.#pending.unshift(line);
158
193
  this.#scheduleRotation();
159
194
  return;
@@ -172,10 +207,48 @@ export class FileChannel implements LogChannel {
172
207
  });
173
208
  }
174
209
 
210
+ /**
211
+ * Stop writing, for good.
212
+ *
213
+ * Anything buffered by a rotation goes out first — those lines were accepted
214
+ * and dropping them at close loses log the caller believed was written — and
215
+ * the flag is set before the flush so nothing the flush triggers can reopen
216
+ * the file.
217
+ */
175
218
  close(): void {
219
+ if (this.#closed) return;
220
+ const pending = this.#pending.splice(0);
221
+ this.#closed = true;
176
222
  if (this.#stream) {
223
+ for (const line of pending) this.#stream.write(line);
177
224
  this.#stream.end();
178
225
  this.#stream = null;
226
+ return;
227
+ }
228
+ // No stream, because a rotation is in flight: it nulls the stream before
229
+ // awaiting the old one's end, and it will not reopen now that #closed is
230
+ // set. Writing the buffer to the stream that no longer exists is how
231
+ // those lines used to disappear — accepted by write(), then dropped.
232
+ //
233
+ // Appended directly instead, and synchronously, because close() is: the
234
+ // path is the current log either way, whether the rotation has renamed
235
+ // it yet or not.
236
+ this.#appendDirectly(pending);
237
+ }
238
+
239
+ /** Last-resort write for lines with no stream left to carry them. */
240
+ #appendDirectly(lines: string[]): void {
241
+ if (lines.length === 0) return;
242
+ try {
243
+ if (!this.#dirReady) {
244
+ fs.mkdirSync(path.dirname(this.#filePath), { recursive: true });
245
+ this.#dirReady = true;
246
+ }
247
+ fs.appendFileSync(this.#filePath, lines.join(""));
248
+ } catch {
249
+ process.stderr.write(
250
+ `[Spectrum] FileChannel: ${lines.length} buffered line(s) lost closing '${this.#filePath}'\n`,
251
+ );
179
252
  }
180
253
  }
181
254
  }
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
+ }