@bymax-one/nest-logger 1.4.21 → 1.4.22

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.
package/CHANGELOG.md CHANGED
@@ -12,6 +12,85 @@ heading here.
12
12
 
13
13
  ## [Unreleased]
14
14
 
15
+ ## [1.4.22] - 2026-11-17
16
+
17
+ ### Breaking
18
+
19
+ - **`maxEntrySizeBytes` is at most 2147483647.** A value such as `2 ** 53` or `1e300` was accepted
20
+ and could never be reached by an entry. `forRoot` now rejects it with
21
+ `options.maxEntrySizeBytes must be at most 2147483647`.
22
+ **Apply:** pass a ceiling of at most 2147483647 bytes; the default and every value up to that are
23
+ unaffected.
24
+
25
+ - **A `maxStringLength` outside 64 to 2147483647 is refused.** 1.4.21 did not read an option of that
26
+ name, so a key `maxStringLength` was ignored whatever it held. It is validated at startup now
27
+ (`options.maxStringLength must be an integer from 64 to 2147483647`), and a value such as `10`,
28
+ `64.5` or `'100'` stops the application from starting. **Apply:** remove the key, or give a whole
29
+ number of characters from 64 up to 2147483647.
30
+
31
+ ### Added
32
+
33
+ - **`maxStringLength` bounds the length of every string of a log record.** A string under a metadata
34
+ key is the caller's own data and was written as given, so one value of a megabyte made an entry of
35
+ a megabyte. With `maxStringLength` set, a string longer than the limit is cut to that many
36
+ characters (a cut never splits a surrogate pair) and ends with `…[truncated]`. It is an integer
37
+ from 64 to 2147483647 and it is off until set. The cut runs after
38
+ every redaction rule and before the event name and the exception fields are written, so it cannot
39
+ cut a string before a rule that needs the whole of it.
40
+ It applies at any depth, and not to a key, a value that is not text, the log message, the
41
+ `logKey`, the bindings of a logger, or anything under a key that has a serializer (`err` and the
42
+ keys of `serializers`). The event name and the `exception.*` and `error.type` fields the library
43
+ writes are added after the cut, so the limit does not apply to them, and the exception fields among them keep the cap of
44
+ 16384 characters they had in 1.4.21. An `Error` placed in the metadata under any
45
+ other key is data of the record when the cut runs, and its message and stack are cut like any
46
+ other string. The names left whole are matched on the root key, so a key of your own named like a
47
+ serializer key is left whole too. A `userId` longer than the
48
+ limit is cut like any other string. A `redactCensor` longer than the limit is refused at startup,
49
+ so a censor is never cut. Setting the option makes the record walk run even when no field name is
50
+ covered (`shouldDisableDefaultRedact: true` and no `redactPaths`), and the walk writes a boxed
51
+ `String` or `Number`, a `Buffer`, a `Uint8Array` and an `Error` in the metadata as the default
52
+ redaction already does: a two-byte `Buffer` is written as `[Binary 2 bytes]` and not as
53
+ `{"type":"Buffer","data":[104,105]}`, while a boxed `Number` is written as `{}` and a boxed
54
+ `String` as a map of its indexes (`{"0":"a","1":"b","2":"c"}` for `new String('abc')`), as the
55
+ default redaction writes them.
56
+
57
+ ### Changed
58
+
59
+ - **The steps of `PrettyDevDestination.onInit` are module functions, not methods.** 1.4.21 split
60
+ `onInit` into the private methods `refuseInProduction`, `buildTransform` and `initFailure`, which
61
+ `onInit` called through `this`. A subclass written without the type check, as JavaScript is, that
62
+ defined a member with one of those names had it called in the place of the step. The steps are now
63
+ functions of the module, so no member of any name replaces them, and the three declarations leave
64
+ the `.d.ts`. Behavior is otherwise unchanged.
65
+
66
+ - **A refused option names the type of the value it received and never quotes it.** The message
67
+ used to end in `Got: "3"` for a string and in `String(value)` for a number, a boolean, a bigint or a
68
+ Symbol, so a token typed into the wrong field, or a Symbol with a description, reached the bootstrap
69
+ log. It now ends in
70
+ `Received a string`, `Received a symbol`, `Received an object` and so on, and prints a value only
71
+ when it is a finite number (`Received the number 63`). The refusals that bypassed the shared path
72
+ and printed `String(value)` (`level`, `redactStrategy`, `resourceFormat`, `errorFormat` and
73
+ `eventNameField`) go through it too. A `service` that is not an object, including `null`, `0`,
74
+ `false`, `''` and `NaN`, is now refused as `options.service must be an object. Received …`:
75
+ 1.4.21 said `options.service is required` for a falsy one and blamed `service.name` or `service.version` for any other,
76
+ and only an undefined `service` keeps `options.service is required`. **Apply:** code that matches
77
+ the text `Got:` of a refusal matches `Received` instead; apart from that and `service`, the
78
+ option's name and the rule are unchanged. Three refusals had no suffix at
79
+ all (a `service.name` or `service.version` that is not a non-empty string, and a
80
+ `maxEntrySizeBytes` of 0 or less) and now end in `Received <type>` too, so an exact match on their
81
+ whole text changes as well; a missing `service.name` or `service.version` still has no suffix.
82
+
83
+ #### Apply to a derived backend
84
+
85
+ `PrettyDevDestination`: nothing is required. A subclass that defines a member named
86
+ `refuseInProduction`, `buildTransform` or `initFailure` keeps it, and `onInit` no longer calls it.
87
+
88
+ `maxStringLength`: a configuration that already passes that key with a value outside 64 to
89
+ 2147483647 must change it, because it is refused now (see the Breaking entry above); otherwise
90
+ nothing is required, since the option is off until set. `ResolvedBymaxLoggerModuleOptions` gains the key `maxStringLength: number | undefined`, so a derived
91
+ backend that builds that object itself adds `maxStringLength: undefined`; one that spreads the
92
+ result of `applyDefaults` already has it.
93
+
15
94
  ## [1.4.21] - 2026-11-17
16
95
 
17
96
  ### Breaking
@@ -2941,7 +3020,8 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2941
3020
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2942
3021
  `release.yml`, Dependabot, and issue templates
2943
3022
 
2944
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.21...HEAD
3023
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.22...HEAD
3024
+ [1.4.22]: https://github.com/bymaxone/nest-logger/compare/v1.4.21...v1.4.22
2945
3025
  [1.4.21]: https://github.com/bymaxone/nest-logger/compare/v1.4.20...v1.4.21
2946
3026
  [1.4.20]: https://github.com/bymaxone/nest-logger/compare/v1.4.19...v1.4.20
2947
3027
  [1.4.19]: https://github.com/bymaxone/nest-logger/compare/v1.4.18...v1.4.19
package/README.md CHANGED
@@ -267,7 +267,8 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
267
267
  | `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` is the legacy `fast-redact` expansion (four-level ceiling, much slower) |
268
268
  | `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
269
269
  | `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
270
- | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field, a whole number (`err` + any custom serializer); over it the value becomes a truncation envelope |
270
+ | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field, a whole number from 1 to 2147483647 (`err` + any custom serializer); over it the value becomes a truncation envelope |
271
+ | `maxStringLength` | `number` | unset (a string is written whole) | The most characters a string of a log record is written with: an integer from 64 to 2147483647. A longer string is cut to that length and ends with `…[truncated]`. See [Bounded string length](#bounded-string-length) |
271
272
  | `destinationHookTimeoutMs` | `number` | `10000` | Longest `onInit` or `onRegistryReady` of a destination, in ms (an integer from 1 to 2147483647). An `onInit` that does not settle in time counts as one that threw: the destination is failed, skipped and reported, and stays inactive if the call settles later. A hung `onInit` may leak what it opened |
272
273
  | `errorOwnFields` | `'all' \| 'safe'` | `'all'` | Which own fields of an error are written. `'all'` writes every one; `'safe'` writes an allow-list of operational names plus `errorOwnFieldNames` (see [Error fields](#error-fields)). A binary value is written as its size in both. Recommended: `'safe'` |
273
274
  | `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
@@ -907,6 +908,12 @@ An interpolated value has no name, so no configuration can redact it. **A value
907
908
 
908
909
  Every serializer, the default `err` one and any you supply, is wrapped so a field whose serialized JSON exceeds `maxEntrySizeBytes` (64 KB by default) is replaced by an envelope with `_truncated`, `_logKey: 'LOGGER_ENTRY_TRUNCATED'`, `_originalSize` and a 200-character `_preview`.
909
910
 
911
+ ### Bounded string length
912
+
913
+ `maxEntrySizeBytes` bounds what a serializer returns, and a string under a metadata key is the caller's own data, written as given. `maxStringLength` bounds that string too, and is off until set. A string longer than the limit is cut to that many characters (UTF-16 units, so a cut never splits a surrogate pair) and ends with `…[truncated]`; what is written is the limit plus 12 characters at most, and a string of exactly the limit is written whole.
914
+
915
+ It applies to every string value of the record at any depth, in an object or an array, after redaction: a value a redaction rule censors is the censor and not a cut text. It does not apply to a key, to a value that is not text, to the log message (already capped at 16384 characters), to the `logKey` of the entry (an identifier, and `event.name` is derived from it), to the bindings of a logger (the service identity and the `context` of an `@InjectLogger` logger are written once, whole), to anything under a key that has a serializer (`err` and the keys of `serializers`): this limit does not cut the error you log under `err`, and `maxEntrySizeBytes` caps what a serializer returns when that output serializes to JSON. The event name and the `exception.type`, `exception.message`, `exception.stacktrace` and `error.type` fields written from an error are added after the cut, so the limit does not apply to them, and the exception fields among them keep the cap of 16384 characters they had in 1.4.21, and a key of your own with one of those names is cut like any other string. The names left whole are matched on the root key, so a key of your own named like a key of `serializers` is left whole too. An `Error` placed in the metadata under any other key is data of the record when the cut runs, so its message, its stack and its own fields are cut like any other string. The limit is an integer from 64, because the strings the library writes into a record itself (trace and span ids) are shorter than that. A string the caller supplies, such as a `userId`, a `tenantId`, or a `requestId` taken from an inbound request header, is cut like any other when it is longer than the limit. Setting it makes the record walk run even when no field name is covered (`shouldDisableDefaultRedact: true` and no `redactPaths`), and the walk writes a boxed `String` or `Number`, a `Buffer`, a `Uint8Array` and an `Error` in the metadata as the default redaction already does: a two-byte `Buffer` is written as `[Binary 2 bytes]` and not as `{"type":"Buffer","data":[104,105]}`, while a boxed `Number` is written as `{}` and a boxed `String` as a map of its indexes (`{"0":"a","1":"b","2":"c"}` for `new String('abc')`), as the default redaction writes them. A `redactCensor` longer than the limit is refused at startup, because a censor the cut shortened would no longer be the text you look for in place of a secret.
916
+
910
917
  ### Security Checklist
911
918
 
912
919
  - `shouldDisableDefaultRedact` stays `false`; if it is on, the `LOGGER_BOOTSTRAP_WARNING` must be justified in a security review.
@@ -32,6 +32,9 @@ var DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
32
32
  var DEFAULT_QUEUE_MAX_BYTES = 33554432;
33
33
  var MIN_QUEUE_MAX_BYTES = 1024;
34
34
  var MAX_QUEUE_MAX_BYTES = 2147483647;
35
+ var MAX_ENTRY_SIZE_BYTES = 2147483647;
36
+ var MIN_STRING_LENGTH_LIMIT = 64;
37
+ var MAX_STRING_LENGTH_LIMIT = 2147483647;
35
38
 
36
39
  // src/server/config/default-options.ts
37
40
  var DEFAULT_HTTP = {
@@ -101,6 +104,7 @@ function applyDefaults(options) {
101
104
  }),
102
105
  otel: Object.freeze(otel),
103
106
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
107
+ maxStringLength: options.maxStringLength,
104
108
  destinationHookTimeoutMs: options.destinationHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS,
105
109
  shutdown: resolveShutdown(options.shutdown),
106
110
  destinationQueue: Object.freeze({
@@ -141,16 +145,27 @@ var LOG_LEVEL_PRIORITY = Object.freeze([
141
145
 
142
146
  // src/server/config/validate-options.ts
143
147
  function reject(path, rule, got) {
144
- const received = got === void 0 ? "" : `. Got: ${describeValue(got)}`;
148
+ const received = got === void 0 ? "" : `. Received ${describeValue(got)}`;
145
149
  throw new Error(`[BymaxLoggerModule] options.${path} ${rule}${received}`);
146
150
  }
147
151
  function describeValue(value) {
148
- if (value === null) return "null";
149
- if (Array.isArray(value)) return "an array";
150
- if (typeof value === "object") return "an object";
151
- if (typeof value === "function") return "a function";
152
- if (typeof value === "string") return JSON.stringify(value);
153
- return String(value);
152
+ switch (typeof value) {
153
+ case "number":
154
+ return Number.isFinite(value) ? `the number ${String(value)}` : "a number that is not finite";
155
+ case "string":
156
+ return "a string";
157
+ case "boolean":
158
+ return "a boolean";
159
+ case "bigint":
160
+ return "a bigint";
161
+ case "symbol":
162
+ return "a symbol";
163
+ case "function":
164
+ return "a function";
165
+ default:
166
+ if (value === null) return "null";
167
+ return Array.isArray(value) ? "an array" : "an object";
168
+ }
154
169
  }
155
170
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
156
171
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -188,6 +203,24 @@ function validateQueue(options) {
188
203
  );
189
204
  }
190
205
  }
206
+ function validateStringLimit(options) {
207
+ const limit = options.maxStringLength;
208
+ if (limit === void 0) return;
209
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < MIN_STRING_LENGTH_LIMIT || limit > MAX_STRING_LENGTH_LIMIT) {
210
+ reject(
211
+ "maxStringLength",
212
+ `must be an integer from ${String(MIN_STRING_LENGTH_LIMIT)} to ${String(MAX_STRING_LENGTH_LIMIT)}`,
213
+ limit
214
+ );
215
+ }
216
+ const censor = options.redactCensor;
217
+ if (typeof censor === "string" && censor.length > limit) {
218
+ reject(
219
+ "redactCensor",
220
+ `must be at most ${String(limit)} characters when maxStringLength is set`
221
+ );
222
+ }
223
+ }
191
224
  function validateLifecycle(options) {
192
225
  checkTimerMs("destinationHookTimeoutMs", options.destinationHookTimeoutMs);
193
226
  const shutdown = checkGroup("shutdown", options.shutdown);
@@ -205,61 +238,46 @@ function validateLifecycle(options) {
205
238
  }
206
239
  }
207
240
  function validateCore(options) {
208
- if (!options.service) {
241
+ const service = options.service;
242
+ if (service === void 0) {
209
243
  throw new Error("[BymaxLoggerModule] options.service is required");
210
244
  }
211
- if (typeof options.service.name !== "string" || options.service.name.trim() === "") {
212
- throw new Error("[BymaxLoggerModule] options.service.name must be a non-empty string");
213
- }
214
- if (typeof options.service.version !== "string" || options.service.version.trim() === "") {
215
- throw new Error("[BymaxLoggerModule] options.service.version must be a non-empty string");
245
+ if (!isRecord(service)) reject("service", "must be an object", service);
246
+ for (const field of ["name", "version"]) {
247
+ const given = service[field];
248
+ if (typeof given !== "string" || given.trim() === "") {
249
+ reject(`service.${field}`, "must be a non-empty string", given);
250
+ }
216
251
  }
217
252
  if (options.level !== void 0 && !LOG_LEVEL_PRIORITY.includes(options.level)) {
218
- throw new Error(
219
- `[BymaxLoggerModule] options.level must be one of: ${LOG_LEVEL_PRIORITY.join(
220
- ", "
221
- )}. Got: ${String(options.level)}`
222
- );
253
+ reject("level", `must be one of: ${LOG_LEVEL_PRIORITY.join(", ")}`, options.level);
223
254
  }
224
255
  const size = options.maxEntrySizeBytes;
225
256
  if (size !== void 0 && !Number.isFinite(size)) {
226
257
  reject("maxEntrySizeBytes", "must be a finite number", size);
227
258
  }
228
259
  if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes <= 0) {
229
- throw new Error("[BymaxLoggerModule] options.maxEntrySizeBytes must be > 0");
260
+ reject("maxEntrySizeBytes", "must be > 0", options.maxEntrySizeBytes);
230
261
  }
231
262
  if (size !== void 0 && !Number.isInteger(size)) {
232
263
  reject("maxEntrySizeBytes", "must be an integer", size);
233
264
  }
265
+ if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes > MAX_ENTRY_SIZE_BYTES) {
266
+ reject("maxEntrySizeBytes", `must be at most ${String(MAX_ENTRY_SIZE_BYTES)}`, size);
267
+ }
234
268
  }
235
269
  function validateClosedSets(options) {
236
270
  if (options.redactStrategy !== void 0 && options.redactStrategy !== "names" && options.redactStrategy !== "paths") {
237
- throw new Error(
238
- `[BymaxLoggerModule] options.redactStrategy must be 'names' or 'paths'. Got: ${String(
239
- options.redactStrategy
240
- )}`
241
- );
271
+ reject("redactStrategy", "must be 'names' or 'paths'", options.redactStrategy);
242
272
  }
243
273
  if (options.resourceFormat !== void 0 && options.resourceFormat !== "nested" && options.resourceFormat !== "flat") {
244
- throw new Error(
245
- `[BymaxLoggerModule] options.resourceFormat must be 'nested' or 'flat'. Got: ${String(
246
- options.resourceFormat
247
- )}`
248
- );
274
+ reject("resourceFormat", "must be 'nested' or 'flat'", options.resourceFormat);
249
275
  }
250
276
  if (options.errorFormat !== void 0 && options.errorFormat !== "pino" && options.errorFormat !== "semconv" && options.errorFormat !== "both") {
251
- throw new Error(
252
- `[BymaxLoggerModule] options.errorFormat must be 'pino', 'semconv' or 'both'. Got: ${String(
253
- options.errorFormat
254
- )}`
255
- );
277
+ reject("errorFormat", "must be 'pino', 'semconv' or 'both'", options.errorFormat);
256
278
  }
257
279
  if (options.eventNameField !== void 0 && options.eventNameField !== false && (typeof options.eventNameField !== "string" || options.eventNameField.length === 0)) {
258
- throw new Error(
259
- `[BymaxLoggerModule] options.eventNameField must be a non-empty string or false. Got: ${String(
260
- options.eventNameField
261
- )}`
262
- );
280
+ reject("eventNameField", "must be a non-empty string or false", options.eventNameField);
263
281
  }
264
282
  }
265
283
  function validateCustomization(options) {
@@ -388,6 +406,7 @@ function validateOptions(options) {
388
406
  validateDestinations(options);
389
407
  validateLifecycle(options);
390
408
  validateQueue(options);
409
+ validateStringLimit(options);
391
410
  validateHttp(options);
392
411
  validateOtel(options);
393
412
  }
@@ -448,9 +467,9 @@ var TEXT_TRUNCATED = "\u2026[truncated]";
448
467
  function cutIfText(value) {
449
468
  return typeof value === "string" ? cutText(value) : value;
450
469
  }
451
- function cutText(text, alreadyCut = false) {
452
- if (!alreadyCut && text.length <= MAX_TEXT_LENGTH) return text;
453
- const head = text.slice(0, MAX_TEXT_LENGTH);
470
+ function cutText(text, alreadyCut = false, limit = MAX_TEXT_LENGTH) {
471
+ if (!alreadyCut && text.length <= limit) return text;
472
+ const head = text.slice(0, limit);
454
473
  const last = head.charCodeAt(head.length - 1);
455
474
  const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
456
475
  return whole + TEXT_TRUNCATED;
@@ -2155,6 +2174,31 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2155
2174
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
2156
2175
  return Array.from(new Set(sources.flat()));
2157
2176
  }
2177
+
2178
+ // src/server/utils/cut-strings.util.ts
2179
+ function isPlainRecord(node) {
2180
+ if (node === null || typeof node !== "object") return false;
2181
+ const prototype = Object.getPrototypeOf(node);
2182
+ return prototype === Object.prototype || prototype === null;
2183
+ }
2184
+ function cutNode(node, limit) {
2185
+ if (typeof node === "string") return cutText(node, false, limit);
2186
+ if (Array.isArray(node)) return node.map((child) => cutNode(child, limit));
2187
+ if (isPlainRecord(node)) {
2188
+ return Object.fromEntries(
2189
+ Object.entries(node).map(([key, child]) => [key, cutNode(child, limit)])
2190
+ );
2191
+ }
2192
+ return node;
2193
+ }
2194
+ function cutStrings(record, limit, exempt) {
2195
+ return Object.fromEntries(
2196
+ Object.entries(record).map(([key, child]) => [
2197
+ key,
2198
+ exempt.has(key) ? child : cutNode(child, limit)
2199
+ ])
2200
+ );
2201
+ }
2158
2202
  function reportWriteFailure(destination, cause, due) {
2159
2203
  const name = safeDestinationName(destination);
2160
2204
  reportDestinationFailure(
@@ -2878,20 +2922,31 @@ var PASS_THROUGH = (value) => value;
2878
2922
  function resolveNameRedactor(options) {
2879
2923
  return buildNameRedactor(options, true, options.redactStrategy === "names");
2880
2924
  }
2925
+ function resolveRecordRedactor(options) {
2926
+ return buildNameRedactor(
2927
+ options,
2928
+ true,
2929
+ options.redactStrategy === "names",
2930
+ options.maxStringLength !== void 0
2931
+ );
2932
+ }
2933
+ function wholeRootKeys(options) {
2934
+ return /* @__PURE__ */ new Set(["logKey", "err", ...Object.keys(options.serializers)]);
2935
+ }
2881
2936
  function ownFieldPolicyOf(options) {
2882
2937
  return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
2883
2938
  }
2884
2939
  function namesInsideErrors(options) {
2885
2940
  return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
2886
2941
  }
2887
- function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2942
+ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true, forcesWalk = false) {
2888
2943
  const allNames = [
2889
2944
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
2890
2945
  ...options.redactPaths.flatMap((path) => leafNameOf(path) ?? [])
2891
2946
  ];
2892
2947
  const names = coversNames ? allNames : [];
2893
2948
  const ownFields = ownFieldPolicyOf(options);
2894
- const walks = names.length > 0 || ownFields.safe;
2949
+ const walks = names.length > 0 || ownFields.safe || forcesWalk;
2895
2950
  if (!walks && resolveRedactOption(options) === void 0) {
2896
2951
  return PASS_THROUGH;
2897
2952
  }
@@ -2957,8 +3012,20 @@ function buildStreams(options, destinations, health) {
2957
3012
  };
2958
3013
  });
2959
3014
  }
2960
- function buildFormatters(options, redactRecord) {
3015
+ function buildRecordFormatter(options, redactRecord) {
2961
3016
  const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
3017
+ const maxStringLength = options.maxStringLength;
3018
+ const wholeRoots = wholeRootKeys(options);
3019
+ return (record) => {
3020
+ const redacted = redactRecord(
3021
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
3022
+ true
3023
+ );
3024
+ const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots);
3025
+ return withSemconvException(withEventName(bounded, options.eventNameField), options.errorFormat);
3026
+ };
3027
+ }
3028
+ function buildFormatters(options, redactRecord, redactBindings) {
2962
3029
  return {
2963
3030
  // Emit the level as a string label instead of the numeric code — easier
2964
3031
  // for log aggregators. Trace context is injected via `mixin`, never via
@@ -2973,26 +3040,17 @@ function buildFormatters(options, redactRecord) {
2973
3040
  // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2974
3041
  // logger construction — no per-entry cost. `true`: bindings are a record
2975
3042
  // root, iterated rather than serialized.
2976
- bindings: (bindings) => redactRecord(bindings, true),
3043
+ bindings: (bindings) => redactBindings(bindings, true),
2977
3044
  // The name-walk redactor runs here, on the merged record (mixin output +
2978
3045
  // the caller's object), which is exactly the surface a caller controls.
2979
3046
  // `base` and child bindings are NOT visible at this hook — they are
2980
3047
  // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2981
3048
  // sensitive, which `pino-factory.spec.ts` pins.
2982
- log: (record) => withSemconvException(
2983
- withEventName(
2984
- redactRecord(
2985
- hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2986
- true
2987
- ),
2988
- options.eventNameField
2989
- ),
2990
- options.errorFormat
2991
- )
3049
+ log: buildRecordFormatter(options, redactRecord)
2992
3050
  };
2993
3051
  }
2994
3052
  function buildPinoInstance(options, logContext, destinations, health) {
2995
- const redactRecord = resolveNameRedactor(options);
3053
+ const redactRecord = resolveRecordRedactor(options);
2996
3054
  const redactSerialized = buildNameRedactor(options);
2997
3055
  const ownFields = ownFieldPolicyOf(options);
2998
3056
  const redactOption = resolveRedactOption(options);
@@ -3012,7 +3070,7 @@ function buildPinoInstance(options, logContext, destinations, health) {
3012
3070
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
3013
3071
  // neither break the line nor add fields to it.
3014
3072
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
3015
- formatters: buildFormatters(options, redactRecord),
3073
+ formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options)),
3016
3074
  serializers: buildSerializers(options, redactSerialized, ownFields),
3017
3075
  mixin: createTraceContextMixin(logContext, options.otel),
3018
3076
  mixinMergeStrategy: mergeMixinSafely
@@ -3910,6 +3968,30 @@ function describeFailure(cause) {
3910
3968
  return "unreadable value";
3911
3969
  }
3912
3970
  }
3971
+ function productionRefusal() {
3972
+ return new Error(
3973
+ "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3974
+ );
3975
+ }
3976
+ async function buildTransform(view) {
3977
+ const { build } = await import('pino-pretty');
3978
+ return build({
3979
+ ...DEFAULT_VIEW,
3980
+ ...view,
3981
+ // AFTER the consumer's view, deliberately. Omitting `destination` from
3982
+ // `PrettyViewOptions` states that the library owns the sink; applying it
3983
+ // last is what ENFORCES it, including against an untyped caller reaching
3984
+ // in from JavaScript. A redirected stream would route around the fan-out
3985
+ // and the last-resort rescue.
3986
+ destination: process.stdout
3987
+ });
3988
+ }
3989
+ function initFailure(cause) {
3990
+ return new Error(
3991
+ isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
3992
+ { cause }
3993
+ );
3994
+ }
3913
3995
  var PrettyDevDestination = class {
3914
3996
  /**
3915
3997
  * @param opts.minLevel — Optional minimum level filter applied by the
@@ -3964,11 +4046,15 @@ var PrettyDevDestination = class {
3964
4046
  * message telling the consumer to install it or drop this destination.
3965
4047
  */
3966
4048
  async onInit() {
3967
- this.refuseInProduction();
4049
+ if (process.env["NODE_ENV"] === "production") {
4050
+ this.initFailed = true;
4051
+ throw productionRefusal();
4052
+ }
3968
4053
  try {
3969
- this.stream = await this.buildTransform();
4054
+ this.stream = await buildTransform(this.view);
3970
4055
  } catch (cause) {
3971
- throw this.initFailure(cause);
4056
+ this.initFailed = true;
4057
+ throw initFailure(cause);
3972
4058
  }
3973
4059
  this.flushBuffer((payload) => {
3974
4060
  try {
@@ -3978,46 +4064,6 @@ var PrettyDevDestination = class {
3978
4064
  }
3979
4065
  });
3980
4066
  }
3981
- /** Refuse to start when `NODE_ENV` is `production`. */
3982
- refuseInProduction() {
3983
- if (process.env["NODE_ENV"] === "production") {
3984
- this.initFailed = true;
3985
- throw new Error(
3986
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3987
- );
3988
- }
3989
- }
3990
- /**
3991
- * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
3992
- *
3993
- * @returns The transform every entry is written to.
3994
- */
3995
- async buildTransform() {
3996
- const { build } = await import('pino-pretty');
3997
- return build({
3998
- ...DEFAULT_VIEW,
3999
- ...this.view,
4000
- // AFTER the consumer's view, deliberately. Omitting `destination` from
4001
- // `PrettyViewOptions` states that the library owns the sink; applying it
4002
- // last is what ENFORCES it, including against an untyped caller reaching
4003
- // in from JavaScript. A redirected stream would route around the fan-out
4004
- // and the last-resort rescue.
4005
- destination: process.stdout
4006
- });
4007
- }
4008
- /**
4009
- * Mark the destination as failed and build the error `onInit` rejects with.
4010
- *
4011
- * @param cause - What the import or `build()` threw.
4012
- * @returns The error to throw.
4013
- */
4014
- initFailure(cause) {
4015
- this.initFailed = true;
4016
- return new Error(
4017
- isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
4018
- { cause }
4019
- );
4020
- }
4021
4067
  /**
4022
4068
  * Write a serialized NDJSON entry to the pretty transform.
4023
4069
  *
@@ -618,8 +618,28 @@ interface BymaxLoggerModuleOptions {
618
618
  http?: HttpOptions;
619
619
  /** OpenTelemetry integration tuning. */
620
620
  otel?: OtelOptions;
621
- /** Maximum size in bytes per log entry. Default: 65536. */
621
+ /** Maximum size in bytes per log entry: an integer from 1 to 2147483647. Default: 65536. */
622
622
  maxEntrySizeBytes?: number;
623
+ /**
624
+ * The most characters a string of a log record is written with. A longer string is cut to this
625
+ * many characters, without splitting a surrogate pair, and ends with `…[truncated]`, so what is
626
+ * written is up to 12 characters longer than the limit. An integer from 64 to 2147483647.
627
+ * Default: not set, and a string is written whole.
628
+ *
629
+ * Applies to every string value of the record at any depth, but not to a key, a value that is
630
+ * not text, the log message (already capped at 16384 characters), the `logKey`, the bindings of a
631
+ * logger (the service identity and a `context`), a value a redaction rule censors, or anything
632
+ * under a key that has a serializer (`err` and the keys of `serializers`; see
633
+ * `maxEntrySizeBytes`), so the stack of an error logged under `err` is never cut by it. The event
634
+ * name and the `exception.*` and `error.type` fields the library writes are added after the cut,
635
+ * so the limit does not apply to them, and a key of your own with one of those names is cut like
636
+ * any other. The names left whole are matched on the root key, so a key of your own named like a
637
+ * serializer key is left whole too. An `Error` placed in the metadata under any other key is
638
+ * data of the record when the cut runs, and its message and stack are cut like any other string.
639
+ * A string the caller supplies, such as a `userId` longer than the limit, is cut like any other.
640
+ * A `redactCensor` longer than the limit is refused at startup, so a censor is never cut.
641
+ */
642
+ maxStringLength?: number;
623
643
  /**
624
644
  * The longest a destination's `onInit` or `onRegistryReady` may take, in milliseconds. Default:
625
645
  * 10000. An integer from 1 to 2147483647 (the largest delay a timer holds).
@@ -669,7 +689,8 @@ interface BymaxLoggerModuleOptions {
669
689
  * middleware) consumes — distinct from the loosely-typed
670
690
  * `BymaxLoggerModuleOptions` the consumer supplies.
671
691
  */
672
- type ResolvedBymaxLoggerModuleOptions = Readonly<Required<Omit<BymaxLoggerModuleOptions, 'http' | 'otel' | 'shutdown' | 'destinationQueue'>> & {
692
+ type ResolvedBymaxLoggerModuleOptions = Readonly<Required<Omit<BymaxLoggerModuleOptions, 'http' | 'otel' | 'shutdown' | 'destinationQueue' | 'maxStringLength'>> & {
693
+ maxStringLength: number | undefined;
673
694
  http: ResolvedHttpOptions;
674
695
  otel: Required<OtelOptions>;
675
696
  shutdown: Required<ShutdownOptions>;
@@ -1401,21 +1422,6 @@ declare class PrettyDevDestination implements ILogDestination {
1401
1422
  * message telling the consumer to install it or drop this destination.
1402
1423
  */
1403
1424
  onInit(): Promise<void>;
1404
- /** Refuse to start when `NODE_ENV` is `production`. */
1405
- private refuseInProduction;
1406
- /**
1407
- * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
1408
- *
1409
- * @returns The transform every entry is written to.
1410
- */
1411
- private buildTransform;
1412
- /**
1413
- * Mark the destination as failed and build the error `onInit` rejects with.
1414
- *
1415
- * @param cause - What the import or `build()` threw.
1416
- * @returns The error to throw.
1417
- */
1418
- private initFailure;
1419
1425
  /**
1420
1426
  * Write a serialized NDJSON entry to the pretty transform.
1421
1427
  *
@@ -618,8 +618,28 @@ interface BymaxLoggerModuleOptions {
618
618
  http?: HttpOptions;
619
619
  /** OpenTelemetry integration tuning. */
620
620
  otel?: OtelOptions;
621
- /** Maximum size in bytes per log entry. Default: 65536. */
621
+ /** Maximum size in bytes per log entry: an integer from 1 to 2147483647. Default: 65536. */
622
622
  maxEntrySizeBytes?: number;
623
+ /**
624
+ * The most characters a string of a log record is written with. A longer string is cut to this
625
+ * many characters, without splitting a surrogate pair, and ends with `…[truncated]`, so what is
626
+ * written is up to 12 characters longer than the limit. An integer from 64 to 2147483647.
627
+ * Default: not set, and a string is written whole.
628
+ *
629
+ * Applies to every string value of the record at any depth, but not to a key, a value that is
630
+ * not text, the log message (already capped at 16384 characters), the `logKey`, the bindings of a
631
+ * logger (the service identity and a `context`), a value a redaction rule censors, or anything
632
+ * under a key that has a serializer (`err` and the keys of `serializers`; see
633
+ * `maxEntrySizeBytes`), so the stack of an error logged under `err` is never cut by it. The event
634
+ * name and the `exception.*` and `error.type` fields the library writes are added after the cut,
635
+ * so the limit does not apply to them, and a key of your own with one of those names is cut like
636
+ * any other. The names left whole are matched on the root key, so a key of your own named like a
637
+ * serializer key is left whole too. An `Error` placed in the metadata under any other key is
638
+ * data of the record when the cut runs, and its message and stack are cut like any other string.
639
+ * A string the caller supplies, such as a `userId` longer than the limit, is cut like any other.
640
+ * A `redactCensor` longer than the limit is refused at startup, so a censor is never cut.
641
+ */
642
+ maxStringLength?: number;
623
643
  /**
624
644
  * The longest a destination's `onInit` or `onRegistryReady` may take, in milliseconds. Default:
625
645
  * 10000. An integer from 1 to 2147483647 (the largest delay a timer holds).
@@ -669,7 +689,8 @@ interface BymaxLoggerModuleOptions {
669
689
  * middleware) consumes — distinct from the loosely-typed
670
690
  * `BymaxLoggerModuleOptions` the consumer supplies.
671
691
  */
672
- type ResolvedBymaxLoggerModuleOptions = Readonly<Required<Omit<BymaxLoggerModuleOptions, 'http' | 'otel' | 'shutdown' | 'destinationQueue'>> & {
692
+ type ResolvedBymaxLoggerModuleOptions = Readonly<Required<Omit<BymaxLoggerModuleOptions, 'http' | 'otel' | 'shutdown' | 'destinationQueue' | 'maxStringLength'>> & {
693
+ maxStringLength: number | undefined;
673
694
  http: ResolvedHttpOptions;
674
695
  otel: Required<OtelOptions>;
675
696
  shutdown: Required<ShutdownOptions>;
@@ -1401,21 +1422,6 @@ declare class PrettyDevDestination implements ILogDestination {
1401
1422
  * message telling the consumer to install it or drop this destination.
1402
1423
  */
1403
1424
  onInit(): Promise<void>;
1404
- /** Refuse to start when `NODE_ENV` is `production`. */
1405
- private refuseInProduction;
1406
- /**
1407
- * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
1408
- *
1409
- * @returns The transform every entry is written to.
1410
- */
1411
- private buildTransform;
1412
- /**
1413
- * Mark the destination as failed and build the error `onInit` rejects with.
1414
- *
1415
- * @param cause - What the import or `build()` threw.
1416
- * @returns The error to throw.
1417
- */
1418
- private initFailure;
1419
1425
  /**
1420
1426
  * Write a serialized NDJSON entry to the pretty transform.
1421
1427
  *
@@ -29,6 +29,9 @@ var DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
29
29
  var DEFAULT_QUEUE_MAX_BYTES = 33554432;
30
30
  var MIN_QUEUE_MAX_BYTES = 1024;
31
31
  var MAX_QUEUE_MAX_BYTES = 2147483647;
32
+ var MAX_ENTRY_SIZE_BYTES = 2147483647;
33
+ var MIN_STRING_LENGTH_LIMIT = 64;
34
+ var MAX_STRING_LENGTH_LIMIT = 2147483647;
32
35
 
33
36
  // src/server/config/default-options.ts
34
37
  var DEFAULT_HTTP = {
@@ -98,6 +101,7 @@ function applyDefaults(options) {
98
101
  }),
99
102
  otel: Object.freeze(otel),
100
103
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
104
+ maxStringLength: options.maxStringLength,
101
105
  destinationHookTimeoutMs: options.destinationHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS,
102
106
  shutdown: resolveShutdown(options.shutdown),
103
107
  destinationQueue: Object.freeze({
@@ -138,16 +142,27 @@ var LOG_LEVEL_PRIORITY = Object.freeze([
138
142
 
139
143
  // src/server/config/validate-options.ts
140
144
  function reject(path2, rule, got) {
141
- const received = got === void 0 ? "" : `. Got: ${describeValue(got)}`;
145
+ const received = got === void 0 ? "" : `. Received ${describeValue(got)}`;
142
146
  throw new Error(`[BymaxLoggerModule] options.${path2} ${rule}${received}`);
143
147
  }
144
148
  function describeValue(value) {
145
- if (value === null) return "null";
146
- if (Array.isArray(value)) return "an array";
147
- if (typeof value === "object") return "an object";
148
- if (typeof value === "function") return "a function";
149
- if (typeof value === "string") return JSON.stringify(value);
150
- return String(value);
149
+ switch (typeof value) {
150
+ case "number":
151
+ return Number.isFinite(value) ? `the number ${String(value)}` : "a number that is not finite";
152
+ case "string":
153
+ return "a string";
154
+ case "boolean":
155
+ return "a boolean";
156
+ case "bigint":
157
+ return "a bigint";
158
+ case "symbol":
159
+ return "a symbol";
160
+ case "function":
161
+ return "a function";
162
+ default:
163
+ if (value === null) return "null";
164
+ return Array.isArray(value) ? "an array" : "an object";
165
+ }
151
166
  }
152
167
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
153
168
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -185,6 +200,24 @@ function validateQueue(options) {
185
200
  );
186
201
  }
187
202
  }
203
+ function validateStringLimit(options) {
204
+ const limit = options.maxStringLength;
205
+ if (limit === void 0) return;
206
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < MIN_STRING_LENGTH_LIMIT || limit > MAX_STRING_LENGTH_LIMIT) {
207
+ reject(
208
+ "maxStringLength",
209
+ `must be an integer from ${String(MIN_STRING_LENGTH_LIMIT)} to ${String(MAX_STRING_LENGTH_LIMIT)}`,
210
+ limit
211
+ );
212
+ }
213
+ const censor = options.redactCensor;
214
+ if (typeof censor === "string" && censor.length > limit) {
215
+ reject(
216
+ "redactCensor",
217
+ `must be at most ${String(limit)} characters when maxStringLength is set`
218
+ );
219
+ }
220
+ }
188
221
  function validateLifecycle(options) {
189
222
  checkTimerMs("destinationHookTimeoutMs", options.destinationHookTimeoutMs);
190
223
  const shutdown = checkGroup("shutdown", options.shutdown);
@@ -202,61 +235,46 @@ function validateLifecycle(options) {
202
235
  }
203
236
  }
204
237
  function validateCore(options) {
205
- if (!options.service) {
238
+ const service = options.service;
239
+ if (service === void 0) {
206
240
  throw new Error("[BymaxLoggerModule] options.service is required");
207
241
  }
208
- if (typeof options.service.name !== "string" || options.service.name.trim() === "") {
209
- throw new Error("[BymaxLoggerModule] options.service.name must be a non-empty string");
210
- }
211
- if (typeof options.service.version !== "string" || options.service.version.trim() === "") {
212
- throw new Error("[BymaxLoggerModule] options.service.version must be a non-empty string");
242
+ if (!isRecord(service)) reject("service", "must be an object", service);
243
+ for (const field of ["name", "version"]) {
244
+ const given = service[field];
245
+ if (typeof given !== "string" || given.trim() === "") {
246
+ reject(`service.${field}`, "must be a non-empty string", given);
247
+ }
213
248
  }
214
249
  if (options.level !== void 0 && !LOG_LEVEL_PRIORITY.includes(options.level)) {
215
- throw new Error(
216
- `[BymaxLoggerModule] options.level must be one of: ${LOG_LEVEL_PRIORITY.join(
217
- ", "
218
- )}. Got: ${String(options.level)}`
219
- );
250
+ reject("level", `must be one of: ${LOG_LEVEL_PRIORITY.join(", ")}`, options.level);
220
251
  }
221
252
  const size = options.maxEntrySizeBytes;
222
253
  if (size !== void 0 && !Number.isFinite(size)) {
223
254
  reject("maxEntrySizeBytes", "must be a finite number", size);
224
255
  }
225
256
  if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes <= 0) {
226
- throw new Error("[BymaxLoggerModule] options.maxEntrySizeBytes must be > 0");
257
+ reject("maxEntrySizeBytes", "must be > 0", options.maxEntrySizeBytes);
227
258
  }
228
259
  if (size !== void 0 && !Number.isInteger(size)) {
229
260
  reject("maxEntrySizeBytes", "must be an integer", size);
230
261
  }
262
+ if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes > MAX_ENTRY_SIZE_BYTES) {
263
+ reject("maxEntrySizeBytes", `must be at most ${String(MAX_ENTRY_SIZE_BYTES)}`, size);
264
+ }
231
265
  }
232
266
  function validateClosedSets(options) {
233
267
  if (options.redactStrategy !== void 0 && options.redactStrategy !== "names" && options.redactStrategy !== "paths") {
234
- throw new Error(
235
- `[BymaxLoggerModule] options.redactStrategy must be 'names' or 'paths'. Got: ${String(
236
- options.redactStrategy
237
- )}`
238
- );
268
+ reject("redactStrategy", "must be 'names' or 'paths'", options.redactStrategy);
239
269
  }
240
270
  if (options.resourceFormat !== void 0 && options.resourceFormat !== "nested" && options.resourceFormat !== "flat") {
241
- throw new Error(
242
- `[BymaxLoggerModule] options.resourceFormat must be 'nested' or 'flat'. Got: ${String(
243
- options.resourceFormat
244
- )}`
245
- );
271
+ reject("resourceFormat", "must be 'nested' or 'flat'", options.resourceFormat);
246
272
  }
247
273
  if (options.errorFormat !== void 0 && options.errorFormat !== "pino" && options.errorFormat !== "semconv" && options.errorFormat !== "both") {
248
- throw new Error(
249
- `[BymaxLoggerModule] options.errorFormat must be 'pino', 'semconv' or 'both'. Got: ${String(
250
- options.errorFormat
251
- )}`
252
- );
274
+ reject("errorFormat", "must be 'pino', 'semconv' or 'both'", options.errorFormat);
253
275
  }
254
276
  if (options.eventNameField !== void 0 && options.eventNameField !== false && (typeof options.eventNameField !== "string" || options.eventNameField.length === 0)) {
255
- throw new Error(
256
- `[BymaxLoggerModule] options.eventNameField must be a non-empty string or false. Got: ${String(
257
- options.eventNameField
258
- )}`
259
- );
277
+ reject("eventNameField", "must be a non-empty string or false", options.eventNameField);
260
278
  }
261
279
  }
262
280
  function validateCustomization(options) {
@@ -385,6 +403,7 @@ function validateOptions(options) {
385
403
  validateDestinations(options);
386
404
  validateLifecycle(options);
387
405
  validateQueue(options);
406
+ validateStringLimit(options);
388
407
  validateHttp(options);
389
408
  validateOtel(options);
390
409
  }
@@ -445,9 +464,9 @@ var TEXT_TRUNCATED = "\u2026[truncated]";
445
464
  function cutIfText(value) {
446
465
  return typeof value === "string" ? cutText(value) : value;
447
466
  }
448
- function cutText(text, alreadyCut = false) {
449
- if (!alreadyCut && text.length <= MAX_TEXT_LENGTH) return text;
450
- const head = text.slice(0, MAX_TEXT_LENGTH);
467
+ function cutText(text, alreadyCut = false, limit = MAX_TEXT_LENGTH) {
468
+ if (!alreadyCut && text.length <= limit) return text;
469
+ const head = text.slice(0, limit);
451
470
  const last = head.charCodeAt(head.length - 1);
452
471
  const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
453
472
  return whole + TEXT_TRUNCATED;
@@ -2152,6 +2171,31 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2152
2171
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
2153
2172
  return Array.from(new Set(sources.flat()));
2154
2173
  }
2174
+
2175
+ // src/server/utils/cut-strings.util.ts
2176
+ function isPlainRecord(node) {
2177
+ if (node === null || typeof node !== "object") return false;
2178
+ const prototype = Object.getPrototypeOf(node);
2179
+ return prototype === Object.prototype || prototype === null;
2180
+ }
2181
+ function cutNode(node, limit) {
2182
+ if (typeof node === "string") return cutText(node, false, limit);
2183
+ if (Array.isArray(node)) return node.map((child) => cutNode(child, limit));
2184
+ if (isPlainRecord(node)) {
2185
+ return Object.fromEntries(
2186
+ Object.entries(node).map(([key, child]) => [key, cutNode(child, limit)])
2187
+ );
2188
+ }
2189
+ return node;
2190
+ }
2191
+ function cutStrings(record, limit, exempt) {
2192
+ return Object.fromEntries(
2193
+ Object.entries(record).map(([key, child]) => [
2194
+ key,
2195
+ exempt.has(key) ? child : cutNode(child, limit)
2196
+ ])
2197
+ );
2198
+ }
2155
2199
  function reportWriteFailure(destination, cause, due) {
2156
2200
  const name = safeDestinationName(destination);
2157
2201
  reportDestinationFailure(
@@ -2875,20 +2919,31 @@ var PASS_THROUGH = (value) => value;
2875
2919
  function resolveNameRedactor(options) {
2876
2920
  return buildNameRedactor(options, true, options.redactStrategy === "names");
2877
2921
  }
2922
+ function resolveRecordRedactor(options) {
2923
+ return buildNameRedactor(
2924
+ options,
2925
+ true,
2926
+ options.redactStrategy === "names",
2927
+ options.maxStringLength !== void 0
2928
+ );
2929
+ }
2930
+ function wholeRootKeys(options) {
2931
+ return /* @__PURE__ */ new Set(["logKey", "err", ...Object.keys(options.serializers)]);
2932
+ }
2878
2933
  function ownFieldPolicyOf(options) {
2879
2934
  return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
2880
2935
  }
2881
2936
  function namesInsideErrors(options) {
2882
2937
  return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
2883
2938
  }
2884
- function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2939
+ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true, forcesWalk = false) {
2885
2940
  const allNames = [
2886
2941
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
2887
2942
  ...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
2888
2943
  ];
2889
2944
  const names = coversNames ? allNames : [];
2890
2945
  const ownFields = ownFieldPolicyOf(options);
2891
- const walks = names.length > 0 || ownFields.safe;
2946
+ const walks = names.length > 0 || ownFields.safe || forcesWalk;
2892
2947
  if (!walks && resolveRedactOption(options) === void 0) {
2893
2948
  return PASS_THROUGH;
2894
2949
  }
@@ -2954,8 +3009,20 @@ function buildStreams(options, destinations, health) {
2954
3009
  };
2955
3010
  });
2956
3011
  }
2957
- function buildFormatters(options, redactRecord) {
3012
+ function buildRecordFormatter(options, redactRecord) {
2958
3013
  const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
3014
+ const maxStringLength = options.maxStringLength;
3015
+ const wholeRoots = wholeRootKeys(options);
3016
+ return (record) => {
3017
+ const redacted = redactRecord(
3018
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
3019
+ true
3020
+ );
3021
+ const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots);
3022
+ return withSemconvException(withEventName(bounded, options.eventNameField), options.errorFormat);
3023
+ };
3024
+ }
3025
+ function buildFormatters(options, redactRecord, redactBindings) {
2959
3026
  return {
2960
3027
  // Emit the level as a string label instead of the numeric code — easier
2961
3028
  // for log aggregators. Trace context is injected via `mixin`, never via
@@ -2970,26 +3037,17 @@ function buildFormatters(options, redactRecord) {
2970
3037
  // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2971
3038
  // logger construction — no per-entry cost. `true`: bindings are a record
2972
3039
  // root, iterated rather than serialized.
2973
- bindings: (bindings) => redactRecord(bindings, true),
3040
+ bindings: (bindings) => redactBindings(bindings, true),
2974
3041
  // The name-walk redactor runs here, on the merged record (mixin output +
2975
3042
  // the caller's object), which is exactly the surface a caller controls.
2976
3043
  // `base` and child bindings are NOT visible at this hook — they are
2977
3044
  // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2978
3045
  // sensitive, which `pino-factory.spec.ts` pins.
2979
- log: (record) => withSemconvException(
2980
- withEventName(
2981
- redactRecord(
2982
- hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2983
- true
2984
- ),
2985
- options.eventNameField
2986
- ),
2987
- options.errorFormat
2988
- )
3046
+ log: buildRecordFormatter(options, redactRecord)
2989
3047
  };
2990
3048
  }
2991
3049
  function buildPinoInstance(options, logContext, destinations, health) {
2992
- const redactRecord = resolveNameRedactor(options);
3050
+ const redactRecord = resolveRecordRedactor(options);
2993
3051
  const redactSerialized = buildNameRedactor(options);
2994
3052
  const ownFields = ownFieldPolicyOf(options);
2995
3053
  const redactOption = resolveRedactOption(options);
@@ -3009,7 +3067,7 @@ function buildPinoInstance(options, logContext, destinations, health) {
3009
3067
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
3010
3068
  // neither break the line nor add fields to it.
3011
3069
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
3012
- formatters: buildFormatters(options, redactRecord),
3070
+ formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options)),
3013
3071
  serializers: buildSerializers(options, redactSerialized, ownFields),
3014
3072
  mixin: createTraceContextMixin(logContext, options.otel),
3015
3073
  mixinMergeStrategy: mergeMixinSafely
@@ -3907,6 +3965,30 @@ function describeFailure(cause) {
3907
3965
  return "unreadable value";
3908
3966
  }
3909
3967
  }
3968
+ function productionRefusal() {
3969
+ return new Error(
3970
+ "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3971
+ );
3972
+ }
3973
+ async function buildTransform(view) {
3974
+ const { build } = await import('pino-pretty');
3975
+ return build({
3976
+ ...DEFAULT_VIEW,
3977
+ ...view,
3978
+ // AFTER the consumer's view, deliberately. Omitting `destination` from
3979
+ // `PrettyViewOptions` states that the library owns the sink; applying it
3980
+ // last is what ENFORCES it, including against an untyped caller reaching
3981
+ // in from JavaScript. A redirected stream would route around the fan-out
3982
+ // and the last-resort rescue.
3983
+ destination: process.stdout
3984
+ });
3985
+ }
3986
+ function initFailure(cause) {
3987
+ return new Error(
3988
+ isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
3989
+ { cause }
3990
+ );
3991
+ }
3910
3992
  var PrettyDevDestination = class {
3911
3993
  /**
3912
3994
  * @param opts.minLevel — Optional minimum level filter applied by the
@@ -3961,11 +4043,15 @@ var PrettyDevDestination = class {
3961
4043
  * message telling the consumer to install it or drop this destination.
3962
4044
  */
3963
4045
  async onInit() {
3964
- this.refuseInProduction();
4046
+ if (process.env["NODE_ENV"] === "production") {
4047
+ this.initFailed = true;
4048
+ throw productionRefusal();
4049
+ }
3965
4050
  try {
3966
- this.stream = await this.buildTransform();
4051
+ this.stream = await buildTransform(this.view);
3967
4052
  } catch (cause) {
3968
- throw this.initFailure(cause);
4053
+ this.initFailed = true;
4054
+ throw initFailure(cause);
3969
4055
  }
3970
4056
  this.flushBuffer((payload) => {
3971
4057
  try {
@@ -3975,46 +4061,6 @@ var PrettyDevDestination = class {
3975
4061
  }
3976
4062
  });
3977
4063
  }
3978
- /** Refuse to start when `NODE_ENV` is `production`. */
3979
- refuseInProduction() {
3980
- if (process.env["NODE_ENV"] === "production") {
3981
- this.initFailed = true;
3982
- throw new Error(
3983
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3984
- );
3985
- }
3986
- }
3987
- /**
3988
- * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
3989
- *
3990
- * @returns The transform every entry is written to.
3991
- */
3992
- async buildTransform() {
3993
- const { build } = await import('pino-pretty');
3994
- return build({
3995
- ...DEFAULT_VIEW,
3996
- ...this.view,
3997
- // AFTER the consumer's view, deliberately. Omitting `destination` from
3998
- // `PrettyViewOptions` states that the library owns the sink; applying it
3999
- // last is what ENFORCES it, including against an untyped caller reaching
4000
- // in from JavaScript. A redirected stream would route around the fan-out
4001
- // and the last-resort rescue.
4002
- destination: process.stdout
4003
- });
4004
- }
4005
- /**
4006
- * Mark the destination as failed and build the error `onInit` rejects with.
4007
- *
4008
- * @param cause - What the import or `build()` threw.
4009
- * @returns The error to throw.
4010
- */
4011
- initFailure(cause) {
4012
- this.initFailed = true;
4013
- return new Error(
4014
- isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
4015
- { cause }
4016
- );
4017
- }
4018
4064
  /**
4019
4065
  * Write a serialized NDJSON entry to the pretty transform.
4020
4066
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.4.21",
3
+ "version": "1.4.22",
4
4
  "description": "Structured JSON logging for NestJS based on Pino 10, with optional OpenTelemetry correlation.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",