@bymax-one/nest-logger 1.4.9 → 1.4.11

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.
@@ -83,6 +83,8 @@ function applyDefaults(options) {
83
83
  }),
84
84
  otel: Object.freeze(otel),
85
85
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
86
+ errorOwnFields: options.errorOwnFields ?? "all",
87
+ errorOwnFieldNames: Object.freeze([...options.errorOwnFieldNames ?? []]),
86
88
  serializers: Object.freeze({ ...options.serializers ?? {} }),
87
89
  timestamp: options.timestamp ?? (() => (/* @__PURE__ */ new Date()).toISOString())
88
90
  };
@@ -227,6 +229,20 @@ function validateCustomization(options) {
227
229
  }
228
230
  }
229
231
  }
232
+ function validateErrorFields(options) {
233
+ const mode = options.errorOwnFields;
234
+ if (mode !== void 0 && mode !== "all" && mode !== "safe") {
235
+ reject("errorOwnFields", "must be 'all' or 'safe'", mode);
236
+ }
237
+ const names = options.errorOwnFieldNames;
238
+ if (names === void 0) return;
239
+ if (!Array.isArray(names)) reject("errorOwnFieldNames", "must be an array of strings", names);
240
+ names.forEach((entry, index) => {
241
+ if (!isNonEmptyString(entry)) {
242
+ reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry);
243
+ }
244
+ });
245
+ }
230
246
  var UNREADABLE = /* @__PURE__ */ Symbol("unreadable");
231
247
  function readMember(destination, key) {
232
248
  try {
@@ -298,6 +314,7 @@ function validateOptions(options) {
298
314
  validateCore(options);
299
315
  validateClosedSets(options);
300
316
  validateCustomization(options);
317
+ validateErrorFields(options);
301
318
  validateDestinations(options);
302
319
  validateHttp(options);
303
320
  validateOtel(options);
@@ -353,6 +370,20 @@ var PROTOTYPE_POLLUTING_KEYS = /* @__PURE__ */ new Set([
353
370
  "prototype"
354
371
  ]);
355
372
 
373
+ // src/server/utils/bounded-text.util.ts
374
+ var MAX_TEXT_LENGTH = 16384;
375
+ var TEXT_TRUNCATED = "\u2026[truncated]";
376
+ function cutIfText(value) {
377
+ return typeof value === "string" ? cutText(value) : value;
378
+ }
379
+ function cutText(text, alreadyCut = false) {
380
+ if (!alreadyCut && text.length <= MAX_TEXT_LENGTH) return text;
381
+ const head = text.slice(0, MAX_TEXT_LENGTH);
382
+ const last = head.charCodeAt(head.length - 1);
383
+ const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
384
+ return whole + TEXT_TRUNCATED;
385
+ }
386
+
356
387
  // src/server/utils/escape-log-text.util.ts
357
388
  var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\r", "\n", "\x85", "\u2028", "\u2029"]);
358
389
  var UNSAFE_IN_SINGLE_LINE = /[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u2028\u2029]/g;
@@ -366,14 +397,35 @@ function toSingleLineMessage(text) {
366
397
  (char) => LINE_TERMINATORS.has(char) ? "\\n" : toEscapeSequence(char)
367
398
  );
368
399
  }
400
+ function toBoundedMessage(text) {
401
+ return cutText(toSingleLineMessage(text));
402
+ }
369
403
  function escapeControlCharacters(text) {
370
404
  return text.replace(UNSAFE_IN_MULTILINE, toEscapeSequence);
371
405
  }
372
-
373
- // src/server/utils/sanitize-error.util.ts
374
- var DEFAULT_MAX_CAUSE_DEPTH = 3;
375
- var MAX_AGGREGATE_ERRORS = 10;
376
- var CIRCULAR_SENTINEL = "[Circular]";
406
+ function isError(value) {
407
+ try {
408
+ return util.types.isNativeError(value) || value instanceof Error;
409
+ } catch {
410
+ return false;
411
+ }
412
+ }
413
+ var DEFAULT_SAFE_ERROR_FIELDS = [
414
+ "code",
415
+ "errno",
416
+ "syscall",
417
+ "signal",
418
+ "status",
419
+ "statusCode",
420
+ "address",
421
+ "port",
422
+ "hostname",
423
+ "constraint",
424
+ "table",
425
+ "column",
426
+ "schema",
427
+ "routine"
428
+ ];
377
429
  var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
378
430
  "name",
379
431
  "message",
@@ -381,15 +433,47 @@ var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
381
433
  "cause",
382
434
  "errors"
383
435
  ]);
436
+ var ALL_OWN_FIELDS = { safe: false, names: /* @__PURE__ */ new Set() };
437
+ function createOwnFieldPolicy(mode, extraNames) {
438
+ if (mode === "all") return ALL_OWN_FIELDS;
439
+ return { safe: true, names: /* @__PURE__ */ new Set([...DEFAULT_SAFE_ERROR_FIELDS, ...extraNames]) };
440
+ }
441
+ function allowsOwnField(policy, key) {
442
+ return !policy.safe || DERIVED_ERROR_FIELDS.has(key) || key === "_errorFieldsIncomplete" || policy.names.has(key);
443
+ }
444
+ var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
445
+ Object.getPrototypeOf(Uint8Array.prototype),
446
+ "byteLength"
447
+ )?.get;
448
+ var DATA_VIEW_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(DataView.prototype, "byteLength")?.get;
449
+ function binaryMarker(view) {
450
+ const size = util.types.isDataView(view) ? DATA_VIEW_BYTE_LENGTH.call(view) : TYPED_ARRAY_BYTE_LENGTH.call(view);
451
+ return `[Binary ${size} bytes]`;
452
+ }
453
+ function withBinaryAsSize(value) {
454
+ if (ArrayBuffer.isView(value)) return binaryMarker(value);
455
+ if (!Array.isArray(value) || !value.some((member) => ArrayBuffer.isView(member))) return value;
456
+ return value.map(
457
+ (member) => ArrayBuffer.isView(member) ? binaryMarker(member) : member
458
+ );
459
+ }
460
+
461
+ // src/server/utils/sanitize-error.util.ts
462
+ var DEFAULT_MAX_CAUSE_DEPTH = 3;
463
+ var MAX_AGGREGATE_ERRORS = 10;
464
+ var CIRCULAR_SENTINEL = "[Circular]";
384
465
  function sanitizeError(err, options) {
385
- const maxCauseDepth = DEFAULT_MAX_CAUSE_DEPTH;
386
- return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, maxCauseDepth);
466
+ const maxCauseDepth = options?.maxCauseDepth ?? DEFAULT_MAX_CAUSE_DEPTH;
467
+ return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, {
468
+ maxDepth: maxCauseDepth,
469
+ ownFields: options?.ownFields ?? ALL_OWN_FIELDS
470
+ });
387
471
  }
388
472
  function isErrorLike(value) {
389
473
  try {
390
474
  return readsAsError(value);
391
475
  } catch {
392
- return isErrorInstance(value);
476
+ return isError(value);
393
477
  }
394
478
  }
395
479
  function readsAsError(value) {
@@ -399,40 +483,32 @@ function readsAsError(value) {
399
483
  const candidate = value;
400
484
  return typeof candidate.name === "string" && typeof candidate.message === "string";
401
485
  }
402
- function isErrorInstance(value) {
403
- try {
404
- return value instanceof Error;
405
- } catch {
406
- return false;
407
- }
408
- }
409
- function toSanitizedError(value, seen, depth2, maxDepth) {
486
+ function toSanitizedError(value, seen, depth2, walk2) {
410
487
  try {
411
488
  if (!readsAsError(value)) {
412
- return { name: "UnknownError", message: String(value) };
489
+ return { name: "UnknownError", message: cutText(String(value)) };
413
490
  }
414
491
  seen.add(value);
415
- const result = { name: value.name, message: value.message };
492
+ const result = { name: cutText(value.name), message: cutText(value.message) };
416
493
  const stack = readOptional(() => value.stack, result);
417
494
  if (stack !== void 0) {
418
495
  result.stack = scrubStack(stack);
419
496
  }
420
- const isAtDepthLimit = depth2 >= maxDepth;
497
+ const isAtDepthLimit = depth2 >= walk2.maxDepth;
421
498
  const cause = readOptional(() => value.cause, result);
422
499
  if (cause !== void 0) {
423
- result.cause = isAtDepthLimit ? createDepthMarker() : toSanitizedChild(cause, seen, depth2 + 1, maxDepth);
500
+ result.cause = isAtDepthLimit ? createDepthMarker() : toSanitizedChild(cause, seen, depth2 + 1, walk2);
424
501
  }
425
502
  const aggregated = readAggregatedErrors(value);
426
503
  if (aggregated !== void 0) {
427
504
  const capped = aggregated.slice(0, MAX_AGGREGATE_ERRORS);
428
505
  result.errors = capped.map(
429
- (inner) => isAtDepthLimit ? createDepthMarker() : toSanitizedChild(inner, seen, depth2 + 1, maxDepth)
506
+ (inner) => isAtDepthLimit ? createDepthMarker() : toSanitizedChild(inner, seen, depth2 + 1, walk2)
430
507
  );
431
- if (aggregated.length > MAX_AGGREGATE_ERRORS) {
432
- result.errors.push(createWidthMarker(aggregated.length - MAX_AGGREGATE_ERRORS));
433
- }
508
+ const left = carriedOmitted(aggregated) || aggregated.length - MAX_AGGREGATE_ERRORS;
509
+ if (left > 0) result.errors.push(createWidthMarker(left));
434
510
  }
435
- assignOwnErrorFields(result, value);
511
+ assignOwnErrorFields(result, value, walk2.ownFields);
436
512
  return result;
437
513
  } catch {
438
514
  return { name: "SanitizeFailed", message: "Failed to sanitize the thrown value" };
@@ -440,28 +516,33 @@ function toSanitizedError(value, seen, depth2, maxDepth) {
440
516
  }
441
517
  var ARGUMENT_FIELDS = /* @__PURE__ */ new Set(["args", "parameters"]);
442
518
  var DATABASE_VALUE_FIELDS = /* @__PURE__ */ new Set(["detail", "where", "internalQuery"]);
443
- var SQLSTATE = /^[0-9A-Z]{5}$/;
519
+ var SQLSTATE = /^[0-9A-DF-Z][0-9A-Z]{4}$/;
444
520
  var OMIT_OWN_FIELD = /* @__PURE__ */ Symbol("omit-own-field");
445
521
  function isDatabaseError(source) {
446
- const own = (key) => Object.getOwnPropertyDescriptor(source, key)?.value;
447
- const code = own("code");
448
- return typeof own("severity") === "string" && typeof own("routine") === "string" && typeof code === "string" && SQLSTATE.test(code);
522
+ const code = Object.getOwnPropertyDescriptor(source, "code")?.value;
523
+ return typeof code === "string" && SQLSTATE.test(code);
449
524
  }
450
- function ownFieldForLog(source, key, value) {
525
+ function ownFieldForLog(source, key, value, policy = ALL_OWN_FIELDS) {
526
+ if (!allowsOwnField(policy, key)) return OMIT_OWN_FIELD;
451
527
  if (ARGUMENT_FIELDS.has(key.toLowerCase())) return OMIT_OWN_FIELD;
452
528
  if (DATABASE_VALUE_FIELDS.has(key) && isDatabaseError(source)) return OMIT_OWN_FIELD;
453
- if (key !== "command" || typeof value !== "object" || value === null) return value;
529
+ if (key !== "command" || typeof value !== "object" || value === null) {
530
+ return withBinaryAsSize(value);
531
+ }
454
532
  const name = Object.getOwnPropertyDescriptor(value, "name")?.value;
455
533
  return typeof name === "string" ? { name } : OMIT_OWN_FIELD;
456
534
  }
457
- function assignOwnErrorFields(target, source) {
535
+ function defineErrorField(target, key, value) {
536
+ Object.defineProperty(target, key, { value, enumerable: true });
537
+ }
538
+ function assignOwnErrorFields(target, source, policy = ALL_OWN_FIELDS) {
458
539
  try {
459
540
  const own = Array.isArray(source) ? {} : source;
460
541
  for (const [key, field] of Object.entries(own)) {
461
- const value = ownFieldForLog(own, key, field);
542
+ const value = ownFieldForLog(own, key, field, policy);
462
543
  if (value === OMIT_OWN_FIELD) continue;
463
544
  if (!Object.hasOwn(target, key) && !DERIVED_ERROR_FIELDS.has(key)) {
464
- Object.defineProperty(target, key, { value, enumerable: true });
545
+ defineErrorField(target, key, value);
465
546
  }
466
547
  }
467
548
  } catch {
@@ -479,20 +560,32 @@ function readOptional(read, node) {
479
560
  return void 0;
480
561
  }
481
562
  }
482
- function toSanitizedChild(value, seen, depth2, maxDepth) {
563
+ function toSanitizedChild(value, seen, depth2, walk2) {
483
564
  if (isObject(value) && seen.has(value)) {
484
565
  return CIRCULAR_SENTINEL;
485
566
  }
486
- return toSanitizedError(value, seen, depth2, maxDepth);
567
+ return toSanitizedError(value, seen, depth2, walk2);
568
+ }
569
+ function carriedOmitted(list) {
570
+ if (list.length > MAX_AGGREGATE_ERRORS + 1) return 0;
571
+ try {
572
+ const cut = list.at(MAX_AGGREGATE_ERRORS);
573
+ const omitted = cut?._truncated === true ? cut._omitted : void 0;
574
+ return Number.isInteger(omitted) ? Math.max(omitted, 0) : 0;
575
+ } catch {
576
+ return 0;
577
+ }
487
578
  }
488
579
  function readAggregatedErrors(value) {
489
580
  const candidate = value.errors;
490
581
  return Array.isArray(candidate) ? candidate : void 0;
491
582
  }
583
+ var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
492
584
  function scrubStack(stack) {
493
- return escapeControlCharacters(
494
- stack.split("\n").filter((line) => !line.includes("node_modules")).join("\n")
585
+ const scrubbed = escapeControlCharacters(
586
+ stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
495
587
  );
588
+ return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
496
589
  }
497
590
  function isObject(value) {
498
591
  return typeof value === "object" && value !== null;
@@ -527,14 +620,14 @@ function withoutOwnedKeys(metadata) {
527
620
  }
528
621
  function safeErrorMessage(error) {
529
622
  try {
530
- return toSingleLineMessage(String(error.message));
623
+ return toBoundedMessage(String(error.message));
531
624
  } catch {
532
625
  return "Unreadable error message";
533
626
  }
534
627
  }
535
628
  function safeLogMessage(message) {
536
629
  try {
537
- return toSingleLineMessage(typeof message === "string" ? message : String(message));
630
+ return toBoundedMessage(typeof message === "string" ? message : String(message));
538
631
  } catch {
539
632
  return "Unreadable log message";
540
633
  }
@@ -608,7 +701,7 @@ exports.PinoLoggerService = class PinoLoggerService {
608
701
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
609
702
  const payload = {};
610
703
  assignIfDefined(payload, "context", context);
611
- assignIfDefined(payload, "stack", stack);
704
+ assignIfDefined(payload, "stack", stack === void 0 ? stack : cutText(stack));
612
705
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
613
706
  this.pino.error(payload, safeLogMessage(message));
614
707
  }
@@ -754,7 +847,7 @@ exports.PinoLoggerService = class PinoLoggerService {
754
847
  const payload = { ...withoutOwnedKeys(metadata), logKey };
755
848
  assignIfDefined(payload, "userId", userId);
756
849
  assignIfDefined(payload, "context", this.context);
757
- const line = toSingleLineMessage(message);
850
+ const line = toBoundedMessage(message);
758
851
  if (level === "info") {
759
852
  this.pino.info(payload, line);
760
853
  } else {
@@ -987,7 +1080,7 @@ function readRecordedError(req) {
987
1080
  return Reflect.get(req, RECORDED_ERROR);
988
1081
  }
989
1082
  function toError(thrown) {
990
- return thrown instanceof Error ? thrown : new Error(String(thrown));
1083
+ return isError(thrown) ? thrown : new Error(String(thrown));
991
1084
  }
992
1085
  function readUserId(req) {
993
1086
  return req.user?.sub ?? req.user?.id;
@@ -1148,7 +1241,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
1148
1241
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
1149
1242
  `${method} ${url} \u2192 ${statusCode}`,
1150
1243
  userId,
1151
- { method, url, statusCode, duration, errorMessage: err.message }
1244
+ { method, url, statusCode, duration, errorMessage: cutIfText(err.message) }
1152
1245
  );
1153
1246
  }
1154
1247
  return;
@@ -1278,10 +1371,10 @@ function reportDestinationFailure(logKey, name, cause, msg) {
1278
1371
  var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
1279
1372
  function describeCause(cause) {
1280
1373
  try {
1281
- return cause instanceof Error ? {
1282
- type: toSingleLineMessage(String(cause.name)),
1283
- message: toSingleLineMessage(String(cause.message))
1284
- } : { type: "UnknownError", message: toSingleLineMessage(String(cause)) };
1374
+ return isError(cause) ? {
1375
+ type: toBoundedMessage(String(cause.name)),
1376
+ message: toBoundedMessage(String(cause.message))
1377
+ } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
1285
1378
  } catch {
1286
1379
  return UNREADABLE_CAUSE;
1287
1380
  }
@@ -1471,27 +1564,114 @@ function destinationToStream(destination, health) {
1471
1564
  });
1472
1565
  }
1473
1566
 
1567
+ // src/server/utils/redact-error-parts.util.ts
1568
+ function defineOwn(target, key, value) {
1569
+ Reflect.defineProperty(target, key, { value, enumerable: true });
1570
+ }
1571
+ var linkDepths = /* @__PURE__ */ new WeakMap();
1572
+ var ERROR_TEXT_FIELDS = /* @__PURE__ */ new Set(["name", "message", "stack"]);
1573
+ var INCOMPLETE_KEY = "_errorFieldsIncomplete";
1574
+ var widthMarkers = /* @__PURE__ */ new WeakSet();
1575
+ function capErrors(errors, host) {
1576
+ if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
1577
+ if (host.hasToJson(errors)) return errors;
1578
+ const kept = [];
1579
+ for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
1580
+ const marker = createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS);
1581
+ widthMarkers.add(marker);
1582
+ kept.push(marker);
1583
+ return kept;
1584
+ }
1585
+ function linkTargets(value) {
1586
+ const targets = [];
1587
+ const take = (link) => {
1588
+ if (typeof link === "object" && link !== null) targets.push(link);
1589
+ };
1590
+ if (!Array.isArray(value)) take(value);
1591
+ else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
1592
+ return targets;
1593
+ }
1594
+ function walkChainPart(value, level, host, depth2) {
1595
+ const targets = linkTargets(value);
1596
+ if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) {
1597
+ if (Array.isArray(value) && host.nameKey === "name") {
1598
+ return Array.from({ length: value.length }, (_member, index) => {
1599
+ const member = Reflect.get(value, index);
1600
+ return typeof member === "object" && member !== null && widthMarkers.has(member) ? member : createDepthMarker();
1601
+ });
1602
+ }
1603
+ return createDepthMarker();
1604
+ }
1605
+ const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
1606
+ for (const target of targets) linkDepths.set(target, level + 1);
1607
+ try {
1608
+ return host.walk(value, depth2 + 1);
1609
+ } finally {
1610
+ before.forEach((earlier, target) => {
1611
+ if (earlier === void 0) linkDepths.delete(target);
1612
+ else linkDepths.set(target, earlier);
1613
+ });
1614
+ }
1615
+ }
1616
+ function cutOrWalk(value, level, host, depth2) {
1617
+ return typeof value === "string" ? cutText(value) : walkChainPart(value, level, host, depth2);
1618
+ }
1619
+ function addErrorParts(copy, error, ownKeys, host, depth2) {
1620
+ const taken = new Set(ownKeys);
1621
+ const level = linkDepths.get(error) ?? 0;
1622
+ let incomplete = false;
1623
+ const add = (key, covers, read, write = (value) => walkChainPart(value, level, host, depth2)) => {
1624
+ if (taken.has(key)) return;
1625
+ try {
1626
+ const written = write(read());
1627
+ if (written === void 0) return;
1628
+ const covered = covers.some((name) => host.sensitive.has(name));
1629
+ defineOwn(copy, key, covered ? host.censor : written);
1630
+ } catch {
1631
+ incomplete = true;
1632
+ }
1633
+ };
1634
+ add(
1635
+ host.nameKey,
1636
+ [host.nameKey, "name"],
1637
+ () => error.name,
1638
+ (name) => cutOrWalk(name, level, host, depth2)
1639
+ );
1640
+ add(
1641
+ "message",
1642
+ ["message"],
1643
+ () => error.message,
1644
+ (message) => cutOrWalk(message, level, host, depth2)
1645
+ );
1646
+ add(
1647
+ "stack",
1648
+ ["stack", "name", "message"],
1649
+ () => error.stack,
1650
+ (stack) => typeof stack === "string" ? scrubStack(stack) : void 0
1651
+ );
1652
+ add("cause", ["cause"], () => error.cause);
1653
+ add("errors", ["errors"], () => capErrors(error.errors, host));
1654
+ if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
1655
+ }
1656
+
1474
1657
  // src/server/utils/redact-by-name.util.ts
1475
1658
  var REDACT_MAX_TRAVERSAL_DEPTH = 100;
1476
1659
  var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
1660
+ var REDACT_MAX_VISITS = 2e5;
1661
+ var REDACT_BUDGET_EXCEEDED = "[REDACTION_BUDGET_EXCEEDED]";
1477
1662
  var REDACT_CIRCULAR = "[Circular]";
1478
- function resolveToJson(value) {
1479
- let getter;
1480
- let candidate;
1481
- let current = value;
1663
+ function resolveToJson(value, viaGet = false) {
1664
+ let candidate = viaGet ? Reflect.get(value, "toJSON") : void 0;
1665
+ let current = viaGet ? null : value;
1482
1666
  while (current !== null) {
1483
1667
  const descriptor = Object.getOwnPropertyDescriptor(current, "toJSON");
1484
1668
  if (descriptor !== void 0) {
1485
- getter = descriptor.get;
1486
- candidate = getter === void 0 ? descriptor.value : getter.call(value);
1669
+ candidate = descriptor.get === void 0 ? descriptor.value : descriptor.get.call(value);
1487
1670
  break;
1488
1671
  }
1489
1672
  current = Object.getPrototypeOf(current);
1490
1673
  }
1491
- return {
1492
- method: typeof candidate === "function" ? candidate : void 0,
1493
- fromAccessor: getter !== void 0
1494
- };
1674
+ return { method: typeof candidate === "function" ? candidate : void 0 };
1495
1675
  }
1496
1676
  function cloneError(error) {
1497
1677
  const descriptors = Object.getOwnPropertyDescriptors(error);
@@ -1505,10 +1685,6 @@ function cloneError(error) {
1505
1685
  }
1506
1686
  return clone;
1507
1687
  }
1508
- var BUFFER_TO_JSON = Buffer.prototype.toJSON;
1509
- function defineOwn(target, key, value) {
1510
- Reflect.defineProperty(target, key, { value, enumerable: true });
1511
- }
1512
1688
  function walkArray(value, rules, depth2, ancestors, inSerialized) {
1513
1689
  const length = value.length;
1514
1690
  const copy = [];
@@ -1521,20 +1697,23 @@ function walkArray(value, rules, depth2, ancestors, inSerialized) {
1521
1697
  }
1522
1698
  return copy;
1523
1699
  }
1524
- function walk(value, rules, depth2, ancestors, honorToJson = true, inSerialized = false) {
1700
+ function walk(value, rules, depth2, ancestors, honorToJson, inSerialized = false) {
1525
1701
  if (value === null) {
1526
1702
  return value;
1527
1703
  }
1528
1704
  if (typeof value !== "object" && typeof value !== "function") {
1529
- return value;
1705
+ return typeof value === "symbol" && rules.ownFields.safe ? void 0 : value;
1530
1706
  }
1531
1707
  if (depth2 > REDACT_MAX_TRAVERSAL_DEPTH) {
1532
1708
  return REDACT_DEPTH_EXCEEDED;
1533
1709
  }
1710
+ if (++rules.visits.count > rules.maxVisits) {
1711
+ return REDACT_BUDGET_EXCEEDED;
1712
+ }
1534
1713
  if (ancestors.has(value)) {
1535
1714
  return REDACT_CIRCULAR;
1536
1715
  }
1537
- if (value instanceof Error) {
1716
+ if (isError(value)) {
1538
1717
  return walkError(value, rules, depth2, ancestors, honorToJson, inSerialized);
1539
1718
  }
1540
1719
  return walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized);
@@ -1543,17 +1722,27 @@ function walkError(error, rules, depth2, ancestors, honorToJson, inSerialized) {
1543
1722
  try {
1544
1723
  return walkObject(error, rules, depth2, ancestors, honorToJson, inSerialized);
1545
1724
  } catch {
1546
- return walk(sanitizeError(error), rules, depth2, ancestors, honorToJson, inSerialized);
1725
+ rules.visits.count--;
1726
+ return walk(
1727
+ sanitizeError(error, { ownFields: rules.ownFields }),
1728
+ rules,
1729
+ depth2,
1730
+ ancestors,
1731
+ honorToJson,
1732
+ inSerialized
1733
+ );
1547
1734
  }
1548
1735
  }
1549
1736
  function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized) {
1550
- const resolvedToJson = resolveToJson(value);
1551
- if (!resolvedToJson.fromAccessor && resolvedToJson.method === BUFFER_TO_JSON) {
1552
- return value;
1737
+ if (ArrayBuffer.isView(value)) {
1738
+ return withBinaryAsSize(value);
1553
1739
  }
1740
+ const plain = rules.ownFields.safe;
1741
+ const resolvedToJson = resolveToJson(value, plain);
1554
1742
  ancestors.add(value);
1555
1743
  try {
1556
- const toJson = honorToJson ? resolvedToJson.method : void 0;
1744
+ const ownsItsForm = rules.ownFields.safe && isError(value);
1745
+ const toJson = honorToJson && !ownsItsForm ? resolvedToJson.method : void 0;
1557
1746
  if (toJson !== void 0) {
1558
1747
  if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
1559
1748
  return rules.censor;
@@ -1561,28 +1750,33 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
1561
1750
  return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
1562
1751
  }
1563
1752
  if (typeof value === "function") {
1564
- return value;
1753
+ return plain ? void 0 : value;
1565
1754
  }
1566
1755
  if (Array.isArray(value)) {
1567
1756
  return walkArray(value, rules, depth2, ancestors, inSerialized);
1568
1757
  }
1569
1758
  const source = value;
1570
1759
  const keys = Object.keys(source);
1571
- const asData = value instanceof Error && rules.errorsAsData && !inSerialized;
1572
- const clone = value instanceof Error ? cloneError(value) : void 0;
1760
+ const asData = isError(value) && (plain || rules.errorsAsData && !inSerialized);
1761
+ const clone = isError(value) ? cloneError(value) : void 0;
1573
1762
  const copy = clone !== void 0 && !asData ? clone : {};
1574
- const scrubbed = value instanceof Error && !inSerialized;
1763
+ const scrubbed = isError(value) && (plain || !inSerialized);
1764
+ const omitted = /* @__PURE__ */ new Set();
1575
1765
  for (const key of keys) {
1576
- const current = scrubbed ? ownFieldForLog(source, key, Reflect.get(source, key)) : Reflect.get(source, key);
1766
+ const read = Reflect.get(source, key);
1767
+ const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
1577
1768
  if (current === OMIT_OWN_FIELD) {
1578
1769
  Reflect.deleteProperty(copy, key);
1770
+ omitted.add(key);
1579
1771
  continue;
1580
1772
  }
1581
1773
  defineOwn(
1582
1774
  copy,
1583
1775
  key,
1584
1776
  rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
1585
- current,
1777
+ // An own enumerable `name`, `message` or `stack` of an `Error` is the same text as
1778
+ // the part the walk would add, so it is cut the same way.
1779
+ scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
1586
1780
  rules,
1587
1781
  depth2 + 1,
1588
1782
  ancestors,
@@ -1591,92 +1785,47 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
1591
1785
  )
1592
1786
  );
1593
1787
  }
1594
- if (asData) addErrorParts(copy, value, keys, rules, depth2, ancestors);
1788
+ if (asData) {
1789
+ const written = keys.filter((key) => !omitted.has(key));
1790
+ addErrorParts(
1791
+ copy,
1792
+ value,
1793
+ written,
1794
+ errorPartsHost(rules, ancestors, inSerialized),
1795
+ depth2
1796
+ );
1797
+ }
1595
1798
  return copy;
1596
1799
  } finally {
1597
1800
  ancestors.delete(value);
1598
1801
  }
1599
1802
  }
1600
- var linkDepths = /* @__PURE__ */ new WeakMap();
1601
- var INCOMPLETE_KEY = "_errorFieldsIncomplete";
1602
- function capErrors(errors) {
1603
- if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
1604
- if (resolveToJson(errors).method !== void 0) return errors;
1605
- const kept = [];
1606
- for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
1607
- kept.push(createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS));
1608
- return kept;
1609
- }
1610
- function linkTargets(value) {
1611
- const targets = [];
1612
- const take = (link) => {
1613
- if (typeof link === "object" && link !== null) targets.push(link);
1614
- };
1615
- if (!Array.isArray(value)) take(value);
1616
- else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
1617
- return targets;
1618
- }
1619
- function walkChainPart(value, level, rules, depth2, ancestors) {
1620
- const targets = linkTargets(value);
1621
- if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) return createDepthMarker();
1622
- const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
1623
- for (const target of targets) linkDepths.set(target, level + 1);
1624
- try {
1625
- return walk(value, rules, depth2 + 1, ancestors);
1626
- } finally {
1627
- before.forEach((earlier, target) => {
1628
- if (earlier === void 0) linkDepths.delete(target);
1629
- else linkDepths.set(target, earlier);
1630
- });
1631
- }
1632
- }
1633
- function addErrorParts(copy, error, ownKeys, rules, depth2, ancestors) {
1634
- const taken = new Set(ownKeys);
1635
- const level = linkDepths.get(error) ?? 0;
1636
- let incomplete = false;
1637
- const add = (key, covers, read, write = (value) => walk(value, rules, depth2 + 1, ancestors)) => {
1638
- if (taken.has(key)) return;
1639
- try {
1640
- const written = write(read());
1641
- if (written === void 0) return;
1642
- const covered = covers.some((name) => rules.sensitive.has(name));
1643
- defineOwn(copy, key, covered ? rules.censor : written);
1644
- } catch {
1645
- incomplete = true;
1646
- }
1803
+ function errorPartsHost(rules, ancestors, inSerialized) {
1804
+ return {
1805
+ sensitive: rules.sensitive,
1806
+ censor: rules.censor,
1807
+ // What a serializer receives names the error `name`, as the error-like shape it reads does;
1808
+ // everything else keeps the `type` the written entries use.
1809
+ nameKey: inSerialized ? "name" : "type",
1810
+ walk: (value, depth2) => walk(value, rules, depth2, ancestors, true, inSerialized),
1811
+ // Under 'safe' the cap does not read a list's `toJSON`: a list over the cap becomes a fresh array
1812
+ // and is never read for it, and a list within the cap is read once, by the walk.
1813
+ hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
1647
1814
  };
1648
- add("type", ["type", "name"], () => error.name);
1649
- add("message", ["message"], () => error.message);
1650
- add(
1651
- "stack",
1652
- ["stack", "name", "message"],
1653
- () => error.stack,
1654
- (stack) => typeof stack === "string" ? scrubStack(stack) : void 0
1655
- );
1656
- add(
1657
- "cause",
1658
- ["cause"],
1659
- () => error.cause,
1660
- (cause) => walkChainPart(cause, level, rules, depth2, ancestors)
1661
- );
1662
- add(
1663
- "errors",
1664
- ["errors"],
1665
- () => capErrors(error.errors),
1666
- (errors) => walkChainPart(errors, level, rules, depth2, ancestors)
1667
- );
1668
- if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
1669
1815
  }
1670
- function createNameRedactor(fieldNames, censor, serializedKeys) {
1816
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS) {
1671
1817
  const rules = {
1672
- sensitive: new Set(fieldNames.map((name) => name.toLowerCase())),
1818
+ sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
1673
1819
  censor,
1674
1820
  serializedKeys: new Set(serializedKeys),
1675
- errorsAsData: serializedKeys !== void 0
1821
+ errorsAsData: serializedKeys !== void 0,
1822
+ maxVisits,
1823
+ ownFields
1676
1824
  };
1677
1825
  return (value, isRecordRoot = false) => {
1678
1826
  try {
1679
- return walk(value, rules, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
1827
+ const call = { ...rules, visits: { count: 0 } };
1828
+ return walk(value, call, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
1680
1829
  } catch {
1681
1830
  return {
1682
1831
  _redactionFailed: true,
@@ -1848,8 +1997,8 @@ function leafNameOf(path) {
1848
1997
  }
1849
1998
  return leaf;
1850
1999
  }
1851
- function serializeErrorValue(value_) {
1852
- const sanitized = sanitizeError(value_);
2000
+ function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
2001
+ const sanitized = sanitizeError(value_, { ownFields });
1853
2002
  const serialized = {
1854
2003
  // `type` rather than `name`: the field consumers already query.
1855
2004
  type: sanitized.name,
@@ -1874,11 +2023,11 @@ function withSemconvException(record, format) {
1874
2023
  try {
1875
2024
  const candidate = record["err"];
1876
2025
  if (typeof candidate?.name === "string") {
1877
- record["exception.type"] = candidate.name;
1878
- record["error.type"] = candidate.name;
2026
+ record["exception.type"] = cutText(candidate.name);
2027
+ record["error.type"] = cutText(candidate.name);
1879
2028
  }
1880
2029
  if (typeof candidate?.message === "string") {
1881
- record["exception.message"] = candidate.message;
2030
+ record["exception.message"] = cutText(candidate.message);
1882
2031
  }
1883
2032
  if (typeof candidate?.stack === "string") {
1884
2033
  record["exception.stacktrace"] = scrubStack(candidate.stack);
@@ -1911,20 +2060,28 @@ function withEventName(record, field) {
1911
2060
  }
1912
2061
  var PASS_THROUGH = (value) => value;
1913
2062
  function resolveNameRedactor(options) {
1914
- if (options.redactStrategy !== "names") {
1915
- return PASS_THROUGH;
1916
- }
1917
- return buildNameRedactor(options, true);
2063
+ return buildNameRedactor(options, true, options.redactStrategy === "names");
1918
2064
  }
1919
- function buildNameRedactor(options, nestedErrorsAsData = false) {
1920
- const names = [
2065
+ function ownFieldPolicyOf(options) {
2066
+ return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
2067
+ }
2068
+ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2069
+ const names = coversNames ? [
1921
2070
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
1922
2071
  ...options.redactPaths.flatMap((path) => leafNameOf(path) ?? [])
1923
- ];
1924
- if (names.length === 0) {
2072
+ ] : [];
2073
+ const ownFields = ownFieldPolicyOf(options);
2074
+ const walks = names.length > 0 || ownFields.safe;
2075
+ if (!walks && resolveRedactOption(options) === void 0) {
1925
2076
  return PASS_THROUGH;
1926
2077
  }
1927
- return nestedErrorsAsData ? createNameRedactor(names, options.redactCensor, ["err", ...Object.keys(options.serializers)]) : createNameRedactor(names, options.redactCensor);
2078
+ return nestedErrorsAsData && walks ? createNameRedactor(
2079
+ names,
2080
+ options.redactCensor,
2081
+ ["err", ...Object.keys(options.serializers)],
2082
+ void 0,
2083
+ ownFields
2084
+ ) : createNameRedactor(names, options.redactCensor, void 0, void 0, ownFields);
1928
2085
  }
1929
2086
  function resolveRedactOption(options) {
1930
2087
  const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
@@ -1937,9 +2094,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
1937
2094
  const maxBytes = options.maxEntrySizeBytes;
1938
2095
  const redactRecord = resolveNameRedactor(options);
1939
2096
  const redactSerialized = buildNameRedactor(options);
2097
+ const ownFields = ownFieldPolicyOf(options);
1940
2098
  const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
1941
2099
  const serializers = {
1942
- err: bound(serializeErrorValue),
2100
+ err: bound((error) => serializeErrorValue(error, ownFields)),
1943
2101
  ...Object.fromEntries(
1944
2102
  Object.entries(options.serializers).map(
1945
2103
  ([key, serializer]) => [key, bound(serializer)]
@@ -2440,7 +2598,7 @@ var DestinationRegistry = class {
2440
2598
  let detail = "UnknownError";
2441
2599
  try {
2442
2600
  const stack = isErrorLike(cause) ? cause.stack : void 0;
2443
- detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(String(stack));
2601
+ detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
2444
2602
  } catch {
2445
2603
  }
2446
2604
  writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
@@ -2783,7 +2941,7 @@ function isPinoPrettyMissing(cause) {
2783
2941
  }
2784
2942
  function describeFailure(cause) {
2785
2943
  try {
2786
- return toSingleLineMessage(cause instanceof Error ? cause.message : String(cause));
2944
+ return toBoundedMessage(isError(cause) ? cause.message : String(cause));
2787
2945
  } catch {
2788
2946
  return "unreadable value";
2789
2947
  }
@@ -3087,7 +3245,7 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
3087
3245
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
3088
3246
  `${method} ${url} \u2192 ${statusCode}`,
3089
3247
  userId,
3090
- recorded === void 0 ? meta : { ...meta, errorMessage: recorded.error.message }
3248
+ recorded === void 0 ? meta : { ...meta, errorMessage: cutIfText(recorded.error.message) }
3091
3249
  );
3092
3250
  return;
3093
3251
  }