@bymax-one/nest-logger 1.4.16 → 1.4.18

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.
@@ -25,15 +25,31 @@ var __decorateClass = (decorators, target, key, kind) => {
25
25
  };
26
26
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
27
27
 
28
+ // src/server/constants/lifecycle-timeouts.constants.ts
29
+ var DEFAULT_HOOK_TIMEOUT_MS = 1e4;
30
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
31
+ var DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
32
+ var DEFAULT_QUEUE_MAX_BYTES = 33554432;
33
+ var MIN_QUEUE_MAX_BYTES = 1024;
34
+ var MAX_QUEUE_MAX_BYTES = 2147483647;
35
+
28
36
  // src/server/config/default-options.ts
29
37
  var DEFAULT_HTTP = {
30
38
  isEnabled: false,
31
39
  shouldCaptureExceptions: true,
32
40
  shouldGenerateRequestId: true,
33
41
  excludePaths: [/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/],
42
+ secretPathSegments: [],
34
43
  tenantIdHeader: "x-tenant-id",
35
44
  tenantIdResolver: void 0
36
45
  };
46
+ function resolveShutdown(given) {
47
+ const timeoutMs = given?.timeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
48
+ return Object.freeze({
49
+ timeoutMs,
50
+ drainTimeoutMs: given?.drainTimeoutMs ?? Math.min(DEFAULT_DRAIN_TIMEOUT_MS, timeoutMs)
51
+ });
52
+ }
37
53
  var DEFAULT_OTEL = {
38
54
  shouldAutoInjectTraceContext: true,
39
55
  fieldFormat: "camelCase",
@@ -80,10 +96,16 @@ function applyDefaults(options) {
80
96
  destinations: Object.freeze([...options.destinations ?? []]),
81
97
  http: Object.freeze({
82
98
  ...http,
83
- excludePaths: Object.freeze([...http.excludePaths])
99
+ excludePaths: Object.freeze([...http.excludePaths]),
100
+ secretPathSegments: Object.freeze([...http.secretPathSegments])
84
101
  }),
85
102
  otel: Object.freeze(otel),
86
103
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
104
+ destinationHookTimeoutMs: options.destinationHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS,
105
+ shutdown: resolveShutdown(options.shutdown),
106
+ destinationQueue: Object.freeze({
107
+ maxBytes: options.destinationQueue?.maxBytes ?? DEFAULT_QUEUE_MAX_BYTES
108
+ }),
87
109
  errorOwnFields: options.errorOwnFields ?? "all",
88
110
  errorOwnFieldNames: Object.freeze([...options.errorOwnFieldNames ?? []]),
89
111
  serializers: Object.freeze({ ...options.serializers ?? {} }),
@@ -147,6 +169,41 @@ function checkGroup(path, value) {
147
169
  if (!isRecord(value)) reject(path, "must be an object", value);
148
170
  return value;
149
171
  }
172
+ var MAX_TIMER_MS = 2147483647;
173
+ function checkTimerMs(path, value) {
174
+ if (value === void 0) return;
175
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_TIMER_MS) {
176
+ reject(path, `must be an integer from 1 to ${String(MAX_TIMER_MS)}`, value);
177
+ }
178
+ }
179
+ function validateQueue(options) {
180
+ const queue = checkGroup("destinationQueue", options.destinationQueue);
181
+ const maxBytes = queue?.["maxBytes"];
182
+ if (maxBytes === void 0 || maxBytes === 0) return;
183
+ if (typeof maxBytes !== "number" || !Number.isInteger(maxBytes) || maxBytes < MIN_QUEUE_MAX_BYTES || maxBytes > MAX_QUEUE_MAX_BYTES) {
184
+ reject(
185
+ "destinationQueue.maxBytes",
186
+ `must be 0 (no bound) or an integer from ${String(MIN_QUEUE_MAX_BYTES)} to ${String(MAX_QUEUE_MAX_BYTES)}`,
187
+ maxBytes
188
+ );
189
+ }
190
+ }
191
+ function validateLifecycle(options) {
192
+ checkTimerMs("destinationHookTimeoutMs", options.destinationHookTimeoutMs);
193
+ const shutdown = checkGroup("shutdown", options.shutdown);
194
+ if (shutdown === void 0) return;
195
+ checkTimerMs("shutdown.timeoutMs", shutdown["timeoutMs"]);
196
+ checkTimerMs("shutdown.drainTimeoutMs", shutdown["drainTimeoutMs"]);
197
+ const { timeoutMs, drainTimeoutMs } = shutdown;
198
+ const total = typeof timeoutMs === "number" ? timeoutMs : DEFAULT_SHUTDOWN_TIMEOUT_MS;
199
+ if (typeof drainTimeoutMs === "number" && drainTimeoutMs > total) {
200
+ reject(
201
+ "shutdown.drainTimeoutMs",
202
+ "must not exceed shutdown.timeoutMs, which covers the drain and every onShutdown",
203
+ drainTimeoutMs
204
+ );
205
+ }
206
+ }
150
207
  function validateCore(options) {
151
208
  if (!options.service) {
152
209
  throw new Error("[BymaxLoggerModule] options.service is required");
@@ -280,23 +337,25 @@ function validateDestinations(options) {
280
337
  }
281
338
  destinations.forEach((entry, index) => validateDestination(entry, index));
282
339
  }
340
+ function checkRegExpList(path, value) {
341
+ if (value === void 0) return;
342
+ if (!Array.isArray(value)) {
343
+ reject(path, "must be an array of RegExp", value);
344
+ }
345
+ value.forEach((pattern, index) => {
346
+ if (!util.types.isRegExp(pattern)) {
347
+ reject(`${path}[${String(index)}]`, "must be a RegExp", pattern);
348
+ }
349
+ });
350
+ }
283
351
  function validateHttp(options) {
284
352
  const http = checkGroup("http", options.http);
285
353
  if (http === void 0) return;
286
354
  checkBoolean("http.isEnabled", http["isEnabled"]);
287
355
  checkBoolean("http.shouldCaptureExceptions", http["shouldCaptureExceptions"]);
288
356
  checkBoolean("http.shouldGenerateRequestId", http["shouldGenerateRequestId"]);
289
- const excludePaths = http["excludePaths"];
290
- if (excludePaths !== void 0) {
291
- if (!Array.isArray(excludePaths)) {
292
- reject("http.excludePaths", "must be an array of RegExp", excludePaths);
293
- }
294
- excludePaths.forEach((pattern, index) => {
295
- if (!util.types.isRegExp(pattern)) {
296
- reject(`http.excludePaths[${String(index)}]`, "must be a RegExp", pattern);
297
- }
298
- });
299
- }
357
+ checkRegExpList("http.excludePaths", http["excludePaths"]);
358
+ checkRegExpList("http.secretPathSegments", http["secretPathSegments"]);
300
359
  const tenantIdHeader = http["tenantIdHeader"];
301
360
  if (tenantIdHeader !== void 0 && tenantIdHeader !== false && !isNonEmptyString(tenantIdHeader)) {
302
361
  reject("http.tenantIdHeader", "must be a non-empty string or false", tenantIdHeader);
@@ -324,6 +383,8 @@ function validateOptions(options) {
324
383
  validateCustomization(options);
325
384
  validateErrorFields(options);
326
385
  validateDestinations(options);
386
+ validateLifecycle(options);
387
+ validateQueue(options);
327
388
  validateHttp(options);
328
389
  validateOtel(options);
329
390
  }
@@ -954,6 +1015,15 @@ exports.DefaultStdoutDestination = class DefaultStdoutDestination {
954
1015
  this.minLevel = opts.minLevel;
955
1016
  }
956
1017
  }
1018
+ /**
1019
+ * The bytes `process.stdout` holds that have not reached its reader.
1020
+ *
1021
+ * @returns `process.stdout.writableLength`, in bytes since Node decodes a string chunk to a
1022
+ * buffer before queueing it.
1023
+ */
1024
+ queuedBytes() {
1025
+ return process.stdout.writableLength;
1026
+ }
957
1027
  /**
958
1028
  * Write a serialized JSON log entry (terminated with `\n`) to `stdout`.
959
1029
  *
@@ -1053,32 +1123,89 @@ function readUserAgent(req) {
1053
1123
  return typeof raw === "string" ? raw : UNKNOWN_USER_AGENT;
1054
1124
  }
1055
1125
 
1126
+ // src/server/utils/matches-exclude-path.util.ts
1127
+ function matchesExcludePath(patterns, path) {
1128
+ return patterns.some((pattern) => {
1129
+ if (pattern.global || pattern.sticky) {
1130
+ pattern.lastIndex = 0;
1131
+ }
1132
+ return pattern.test(path);
1133
+ });
1134
+ }
1135
+
1056
1136
  // src/server/utils/normalize-url.util.ts
1057
1137
  var UUID_REGEX = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![0-9a-f])/gi;
1058
1138
  var ULID_REGEX = /\/[0-9A-HJKMNP-TV-Z]{26}(?![0-9A-HJKMNP-TV-Z])/g;
1059
1139
  var NANOID_REGEX = /\/[A-Za-z0-9_-]{21}(?![A-Za-z0-9_-])/g;
1060
1140
  var NUMERIC_ID_REGEX = /\/\d+/g;
1061
1141
  var ID_PLACEHOLDER = "/:id";
1062
- function normalizeUrl(url) {
1063
- return stripQueryString(url).replace(UUID_REGEX, ID_PLACEHOLDER).replace(ULID_REGEX, ID_PLACEHOLDER).replace(NANOID_REGEX, ID_PLACEHOLDER).replace(NUMERIC_ID_REGEX, ID_PLACEHOLDER);
1142
+ var SECRET_PLACEHOLDER = ":redacted";
1143
+ var HEX_SECRET_REGEX = /^[0-9a-f]{32,}$/i;
1144
+ var JWT_SECRET_REGEX = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/;
1145
+ var TOKEN_SECRET_REGEX = /^[A-Za-z0-9_+/-]{32,}={0,2}$/;
1146
+ var SLUG_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)+$/;
1147
+ var HEX_RUN_REGEX = /[0-9a-f]{32}/i;
1148
+ var UUID_SEGMENT_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1149
+ var EMAIL_SECRET_REGEX = /^[^@\s]+@[^@\s.]+(?:\.[^@\s.]+)+$/;
1150
+ function decodeSegment(segment) {
1151
+ try {
1152
+ return decodeURIComponent(segment);
1153
+ } catch {
1154
+ return segment;
1155
+ }
1156
+ }
1157
+ function isSecretSegment(segment, extra) {
1158
+ if (segment === "") return false;
1159
+ const decoded = decodeSegment(segment);
1160
+ return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || hasTokenPart(decoded) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
1161
+ }
1162
+ function hasTokenPart(segment) {
1163
+ return segment.split(".").some(looksLikeToken);
1164
+ }
1165
+ function withoutExtension(segment) {
1166
+ const dot = segment.lastIndexOf(".");
1167
+ const dotAfterStart = dot > 0;
1168
+ return dotAfterStart && segment.length - dot <= 9 ? segment.slice(0, dot) : segment;
1169
+ }
1170
+ function looksLikeToken(value) {
1171
+ return HEX_SECRET_REGEX.test(value) || HEX_RUN_REGEX.test(value) || JWT_SECRET_REGEX.test(value) || TOKEN_SECRET_REGEX.test(value) && !SLUG_REGEX.test(value) && !UUID_SEGMENT_REGEX.test(value);
1172
+ }
1173
+ function secretPathSegments(url, extra = []) {
1174
+ const found = /* @__PURE__ */ new Set();
1175
+ for (const segment of stripQueryString(url).split("/")) {
1176
+ if (isSecretSegment(segment, extra)) found.add(segment);
1177
+ }
1178
+ return [...found];
1179
+ }
1180
+ function scrubSecretSegments(path, extra = []) {
1181
+ return path.split("/").map((segment) => isSecretSegment(segment, extra) ? SECRET_PLACEHOLDER : segment).join("/");
1182
+ }
1183
+ function normalizeUrl(url, extra = []) {
1184
+ return scrubSecretSegments(stripQueryString(url), extra).replace(UUID_REGEX, ID_PLACEHOLDER).replace(ULID_REGEX, ID_PLACEHOLDER).replace(NANOID_REGEX, ID_PLACEHOLDER).replace(NUMERIC_ID_REGEX, ID_PLACEHOLDER);
1064
1185
  }
1065
1186
  function stripQueryString(url) {
1066
1187
  const queryStart = url.indexOf("?");
1067
1188
  return queryStart === -1 ? url : url.slice(0, queryStart);
1068
1189
  }
1069
- function withoutRequestQuery(text, ...urls) {
1190
+ function withoutRequestSecrets(text, extra, ...urls) {
1070
1191
  let result = text;
1192
+ const segments = /* @__PURE__ */ new Set();
1071
1193
  for (const url of urls) {
1072
1194
  if (url === void 0) continue;
1073
1195
  const queryStart = url.indexOf("?");
1074
1196
  if (queryStart !== -1 && url.length - queryStart > 1) {
1075
1197
  result = result.split(url.slice(queryStart)).join("");
1076
1198
  }
1199
+ for (const segment of secretPathSegments(url, extra)) segments.add(segment);
1200
+ }
1201
+ if (segments.size > 0) {
1202
+ const alternation = [...segments].sort((left, right) => right.length - left.length).map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
1203
+ result = result.replace(new RegExp(alternation, "g"), SECRET_PLACEHOLDER);
1077
1204
  }
1078
1205
  return result;
1079
1206
  }
1080
- function withoutRequestQueryIfText(value, ...urls) {
1081
- return typeof value === "string" ? withoutRequestQuery(value, ...urls) : value;
1207
+ function withoutRequestSecretsIfText(value, extra, ...urls) {
1208
+ return typeof value === "string" ? withoutRequestSecrets(value, extra, ...urls) : value;
1082
1209
  }
1083
1210
 
1084
1211
  // src/server/filters/http-exception.filter.ts
@@ -1091,9 +1218,12 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
1091
1218
  * @param logger - The structured logger exception entries are written to.
1092
1219
  * Injected by token explicitly: the package is bundled without
1093
1220
  * `emitDecoratorMetadata`, so implicit class-type injection would not resolve.
1221
+ * @param options - Resolved module options, read for `http.secretPathSegments`. Optional, so a
1222
+ * filter built by hand with the logger alone keeps the built-in credential patterns.
1094
1223
  */
1095
- constructor(logger) {
1224
+ constructor(logger, options) {
1096
1225
  this.logger = logger;
1226
+ this.secretPathSegments = options?.http.secretPathSegments ?? [];
1097
1227
  }
1098
1228
  /**
1099
1229
  * Log the exception at the status-appropriate level and write the JSON
@@ -1107,7 +1237,7 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
1107
1237
  const res = ctx.getResponse();
1108
1238
  const req = ctx.getRequest();
1109
1239
  const userId = req.user?.sub ?? req.user?.id;
1110
- const url = stripQueryString(req.url);
1240
+ const url = scrubSecretSegments(stripQueryString(req.url), this.secretPathSegments);
1111
1241
  if (exception instanceof common.HttpException) {
1112
1242
  const status = exception.getStatus();
1113
1243
  const parserError = readRecordedParserError(req);
@@ -1127,7 +1257,12 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
1127
1257
  } else {
1128
1258
  this.logger.warnStructured(
1129
1259
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1130
- parserError?.logMessage ?? withoutRequestQuery(exception.message, req.originalUrl, req.url),
1260
+ parserError?.logMessage ?? withoutRequestSecrets(
1261
+ exception.message,
1262
+ this.secretPathSegments,
1263
+ req.originalUrl,
1264
+ req.url
1265
+ ),
1131
1266
  userId,
1132
1267
  metadata
1133
1268
  );
@@ -1157,7 +1292,7 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
1157
1292
  const { method, url, userId } = request;
1158
1293
  this.logger.warnStructured(
1159
1294
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1160
- withoutRequestQuery(clientError.logMessage, ...rawUrls),
1295
+ withoutRequestSecrets(clientError.logMessage, this.secretPathSegments, ...rawUrls),
1161
1296
  userId,
1162
1297
  {
1163
1298
  method,
@@ -1192,20 +1327,10 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
1192
1327
  };
1193
1328
  exports.HttpExceptionFilter = __decorateClass([
1194
1329
  common.Catch(),
1195
- __decorateParam(0, common.Inject(exports.PinoLoggerService))
1330
+ __decorateParam(0, common.Inject(exports.PinoLoggerService)),
1331
+ __decorateParam(1, common.Optional()),
1332
+ __decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
1196
1333
  ], exports.HttpExceptionFilter);
1197
-
1198
- // src/server/utils/matches-exclude-path.util.ts
1199
- function matchesExcludePath(patterns, path) {
1200
- return patterns.some((pattern) => {
1201
- if (pattern.global || pattern.sticky) {
1202
- pattern.lastIndex = 0;
1203
- }
1204
- return pattern.test(path);
1205
- });
1206
- }
1207
-
1208
- // src/server/interceptors/http-logging.interceptor.ts
1209
1334
  var HTTP_SUCCESS_MIN = 200;
1210
1335
  exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1211
1336
  /**
@@ -1218,6 +1343,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1218
1343
  constructor(logger, options) {
1219
1344
  this.logger = logger;
1220
1345
  this.excludePaths = options.http.excludePaths;
1346
+ this.secretPathSegments = options.http.secretPathSegments;
1221
1347
  }
1222
1348
  /**
1223
1349
  * Whether a request path bypasses HTTP logging (matches any `excludePaths`).
@@ -1249,7 +1375,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1249
1375
  }
1250
1376
  const userAgent = readUserAgent(req);
1251
1377
  const userId = readUserId(req);
1252
- const normalizedUrl = normalizeUrl(url);
1378
+ const normalizedUrl = normalizeUrl(url, this.secretPathSegments);
1253
1379
  const start = Date.now();
1254
1380
  this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${normalizedUrl}`, userId, {
1255
1381
  method,
@@ -1257,7 +1383,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1257
1383
  // Query string stripped: it may carry secrets (reset tokens, OAuth codes)
1258
1384
  // that Pino's path-based redaction cannot scrub from a string value. The
1259
1385
  // raw (un-normalized) path is kept for per-request debugging.
1260
- fullUrl: stripQueryString(url),
1386
+ fullUrl: scrubSecretSegments(stripQueryString(url), this.secretPathSegments),
1261
1387
  ip,
1262
1388
  userAgent
1263
1389
  });
@@ -1355,7 +1481,9 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1355
1481
  url,
1356
1482
  statusCode,
1357
1483
  duration,
1358
- errorMessage: cutIfText(withoutRequestQueryIfText(err.message, ...rawUrls))
1484
+ errorMessage: cutIfText(
1485
+ withoutRequestSecretsIfText(err.message, this.secretPathSegments, ...rawUrls)
1486
+ )
1359
1487
  }
1360
1488
  );
1361
1489
  }
@@ -1393,7 +1521,9 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1393
1521
  url,
1394
1522
  statusCode: clientError.status,
1395
1523
  duration,
1396
- errorMessage: cutIfText(withoutRequestQueryIfText(clientError.logMessage, ...rawUrls)),
1524
+ errorMessage: cutIfText(
1525
+ withoutRequestSecretsIfText(clientError.logMessage, this.secretPathSegments, ...rawUrls)
1526
+ ),
1397
1527
  bodyParserType: clientError.bodyParserType
1398
1528
  }
1399
1529
  );
@@ -1815,7 +1945,47 @@ var REDACT_COMMON_FIELDS = [
1815
1945
  "cookie",
1816
1946
  "set-cookie",
1817
1947
  "x-api-key",
1818
- "x-auth-token"
1948
+ "x-auth-token",
1949
+ // The spellings systems actually write. The default `'names'` matching is case-insensitive, so
1950
+ // `accessToken` already covers `ACCESSTOKEN`, but not `access_token` (the OAuth wire name) or
1951
+ // `access-token`: those are different names. The legacy `'paths'` engine is case-sensitive, so
1952
+ // the all-lowercase `apikey` and `sessiontoken` are listed too.
1953
+ // OAuth and API credentials, snake case.
1954
+ "access_token",
1955
+ "refresh_token",
1956
+ "id_token",
1957
+ "api_key",
1958
+ "apikey",
1959
+ "api_secret",
1960
+ "client_secret",
1961
+ "signing_secret",
1962
+ "private_key",
1963
+ "secret_key",
1964
+ "secretKey",
1965
+ // The same, kebab case.
1966
+ "access-token",
1967
+ "refresh-token",
1968
+ "id-token",
1969
+ "api-key",
1970
+ "client-secret",
1971
+ "private-key",
1972
+ // Session and CSRF credentials, in the spellings of a cookie, a header and a body field. A bare
1973
+ // `sessionId` is deliberately absent: many applications carry it as a correlation key, and the
1974
+ // only way to get such a field back would be to turn every default off.
1975
+ "proxy-authorization",
1976
+ "session_token",
1977
+ "sessionToken",
1978
+ "sessiontoken",
1979
+ "session-token",
1980
+ "x-csrf-token",
1981
+ "x-xsrf-token",
1982
+ "csrf_token",
1983
+ "csrfToken",
1984
+ "csrf-token",
1985
+ // The password family, snake case.
1986
+ "password_hash",
1987
+ "new_password",
1988
+ "old_password"
1819
1989
  ];
1820
1990
  var REDACT_ABSOLUTE_PATHS = [
1821
1991
  "req.headers.authorization",
@@ -1831,14 +2001,15 @@ var DEFAULT_REDACT_PATHS = [
1831
2001
  ];
1832
2002
 
1833
2003
  // src/server/utils/report-destination-failure.util.ts
1834
- function reportDestinationFailure(logKey, name, cause, msg) {
2004
+ function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0) {
1835
2005
  writeStderrSafely(
1836
2006
  JSON.stringify({
1837
2007
  level: "error",
1838
2008
  logKey,
1839
2009
  destination: toSingleLineMessage(name),
1840
2010
  err: describeCause(cause),
1841
- msg: toSingleLineMessage(msg)
2011
+ msg: toSingleLineMessage(msg),
2012
+ ...suppressed > 0 ? { suppressed } : {}
1842
2013
  }) + "\n"
1843
2014
  );
1844
2015
  }
@@ -1981,29 +2152,108 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
1981
2152
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
1982
2153
  return Array.from(new Set(sources.flat()));
1983
2154
  }
1984
- function reportWriteFailure(destination, cause) {
2155
+ function reportWriteFailure(destination, cause, due) {
1985
2156
  const name = safeDestinationName(destination);
1986
2157
  reportDestinationFailure(
1987
2158
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
1988
2159
  name,
1989
2160
  cause,
1990
- `Log destination "${name}" failed to write; the entry was dropped`
2161
+ `Log destination "${name}" failed to write; the entry was dropped`,
2162
+ due - 1
1991
2163
  );
1992
2164
  }
1993
2165
  function rescueToStdout(payload) {
1994
2166
  writeStdoutSafely(payload);
1995
2167
  }
1996
- function destinationToStream(destination, health) {
1997
- return new stream.Writable({
2168
+ function ownQueuedBytes(destination) {
2169
+ try {
2170
+ const bytes = destination.queuedBytes?.() ?? 0;
2171
+ const positive = Number.isFinite(bytes) && bytes > 0;
2172
+ return positive ? bytes : 0;
2173
+ } catch {
2174
+ return 0;
2175
+ }
2176
+ }
2177
+ var BoundedWritable = class extends stream.Writable {
2178
+ constructor(destination, health, maxBytes, queue, options) {
2179
+ super(options);
2180
+ this.destination = destination;
2181
+ this.health = health;
2182
+ this.maxBytes = maxBytes;
2183
+ this.queue = queue;
2184
+ }
2185
+ /**
2186
+ * A destroyed stream holds nothing: Writable fails the chunks still buffered without calling the
2187
+ * write handler, so nothing else would release their bytes.
2188
+ */
2189
+ _destroy(error, callback) {
2190
+ this.queue.bytes = 0;
2191
+ super._destroy(error, callback);
2192
+ }
2193
+ /** The bytes of NDJSON waiting for the destination, the write in flight included. */
2194
+ get queuedBytes() {
2195
+ return this.queue.bytes;
2196
+ }
2197
+ write(chunk, encodingOrCallback, callback) {
2198
+ if (this.writableEnded || this.destroyed) {
2199
+ return this.forward(chunk, encodingOrCallback, callback);
2200
+ }
2201
+ const bytes = Buffer.byteLength(chunk);
2202
+ const held = this.heldBytes();
2203
+ if (this.maxBytes > 0 && held > 0 && held + bytes > this.maxBytes) {
2204
+ this.dropped();
2205
+ const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
2206
+ done?.();
2207
+ return true;
2208
+ }
2209
+ this.queue.bytes += bytes;
2210
+ return this.forward(chunk, encodingOrCallback, callback);
2211
+ }
2212
+ /** `Writable.write` for either of its two signatures. */
2213
+ forward(chunk, encodingOrCallback, callback) {
2214
+ return typeof encodingOrCallback === "function" ? super.write(chunk, encodingOrCallback) : super.write(chunk, encodingOrCallback ?? "utf8", callback);
2215
+ }
2216
+ /**
2217
+ * What the entry would queue behind. A live destination holds its module queue and what it reports
2218
+ * in a buffer of its own. A failed destination receives nothing, so what it reports does not count,
2219
+ * and the one elected to rescue entries writes them to stdout, whose queue is what grows.
2220
+ */
2221
+ heldBytes() {
2222
+ if (!this.health.isFailed(this.destination)) {
2223
+ return this.queue.bytes + ownQueuedBytes(this.destination);
2224
+ }
2225
+ return this.health.shouldRescue(this.destination) ? this.queue.bytes + process.stdout.writableLength : 0;
2226
+ }
2227
+ /** Count the drop, and write the report when one is due. */
2228
+ dropped() {
2229
+ const due = this.health.recordDrop(this.destination, performance.now());
2230
+ if (due === void 0) return;
2231
+ const name = toSingleLineMessage(safeDestinationName(this.destination));
2232
+ writeStderrSafely(
2233
+ `[DestinationRegistry] Destination "${name}" queue full: ${String(due)} entries dropped since the last report (limit ${String(this.maxBytes)} bytes)
2234
+ `
2235
+ );
2236
+ }
2237
+ };
2238
+ function destinationToStream(destination, health, maxQueueBytes = 0) {
2239
+ const queue = { bytes: 0 };
2240
+ const stream = new BoundedWritable(destination, health, maxQueueBytes, queue, {
1998
2241
  // Keep string chunks as strings (Node's default re-encodes them to Buffers
1999
2242
  // before `_write`): the common Pino path emits NDJSON strings, so this skips
2000
2243
  // a string→Buffer→string round-trip on the hot logging path.
2001
2244
  // Stryker disable next-line BooleanLiteral: equivalent for every chunk this stream receives — with `true`, Node encodes the string to a Buffer and `write()` below decodes it back with `toString('utf-8')`. Pino writes UTF-8 NDJSON strings at the default encoding, so the round-trip returns the identical string. It is NOT equivalent in general: a `write(chunk, 'latin1')` would round-trip through UTF-8 and change non-ASCII bytes, which is unreachable here because nothing writes to this stream but Pino. The flag stays because it skips the round-trip on the hot logging path.
2002
2245
  decodeStrings: false,
2003
- write(chunk, _encoding, callback) {
2246
+ write(chunk, _encoding, settled) {
2247
+ const bytes = Buffer.byteLength(chunk);
2248
+ const callback = (error) => {
2249
+ queue.bytes = Math.max(0, queue.bytes - bytes);
2250
+ settled(error);
2251
+ };
2004
2252
  const onFailure = (cause) => {
2005
- health.markWriteFailed(destination);
2006
- reportWriteFailure(destination, cause);
2253
+ const due = health.recordWriteFailure(destination, performance.now());
2254
+ if (due !== void 0) {
2255
+ reportWriteFailure(destination, cause, due);
2256
+ }
2007
2257
  callback();
2008
2258
  };
2009
2259
  try {
@@ -2036,6 +2286,15 @@ function destinationToStream(destination, health) {
2036
2286
  }
2037
2287
  }
2038
2288
  });
2289
+ return stream;
2290
+ }
2291
+
2292
+ // src/server/utils/censor-raw-headers.util.ts
2293
+ function censorRawHeaders(raw, sensitive, censor) {
2294
+ return raw.map((entry, index) => {
2295
+ const name = index % 2 === 1 ? raw[index - 1] : void 0;
2296
+ return typeof name === "string" && sensitive.has(name.toLowerCase()) ? censor : entry;
2297
+ });
2039
2298
  }
2040
2299
 
2041
2300
  // src/server/utils/redact-error-clone.util.ts
@@ -2155,6 +2414,10 @@ function addErrorParts(copy, error, ownKeys, host, depth2) {
2155
2414
  }
2156
2415
 
2157
2416
  // src/server/utils/redact-by-name.util.ts
2417
+ var RAW_HEADER_KEYS = /* @__PURE__ */ new Set(["rawheaders", "rawtrailers"]);
2418
+ function censorHeaderArray(key, walked, rules) {
2419
+ return RAW_HEADER_KEYS.has(key.toLowerCase()) && Array.isArray(walked) ? censorRawHeaders(walked, rules.headerNames, rules.censor) : walked;
2420
+ }
2158
2421
  var REDACT_MAX_TRAVERSAL_DEPTH = 100;
2159
2422
  var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
2160
2423
  var REDACT_MAX_VISITS = 2e5;
@@ -2283,13 +2546,17 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2283
2546
  defineOwn(
2284
2547
  copy,
2285
2548
  key,
2286
- rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
2287
- scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2288
- rules,
2289
- depth2 + 1,
2290
- ancestors,
2291
- true,
2292
- inSerialized || !honorToJson && rules.serializedKeys.has(key)
2549
+ rules.sensitive.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
2550
+ key,
2551
+ walk(
2552
+ scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2553
+ rules,
2554
+ depth2 + 1,
2555
+ ancestors,
2556
+ true,
2557
+ inSerialized || !honorToJson && rules.serializedKeys.has(key)
2558
+ ),
2559
+ rules
2293
2560
  )
2294
2561
  );
2295
2562
  }
@@ -2319,9 +2586,10 @@ function errorPartsHost(rules, ancestors, inSerialized) {
2319
2586
  hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
2320
2587
  };
2321
2588
  }
2322
- function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames) {
2589
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames) {
2323
2590
  const rules = {
2324
2591
  sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
2592
+ headerNames: new Set(Array.from(headerNames ?? fieldNames, (name) => name.toLowerCase())),
2325
2593
  censor,
2326
2594
  serializedKeys: new Set(serializedKeys),
2327
2595
  errorsAsData: serializedKeys !== void 0,
@@ -2468,6 +2736,39 @@ function extraServiceFields(service) {
2468
2736
  return extras;
2469
2737
  }
2470
2738
 
2739
+ // src/server/utils/serialize-request.util.ts
2740
+ function isObject2(value) {
2741
+ return typeof value === "object" && value !== null;
2742
+ }
2743
+ function isRequest(value) {
2744
+ if (!isObject2(value)) return false;
2745
+ const { rawHeaders, method, socket } = value;
2746
+ return Array.isArray(rawHeaders) || typeof method === "string" && isObject2(socket);
2747
+ }
2748
+ function copyHeaders(headers) {
2749
+ return isObject2(headers) ? { ...headers } : {};
2750
+ }
2751
+ function serializeRequestValue(input, secretSegments = []) {
2752
+ try {
2753
+ if (!isRequest(input)) return input;
2754
+ const url = input.originalUrl ?? input.url;
2755
+ const socket = input.socket;
2756
+ return {
2757
+ method: input.method,
2758
+ url: typeof url === "string" ? scrubSecretSegments(stripQueryString(url), secretSegments) : url,
2759
+ headers: copyHeaders(input.headers),
2760
+ remoteAddress: socket?.remoteAddress
2761
+ };
2762
+ } catch {
2763
+ return { _unserializable: "request" };
2764
+ }
2765
+ }
2766
+ function withSerializedRequest(record, secretSegments = []) {
2767
+ const request = record["req"];
2768
+ const serialized = serializeRequestValue(request, secretSegments);
2769
+ return serialized === request ? record : { ...record, req: serialized };
2770
+ }
2771
+
2471
2772
  // src/server/utils/truncate-large-entries.ts
2472
2773
  var PREVIEW_LENGTH = 200;
2473
2774
  function createSizeBoundedSerializer(baseSerializer, maxBytes) {
@@ -2581,10 +2882,11 @@ function namesInsideErrors(options) {
2581
2882
  return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
2582
2883
  }
2583
2884
  function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2584
- const names = coversNames ? [
2885
+ const allNames = [
2585
2886
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
2586
2887
  ...options.redactPaths.flatMap((path) => leafNameOf(path) ?? [])
2587
- ] : [];
2888
+ ];
2889
+ const names = coversNames ? allNames : [];
2588
2890
  const ownFields = ownFieldPolicyOf(options);
2589
2891
  const walks = names.length > 0 || ownFields.safe;
2590
2892
  if (!walks && resolveRedactOption(options) === void 0) {
@@ -2596,8 +2898,17 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
2596
2898
  ["err", ...Object.keys(options.serializers)],
2597
2899
  void 0,
2598
2900
  ownFields,
2599
- coversNames ? void 0 : namesInsideErrors(options)
2600
- ) : createNameRedactor(names, options.redactCensor, void 0, void 0, ownFields);
2901
+ coversNames ? void 0 : namesInsideErrors(options),
2902
+ allNames
2903
+ ) : createNameRedactor(
2904
+ names,
2905
+ options.redactCensor,
2906
+ void 0,
2907
+ void 0,
2908
+ ownFields,
2909
+ void 0,
2910
+ allNames
2911
+ );
2601
2912
  }
2602
2913
  function resolveRedactOption(options) {
2603
2914
  const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
@@ -2612,6 +2923,7 @@ function buildPinoInstance(options, logContext, destinations, health) {
2612
2923
  const redactSerialized = buildNameRedactor(options);
2613
2924
  const ownFields = ownFieldPolicyOf(options);
2614
2925
  const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
2926
+ const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
2615
2927
  const serializers = {
2616
2928
  err: bound((error) => serializeErrorValue(error, ownFields)),
2617
2929
  ...Object.fromEntries(
@@ -2659,7 +2971,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
2659
2971
  // sensitive, which `pino-factory.spec.ts` pins.
2660
2972
  log: (record) => withSemconvException(
2661
2973
  withEventName(
2662
- redactRecord(record, true),
2974
+ redactRecord(
2975
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2976
+ true
2977
+ ),
2663
2978
  options.eventNameField
2664
2979
  ),
2665
2980
  options.errorFormat
@@ -2684,16 +2999,34 @@ function buildPinoInstance(options, logContext, destinations, health) {
2684
2999
  }
2685
3000
  }
2686
3001
  };
2687
- const streams = destinations.map((destination) => ({
2688
- // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
2689
- // consumer implementing `minLevel` as a throwing getter would fail the factory
2690
- // and the application would never start — earlier than any fail-soft path can
2691
- // contain. Unreadable and absent give the same answer: the module level.
2692
- level: safeMinLevel(destination) ?? options.level,
2693
- stream: destinationToStream(destination, health)
2694
- }));
3002
+ const streams = destinations.map((destination) => {
3003
+ const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
3004
+ health.registerStream(destination, stream);
3005
+ return {
3006
+ // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
3007
+ // consumer implementing `minLevel` as a throwing getter would fail the factory
3008
+ // and the application would never start — earlier than any fail-soft path can
3009
+ // contain. Unreadable and absent give the same answer: the module level.
3010
+ level: safeMinLevel(destination) ?? options.level,
3011
+ stream
3012
+ };
3013
+ });
2695
3014
  return pino__default.default(pinoOptions, pino__default.default.multistream(streams));
2696
3015
  }
3016
+ var DROP_REPORT_INTERVAL_MS = 1e4;
3017
+ function countInWindow(records, destination, now) {
3018
+ const record = records.get(destination) ?? { total: 0, unreported: 0, lastReportAt: void 0 };
3019
+ records.set(destination, record);
3020
+ record.total += 1;
3021
+ record.unreported += 1;
3022
+ if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
3023
+ return void 0;
3024
+ }
3025
+ record.lastReportAt = now;
3026
+ const due = record.unreported;
3027
+ record.unreported = 0;
3028
+ return due;
3029
+ }
2697
3030
  var DestinationHealth = class {
2698
3031
  constructor() {
2699
3032
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
@@ -2737,6 +3070,12 @@ var DestinationHealth = class {
2737
3070
  * when the last one settles.
2738
3071
  */
2739
3072
  this.pendingWrites = /* @__PURE__ */ new Map();
3073
+ /** The `Writable` that fronts each destination, whose buffer is the queue of entries it holds. */
3074
+ this.streams = /* @__PURE__ */ new Map();
3075
+ /** Entries dropped for want of queue room, per destination, and when the last one was reported. */
3076
+ this.drops = /* @__PURE__ */ new Map();
3077
+ /** Writes a destination refused, per destination, and when the last one was reported. */
3078
+ this.writeFailures = /* @__PURE__ */ new Map();
2740
3079
  /**
2741
3080
  * The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
2742
3081
  * every real level so the first `markFailed` always wins the comparison.
@@ -2755,6 +3094,77 @@ var DestinationHealth = class {
2755
3094
  markWriteFailed(destination) {
2756
3095
  this.writeFailed.add(destination);
2757
3096
  }
3097
+ /**
3098
+ * Record one entry dropped because the destination's queue was full, and say whether the drop is
3099
+ * due a report.
3100
+ *
3101
+ * A report is due on the first drop and then at most once every {@link DROP_REPORT_INTERVAL_MS},
3102
+ * so a sustained overflow costs one stderr line per window and not one per entry.
3103
+ *
3104
+ * @param destination - The destination whose queue was full.
3105
+ * @param now - A monotonic reading in milliseconds (`performance.now()`).
3106
+ * @returns The number of drops since the last report when one is due, otherwise `undefined`.
3107
+ */
3108
+ recordDrop(destination, now) {
3109
+ this.writeFailed.add(destination);
3110
+ return countInWindow(this.drops, destination, now);
3111
+ }
3112
+ /**
3113
+ * Record one write the destination refused (it threw or rejected), and say whether the failure is
3114
+ * due a report.
3115
+ *
3116
+ * The destination is marked as having failed a write at once, as {@link markWriteFailed} does; only
3117
+ * the report is windowed, in the same way as {@link recordDrop}: the first failure is due at once
3118
+ * and then at most once every {@link DROP_REPORT_INTERVAL_MS}, so a destination that refuses every
3119
+ * entry costs one stderr line per window and not one per entry.
3120
+ *
3121
+ * @param destination - The destination whose write failed.
3122
+ * @param now - A monotonic reading in milliseconds (`performance.now()`).
3123
+ * @returns The number of failures since the last report, this one included, when one is due,
3124
+ * otherwise `undefined`.
3125
+ */
3126
+ recordWriteFailure(destination, now) {
3127
+ this.writeFailed.add(destination);
3128
+ return countInWindow(this.writeFailures, destination, now);
3129
+ }
3130
+ /**
3131
+ * How many writes a destination has refused since startup.
3132
+ *
3133
+ * @param destination - The destination to ask about.
3134
+ * @returns The count, `0` when none.
3135
+ */
3136
+ failedWriteTotal(destination) {
3137
+ return this.writeFailures.get(destination)?.total ?? 0;
3138
+ }
3139
+ /**
3140
+ * How many entries a destination has had dropped for want of queue room.
3141
+ *
3142
+ * @param destination - The destination to ask about.
3143
+ * @returns The count since startup, `0` when none.
3144
+ */
3145
+ droppedTotal(destination) {
3146
+ return this.drops.get(destination)?.total ?? 0;
3147
+ }
3148
+ /**
3149
+ * Record the stream that fronts a destination, whose buffer is the queue of entries it holds.
3150
+ *
3151
+ * @param destination - The destination.
3152
+ * @param stream - Its `Writable` adapter, read only for the bytes it holds queued.
3153
+ */
3154
+ registerStream(destination, stream) {
3155
+ this.streams.set(destination, stream);
3156
+ }
3157
+ /**
3158
+ * How much a destination still holds: the size of what Pino has written to its stream and the
3159
+ * destination has not yet taken, the write in flight included. Zero means nothing is queued.
3160
+ *
3161
+ * @param destination - The destination to ask about.
3162
+ * @returns The queued size in bytes of NDJSON, `0` for a
3163
+ * destination whose stream is not known.
3164
+ */
3165
+ queuedSize(destination) {
3166
+ return this.streams.get(destination)?.queuedBytes ?? 0;
3167
+ }
2758
3168
  /**
2759
3169
  * Record that an asynchronous write to a destination has started.
2760
3170
  *
@@ -2864,6 +3274,34 @@ var DestinationHealth = class {
2864
3274
  DestinationHealth = __decorateClass([
2865
3275
  common.Injectable()
2866
3276
  ], DestinationHealth);
3277
+
3278
+ // src/server/utils/with-timeout.util.ts
3279
+ var HookTimeoutError = class extends Error {
3280
+ constructor(timeoutMs) {
3281
+ super(`did not settle within ${String(timeoutMs)} ms`);
3282
+ this.timeoutMs = timeoutMs;
3283
+ this.name = "HookTimeoutError";
3284
+ }
3285
+ };
3286
+ function withTimeout(work, ms) {
3287
+ return new Promise((resolve, reject2) => {
3288
+ const timer = setTimeout(() => {
3289
+ reject2(new HookTimeoutError(ms));
3290
+ }, ms);
3291
+ const settle = (done) => (...args) => {
3292
+ clearTimeout(timer);
3293
+ done(...args);
3294
+ };
3295
+ try {
3296
+ Promise.resolve(work()).then(settle(resolve), settle(reject2));
3297
+ } catch (cause) {
3298
+ settle(reject2)(cause);
3299
+ }
3300
+ });
3301
+ }
3302
+
3303
+ // src/server/services/destination-registry.service.ts
3304
+ var DRAIN_POLL_MS = 5;
2867
3305
  var DestinationRegistry = class {
2868
3306
  /**
2869
3307
  * @param registered - Every destination declared under
@@ -2908,7 +3346,7 @@ var DestinationRegistry = class {
2908
3346
  async onModuleInit() {
2909
3347
  for (const destination of this.registered) {
2910
3348
  try {
2911
- await destination.onInit?.();
3349
+ await withTimeout(() => destination.onInit?.(), this.options.destinationHookTimeoutMs);
2912
3350
  this.active.push(destination);
2913
3351
  this.health.markHealthy(destination, this.effectiveLevelOf(destination));
2914
3352
  } catch (cause) {
@@ -2940,12 +3378,15 @@ var DestinationRegistry = class {
2940
3378
  async notifyRegistryReady() {
2941
3379
  for (const destination of this.registered) {
2942
3380
  try {
2943
- await destination.onRegistryReady?.({
2944
- heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
2945
- destination,
2946
- this.effectiveLevelOf(destination)
2947
- )
2948
- });
3381
+ await withTimeout(
3382
+ () => destination.onRegistryReady?.({
3383
+ heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
3384
+ destination,
3385
+ this.effectiveLevelOf(destination)
3386
+ )
3387
+ }),
3388
+ this.options.destinationHookTimeoutMs
3389
+ );
2949
3390
  } catch (cause) {
2950
3391
  this.reportHookFailure(destination, cause);
2951
3392
  }
@@ -3063,6 +3504,9 @@ var DestinationRegistry = class {
3063
3504
  * point in the shutdown sequence.
3064
3505
  */
3065
3506
  async onApplicationShutdown() {
3507
+ const startedAt = performance.now();
3508
+ const { timeoutMs, drainTimeoutMs } = this.options.shutdown;
3509
+ const deadline = startedAt + timeoutMs;
3066
3510
  this.logger.info(
3067
3511
  RESERVED_LOG_KEYS.LOGGER_SHUTDOWN_OK,
3068
3512
  "BymaxLoggerModule shutting down",
@@ -3072,13 +3516,82 @@ var DestinationRegistry = class {
3072
3516
  await new Promise((resolve) => {
3073
3517
  setImmediate(resolve);
3074
3518
  });
3519
+ await this.drain(Math.min(deadline, startedAt + drainTimeoutMs));
3520
+ const skipped = [];
3075
3521
  for (const destination of [...this.active].reverse()) {
3522
+ const remaining = deadline - performance.now();
3523
+ if (remaining <= 0) {
3524
+ skipped.push(toSingleLineMessage(safeDestinationName(destination)));
3525
+ continue;
3526
+ }
3076
3527
  try {
3077
- await destination.onShutdown?.();
3528
+ await withTimeout(() => destination.onShutdown?.(), remaining);
3078
3529
  } catch (cause) {
3079
3530
  this.reportShutdownFailure(destination, cause);
3080
3531
  }
3081
3532
  }
3533
+ this.reportDropTotals();
3534
+ if (skipped.length > 0) {
3535
+ writeStderrSafely(
3536
+ `[DestinationRegistry] Shutdown budget of ${String(timeoutMs)} ms spent; onShutdown not called for: ${skipped.map((name) => `"${name}"`).join(", ")}
3537
+ `
3538
+ );
3539
+ }
3540
+ }
3541
+ /**
3542
+ * Say, once, how many entries each destination had dropped for want of queue room, when any did.
3543
+ * It carries the name and the count and no entry content.
3544
+ */
3545
+ reportDropTotals() {
3546
+ for (const destination of this.registered) {
3547
+ const name = toSingleLineMessage(safeDestinationName(destination));
3548
+ const total = this.health.droppedTotal(destination);
3549
+ if (total > 0) {
3550
+ writeStderrSafely(
3551
+ `[DestinationRegistry] Destination "${name}" dropped ${String(total)} entries in total because its queue was full
3552
+ `
3553
+ );
3554
+ }
3555
+ const failed = this.health.failedWriteTotal(destination);
3556
+ if (failed > 1) {
3557
+ writeStderrSafely(
3558
+ `[DestinationRegistry] Destination "${name}" failed ${String(failed)} writes in total; each dropped its entry
3559
+ `
3560
+ );
3561
+ }
3562
+ }
3563
+ }
3564
+ /**
3565
+ * Wait until no active destination holds a queued entry, or the drain deadline passes.
3566
+ *
3567
+ * A destination reads its entries from a `Writable` that buffers what Pino has written, and it
3568
+ * takes them one at a time. `onShutdown` is its signal to flush and close, so a write that begins
3569
+ * after it is a write on a closed resource. The wait does not end the streams, because Pino may
3570
+ * still log while the application shuts down, and an entry written after the end of a stream is an
3571
+ * error. An entry written during the wait extends it, up to the deadline. When the deadline ends it,
3572
+ * one line names the destinations and their queued sizes; it carries no entry content.
3573
+ *
3574
+ * @param drainDeadline - The time, in `performance.now()` milliseconds, the wait ends at.
3575
+ */
3576
+ async drain(drainDeadline) {
3577
+ for (; ; ) {
3578
+ const queued = this.active.filter((destination) => this.health.queuedSize(destination) > 0);
3579
+ if (queued.length === 0) return;
3580
+ const remaining = drainDeadline - performance.now();
3581
+ if (remaining <= 0) {
3582
+ const named = queued.map(
3583
+ (destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.health.queuedSize(destination))})`
3584
+ );
3585
+ writeStderrSafely(
3586
+ `[DestinationRegistry] Shutdown drain ended with entries still queued, by size: ${named.join(", ")}
3587
+ `
3588
+ );
3589
+ return;
3590
+ }
3591
+ await new Promise((resolve) => {
3592
+ setTimeout(resolve, Math.min(DRAIN_POLL_MS, remaining));
3593
+ });
3594
+ }
3082
3595
  }
3083
3596
  /**
3084
3597
  * Report a failing `onShutdown` on stderr without letting the report itself
@@ -3582,6 +4095,7 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
3582
4095
  this.logContext = logContext;
3583
4096
  this.isEnabled = options.http.isEnabled;
3584
4097
  this.excludePaths = options.http.excludePaths;
4098
+ this.secretPathSegments = options.http.secretPathSegments;
3585
4099
  }
3586
4100
  /**
3587
4101
  * Emit START, arm the terminal entry on `'close'`, and continue the chain.
@@ -3607,14 +4121,14 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
3607
4121
  }
3608
4122
  markRecorderActive(req);
3609
4123
  const method = req.method;
3610
- const url = normalizeUrl(target);
4124
+ const url = normalizeUrl(target, this.secretPathSegments);
3611
4125
  const start = Date.now();
3612
4126
  this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${url}`, readUserId(req), {
3613
4127
  method,
3614
4128
  url,
3615
4129
  // Query string stripped: it may carry secrets (reset tokens, OAuth codes)
3616
4130
  // that no key-name redaction can scrub out of a string VALUE.
3617
- fullUrl: path,
4131
+ fullUrl: scrubSecretSegments(path, this.secretPathSegments),
3618
4132
  // Conventional for an access log and personal data under GDPR/LGPD. Its
3619
4133
  // fidelity is the app's to establish: behind a proxy it is only the real
3620
4134
  // client when the app configures `trust proxy`, and a value the app has not
@@ -3679,7 +4193,12 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
3679
4193
  recorded === void 0 ? meta : {
3680
4194
  ...meta,
3681
4195
  errorMessage: cutIfText(
3682
- withoutRequestQueryIfText(recorded.error.message, req.originalUrl, req.url)
4196
+ withoutRequestSecretsIfText(
4197
+ recorded.error.message,
4198
+ this.secretPathSegments,
4199
+ req.originalUrl,
4200
+ req.url
4201
+ )
3683
4202
  )
3684
4203
  }
3685
4204
  );
@@ -3767,6 +4286,10 @@ exports.PinoUnexpectedErrorSink = class PinoUnexpectedErrorSink {
3767
4286
  if (report.correlationId !== void 0) {
3768
4287
  metadata["correlationId"] = report.correlationId;
3769
4288
  }
4289
+ if (isCount(report.repeated)) {
4290
+ metadata["repeated"] = report.repeated;
4291
+ }
4292
+ Object.assign(metadata, exceptionFields(report.error));
3770
4293
  this.logger.errorStructured(
3771
4294
  RESERVED_LOG_KEYS.HTTP_UNEXPECTED_ERROR,
3772
4295
  toLoggableError(report.error),
@@ -3790,6 +4313,34 @@ exports.PinoUnexpectedErrorSink = __decorateClass([
3790
4313
  function toLoggableError(value) {
3791
4314
  return isErrorLike(value) ? value : sanitizeError(value);
3792
4315
  }
4316
+ var MAX_CODE_LENGTH = 128;
4317
+ function isCount(value) {
4318
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4319
+ }
4320
+ function isRecord2(value) {
4321
+ return typeof value === "object" && value !== null;
4322
+ }
4323
+ function exceptionFields(error) {
4324
+ try {
4325
+ if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4326
+ const response = error["getResponse"]();
4327
+ if (!isRecord2(response)) return {};
4328
+ const nested = response["error"];
4329
+ const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4330
+ const fields = {};
4331
+ const code = carrier["code"];
4332
+ if (typeof code === "string") {
4333
+ fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4334
+ }
4335
+ const details = carrier["details"];
4336
+ if (isRecord2(details)) {
4337
+ fields["errorDetails"] = details;
4338
+ }
4339
+ return fields;
4340
+ } catch {
4341
+ return {};
4342
+ }
4343
+ }
3793
4344
  var INJECT_LOGGER_CONTEXT_METADATA_KEY = "bymax_logger:context";
3794
4345
  function InjectLogger(context) {
3795
4346
  return (target, propertyKey, parameterIndex) => {