@bymax-one/nest-logger 1.4.10 → 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.
@@ -80,6 +80,8 @@ function applyDefaults(options) {
80
80
  }),
81
81
  otel: Object.freeze(otel),
82
82
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
83
+ errorOwnFields: options.errorOwnFields ?? "all",
84
+ errorOwnFieldNames: Object.freeze([...options.errorOwnFieldNames ?? []]),
83
85
  serializers: Object.freeze({ ...options.serializers ?? {} }),
84
86
  timestamp: options.timestamp ?? (() => (/* @__PURE__ */ new Date()).toISOString())
85
87
  };
@@ -224,6 +226,20 @@ function validateCustomization(options) {
224
226
  }
225
227
  }
226
228
  }
229
+ function validateErrorFields(options) {
230
+ const mode = options.errorOwnFields;
231
+ if (mode !== void 0 && mode !== "all" && mode !== "safe") {
232
+ reject("errorOwnFields", "must be 'all' or 'safe'", mode);
233
+ }
234
+ const names = options.errorOwnFieldNames;
235
+ if (names === void 0) return;
236
+ if (!Array.isArray(names)) reject("errorOwnFieldNames", "must be an array of strings", names);
237
+ names.forEach((entry, index) => {
238
+ if (!isNonEmptyString(entry)) {
239
+ reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry);
240
+ }
241
+ });
242
+ }
227
243
  var UNREADABLE = /* @__PURE__ */ Symbol("unreadable");
228
244
  function readMember(destination, key) {
229
245
  try {
@@ -295,6 +311,7 @@ function validateOptions(options) {
295
311
  validateCore(options);
296
312
  validateClosedSets(options);
297
313
  validateCustomization(options);
314
+ validateErrorFields(options);
298
315
  validateDestinations(options);
299
316
  validateHttp(options);
300
317
  validateOtel(options);
@@ -350,6 +367,20 @@ var PROTOTYPE_POLLUTING_KEYS = /* @__PURE__ */ new Set([
350
367
  "prototype"
351
368
  ]);
352
369
 
370
+ // src/server/utils/bounded-text.util.ts
371
+ var MAX_TEXT_LENGTH = 16384;
372
+ var TEXT_TRUNCATED = "\u2026[truncated]";
373
+ function cutIfText(value) {
374
+ return typeof value === "string" ? cutText(value) : value;
375
+ }
376
+ function cutText(text, alreadyCut = false) {
377
+ if (!alreadyCut && text.length <= MAX_TEXT_LENGTH) return text;
378
+ const head = text.slice(0, MAX_TEXT_LENGTH);
379
+ const last = head.charCodeAt(head.length - 1);
380
+ const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
381
+ return whole + TEXT_TRUNCATED;
382
+ }
383
+
353
384
  // src/server/utils/escape-log-text.util.ts
354
385
  var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\r", "\n", "\x85", "\u2028", "\u2029"]);
355
386
  var UNSAFE_IN_SINGLE_LINE = /[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u2028\u2029]/g;
@@ -363,14 +394,35 @@ function toSingleLineMessage(text) {
363
394
  (char) => LINE_TERMINATORS.has(char) ? "\\n" : toEscapeSequence(char)
364
395
  );
365
396
  }
397
+ function toBoundedMessage(text) {
398
+ return cutText(toSingleLineMessage(text));
399
+ }
366
400
  function escapeControlCharacters(text) {
367
401
  return text.replace(UNSAFE_IN_MULTILINE, toEscapeSequence);
368
402
  }
369
-
370
- // src/server/utils/sanitize-error.util.ts
371
- var DEFAULT_MAX_CAUSE_DEPTH = 3;
372
- var MAX_AGGREGATE_ERRORS = 10;
373
- var CIRCULAR_SENTINEL = "[Circular]";
403
+ function isError(value) {
404
+ try {
405
+ return types.isNativeError(value) || value instanceof Error;
406
+ } catch {
407
+ return false;
408
+ }
409
+ }
410
+ var DEFAULT_SAFE_ERROR_FIELDS = [
411
+ "code",
412
+ "errno",
413
+ "syscall",
414
+ "signal",
415
+ "status",
416
+ "statusCode",
417
+ "address",
418
+ "port",
419
+ "hostname",
420
+ "constraint",
421
+ "table",
422
+ "column",
423
+ "schema",
424
+ "routine"
425
+ ];
374
426
  var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
375
427
  "name",
376
428
  "message",
@@ -378,15 +430,47 @@ var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
378
430
  "cause",
379
431
  "errors"
380
432
  ]);
433
+ var ALL_OWN_FIELDS = { safe: false, names: /* @__PURE__ */ new Set() };
434
+ function createOwnFieldPolicy(mode, extraNames) {
435
+ if (mode === "all") return ALL_OWN_FIELDS;
436
+ return { safe: true, names: /* @__PURE__ */ new Set([...DEFAULT_SAFE_ERROR_FIELDS, ...extraNames]) };
437
+ }
438
+ function allowsOwnField(policy, key) {
439
+ return !policy.safe || DERIVED_ERROR_FIELDS.has(key) || key === "_errorFieldsIncomplete" || policy.names.has(key);
440
+ }
441
+ var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
442
+ Object.getPrototypeOf(Uint8Array.prototype),
443
+ "byteLength"
444
+ )?.get;
445
+ var DATA_VIEW_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(DataView.prototype, "byteLength")?.get;
446
+ function binaryMarker(view) {
447
+ const size = types.isDataView(view) ? DATA_VIEW_BYTE_LENGTH.call(view) : TYPED_ARRAY_BYTE_LENGTH.call(view);
448
+ return `[Binary ${size} bytes]`;
449
+ }
450
+ function withBinaryAsSize(value) {
451
+ if (ArrayBuffer.isView(value)) return binaryMarker(value);
452
+ if (!Array.isArray(value) || !value.some((member) => ArrayBuffer.isView(member))) return value;
453
+ return value.map(
454
+ (member) => ArrayBuffer.isView(member) ? binaryMarker(member) : member
455
+ );
456
+ }
457
+
458
+ // src/server/utils/sanitize-error.util.ts
459
+ var DEFAULT_MAX_CAUSE_DEPTH = 3;
460
+ var MAX_AGGREGATE_ERRORS = 10;
461
+ var CIRCULAR_SENTINEL = "[Circular]";
381
462
  function sanitizeError(err, options) {
382
- const maxCauseDepth = DEFAULT_MAX_CAUSE_DEPTH;
383
- return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, maxCauseDepth);
463
+ const maxCauseDepth = options?.maxCauseDepth ?? DEFAULT_MAX_CAUSE_DEPTH;
464
+ return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, {
465
+ maxDepth: maxCauseDepth,
466
+ ownFields: options?.ownFields ?? ALL_OWN_FIELDS
467
+ });
384
468
  }
385
469
  function isErrorLike(value) {
386
470
  try {
387
471
  return readsAsError(value);
388
472
  } catch {
389
- return isErrorInstance(value);
473
+ return isError(value);
390
474
  }
391
475
  }
392
476
  function readsAsError(value) {
@@ -396,40 +480,32 @@ function readsAsError(value) {
396
480
  const candidate = value;
397
481
  return typeof candidate.name === "string" && typeof candidate.message === "string";
398
482
  }
399
- function isErrorInstance(value) {
400
- try {
401
- return value instanceof Error;
402
- } catch {
403
- return false;
404
- }
405
- }
406
- function toSanitizedError(value, seen, depth2, maxDepth) {
483
+ function toSanitizedError(value, seen, depth2, walk2) {
407
484
  try {
408
485
  if (!readsAsError(value)) {
409
- return { name: "UnknownError", message: String(value) };
486
+ return { name: "UnknownError", message: cutText(String(value)) };
410
487
  }
411
488
  seen.add(value);
412
- const result = { name: value.name, message: value.message };
489
+ const result = { name: cutText(value.name), message: cutText(value.message) };
413
490
  const stack = readOptional(() => value.stack, result);
414
491
  if (stack !== void 0) {
415
492
  result.stack = scrubStack(stack);
416
493
  }
417
- const isAtDepthLimit = depth2 >= maxDepth;
494
+ const isAtDepthLimit = depth2 >= walk2.maxDepth;
418
495
  const cause = readOptional(() => value.cause, result);
419
496
  if (cause !== void 0) {
420
- result.cause = isAtDepthLimit ? createDepthMarker() : toSanitizedChild(cause, seen, depth2 + 1, maxDepth);
497
+ result.cause = isAtDepthLimit ? createDepthMarker() : toSanitizedChild(cause, seen, depth2 + 1, walk2);
421
498
  }
422
499
  const aggregated = readAggregatedErrors(value);
423
500
  if (aggregated !== void 0) {
424
501
  const capped = aggregated.slice(0, MAX_AGGREGATE_ERRORS);
425
502
  result.errors = capped.map(
426
- (inner) => isAtDepthLimit ? createDepthMarker() : toSanitizedChild(inner, seen, depth2 + 1, maxDepth)
503
+ (inner) => isAtDepthLimit ? createDepthMarker() : toSanitizedChild(inner, seen, depth2 + 1, walk2)
427
504
  );
428
- if (aggregated.length > MAX_AGGREGATE_ERRORS) {
429
- result.errors.push(createWidthMarker(aggregated.length - MAX_AGGREGATE_ERRORS));
430
- }
505
+ const left = carriedOmitted(aggregated) || aggregated.length - MAX_AGGREGATE_ERRORS;
506
+ if (left > 0) result.errors.push(createWidthMarker(left));
431
507
  }
432
- assignOwnErrorFields(result, value);
508
+ assignOwnErrorFields(result, value, walk2.ownFields);
433
509
  return result;
434
510
  } catch {
435
511
  return { name: "SanitizeFailed", message: "Failed to sanitize the thrown value" };
@@ -443,21 +519,27 @@ function isDatabaseError(source) {
443
519
  const code = Object.getOwnPropertyDescriptor(source, "code")?.value;
444
520
  return typeof code === "string" && SQLSTATE.test(code);
445
521
  }
446
- function ownFieldForLog(source, key, value) {
522
+ function ownFieldForLog(source, key, value, policy = ALL_OWN_FIELDS) {
523
+ if (!allowsOwnField(policy, key)) return OMIT_OWN_FIELD;
447
524
  if (ARGUMENT_FIELDS.has(key.toLowerCase())) return OMIT_OWN_FIELD;
448
525
  if (DATABASE_VALUE_FIELDS.has(key) && isDatabaseError(source)) return OMIT_OWN_FIELD;
449
- if (key !== "command" || typeof value !== "object" || value === null) return value;
526
+ if (key !== "command" || typeof value !== "object" || value === null) {
527
+ return withBinaryAsSize(value);
528
+ }
450
529
  const name = Object.getOwnPropertyDescriptor(value, "name")?.value;
451
530
  return typeof name === "string" ? { name } : OMIT_OWN_FIELD;
452
531
  }
453
- function assignOwnErrorFields(target, source) {
532
+ function defineErrorField(target, key, value) {
533
+ Object.defineProperty(target, key, { value, enumerable: true });
534
+ }
535
+ function assignOwnErrorFields(target, source, policy = ALL_OWN_FIELDS) {
454
536
  try {
455
537
  const own = Array.isArray(source) ? {} : source;
456
538
  for (const [key, field] of Object.entries(own)) {
457
- const value = ownFieldForLog(own, key, field);
539
+ const value = ownFieldForLog(own, key, field, policy);
458
540
  if (value === OMIT_OWN_FIELD) continue;
459
541
  if (!Object.hasOwn(target, key) && !DERIVED_ERROR_FIELDS.has(key)) {
460
- Object.defineProperty(target, key, { value, enumerable: true });
542
+ defineErrorField(target, key, value);
461
543
  }
462
544
  }
463
545
  } catch {
@@ -475,34 +557,32 @@ function readOptional(read, node) {
475
557
  return void 0;
476
558
  }
477
559
  }
478
- function toSanitizedChild(value, seen, depth2, maxDepth) {
560
+ function toSanitizedChild(value, seen, depth2, walk2) {
479
561
  if (isObject(value) && seen.has(value)) {
480
562
  return CIRCULAR_SENTINEL;
481
563
  }
482
- return toSanitizedError(value, seen, depth2, maxDepth);
564
+ return toSanitizedError(value, seen, depth2, walk2);
565
+ }
566
+ function carriedOmitted(list) {
567
+ if (list.length > MAX_AGGREGATE_ERRORS + 1) return 0;
568
+ try {
569
+ const cut = list.at(MAX_AGGREGATE_ERRORS);
570
+ const omitted = cut?._truncated === true ? cut._omitted : void 0;
571
+ return Number.isInteger(omitted) ? Math.max(omitted, 0) : 0;
572
+ } catch {
573
+ return 0;
574
+ }
483
575
  }
484
576
  function readAggregatedErrors(value) {
485
577
  const candidate = value.errors;
486
578
  return Array.isArray(candidate) ? candidate : void 0;
487
579
  }
488
- var MAX_STACK_LENGTH = 16384;
489
- var STACK_TRUNCATED = "\u2026[truncated]";
490
- var MAX_STACK_SCAN = 8 * MAX_STACK_LENGTH;
580
+ var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
491
581
  function scrubStack(stack) {
492
582
  const scrubbed = escapeControlCharacters(
493
583
  stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
494
584
  );
495
- return cutAtLimit(scrubbed, stack.length > MAX_STACK_SCAN);
496
- }
497
- function cutAtLimit(text, alreadyCut) {
498
- if (!alreadyCut && text.length <= MAX_STACK_LENGTH) return text;
499
- const head = text.slice(0, MAX_STACK_LENGTH);
500
- const last = head.charCodeAt(head.length - 1);
501
- const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
502
- return whole + STACK_TRUNCATED;
503
- }
504
- function cutStack(stack) {
505
- return cutAtLimit(stack, false);
585
+ return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
506
586
  }
507
587
  function isObject(value) {
508
588
  return typeof value === "object" && value !== null;
@@ -537,14 +617,14 @@ function withoutOwnedKeys(metadata) {
537
617
  }
538
618
  function safeErrorMessage(error) {
539
619
  try {
540
- return toSingleLineMessage(String(error.message));
620
+ return toBoundedMessage(String(error.message));
541
621
  } catch {
542
622
  return "Unreadable error message";
543
623
  }
544
624
  }
545
625
  function safeLogMessage(message) {
546
626
  try {
547
- return toSingleLineMessage(typeof message === "string" ? message : String(message));
627
+ return toBoundedMessage(typeof message === "string" ? message : String(message));
548
628
  } catch {
549
629
  return "Unreadable log message";
550
630
  }
@@ -618,7 +698,7 @@ var PinoLoggerService = class {
618
698
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
619
699
  const payload = {};
620
700
  assignIfDefined(payload, "context", context);
621
- assignIfDefined(payload, "stack", stack === void 0 ? stack : cutStack(stack));
701
+ assignIfDefined(payload, "stack", stack === void 0 ? stack : cutText(stack));
622
702
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
623
703
  this.pino.error(payload, safeLogMessage(message));
624
704
  }
@@ -764,7 +844,7 @@ var PinoLoggerService = class {
764
844
  const payload = { ...withoutOwnedKeys(metadata), logKey };
765
845
  assignIfDefined(payload, "userId", userId);
766
846
  assignIfDefined(payload, "context", this.context);
767
- const line = toSingleLineMessage(message);
847
+ const line = toBoundedMessage(message);
768
848
  if (level === "info") {
769
849
  this.pino.info(payload, line);
770
850
  } else {
@@ -997,7 +1077,7 @@ function readRecordedError(req) {
997
1077
  return Reflect.get(req, RECORDED_ERROR);
998
1078
  }
999
1079
  function toError(thrown) {
1000
- return thrown instanceof Error ? thrown : new Error(String(thrown));
1080
+ return isError(thrown) ? thrown : new Error(String(thrown));
1001
1081
  }
1002
1082
  function readUserId(req) {
1003
1083
  return req.user?.sub ?? req.user?.id;
@@ -1158,7 +1238,7 @@ var HttpLoggingInterceptor = class {
1158
1238
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
1159
1239
  `${method} ${url} \u2192 ${statusCode}`,
1160
1240
  userId,
1161
- { method, url, statusCode, duration, errorMessage: err.message }
1241
+ { method, url, statusCode, duration, errorMessage: cutIfText(err.message) }
1162
1242
  );
1163
1243
  }
1164
1244
  return;
@@ -1288,10 +1368,10 @@ function reportDestinationFailure(logKey, name, cause, msg) {
1288
1368
  var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
1289
1369
  function describeCause(cause) {
1290
1370
  try {
1291
- return cause instanceof Error ? {
1292
- type: toSingleLineMessage(String(cause.name)),
1293
- message: toSingleLineMessage(String(cause.message))
1294
- } : { type: "UnknownError", message: toSingleLineMessage(String(cause)) };
1371
+ return isError(cause) ? {
1372
+ type: toBoundedMessage(String(cause.name)),
1373
+ message: toBoundedMessage(String(cause.message))
1374
+ } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
1295
1375
  } catch {
1296
1376
  return UNREADABLE_CAUSE;
1297
1377
  }
@@ -1481,29 +1561,114 @@ function destinationToStream(destination, health) {
1481
1561
  });
1482
1562
  }
1483
1563
 
1564
+ // src/server/utils/redact-error-parts.util.ts
1565
+ function defineOwn(target, key, value) {
1566
+ Reflect.defineProperty(target, key, { value, enumerable: true });
1567
+ }
1568
+ var linkDepths = /* @__PURE__ */ new WeakMap();
1569
+ var ERROR_TEXT_FIELDS = /* @__PURE__ */ new Set(["name", "message", "stack"]);
1570
+ var INCOMPLETE_KEY = "_errorFieldsIncomplete";
1571
+ var widthMarkers = /* @__PURE__ */ new WeakSet();
1572
+ function capErrors(errors, host) {
1573
+ if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
1574
+ if (host.hasToJson(errors)) return errors;
1575
+ const kept = [];
1576
+ for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
1577
+ const marker = createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS);
1578
+ widthMarkers.add(marker);
1579
+ kept.push(marker);
1580
+ return kept;
1581
+ }
1582
+ function linkTargets(value) {
1583
+ const targets = [];
1584
+ const take = (link) => {
1585
+ if (typeof link === "object" && link !== null) targets.push(link);
1586
+ };
1587
+ if (!Array.isArray(value)) take(value);
1588
+ else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
1589
+ return targets;
1590
+ }
1591
+ function walkChainPart(value, level, host, depth2) {
1592
+ const targets = linkTargets(value);
1593
+ if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) {
1594
+ if (Array.isArray(value) && host.nameKey === "name") {
1595
+ return Array.from({ length: value.length }, (_member, index) => {
1596
+ const member = Reflect.get(value, index);
1597
+ return typeof member === "object" && member !== null && widthMarkers.has(member) ? member : createDepthMarker();
1598
+ });
1599
+ }
1600
+ return createDepthMarker();
1601
+ }
1602
+ const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
1603
+ for (const target of targets) linkDepths.set(target, level + 1);
1604
+ try {
1605
+ return host.walk(value, depth2 + 1);
1606
+ } finally {
1607
+ before.forEach((earlier, target) => {
1608
+ if (earlier === void 0) linkDepths.delete(target);
1609
+ else linkDepths.set(target, earlier);
1610
+ });
1611
+ }
1612
+ }
1613
+ function cutOrWalk(value, level, host, depth2) {
1614
+ return typeof value === "string" ? cutText(value) : walkChainPart(value, level, host, depth2);
1615
+ }
1616
+ function addErrorParts(copy, error, ownKeys, host, depth2) {
1617
+ const taken = new Set(ownKeys);
1618
+ const level = linkDepths.get(error) ?? 0;
1619
+ let incomplete = false;
1620
+ const add = (key, covers, read, write = (value) => walkChainPart(value, level, host, depth2)) => {
1621
+ if (taken.has(key)) return;
1622
+ try {
1623
+ const written = write(read());
1624
+ if (written === void 0) return;
1625
+ const covered = covers.some((name) => host.sensitive.has(name));
1626
+ defineOwn(copy, key, covered ? host.censor : written);
1627
+ } catch {
1628
+ incomplete = true;
1629
+ }
1630
+ };
1631
+ add(
1632
+ host.nameKey,
1633
+ [host.nameKey, "name"],
1634
+ () => error.name,
1635
+ (name) => cutOrWalk(name, level, host, depth2)
1636
+ );
1637
+ add(
1638
+ "message",
1639
+ ["message"],
1640
+ () => error.message,
1641
+ (message) => cutOrWalk(message, level, host, depth2)
1642
+ );
1643
+ add(
1644
+ "stack",
1645
+ ["stack", "name", "message"],
1646
+ () => error.stack,
1647
+ (stack) => typeof stack === "string" ? scrubStack(stack) : void 0
1648
+ );
1649
+ add("cause", ["cause"], () => error.cause);
1650
+ add("errors", ["errors"], () => capErrors(error.errors, host));
1651
+ if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
1652
+ }
1653
+
1484
1654
  // src/server/utils/redact-by-name.util.ts
1485
1655
  var REDACT_MAX_TRAVERSAL_DEPTH = 100;
1486
1656
  var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
1487
1657
  var REDACT_MAX_VISITS = 2e5;
1488
1658
  var REDACT_BUDGET_EXCEEDED = "[REDACTION_BUDGET_EXCEEDED]";
1489
1659
  var REDACT_CIRCULAR = "[Circular]";
1490
- function resolveToJson(value) {
1491
- let getter;
1492
- let candidate;
1493
- let current = value;
1660
+ function resolveToJson(value, viaGet = false) {
1661
+ let candidate = viaGet ? Reflect.get(value, "toJSON") : void 0;
1662
+ let current = viaGet ? null : value;
1494
1663
  while (current !== null) {
1495
1664
  const descriptor = Object.getOwnPropertyDescriptor(current, "toJSON");
1496
1665
  if (descriptor !== void 0) {
1497
- getter = descriptor.get;
1498
- candidate = getter === void 0 ? descriptor.value : getter.call(value);
1666
+ candidate = descriptor.get === void 0 ? descriptor.value : descriptor.get.call(value);
1499
1667
  break;
1500
1668
  }
1501
1669
  current = Object.getPrototypeOf(current);
1502
1670
  }
1503
- return {
1504
- method: typeof candidate === "function" ? candidate : void 0,
1505
- fromAccessor: getter !== void 0
1506
- };
1671
+ return { method: typeof candidate === "function" ? candidate : void 0 };
1507
1672
  }
1508
1673
  function cloneError(error) {
1509
1674
  const descriptors = Object.getOwnPropertyDescriptors(error);
@@ -1517,10 +1682,6 @@ function cloneError(error) {
1517
1682
  }
1518
1683
  return clone;
1519
1684
  }
1520
- var BUFFER_TO_JSON = Buffer.prototype.toJSON;
1521
- function defineOwn(target, key, value) {
1522
- Reflect.defineProperty(target, key, { value, enumerable: true });
1523
- }
1524
1685
  function walkArray(value, rules, depth2, ancestors, inSerialized) {
1525
1686
  const length = value.length;
1526
1687
  const copy = [];
@@ -1533,12 +1694,12 @@ function walkArray(value, rules, depth2, ancestors, inSerialized) {
1533
1694
  }
1534
1695
  return copy;
1535
1696
  }
1536
- function walk(value, rules, depth2, ancestors, honorToJson = true, inSerialized = false) {
1697
+ function walk(value, rules, depth2, ancestors, honorToJson, inSerialized = false) {
1537
1698
  if (value === null) {
1538
1699
  return value;
1539
1700
  }
1540
1701
  if (typeof value !== "object" && typeof value !== "function") {
1541
- return value;
1702
+ return typeof value === "symbol" && rules.ownFields.safe ? void 0 : value;
1542
1703
  }
1543
1704
  if (depth2 > REDACT_MAX_TRAVERSAL_DEPTH) {
1544
1705
  return REDACT_DEPTH_EXCEEDED;
@@ -1549,7 +1710,7 @@ function walk(value, rules, depth2, ancestors, honorToJson = true, inSerialized
1549
1710
  if (ancestors.has(value)) {
1550
1711
  return REDACT_CIRCULAR;
1551
1712
  }
1552
- if (value instanceof Error) {
1713
+ if (isError(value)) {
1553
1714
  return walkError(value, rules, depth2, ancestors, honorToJson, inSerialized);
1554
1715
  }
1555
1716
  return walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized);
@@ -1559,17 +1720,26 @@ function walkError(error, rules, depth2, ancestors, honorToJson, inSerialized) {
1559
1720
  return walkObject(error, rules, depth2, ancestors, honorToJson, inSerialized);
1560
1721
  } catch {
1561
1722
  rules.visits.count--;
1562
- return walk(sanitizeError(error), rules, depth2, ancestors, honorToJson, inSerialized);
1723
+ return walk(
1724
+ sanitizeError(error, { ownFields: rules.ownFields }),
1725
+ rules,
1726
+ depth2,
1727
+ ancestors,
1728
+ honorToJson,
1729
+ inSerialized
1730
+ );
1563
1731
  }
1564
1732
  }
1565
1733
  function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized) {
1566
- const resolvedToJson = resolveToJson(value);
1567
- if (!resolvedToJson.fromAccessor && resolvedToJson.method === BUFFER_TO_JSON) {
1568
- return value;
1734
+ if (ArrayBuffer.isView(value)) {
1735
+ return withBinaryAsSize(value);
1569
1736
  }
1737
+ const plain = rules.ownFields.safe;
1738
+ const resolvedToJson = resolveToJson(value, plain);
1570
1739
  ancestors.add(value);
1571
1740
  try {
1572
- const toJson = honorToJson ? resolvedToJson.method : void 0;
1741
+ const ownsItsForm = rules.ownFields.safe && isError(value);
1742
+ const toJson = honorToJson && !ownsItsForm ? resolvedToJson.method : void 0;
1573
1743
  if (toJson !== void 0) {
1574
1744
  if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
1575
1745
  return rules.censor;
@@ -1577,28 +1747,33 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
1577
1747
  return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
1578
1748
  }
1579
1749
  if (typeof value === "function") {
1580
- return value;
1750
+ return plain ? void 0 : value;
1581
1751
  }
1582
1752
  if (Array.isArray(value)) {
1583
1753
  return walkArray(value, rules, depth2, ancestors, inSerialized);
1584
1754
  }
1585
1755
  const source = value;
1586
1756
  const keys = Object.keys(source);
1587
- const asData = value instanceof Error && rules.errorsAsData && !inSerialized;
1588
- const clone = value instanceof Error ? cloneError(value) : void 0;
1757
+ const asData = isError(value) && (plain || rules.errorsAsData && !inSerialized);
1758
+ const clone = isError(value) ? cloneError(value) : void 0;
1589
1759
  const copy = clone !== void 0 && !asData ? clone : {};
1590
- const scrubbed = value instanceof Error && !inSerialized;
1760
+ const scrubbed = isError(value) && (plain || !inSerialized);
1761
+ const omitted = /* @__PURE__ */ new Set();
1591
1762
  for (const key of keys) {
1592
- const current = scrubbed ? ownFieldForLog(source, key, Reflect.get(source, key)) : Reflect.get(source, key);
1763
+ const read = Reflect.get(source, key);
1764
+ const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
1593
1765
  if (current === OMIT_OWN_FIELD) {
1594
1766
  Reflect.deleteProperty(copy, key);
1767
+ omitted.add(key);
1595
1768
  continue;
1596
1769
  }
1597
1770
  defineOwn(
1598
1771
  copy,
1599
1772
  key,
1600
1773
  rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
1601
- current,
1774
+ // An own enumerable `name`, `message` or `stack` of an `Error` is the same text as
1775
+ // the part the walk would add, so it is cut the same way.
1776
+ scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
1602
1777
  rules,
1603
1778
  depth2 + 1,
1604
1779
  ancestors,
@@ -1607,79 +1782,42 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
1607
1782
  )
1608
1783
  );
1609
1784
  }
1610
- if (asData) addErrorParts(copy, value, keys, rules, depth2, ancestors);
1785
+ if (asData) {
1786
+ const written = keys.filter((key) => !omitted.has(key));
1787
+ addErrorParts(
1788
+ copy,
1789
+ value,
1790
+ written,
1791
+ errorPartsHost(rules, ancestors, inSerialized),
1792
+ depth2
1793
+ );
1794
+ }
1611
1795
  return copy;
1612
1796
  } finally {
1613
1797
  ancestors.delete(value);
1614
1798
  }
1615
1799
  }
1616
- var linkDepths = /* @__PURE__ */ new WeakMap();
1617
- var INCOMPLETE_KEY = "_errorFieldsIncomplete";
1618
- function capErrors(errors) {
1619
- if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
1620
- if (resolveToJson(errors).method !== void 0) return errors;
1621
- const kept = [];
1622
- for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
1623
- kept.push(createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS));
1624
- return kept;
1625
- }
1626
- function linkTargets(value) {
1627
- const targets = [];
1628
- const take = (link) => {
1629
- if (typeof link === "object" && link !== null) targets.push(link);
1630
- };
1631
- if (!Array.isArray(value)) take(value);
1632
- else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
1633
- return targets;
1634
- }
1635
- function walkChainPart(value, level, rules, depth2, ancestors) {
1636
- const targets = linkTargets(value);
1637
- if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) return createDepthMarker();
1638
- const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
1639
- for (const target of targets) linkDepths.set(target, level + 1);
1640
- try {
1641
- return walk(value, rules, depth2 + 1, ancestors);
1642
- } finally {
1643
- before.forEach((earlier, target) => {
1644
- if (earlier === void 0) linkDepths.delete(target);
1645
- else linkDepths.set(target, earlier);
1646
- });
1647
- }
1648
- }
1649
- function addErrorParts(copy, error, ownKeys, rules, depth2, ancestors) {
1650
- const taken = new Set(ownKeys);
1651
- const level = linkDepths.get(error) ?? 0;
1652
- let incomplete = false;
1653
- const add = (key, covers, read, write = (value) => walkChainPart(value, level, rules, depth2, ancestors)) => {
1654
- if (taken.has(key)) return;
1655
- try {
1656
- const written = write(read());
1657
- if (written === void 0) return;
1658
- const covered = covers.some((name) => rules.sensitive.has(name));
1659
- defineOwn(copy, key, covered ? rules.censor : written);
1660
- } catch {
1661
- incomplete = true;
1662
- }
1800
+ function errorPartsHost(rules, ancestors, inSerialized) {
1801
+ return {
1802
+ sensitive: rules.sensitive,
1803
+ censor: rules.censor,
1804
+ // What a serializer receives names the error `name`, as the error-like shape it reads does;
1805
+ // everything else keeps the `type` the written entries use.
1806
+ nameKey: inSerialized ? "name" : "type",
1807
+ walk: (value, depth2) => walk(value, rules, depth2, ancestors, true, inSerialized),
1808
+ // Under 'safe' the cap does not read a list's `toJSON`: a list over the cap becomes a fresh array
1809
+ // and is never read for it, and a list within the cap is read once, by the walk.
1810
+ hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
1663
1811
  };
1664
- add("type", ["type", "name"], () => error.name);
1665
- add("message", ["message"], () => error.message);
1666
- add(
1667
- "stack",
1668
- ["stack", "name", "message"],
1669
- () => error.stack,
1670
- (stack) => typeof stack === "string" ? scrubStack(stack) : void 0
1671
- );
1672
- add("cause", ["cause"], () => error.cause);
1673
- add("errors", ["errors"], () => capErrors(error.errors));
1674
- if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
1675
1812
  }
1676
- function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS) {
1813
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS) {
1677
1814
  const rules = {
1678
- sensitive: new Set(fieldNames.map((name) => name.toLowerCase())),
1815
+ sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
1679
1816
  censor,
1680
1817
  serializedKeys: new Set(serializedKeys),
1681
1818
  errorsAsData: serializedKeys !== void 0,
1682
- maxVisits
1819
+ maxVisits,
1820
+ ownFields
1683
1821
  };
1684
1822
  return (value, isRecordRoot = false) => {
1685
1823
  try {
@@ -1856,8 +1994,8 @@ function leafNameOf(path2) {
1856
1994
  }
1857
1995
  return leaf;
1858
1996
  }
1859
- function serializeErrorValue(value_) {
1860
- const sanitized = sanitizeError(value_);
1997
+ function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
1998
+ const sanitized = sanitizeError(value_, { ownFields });
1861
1999
  const serialized = {
1862
2000
  // `type` rather than `name`: the field consumers already query.
1863
2001
  type: sanitized.name,
@@ -1882,11 +2020,11 @@ function withSemconvException(record, format) {
1882
2020
  try {
1883
2021
  const candidate = record["err"];
1884
2022
  if (typeof candidate?.name === "string") {
1885
- record["exception.type"] = candidate.name;
1886
- record["error.type"] = candidate.name;
2023
+ record["exception.type"] = cutText(candidate.name);
2024
+ record["error.type"] = cutText(candidate.name);
1887
2025
  }
1888
2026
  if (typeof candidate?.message === "string") {
1889
- record["exception.message"] = candidate.message;
2027
+ record["exception.message"] = cutText(candidate.message);
1890
2028
  }
1891
2029
  if (typeof candidate?.stack === "string") {
1892
2030
  record["exception.stacktrace"] = scrubStack(candidate.stack);
@@ -1919,20 +2057,28 @@ function withEventName(record, field) {
1919
2057
  }
1920
2058
  var PASS_THROUGH = (value) => value;
1921
2059
  function resolveNameRedactor(options) {
1922
- if (options.redactStrategy !== "names") {
1923
- return PASS_THROUGH;
1924
- }
1925
- return buildNameRedactor(options, true);
2060
+ return buildNameRedactor(options, true, options.redactStrategy === "names");
1926
2061
  }
1927
- function buildNameRedactor(options, nestedErrorsAsData = false) {
1928
- const names = [
2062
+ function ownFieldPolicyOf(options) {
2063
+ return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
2064
+ }
2065
+ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2066
+ const names = coversNames ? [
1929
2067
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
1930
2068
  ...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
1931
- ];
1932
- if (names.length === 0) {
2069
+ ] : [];
2070
+ const ownFields = ownFieldPolicyOf(options);
2071
+ const walks = names.length > 0 || ownFields.safe;
2072
+ if (!walks && resolveRedactOption(options) === void 0) {
1933
2073
  return PASS_THROUGH;
1934
2074
  }
1935
- return nestedErrorsAsData ? createNameRedactor(names, options.redactCensor, ["err", ...Object.keys(options.serializers)]) : createNameRedactor(names, options.redactCensor);
2075
+ return nestedErrorsAsData && walks ? createNameRedactor(
2076
+ names,
2077
+ options.redactCensor,
2078
+ ["err", ...Object.keys(options.serializers)],
2079
+ void 0,
2080
+ ownFields
2081
+ ) : createNameRedactor(names, options.redactCensor, void 0, void 0, ownFields);
1936
2082
  }
1937
2083
  function resolveRedactOption(options) {
1938
2084
  const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
@@ -1945,9 +2091,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
1945
2091
  const maxBytes = options.maxEntrySizeBytes;
1946
2092
  const redactRecord = resolveNameRedactor(options);
1947
2093
  const redactSerialized = buildNameRedactor(options);
2094
+ const ownFields = ownFieldPolicyOf(options);
1948
2095
  const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
1949
2096
  const serializers = {
1950
- err: bound(serializeErrorValue),
2097
+ err: bound((error) => serializeErrorValue(error, ownFields)),
1951
2098
  ...Object.fromEntries(
1952
2099
  Object.entries(options.serializers).map(
1953
2100
  ([key, serializer]) => [key, bound(serializer)]
@@ -2448,7 +2595,7 @@ var DestinationRegistry = class {
2448
2595
  let detail = "UnknownError";
2449
2596
  try {
2450
2597
  const stack = isErrorLike(cause) ? cause.stack : void 0;
2451
- detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutStack(String(stack)));
2598
+ detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
2452
2599
  } catch {
2453
2600
  }
2454
2601
  writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
@@ -2791,7 +2938,7 @@ function isPinoPrettyMissing(cause) {
2791
2938
  }
2792
2939
  function describeFailure(cause) {
2793
2940
  try {
2794
- return toSingleLineMessage(cause instanceof Error ? cause.message : String(cause));
2941
+ return toBoundedMessage(isError(cause) ? cause.message : String(cause));
2795
2942
  } catch {
2796
2943
  return "unreadable value";
2797
2944
  }
@@ -3095,7 +3242,7 @@ var HttpAccessLogMiddleware = class {
3095
3242
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
3096
3243
  `${method} ${url} \u2192 ${statusCode}`,
3097
3244
  userId,
3098
- recorded === void 0 ? meta : { ...meta, errorMessage: recorded.error.message }
3245
+ recorded === void 0 ? meta : { ...meta, errorMessage: cutIfText(recorded.error.message) }
3099
3246
  );
3100
3247
  return;
3101
3248
  }