@bymax-one/nest-logger 1.2.7 → 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.
@@ -354,10 +354,30 @@ function assignIfDefined(payload, key, value) {
354
354
  }
355
355
  exports.PinoLoggerService = class PinoLoggerService {
356
356
  /**
357
+ * **A hand-built instance is NOT this library's behaviour.** Constructing
358
+ * `new PinoLoggerService(pino({...}, sink))` directly works in the sense of not
359
+ * throwing, and the parameter default below exists for exactly that — but the
360
+ * Pino instance you built has none of the wiring `buildPinoInstance` installs,
361
+ * and the omissions are silent:
362
+ *
363
+ * - **no `err` serializer**, so an `Error` is serialized by Pino's default.
364
+ * The `cause` chain disappears ENTIRELY — no marker, no warning, and a
365
+ * `cause` that reads as "the field was never set";
366
+ * - **no name-based redaction** of serializer output or child bindings;
367
+ * - **no trace-context mixin**, so `requestId` / `tenantId` / OTel ids are
368
+ * absent;
369
+ * - **no size bound**, so nothing is truncated.
370
+ *
371
+ * That matters most for tests, which is the use this doc used to invite without
372
+ * qualification: a consumer wrote one to check whether a `cause` carried its
373
+ * `code`, measured absence, and nearly filed it against this library. The
374
+ * absence was their harness. For a faithful harness, boot the module (or use
375
+ * `BymaxLoggerModule.forRoot` in a testing module) rather than hand-building.
376
+ *
357
377
  * @param pino - The wrapped Pino instance.
358
378
  * @param redact - The DEFAULT-coverage redactor, applied to `child()` bindings.
359
- * Defaults to the identity so a hand-built instance (benchmarks, unit tests)
360
- * still works; the module always injects the configured one.
379
+ * Defaults to the identity so a hand-built instance still works; the module
380
+ * always injects the configured one.
361
381
  */
362
382
  constructor(pino2, redact = (value) => value) {
363
383
  this.pino = pino2;
@@ -1097,9 +1117,35 @@ function reportDestinationFailure(logKey, name, cause, msg) {
1097
1117
  } catch {
1098
1118
  }
1099
1119
  }
1120
+ function safeDestinationName(destination) {
1121
+ try {
1122
+ return String(destination.name);
1123
+ } catch {
1124
+ return "unknown";
1125
+ }
1126
+ }
1127
+ function isLogLevel(value) {
1128
+ return LOG_LEVEL_PRIORITY.includes(value);
1129
+ }
1130
+ var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
1131
+ function safeMinLevel(destination) {
1132
+ if (resolvedMinLevels.has(destination)) {
1133
+ return resolvedMinLevels.get(destination);
1134
+ }
1135
+ let resolved;
1136
+ try {
1137
+ const read = destination.minLevel;
1138
+ resolved = isLogLevel(read) ? read : void 0;
1139
+ } catch {
1140
+ resolved = void 0;
1141
+ }
1142
+ resolvedMinLevels.set(destination, resolved);
1143
+ return resolved;
1144
+ }
1100
1145
 
1101
1146
  // src/server/utils/destination-to-stream.ts
1102
- function reportWriteFailure(name, cause) {
1147
+ function reportWriteFailure(destination, cause) {
1148
+ const name = safeDestinationName(destination);
1103
1149
  reportDestinationFailure(
1104
1150
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
1105
1151
  name,
@@ -1119,7 +1165,8 @@ function destinationToStream(destination, health) {
1119
1165
  decodeStrings: false,
1120
1166
  write(chunk, _encoding, callback) {
1121
1167
  const onFailure = (cause) => {
1122
- reportWriteFailure(destination.name, cause);
1168
+ health.markWriteFailed(destination);
1169
+ reportWriteFailure(destination, cause);
1123
1170
  callback();
1124
1171
  };
1125
1172
  try {
@@ -1132,10 +1179,20 @@ function destinationToStream(destination, health) {
1132
1179
  return;
1133
1180
  }
1134
1181
  const result = destination.write(payload);
1135
- if (result instanceof Promise) {
1136
- result.then(() => callback(), onFailure);
1137
- } else {
1182
+ if (result === void 0) {
1138
1183
  callback();
1184
+ } else {
1185
+ health.markWritePending(destination);
1186
+ Promise.resolve(result).then(
1187
+ () => {
1188
+ health.markWriteSettled(destination);
1189
+ callback();
1190
+ },
1191
+ (cause) => {
1192
+ health.markWriteSettled(destination);
1193
+ onFailure(cause);
1194
+ }
1195
+ );
1139
1196
  }
1140
1197
  } catch (cause) {
1141
1198
  onFailure(cause);
@@ -1580,7 +1637,11 @@ function buildPinoInstance(options, logContext, destinations, health) {
1580
1637
  }
1581
1638
  };
1582
1639
  const streams = destinations.map((destination) => ({
1583
- level: destination.minLevel ?? options.level,
1640
+ // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
1641
+ // consumer implementing `minLevel` as a throwing getter would fail the factory
1642
+ // and the application would never start — earlier than any fail-soft path can
1643
+ // contain. Unreadable and absent give the same answer: the module level.
1644
+ level: safeMinLevel(destination) ?? options.level,
1584
1645
  stream: destinationToStream(destination, health)
1585
1646
  }));
1586
1647
  return pino__default.default(pinoOptions, pino__default.default.multistream(streams));
@@ -1590,24 +1651,91 @@ var DestinationHealth = class {
1590
1651
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
1591
1652
  this.failed = /* @__PURE__ */ new Set();
1592
1653
  /**
1593
- * Whether ANY destination initialized successfully.
1654
+ * Destinations that initialized, each with its effective level as an index into
1655
+ * {@link LOG_LEVEL_PRIORITY}.
1656
+ *
1657
+ * Keyed by identity rather than reduced to a flag or a minimum, because the
1658
+ * question a buffering destination asks is "did SOMEONE ELSE receive what I
1659
+ * received?" — and a minimum cannot exclude the asker. A destination that is
1660
+ * itself the only healthy sink would otherwise be told its held entries were
1661
+ * delivered elsewhere, and discard its only copies.
1662
+ *
1663
+ * The level matters for the same reason it does everywhere here: `pino.multistream`
1664
+ * filters per stream, so "alive" and "received what I received" are different
1665
+ * facts.
1666
+ */
1667
+ this.healthy = /* @__PURE__ */ new Map();
1668
+ /**
1669
+ * Destinations whose `write()` threw or rejected at least once.
1594
1670
  *
1595
- * A boolean rather than a count, deliberately: the only question ever asked of
1596
- * it is "is there somewhere to write?". Mutation testing made the point — a
1597
- * counter incremented with `+=` survived being flipped to `-=`, because
1598
- * `count === 0` means the same thing either way. A value whose arithmetic
1599
- * cannot be observed was not a counter, it was a flag wearing a number.
1671
+ * Init health says a sink is LIVE; it does not say the sink accepted anything.
1672
+ * A destination that throws on write is reported and skipped per entry, so
1673
+ * inferring delivery from level alone would credit it with entries it dropped.
1674
+ * Uncertainty drains, so any write failure disqualifies it as proof of delivery
1675
+ * for the whole window — coarser than per-entry tracking, and wrong only in the
1676
+ * direction that duplicates rather than loses.
1600
1677
  */
1601
- this.hasHealthy = false;
1678
+ this.writeFailed = /* @__PURE__ */ new Set();
1679
+ /**
1680
+ * In-flight asynchronous writes per destination.
1681
+ *
1682
+ * A rejected async write is only recorded when its promise settles, and the
1683
+ * registry can compute readiness while one is still pending — so "no failure
1684
+ * recorded" is not "every write landed". A destination with anything in flight
1685
+ * is UNPROVEN rather than trusted: counting it as delivery would let a
1686
+ * buffering sink discard its copy moments before the pending write rejects.
1687
+ *
1688
+ * A counter rather than a flag because writes overlap; it returns to zero only
1689
+ * when the last one settles.
1690
+ */
1691
+ this.pendingWrites = /* @__PURE__ */ new Map();
1602
1692
  /**
1603
1693
  * The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
1604
1694
  * every real level so the first `markFailed` always wins the comparison.
1605
1695
  */
1606
1696
  this.rescuerLevel = Number.POSITIVE_INFINITY;
1607
1697
  }
1608
- /** Record that a destination initialized successfully. */
1609
- markHealthy() {
1610
- this.hasHealthy = true;
1698
+ /**
1699
+ * Record that a destination's `write()` threw or rejected.
1700
+ *
1701
+ * Called from the fan-out's failure path, which already reports the entry as
1702
+ * dropped. This is what stops {@link deliveredByHealthySink} from crediting a
1703
+ * throwing sink with entries it never accepted.
1704
+ *
1705
+ * @param destination - The destination whose write failed.
1706
+ */
1707
+ markWriteFailed(destination) {
1708
+ this.writeFailed.add(destination);
1709
+ }
1710
+ /**
1711
+ * Record that an asynchronous write to a destination has started.
1712
+ *
1713
+ * @param destination - The destination being written to.
1714
+ */
1715
+ markWritePending(destination) {
1716
+ this.pendingWrites.set(destination, (this.pendingWrites.get(destination) ?? 0) + 1);
1717
+ }
1718
+ /**
1719
+ * Record that an asynchronous write has settled, however it settled.
1720
+ *
1721
+ * Paired with {@link markWritePending} on both the fulfilled and rejected
1722
+ * paths — a counter that only decremented on success would never return to
1723
+ * zero for a failing sink, which is a different claim from the one this makes.
1724
+ *
1725
+ * @param destination - The destination whose write settled.
1726
+ */
1727
+ markWriteSettled(destination) {
1728
+ this.pendingWrites.set(destination, (this.pendingWrites.get(destination) ?? 1) - 1);
1729
+ }
1730
+ /**
1731
+ * Record that a destination initialized successfully.
1732
+ *
1733
+ * @param destination - The destination that initialized.
1734
+ * @param effectiveLevel - Its multistream level: `minLevel` when set, otherwise
1735
+ * the module-wide `level`.
1736
+ */
1737
+ markHealthy(destination, effectiveLevel) {
1738
+ this.healthy.set(destination, LOG_LEVEL_PRIORITY.indexOf(effectiveLevel));
1611
1739
  }
1612
1740
  /**
1613
1741
  * Record that a destination failed to initialize, and re-elect the rescuer.
@@ -1658,7 +1786,31 @@ var DestinationHealth = class {
1658
1786
  * rescuer.
1659
1787
  */
1660
1788
  shouldRescue(destination) {
1661
- return !this.hasHealthy && this.rescuer === destination;
1789
+ return this.healthy.size === 0 && this.rescuer === destination;
1790
+ }
1791
+ /**
1792
+ * Whether a LIVE sink received everything a destination at `effectiveLevel`
1793
+ * received — the question a destination holding pre-init entries actually has
1794
+ * before discarding them.
1795
+ *
1796
+ * Not "did any sink survive": `pino.multistream` filters per stream, so a
1797
+ * healthy `error` sink never saw the `info` entries a pretty sink at `info`
1798
+ * buffered. Discarding those because something else was alive would lose them,
1799
+ * which is the failure the buffer exists to prevent. A healthy sink whose level
1800
+ * is at or below this one accepted a superset, so those entries are delivered.
1801
+ *
1802
+ * @param effectiveLevel - The asking destination's multistream level.
1803
+ * @returns `true` when a live sink accepted everything this destination did.
1804
+ */
1805
+ deliveredByHealthySink(asking, effectiveLevel) {
1806
+ const level = LOG_LEVEL_PRIORITY.indexOf(effectiveLevel);
1807
+ for (const [destination, healthyLevel] of this.healthy) {
1808
+ const unproven = this.writeFailed.has(destination) || (this.pendingWrites.get(destination) ?? 0) > 0;
1809
+ if (destination !== asking && !unproven && healthyLevel <= level) {
1810
+ return true;
1811
+ }
1812
+ }
1813
+ return false;
1662
1814
  }
1663
1815
  };
1664
1816
  DestinationHealth = __decorateClass([
@@ -1710,14 +1862,70 @@ var DestinationRegistry = class {
1710
1862
  try {
1711
1863
  await destination.onInit?.();
1712
1864
  this.active.push(destination);
1713
- this.health.markHealthy();
1865
+ this.health.markHealthy(destination, this.effectiveLevelOf(destination));
1714
1866
  } catch (cause) {
1715
- this.health.markFailed(destination, destination.minLevel ?? this.options.level);
1716
- this.reportInitFailure(destination.name, cause);
1867
+ this.health.markFailed(destination, this.effectiveLevelOf(destination));
1868
+ this.reportInitFailure(destination, cause);
1717
1869
  }
1718
1870
  }
1871
+ await this.notifyRegistryReady();
1719
1872
  this.announceBootstrap();
1720
1873
  }
1874
+ /**
1875
+ * Tell every REGISTERED destination — live or failed — what happened to the
1876
+ * entries it may be holding, before the first post-init entry is emitted.
1877
+ *
1878
+ * The signal it carries is one the destination cannot compute: whether ANOTHER
1879
+ * live sink appears to have accepted everything this one accepted.
1880
+ * `pino.multistream` filters per stream, a destination is not its own witness, a
1881
+ * sink whose write threw did not receive that entry, and one whose write has not
1882
+ * settled has shown nothing yet — all of which live in `deliveredByHealthySink`.
1883
+ *
1884
+ * A signal rather than a proof, deliberately: a write still queued inside the
1885
+ * `Writable` adapter is invisible to that accounting, so the flag says which
1886
+ * risk is smaller, not that the entry is safe. See `ILogDestination.onRegistryReady`.
1887
+ *
1888
+ * Each notification is isolated: a destination that throws here is reported and
1889
+ * skipped rather than aborting the remaining ones or the bootstrap entry.
1890
+ * Failing at this hook cannot be allowed to cost more than the hook was worth.
1891
+ */
1892
+ async notifyRegistryReady() {
1893
+ for (const destination of this.registered) {
1894
+ try {
1895
+ await destination.onRegistryReady?.({
1896
+ heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
1897
+ destination,
1898
+ this.effectiveLevelOf(destination)
1899
+ )
1900
+ });
1901
+ } catch (cause) {
1902
+ this.reportHookFailure(destination, cause);
1903
+ }
1904
+ }
1905
+ }
1906
+ /**
1907
+ * The severity a destination actually receives: the STRICTER of the module
1908
+ * level and its own `minLevel`.
1909
+ *
1910
+ * Pino filters at the instance level BEFORE `pino.multistream` sees an entry,
1911
+ * so a `minLevel` below the global one cannot widen what a destination gets —
1912
+ * the factory's own docs say so. Recording the raw `minLevel` therefore
1913
+ * understated delivery: with a global `error` and a healthy sink at `info`,
1914
+ * both sinks in fact receive the same `error` entries, but a pretty sink
1915
+ * declared at `trace` compared as `trace`, delivery read as unproven, and the
1916
+ * buffer drained raw — a duplicate produced by arithmetic rather than by any
1917
+ * real gap.
1918
+ *
1919
+ * @param destination - The destination whose threshold is being computed.
1920
+ * @returns The level entries must clear to reach it.
1921
+ */
1922
+ effectiveLevelOf(destination) {
1923
+ const configured = safeMinLevel(destination);
1924
+ if (configured === void 0) {
1925
+ return this.options.level;
1926
+ }
1927
+ return LOG_LEVEL_PRIORITY.indexOf(configured) > LOG_LEVEL_PRIORITY.indexOf(this.options.level) ? configured : this.options.level;
1928
+ }
1721
1929
  /**
1722
1930
  * Report one destination init failure as a structured
1723
1931
  * `LOGGER_DESTINATION_INIT_FAILED` line on `process.stderr`.
@@ -1726,10 +1934,13 @@ var DestinationRegistry = class {
1726
1934
  * than restating the shape, so an operator greps one `logKey` regardless of
1727
1935
  * which stage failed — and the two cannot drift apart.
1728
1936
  *
1729
- * @param name - The failing destination's name.
1937
+ * @param destination - The failing destination. Passed whole, so its `name` is
1938
+ * read under `safeDestinationName` rather than at the call site — which sits
1939
+ * inside the catch, where a throwing getter would abort bootstrap.
1730
1940
  * @param cause - The thrown or rejected value.
1731
1941
  */
1732
- reportInitFailure(name, cause) {
1942
+ reportInitFailure(destination, cause) {
1943
+ const name = safeDestinationName(destination);
1733
1944
  reportDestinationFailure(
1734
1945
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
1735
1946
  name,
@@ -1737,6 +1948,30 @@ var DestinationRegistry = class {
1737
1948
  `Log destination "${name}" failed to initialize and will receive no entries. If no destination initializes, entries fall back to raw NDJSON on stdout.`
1738
1949
  );
1739
1950
  }
1951
+ /**
1952
+ * Report a failure from the readiness hook, with wording that matches the
1953
+ * destination's actual state.
1954
+ *
1955
+ * The loop calls every registered destination, healthy and failed alike, so one
1956
+ * message cannot be true for both. A healthy one keeps receiving entries and was
1957
+ * never an init failure; a failed one was already dropped from the fan-out and
1958
+ * saying it "remains active" would contradict the report it just got. The key
1959
+ * stays `LOGGER_DESTINATION_INIT_FAILED` either way so an operator greps one
1960
+ * thing across every destination-lifecycle problem.
1961
+ *
1962
+ * @param destination - The destination whose hook threw.
1963
+ * @param cause - The thrown value.
1964
+ */
1965
+ reportHookFailure(destination, cause) {
1966
+ const stillActive = !this.health.isFailed(destination);
1967
+ const name = safeDestinationName(destination);
1968
+ reportDestinationFailure(
1969
+ RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
1970
+ name,
1971
+ cause,
1972
+ `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.")
1973
+ );
1974
+ }
1740
1975
  /**
1741
1976
  * Emit the one-shot bootstrap entries, AFTER every destination has been
1742
1977
  * initialized.
@@ -1793,14 +2028,50 @@ var DestinationRegistry = class {
1793
2028
  try {
1794
2029
  await destination.onShutdown?.();
1795
2030
  } catch (cause) {
1796
- const detail = cause instanceof Error ? cause.stack ?? cause.message : String(cause);
1797
- writeStderrSafely(
1798
- `[DestinationRegistry] Shutdown failed for "${destination.name}": ${detail}
1799
- `
1800
- );
2031
+ this.reportShutdownFailure(destination, cause);
1801
2032
  }
1802
2033
  }
1803
2034
  }
2035
+ /**
2036
+ * Report a failing `onShutdown` on stderr without letting the report itself
2037
+ * abort the teardown of the destinations still queued behind it.
2038
+ *
2039
+ * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
2040
+ * an `Error` with hostile getters, and `String(cause)` on a value with a
2041
+ * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
2042
+ * the `catch` that exists to keep one bad sink from mattering, so an escape
2043
+ * here would propagate out of `onApplicationShutdown` and skip every remaining
2044
+ * destination's flush. The never-throw contract has to cover READING the value,
2045
+ * not just writing it, which is the same correction `reportDestinationFailure`
2046
+ * already carries.
2047
+ *
2048
+ * The text is escaped for the same reason every other terminal-bound path is:
2049
+ * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
2050
+ * newlines and neutralizes everything else that can drive a terminal.
2051
+ *
2052
+ * The DESTINATION is passed rather than its name, so that read happens in here
2053
+ * too. `name` is declared `readonly name: string` but nothing stops a consumer
2054
+ * implementing it as a getter, and reading it at the call site would put it back
2055
+ * outside the guard — inside the `catch`, where a throw has the same cost.
2056
+ *
2057
+ * Two separate guards, not one: a name that cannot be read must not also cost
2058
+ * the failure detail, and a detail that cannot be read must not cost the name.
2059
+ * Either alone still identifies which sink failed.
2060
+ *
2061
+ * @param destination - The destination whose `onShutdown` threw.
2062
+ * @param cause - The thrown value, of any shape.
2063
+ */
2064
+ reportShutdownFailure(destination, cause) {
2065
+ const name = toSingleLineMessage(safeDestinationName(destination));
2066
+ let detail = "UnknownError";
2067
+ try {
2068
+ const stack = isErrorLike(cause) ? cause.stack : void 0;
2069
+ detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(String(stack));
2070
+ } catch {
2071
+ }
2072
+ writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
2073
+ `);
2074
+ }
1804
2075
  /**
1805
2076
  * The destinations that initialized successfully.
1806
2077
  *
@@ -2151,9 +2422,6 @@ var PrettyDevDestination = class {
2151
2422
  });
2152
2423
  } catch {
2153
2424
  this.initFailed = true;
2154
- this.flushBuffer((payload) => {
2155
- writeRawToStdout(payload);
2156
- });
2157
2425
  throw new Error(
2158
2426
  "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`."
2159
2427
  );
@@ -2204,6 +2472,41 @@ var PrettyDevDestination = class {
2204
2472
  this.buffer.push(payload);
2205
2473
  this.bufferedBytes += payloadBytes;
2206
2474
  }
2475
+ /**
2476
+ * Resolve anything still held, now that the registry knows what became of it.
2477
+ *
2478
+ * **Discard only where another sink is believed to have taken the same entries;
2479
+ * emit everything else.** Losing a boot entry is not an acceptable outcome, and
2480
+ * every richer policy tried here had a losing branch: trusting "a sink survived"
2481
+ * lost entries to a sink at a higher level, trusting a level lost them to a sink
2482
+ * that was itself the asker, then to one whose writes were throwing, then to one
2483
+ * whose write had not settled yet. Each of those is now folded into the single
2484
+ * signal handed in — and where it is uncertain, it says `false` and this drains.
2485
+ *
2486
+ * That signal is not a proof, and this hook does not treat it as one. It cannot
2487
+ * see an entry still queued inside the `Writable` adapter, because the adapter
2488
+ * has not called `destination.write()` for it yet. Discarding on it is a bet
2489
+ * that a duplicated boot line costs less than a lost one — which is the trade
2490
+ * this destination accepts, and which a destination that cannot lose anything
2491
+ * should decline by ignoring the flag and always emitting.
2492
+ *
2493
+ * The cost is stated rather than hidden: when nothing survived, every holding
2494
+ * destination drains, so N of them produce N copies of the boot entries. A
2495
+ * duplicated line in an already-degraded boot is a smaller harm than a lost one,
2496
+ * and it is loud rather than silent.
2497
+ *
2498
+ * A no-op once {@link onInit} succeeded — the buffer was flushed through the
2499
+ * transform there and is already empty.
2500
+ *
2501
+ * @param status.heldEntriesDeliveredElsewhere - Another live sink appears to
2502
+ * have taken everything this one took. A deduplication signal, not a proof —
2503
+ * see `ILogDestination.onRegistryReady` for what it cannot see.
2504
+ */
2505
+ onRegistryReady(status) {
2506
+ this.flushBuffer(
2507
+ status.heldEntriesDeliveredElsewhere ? () => void 0 : writeRawToStdout
2508
+ );
2509
+ }
2207
2510
  /**
2208
2511
  * Hand every buffered entry to `emit`, in arrival order, and empty the buffer.
2209
2512
  *
@@ -69,12 +69,55 @@ interface ILogDestination {
69
69
  *
70
70
  * @param payload — Newline-terminated JSON entry, UTF-8 encoded.
71
71
  */
72
- write(payload: string): void | Promise<void>;
72
+ write(payload: string): void | PromiseLike<void>;
73
73
  /**
74
74
  * Optional lifecycle hook — called once during NestJS module init.
75
75
  * Use for opening connections, allocating buffers, scheduling flushers.
76
76
  */
77
- onInit?(): void | Promise<void>;
77
+ onInit?(): void | PromiseLike<void>;
78
+ /**
79
+ * Optional lifecycle hook — called once after EVERY destination's `onInit`
80
+ * has settled, successfully or not, and before the bootstrap entry is emitted.
81
+ *
82
+ * Only useful to a destination that holds entries written before its own
83
+ * `onInit` ran: until this point it cannot know what became of them. The
84
+ * fan-out hands each entry to every registered destination whose level accepts
85
+ * it, so a held copy may be a SECOND copy.
86
+ *
87
+ * **This is a deduplication signal, not a proof — and the difference is the
88
+ * whole contract.** A held copy may be a second copy, so emitting it duplicates
89
+ * a line and dropping it may lose one. The flag says which risk is smaller, as
90
+ * far as this library can see; it does not say the entry is safe.
91
+ *
92
+ * The library's own destinations act on it by discarding when it is `true` and
93
+ * emitting otherwise, because a duplicated boot line is a smaller harm than a
94
+ * lost one. **A destination that cannot tolerate ANY loss should emit
95
+ * regardless** — see the accounting limits on the flag below.
96
+ *
97
+ * Called on failed destinations too, which is the point: the one that could not
98
+ * initialize is exactly the one still holding entries.
99
+ *
100
+ * @param status.heldEntriesDeliveredElsewhere - Whether another live sink
101
+ * accepted everything this destination accepted, as far as this library can
102
+ * see. `true` requires that sink to be not this one, initialized, at or below
103
+ * this level, with no write failure and no write still in flight; anything
104
+ * less certain is `false`.
105
+ *
106
+ * **What it cannot see:** a write still QUEUED inside the `Writable` adapter,
107
+ * behind a slow async sink that has not been called yet. So `true` can precede
108
+ * a queued write that later fails, and there is no flag that distinguishes
109
+ * that case — which is exactly why this is a tradeoff rather than a
110
+ * guarantee. It normally arrives, being queued rather than lost.
111
+ *
112
+ * @returns Nothing, or a promise the library AWAITS. Returning one is
113
+ * supported deliberately: TypeScript accepts an `async` implementation where
114
+ * a void-returning member is declared, so a hook that was not awaited would
115
+ * reject into nothing and let the bootstrap entry be emitted before the
116
+ * buffer had been resolved.
117
+ */
118
+ onRegistryReady?(status: {
119
+ readonly heldEntriesDeliveredElsewhere: boolean;
120
+ }): void | PromiseLike<void>;
78
121
  /**
79
122
  * Optional lifecycle hook — called during NestJS `onApplicationShutdown`.
80
123
  * MUST flush any pending writes and close resources.
@@ -82,7 +125,7 @@ interface ILogDestination {
82
125
  * The library awaits this — graceful shutdown blocks until all destinations
83
126
  * return.
84
127
  */
85
- onShutdown?(): void | Promise<void>;
128
+ onShutdown?(): void | PromiseLike<void>;
86
129
  }
87
130
 
88
131
  /**
@@ -636,10 +679,30 @@ declare class PinoLoggerService implements LoggerService, OnApplicationShutdown
636
679
  private readonly redact;
637
680
  private context?;
638
681
  /**
682
+ * **A hand-built instance is NOT this library's behaviour.** Constructing
683
+ * `new PinoLoggerService(pino({...}, sink))` directly works in the sense of not
684
+ * throwing, and the parameter default below exists for exactly that — but the
685
+ * Pino instance you built has none of the wiring `buildPinoInstance` installs,
686
+ * and the omissions are silent:
687
+ *
688
+ * - **no `err` serializer**, so an `Error` is serialized by Pino's default.
689
+ * The `cause` chain disappears ENTIRELY — no marker, no warning, and a
690
+ * `cause` that reads as "the field was never set";
691
+ * - **no name-based redaction** of serializer output or child bindings;
692
+ * - **no trace-context mixin**, so `requestId` / `tenantId` / OTel ids are
693
+ * absent;
694
+ * - **no size bound**, so nothing is truncated.
695
+ *
696
+ * That matters most for tests, which is the use this doc used to invite without
697
+ * qualification: a consumer wrote one to check whether a `cause` carried its
698
+ * `code`, measured absence, and nearly filed it against this library. The
699
+ * absence was their harness. For a faithful harness, boot the module (or use
700
+ * `BymaxLoggerModule.forRoot` in a testing module) rather than hand-building.
701
+ *
639
702
  * @param pino - The wrapped Pino instance.
640
703
  * @param redact - The DEFAULT-coverage redactor, applied to `child()` bindings.
641
- * Defaults to the identity so a hand-built instance (benchmarks, unit tests)
642
- * still works; the module always injects the configured one.
704
+ * Defaults to the identity so a hand-built instance still works; the module
705
+ * always injects the configured one.
643
706
  */
644
707
  constructor(pino: Logger, redact?: Redactor);
645
708
  /**
@@ -932,16 +995,42 @@ interface PrettyViewOptions {
932
995
  */
933
996
  ignore?: string;
934
997
  /**
935
- * Render only the message line, hiding the record entirely. In pretty mode
936
- * there is no JSON copy behind it (`destinations` REPLACES stdout), so a field
937
- * hidden here is not visible anywhere — including `logKey`. That is the point
938
- * of the option rather than a caveat; use `messageFormat` to pull a specific
939
- * field back into the line. Default: `false`.
998
+ * Render only the message line, hiding the record entirely. Display-only, and
999
+ * scoped to THIS destination: a field hidden here is still delivered in full to
1000
+ * every other destination registered alongside it.
1001
+ *
1002
+ * When pretty is the ONLY destination, that scope makes it total — `destinations`
1003
+ * replaces the default stdout sink, so there is no JSON copy behind the
1004
+ * rendering and a hidden field, `logKey` included, is not visible anywhere. That
1005
+ * is the point of the option rather than a caveat; use `messageFormat` to pull a
1006
+ * specific field back into the line. Default: `false`.
940
1007
  */
941
1008
  hideObject?: boolean;
942
1009
  /**
943
1010
  * Template for the message line, e.g. `'[{context}] {msg}'`. The way to keep a
944
1011
  * chosen field visible when `hideObject` is on.
1012
+ *
1013
+ * **Every placeholder EXCEPT `{msg}` is interpolated raw, and that reopens
1014
+ * terminal log forging.** This library normalizes line separators and control
1015
+ * characters in `msg` and in the stack — not in metadata, because escaping data
1016
+ * would mean rewriting what you asked to be logged. `pino-pretty` substitutes
1017
+ * whatever the field holds, so a newline in an interpolated field splits one
1018
+ * entry into two, and the second reads like a genuine record. Measured, with a
1019
+ * newline in `context`:
1020
+ *
1021
+ * ```
1022
+ * lines produced by ONE entry: 2
1023
+ * 1: "[10:35:14.484] INFO: [Auth"
1024
+ * 2: "[10:00:00.000] INFO: FORGED admin promoted] real entry …"
1025
+ * ```
1026
+ *
1027
+ * So: interpolate only fields whose values your own code sets. Never a field
1028
+ * carrying user input — `{tenantId}`, `{userId}`, a header, a query value. If
1029
+ * you need one of those visible, leave it in the record instead of the format
1030
+ * string. That closes THIS path — the raw placeholder — and no more: a metadata
1031
+ * value is not safe terminal text either, because `JSON.stringify` escapes only
1032
+ * C0 and emits DEL, the C1 range (U+0085 NEL included), U+2028 and U+2029
1033
+ * verbatim. Only `msg` and the stack carry the one-entry-one-line guarantee.
945
1034
  */
946
1035
  messageFormat?: string;
947
1036
  /** Timestamp format, or `false` to leave it raw. Default: `'SYS:HH:MM:ss.l'`. */
@@ -1046,6 +1135,39 @@ declare class PrettyDevDestination implements ILogDestination {
1046
1135
  * @param payload — Newline-terminated JSON entry, UTF-8 encoded.
1047
1136
  */
1048
1137
  write(payload: string): void;
1138
+ /**
1139
+ * Resolve anything still held, now that the registry knows what became of it.
1140
+ *
1141
+ * **Discard only where another sink is believed to have taken the same entries;
1142
+ * emit everything else.** Losing a boot entry is not an acceptable outcome, and
1143
+ * every richer policy tried here had a losing branch: trusting "a sink survived"
1144
+ * lost entries to a sink at a higher level, trusting a level lost them to a sink
1145
+ * that was itself the asker, then to one whose writes were throwing, then to one
1146
+ * whose write had not settled yet. Each of those is now folded into the single
1147
+ * signal handed in — and where it is uncertain, it says `false` and this drains.
1148
+ *
1149
+ * That signal is not a proof, and this hook does not treat it as one. It cannot
1150
+ * see an entry still queued inside the `Writable` adapter, because the adapter
1151
+ * has not called `destination.write()` for it yet. Discarding on it is a bet
1152
+ * that a duplicated boot line costs less than a lost one — which is the trade
1153
+ * this destination accepts, and which a destination that cannot lose anything
1154
+ * should decline by ignoring the flag and always emitting.
1155
+ *
1156
+ * The cost is stated rather than hidden: when nothing survived, every holding
1157
+ * destination drains, so N of them produce N copies of the boot entries. A
1158
+ * duplicated line in an already-degraded boot is a smaller harm than a lost one,
1159
+ * and it is loud rather than silent.
1160
+ *
1161
+ * A no-op once {@link onInit} succeeded — the buffer was flushed through the
1162
+ * transform there and is already empty.
1163
+ *
1164
+ * @param status.heldEntriesDeliveredElsewhere - Another live sink appears to
1165
+ * have taken everything this one took. A deduplication signal, not a proof —
1166
+ * see `ILogDestination.onRegistryReady` for what it cannot see.
1167
+ */
1168
+ onRegistryReady(status: {
1169
+ readonly heldEntriesDeliveredElsewhere: boolean;
1170
+ }): void;
1049
1171
  /**
1050
1172
  * Hand every buffered entry to `emit`, in arrival order, and empty the buffer.
1051
1173
  *