@bymax-one/nest-logger 1.2.6 → 1.2.9

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.
@@ -229,6 +229,13 @@ function escapeControlCharacters(text) {
229
229
  var DEFAULT_MAX_CAUSE_DEPTH = 3;
230
230
  var MAX_AGGREGATE_ERRORS = 10;
231
231
  var CIRCULAR_SENTINEL = "[Circular]";
232
+ var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
233
+ "name",
234
+ "message",
235
+ "stack",
236
+ "cause",
237
+ "errors"
238
+ ]);
232
239
  function sanitizeError(err, options) {
233
240
  const maxCauseDepth = DEFAULT_MAX_CAUSE_DEPTH;
234
241
  return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, maxCauseDepth);
@@ -264,11 +271,23 @@ function toSanitizedError(value, seen, depth2, maxDepth) {
264
271
  result.errors.push(createWidthMarker(aggregated.length - MAX_AGGREGATE_ERRORS));
265
272
  }
266
273
  }
274
+ assignOwnErrorFields(result, value);
267
275
  return result;
268
276
  } catch {
269
277
  return { name: "SanitizeFailed", message: "Failed to sanitize the thrown value" };
270
278
  }
271
279
  }
280
+ function assignOwnErrorFields(target, source) {
281
+ try {
282
+ const own = Array.isArray(source) ? {} : source;
283
+ for (const [key, value] of Object.entries(own)) {
284
+ if (!Object.hasOwn(target, key) && !DERIVED_ERROR_FIELDS.has(key)) {
285
+ Object.defineProperty(target, key, { value, enumerable: true });
286
+ }
287
+ }
288
+ } catch {
289
+ }
290
+ }
272
291
  function toSanitizedChild(value, seen, depth2, maxDepth) {
273
292
  if (isObject(value) && seen.has(value)) {
274
293
  return CIRCULAR_SENTINEL;
@@ -332,10 +351,30 @@ function assignIfDefined(payload, key, value) {
332
351
  }
333
352
  var PinoLoggerService = class {
334
353
  /**
354
+ * **A hand-built instance is NOT this library's behaviour.** Constructing
355
+ * `new PinoLoggerService(pino({...}, sink))` directly works in the sense of not
356
+ * throwing, and the parameter default below exists for exactly that — but the
357
+ * Pino instance you built has none of the wiring `buildPinoInstance` installs,
358
+ * and the omissions are silent:
359
+ *
360
+ * - **no `err` serializer**, so an `Error` is serialized by Pino's default.
361
+ * The `cause` chain disappears ENTIRELY — no marker, no warning, and a
362
+ * `cause` that reads as "the field was never set";
363
+ * - **no name-based redaction** of serializer output or child bindings;
364
+ * - **no trace-context mixin**, so `requestId` / `tenantId` / OTel ids are
365
+ * absent;
366
+ * - **no size bound**, so nothing is truncated.
367
+ *
368
+ * That matters most for tests, which is the use this doc used to invite without
369
+ * qualification: a consumer wrote one to check whether a `cause` carried its
370
+ * `code`, measured absence, and nearly filed it against this library. The
371
+ * absence was their harness. For a faithful harness, boot the module (or use
372
+ * `BymaxLoggerModule.forRoot` in a testing module) rather than hand-building.
373
+ *
335
374
  * @param pino - The wrapped Pino instance.
336
375
  * @param redact - The DEFAULT-coverage redactor, applied to `child()` bindings.
337
- * Defaults to the identity so a hand-built instance (benchmarks, unit tests)
338
- * still works; the module always injects the configured one.
376
+ * Defaults to the identity so a hand-built instance still works; the module
377
+ * always injects the configured one.
339
378
  */
340
379
  constructor(pino2, redact = (value) => value) {
341
380
  this.pino = pino2;
@@ -1075,9 +1114,35 @@ function reportDestinationFailure(logKey, name, cause, msg) {
1075
1114
  } catch {
1076
1115
  }
1077
1116
  }
1117
+ function safeDestinationName(destination) {
1118
+ try {
1119
+ return String(destination.name);
1120
+ } catch {
1121
+ return "unknown";
1122
+ }
1123
+ }
1124
+ function isLogLevel(value) {
1125
+ return LOG_LEVEL_PRIORITY.includes(value);
1126
+ }
1127
+ var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
1128
+ function safeMinLevel(destination) {
1129
+ if (resolvedMinLevels.has(destination)) {
1130
+ return resolvedMinLevels.get(destination);
1131
+ }
1132
+ let resolved;
1133
+ try {
1134
+ const read = destination.minLevel;
1135
+ resolved = isLogLevel(read) ? read : void 0;
1136
+ } catch {
1137
+ resolved = void 0;
1138
+ }
1139
+ resolvedMinLevels.set(destination, resolved);
1140
+ return resolved;
1141
+ }
1078
1142
 
1079
1143
  // src/server/utils/destination-to-stream.ts
1080
- function reportWriteFailure(name, cause) {
1144
+ function reportWriteFailure(destination, cause) {
1145
+ const name = safeDestinationName(destination);
1081
1146
  reportDestinationFailure(
1082
1147
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
1083
1148
  name,
@@ -1097,7 +1162,8 @@ function destinationToStream(destination, health) {
1097
1162
  decodeStrings: false,
1098
1163
  write(chunk, _encoding, callback) {
1099
1164
  const onFailure = (cause) => {
1100
- reportWriteFailure(destination.name, cause);
1165
+ health.markWriteFailed(destination);
1166
+ reportWriteFailure(destination, cause);
1101
1167
  callback();
1102
1168
  };
1103
1169
  try {
@@ -1110,10 +1176,20 @@ function destinationToStream(destination, health) {
1110
1176
  return;
1111
1177
  }
1112
1178
  const result = destination.write(payload);
1113
- if (result instanceof Promise) {
1114
- result.then(() => callback(), onFailure);
1115
- } else {
1179
+ if (result === void 0) {
1116
1180
  callback();
1181
+ } else {
1182
+ health.markWritePending(destination);
1183
+ Promise.resolve(result).then(
1184
+ () => {
1185
+ health.markWriteSettled(destination);
1186
+ callback();
1187
+ },
1188
+ (cause) => {
1189
+ health.markWriteSettled(destination);
1190
+ onFailure(cause);
1191
+ }
1192
+ );
1117
1193
  }
1118
1194
  } catch (cause) {
1119
1195
  onFailure(cause);
@@ -1398,13 +1474,6 @@ function leafNameOf(path2) {
1398
1474
  }
1399
1475
  return leaf;
1400
1476
  }
1401
- var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
1402
- "name",
1403
- "message",
1404
- "stack",
1405
- "cause",
1406
- "errors"
1407
- ]);
1408
1477
  function serializeErrorValue(value_) {
1409
1478
  const sanitized = sanitizeError(value_);
1410
1479
  const serialized = {
@@ -1421,18 +1490,7 @@ function serializeErrorValue(value_) {
1421
1490
  if (sanitized.errors !== void 0) {
1422
1491
  serialized["errors"] = sanitized.errors;
1423
1492
  }
1424
- try {
1425
- const source = (
1426
- // Stryker disable next-line ConditionalExpression: equivalent BY CONSTRUCTION, not untested — the never-throw catch below makes the mutant observationally identical: with the null check flipped to true, `Object.entries(null)` throws, the catch swallows it, and the emitted envelope is byte-for-byte the same. The guard stays because routing the ordinary null case through exception control flow would trade an explicit branch for a hidden one.
1427
- typeof value_ === "object" && value_ !== null && !Array.isArray(value_) ? value_ : {}
1428
- );
1429
- for (const [key, value] of Object.entries(source)) {
1430
- if (!Object.hasOwn(serialized, key) && !DERIVED_ERROR_FIELDS.has(key)) {
1431
- Reflect.set(serialized, key, value);
1432
- }
1433
- }
1434
- } catch {
1435
- }
1493
+ assignOwnErrorFields(serialized, sanitized);
1436
1494
  return serialized;
1437
1495
  }
1438
1496
  function withSemconvException(record, format) {
@@ -1482,6 +1540,9 @@ function resolveNameRedactor(options) {
1482
1540
  if (options.redactStrategy !== "names") {
1483
1541
  return PASS_THROUGH;
1484
1542
  }
1543
+ return buildNameRedactor(options);
1544
+ }
1545
+ function buildNameRedactor(options) {
1485
1546
  const names = [
1486
1547
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
1487
1548
  ...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
@@ -1500,8 +1561,9 @@ function resolveRedactOption(options) {
1500
1561
  }
1501
1562
  function buildPinoInstance(options, logContext, destinations, health) {
1502
1563
  const maxBytes = options.maxEntrySizeBytes;
1503
- const redact = resolveNameRedactor(options);
1504
- const bound = (serializer) => createSizeBoundedSerializer((input) => redact(serializer(input)), maxBytes);
1564
+ const redactRecord = resolveNameRedactor(options);
1565
+ const redactSerialized = buildNameRedactor(options);
1566
+ const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
1505
1567
  const serializers = {
1506
1568
  err: bound(serializeErrorValue),
1507
1569
  ...Object.fromEntries(
@@ -1538,14 +1600,17 @@ function buildPinoInstance(options, logContext, destinations, health) {
1538
1600
  // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
1539
1601
  // logger construction — no per-entry cost. `true`: bindings are a record
1540
1602
  // root, iterated rather than serialized.
1541
- bindings: (bindings) => redact(bindings, true),
1603
+ bindings: (bindings) => redactRecord(bindings, true),
1542
1604
  // The name-walk redactor runs here, on the merged record (mixin output +
1543
1605
  // the caller's object), which is exactly the surface a caller controls.
1544
1606
  // `base` and child bindings are NOT visible at this hook — they are
1545
1607
  // library-owned (`service`, the `@InjectLogger` context) and carry nothing
1546
1608
  // sensitive, which `pino-factory.spec.ts` pins.
1547
1609
  log: (record) => withSemconvException(
1548
- withEventName(redact(record, true), options.eventNameField),
1610
+ withEventName(
1611
+ redactRecord(record, true),
1612
+ options.eventNameField
1613
+ ),
1549
1614
  options.errorFormat
1550
1615
  )
1551
1616
  },
@@ -1569,7 +1634,11 @@ function buildPinoInstance(options, logContext, destinations, health) {
1569
1634
  }
1570
1635
  };
1571
1636
  const streams = destinations.map((destination) => ({
1572
- level: destination.minLevel ?? options.level,
1637
+ // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
1638
+ // consumer implementing `minLevel` as a throwing getter would fail the factory
1639
+ // and the application would never start — earlier than any fail-soft path can
1640
+ // contain. Unreadable and absent give the same answer: the module level.
1641
+ level: safeMinLevel(destination) ?? options.level,
1573
1642
  stream: destinationToStream(destination, health)
1574
1643
  }));
1575
1644
  return pino(pinoOptions, pino.multistream(streams));
@@ -1579,24 +1648,91 @@ var DestinationHealth = class {
1579
1648
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
1580
1649
  this.failed = /* @__PURE__ */ new Set();
1581
1650
  /**
1582
- * Whether ANY destination initialized successfully.
1651
+ * Destinations that initialized, each with its effective level as an index into
1652
+ * {@link LOG_LEVEL_PRIORITY}.
1653
+ *
1654
+ * Keyed by identity rather than reduced to a flag or a minimum, because the
1655
+ * question a buffering destination asks is "did SOMEONE ELSE receive what I
1656
+ * received?" — and a minimum cannot exclude the asker. A destination that is
1657
+ * itself the only healthy sink would otherwise be told its held entries were
1658
+ * delivered elsewhere, and discard its only copies.
1659
+ *
1660
+ * The level matters for the same reason it does everywhere here: `pino.multistream`
1661
+ * filters per stream, so "alive" and "received what I received" are different
1662
+ * facts.
1663
+ */
1664
+ this.healthy = /* @__PURE__ */ new Map();
1665
+ /**
1666
+ * Destinations whose `write()` threw or rejected at least once.
1667
+ *
1668
+ * Init health says a sink is LIVE; it does not say the sink accepted anything.
1669
+ * A destination that throws on write is reported and skipped per entry, so
1670
+ * inferring delivery from level alone would credit it with entries it dropped.
1671
+ * Uncertainty drains, so any write failure disqualifies it as proof of delivery
1672
+ * for the whole window — coarser than per-entry tracking, and wrong only in the
1673
+ * direction that duplicates rather than loses.
1674
+ */
1675
+ this.writeFailed = /* @__PURE__ */ new Set();
1676
+ /**
1677
+ * In-flight asynchronous writes per destination.
1678
+ *
1679
+ * A rejected async write is only recorded when its promise settles, and the
1680
+ * registry can compute readiness while one is still pending — so "no failure
1681
+ * recorded" is not "every write landed". A destination with anything in flight
1682
+ * is UNPROVEN rather than trusted: counting it as delivery would let a
1683
+ * buffering sink discard its copy moments before the pending write rejects.
1583
1684
  *
1584
- * A boolean rather than a count, deliberately: the only question ever asked of
1585
- * it is "is there somewhere to write?". Mutation testing made the point — a
1586
- * counter incremented with `+=` survived being flipped to `-=`, because
1587
- * `count === 0` means the same thing either way. A value whose arithmetic
1588
- * cannot be observed was not a counter, it was a flag wearing a number.
1685
+ * A counter rather than a flag because writes overlap; it returns to zero only
1686
+ * when the last one settles.
1589
1687
  */
1590
- this.hasHealthy = false;
1688
+ this.pendingWrites = /* @__PURE__ */ new Map();
1591
1689
  /**
1592
1690
  * The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
1593
1691
  * every real level so the first `markFailed` always wins the comparison.
1594
1692
  */
1595
1693
  this.rescuerLevel = Number.POSITIVE_INFINITY;
1596
1694
  }
1597
- /** Record that a destination initialized successfully. */
1598
- markHealthy() {
1599
- this.hasHealthy = true;
1695
+ /**
1696
+ * Record that a destination's `write()` threw or rejected.
1697
+ *
1698
+ * Called from the fan-out's failure path, which already reports the entry as
1699
+ * dropped. This is what stops {@link deliveredByHealthySink} from crediting a
1700
+ * throwing sink with entries it never accepted.
1701
+ *
1702
+ * @param destination - The destination whose write failed.
1703
+ */
1704
+ markWriteFailed(destination) {
1705
+ this.writeFailed.add(destination);
1706
+ }
1707
+ /**
1708
+ * Record that an asynchronous write to a destination has started.
1709
+ *
1710
+ * @param destination - The destination being written to.
1711
+ */
1712
+ markWritePending(destination) {
1713
+ this.pendingWrites.set(destination, (this.pendingWrites.get(destination) ?? 0) + 1);
1714
+ }
1715
+ /**
1716
+ * Record that an asynchronous write has settled, however it settled.
1717
+ *
1718
+ * Paired with {@link markWritePending} on both the fulfilled and rejected
1719
+ * paths — a counter that only decremented on success would never return to
1720
+ * zero for a failing sink, which is a different claim from the one this makes.
1721
+ *
1722
+ * @param destination - The destination whose write settled.
1723
+ */
1724
+ markWriteSettled(destination) {
1725
+ this.pendingWrites.set(destination, (this.pendingWrites.get(destination) ?? 1) - 1);
1726
+ }
1727
+ /**
1728
+ * Record that a destination initialized successfully.
1729
+ *
1730
+ * @param destination - The destination that initialized.
1731
+ * @param effectiveLevel - Its multistream level: `minLevel` when set, otherwise
1732
+ * the module-wide `level`.
1733
+ */
1734
+ markHealthy(destination, effectiveLevel) {
1735
+ this.healthy.set(destination, LOG_LEVEL_PRIORITY.indexOf(effectiveLevel));
1600
1736
  }
1601
1737
  /**
1602
1738
  * Record that a destination failed to initialize, and re-elect the rescuer.
@@ -1647,7 +1783,31 @@ var DestinationHealth = class {
1647
1783
  * rescuer.
1648
1784
  */
1649
1785
  shouldRescue(destination) {
1650
- return !this.hasHealthy && this.rescuer === destination;
1786
+ return this.healthy.size === 0 && this.rescuer === destination;
1787
+ }
1788
+ /**
1789
+ * Whether a LIVE sink received everything a destination at `effectiveLevel`
1790
+ * received — the question a destination holding pre-init entries actually has
1791
+ * before discarding them.
1792
+ *
1793
+ * Not "did any sink survive": `pino.multistream` filters per stream, so a
1794
+ * healthy `error` sink never saw the `info` entries a pretty sink at `info`
1795
+ * buffered. Discarding those because something else was alive would lose them,
1796
+ * which is the failure the buffer exists to prevent. A healthy sink whose level
1797
+ * is at or below this one accepted a superset, so those entries are delivered.
1798
+ *
1799
+ * @param effectiveLevel - The asking destination's multistream level.
1800
+ * @returns `true` when a live sink accepted everything this destination did.
1801
+ */
1802
+ deliveredByHealthySink(asking, effectiveLevel) {
1803
+ const level = LOG_LEVEL_PRIORITY.indexOf(effectiveLevel);
1804
+ for (const [destination, healthyLevel] of this.healthy) {
1805
+ const unproven = this.writeFailed.has(destination) || (this.pendingWrites.get(destination) ?? 0) > 0;
1806
+ if (destination !== asking && !unproven && healthyLevel <= level) {
1807
+ return true;
1808
+ }
1809
+ }
1810
+ return false;
1651
1811
  }
1652
1812
  };
1653
1813
  DestinationHealth = __decorateClass([
@@ -1699,14 +1859,70 @@ var DestinationRegistry = class {
1699
1859
  try {
1700
1860
  await destination.onInit?.();
1701
1861
  this.active.push(destination);
1702
- this.health.markHealthy();
1862
+ this.health.markHealthy(destination, this.effectiveLevelOf(destination));
1703
1863
  } catch (cause) {
1704
- this.health.markFailed(destination, destination.minLevel ?? this.options.level);
1705
- this.reportInitFailure(destination.name, cause);
1864
+ this.health.markFailed(destination, this.effectiveLevelOf(destination));
1865
+ this.reportInitFailure(destination, cause);
1706
1866
  }
1707
1867
  }
1868
+ await this.notifyRegistryReady();
1708
1869
  this.announceBootstrap();
1709
1870
  }
1871
+ /**
1872
+ * Tell every REGISTERED destination — live or failed — what happened to the
1873
+ * entries it may be holding, before the first post-init entry is emitted.
1874
+ *
1875
+ * The signal it carries is one the destination cannot compute: whether ANOTHER
1876
+ * live sink appears to have accepted everything this one accepted.
1877
+ * `pino.multistream` filters per stream, a destination is not its own witness, a
1878
+ * sink whose write threw did not receive that entry, and one whose write has not
1879
+ * settled has shown nothing yet — all of which live in `deliveredByHealthySink`.
1880
+ *
1881
+ * A signal rather than a proof, deliberately: a write still queued inside the
1882
+ * `Writable` adapter is invisible to that accounting, so the flag says which
1883
+ * risk is smaller, not that the entry is safe. See `ILogDestination.onRegistryReady`.
1884
+ *
1885
+ * Each notification is isolated: a destination that throws here is reported and
1886
+ * skipped rather than aborting the remaining ones or the bootstrap entry.
1887
+ * Failing at this hook cannot be allowed to cost more than the hook was worth.
1888
+ */
1889
+ async notifyRegistryReady() {
1890
+ for (const destination of this.registered) {
1891
+ try {
1892
+ await destination.onRegistryReady?.({
1893
+ heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
1894
+ destination,
1895
+ this.effectiveLevelOf(destination)
1896
+ )
1897
+ });
1898
+ } catch (cause) {
1899
+ this.reportHookFailure(destination, cause);
1900
+ }
1901
+ }
1902
+ }
1903
+ /**
1904
+ * The severity a destination actually receives: the STRICTER of the module
1905
+ * level and its own `minLevel`.
1906
+ *
1907
+ * Pino filters at the instance level BEFORE `pino.multistream` sees an entry,
1908
+ * so a `minLevel` below the global one cannot widen what a destination gets —
1909
+ * the factory's own docs say so. Recording the raw `minLevel` therefore
1910
+ * understated delivery: with a global `error` and a healthy sink at `info`,
1911
+ * both sinks in fact receive the same `error` entries, but a pretty sink
1912
+ * declared at `trace` compared as `trace`, delivery read as unproven, and the
1913
+ * buffer drained raw — a duplicate produced by arithmetic rather than by any
1914
+ * real gap.
1915
+ *
1916
+ * @param destination - The destination whose threshold is being computed.
1917
+ * @returns The level entries must clear to reach it.
1918
+ */
1919
+ effectiveLevelOf(destination) {
1920
+ const configured = safeMinLevel(destination);
1921
+ if (configured === void 0) {
1922
+ return this.options.level;
1923
+ }
1924
+ return LOG_LEVEL_PRIORITY.indexOf(configured) > LOG_LEVEL_PRIORITY.indexOf(this.options.level) ? configured : this.options.level;
1925
+ }
1710
1926
  /**
1711
1927
  * Report one destination init failure as a structured
1712
1928
  * `LOGGER_DESTINATION_INIT_FAILED` line on `process.stderr`.
@@ -1715,10 +1931,13 @@ var DestinationRegistry = class {
1715
1931
  * than restating the shape, so an operator greps one `logKey` regardless of
1716
1932
  * which stage failed — and the two cannot drift apart.
1717
1933
  *
1718
- * @param name - The failing destination's name.
1934
+ * @param destination - The failing destination. Passed whole, so its `name` is
1935
+ * read under `safeDestinationName` rather than at the call site — which sits
1936
+ * inside the catch, where a throwing getter would abort bootstrap.
1719
1937
  * @param cause - The thrown or rejected value.
1720
1938
  */
1721
- reportInitFailure(name, cause) {
1939
+ reportInitFailure(destination, cause) {
1940
+ const name = safeDestinationName(destination);
1722
1941
  reportDestinationFailure(
1723
1942
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
1724
1943
  name,
@@ -1726,6 +1945,30 @@ var DestinationRegistry = class {
1726
1945
  `Log destination "${name}" failed to initialize and will receive no entries. If no destination initializes, entries fall back to raw NDJSON on stdout.`
1727
1946
  );
1728
1947
  }
1948
+ /**
1949
+ * Report a failure from the readiness hook, with wording that matches the
1950
+ * destination's actual state.
1951
+ *
1952
+ * The loop calls every registered destination, healthy and failed alike, so one
1953
+ * message cannot be true for both. A healthy one keeps receiving entries and was
1954
+ * never an init failure; a failed one was already dropped from the fan-out and
1955
+ * saying it "remains active" would contradict the report it just got. The key
1956
+ * stays `LOGGER_DESTINATION_INIT_FAILED` either way so an operator greps one
1957
+ * thing across every destination-lifecycle problem.
1958
+ *
1959
+ * @param destination - The destination whose hook threw.
1960
+ * @param cause - The thrown value.
1961
+ */
1962
+ reportHookFailure(destination, cause) {
1963
+ const stillActive = !this.health.isFailed(destination);
1964
+ const name = safeDestinationName(destination);
1965
+ reportDestinationFailure(
1966
+ RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
1967
+ name,
1968
+ cause,
1969
+ `Log destination "${name}" threw from onRegistryReady. ` + (stillActive ? "It initialized successfully and keeps receiving entries; only anything it was holding from before init may be affected." : "It had already failed to initialize and receives no entries; anything it was still holding is lost.")
1970
+ );
1971
+ }
1729
1972
  /**
1730
1973
  * Emit the one-shot bootstrap entries, AFTER every destination has been
1731
1974
  * initialized.
@@ -1782,14 +2025,50 @@ var DestinationRegistry = class {
1782
2025
  try {
1783
2026
  await destination.onShutdown?.();
1784
2027
  } catch (cause) {
1785
- const detail = cause instanceof Error ? cause.stack ?? cause.message : String(cause);
1786
- writeStderrSafely(
1787
- `[DestinationRegistry] Shutdown failed for "${destination.name}": ${detail}
1788
- `
1789
- );
2028
+ this.reportShutdownFailure(destination, cause);
1790
2029
  }
1791
2030
  }
1792
2031
  }
2032
+ /**
2033
+ * Report a failing `onShutdown` on stderr without letting the report itself
2034
+ * abort the teardown of the destinations still queued behind it.
2035
+ *
2036
+ * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
2037
+ * an `Error` with hostile getters, and `String(cause)` on a value with a
2038
+ * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
2039
+ * the `catch` that exists to keep one bad sink from mattering, so an escape
2040
+ * here would propagate out of `onApplicationShutdown` and skip every remaining
2041
+ * destination's flush. The never-throw contract has to cover READING the value,
2042
+ * not just writing it, which is the same correction `reportDestinationFailure`
2043
+ * already carries.
2044
+ *
2045
+ * The text is escaped for the same reason every other terminal-bound path is:
2046
+ * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
2047
+ * newlines and neutralizes everything else that can drive a terminal.
2048
+ *
2049
+ * The DESTINATION is passed rather than its name, so that read happens in here
2050
+ * too. `name` is declared `readonly name: string` but nothing stops a consumer
2051
+ * implementing it as a getter, and reading it at the call site would put it back
2052
+ * outside the guard — inside the `catch`, where a throw has the same cost.
2053
+ *
2054
+ * Two separate guards, not one: a name that cannot be read must not also cost
2055
+ * the failure detail, and a detail that cannot be read must not cost the name.
2056
+ * Either alone still identifies which sink failed.
2057
+ *
2058
+ * @param destination - The destination whose `onShutdown` threw.
2059
+ * @param cause - The thrown value, of any shape.
2060
+ */
2061
+ reportShutdownFailure(destination, cause) {
2062
+ const name = toSingleLineMessage(safeDestinationName(destination));
2063
+ let detail = "UnknownError";
2064
+ try {
2065
+ const stack = isErrorLike(cause) ? cause.stack : void 0;
2066
+ detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(String(stack));
2067
+ } catch {
2068
+ }
2069
+ writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
2070
+ `);
2071
+ }
1793
2072
  /**
1794
2073
  * The destinations that initialized successfully.
1795
2074
  *
@@ -2140,9 +2419,6 @@ var PrettyDevDestination = class {
2140
2419
  });
2141
2420
  } catch {
2142
2421
  this.initFailed = true;
2143
- this.flushBuffer((payload) => {
2144
- writeRawToStdout(payload);
2145
- });
2146
2422
  throw new Error(
2147
2423
  "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`."
2148
2424
  );
@@ -2193,6 +2469,41 @@ var PrettyDevDestination = class {
2193
2469
  this.buffer.push(payload);
2194
2470
  this.bufferedBytes += payloadBytes;
2195
2471
  }
2472
+ /**
2473
+ * Resolve anything still held, now that the registry knows what became of it.
2474
+ *
2475
+ * **Discard only where another sink is believed to have taken the same entries;
2476
+ * emit everything else.** Losing a boot entry is not an acceptable outcome, and
2477
+ * every richer policy tried here had a losing branch: trusting "a sink survived"
2478
+ * lost entries to a sink at a higher level, trusting a level lost them to a sink
2479
+ * that was itself the asker, then to one whose writes were throwing, then to one
2480
+ * whose write had not settled yet. Each of those is now folded into the single
2481
+ * signal handed in — and where it is uncertain, it says `false` and this drains.
2482
+ *
2483
+ * That signal is not a proof, and this hook does not treat it as one. It cannot
2484
+ * see an entry still queued inside the `Writable` adapter, because the adapter
2485
+ * has not called `destination.write()` for it yet. Discarding on it is a bet
2486
+ * that a duplicated boot line costs less than a lost one — which is the trade
2487
+ * this destination accepts, and which a destination that cannot lose anything
2488
+ * should decline by ignoring the flag and always emitting.
2489
+ *
2490
+ * The cost is stated rather than hidden: when nothing survived, every holding
2491
+ * destination drains, so N of them produce N copies of the boot entries. A
2492
+ * duplicated line in an already-degraded boot is a smaller harm than a lost one,
2493
+ * and it is loud rather than silent.
2494
+ *
2495
+ * A no-op once {@link onInit} succeeded — the buffer was flushed through the
2496
+ * transform there and is already empty.
2497
+ *
2498
+ * @param status.heldEntriesDeliveredElsewhere - Another live sink appears to
2499
+ * have taken everything this one took. A deduplication signal, not a proof —
2500
+ * see `ILogDestination.onRegistryReady` for what it cannot see.
2501
+ */
2502
+ onRegistryReady(status) {
2503
+ this.flushBuffer(
2504
+ status.heldEntriesDeliveredElsewhere ? () => void 0 : writeRawToStdout
2505
+ );
2506
+ }
2196
2507
  /**
2197
2508
  * Hand every buffered entry to `emit`, in arrival order, and empty the buffer.
2198
2509
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.2.6",
3
+ "version": "1.2.9",
4
4
  "description": "Structured JSON logging for NestJS based on Pino 10, with optional OpenTelemetry correlation.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -57,6 +57,7 @@
57
57
  "bench": "node --expose-gc --import tsx bench/throughput.bench.ts",
58
58
  "build": "pnpm clean && tsup",
59
59
  "check:exports": "attw --pack .",
60
+ "check:docs": "node scripts/check-doc-snippets.mjs",
60
61
  "check:mutants": "node scripts/check-mutation-directives.mjs",
61
62
  "check:published": "node scripts/check-published-surface.mjs",
62
63
  "clean": "rm -rf dist coverage",
@@ -66,7 +67,7 @@
66
67
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
67
68
  "mutation:dry-run": "stryker run --dryRunOnly",
68
69
  "prepare": "husky",
69
- "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm test:cov:all && pnpm build && pnpm check:published",
70
+ "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:docs && pnpm test:cov:all && pnpm build && pnpm check:published",
70
71
  "release": "npm publish --provenance --access public",
71
72
  "size": "node scripts/check-size.mjs",
72
73
  "test": "jest",