@warlock.js/logger 5.30.0 → 5.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +32 -5
  2. package/README.md +8 -11
  3. package/cjs/index.cjs +339 -31
  4. package/cjs/index.cjs.map +1 -1
  5. package/esm/channels/console-log.d.mts +2 -4
  6. package/esm/channels/console-log.d.mts.map +1 -1
  7. package/esm/channels/console-log.mjs.map +1 -1
  8. package/esm/channels/file-log.d.mts +130 -15
  9. package/esm/channels/file-log.d.mts.map +1 -1
  10. package/esm/channels/file-log.mjs +204 -23
  11. package/esm/channels/file-log.mjs.map +1 -1
  12. package/esm/channels/file-name-pattern.d.mts +15 -0
  13. package/esm/channels/file-name-pattern.d.mts.map +1 -0
  14. package/esm/channels/file-name-pattern.mjs +41 -0
  15. package/esm/channels/file-name-pattern.mjs.map +1 -0
  16. package/esm/channels/index.mjs +2 -2
  17. package/esm/channels/json-file-log.d.mts +1 -3
  18. package/esm/channels/json-file-log.d.mts.map +1 -1
  19. package/esm/channels/json-file-log.mjs +24 -5
  20. package/esm/channels/json-file-log.mjs.map +1 -1
  21. package/esm/channels/sentry-log.d.mts +7 -8
  22. package/esm/channels/sentry-log.d.mts.map +1 -1
  23. package/esm/channels/sentry-log.mjs.map +1 -1
  24. package/esm/index.d.mts +5 -3
  25. package/esm/index.mjs +3 -2
  26. package/esm/log-channel.d.mts +23 -3
  27. package/esm/log-channel.d.mts.map +1 -1
  28. package/esm/log-channel.mjs +22 -0
  29. package/esm/log-channel.mjs.map +1 -1
  30. package/esm/logger.d.mts +8 -5
  31. package/esm/logger.d.mts.map +1 -1
  32. package/esm/logger.mjs +12 -3
  33. package/esm/logger.mjs.map +1 -1
  34. package/esm/redact/default-keys.d.mts +3 -4
  35. package/esm/redact/default-keys.d.mts.map +1 -1
  36. package/esm/redact/escape-log-value.d.mts +25 -0
  37. package/esm/redact/escape-log-value.d.mts.map +1 -0
  38. package/esm/redact/escape-log-value.mjs +37 -0
  39. package/esm/redact/escape-log-value.mjs.map +1 -0
  40. package/esm/redact/index.mjs +2 -1
  41. package/esm/redact/mask-email.d.mts +3 -4
  42. package/esm/redact/mask-email.d.mts.map +1 -1
  43. package/esm/redact/redact.d.mts +3 -5
  44. package/esm/redact/redact.d.mts.map +1 -1
  45. package/esm/redact/redact.mjs.map +1 -1
  46. package/esm/types.d.mts +14 -14
  47. package/esm/types.d.mts.map +1 -1
  48. package/esm/utils/capture-unhandled-errors.d.mts +2 -3
  49. package/esm/utils/capture-unhandled-errors.d.mts.map +1 -1
  50. package/esm/utils/clear-message.d.mts +1 -2
  51. package/esm/utils/clear-message.d.mts.map +1 -1
  52. package/esm/utils/index.mjs +1 -1
  53. package/esm/utils/safe-json-stringify.d.mts +1 -2
  54. package/esm/utils/safe-json-stringify.d.mts.map +1 -1
  55. package/llms-full.txt +241 -141
  56. package/llms.txt +2 -2
  57. package/package.json +2 -2
  58. package/skills/capture-unhandled-errors/SKILL.md +9 -10
  59. package/skills/configure-logger/SKILL.md +7 -10
  60. package/skills/filter-log-entries/SKILL.md +2 -2
  61. package/skills/flush-logs-on-shutdown/SKILL.md +32 -13
  62. package/skills/index.md +4 -1
  63. package/skills/logger-basics/SKILL.md +18 -21
  64. package/skills/overview/SKILL.md +17 -6
  65. package/skills/pick-log-channel/SKILL.md +36 -24
  66. package/skills/redact-sensitive-log-fields/SKILL.md +48 -18
  67. package/skills/ship-logs-to-sentry/SKILL.md +18 -18
  68. package/skills/test-logging-code/SKILL.md +4 -2
  69. package/skills/write-custom-log-channel/SKILL.md +50 -17
@@ -15,6 +15,28 @@ var LogChannel = class {
15
15
  }, 0);
16
16
  }
17
17
  /**
18
+ * Route this channel's own failures (those outside a `log()` call) to the
19
+ * given reporter. `Logger` calls this when the channel is added, so the
20
+ * failures reach `log.onChannelError(...)`.
21
+ */
22
+ setErrorReporter(reporter) {
23
+ this.errorReporter = reporter;
24
+ }
25
+ /**
26
+ * Report a failure that happened outside a `log()` call. Never throws:
27
+ * without a reporter it writes one line to stderr.
28
+ */
29
+ reportError(error, entry) {
30
+ try {
31
+ if (this.errorReporter) {
32
+ this.errorReporter(error, entry);
33
+ return;
34
+ }
35
+ const reason = error instanceof Error ? error.message : String(error);
36
+ process.stderr.write(`[@warlock.js/logger] channel "${this.name}" failed: ${reason}\n`);
37
+ } catch {}
38
+ }
39
+ /**
18
40
  * Get config value
19
41
  */
20
42
  config(key) {
@@ -1 +1 @@
1
- {"version":3,"file":"log-channel.mjs","names":[],"sources":["../../../../../../../packages/logger/src/log-channel.ts"],"sourcesContent":["import type {\n BasicLogConfigurations,\n LogContract,\n LoggingData,\n RedactConfig,\n} from \"./types\";\n\nexport abstract class LogChannel<\n Options extends BasicLogConfigurations = BasicLogConfigurations,\n> implements LogContract {\n /**\n * Channel name\n */\n public name!: string;\n\n /**\n * Channel description\n */\n public description?: string;\n\n /**\n * Determine if channel is logging in terminal\n */\n public terminal = false;\n\n /**\n * Default Configurations\n */\n protected defaultConfigurations: Options = {} as Options;\n\n /**\n * Channel configurations\n */\n protected channelConfigurations: Options = {} as Options; //\n\n /**\n * Determine whether the channel is fully initialized\n */\n protected isInitialized = false;\n\n /**\n * Constructor\n */\n public constructor(configurations?: Options) {\n if (configurations) {\n this.setConfigurations(configurations);\n }\n\n setTimeout(async () => {\n if (this.init) {\n await this.init();\n }\n\n this.isInitialized = true;\n }, 0);\n }\n\n /**\n * Initialize the channel\n */\n protected init?(): void | Promise<void>;\n\n /**\n * Get config value\n */\n protected config<K extends keyof Options>(key: K): Options[K] {\n return (\n this.channelConfigurations[key] ?? (this.defaultConfigurations ?? {})[key]\n );\n }\n\n /**\n * Set configurations\n */\n protected setConfigurations(configurations: Options) {\n this.channelConfigurations = {\n ...this.channelConfigurations,\n ...configurations,\n };\n\n return this;\n }\n\n /**\n * Determine if the message should be logged\n */\n protected shouldBeLogged(data: LoggingData): boolean {\n // check for debug mode\n const allowedLevels = this.config(\"levels\");\n\n if (allowedLevels?.length && !allowedLevels.includes(data.type))\n return false;\n\n const filter = this.config(\"filter\");\n\n if (filter) {\n return filter(data);\n }\n\n return true;\n }\n\n /**\n * Log the given message\n */\n public abstract log(data: LoggingData): void | Promise<void>;\n\n /**\n * Synchronously flush messages\n */\n public flushSync?(): void;\n\n /**\n * Asynchronously flush buffered messages.\n *\n * Optional — channels that write synchronously per entry (e.g. `ConsoleLog`)\n * don't implement it. Buffering channels override this to drain their buffer\n * over async I/O so callers can `await log.flush()` on graceful shutdown.\n */\n public flush?(): void | Promise<void>;\n\n /**\n * Read the channel's redact config (if any). Used by `Logger` to apply\n * per-channel additive redaction on top of the logger-wide floor.\n * Subclasses normally don't override this — set `redact` in your channel\n * configuration instead.\n */\n public getRedactConfig(): RedactConfig | undefined {\n return this.config(\"redact\" as keyof Options) as RedactConfig | undefined;\n }\n\n /**\n * Get date and time formats\n */\n protected getDateAndTimeFormat() {\n const dateFormat = this.config(\"dateFormat\");\n const date = dateFormat?.date ?? \"DD-MM-YYYY\";\n const time = dateFormat?.time ?? \"HH:mm:ss\";\n\n return { date, time };\n }\n\n /**\n * get basic configurations with the given ones\n */\n protected withBasicConfigurations(configurations: Partial<Options>): Options {\n return {\n filter: () => true,\n ...configurations,\n } as any as Options;\n }\n}\n"],"mappings":";AAOA,IAAsB,aAAtB,MAEyB;;;;CAkCvB,AAAO,YAAY,gBAA0B;kBApB3B;+BAKyB,CAAC;+BAKD,CAAC;uBAKlB;EAMxB,IAAI,gBACF,KAAK,kBAAkB,cAAc;EAGvC,WAAW,YAAY;GACrB,IAAI,KAAK,MACP,MAAM,KAAK,KAAK;GAGlB,KAAK,gBAAgB;EACvB,GAAG,CAAC;CACN;;;;CAUA,AAAU,OAAgC,KAAoB;EAC5D,OACE,KAAK,sBAAsB,SAAS,KAAK,yBAAyB,CAAC,EAAC,CAAE;CAE1E;;;;CAKA,AAAU,kBAAkB,gBAAyB;EACnD,KAAK,wBAAwB;GAC3B,GAAG,KAAK;GACR,GAAG;EACL;EAEA,OAAO;CACT;;;;CAKA,AAAU,eAAe,MAA4B;EAEnD,MAAM,gBAAgB,KAAK,OAAO,QAAQ;EAE1C,IAAI,eAAe,UAAU,CAAC,cAAc,SAAS,KAAK,IAAI,GAC5D,OAAO;EAET,MAAM,SAAS,KAAK,OAAO,QAAQ;EAEnC,IAAI,QACF,OAAO,OAAO,IAAI;EAGpB,OAAO;CACT;;;;;;;CA2BA,AAAO,kBAA4C;EACjD,OAAO,KAAK,OAAO,QAAyB;CAC9C;;;;CAKA,AAAU,uBAAuB;EAC/B,MAAM,aAAa,KAAK,OAAO,YAAY;EAI3C,OAAO;GAAE,MAHI,YAAY,QAAQ;GAGlB,MAFF,YAAY,QAAQ;EAEb;CACtB;;;;CAKA,AAAU,wBAAwB,gBAA2C;EAC3E,OAAO;GACL,cAAc;GACd,GAAG;EACL;CACF;AACF"}
1
+ {"version":3,"file":"log-channel.mjs","names":[],"sources":["../../../../../../../packages/logger/src/log-channel.ts"],"sourcesContent":["import type { BasicLogConfigurations, LogContract, LoggingData, RedactConfig } from \"./types\";\n\n/**\n * Receives a failure the channel hits outside a `log()` call (for example\n * `FileLog` retention). The logger installs one that forwards to its\n * `onChannelError` handler.\n */\nexport type ChannelErrorReporter = (error: unknown, entry: LoggingData) => void;\n\nexport abstract class LogChannel<\n Options extends BasicLogConfigurations = BasicLogConfigurations,\n> implements LogContract {\n /**\n * Channel name\n */\n public name!: string;\n\n /**\n * Channel description\n */\n public description?: string;\n\n /**\n * Determine if channel is logging in terminal\n */\n public terminal = false;\n\n /**\n * Default Configurations\n */\n protected defaultConfigurations: Options = {} as Options;\n\n /**\n * Channel configurations\n */\n protected channelConfigurations: Options = {} as Options; //\n\n /**\n * Determine whether the channel is fully initialized\n */\n protected isInitialized = false;\n\n /**\n * Where {@link reportError} sends failures; set by the logger the channel\n * is added to.\n */\n protected errorReporter?: ChannelErrorReporter;\n\n /**\n * Constructor\n */\n public constructor(configurations?: Options) {\n if (configurations) {\n this.setConfigurations(configurations);\n }\n\n setTimeout(async () => {\n if (this.init) {\n await this.init();\n }\n\n this.isInitialized = true;\n }, 0);\n }\n\n /**\n * Route this channel's own failures (those outside a `log()` call) to the\n * given reporter. `Logger` calls this when the channel is added, so the\n * failures reach `log.onChannelError(...)`.\n */\n public setErrorReporter(reporter: ChannelErrorReporter | undefined): void {\n this.errorReporter = reporter;\n }\n\n /**\n * Report a failure that happened outside a `log()` call. Never throws:\n * without a reporter it writes one line to stderr.\n */\n protected reportError(error: unknown, entry: LoggingData): void {\n try {\n if (this.errorReporter) {\n this.errorReporter(error, entry);\n return;\n }\n\n const reason = error instanceof Error ? error.message : String(error);\n process.stderr.write(`[@warlock.js/logger] channel \"${this.name}\" failed: ${reason}\\n`);\n } catch {\n // Reporting a failure must never become one.\n }\n }\n\n /**\n * Initialize the channel\n */\n protected init?(): void | Promise<void>;\n\n /**\n * Get config value\n */\n protected config<K extends keyof Options>(key: K): Options[K] {\n return this.channelConfigurations[key] ?? (this.defaultConfigurations ?? {})[key];\n }\n\n /**\n * Set configurations\n */\n protected setConfigurations(configurations: Options) {\n this.channelConfigurations = {\n ...this.channelConfigurations,\n ...configurations,\n };\n\n return this;\n }\n\n /**\n * Determine if the message should be logged\n */\n protected shouldBeLogged(data: LoggingData): boolean {\n // check for debug mode\n const allowedLevels = this.config(\"levels\");\n\n if (allowedLevels?.length && !allowedLevels.includes(data.type)) return false;\n\n const filter = this.config(\"filter\");\n\n if (filter) {\n return filter(data);\n }\n\n return true;\n }\n\n /**\n * Log the given message\n */\n public abstract log(data: LoggingData): void | Promise<void>;\n\n /**\n * Synchronously flush messages\n */\n public flushSync?(): void;\n\n /**\n * Asynchronously flush buffered messages.\n *\n * Optional — channels that write synchronously per entry (e.g. `ConsoleLog`)\n * don't implement it. Buffering channels override this to drain their buffer\n * over async I/O so callers can `await log.flush()` on graceful shutdown.\n */\n public flush?(): void | Promise<void>;\n\n /**\n * Read the channel's redact config (if any). Used by `Logger` to apply\n * per-channel additive redaction on top of the logger-wide floor.\n * Subclasses normally don't override this — set `redact` in your channel\n * configuration instead.\n */\n public getRedactConfig(): RedactConfig | undefined {\n return this.config(\"redact\" as keyof Options) as RedactConfig | undefined;\n }\n\n /**\n * Get date and time formats\n */\n protected getDateAndTimeFormat() {\n const dateFormat = this.config(\"dateFormat\");\n const date = dateFormat?.date ?? \"DD-MM-YYYY\";\n const time = dateFormat?.time ?? \"HH:mm:ss\";\n\n return { date, time };\n }\n\n /**\n * get basic configurations with the given ones\n */\n protected withBasicConfigurations(configurations: Partial<Options>): Options {\n return {\n filter: () => true,\n ...configurations,\n } as any as Options;\n }\n}\n"],"mappings":";AASA,IAAsB,aAAtB,MAEyB;;;;CAwCvB,AAAO,YAAY,gBAA0B;kBA1B3B;+BAKyB,CAAC;+BAKD,CAAC;uBAKlB;EAYxB,IAAI,gBACF,KAAK,kBAAkB,cAAc;EAGvC,WAAW,YAAY;GACrB,IAAI,KAAK,MACP,MAAM,KAAK,KAAK;GAGlB,KAAK,gBAAgB;EACvB,GAAG,CAAC;CACN;;;;;;CAOA,AAAO,iBAAiB,UAAkD;EACxE,KAAK,gBAAgB;CACvB;;;;;CAMA,AAAU,YAAY,OAAgB,OAA0B;EAC9D,IAAI;GACF,IAAI,KAAK,eAAe;IACtB,KAAK,cAAc,OAAO,KAAK;IAC/B;GACF;GAEA,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACpE,QAAQ,OAAO,MAAM,iCAAiC,KAAK,KAAK,YAAY,OAAO,GAAG;EACxF,QAAQ,CAER;CACF;;;;CAUA,AAAU,OAAgC,KAAoB;EAC5D,OAAO,KAAK,sBAAsB,SAAS,KAAK,yBAAyB,CAAC,EAAC,CAAE;CAC/E;;;;CAKA,AAAU,kBAAkB,gBAAyB;EACnD,KAAK,wBAAwB;GAC3B,GAAG,KAAK;GACR,GAAG;EACL;EAEA,OAAO;CACT;;;;CAKA,AAAU,eAAe,MAA4B;EAEnD,MAAM,gBAAgB,KAAK,OAAO,QAAQ;EAE1C,IAAI,eAAe,UAAU,CAAC,cAAc,SAAS,KAAK,IAAI,GAAG,OAAO;EAExE,MAAM,SAAS,KAAK,OAAO,QAAQ;EAEnC,IAAI,QACF,OAAO,OAAO,IAAI;EAGpB,OAAO;CACT;;;;;;;CA2BA,AAAO,kBAA4C;EACjD,OAAO,KAAK,OAAO,QAAyB;CAC9C;;;;CAKA,AAAU,uBAAuB;EAC/B,MAAM,aAAa,KAAK,OAAO,YAAY;EAI3C,OAAO;GAAE,MAHI,YAAY,QAAQ;GAGlB,MAFF,YAAY,QAAQ;EAEb;CACtB;;;;CAKA,AAAU,wBAAwB,gBAA2C;EAC3E,OAAO;GACL,cAAc;GACd,GAAG;EACL;CACF;AACF"}
package/esm/logger.d.mts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { AutoFlushEvent, BasicLogConfigurations, ChannelErrorHandler, LogLevel, LoggingData, OmittedLoggingData, RedactConfig } from "./types.mjs";
2
2
  import { LogChannel } from "./log-channel.mjs";
3
-
4
3
  //#region ../../packages/logger/src/logger.d.ts
5
- declare class Logger {
4
+ export declare class Logger {
6
5
  /**
7
6
  * Current channel
8
7
  */
@@ -100,6 +99,11 @@ declare class Logger {
100
99
  * Set channels
101
100
  */
102
101
  setChannels(channels: LogChannel[]): this;
102
+ /**
103
+ * Route a channel's own failures (outside `log()`, such as file retention)
104
+ * to this logger's channel error handler.
105
+ */
106
+ private attachChannel;
103
107
  /**
104
108
  * Normalize log data to a single object
105
109
  */
@@ -249,7 +253,7 @@ declare class Logger {
249
253
  * Default `timeout` of {@link Logger.flush}: long enough for a healthy network
250
254
  * channel, short enough that a hung one cannot eat a shutdown budget.
251
255
  */
252
- declare const DEFAULT_FLUSH_TIMEOUT_MS = 5000;
256
+ export declare const DEFAULT_FLUSH_TIMEOUT_MS = 5000;
253
257
  /**
254
258
  * The package singleton. Use this for everyday logging — `log.info(...)`,
255
259
  * `log.error(...)`, `log.configure(...)`. Custom logger instances can be
@@ -264,7 +268,6 @@ declare const DEFAULT_FLUSH_TIMEOUT_MS = 5000;
264
268
  * collapsed into a single name. Use `log.info(...)` (or any other level
265
269
  * shortcut) to emit entries.
266
270
  */
267
- declare const log: Logger;
271
+ export declare const log: Logger;
268
272
  //#endregion
269
- export { DEFAULT_FLUSH_TIMEOUT_MS, Logger, log };
270
273
  //# sourceMappingURL=logger.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.mts","names":[],"sources":["../../../../../../../packages/logger/src/logger.ts"],"mappings":";;;;cAsCa,MAAA;;AAAb;;EAIS,QAAA,EAAU,UAAA;EAEV,EAAA;EA0CoB;;;;;EAAA,QAnCnB,iBAAA;EAoFuB;;;;;;EAAA,QA5EvB,QAAA;EA2RQ;;;;;;EAAA,QAnRR,YAAA;EA6TI;;;;;;EAAA,QArTJ,iBAAA;EA8XU;;;;EAAA,QAxXV,mBAAA;EA2gBqC;;;EAtgBtC,UAAA,CAAW,OAAA,EAAS,UAAA;EAnCnB;;;EA4CD,SAAA,CAAU,MAAA;IACf,QAAA,GAAW,UAAA;IACX,WAAA,GAAc,cAAA;IACd,QAAA,GAAW,QAAA;IACX,MAAA,GAAS,YAAA;IACT,cAAA,GAAiB,mBAAA;EAAA;EAJN;;;;;;;;;;EAuCN,cAAA,CAAe,OAAA,EAAS,mBAAA;EAAA;;;;;;;;;;;EAgBxB,SAAA,CAAU,MAAA,EAAQ,YAAA;EAqClB;;;EA7BA,SAAA,IAAa,YAAA;EA8Eb;;;;;;;;;;EAhEA,WAAA,CAAY,KAAA,EAAO,QAAA;EA4KxB;;;EApKK,WAAA,IAAe,QAAA;EA+KpB;;;EAxKK,WAAA,CAAY,QAAA,EAAU,UAAA;EAmLtB;;;EAAA,QA1KC,gBAAA;EA6KN;;;;;;;;;;;;;;EArIK,GAAA,CAAI,IAAA,EAAM,WAAA;EAgKL;;;;;EAAA,QA9HJ,OAAA;EAAA,QAqDA,kBAAA;EA6FI;;;EA5EL,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EA0FV;;;EAjFK,IAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAgFV;;;EAvEK,IAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAsFA;;;EA7EL,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAuFe;;;EA9EpB,OAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAoHkB;;;;;;;;;EApGvB,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAmOD;;;;AAAwB;AA4CrC;;;;EA/PS,MAAA,CACL,SAAA,WACA,MAAA,UACA,MAAA,UACA,OAAA,OACA,OAAA,GAAU,MAAA;;;;;;;;;;;EAgBL,KAAA,CACL,MAAA,UACA,MAAA,YACE,KAAA,GAAQ,MAAA;;;;EAcL,OAAA,CAAQ,IAAA,WAAY,UAAA,CAdT,sBAAA;;;;EAqBX,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCM,KAAA,CAAM,OAAA;IAAW,OAAA;EAAA,IAA0B,OAAA;;;;;UA0D1C,YAAA;;;;;;;;;;;;;;;;;;;EAiCP,eAAA,CAAgB,MAAA,EAAQ,cAAA;;;;;EAyBxB,gBAAA;AAAA;;;;;cAeI,wBAAA;;;;;;;;;;;;;;;cA4CA,GAAA,EAAG,MAAe"}
1
+ {"version":3,"file":"logger.d.mts","names":["_$__types0.BasicLogConfigurations"],"sources":["../../../../../../../packages/logger/src/logger.ts"],"mappings":";;;qBAsCa;;;;EAIJ,UAAU;EAEV;;;;;;UAOC;;;;;;;UAQA;;;;;;;UAQA;;;;;;;UAQA;;;;;UAMA;;;;EAKD,WAAW,SAAS;;;;EASpB,UAAU;IACf,WAAW;IACX,cAAc;IACd,WAAW;IACX,SAAS;IACT,iBAAiB;;;;;;;;;;;;EAmCZ,eAAe,SAAS;;;;;;;;;;;;EAgBxB,UAAU,QAAQ;;;;EAQlB,aAAa;;;;;;;;;;;EAcb,YAAY,OAAO;;;;EAQnB,eAAe;;;;EAOf,YAAY,UAAU;;;;;UAcrB;;;;UAWA;;;;;;;;;;;;;;;EAwCD,IAAI,MAAM;;;;;;UAkCT;UAqDA;;;;EAiBD,MACL,cAAc,6BACd,iBACA,eACA,UAAU;;;;EASL,KACL,cAAc,6BACd,iBACA,eACA,UAAU;;;;EASL,KACL,cAAc,6BACd,iBACA,eACA,UAAU;;;;EASL,MACL,cAAc,6BACd,iBACA,eACA,UAAU;;;;EASL,QACL,cAAc,6BACd,iBACA,eACA,UAAU;;;;;;;;;;EAgBL,MACL,cAAc,6BACd,iBACA,eACA,UAAU;;;;;;;;;;EAgBL,OACL,oBACA,gBACA,gBACA,cACA,UAAU;;;;;;;;;;;EAgBL,MAAM,gBAAgB,kBAAkB,QAAQ;;;;EAchD,QAAQ,eAAY,WAd4BA;;;;EAqBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCM,MAAM;IAAW;MAA0B;;;;;UA0D1C;;;;;;;;;;;;;;;;;;;EAiCP,gBAAgB,QAAQ;;;;;EAyBxB;;;;;;qBAeI;;;;;;;;;;;;;;;qBA8CA,KAAG"}
package/esm/logger.mjs CHANGED
@@ -4,7 +4,7 @@ import { clearMessage } from "./utils/clear-message.mjs";
4
4
  import { Random } from "@mongez/reinforcements";
5
5
 
6
6
  //#region ../../packages/logger/src/logger.ts
7
- const SIGNAL_EVENTS = new Set([
7
+ const SIGNAL_EVENTS = /* @__PURE__ */ new Set([
8
8
  "SIGINT",
9
9
  "SIGTERM",
10
10
  "SIGHUP",
@@ -38,14 +38,14 @@ var Logger = class {
38
38
  * Add a new channel
39
39
  */
40
40
  addChannel(channel) {
41
- this.channels.push(channel);
41
+ this.channels.push(this.attachChannel(channel));
42
42
  return this;
43
43
  }
44
44
  /**
45
45
  * Set base configurations
46
46
  */
47
47
  configure(config) {
48
- if (config.channels) this.channels = config.channels;
48
+ if (config.channels) this.setChannels(config.channels);
49
49
  if (config.autoFlushOn) this.enableAutoFlush(config.autoFlushOn);
50
50
  if (config.minLevel !== void 0) this.setMinLevel(config.minLevel);
51
51
  if (config.redact !== void 0) this.setRedact(config.redact);
@@ -112,9 +112,18 @@ var Logger = class {
112
112
  */
113
113
  setChannels(channels) {
114
114
  this.channels = channels;
115
+ for (const channel of channels) this.attachChannel(channel);
115
116
  return this;
116
117
  }
117
118
  /**
119
+ * Route a channel's own failures (outside `log()`, such as file retention)
120
+ * to this logger's channel error handler.
121
+ */
122
+ attachChannel(channel) {
123
+ if (typeof channel.setErrorReporter === "function") channel.setErrorReporter((error, entry) => this.reportChannelError(error, channel, entry));
124
+ return channel;
125
+ }
126
+ /**
118
127
  * Normalize log data to a single object
119
128
  */
120
129
  normalizeLogData(dataOrModule, action, message = "", level, context) {
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../packages/logger/src/logger.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport type { LogChannel } from \"./log-channel\";\nimport { applyRedact, mergeRedact } from \"./redact\";\nimport type {\n AutoFlushEvent,\n ChannelErrorHandler,\n LogContract,\n LoggingData,\n LogLevel,\n OmittedLoggingData,\n RedactConfig,\n} from \"./types\";\nimport { clearMessage } from \"./utils/clear-message\";\n\nconst SIGNAL_EVENTS: ReadonlySet<AutoFlushEvent> = new Set([\n \"SIGINT\",\n \"SIGTERM\",\n \"SIGHUP\",\n \"SIGBREAK\",\n \"SIGUSR2\",\n]);\n\n/**\n * Severity ranks used by `setMinLevel`. Higher number = more severe. The\n * ordering matches conventional log-level hierarchies: `debug` is noisiest\n * and easiest to drop; `error` is the loudest and never dropped by the\n * minimum-level filter. `success` sits beside `info` — it's an informational\n * outcome, not a warning.\n */\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n success: 1,\n warn: 2,\n error: 3,\n fatal: 4,\n};\n\nexport class Logger {\n /**\n * Current channel\n */\n public channels: LogChannel[] = [];\n\n public id = \"logger-\" + Random.string(32);\n\n /**\n * Registered auto-flush handlers, keyed by event name. Stored so repeated\n * calls to `enableAutoFlush` replace rather than stack, and so\n * `disableAutoFlush` can remove them cleanly.\n */\n private autoFlushHandlers = new Map<AutoFlushEvent, () => void>();\n\n /**\n * Logger-wide minimum severity. When set, entries below this level are\n * dropped before any channel is invoked — cheaper than per-channel `levels`\n * filters because the fan-out loop is skipped entirely. `undefined` means\n * no minimum (every entry reaches every channel that accepts it).\n */\n private minLevel?: LogLevel;\n\n /**\n * Logger-wide redaction floor. Applied once before fan-out — every\n * channel receives an entry with these paths already censored. Channel\n * configs can extend the path list (additive); they cannot remove paths\n * set here.\n */\n private redactConfig?: RedactConfig;\n\n /**\n * Deliveries still in flight on async channels, per channel. `log()` never\n * awaits them; `flush()` does, so a graceful shutdown still waits for every\n * entry. Kept per channel so one hung channel cannot hold up another's\n * drain.\n */\n private pendingDeliveries = new Map<LogChannel, Set<Promise<void>>>();\n\n /**\n * Receives a channel's delivery failure (a sync throw or a rejected async\n * `log()`). Defaults to a single stderr line, never back through the logger.\n */\n private channelErrorHandler: ChannelErrorHandler = reportChannelError;\n\n /**\n * Add a new channel\n */\n public addChannel(channel: LogChannel) {\n this.channels.push(channel);\n\n return this;\n }\n\n /**\n * Set base configurations\n */\n public configure(config: {\n channels?: LogChannel[];\n autoFlushOn?: AutoFlushEvent[];\n minLevel?: LogLevel;\n redact?: RedactConfig;\n onChannelError?: ChannelErrorHandler;\n }) {\n if (config.channels) {\n this.channels = config.channels;\n }\n\n if (config.autoFlushOn) {\n this.enableAutoFlush(config.autoFlushOn);\n }\n\n if (config.minLevel !== undefined) {\n this.setMinLevel(config.minLevel);\n }\n\n if (config.redact !== undefined) {\n this.setRedact(config.redact);\n }\n\n if (config.onChannelError) {\n this.onChannelError(config.onChannelError);\n }\n\n return this;\n }\n\n /**\n * Handle a channel's delivery failure. Logging is fire-and-forget, so a\n * channel that throws or rejects never reaches the call site and never\n * becomes an unhandled rejection; it goes to this handler instead. The\n * default writes one line to stderr. The handler must not log through this\n * logger (a failing channel would loop).\n *\n * @example\n * log.onChannelError((error, channel) => metrics.increment(`log.${channel.name}.failed`));\n */\n public onChannelError(handler: ChannelErrorHandler): this {\n this.channelErrorHandler = handler;\n return this;\n }\n\n /**\n * Set the logger-wide redaction floor. Applied to every entry before\n * fan-out; channel configs add more paths on top, never fewer. Pass\n * `undefined` to clear.\n *\n * @example\n * log.setRedact({\n * paths: [\"context.password\", \"context.*.token\"],\n * censor: \"[REDACTED]\",\n * });\n */\n public setRedact(config: RedactConfig | undefined): this {\n this.redactConfig = config;\n return this;\n }\n\n /**\n * Read the active logger-wide redact config (or `undefined`).\n */\n public getRedact(): RedactConfig | undefined {\n return this.redactConfig;\n }\n\n /**\n * Drop every entry whose severity is below `level` before fan-out. Cheaper\n * than per-channel `levels` filters because the loop never runs and no\n * channel receives the entry. Pass `undefined` to clear and accept all\n * levels again.\n *\n * @example\n * // production: silence debug noise everywhere at once\n * logger.setMinLevel(\"info\");\n */\n public setMinLevel(level: LogLevel | undefined): this {\n this.minLevel = level;\n return this;\n }\n\n /**\n * Read the active minimum severity (or `undefined` when none is set).\n */\n public getMinLevel(): LogLevel | undefined {\n return this.minLevel;\n }\n\n /**\n * Set channels\n */\n public setChannels(channels: LogChannel[]) {\n this.channels = channels;\n\n return this;\n }\n\n /**\n * Normalize log data to a single object\n */\n private normalizeLogData(\n dataOrModule: LoggingData | OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n level?: LogLevel,\n context?: Record<string, any>,\n ): LoggingData {\n if (typeof dataOrModule === \"object\") {\n // If level is provided, override type\n return {\n type: (level || (dataOrModule as any).type || \"info\") as LogLevel,\n module: dataOrModule.module,\n action: dataOrModule.action,\n message: dataOrModule.message,\n ...(context ? { context } : dataOrModule.context ? { context: dataOrModule.context } : {}),\n };\n }\n return {\n type: (level || \"info\") as LogLevel,\n module: dataOrModule,\n action: action as string,\n message,\n ...(context ? { context } : {}),\n };\n }\n\n /**\n * Make log\n *\n * Fans out a single log entry to every registered channel. Non-terminal\n * channels receive a copy whose `message` has had ANSI color codes stripped\n * — each channel sees its own shallow clone so one channel cannot observe\n * another's mutations (e.g. a later terminal channel still sees the original\n * colored message).\n *\n * Synchronous and fire-and-forget: it returns the logger, not a promise.\n * Async channel deliveries are tracked and awaited by {@link flush}; a\n * channel that throws or rejects is isolated from the others and reported\n * to {@link onChannelError}.\n */\n public log(data: LoggingData): this {\n if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) {\n return this;\n }\n\n // Apply the logger-wide redact floor once. Every channel sees the\n // result; no channel can undo a logger-wide redaction (additive-only\n // semantics). A redaction that throws (a bad censor function) drops the\n // entry: delivering it unredacted would leak exactly what the config\n // exists to hide.\n let baseEntry: LoggingData;\n\n try {\n baseEntry = applyRedact(data, this.redactConfig);\n } catch (error) {\n for (const channel of this.channels) {\n this.reportChannelError(error, channel, redactionFailedEntry(data));\n }\n\n return this;\n }\n\n for (const channel of this.channels) {\n this.deliver(channel, data, baseEntry);\n }\n\n return this;\n }\n\n /**\n * Prepare and hand one entry to one channel, isolating its failure (a\n * channel redaction that throws included) and tracking an async delivery\n * until it settles.\n */\n private deliver(channel: LogChannel, data: LoggingData, baseEntry: LoggingData) {\n let payload: LoggingData = baseEntry;\n let result: void | Promise<void>;\n\n try {\n const channelRedact = channel.getRedactConfig?.();\n\n // When the channel adds paths, redact again from `data` rather than\n // from `baseEntry` so the merged config (which already contains the\n // logger-wide paths) does the full pass — avoids double-cloning the\n // already-redacted base.\n if (channelRedact) {\n payload = applyRedact(data, mergeRedact(this.redactConfig, channelRedact));\n }\n\n if (channel.terminal === false) {\n payload = { ...payload, message: clearMessage(payload.message) };\n }\n\n result = channel.log(payload);\n } catch (error) {\n // `payload` is the logger-wide redacted entry until the channel's own\n // redaction succeeded, so the handler never sees less-redacted data\n // than some channel would have.\n this.reportChannelError(error, channel, payload);\n return;\n }\n\n if (!result || typeof (result as Promise<void>).then !== \"function\") {\n return;\n }\n\n let pending = this.pendingDeliveries.get(channel);\n\n if (!pending) {\n pending = new Set();\n this.pendingDeliveries.set(channel, pending);\n }\n\n const tracked = pending;\n const delivery: Promise<void> = Promise.resolve(result)\n .catch((error) => this.reportChannelError(error, channel, payload))\n .finally(() => {\n tracked.delete(delivery);\n\n if (tracked.size === 0 && this.pendingDeliveries.get(channel) === tracked) {\n this.pendingDeliveries.delete(channel);\n }\n });\n\n tracked.add(delivery);\n }\n\n private reportChannelError(error: unknown, channel: LogContract, entry: LoggingData) {\n try {\n const outcome: unknown = this.channelErrorHandler(error, channel, entry);\n\n // An async handler that rejects must not become an unhandled rejection\n // (which an app may route straight back into this logger).\n if (outcome && typeof (outcome as Promise<unknown>).then === \"function\") {\n (outcome as Promise<unknown>).then(undefined, () => {});\n }\n } catch {\n // An error handler that throws must not turn logging into a crash.\n }\n }\n\n /**\n * Make debug log\n */\n public debug(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"debug\", context);\n return this.log(data);\n }\n\n /**\n * Make info log\n */\n public info(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"info\", context);\n return this.log(data);\n }\n\n /**\n * Make warn log\n */\n public warn(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"warn\", context);\n return this.log(data);\n }\n\n /**\n * Make error log\n */\n public error(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"error\", context);\n return this.log(data);\n }\n\n /**\n * Make success log\n */\n public success(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"success\", context);\n\n return this.log(data);\n }\n\n /**\n * Make fatal log — for unrecoverable failures where the application is going\n * down (failed bootstrap, lost connection to a required dependency that the\n * caller has decided not to retry, an `uncaughtException`).\n *\n * Identical shape to {@link error}; the level is purely informational —\n * `fatal` does NOT auto-flush or exit. The caller decides whether to call\n * `await log.flush()` and `process.exit(...)`.\n */\n public fatal(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"fatal\", context);\n\n return this.log(data);\n }\n\n /**\n * Log an `error` entry when `condition` is falsy. No-op otherwise — the\n * entry is never built and channels are not invoked, so this is genuinely\n * free in the happy path. Mirrors the spirit of `console.assert` but routes\n * through the logger pipeline so persistent channels capture failures.\n *\n * @example\n * log.assert(user !== null, \"auth\", \"session\", \"user vanished mid-flight\", { sessionId });\n */\n public assert(\n condition: unknown,\n module: string,\n action: string,\n message: any,\n context?: Record<string, any>,\n ): this {\n if (condition) return this;\n return this.error(module, action, message, context);\n }\n\n /**\n * Start a duration timer. The returned function emits an `info` entry\n * with `completed in <ms>ms` and a `durationMs` field in `context` when\n * called. Pass an object to `end()` to merge extra fields into context.\n *\n * @example\n * const end = log.timer(\"db\", \"users.findById\");\n * const user = await usersRepo.findById(id);\n * end({ id, found: !!user });\n */\n public timer(\n module: string,\n action: string,\n ): (extra?: Record<string, any>) => this {\n const startedAt = Date.now();\n return (extra?: Record<string, any>) => {\n const durationMs = Date.now() - startedAt;\n return this.info(module, action, `completed in ${durationMs}ms`, {\n durationMs,\n ...(extra ?? {}),\n });\n };\n }\n\n /**\n * Get channel by name\n */\n public channel(name: string) {\n return this.channels.find((channel) => channel.name === name);\n }\n\n /**\n * Synchronously flush logs\n */\n public flushSync() {\n for (const channel of this.channels) {\n if (channel.flushSync) {\n channel.flushSync();\n }\n }\n }\n\n /**\n * Wait for every in-flight async delivery, then drain every channel that\n * implements `flush()` — bounded by `timeout` (default\n * {@link DEFAULT_FLUSH_TIMEOUT_MS}).\n *\n * Unlike {@link flushSync}, this awaits each channel's async I/O — the\n * correct call for a graceful shutdown that can afford to wait\n * (`await log.flush()` after closing the HTTP server, before\n * `process.exit`). A channel whose delivery is async (a network transport,\n * an async disk write) implements `flush()`, not `flushSync()`.\n *\n * Channels drain concurrently and independently: each waits for its own\n * pending deliveries (including ones logged while the flush runs), then\n * runs its `flush()`. A channel whose delivery hangs therefore cannot hold\n * up another channel's drain, and a channel whose flush rejects can neither\n * stop the others nor escape as an unhandled rejection. When `timeout`\n * elapses, `flush()` resolves anyway and each channel still draining is\n * reported to {@link onChannelError}. Channels without `flush()` only wait\n * for their deliveries.\n *\n * @example\n * async function shutdown() {\n * await httpServer.close();\n * await log.flush({ timeout: 3000 });\n * process.exit(0);\n * }\n */\n public async flush(options: { timeout?: number } = {}): Promise<void> {\n const timeout = options.timeout ?? DEFAULT_FLUSH_TIMEOUT_MS;\n const draining = new Set<LogChannel>(this.channels);\n\n for (const channel of this.pendingDeliveries.keys()) {\n draining.add(channel);\n }\n\n const unfinished = new Set(draining);\n\n const drains = [...draining].map(async (channel) => {\n try {\n await this.drainChannel(channel);\n } catch {\n // A single channel must never break shutdown for the others —\n // a graceful drain is best-effort across every channel.\n } finally {\n unfinished.delete(channel);\n }\n });\n\n const settled = Promise.allSettled(drains).then(() => false);\n\n // `Infinity` (or any non-finite value) waits without a limit; setTimeout\n // would otherwise overflow it to an immediate timeout.\n if (!Number.isFinite(timeout)) {\n await settled;\n return;\n }\n\n let resolveTimeout!: (timedOut: boolean) => void;\n const timeoutReached = new Promise<boolean>((resolve) => {\n resolveTimeout = resolve;\n });\n const timer = setTimeout(() => resolveTimeout(true), Math.max(0, timeout));\n\n // Never keep the process alive just to time a flush out.\n (timer as { unref?: () => void }).unref?.();\n\n const timedOut = await Promise.race([settled, timeoutReached]);\n\n clearTimeout(timer);\n\n if (!timedOut) return;\n\n for (const channel of unfinished) {\n this.reportChannelError(\n new Error(`flush timed out after ${timeout}ms; entries still in flight may be lost`),\n channel,\n { type: \"warn\", module: \"logger\", action: \"flush\", message: \"flush timed out\" },\n );\n }\n }\n\n /**\n * Wait until the channel has no delivery in flight, run its `flush()`, and\n * repeat while that flush let new deliveries in.\n */\n private async drainChannel(channel: LogChannel) {\n do {\n let pending = this.pendingDeliveries.get(channel);\n\n while (pending && pending.size > 0) {\n await Promise.allSettled([...pending]);\n pending = this.pendingDeliveries.get(channel);\n }\n\n if (channel.flush) {\n await channel.flush();\n }\n } while ((this.pendingDeliveries.get(channel)?.size ?? 0) > 0);\n }\n\n /**\n * Register one process-level handler per event that calls `flushSync()`\n * before the process terminates.\n *\n * For signal events (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGBREAK`, `SIGUSR2`)\n * the handler flushes and then re-raises the signal so Node's default exit\n * behavior runs. For `beforeExit`, the handler flushes in place — Node exits\n * naturally afterwards.\n *\n * Idempotent: calling with the same events replaces the previous handlers.\n * Call `disableAutoFlush()` to unregister.\n *\n * @example\n * log.configure({\n * channels: [new ConsoleLog(), new FileLog()],\n * autoFlushOn: [\"SIGINT\", \"SIGTERM\", \"beforeExit\"],\n * });\n */\n public enableAutoFlush(events: AutoFlushEvent[]): this {\n this.disableAutoFlush();\n\n for (const event of events) {\n const handler = SIGNAL_EVENTS.has(event)\n ? () => {\n this.flushSync();\n process.off(event, handler);\n process.kill(process.pid, event as NodeJS.Signals);\n }\n : () => {\n this.flushSync();\n };\n\n process.on(event, handler);\n this.autoFlushHandlers.set(event, handler);\n }\n\n return this;\n }\n\n /**\n * Remove every handler previously registered by `enableAutoFlush`.\n * Safe to call when no handlers are registered.\n */\n public disableAutoFlush(): this {\n for (const [event, handler] of this.autoFlushHandlers) {\n process.off(event, handler);\n }\n\n this.autoFlushHandlers.clear();\n\n return this;\n }\n}\n\n/**\n * Default `timeout` of {@link Logger.flush}: long enough for a healthy network\n * channel, short enough that a hung one cannot eat a shutdown budget.\n */\nexport const DEFAULT_FLUSH_TIMEOUT_MS = 5000;\n\n/**\n * What the error handler receives when the logger-wide redaction itself\n * failed: the entry's identity only, never the unredacted message or context.\n */\nfunction redactionFailedEntry(data: LoggingData): LoggingData {\n return {\n type: data.type,\n module: data.module,\n action: data.action,\n message: \"[entry dropped: redaction failed]\",\n };\n}\n\n/**\n * Default {@link ChannelErrorHandler}: one stderr line per failure. Written\n * directly to the stream, never through a logger, so a broken channel cannot\n * recurse.\n */\nfunction reportChannelError(error: unknown, channel: LogContract) {\n const reason = error instanceof Error ? error.message : String(error);\n\n try {\n process.stderr.write(`[@warlock.js/logger] channel \"${channel.name}\" failed to log: ${reason}\\n`);\n } catch {\n // stderr itself is gone; nothing left to report to.\n }\n}\n\n/**\n * The package singleton. Use this for everyday logging — `log.info(...)`,\n * `log.error(...)`, `log.configure(...)`. Custom logger instances can be\n * created by instantiating `Logger` directly.\n *\n * The name is intentionally short: `log` reads naturally at the call site\n * (`log.info(\"auth\", \"login\", \"ok\")`) and matches the convention used in\n * pino, bunyan, and most JS logging tutorials.\n *\n * Note that `log` is a `Logger` instance, **not** a function — the bare\n * callable form was removed when the dual `log` / `logger` exports were\n * collapsed into a single name. Use `log.info(...)` (or any other level\n * shortcut) to emit entries.\n */\nexport const log = new Logger();\n"],"mappings":";;;;;;AAcA,MAAM,gBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AASD,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,IAAa,SAAb,MAAoB;;kBAIc,CAAC;YAErB,YAAY,OAAO,OAAO,EAAE;2CAOZ,IAAI,IAAgC;2CAwBpC,IAAI,IAA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IAAI;EACF,QAAQ,OAAO,MAAM,iCAAiC,QAAQ,KAAK,mBAAmB,OAAO,GAAG;CAClG,QAAQ,CAER;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,MAAM,IAAI,OAAO"}
1
+ {"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../packages/logger/src/logger.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport type { LogChannel } from \"./log-channel\";\nimport { applyRedact, mergeRedact } from \"./redact\";\nimport type {\n AutoFlushEvent,\n ChannelErrorHandler,\n LogContract,\n LoggingData,\n LogLevel,\n OmittedLoggingData,\n RedactConfig,\n} from \"./types\";\nimport { clearMessage } from \"./utils/clear-message\";\n\nconst SIGNAL_EVENTS: ReadonlySet<AutoFlushEvent> = new Set([\n \"SIGINT\",\n \"SIGTERM\",\n \"SIGHUP\",\n \"SIGBREAK\",\n \"SIGUSR2\",\n]);\n\n/**\n * Severity ranks used by `setMinLevel`. Higher number = more severe. The\n * ordering matches conventional log-level hierarchies: `debug` is noisiest\n * and easiest to drop; `error` is the loudest and never dropped by the\n * minimum-level filter. `success` sits beside `info` — it's an informational\n * outcome, not a warning.\n */\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n success: 1,\n warn: 2,\n error: 3,\n fatal: 4,\n};\n\nexport class Logger {\n /**\n * Current channel\n */\n public channels: LogChannel[] = [];\n\n public id = \"logger-\" + Random.string(32);\n\n /**\n * Registered auto-flush handlers, keyed by event name. Stored so repeated\n * calls to `enableAutoFlush` replace rather than stack, and so\n * `disableAutoFlush` can remove them cleanly.\n */\n private autoFlushHandlers = new Map<AutoFlushEvent, () => void>();\n\n /**\n * Logger-wide minimum severity. When set, entries below this level are\n * dropped before any channel is invoked — cheaper than per-channel `levels`\n * filters because the fan-out loop is skipped entirely. `undefined` means\n * no minimum (every entry reaches every channel that accepts it).\n */\n private minLevel?: LogLevel;\n\n /**\n * Logger-wide redaction floor. Applied once before fan-out — every\n * channel receives an entry with these paths already censored. Channel\n * configs can extend the path list (additive); they cannot remove paths\n * set here.\n */\n private redactConfig?: RedactConfig;\n\n /**\n * Deliveries still in flight on async channels, per channel. `log()` never\n * awaits them; `flush()` does, so a graceful shutdown still waits for every\n * entry. Kept per channel so one hung channel cannot hold up another's\n * drain.\n */\n private pendingDeliveries = new Map<LogChannel, Set<Promise<void>>>();\n\n /**\n * Receives a channel's delivery failure (a sync throw or a rejected async\n * `log()`). Defaults to a single stderr line, never back through the logger.\n */\n private channelErrorHandler: ChannelErrorHandler = reportChannelError;\n\n /**\n * Add a new channel\n */\n public addChannel(channel: LogChannel) {\n this.channels.push(this.attachChannel(channel));\n\n return this;\n }\n\n /**\n * Set base configurations\n */\n public configure(config: {\n channels?: LogChannel[];\n autoFlushOn?: AutoFlushEvent[];\n minLevel?: LogLevel;\n redact?: RedactConfig;\n onChannelError?: ChannelErrorHandler;\n }) {\n if (config.channels) {\n this.setChannels(config.channels);\n }\n\n if (config.autoFlushOn) {\n this.enableAutoFlush(config.autoFlushOn);\n }\n\n if (config.minLevel !== undefined) {\n this.setMinLevel(config.minLevel);\n }\n\n if (config.redact !== undefined) {\n this.setRedact(config.redact);\n }\n\n if (config.onChannelError) {\n this.onChannelError(config.onChannelError);\n }\n\n return this;\n }\n\n /**\n * Handle a channel's delivery failure. Logging is fire-and-forget, so a\n * channel that throws or rejects never reaches the call site and never\n * becomes an unhandled rejection; it goes to this handler instead. The\n * default writes one line to stderr. The handler must not log through this\n * logger (a failing channel would loop).\n *\n * @example\n * log.onChannelError((error, channel) => metrics.increment(`log.${channel.name}.failed`));\n */\n public onChannelError(handler: ChannelErrorHandler): this {\n this.channelErrorHandler = handler;\n return this;\n }\n\n /**\n * Set the logger-wide redaction floor. Applied to every entry before\n * fan-out; channel configs add more paths on top, never fewer. Pass\n * `undefined` to clear.\n *\n * @example\n * log.setRedact({\n * paths: [\"context.password\", \"context.*.token\"],\n * censor: \"[REDACTED]\",\n * });\n */\n public setRedact(config: RedactConfig | undefined): this {\n this.redactConfig = config;\n return this;\n }\n\n /**\n * Read the active logger-wide redact config (or `undefined`).\n */\n public getRedact(): RedactConfig | undefined {\n return this.redactConfig;\n }\n\n /**\n * Drop every entry whose severity is below `level` before fan-out. Cheaper\n * than per-channel `levels` filters because the loop never runs and no\n * channel receives the entry. Pass `undefined` to clear and accept all\n * levels again.\n *\n * @example\n * // production: silence debug noise everywhere at once\n * logger.setMinLevel(\"info\");\n */\n public setMinLevel(level: LogLevel | undefined): this {\n this.minLevel = level;\n return this;\n }\n\n /**\n * Read the active minimum severity (or `undefined` when none is set).\n */\n public getMinLevel(): LogLevel | undefined {\n return this.minLevel;\n }\n\n /**\n * Set channels\n */\n public setChannels(channels: LogChannel[]) {\n this.channels = channels;\n\n for (const channel of channels) {\n this.attachChannel(channel);\n }\n\n return this;\n }\n\n /**\n * Route a channel's own failures (outside `log()`, such as file retention)\n * to this logger's channel error handler.\n */\n private attachChannel(channel: LogChannel): LogChannel {\n if (typeof channel.setErrorReporter === \"function\") {\n channel.setErrorReporter((error, entry) => this.reportChannelError(error, channel, entry));\n }\n\n return channel;\n }\n\n /**\n * Normalize log data to a single object\n */\n private normalizeLogData(\n dataOrModule: LoggingData | OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n level?: LogLevel,\n context?: Record<string, any>,\n ): LoggingData {\n if (typeof dataOrModule === \"object\") {\n // If level is provided, override type\n return {\n type: (level || (dataOrModule as any).type || \"info\") as LogLevel,\n module: dataOrModule.module,\n action: dataOrModule.action,\n message: dataOrModule.message,\n ...(context ? { context } : dataOrModule.context ? { context: dataOrModule.context } : {}),\n };\n }\n return {\n type: (level || \"info\") as LogLevel,\n module: dataOrModule,\n action: action as string,\n message,\n ...(context ? { context } : {}),\n };\n }\n\n /**\n * Make log\n *\n * Fans out a single log entry to every registered channel. Non-terminal\n * channels receive a copy whose `message` has had ANSI color codes stripped\n * — each channel sees its own shallow clone so one channel cannot observe\n * another's mutations (e.g. a later terminal channel still sees the original\n * colored message).\n *\n * Synchronous and fire-and-forget: it returns the logger, not a promise.\n * Async channel deliveries are tracked and awaited by {@link flush}; a\n * channel that throws or rejects is isolated from the others and reported\n * to {@link onChannelError}.\n */\n public log(data: LoggingData): this {\n if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) {\n return this;\n }\n\n // Apply the logger-wide redact floor once. Every channel sees the\n // result; no channel can undo a logger-wide redaction (additive-only\n // semantics). A redaction that throws (a bad censor function) drops the\n // entry: delivering it unredacted would leak exactly what the config\n // exists to hide.\n let baseEntry: LoggingData;\n\n try {\n baseEntry = applyRedact(data, this.redactConfig);\n } catch (error) {\n for (const channel of this.channels) {\n this.reportChannelError(error, channel, redactionFailedEntry(data));\n }\n\n return this;\n }\n\n for (const channel of this.channels) {\n this.deliver(channel, data, baseEntry);\n }\n\n return this;\n }\n\n /**\n * Prepare and hand one entry to one channel, isolating its failure (a\n * channel redaction that throws included) and tracking an async delivery\n * until it settles.\n */\n private deliver(channel: LogChannel, data: LoggingData, baseEntry: LoggingData) {\n let payload: LoggingData = baseEntry;\n let result: void | Promise<void>;\n\n try {\n const channelRedact = channel.getRedactConfig?.();\n\n // When the channel adds paths, redact again from `data` rather than\n // from `baseEntry` so the merged config (which already contains the\n // logger-wide paths) does the full pass — avoids double-cloning the\n // already-redacted base.\n if (channelRedact) {\n payload = applyRedact(data, mergeRedact(this.redactConfig, channelRedact));\n }\n\n if (channel.terminal === false) {\n payload = { ...payload, message: clearMessage(payload.message) };\n }\n\n result = channel.log(payload);\n } catch (error) {\n // `payload` is the logger-wide redacted entry until the channel's own\n // redaction succeeded, so the handler never sees less-redacted data\n // than some channel would have.\n this.reportChannelError(error, channel, payload);\n return;\n }\n\n if (!result || typeof (result as Promise<void>).then !== \"function\") {\n return;\n }\n\n let pending = this.pendingDeliveries.get(channel);\n\n if (!pending) {\n pending = new Set();\n this.pendingDeliveries.set(channel, pending);\n }\n\n const tracked = pending;\n const delivery: Promise<void> = Promise.resolve(result)\n .catch((error) => this.reportChannelError(error, channel, payload))\n .finally(() => {\n tracked.delete(delivery);\n\n if (tracked.size === 0 && this.pendingDeliveries.get(channel) === tracked) {\n this.pendingDeliveries.delete(channel);\n }\n });\n\n tracked.add(delivery);\n }\n\n private reportChannelError(error: unknown, channel: LogContract, entry: LoggingData) {\n try {\n const outcome: unknown = this.channelErrorHandler(error, channel, entry);\n\n // An async handler that rejects must not become an unhandled rejection\n // (which an app may route straight back into this logger).\n if (outcome && typeof (outcome as Promise<unknown>).then === \"function\") {\n (outcome as Promise<unknown>).then(undefined, () => {});\n }\n } catch {\n // An error handler that throws must not turn logging into a crash.\n }\n }\n\n /**\n * Make debug log\n */\n public debug(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"debug\", context);\n return this.log(data);\n }\n\n /**\n * Make info log\n */\n public info(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"info\", context);\n return this.log(data);\n }\n\n /**\n * Make warn log\n */\n public warn(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"warn\", context);\n return this.log(data);\n }\n\n /**\n * Make error log\n */\n public error(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"error\", context);\n return this.log(data);\n }\n\n /**\n * Make success log\n */\n public success(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"success\", context);\n\n return this.log(data);\n }\n\n /**\n * Make fatal log — for unrecoverable failures where the application is going\n * down (failed bootstrap, lost connection to a required dependency that the\n * caller has decided not to retry, an `uncaughtException`).\n *\n * Identical shape to {@link error}; the level is purely informational —\n * `fatal` does NOT auto-flush or exit. The caller decides whether to call\n * `await log.flush()` and `process.exit(...)`.\n */\n public fatal(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"fatal\", context);\n\n return this.log(data);\n }\n\n /**\n * Log an `error` entry when `condition` is falsy. No-op otherwise — the\n * entry is never built and channels are not invoked, so this is genuinely\n * free in the happy path. Mirrors the spirit of `console.assert` but routes\n * through the logger pipeline so persistent channels capture failures.\n *\n * @example\n * log.assert(user !== null, \"auth\", \"session\", \"user vanished mid-flight\", { sessionId });\n */\n public assert(\n condition: unknown,\n module: string,\n action: string,\n message: any,\n context?: Record<string, any>,\n ): this {\n if (condition) return this;\n return this.error(module, action, message, context);\n }\n\n /**\n * Start a duration timer. The returned function emits an `info` entry\n * with `completed in <ms>ms` and a `durationMs` field in `context` when\n * called. Pass an object to `end()` to merge extra fields into context.\n *\n * @example\n * const end = log.timer(\"db\", \"users.findById\");\n * const user = await usersRepo.findById(id);\n * end({ id, found: !!user });\n */\n public timer(module: string, action: string): (extra?: Record<string, any>) => this {\n const startedAt = Date.now();\n return (extra?: Record<string, any>) => {\n const durationMs = Date.now() - startedAt;\n return this.info(module, action, `completed in ${durationMs}ms`, {\n durationMs,\n ...(extra ?? {}),\n });\n };\n }\n\n /**\n * Get channel by name\n */\n public channel(name: string) {\n return this.channels.find((channel) => channel.name === name);\n }\n\n /**\n * Synchronously flush logs\n */\n public flushSync() {\n for (const channel of this.channels) {\n if (channel.flushSync) {\n channel.flushSync();\n }\n }\n }\n\n /**\n * Wait for every in-flight async delivery, then drain every channel that\n * implements `flush()` — bounded by `timeout` (default\n * {@link DEFAULT_FLUSH_TIMEOUT_MS}).\n *\n * Unlike {@link flushSync}, this awaits each channel's async I/O — the\n * correct call for a graceful shutdown that can afford to wait\n * (`await log.flush()` after closing the HTTP server, before\n * `process.exit`). A channel whose delivery is async (a network transport,\n * an async disk write) implements `flush()`, not `flushSync()`.\n *\n * Channels drain concurrently and independently: each waits for its own\n * pending deliveries (including ones logged while the flush runs), then\n * runs its `flush()`. A channel whose delivery hangs therefore cannot hold\n * up another channel's drain, and a channel whose flush rejects can neither\n * stop the others nor escape as an unhandled rejection. When `timeout`\n * elapses, `flush()` resolves anyway and each channel still draining is\n * reported to {@link onChannelError}. Channels without `flush()` only wait\n * for their deliveries.\n *\n * @example\n * async function shutdown() {\n * await httpServer.close();\n * await log.flush({ timeout: 3000 });\n * process.exit(0);\n * }\n */\n public async flush(options: { timeout?: number } = {}): Promise<void> {\n const timeout = options.timeout ?? DEFAULT_FLUSH_TIMEOUT_MS;\n const draining = new Set<LogChannel>(this.channels);\n\n for (const channel of this.pendingDeliveries.keys()) {\n draining.add(channel);\n }\n\n const unfinished = new Set(draining);\n\n const drains = [...draining].map(async (channel) => {\n try {\n await this.drainChannel(channel);\n } catch {\n // A single channel must never break shutdown for the others —\n // a graceful drain is best-effort across every channel.\n } finally {\n unfinished.delete(channel);\n }\n });\n\n const settled = Promise.allSettled(drains).then(() => false);\n\n // `Infinity` (or any non-finite value) waits without a limit; setTimeout\n // would otherwise overflow it to an immediate timeout.\n if (!Number.isFinite(timeout)) {\n await settled;\n return;\n }\n\n let resolveTimeout!: (timedOut: boolean) => void;\n const timeoutReached = new Promise<boolean>((resolve) => {\n resolveTimeout = resolve;\n });\n const timer = setTimeout(() => resolveTimeout(true), Math.max(0, timeout));\n\n // Never keep the process alive just to time a flush out.\n (timer as { unref?: () => void }).unref?.();\n\n const timedOut = await Promise.race([settled, timeoutReached]);\n\n clearTimeout(timer);\n\n if (!timedOut) return;\n\n for (const channel of unfinished) {\n this.reportChannelError(\n new Error(`flush timed out after ${timeout}ms; entries still in flight may be lost`),\n channel,\n { type: \"warn\", module: \"logger\", action: \"flush\", message: \"flush timed out\" },\n );\n }\n }\n\n /**\n * Wait until the channel has no delivery in flight, run its `flush()`, and\n * repeat while that flush let new deliveries in.\n */\n private async drainChannel(channel: LogChannel) {\n do {\n let pending = this.pendingDeliveries.get(channel);\n\n while (pending && pending.size > 0) {\n await Promise.allSettled([...pending]);\n pending = this.pendingDeliveries.get(channel);\n }\n\n if (channel.flush) {\n await channel.flush();\n }\n } while ((this.pendingDeliveries.get(channel)?.size ?? 0) > 0);\n }\n\n /**\n * Register one process-level handler per event that calls `flushSync()`\n * before the process terminates.\n *\n * For signal events (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGBREAK`, `SIGUSR2`)\n * the handler flushes and then re-raises the signal so Node's default exit\n * behavior runs. For `beforeExit`, the handler flushes in place — Node exits\n * naturally afterwards.\n *\n * Idempotent: calling with the same events replaces the previous handlers.\n * Call `disableAutoFlush()` to unregister.\n *\n * @example\n * log.configure({\n * channels: [new ConsoleLog(), new FileLog()],\n * autoFlushOn: [\"SIGINT\", \"SIGTERM\", \"beforeExit\"],\n * });\n */\n public enableAutoFlush(events: AutoFlushEvent[]): this {\n this.disableAutoFlush();\n\n for (const event of events) {\n const handler = SIGNAL_EVENTS.has(event)\n ? () => {\n this.flushSync();\n process.off(event, handler);\n process.kill(process.pid, event as NodeJS.Signals);\n }\n : () => {\n this.flushSync();\n };\n\n process.on(event, handler);\n this.autoFlushHandlers.set(event, handler);\n }\n\n return this;\n }\n\n /**\n * Remove every handler previously registered by `enableAutoFlush`.\n * Safe to call when no handlers are registered.\n */\n public disableAutoFlush(): this {\n for (const [event, handler] of this.autoFlushHandlers) {\n process.off(event, handler);\n }\n\n this.autoFlushHandlers.clear();\n\n return this;\n }\n}\n\n/**\n * Default `timeout` of {@link Logger.flush}: long enough for a healthy network\n * channel, short enough that a hung one cannot eat a shutdown budget.\n */\nexport const DEFAULT_FLUSH_TIMEOUT_MS = 5000;\n\n/**\n * What the error handler receives when the logger-wide redaction itself\n * failed: the entry's identity only, never the unredacted message or context.\n */\nfunction redactionFailedEntry(data: LoggingData): LoggingData {\n return {\n type: data.type,\n module: data.module,\n action: data.action,\n message: \"[entry dropped: redaction failed]\",\n };\n}\n\n/**\n * Default {@link ChannelErrorHandler}: one stderr line per failure. Written\n * directly to the stream, never through a logger, so a broken channel cannot\n * recurse.\n */\nfunction reportChannelError(error: unknown, channel: LogContract) {\n const reason = error instanceof Error ? error.message : String(error);\n\n try {\n process.stderr.write(\n `[@warlock.js/logger] channel \"${channel.name}\" failed to log: ${reason}\\n`,\n );\n } catch {\n // stderr itself is gone; nothing left to report to.\n }\n}\n\n/**\n * The package singleton. Use this for everyday logging — `log.info(...)`,\n * `log.error(...)`, `log.configure(...)`. Custom logger instances can be\n * created by instantiating `Logger` directly.\n *\n * The name is intentionally short: `log` reads naturally at the call site\n * (`log.info(\"auth\", \"login\", \"ok\")`) and matches the convention used in\n * pino, bunyan, and most JS logging tutorials.\n *\n * Note that `log` is a `Logger` instance, **not** a function — the bare\n * callable form was removed when the dual `log` / `logger` exports were\n * collapsed into a single name. Use `log.info(...)` (or any other level\n * shortcut) to emit entries.\n */\nexport const log = new Logger();\n"],"mappings":";;;;;;AAcA,MAAM,gCAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AASD,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,IAAa,SAAb,MAAoB;;kBAIc,CAAC;YAErB,YAAY,OAAO,OAAO,EAAE;2CAOZ,IAAI,IAAgC;2CAwBpC,IAAI,IAAoC;6BAMjB;;;;;CAKnD,AAAO,WAAW,SAAqB;EACrC,KAAK,SAAS,KAAK,KAAK,cAAc,OAAO,CAAC;EAE9C,OAAO;CACT;;;;CAKA,AAAO,UAAU,QAMd;EACD,IAAI,OAAO,UACT,KAAK,YAAY,OAAO,QAAQ;EAGlC,IAAI,OAAO,aACT,KAAK,gBAAgB,OAAO,WAAW;EAGzC,IAAI,OAAO,aAAa,QACtB,KAAK,YAAY,OAAO,QAAQ;EAGlC,IAAI,OAA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ACF,QAAQ,CAER;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,MAAM,IAAI,OAAO"}
@@ -42,7 +42,7 @@
42
42
  * non-alphanumeric character. Collapses `apiKey`, `api_key`, `API-KEY`,
43
43
  * `Api Key` and `apikey` onto a single entry.
44
44
  */
45
- declare function normalizeRedactKey(key: string): string;
45
+ export declare function normalizeRedactKey(key: string): string;
46
46
  /**
47
47
  * The default denylist, in source spelling. Anything whose normalized key
48
48
  * matches one of these is replaced by the configured censor (`"[REDACTED]"`
@@ -52,12 +52,11 @@ declare function normalizeRedactKey(key: string): string;
52
52
  * Exported so applications can inspect, log, or build on the exact set they
53
53
  * are getting rather than guessing at it.
54
54
  */
55
- declare const DEFAULT_REDACT_KEYS: readonly string[];
55
+ export declare const DEFAULT_REDACT_KEYS: readonly string[];
56
56
  /**
57
57
  * The default denylist, pre-normalized. Frozen at module load so the hot path
58
58
  * never rebuilds it.
59
59
  */
60
- declare const DEFAULT_REDACT_KEY_SET: ReadonlySet<string>;
60
+ export declare const DEFAULT_REDACT_KEY_SET: ReadonlySet<string>;
61
61
  //#endregion
62
- export { DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, normalizeRedactKey };
63
62
  //# sourceMappingURL=default-keys.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"default-keys.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/default-keys.ts"],"mappings":";;AA4CA;;;;AAA8C;AAa9C;;;;AAqEC;AAMD;;;;AAAgD;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAxFhC,kBAAA,CAAmB,GAAW;;;;;;;;;;cAajC,mBAAA;;;;;cA2EA,sBAAA,EAAwB,WAAW"}
1
+ {"version":3,"file":"default-keys.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/default-keys.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA4CgB,mBAAmB;;;;;;;;;;qBAatB;;;;;qBA2EA,wBAAwB"}
@@ -0,0 +1,25 @@
1
+ //#region ../../packages/logger/src/redact/escape-log-value.d.ts
2
+ export type EscapeLogValueOptions = {
3
+ /**
4
+ * Longest result, in characters. Longer values are cut and end with
5
+ * `…[truncated]`. Unlimited by default.
6
+ */
7
+ maxLength?: number;
8
+ };
9
+ /**
10
+ * Make client-controlled text safe to put inside a log line: line breaks and
11
+ * tabs become the visible escapes `\r`, `\n`, `\t`, other control characters
12
+ * (including NUL, DEL, C1 controls and the Unicode line/paragraph separators)
13
+ * become `\uXXXX`, and ANSI terminal escape sequences are removed.
14
+ *
15
+ * Without it, a user agent or form field containing `\n2026-01-01 [info] …`
16
+ * writes a forged entry into a text log, and an ANSI sequence can rewrite what
17
+ * a terminal shows. Structured channels (JSON) are not affected, but console
18
+ * and file channels are.
19
+ *
20
+ * @example
21
+ * log.info("auth", "login", `Login from ${escapeLogValue(request.userAgent)}`);
22
+ */
23
+ export declare function escapeLogValue(value: unknown, options?: EscapeLogValueOptions): string;
24
+ //#endregion
25
+ //# sourceMappingURL=escape-log-value.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escape-log-value.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/escape-log-value.ts"],"mappings":";YAWY;;;;;EAKV;;;;;;;;;;;;;;;;wBAiBc,eAAe,gBAAgB,UAAS"}
@@ -0,0 +1,37 @@
1
+ //#region ../../packages/logger/src/redact/escape-log-value.ts
2
+ /**
3
+ * ANSI escape sequences: CSI (`ESC [ … final`) and the two-character
4
+ * `ESC x` escapes (`ESC c` resets a terminal). Bounded so matching stays linear on long input.
5
+ */
6
+ const ANSI_ESCAPE = /\u001b(?:\[[0-?]{0,32}[ -/]{0,8}[@-~]|[0-~])/g;
7
+ /** Control characters that are not already handled as `\r`, `\n` or `\t`. */
8
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u2028\u2029]/g;
9
+ /**
10
+ * Make client-controlled text safe to put inside a log line: line breaks and
11
+ * tabs become the visible escapes `\r`, `\n`, `\t`, other control characters
12
+ * (including NUL, DEL, C1 controls and the Unicode line/paragraph separators)
13
+ * become `\uXXXX`, and ANSI terminal escape sequences are removed.
14
+ *
15
+ * Without it, a user agent or form field containing `\n2026-01-01 [info] …`
16
+ * writes a forged entry into a text log, and an ANSI sequence can rewrite what
17
+ * a terminal shows. Structured channels (JSON) are not affected, but console
18
+ * and file channels are.
19
+ *
20
+ * @example
21
+ * log.info("auth", "login", `Login from ${escapeLogValue(request.userAgent)}`);
22
+ */
23
+ function escapeLogValue(value, options = {}) {
24
+ let text = typeof value === "string" ? value : String(value);
25
+ const maxLength = options.maxLength;
26
+ let truncated = false;
27
+ if (maxLength !== void 0 && maxLength >= 0 && text.length > maxLength) {
28
+ text = text.slice(0, maxLength);
29
+ truncated = true;
30
+ }
31
+ const escaped = text.replace(ANSI_ESCAPE, "").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(CONTROL, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
32
+ return truncated ? `${escaped}…[truncated]` : escaped;
33
+ }
34
+
35
+ //#endregion
36
+ export { escapeLogValue };
37
+ //# sourceMappingURL=escape-log-value.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escape-log-value.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/redact/escape-log-value.ts"],"sourcesContent":["/**\n * ANSI escape sequences: CSI (`ESC [ … final`) and the two-character\n * `ESC x` escapes (`ESC c` resets a terminal). Bounded so matching stays linear on long input.\n */\n// oxlint-disable-next-line eslint/no-control-regex -- matching terminal escapes is the point.\nconst ANSI_ESCAPE = /\\u001b(?:\\[[0-?]{0,32}[ -/]{0,8}[@-~]|[0-~])/g;\n\n/** Control characters that are not already handled as `\\r`, `\\n` or `\\t`. */\n// oxlint-disable-next-line eslint/no-control-regex -- escaping control characters is the point.\nconst CONTROL = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g;\n\nexport type EscapeLogValueOptions = {\n /**\n * Longest result, in characters. Longer values are cut and end with\n * `…[truncated]`. Unlimited by default.\n */\n maxLength?: number;\n};\n\n/**\n * Make client-controlled text safe to put inside a log line: line breaks and\n * tabs become the visible escapes `\\r`, `\\n`, `\\t`, other control characters\n * (including NUL, DEL, C1 controls and the Unicode line/paragraph separators)\n * become `\\uXXXX`, and ANSI terminal escape sequences are removed.\n *\n * Without it, a user agent or form field containing `\\n2026-01-01 [info] …`\n * writes a forged entry into a text log, and an ANSI sequence can rewrite what\n * a terminal shows. Structured channels (JSON) are not affected, but console\n * and file channels are.\n *\n * @example\n * log.info(\"auth\", \"login\", `Login from ${escapeLogValue(request.userAgent)}`);\n */\nexport function escapeLogValue(value: unknown, options: EscapeLogValueOptions = {}): string {\n let text = typeof value === \"string\" ? value : String(value);\n\n const maxLength = options.maxLength;\n let truncated = false;\n if (maxLength !== undefined && maxLength >= 0 && text.length > maxLength) {\n text = text.slice(0, maxLength);\n truncated = true;\n }\n\n const escaped = text\n .replace(ANSI_ESCAPE, \"\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\t/g, \"\\\\t\")\n .replace(CONTROL, (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`);\n\n return truncated ? `${escaped}…[truncated]` : escaped;\n}\n"],"mappings":";;;;;AAKA,MAAM,cAAc;;AAIpB,MAAM,UAAU;;;;;;;;;;;;;;;AAwBhB,SAAgB,eAAe,OAAgB,UAAiC,CAAC,GAAW;CAC1F,IAAI,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;CAE3D,MAAM,YAAY,QAAQ;CAC1B,IAAI,YAAY;CAChB,IAAI,cAAc,UAAa,aAAa,KAAK,KAAK,SAAS,WAAW;EACxE,OAAO,KAAK,MAAM,GAAG,SAAS;EAC9B,YAAY;CACd;CAEA,MAAM,UAAU,KACb,QAAQ,aAAa,EAAE,CAAC,CACxB,QAAQ,OAAO,KAAK,CAAC,CACrB,QAAQ,OAAO,KAAK,CAAC,CACrB,QAAQ,OAAO,KAAK,CAAC,CACrB,QAAQ,UAAU,SAAS,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG;CAEtF,OAAO,YAAY,GAAG,QAAQ,gBAAgB;AAChD"}
@@ -1,5 +1,6 @@
1
1
  import { DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, normalizeRedactKey } from "./default-keys.mjs";
2
2
  import { applyRedact, mergeRedact, resolveRedactKeys } from "./redact.mjs";
3
+ import { escapeLogValue } from "./escape-log-value.mjs";
3
4
  import { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText } from "./mask-email.mjs";
4
5
 
5
- export { };
6
+ export { DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, MASK_EMAILS_MAX_LENGTH, applyRedact, escapeLogValue, maskEmail, maskEmailsInText, mergeRedact, normalizeRedactKey, resolveRedactKeys };
@@ -4,7 +4,7 @@
4
4
  * replaced by a marker, so a huge cache key or message cannot cost more than a
5
5
  * bounded amount of time per log line, and nothing past the cut can leak.
6
6
  */
7
- declare const MASK_EMAILS_MAX_LENGTH = 16384;
7
+ export declare const MASK_EMAILS_MAX_LENGTH = 16384;
8
8
  /**
9
9
  * Mask one email address, keeping its first character and its domain:
10
10
  * `member@example.com` → `m***@example.com`. A value without an `@` is
@@ -16,7 +16,7 @@ declare const MASK_EMAILS_MAX_LENGTH = 16384;
16
16
  * @example
17
17
  * log.info("mail", "send", `Sending mail to: ${maskEmail(to)}`);
18
18
  */
19
- declare function maskEmail(address: string): string;
19
+ export declare function maskEmail(address: string): string;
20
20
  /**
21
21
  * Mask every email address the pattern above recognises in a piece of text
22
22
  * with {@link maskEmail}. Text longer than {@link MASK_EMAILS_MAX_LENGTH}
@@ -34,7 +34,6 @@ declare function maskEmail(address: string): string;
34
34
  * maskEmailsInText("sent to member@example.com") // "sent to m***@example.com"
35
35
  * maskEmailsInText("email.member@example.com") // "e***@example.com"
36
36
  */
37
- declare function maskEmailsInText(text: string): string;
37
+ export declare function maskEmailsInText(text: string): string;
38
38
  //#endregion
39
- export { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText };
40
39
  //# sourceMappingURL=mask-email.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mask-email.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/mask-email.ts"],"mappings":";;AAoBA;;;;cAAa,sBAAA;AAab;;;;AAAyC;AA4BzC;;;;AAA6C;;AA5B7C,iBAAgB,SAAA,CAAU,OAAe;;;;;;;;;;;;;;;;;;iBA4BzB,gBAAA,CAAiB,IAAY"}
1
+ {"version":3,"file":"mask-email.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/mask-email.ts"],"mappings":";;;;;;qBAoBa;;;;;;;;;;;;wBAaG,UAAU;;;;;;;;;;;;;;;;;;wBA4BV,iBAAiB"}
@@ -1,5 +1,4 @@
1
1
  import { LoggingData, RedactConfig } from "../types.mjs";
2
-
3
2
  //#region ../../packages/logger/src/redact/redact.d.ts
4
3
  /**
5
4
  * Resolve the effective key denylist for a config: the built-in set (unless
@@ -8,7 +7,7 @@ import { LoggingData, RedactConfig } from "../types.mjs";
8
7
  * Returns `undefined` only when there is nothing to match — i.e. defaults are
9
8
  * explicitly off and no custom keys were supplied.
10
9
  */
11
- declare function resolveRedactKeys(config: RedactConfig | undefined): ReadonlySet<string> | undefined;
10
+ export declare function resolveRedactKeys(config: RedactConfig | undefined): ReadonlySet<string> | undefined;
12
11
  /**
13
12
  * Produce a new `LoggingData` with sensitive data censored:
14
13
  *
@@ -37,7 +36,7 @@ declare function resolveRedactKeys(config: RedactConfig | undefined): ReadonlySe
37
36
  * client that exposes request config behind a getter still slips through.
38
37
  * Enumerable ones (axios's `.config`, `.response`) *are* covered.
39
38
  */
40
- declare function applyRedact(data: LoggingData, config: RedactConfig | undefined): LoggingData;
39
+ export declare function applyRedact(data: LoggingData, config: RedactConfig | undefined): LoggingData;
41
40
  /**
42
41
  * Combine two redact configs into one effective config. Used to merge a
43
42
  * channel's additive paths on top of the logger-wide floor.
@@ -52,7 +51,6 @@ declare function applyRedact(data: LoggingData, config: RedactConfig | undefined
52
51
  * choice is inherited — opting out logger-wide is not quietly undone by
53
52
  * any channel that happens to set a `redact` option.
54
53
  */
55
- declare function mergeRedact(base: RedactConfig | undefined, extra: RedactConfig | undefined): RedactConfig | undefined;
54
+ export declare function mergeRedact(base: RedactConfig | undefined, extra: RedactConfig | undefined): RedactConfig | undefined;
56
55
  //#endregion
57
- export { applyRedact, mergeRedact, resolveRedactKeys };
58
56
  //# sourceMappingURL=redact.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"redact.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/redact.ts"],"mappings":";;;;;AAkVA;;;;;iBAAgB,iBAAA,CACd,MAAA,EAAQ,YAAA,eACP,WAAW;;;AAAA;AAiDd;;;;;;;;;;;;;;AAGc;AAgDd;;;;;;;;;;iBAnDgB,WAAA,CACd,IAAA,EAAM,WAAA,EACN,MAAA,EAAQ,YAAA,eACP,WAAA;;;;AAmDY;;;;;;;;;;;iBAHC,WAAA,CACd,IAAA,EAAM,YAAA,cACN,KAAA,EAAO,YAAA,eACN,YAAA"}
1
+ {"version":3,"file":"redact.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/redact.ts"],"mappings":";;;;;;;;;wBA+UgB,kBACd,QAAQ,2BACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiDa,YAAY,MAAM,aAAa,QAAQ,2BAA2B;;;;;;;;;;;;;;;wBAgDlE,YACd,MAAM,0BACN,OAAO,2BACN"}
@@ -1 +1 @@
1
- {"version":3,"file":"redact.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/redact/redact.ts"],"sourcesContent":["import type { LoggingData, RedactCensor, RedactConfig } from \"../types\";\nimport {\n DEFAULT_REDACT_KEY_SET,\n normalizeRedactKey,\n} from \"./default-keys\";\n\nconst DEFAULT_CENSOR = \"[REDACTED]\";\n\n/**\n * Per-key redaction settings threaded through the clone walk. Absent when the\n * walk is a plain structural clone (path-only redaction).\n */\ntype KeyRedaction = {\n /** Normalized key names to censor wherever they appear. */\n keys: ReadonlySet<string>;\n censor: RedactCensor;\n /**\n * Dotted paths the path-glob pass already censored. Skipped here so a\n * function censor is never invoked twice on the same leaf (the second call\n * would receive the already-masked value, not the original).\n */\n alreadyCensored: ReadonlySet<string>;\n};\n\n/**\n * Values we copy by reference rather than walking. Expanding these with\n * `Object.keys` would be destructive, not protective — a `Buffer` becomes a\n * multi-thousand-key index map, a `Map`/`Set`/`RegExp` becomes `{}`. Their\n * contents are consequently *not* reachable by redaction; see the residual\n * gaps documented on `applyRedact`.\n */\nfunction isOpaque(value: object): boolean {\n return (\n ArrayBuffer.isView(value) ||\n value instanceof ArrayBuffer ||\n value instanceof Map ||\n value instanceof Set ||\n value instanceof WeakMap ||\n value instanceof WeakSet ||\n value instanceof Promise ||\n value instanceof RegExp\n );\n}\n\n/**\n * Deep-clone a value with structural fidelity for log entries — handles plain\n * objects, arrays, `Date`, `Error`, and primitives. Anything else (buffers,\n * maps, sets, promises, regexes) is copied by reference: we only redact\n * through walkable structures anyway, and rebuilding e.g. a `Buffer` would\n * change semantics.\n *\n * Purpose-built rather than reaching for `structuredClone`: `Error` instances\n * lose their `message`/`stack` under `structuredClone` in some Node versions,\n * and the logger pipeline carries them often.\n *\n * When `redaction` is supplied, keys matching its denylist are censored during\n * the same pass — one traversal, not two.\n */\nfunction cloneEntry<T>(\n value: T,\n seen = new WeakMap<object, any>(),\n redaction?: KeyRedaction,\n trail: string[] = [],\n): T {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n const asObject = value as unknown as object;\n\n if (seen.has(asObject)) {\n return seen.get(asObject);\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime()) as unknown as T;\n }\n\n if (isOpaque(asObject)) {\n return value;\n }\n\n if (value instanceof Error) {\n return cloneError(value, seen, redaction, trail) as unknown as T;\n }\n\n if (Array.isArray(value)) {\n const arr: any[] = [];\n seen.set(asObject, arr);\n value.forEach((item, index) => {\n // Array indices are positions, not names — never key-matched, but the\n // trail still carries them so function censors see a usable path.\n arr.push(cloneEntry(item, seen, redaction, [...trail, String(index)]));\n });\n return arr as unknown as T;\n }\n\n const out: Record<string, any> = {};\n seen.set(asObject, out);\n copyOwnKeys(value as Record<string, any>, out, seen, redaction, trail);\n return out as unknown as T;\n}\n\n/**\n * Copy every own enumerable key from `source` onto `target`, censoring the\n * ones the key denylist matches and recursing into the rest.\n */\nfunction copyOwnKeys(\n source: Record<string, any>,\n target: Record<string, any>,\n seen: WeakMap<object, any>,\n redaction: KeyRedaction | undefined,\n trail: string[],\n): void {\n for (const key of Object.keys(source)) {\n const childTrail = [...trail, key];\n\n if (\n redaction &&\n redaction.keys.has(normalizeRedactKey(key)) &&\n !redaction.alreadyCensored.has(childTrail.join(\".\"))\n ) {\n target[key] = applyCensor(source[key], redaction.censor, childTrail);\n continue;\n }\n\n target[key] = cloneEntry(source[key], seen, redaction, childTrail);\n }\n}\n\n/**\n * Clone an `Error`, preserving its own enumerable properties.\n *\n * Those extra properties matter for redaction: HTTP clients (axios, got)\n * attach `.config`/`.request`/`.response` to the errors they throw, and those\n * routinely carry the *outgoing* `Authorization` header of the failed request.\n * Copying them through the walk is what lets the key denylist reach in and\n * censor them — dropping them instead (the pre-4.15.0 behavior) hid the\n * secret only when redaction happened to be configured, and took `.code` and\n * friends with it.\n *\n * `name`/`message`/`stack` are non-enumerable on `Error`, so they are carried\n * over explicitly.\n */\nfunction cloneError(\n value: Error,\n seen: WeakMap<object, any>,\n redaction: KeyRedaction | undefined,\n trail: string[],\n): Error {\n let copy: Error;\n\n try {\n copy = new (value.constructor as ErrorConstructor)(value.message);\n } catch {\n // A subclass whose constructor demands a different signature must not\n // take the whole log call down with it.\n copy = new Error(value.message);\n }\n\n // Assigned rather than trusted to the constructor: a subclass that derives\n // its message from a structured argument (`new HttpError({ detail })`)\n // produces an empty message when replayed with a plain string. Defined\n // non-enumerably to match native `Error`, so the clone serializes with the\n // same shape as the original.\n for (const [key, source] of [\n [\"message\", value.message],\n [\"name\", value.name],\n [\"stack\", value.stack],\n ] as const) {\n Object.defineProperty(copy, key, {\n value: source,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n }\n\n seen.set(value, copy);\n copyOwnKeys(value as unknown as Record<string, any>, copy as any, seen, redaction, trail);\n\n return copy;\n}\n\n/**\n * Apply a single censor decision to a value. String censors are returned\n * verbatim; function censors receive the original value plus the dotted\n * path so callers can implement value-aware redaction (mask all but the\n * last 4 chars, hash, etc.).\n */\nfunction applyCensor(value: any, censor: RedactCensor, path: string[]): any {\n if (typeof censor === \"function\") {\n return censor(value, path.join(\".\"));\n }\n return censor;\n}\n\n/**\n * Walk `target` following the remaining `segments` of a path pattern,\n * replacing matched leaves via `censor`. Operates in place — the caller\n * is responsible for cloning before calling.\n *\n * Every censored leaf's dotted path is recorded in `censored` so a following\n * key-denylist pass can leave it alone.\n *\n * Wildcards:\n * - `*` matches exactly one segment (any key on a plain object, any index\n * on an array — stringified for the path that's passed to a function\n * censor).\n * - `**` matches zero or more segments greedily; the rest of the pattern\n * is then attempted at the current level and at every descendant.\n */\nfunction redactAtPath(\n target: any,\n segments: string[],\n censor: RedactCensor,\n pathTrail: string[],\n censored: Set<string>,\n): void {\n if (target === null || typeof target !== \"object\") {\n return;\n }\n\n if (segments.length === 0) {\n return;\n }\n\n const [head, ...rest] = segments;\n\n if (head === undefined) {\n // The `segments.length === 0` guard above already makes this unreachable,\n // but the compiler cannot narrow a DESTRUCTURED element from a length\n // check, so under `noUncheckedIndexedAccess` `head` is `string |\n // undefined` and every use of it below inherits that.\n //\n // Stated rather than asserted away with `!`, because of what this function\n // is: if `head` were ever undefined, `keysToVisit` would carry an\n // `undefined` key, `target[key]` would read and WRITE the literal property\n // \"undefined\", and the field that was supposed to be censored would be\n // left in the log untouched. A redaction path is the wrong place to be\n // approximately right.\n return;\n }\n\n if (head === \"**\") {\n // Try matching `rest` at the current level (the zero-segment match\n // case), then recurse into every child carrying the `**` forward so\n // it keeps matching at deeper levels too.\n if (rest.length > 0) {\n redactAtPath(target, rest, censor, pathTrail, censored);\n }\n const keys = Array.isArray(target)\n ? target.map((_, index) => String(index))\n : Object.keys(target);\n for (const key of keys) {\n redactAtPath(target[key], segments, censor, [...pathTrail, key], censored);\n }\n return;\n }\n\n const keysToVisit =\n head === \"*\"\n ? Array.isArray(target)\n ? target.map((_, index) => String(index))\n : Object.keys(target)\n : Array.isArray(target)\n ? // Numeric segment can index into an array.\n /^\\d+$/.test(head) && Number(head) < target.length\n ? [head]\n : []\n : Object.prototype.hasOwnProperty.call(target, head)\n ? [head]\n : [];\n\n for (const key of keysToVisit) {\n if (rest.length === 0) {\n const leafTrail = [...pathTrail, key];\n target[key] = applyCensor(target[key], censor, leafTrail);\n censored.add(leafTrail.join(\".\"));\n } else {\n redactAtPath(target[key], rest, censor, [...pathTrail, key], censored);\n }\n }\n}\n\n/**\n * Cheap pre-scan: does this graph contain any denylisted key at all?\n *\n * Lets the default-on key pass stay allocation-free for the overwhelming\n * majority of entries, which carry no secrets — we only pay for a clone when\n * there is actually something to censor. Also keeps `applyRedact`'s\n * \"returns the input by reference when nothing changed\" contract intact.\n */\nfunction hasDenylistedKey(\n value: any,\n keys: ReadonlySet<string>,\n seen = new WeakSet<object>(),\n): boolean {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n\n const asObject = value as object;\n\n if (seen.has(asObject)) return false;\n seen.add(asObject);\n\n if (value instanceof Date || isOpaque(asObject)) {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.some((item) => hasDenylistedKey(item, keys, seen));\n }\n\n for (const key of Object.keys(value)) {\n if (keys.has(normalizeRedactKey(key))) return true;\n if (hasDenylistedKey(value[key], keys, seen)) return true;\n }\n\n return false;\n}\n\n/**\n * Cache of resolved key sets, keyed by the config object they came from.\n * Logger-wide and channel configs are long-lived references, so this makes\n * the per-entry cost a single map lookup. Merged configs (rebuilt per entry\n * by `mergeRedact`) fall out of the `WeakMap` on their own.\n */\nconst keySetCache = new WeakMap<RedactConfig, ReadonlySet<string>>();\n\n/**\n * Resolve the effective key denylist for a config: the built-in set (unless\n * `defaultKeys: false`) plus any `keys` the application added.\n *\n * Returns `undefined` only when there is nothing to match — i.e. defaults are\n * explicitly off and no custom keys were supplied.\n */\nexport function resolveRedactKeys(\n config: RedactConfig | undefined,\n): ReadonlySet<string> | undefined {\n const useDefaults = config?.defaultKeys !== false;\n const extra = config?.keys;\n\n if (!extra || extra.length === 0) {\n return useDefaults ? DEFAULT_REDACT_KEY_SET : undefined;\n }\n\n const cached = config && keySetCache.get(config);\n if (cached) return cached;\n\n const resolved = new Set<string>(useDefaults ? DEFAULT_REDACT_KEY_SET : []);\n for (const key of extra) {\n resolved.add(normalizeRedactKey(key));\n }\n\n if (config) keySetCache.set(config, resolved);\n\n return resolved;\n}\n\n/**\n * Produce a new `LoggingData` with sensitive data censored:\n *\n * 1. every path in `config.paths` (opt-in globs), then\n * 2. every key matching the denylist — the built-in\n * {@link DEFAULT_REDACT_KEYS} plus `config.keys`, at any depth of\n * `context`, `message`, and an `Error`'s own enumerable properties.\n *\n * Step 2 runs **with no config at all**: passing `undefined` still censors\n * `password`, `authorization`, `token`, `apiKey` and friends. Pass\n * `{ defaultKeys: false }` to opt out.\n *\n * Paths run first so a function censor sees the original value rather than a\n * mask; leaves the path pass already censored are skipped by the key pass.\n *\n * The original entry is never mutated — channels and other call sites can\n * hold references to the input safely. Returns the input **by reference**\n * when nothing matched, so the fast path stays allocation-free.\n *\n * ## Residual gaps (by design, documented rather than silently absent)\n *\n * - **Secrets interpolated into a `message` string** (`` `token=${t}` ``)\n * cannot be reached — neither a path nor a key names a substring.\n * - **`Map`/`Set`/`Buffer` contents** are not traversed (see {@link isOpaque}).\n * - **Non-enumerable / getter-backed properties** are not walked, so an HTTP\n * client that exposes request config behind a getter still slips through.\n * Enumerable ones (axios's `.config`, `.response`) *are* covered.\n */\nexport function applyRedact(\n data: LoggingData,\n config: RedactConfig | undefined,\n): LoggingData {\n const paths = config?.paths ?? [];\n const keys = resolveRedactKeys(config);\n\n if (paths.length === 0 && !keys) {\n return data;\n }\n\n const censor = config?.censor ?? DEFAULT_CENSOR;\n\n let result = data;\n const censored = new Set<string>();\n\n if (paths.length > 0) {\n result = cloneEntry(data);\n\n for (const pattern of paths) {\n const segments = pattern.split(\".\").filter((segment) => segment.length > 0);\n if (segments.length === 0) continue;\n redactAtPath(result, segments, censor, [], censored);\n }\n }\n\n if (keys && hasDenylistedKey(result, keys)) {\n result = cloneEntry(result, new WeakMap(), {\n keys,\n censor,\n alreadyCensored: censored,\n });\n }\n\n return result;\n}\n\n/**\n * Combine two redact configs into one effective config. Used to merge a\n * channel's additive paths on top of the logger-wide floor.\n *\n * - `paths` and `keys` are concatenated; duplicates are kept (the matcher\n * tolerates them, and de-duping cross-config would mask a developer typo).\n * - `censor` from the channel wins; falls back to the logger's; falls back\n * to the default `\"[REDACTED]\"`.\n * - `defaultKeys` follows the additive-only contract: a channel can turn the\n * built-in denylist back *on* (`true`) but can never turn off one the\n * logger-wide floor left enabled. When the channel is silent, the logger's\n * choice is inherited — opting out logger-wide is not quietly undone by\n * any channel that happens to set a `redact` option.\n */\nexport function mergeRedact(\n base: RedactConfig | undefined,\n extra: RedactConfig | undefined,\n): RedactConfig | undefined {\n if (!base && !extra) return undefined;\n\n if (!base) {\n // An absent logger-wide config still means \"built-in denylist on\" — it is\n // the floor, not the absence of one. A channel may not switch it off, so\n // its `defaultKeys: false` is overridden here rather than inherited.\n return extra!.defaultKeys === false\n ? { ...extra!, defaultKeys: true }\n : extra;\n }\n\n if (!extra) return base;\n\n return {\n paths: [...(base.paths ?? []), ...(extra.paths ?? [])],\n keys: [...(base.keys ?? []), ...(extra.keys ?? [])],\n defaultKeys: extra.defaultKeys === true ? true : base.defaultKeys,\n censor: extra.censor ?? base.censor,\n };\n}\n"],"mappings":";;;AAMA,MAAM,iBAAiB;;;;;;;;AAyBvB,SAAS,SAAS,OAAwB;CACxC,OACE,YAAY,OAAO,KAAK,KACxB,iBAAiB,eACjB,iBAAiB,OACjB,iBAAiB,OACjB,iBAAiB,WACjB,iBAAiB,WACjB,iBAAiB,WACjB,iBAAiB;AAErB;;;;;;;;;;;;;;;AAgBA,SAAS,WACP,OACA,uBAAO,IAAI,QAAqB,GAChC,WACA,QAAkB,CAAC,GAChB;CACH,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAGT,MAAM,WAAW;CAEjB,IAAI,KAAK,IAAI,QAAQ,GACnB,OAAO,KAAK,IAAI,QAAQ;CAG1B,IAAI,iBAAiB,MACnB,OAAO,IAAI,KAAK,MAAM,QAAQ,CAAC;CAGjC,IAAI,SAAS,QAAQ,GACnB,OAAO;CAGT,IAAI,iBAAiB,OACnB,OAAO,WAAW,OAAO,MAAM,WAAW,KAAK;CAGjD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,MAAa,CAAC;EACpB,KAAK,IAAI,UAAU,GAAG;EACtB,MAAM,SAAS,MAAM,UAAU;GAG7B,IAAI,KAAK,WAAW,MAAM,MAAM,WAAW,CAAC,GAAG,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC;EACvE,CAAC;EACD,OAAO;CACT;CAEA,MAAM,MAA2B,CAAC;CAClC,KAAK,IAAI,UAAU,GAAG;CACtB,YAAY,OAA8B,KAAK,MAAM,WAAW,KAAK;CACrE,OAAO;AACT;;;;;AAMA,SAAS,YACP,QACA,QACA,MACA,WACA,OACM;CACN,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,aAAa,CAAC,GAAG,OAAO,GAAG;EAEjC,IACE,aACA,UAAU,KAAK,IAAI,mBAAmB,GAAG,CAAC,KAC1C,CAAC,UAAU,g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AG;EAAQ,aAAa;CAAK,IAC/B;CAGN,IAAI,CAAC,OAAO,OAAO;CAEnB,OAAO;EACL,OAAO,CAAC,GAAI,KAAK,SAAS,CAAC,GAAI,GAAI,MAAM,SAAS,CAAC,CAAE;EACrD,MAAM,CAAC,GAAI,KAAK,QAAQ,CAAC,GAAI,GAAI,MAAM,QAAQ,CAAC,CAAE;EAClD,aAAa,MAAM,gBAAgB,OAAO,OAAO,KAAK;EACtD,QAAQ,MAAM,UAAU,KAAK;CAC/B;AACF"}
1
+ {"version":3,"file":"redact.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/redact/redact.ts"],"sourcesContent":["import type { LoggingData, RedactCensor, RedactConfig } from \"../types\";\nimport { DEFAULT_REDACT_KEY_SET, normalizeRedactKey } from \"./default-keys\";\n\nconst DEFAULT_CENSOR = \"[REDACTED]\";\n\n/**\n * Per-key redaction settings threaded through the clone walk. Absent when the\n * walk is a plain structural clone (path-only redaction).\n */\ntype KeyRedaction = {\n /** Normalized key names to censor wherever they appear. */\n keys: ReadonlySet<string>;\n censor: RedactCensor;\n /**\n * Dotted paths the path-glob pass already censored. Skipped here so a\n * function censor is never invoked twice on the same leaf (the second call\n * would receive the already-masked value, not the original).\n */\n alreadyCensored: ReadonlySet<string>;\n};\n\n/**\n * Values we copy by reference rather than walking. Expanding these with\n * `Object.keys` would be destructive, not protective — a `Buffer` becomes a\n * multi-thousand-key index map, a `Map`/`Set`/`RegExp` becomes `{}`. Their\n * contents are consequently *not* reachable by redaction; see the residual\n * gaps documented on `applyRedact`.\n */\nfunction isOpaque(value: object): boolean {\n return (\n ArrayBuffer.isView(value) ||\n value instanceof ArrayBuffer ||\n value instanceof Map ||\n value instanceof Set ||\n value instanceof WeakMap ||\n value instanceof WeakSet ||\n value instanceof Promise ||\n value instanceof RegExp\n );\n}\n\n/**\n * Deep-clone a value with structural fidelity for log entries — handles plain\n * objects, arrays, `Date`, `Error`, and primitives. Anything else (buffers,\n * maps, sets, promises, regexes) is copied by reference: we only redact\n * through walkable structures anyway, and rebuilding e.g. a `Buffer` would\n * change semantics.\n *\n * Purpose-built rather than reaching for `structuredClone`: `Error` instances\n * lose their `message`/`stack` under `structuredClone` in some Node versions,\n * and the logger pipeline carries them often.\n *\n * When `redaction` is supplied, keys matching its denylist are censored during\n * the same pass — one traversal, not two.\n */\nfunction cloneEntry<T>(\n value: T,\n seen = new WeakMap<object, any>(),\n redaction?: KeyRedaction,\n trail: string[] = [],\n): T {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n const asObject = value as unknown as object;\n\n if (seen.has(asObject)) {\n return seen.get(asObject);\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime()) as unknown as T;\n }\n\n if (isOpaque(asObject)) {\n return value;\n }\n\n if (value instanceof Error) {\n return cloneError(value, seen, redaction, trail) as unknown as T;\n }\n\n if (Array.isArray(value)) {\n const arr: any[] = [];\n seen.set(asObject, arr);\n value.forEach((item, index) => {\n // Array indices are positions, not names — never key-matched, but the\n // trail still carries them so function censors see a usable path.\n arr.push(cloneEntry(item, seen, redaction, [...trail, String(index)]));\n });\n return arr as unknown as T;\n }\n\n const out: Record<string, any> = {};\n seen.set(asObject, out);\n copyOwnKeys(value as Record<string, any>, out, seen, redaction, trail);\n return out as unknown as T;\n}\n\n/**\n * Copy every own enumerable key from `source` onto `target`, censoring the\n * ones the key denylist matches and recursing into the rest.\n */\nfunction copyOwnKeys(\n source: Record<string, any>,\n target: Record<string, any>,\n seen: WeakMap<object, any>,\n redaction: KeyRedaction | undefined,\n trail: string[],\n): void {\n for (const key of Object.keys(source)) {\n const childTrail = [...trail, key];\n\n if (\n redaction &&\n redaction.keys.has(normalizeRedactKey(key)) &&\n !redaction.alreadyCensored.has(childTrail.join(\".\"))\n ) {\n target[key] = applyCensor(source[key], redaction.censor, childTrail);\n continue;\n }\n\n target[key] = cloneEntry(source[key], seen, redaction, childTrail);\n }\n}\n\n/**\n * Clone an `Error`, preserving its own enumerable properties.\n *\n * Those extra properties matter for redaction: HTTP clients (axios, got)\n * attach `.config`/`.request`/`.response` to the errors they throw, and those\n * routinely carry the *outgoing* `Authorization` header of the failed request.\n * Copying them through the walk is what lets the key denylist reach in and\n * censor them — dropping them instead (the pre-4.15.0 behavior) hid the\n * secret only when redaction happened to be configured, and took `.code` and\n * friends with it.\n *\n * `name`/`message`/`stack` are non-enumerable on `Error`, so they are carried\n * over explicitly.\n */\nfunction cloneError(\n value: Error,\n seen: WeakMap<object, any>,\n redaction: KeyRedaction | undefined,\n trail: string[],\n): Error {\n let copy: Error;\n\n try {\n copy = new (value.constructor as ErrorConstructor)(value.message);\n } catch {\n // A subclass whose constructor demands a different signature must not\n // take the whole log call down with it.\n copy = new Error(value.message);\n }\n\n // Assigned rather than trusted to the constructor: a subclass that derives\n // its message from a structured argument (`new HttpError({ detail })`)\n // produces an empty message when replayed with a plain string. Defined\n // non-enumerably to match native `Error`, so the clone serializes with the\n // same shape as the original.\n for (const [key, source] of [\n [\"message\", value.message],\n [\"name\", value.name],\n [\"stack\", value.stack],\n ] as const) {\n Object.defineProperty(copy, key, {\n value: source,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n }\n\n seen.set(value, copy);\n copyOwnKeys(value as unknown as Record<string, any>, copy as any, seen, redaction, trail);\n\n return copy;\n}\n\n/**\n * Apply a single censor decision to a value. String censors are returned\n * verbatim; function censors receive the original value plus the dotted\n * path so callers can implement value-aware redaction (mask all but the\n * last 4 chars, hash, etc.).\n */\nfunction applyCensor(value: any, censor: RedactCensor, path: string[]): any {\n if (typeof censor === \"function\") {\n return censor(value, path.join(\".\"));\n }\n return censor;\n}\n\n/**\n * Walk `target` following the remaining `segments` of a path pattern,\n * replacing matched leaves via `censor`. Operates in place — the caller\n * is responsible for cloning before calling.\n *\n * Every censored leaf's dotted path is recorded in `censored` so a following\n * key-denylist pass can leave it alone.\n *\n * Wildcards:\n * - `*` matches exactly one segment (any key on a plain object, any index\n * on an array — stringified for the path that's passed to a function\n * censor).\n * - `**` matches zero or more segments greedily; the rest of the pattern\n * is then attempted at the current level and at every descendant.\n */\nfunction redactAtPath(\n target: any,\n segments: string[],\n censor: RedactCensor,\n pathTrail: string[],\n censored: Set<string>,\n): void {\n if (target === null || typeof target !== \"object\") {\n return;\n }\n\n if (segments.length === 0) {\n return;\n }\n\n const [head, ...rest] = segments;\n\n if (head === undefined) {\n // The `segments.length === 0` guard above already makes this unreachable,\n // but the compiler cannot narrow a DESTRUCTURED element from a length\n // check, so under `noUncheckedIndexedAccess` `head` is `string |\n // undefined` and every use of it below inherits that.\n //\n // Stated rather than asserted away with `!`, because of what this function\n // is: if `head` were ever undefined, `keysToVisit` would carry an\n // `undefined` key, `target[key]` would read and WRITE the literal property\n // \"undefined\", and the field that was supposed to be censored would be\n // left in the log untouched. A redaction path is the wrong place to be\n // approximately right.\n return;\n }\n\n if (head === \"**\") {\n // Try matching `rest` at the current level (the zero-segment match\n // case), then recurse into every child carrying the `**` forward so\n // it keeps matching at deeper levels too.\n if (rest.length > 0) {\n redactAtPath(target, rest, censor, pathTrail, censored);\n }\n const keys = Array.isArray(target)\n ? target.map((_, index) => String(index))\n : Object.keys(target);\n for (const key of keys) {\n redactAtPath(target[key], segments, censor, [...pathTrail, key], censored);\n }\n return;\n }\n\n const keysToVisit =\n head === \"*\"\n ? Array.isArray(target)\n ? target.map((_, index) => String(index))\n : Object.keys(target)\n : Array.isArray(target)\n ? // Numeric segment can index into an array.\n /^\\d+$/.test(head) && Number(head) < target.length\n ? [head]\n : []\n : Object.prototype.hasOwnProperty.call(target, head)\n ? [head]\n : [];\n\n for (const key of keysToVisit) {\n if (rest.length === 0) {\n const leafTrail = [...pathTrail, key];\n target[key] = applyCensor(target[key], censor, leafTrail);\n censored.add(leafTrail.join(\".\"));\n } else {\n redactAtPath(target[key], rest, censor, [...pathTrail, key], censored);\n }\n }\n}\n\n/**\n * Cheap pre-scan: does this graph contain any denylisted key at all?\n *\n * Lets the default-on key pass stay allocation-free for the overwhelming\n * majority of entries, which carry no secrets — we only pay for a clone when\n * there is actually something to censor. Also keeps `applyRedact`'s\n * \"returns the input by reference when nothing changed\" contract intact.\n */\nfunction hasDenylistedKey(\n value: any,\n keys: ReadonlySet<string>,\n seen = new WeakSet<object>(),\n): boolean {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n\n const asObject = value as object;\n\n if (seen.has(asObject)) return false;\n seen.add(asObject);\n\n if (value instanceof Date || isOpaque(asObject)) {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.some((item) => hasDenylistedKey(item, keys, seen));\n }\n\n for (const key of Object.keys(value)) {\n if (keys.has(normalizeRedactKey(key))) return true;\n if (hasDenylistedKey(value[key], keys, seen)) return true;\n }\n\n return false;\n}\n\n/**\n * Cache of resolved key sets, keyed by the config object they came from.\n * Logger-wide and channel configs are long-lived references, so this makes\n * the per-entry cost a single map lookup. Merged configs (rebuilt per entry\n * by `mergeRedact`) fall out of the `WeakMap` on their own.\n */\nconst keySetCache = new WeakMap<RedactConfig, ReadonlySet<string>>();\n\n/**\n * Resolve the effective key denylist for a config: the built-in set (unless\n * `defaultKeys: false`) plus any `keys` the application added.\n *\n * Returns `undefined` only when there is nothing to match — i.e. defaults are\n * explicitly off and no custom keys were supplied.\n */\nexport function resolveRedactKeys(\n config: RedactConfig | undefined,\n): ReadonlySet<string> | undefined {\n const useDefaults = config?.defaultKeys !== false;\n const extra = config?.keys;\n\n if (!extra || extra.length === 0) {\n return useDefaults ? DEFAULT_REDACT_KEY_SET : undefined;\n }\n\n const cached = config && keySetCache.get(config);\n if (cached) return cached;\n\n const resolved = new Set<string>(useDefaults ? DEFAULT_REDACT_KEY_SET : []);\n for (const key of extra) {\n resolved.add(normalizeRedactKey(key));\n }\n\n if (config) keySetCache.set(config, resolved);\n\n return resolved;\n}\n\n/**\n * Produce a new `LoggingData` with sensitive data censored:\n *\n * 1. every path in `config.paths` (opt-in globs), then\n * 2. every key matching the denylist — the built-in\n * {@link DEFAULT_REDACT_KEYS} plus `config.keys`, at any depth of\n * `context`, `message`, and an `Error`'s own enumerable properties.\n *\n * Step 2 runs **with no config at all**: passing `undefined` still censors\n * `password`, `authorization`, `token`, `apiKey` and friends. Pass\n * `{ defaultKeys: false }` to opt out.\n *\n * Paths run first so a function censor sees the original value rather than a\n * mask; leaves the path pass already censored are skipped by the key pass.\n *\n * The original entry is never mutated — channels and other call sites can\n * hold references to the input safely. Returns the input **by reference**\n * when nothing matched, so the fast path stays allocation-free.\n *\n * ## Residual gaps (by design, documented rather than silently absent)\n *\n * - **Secrets interpolated into a `message` string** (`` `token=${t}` ``)\n * cannot be reached — neither a path nor a key names a substring.\n * - **`Map`/`Set`/`Buffer` contents** are not traversed (see {@link isOpaque}).\n * - **Non-enumerable / getter-backed properties** are not walked, so an HTTP\n * client that exposes request config behind a getter still slips through.\n * Enumerable ones (axios's `.config`, `.response`) *are* covered.\n */\nexport function applyRedact(data: LoggingData, config: RedactConfig | undefined): LoggingData {\n const paths = config?.paths ?? [];\n const keys = resolveRedactKeys(config);\n\n if (paths.length === 0 && !keys) {\n return data;\n }\n\n const censor = config?.censor ?? DEFAULT_CENSOR;\n\n let result = data;\n const censored = new Set<string>();\n\n if (paths.length > 0) {\n result = cloneEntry(data);\n\n for (const pattern of paths) {\n const segments = pattern.split(\".\").filter((segment) => segment.length > 0);\n if (segments.length === 0) continue;\n redactAtPath(result, segments, censor, [], censored);\n }\n }\n\n if (keys && hasDenylistedKey(result, keys)) {\n result = cloneEntry(result, new WeakMap(), {\n keys,\n censor,\n alreadyCensored: censored,\n });\n }\n\n return result;\n}\n\n/**\n * Combine two redact configs into one effective config. Used to merge a\n * channel's additive paths on top of the logger-wide floor.\n *\n * - `paths` and `keys` are concatenated; duplicates are kept (the matcher\n * tolerates them, and de-duping cross-config would mask a developer typo).\n * - `censor` from the channel wins; falls back to the logger's; falls back\n * to the default `\"[REDACTED]\"`.\n * - `defaultKeys` follows the additive-only contract: a channel can turn the\n * built-in denylist back *on* (`true`) but can never turn off one the\n * logger-wide floor left enabled. When the channel is silent, the logger's\n * choice is inherited — opting out logger-wide is not quietly undone by\n * any channel that happens to set a `redact` option.\n */\nexport function mergeRedact(\n base: RedactConfig | undefined,\n extra: RedactConfig | undefined,\n): RedactConfig | undefined {\n if (!base && !extra) return undefined;\n\n if (!base) {\n // An absent logger-wide config still means \"built-in denylist on\" — it is\n // the floor, not the absence of one. A channel may not switch it off, so\n // its `defaultKeys: false` is overridden here rather than inherited.\n return extra!.defaultKeys === false ? { ...extra!, defaultKeys: true } : extra;\n }\n\n if (!extra) return base;\n\n return {\n paths: [...(base.paths ?? []), ...(extra.paths ?? [])],\n keys: [...(base.keys ?? []), ...(extra.keys ?? [])],\n defaultKeys: extra.defaultKeys === true ? true : base.defaultKeys,\n censor: extra.censor ?? base.censor,\n };\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;;;;AAyBvB,SAAS,SAAS,OAAwB;CACxC,OACE,YAAY,OAAO,KAAK,KACxB,iBAAiB,eACjB,iBAAiB,OACjB,iBAAiB,OACjB,iBAAiB,WACjB,iBAAiB,WACjB,iBAAiB,WACjB,iBAAiB;AAErB;;;;;;;;;;;;;;;AAgBA,SAAS,WACP,OACA,uBAAO,IAAI,QAAqB,GAChC,WACA,QAAkB,CAAC,GAChB;CACH,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAGT,MAAM,WAAW;CAEjB,IAAI,KAAK,IAAI,QAAQ,GACnB,OAAO,KAAK,IAAI,QAAQ;CAG1B,IAAI,iBAAiB,MACnB,OAAO,IAAI,KAAK,MAAM,QAAQ,CAAC;CAGjC,IAAI,SAAS,QAAQ,GACnB,OAAO;CAGT,IAAI,iBAAiB,OACnB,OAAO,WAAW,OAAO,MAAM,WAAW,KAAK;CAGjD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,MAAa,CAAC;EACpB,KAAK,IAAI,UAAU,GAAG;EACtB,MAAM,SAAS,MAAM,UAAU;GAG7B,IAAI,KAAK,WAAW,MAAM,MAAM,WAAW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