@c9up/spectrum 0.1.20 → 0.1.21

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 (68) hide show
  1. package/README.md +12 -3
  2. package/dist/Logger.d.ts.map +1 -1
  3. package/dist/Logger.js +55 -24
  4. package/dist/Logger.js.map +1 -1
  5. package/dist/LoggerManager.d.ts +2 -1
  6. package/dist/LoggerManager.d.ts.map +1 -1
  7. package/dist/LoggerManager.js +15 -9
  8. package/dist/LoggerManager.js.map +1 -1
  9. package/dist/SpectrumProvider.d.ts.map +1 -1
  10. package/dist/SpectrumProvider.js +10 -5
  11. package/dist/SpectrumProvider.js.map +1 -1
  12. package/dist/channels/FileChannel.d.ts.map +1 -1
  13. package/dist/channels/FileChannel.js +10 -4
  14. package/dist/channels/FileChannel.js.map +1 -1
  15. package/dist/config.d.ts +10 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +21 -3
  18. package/dist/config.js.map +1 -1
  19. package/dist/errors.d.ts +31 -6
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +33 -10
  22. package/dist/errors.js.map +1 -1
  23. package/dist/format.d.ts +23 -0
  24. package/dist/format.d.ts.map +1 -0
  25. package/dist/format.js +109 -0
  26. package/dist/format.js.map +1 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/jsonLine.js +2 -2
  32. package/dist/jsonLine.js.map +1 -1
  33. package/dist/redact.d.ts.map +1 -1
  34. package/dist/redact.js +33 -6
  35. package/dist/redact.js.map +1 -1
  36. package/dist/services/main.d.ts.map +1 -1
  37. package/dist/services/main.js +2 -2
  38. package/dist/services/main.js.map +1 -1
  39. package/dist/stdSerializers.d.ts +10 -3
  40. package/dist/stdSerializers.d.ts.map +1 -1
  41. package/dist/stdSerializers.js +86 -6
  42. package/dist/stdSerializers.js.map +1 -1
  43. package/dist/targets.d.ts.map +1 -1
  44. package/dist/targets.js +24 -8
  45. package/dist/targets.js.map +1 -1
  46. package/dist/testing/FakeLogger.d.ts.map +1 -1
  47. package/dist/testing/FakeLogger.js +84 -26
  48. package/dist/testing/FakeLogger.js.map +1 -1
  49. package/dist/types.d.ts.map +1 -1
  50. package/dist/types.js +6 -2
  51. package/dist/types.js.map +1 -1
  52. package/package.json +7 -4
  53. package/src/Logger.ts +61 -34
  54. package/src/LoggerManager.ts +18 -12
  55. package/src/SpectrumProvider.ts +13 -10
  56. package/src/channels/FileChannel.ts +7 -10
  57. package/src/config.ts +27 -5
  58. package/src/errors.ts +92 -11
  59. package/src/format.ts +105 -0
  60. package/src/index.ts +1 -1
  61. package/src/jsonLine.ts +3 -3
  62. package/src/redact.ts +32 -7
  63. package/src/services/main.ts +2 -4
  64. package/src/stdSerializers.ts +89 -6
  65. package/src/targets.ts +23 -28
  66. package/src/testing/FakeLogger.ts +85 -31
  67. package/src/types.ts +6 -5
  68. package/stubs/config/logger.stub +8 -4
package/src/Logger.ts CHANGED
@@ -13,9 +13,12 @@
13
13
  * @implements FR54, FR55, FR56, FR58
14
14
  */
15
15
 
16
- import { format } from "node:util";
17
- import { SpectrumError } from "./errors.js";
16
+ import {
17
+ E_SPECTRUM_INVALID_STRINGIFY_LIMIT,
18
+ E_SPECTRUM_UNSUPPORTED_OPTION,
19
+ } from "./errors.js";
18
20
  import { emitLog, hasLogListeners } from "./events.js";
21
+ import { formatMessage } from "./format.js";
19
22
  import {
20
23
  attachLineOptions,
21
24
  type JsonLineOptions,
@@ -28,6 +31,7 @@ import {
28
31
  DEFAULT_STRINGIFY_LIMITS,
29
32
  isStringifyLimit,
30
33
  type StringifyLimits,
34
+ stringifyValue,
31
35
  } from "./stringify.js";
32
36
  import { channelsFromConfig } from "./targets.js";
33
37
  import type {
@@ -47,9 +51,6 @@ import {
47
51
 
48
52
  export type { LogLevel };
49
53
 
50
- /** printf-style tokens understood by `util.format`. */
51
- const PRINTF_TOKEN = /%[sdifjoOc%]/;
52
-
53
54
  function isLogLevel(value: string): value is LogLevel {
54
55
  return value in LOG_LEVEL_ORDER;
55
56
  }
@@ -72,10 +73,7 @@ function stringifyLimits(config: LogConfig): StringifyLimits {
72
73
  ["edgeLimit", edgeLimit],
73
74
  ] as const) {
74
75
  if (value !== undefined && !isStringifyLimit(value)) {
75
- throw new SpectrumError(
76
- "E_SPECTRUM_INVALID_STRINGIFY_LIMIT",
77
- `${name} must be a positive integer, got ${String(value)}`,
78
- );
76
+ throw new E_SPECTRUM_INVALID_STRINGIFY_LIMIT([name, String(value)]);
79
77
  }
80
78
  }
81
79
  return {
@@ -121,10 +119,7 @@ function rejectUnsupportedOptions(config: LogConfig): void {
121
119
  for (const option of UNSUPPORTED_OPTIONS) {
122
120
  const value: unknown = Reflect.get(config, option);
123
121
  if (value !== undefined) {
124
- throw new SpectrumError(
125
- "E_SPECTRUM_UNSUPPORTED_OPTION",
126
- `the "${option}" logger option is not supported`,
127
- );
122
+ throw new E_SPECTRUM_UNSUPPORTED_OPTION([option]);
128
123
  }
129
124
  }
130
125
  const streamWrite: unknown =
@@ -132,10 +127,7 @@ function rejectUnsupportedOptions(config: LogConfig): void {
132
127
  ? undefined
133
128
  : Reflect.get(config.hooks, "streamWrite");
134
129
  if (streamWrite !== undefined) {
135
- throw new SpectrumError(
136
- "E_SPECTRUM_UNSUPPORTED_OPTION",
137
- 'the "hooks.streamWrite" logger option is not supported',
138
- );
130
+ throw new E_SPECTRUM_UNSUPPORTED_OPTION(["hooks.streamWrite"]);
139
131
  }
140
132
  }
141
133
 
@@ -442,10 +434,14 @@ export class Logger {
442
434
  *
443
435
  * - `(object, message?, ...values)` → object merged at root (pino).
444
436
  * - `(error, message?, ...values)` → `{ err }` merged (pino err serializer).
445
- * - `(message, ...values)` → printf via `util.format` (pino).
446
- * - `(message, singleObject)` with no printf token → merged as structured
447
- * fields. This is spectrum's message-first ergonomic (ream ContextLogger
448
- * particularity) preserved on top of pino's message-first form.
437
+ * - `(message, ...values)` → printf, with pino's formatter rules.
438
+ * - `(message, singleObject)` → the object merged as structured fields,
439
+ * the message written as given; `(message, singleError)` → `{ err }`.
440
+ *
441
+ * NAMED DEVIATION — the last form is spectrum's own (ream's request logger
442
+ * is `info(message, data)`), and it no longer looks at the message to
443
+ * decide: a `%j` or `%c` that request data put into the message used to
444
+ * turn the fields into clear text inside `msg`, or swallow them.
449
445
  */
450
446
  #resolveArgs(
451
447
  arg0: unknown,
@@ -472,14 +468,14 @@ export class Logger {
472
468
  if (arg0 instanceof Error) {
473
469
  const message =
474
470
  typeof rest[0] === "string"
475
- ? format(rest[0], ...rest.slice(1))
471
+ ? this.#format(rest[0], rest.slice(1))
476
472
  : arg0.message;
477
473
  return { message, mergingObject: { [errorKey]: arg0 }, given: true };
478
474
  }
479
475
  if (isMergeableObject(arg0)) {
480
476
  if (typeof rest[0] === "string") {
481
477
  return {
482
- message: format(rest[0], ...rest.slice(1)),
478
+ message: this.#format(rest[0], rest.slice(1)),
483
479
  mergingObject: arg0,
484
480
  given: true,
485
481
  };
@@ -493,15 +489,42 @@ export class Logger {
493
489
  }
494
490
 
495
491
  const template = typeof arg0 === "string" ? arg0 : String(arg0);
496
- if (
497
- rest.length === 1 &&
498
- isMergeableObject(rest[0]) &&
499
- !PRINTF_TOKEN.test(template)
500
- ) {
501
- return { message: template, mergingObject: rest[0], given: true };
492
+ if (rest.length === 1) {
493
+ const only = rest[0];
494
+ if (only instanceof Error) {
495
+ return {
496
+ message: template,
497
+ mergingObject: { [errorKey]: only },
498
+ given: true,
499
+ };
500
+ }
501
+ if (isMergeableObject(only)) {
502
+ return { message: template, mergingObject: only, given: true };
503
+ }
502
504
  }
503
- const message = rest.length > 0 ? format(template, ...rest) : template;
504
- return { message, given: true };
505
+ return { message: this.#format(template, rest), given: true };
506
+ }
507
+
508
+ /** printf interpolation; an object goes in serialised and redacted. */
509
+ #format(template: string, values: readonly unknown[]): string {
510
+ return formatMessage(template, values, (value) =>
511
+ this.#interpolated(value),
512
+ );
513
+ }
514
+
515
+ /**
516
+ * An object a `%j`, `%o` or `%O` writes into the message: through the
517
+ * serializers and the redaction paths, as a merging object goes. pino
518
+ * redacts an interpolated object with the logger's full path list; a
519
+ * value that skipped it would put the very field the config censors in
520
+ * clear text, one key away from where the config looks for it.
521
+ */
522
+ #interpolated(value: unknown): string {
523
+ let out: unknown = value;
524
+ if (value instanceof Error) out = serializeError(value);
525
+ else if (isMergeableObject(value)) out = this.#applySerializers(value);
526
+ out = this.#redactValue(out);
527
+ return stringifyValue(out, this.#lineOptions?.limits) ?? "undefined";
505
528
  }
506
529
 
507
530
  /** The merging object with the mixin's fields; the merging object wins by default. */
@@ -536,12 +559,16 @@ export class Logger {
536
559
  }
537
560
 
538
561
  #applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
539
- if (this.#redactPaths.length === 0) return bag;
540
- let out: unknown = bag;
562
+ const out = this.#redactValue(bag);
563
+ return isMergeableObject(out) ? out : bag;
564
+ }
565
+
566
+ #redactValue(value: unknown): unknown {
567
+ let out = value;
541
568
  for (const tokens of this.#redactPaths) {
542
569
  out = redactPath(out, tokens, this.#redactAction);
543
570
  }
544
- return isMergeableObject(out) ? out : bag;
571
+ return out;
545
572
  }
546
573
 
547
574
  #write(
@@ -5,6 +5,11 @@
5
5
  * loggers forever, and exposes `use()` / `create()`.
6
6
  */
7
7
 
8
+ import { declaredLogger } from "./config.js";
9
+ import {
10
+ E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER,
11
+ E_SPECTRUM_UNKNOWN_LOGGER,
12
+ } from "./errors.js";
8
13
  import { Logger } from "./Logger.js";
9
14
  import type { LogConfig, LoggerManagerConfig } from "./types.js";
10
15
 
@@ -13,13 +18,13 @@ export class LoggerManager extends Logger {
13
18
  #loggers: Map<string, Logger> = new Map();
14
19
 
15
20
  constructor(config: LoggerManagerConfig) {
16
- const selected = config.loggers[config.default];
21
+ const selected = declaredLogger(config.loggers, config.default);
17
22
  if (selected === undefined) {
18
23
  // Naming a logger that is not in `loggers` used to build a manager
19
24
  // around undefined and fail on the first line written.
20
- throw new Error(
21
- `[spectrum] config.logger names '${config.default}', which is not in \`loggers\`. Declared: ${Object.keys(config.loggers).join(", ") || "(none)"}.`,
22
- );
25
+ throw new E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER([
26
+ `config.logger names '${config.default}', which is not in \`loggers\`. Declared: ${Object.keys(config.loggers).join(", ") || "(none)"}.`,
27
+ ]);
23
28
  }
24
29
  super(selected);
25
30
  this.#config = config;
@@ -32,11 +37,12 @@ export class LoggerManager extends Logger {
32
37
  const cached = this.#loggers.get(key);
33
38
  if (cached) return cached;
34
39
 
35
- const config = this.#config.loggers[key];
36
- if (!config) {
37
- throw new Error(
38
- `[spectrum] Unknown logger "${key}". Registered: ${Object.keys(this.#config.loggers).join(", ")}`,
39
- );
40
+ const config = declaredLogger(this.#config.loggers, key);
41
+ if (config === undefined) {
42
+ throw new E_SPECTRUM_UNKNOWN_LOGGER([
43
+ key,
44
+ Object.keys(this.#config.loggers).join(", "),
45
+ ]);
40
46
  }
41
47
  const logger = this.createLogger(key, config);
42
48
  this.#loggers.set(key, logger);
@@ -45,11 +51,11 @@ export class LoggerManager extends Logger {
45
51
 
46
52
  /**
47
53
  * Build a named logger: the config's `name` defaults to the name it is
48
- * registered under. Not cached; `use()` caches what this returns.
54
+ * registered under. Not cached; `use()` caches what this returns. The
55
+ * config handed in is not written to: the name goes on a copy.
49
56
  */
50
57
  createLogger(name: string, config: LogConfig): Logger {
51
- if (!config.name) config.name = name;
52
- return new Logger(config);
58
+ return new Logger(config.name ? config : { ...config, name });
53
59
  }
54
60
 
55
61
  /**
@@ -1,6 +1,10 @@
1
1
  import "./augmentations.js";
2
2
  import { ConsoleChannel } from "./channels/ConsoleChannel.js";
3
- import { SpectrumError } from "./errors.js";
3
+ import { declaredLogger } from "./config.js";
4
+ import {
5
+ E_SPECTRUM_LOGGER_NOT_BOUND,
6
+ E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER,
7
+ } from "./errors.js";
4
8
  import { onLog } from "./events.js";
5
9
  import { Logger } from "./Logger.js";
6
10
  import { LoggerManager } from "./LoggerManager.js";
@@ -96,10 +100,7 @@ export default class SpectrumProvider {
96
100
  async boot() {
97
101
  const logger = await this.app.container.resolve(Logger);
98
102
  if (!(logger instanceof Logger)) {
99
- throw new SpectrumError(
100
- "E_SPECTRUM_LOGGER_NOT_BOUND",
101
- "the container resolved something other than a Logger for the Logger token",
102
- );
103
+ throw new E_SPECTRUM_LOGGER_NOT_BOUND();
103
104
  }
104
105
  this.#owned = logger;
105
106
  setLogger(logger);
@@ -180,17 +181,19 @@ export default class SpectrumProvider {
180
181
  */
181
182
  #normalize(raw: unknown): LoggerManagerConfig {
182
183
  if (isManagerConfig(raw)) {
183
- const loggers: Record<string, LogConfig> = {};
184
+ // On a null prototype: a logger declared as `__proto__` is an entry
185
+ // here, not the prototype of the map.
186
+ const loggers: Record<string, LogConfig> = Object.create(null);
184
187
  for (const [name, cfg] of Object.entries(raw.loggers)) {
185
188
  loggers[name] = this.#normalizeLogger(cfg);
186
189
  }
187
190
  // Fail loud at boot if `default` references a missing logger — else
188
191
  // LoggerManager builds with `loggers[default] === undefined` and crashes
189
192
  // with a cryptic TypeError on the first log. Mirrors defineConfig().
190
- if (!loggers[raw.default]) {
191
- throw new Error(
192
- `[spectrum] Missing "loggers.${raw.default}". It is referenced by the "default" logger`,
193
- );
193
+ if (declaredLogger(loggers, raw.default) === undefined) {
194
+ throw new E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER([
195
+ `Missing "loggers.${raw.default}". It is referenced by the "default" logger`,
196
+ ]);
194
197
  }
195
198
  return { default: raw.default, loggers };
196
199
  }
@@ -19,7 +19,7 @@ import * as fs from "node:fs";
19
19
  import * as fsp from "node:fs/promises";
20
20
  import * as path from "node:path";
21
21
  import { promisify } from "node:util";
22
- import { SpectrumError } from "../errors.js";
22
+ import { E_SPECTRUM_INVALID_FILE_OPTIONS } from "../errors.js";
23
23
  import { jsonLine } from "../jsonLine.js";
24
24
  import type { LogChannel, LogEntry } from "../types.js";
25
25
 
@@ -65,10 +65,9 @@ function positiveInteger(
65
65
  ): number {
66
66
  if (value === undefined) return fallback;
67
67
  if (!Number.isInteger(value) || value <= 0) {
68
- throw new SpectrumError(
69
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
68
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
70
69
  `FileChannel ${name} must be a positive integer, got ${String(value)}`,
71
- );
70
+ ]);
72
71
  }
73
72
  return value;
74
73
  }
@@ -107,16 +106,14 @@ export class FileChannel implements LogChannel {
107
106
  constructor(config: FileChannelConfig) {
108
107
  const { path: filePath, fd } = config;
109
108
  if ((filePath === undefined) === (fd === undefined)) {
110
- throw new SpectrumError(
111
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
109
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
112
110
  "FileChannel needs exactly one of `path` and `fd`",
113
- );
111
+ ]);
114
112
  }
115
113
  if (fd !== undefined && !(Number.isInteger(fd) && fd >= 0)) {
116
- throw new SpectrumError(
117
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
114
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
118
115
  `FileChannel fd must be a non-negative integer, got ${String(fd)}`,
119
- );
116
+ ]);
120
117
  }
121
118
  this.#filePath = filePath ?? `fd ${String(fd)}`;
122
119
  this.#fdGiven = fd !== undefined;
package/src/config.ts CHANGED
@@ -1,5 +1,27 @@
1
+ import {
2
+ E_SPECTRUM_MISSING_DEFAULT_LOGGER,
3
+ E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER,
4
+ } from "./errors.js";
1
5
  import type { LogConfig, LoggerManagerConfig } from "./types.js";
2
6
 
7
+ /**
8
+ * The logger `name` declares, read as an OWN key of `loggers`.
9
+ *
10
+ * NAMED DEVIATION — upstream reads `loggers[name]`, which answers
11
+ * `Object.prototype` for `__proto__` and a function for `constructor` or
12
+ * `toString`. The first then had `name` written onto it — onto every object
13
+ * of the process — and the others built a logger with no channel that wrote
14
+ * nothing. A name that is not declared is unknown, whatever it is spelled.
15
+ */
16
+ export function declaredLogger(
17
+ loggers: Record<string, LogConfig>,
18
+ name: string,
19
+ ): LogConfig | undefined {
20
+ if (!Object.hasOwn(loggers, name)) return undefined;
21
+ const config = loggers[name];
22
+ return typeof config === "object" && config !== null ? config : undefined;
23
+ }
24
+
3
25
  /**
4
26
  * Define the logger config. Accepts either the Adonis multi-logger shape
5
27
  * (`{ default, loggers }`) or the legacy flat shape (`{ level, channels,
@@ -13,12 +35,12 @@ export function defineConfig(
13
35
  ): LoggerManagerConfig {
14
36
  if ("loggers" in config) {
15
37
  if (!config.default) {
16
- throw new Error('[spectrum] Missing "default" property in logger config');
38
+ throw new E_SPECTRUM_MISSING_DEFAULT_LOGGER();
17
39
  }
18
- if (!config.loggers[config.default]) {
19
- throw new Error(
20
- `[spectrum] Missing "loggers.${config.default}". It is referenced by the "default" logger`,
21
- );
40
+ if (declaredLogger(config.loggers, config.default) === undefined) {
41
+ throw new E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER([
42
+ `Missing "loggers.${config.default}". It is referenced by the "default" logger`,
43
+ ]);
22
44
  }
23
45
  return config;
24
46
  }
package/src/errors.ts CHANGED
@@ -1,13 +1,94 @@
1
1
  /**
2
- * A spectrum configuration or usage error, carrying an `E_SPECTRUM_*` code an
3
- * application can filter on.
2
+ * Spectrum errors, one class per code. An application branches on
3
+ * `error.code` or on `error instanceof errors.E_…`; every one is a flare
4
+ * `Exception`, with the HTTP status an exception handler answers with.
4
5
  */
5
- export class SpectrumError extends Error {
6
- readonly code: string;
7
-
8
- constructor(code: string, message: string) {
9
- super(`[spectrum] ${message}`);
10
- this.name = "SpectrumError";
11
- this.code = code;
12
- }
13
- }
6
+
7
+ import { createError } from "@c9up/flare";
8
+
9
+ /** A configured level, a target level or `logLevel()` input is not a level. */
10
+ export const E_SPECTRUM_UNKNOWN_LEVEL = createError<[string, string, string]>(
11
+ "[spectrum] %s level %s. Use one of: %s.",
12
+ "E_SPECTRUM_UNKNOWN_LEVEL",
13
+ );
14
+
15
+ /** A transport target or destination spectrum cannot build. */
16
+ export const E_SPECTRUM_UNSUPPORTED_TARGET = createError<[string]>(
17
+ "[spectrum] %s",
18
+ "E_SPECTRUM_UNSUPPORTED_TARGET",
19
+ );
20
+
21
+ /** A file destination's options are invalid. */
22
+ export const E_SPECTRUM_INVALID_FILE_OPTIONS = createError<[string]>(
23
+ "[spectrum] %s",
24
+ "E_SPECTRUM_INVALID_FILE_OPTIONS",
25
+ );
26
+
27
+ /** `messageKey`, `timestamp`, `base` or `formatters` is invalid. */
28
+ export const E_SPECTRUM_INVALID_LINE_OPTIONS = createError<[string]>(
29
+ "[spectrum] %s",
30
+ "E_SPECTRUM_INVALID_LINE_OPTIONS",
31
+ );
32
+
33
+ /** A `redact` path cannot be parsed. */
34
+ export const E_SPECTRUM_INVALID_REDACT_PATH = createError<[string]>(
35
+ "[spectrum] %s",
36
+ "E_SPECTRUM_INVALID_REDACT_PATH",
37
+ );
38
+
39
+ /** `depthLimit` or `edgeLimit` is not a positive integer. */
40
+ export const E_SPECTRUM_INVALID_STRINGIFY_LIMIT = createError<
41
+ [string, unknown]
42
+ >(
43
+ "[spectrum] %s must be a positive integer, got %s",
44
+ "E_SPECTRUM_INVALID_STRINGIFY_LIMIT",
45
+ );
46
+
47
+ /** The config sets an option spectrum does not support. */
48
+ export const E_SPECTRUM_UNSUPPORTED_OPTION = createError<[string]>(
49
+ '[spectrum] the "%s" logger option is not supported',
50
+ "E_SPECTRUM_UNSUPPORTED_OPTION",
51
+ );
52
+
53
+ /** At boot, the container resolves something other than a `Logger`. */
54
+ export const E_SPECTRUM_LOGGER_NOT_BOUND = createError(
55
+ "[spectrum] the container resolved something other than a Logger for the Logger token",
56
+ "E_SPECTRUM_LOGGER_NOT_BOUND",
57
+ );
58
+
59
+ /** A multi-logger config names no `default` logger. */
60
+ export const E_SPECTRUM_MISSING_DEFAULT_LOGGER = createError(
61
+ '[spectrum] Missing "default" property in logger config',
62
+ "E_SPECTRUM_MISSING_DEFAULT_LOGGER",
63
+ );
64
+
65
+ /** The `default` logger is not declared in `loggers`. */
66
+ export const E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER = createError<[string]>(
67
+ "[spectrum] %s",
68
+ "E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER",
69
+ );
70
+
71
+ /** `logger.use(name)` names a logger that is not in `loggers`. */
72
+ export const E_SPECTRUM_UNKNOWN_LOGGER = createError<[string, string]>(
73
+ '[spectrum] Unknown logger "%s". Registered: %s',
74
+ "E_SPECTRUM_UNKNOWN_LOGGER",
75
+ );
76
+
77
+ /** The `services/main` logger was used before `SpectrumProvider` booted. */
78
+ export const E_SPECTRUM_NOT_BOOTED = createError(
79
+ "[spectrum] Logger singleton accessed before SpectrumProvider.boot() ran. " +
80
+ "Check that `@c9up/spectrum/provider` is listed in your reamrc.ts providers.",
81
+ "E_SPECTRUM_NOT_BOOTED",
82
+ );
83
+
84
+ /** A `FakeLogger` assertion failed. */
85
+ export const E_SPECTRUM_ASSERTION_FAILED = createError<[string]>(
86
+ "[spectrum] %s",
87
+ "E_SPECTRUM_ASSERTION_FAILED",
88
+ );
89
+
90
+ /** A `FakeLogger` assertion got an empty `containing`. */
91
+ export const E_SPECTRUM_INVALID_PREDICATE = createError(
92
+ "[spectrum] FakeLogger: `containing` predicate cannot be an empty string — it would match every captured message.",
93
+ "E_SPECTRUM_INVALID_PREDICATE",
94
+ );
package/src/format.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * printf interpolation of a log message, with upstream's rules.
3
+ *
4
+ * Node's `util.format` is not what upstream runs, and the difference is a
5
+ * leak: it inspects an object for `%s`, `%o` and `%O` with no redaction, knows
6
+ * `%c` (which swallows an argument), and appends every argument no token took
7
+ * to the end of the message. A message that carries request data then decides,
8
+ * by its content, what of the remaining arguments ends up in clear in `msg`.
9
+ *
10
+ * These are the rules of the formatter upstream uses: `%s` is `String(value)`,
11
+ * `%d` / `%f` a number, `%i` an integer, `%%` a percent sign that consumes
12
+ * nothing, `%j` / `%o` / `%O` the value through `stringify` — which the logger
13
+ * hands in already serialised and redacted — and an argument no token takes
14
+ * is dropped. Any other `%x` is left as written.
15
+ */
16
+
17
+ /** Turns a value interpolated by `%j`, `%o` or `%O` into text. */
18
+ export type InterpolationStringify = (value: unknown) => string;
19
+
20
+ const PERCENT = 37;
21
+ const LOWER_D = 100;
22
+ const LOWER_F = 102;
23
+ const LOWER_I = 105;
24
+ const LOWER_J = 106;
25
+ const LOWER_O = 111;
26
+ const UPPER_O = 79;
27
+ const LOWER_S = 115;
28
+
29
+ /** `String(value)`, without letting a throwing `toString` take the line down. */
30
+ function asText(value: unknown): string {
31
+ try {
32
+ return String(value);
33
+ } catch {
34
+ return "[unprintable]";
35
+ }
36
+ }
37
+
38
+ /** `Number(value)`, which throws on a symbol or an object without a primitive. */
39
+ function asNumber(value: unknown, integer: boolean): string {
40
+ try {
41
+ const number = Number(value);
42
+ return String(integer ? Math.floor(number) : number);
43
+ } catch {
44
+ return "NaN";
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The message with its tokens replaced by `args`. Without arguments the
50
+ * template is returned as written, `%%` included.
51
+ */
52
+ export function formatMessage(
53
+ template: string,
54
+ args: readonly unknown[],
55
+ stringify: InterpolationStringify,
56
+ ): string {
57
+ if (args.length === 0) return template;
58
+ let out = "";
59
+ let argIndex = 0;
60
+ let lastPos = -1;
61
+ const length = template.length;
62
+ for (let i = 0; i < length; i++) {
63
+ if (template.charCodeAt(i) !== PERCENT || i + 1 >= length) continue;
64
+ lastPos = lastPos > -1 ? lastPos : 0;
65
+ const arg = args[argIndex];
66
+ const available = argIndex < args.length;
67
+ let replacement: string | undefined;
68
+ switch (template.charCodeAt(i + 1)) {
69
+ case LOWER_D:
70
+ case LOWER_F:
71
+ if (available && arg != null) replacement = asNumber(arg, false);
72
+ break;
73
+ case LOWER_I:
74
+ if (available && arg != null) replacement = asNumber(arg, true);
75
+ break;
76
+ case LOWER_J:
77
+ case LOWER_O:
78
+ case UPPER_O:
79
+ if (!available || arg === undefined) break;
80
+ if (typeof arg === "string") replacement = `'${arg}'`;
81
+ else if (typeof arg === "function") {
82
+ replacement = arg.name || "<anonymous>";
83
+ } else replacement = stringify(arg);
84
+ break;
85
+ case LOWER_S:
86
+ if (available) replacement = asText(arg);
87
+ break;
88
+ case PERCENT:
89
+ replacement = "%";
90
+ // A literal percent takes no argument.
91
+ argIndex--;
92
+ break;
93
+ }
94
+ if (replacement !== undefined) {
95
+ if (lastPos < i) out += template.slice(lastPos, i);
96
+ out += replacement;
97
+ lastPos = i + 2;
98
+ i++;
99
+ }
100
+ argIndex++;
101
+ }
102
+ if (lastPos === -1) return template;
103
+ if (lastPos < length) out += template.slice(lastPos);
104
+ return out;
105
+ }
package/src/index.ts CHANGED
@@ -13,7 +13,7 @@ export {
13
13
  export { FileChannel, type FileChannelConfig } from "./channels/FileChannel.js";
14
14
  export { defineConfig } from "./config.js";
15
15
  export { configure } from "./configure.js";
16
- export { SpectrumError } from "./errors.js";
16
+ export * as errors from "./errors.js";
17
17
  export { clearLogListeners, type LogListener, onLog } from "./events.js";
18
18
  export type { LineFormatters, TimestampOption } from "./jsonLine.js";
19
19
  export { Logger, type LogLevel } from "./Logger.js";
package/src/jsonLine.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { hostname } from "node:os";
14
- import { SpectrumError } from "./errors.js";
14
+ import { E_SPECTRUM_INVALID_LINE_OPTIONS } from "./errors.js";
15
15
  import {
16
16
  DEFAULT_STRINGIFY_LIMITS,
17
17
  type StringifyLimits,
@@ -81,8 +81,8 @@ export function lineOptionsFor(entry: object): JsonLineOptions {
81
81
  return entryOptions.get(entry) ?? DEFAULT_LINE_OPTIONS;
82
82
  }
83
83
 
84
- function invalid(detail: string): SpectrumError {
85
- return new SpectrumError("E_SPECTRUM_INVALID_LINE_OPTIONS", detail);
84
+ function invalid(detail: string): Error {
85
+ return new E_SPECTRUM_INVALID_LINE_OPTIONS([detail]);
86
86
  }
87
87
 
88
88
  function isRecord(value: unknown): value is Record<string, unknown> {