From 431dae8f63c3380e3f849a9e6ea6762c0b6b7353 Mon Sep 17 00:00:00 2001 From: Damilorlar Date: Wed, 25 Nov 2026 06:48:01 +0100 Subject: [PATCH 1/3] feat: add truncate utility for oversized fields in structured logs (issue #667) - Add configurable max serialized string length - Mark truncated values with suffix without including discarded content - Handle nested fields consistently - Add tests for strings, arrays, and error objects --- packages/sdk/src/truncate.test.ts | 83 +++++++++++++++++++++++++++ packages/sdk/src/truncate.ts | 95 +++++++++++++++++++++++++++++++ 2 files changed, 178 insertions(+) create mode 100644 packages/sdk/src/truncate.test.ts create mode 100644 packages/sdk/src/truncate.ts diff --git a/packages/sdk/src/truncate.test.ts b/packages/sdk/src/truncate.test.ts new file mode 100644 index 00000000..af6ee3df --- /dev/null +++ b/packages/sdk/src/truncate.test.ts @@ -0,0 +1,83 @@ +import { truncateStrings, truncateError, type TruncateOptions } from "./truncate.js"; +import { describe, it, expect } from "vitest"; + +describe("truncateStrings", () => { + it("should truncate strings longer than maxLength", () => { + const input = "Hello, this is a very long string that should be truncated"; + const result = truncateStrings(input, { maxLength: 10 }); + expect(result).toBe("Hello, this..."); + }); + + it("should not truncate strings shorter than maxLength", () => { + const input = "Short"; + const result = truncateStrings(input, { maxLength: 10 }); + expect(result).toBe("Short"); + }); + + it("should truncate nested strings in objects", () => { + const input = { message: "Hello world", nested: { deep: "A very deep nested string that needs truncation" } }; + const result = truncateStrings(input, { maxLength: 10 }); + expect(result.message).toBe("Hello world"); + expect(result.nested.deep).toMatch(/A very de.../); + }); + + it("should truncate strings in arrays", () => { + const input = ["short", "A very long string that should be truncated", "another short one"]; + const result = truncateStrings(input, { maxLength: 10 }); + expect(result[0]).toBe("short"); + expect(result[1]).toMatch(/Long stri.../); + expect(result[2]).toBe("another short one"); + }); + + it("should handle null and undefined", () => { + const result = truncateStrings(null as any, { maxLength: 10 }); + expect(result).toBeNull(); + const result2 = truncateStrings(undefined as any, { maxLength: 10 }); + expect(result2).toBeUndefined(); + }); + + it("should handle empty strings", () => { + const result = truncateStrings("", { maxLength: 10 }); + expect(result).toBe(""); + }); + + it("should use custom maxLength and truncatedSuffix", () => { + const input = "This is a test string that is quite long"; + const result = truncateStrings(input, { maxLength: 10, truncatedSuffix: "[TRUNCATED]" }); + expect(result).toBe("This is a [TRUNCATED]"); + }); +}); + +describe("truncateError", () => { + it("should truncate error message and preserve name", () => { + const err = new Error("This is a test error message that is quite long to trigger truncation"); + const result = truncateError(err, { maxLength: 20 }); + expect(result.name).toBe("Error"); + expect(result.message).toMatch(/This is a test/); + expect((result.message as string).length).toBeLessThanOrEqual(20); + }); + + it("should copy over custom error properties", () => { + const err = new Error("test message"); + err.code = "ERR_TEST"; + err.customField = "some value"; + const result = truncateError(err, { maxLength: 10 }); + expect(result.code).toBe("ERR_TEST"); + expect(result.customField).toBe("some value"); + }); + + it("should truncate nested properties in error", () => { + // @ts-expect-error - testing with non-standard error structure + const err = new Error("test"); + err.nested = { deep: "A very deeply nested string that definitely needs truncation" }; + const result = truncateError(err, { maxLength: 15 }); + expect((result.nested as any).deep).toMatch(/A very de.../); + }); + + it("should handle empty error", () => { + const err = new Error(""); + const result = truncateError(err, { maxLength: 10 }); + expect(result.message).toBe(""); + expect(result.name).toBe("Error"); + }); +}); \ No newline at end of file diff --git a/packages/sdk/src/truncate.ts b/packages/sdk/src/truncate.ts new file mode 100644 index 00000000..5c1be2ca --- /dev/null +++ b/packages/sdk/src/truncate.ts @@ -0,0 +1,95 @@ +/** + * Truncates oversized string fields in structured data (objects, arrays, error objects) + * to prevent log inflation and accidental retention of sensitive context. + * + * Acceptance criteria for issue #667: + * - Add a configurable maximum serialized string length in the shared logging package. + * - Mark truncated values without including discarded content. + * - Handle nested fields consistently. + * - Add tests for strings, arrays, and error objects. + * + * The `maxLength` parameter is configurable by the caller. + * Truncated values are marked with a suffix so the caller knows content was discarded. + */ +export type TruncateOptions = { + /** Maximum length for any string value. Defaults to 100. */ + maxLength?: number; + /** Suffix to append to truncated values. */ + truncatedSuffix?: string; +}; + +/** + * Recursively truncate string values in data structures. + * + * - Strings longer than `maxLength` are truncated and suffix-appended. + * - Objects and arrays are recursed into, preserving structure. + * - Non-string values are returned as-is. + * + * @param data The data structure to truncate (object, array, or primitive). + * @param options Configuration for truncation behavior. + * @returns A new data structure with strings truncated beyond `maxLength`. + */ +export function truncateStrings( + data: unknown, + options: TruncateOptions = {}, +): unknown { + const { maxLength = 100, truncatedSuffix = "..." } = options; + const marker = truncatedSuffix; + + if (typeof data === "string") { + return data.length > maxLength + ? data.slice(0, maxLength) + marker + : data; + } + + if (Array.isArray(data)) { + return data.map((item) => truncateStrings(item, options)); + } + + if (data !== null && typeof data === "object") { + const result: Record = {}; + for (const [key, value] of Object.entries(data)) { + result[key] = truncateStrings(value, options); + } + return result; + } + + return data; +} + +/** + * Truncates string fields in an Error object, preserving the error class and + * non-string properties. Useful for serializing errors in logs without + * leaking large stack traces or sensitive data. + * + * @param err The Error instance to truncate. + * @param options Configuration for truncation behavior. + * @returns A plain object with all string values truncated, suitable for logging. + */ +export function truncateError( + err: Error, + options: TruncateOptions = {}, +): Record { + const { maxLength = 100, truncatedSuffix = "..." } = options; + const result: Record = { + name: err.name, + message: truncateStrings(err.message, { maxLength, truncatedSuffix }) as string, + }; + + // Copy own enumerable properties that are strings or objects/arrays + // (but not the prototype chain methods like stack, etc.) + for (const key of Object.keys(err) as (keyof Error)[]) { + if (key === "stack" || key === "message") continue; + const value = (err as any)[key]; + if (typeof value === "string") { + result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); + } else if (value !== null && typeof value === "object" && !Array.isArray(value)) { + // Recursively truncate nested objects + result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); + } else if (Array.isArray(value)) { + result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); + } + } + + return result; +} \ No newline at end of file From 3ad1938ba55f316a774363096a77f1ce3a968040 Mon Sep 17 00:00:00 2001 From: Damilorlar Date: Wed, 25 Nov 2026 06:48:32 +0100 Subject: [PATCH 2/3] feat: add truncate utility for oversized fields in structured logs (issue #667) - Add configurable max serialized string length - Mark truncated values with suffix without including discarded content - Handle nested fields consistently - Add tests for strings, arrays, and error objects --- packages/sdk/package.json | 5 +++-- packages/sdk/src/index.ts | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 8f2a6890..6c2dabdb 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -24,7 +24,7 @@ ".": "./src/index.ts" }, "scripts": { - "test": "node --import tsx --test src/client.test.ts src/encoding.test.ts src/errors.test.ts src/ids.test.ts src/mainnet-readiness.test.ts", + "test": "node --import tsx --test src/client.test.ts src/encoding.test.ts src/errors.test.ts src/ids.test.ts src/mainnet-readiness.test.ts src/truncate.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { @@ -36,6 +36,7 @@ "devDependencies": { "@types/node": "^25.9.1", "tsx": "^4.22.4", - "typescript": "^6.0.3" + "typescript": "^6.0.3", + "vitest": "^2.0.5" } } diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index ac678ec0..bc9e362d 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -76,6 +76,7 @@ export { type BidReceiptEntry, RECEIPT_VERSION, } from "./receipt.js"; +export { truncateStrings, truncateError, type TruncateOptions } from "./truncate.js"; export { verifyReceipt, type VerificationIssue, From c6b546b1d77fd438237be31c23101fad6baf22ef Mon Sep 17 00:00:00 2001 From: Codebuff Date: Wed, 25 Nov 2026 11:09:51 +0000 Subject: [PATCH 3/3] fix(sdk): run the log-truncation tests and keep the lockfile frozen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The branch added a second `test` key and a vitest devDependency to the SDK package, so `pnpm install --frozen-lockfile` failed before every CI job could start and the new tests were never executed. Run them on node:test with the rest of the SDK, correct the assertions, tighten the truncation types, and extend the public-API snapshot for the two new exports. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- packages/sdk/package.json | 7 +- packages/sdk/src/public-api-snapshot.test.ts | 2 + packages/sdk/src/truncate.test.ts | 192 +++++++++++++------ packages/sdk/src/truncate.ts | 132 ++++++------- 4 files changed, 208 insertions(+), 125 deletions(-) diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 7a103ab3..acd5d656 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -25,9 +25,7 @@ "./network": "./src/network.ts" }, "scripts": { - "test": "node --import tsx --test src/client.test.ts src/encoding.test.ts src/errors.test.ts src/ids.test.ts src/mainnet-readiness.test.ts src/truncate.test.ts", - - "test": "node --import tsx --test src/asset-config.test.ts src/client.test.ts src/conservation.test.ts src/encoding.test.ts src/encrypted-blob.test.ts src/errors.test.ts src/export-receipt.test.ts src/ids.test.ts src/mainnet-readiness.test.ts src/network.test.ts src/preflight.test.ts src/public-api-snapshot.test.ts src/receipt.test.ts src/redact.test.ts src/round-status.test.ts src/status-client.test.ts src/verify.test.ts", + "test": "node --import tsx --test src/asset-config.test.ts src/client.test.ts src/conservation.test.ts src/encoding.test.ts src/encrypted-blob.test.ts src/errors.test.ts src/export-receipt.test.ts src/ids.test.ts src/mainnet-readiness.test.ts src/network.test.ts src/preflight.test.ts src/public-api-snapshot.test.ts src/receipt.test.ts src/redact.test.ts src/round-status.test.ts src/status-client.test.ts src/truncate.test.ts src/verify.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { @@ -41,7 +39,6 @@ "devDependencies": { "@types/node": "^25.9.1", "tsx": "^4.22.4", - "typescript": "^6.0.3", - "vitest": "^2.0.5" + "typescript": "^6.0.3" } } diff --git a/packages/sdk/src/public-api-snapshot.test.ts b/packages/sdk/src/public-api-snapshot.test.ts index 0a9e6df6..97ae3dec 100644 --- a/packages/sdk/src/public-api-snapshot.test.ts +++ b/packages/sdk/src/public-api-snapshot.test.ts @@ -106,6 +106,8 @@ const EXPECTED_EXPORTS = [ "runMainnetReadiness", "summarizeDeploymentValue", "serializeReceipt", + "truncateError", + "truncateStrings", "tryDecodeBase64", "tryDecodeHex", "validateAssetConfig", diff --git a/packages/sdk/src/truncate.test.ts b/packages/sdk/src/truncate.test.ts index af6ee3df..d54e3f26 100644 --- a/packages/sdk/src/truncate.test.ts +++ b/packages/sdk/src/truncate.test.ts @@ -1,83 +1,163 @@ -import { truncateStrings, truncateError, type TruncateOptions } from "./truncate.js"; -import { describe, it, expect } from "vitest"; +// Copyright (c) 2026 Sub Rosa contributors +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; + +import { + DEFAULT_MAX_LENGTH, + DEFAULT_TRUNCATED_SUFFIX, + truncateError, + truncateStrings, + type TruncateOptions, +} from "./truncate.js"; + +function asRecord(value: unknown): Record { + assert.ok(value !== null && typeof value === "object" && !Array.isArray(value)); + return value as Record; +} + +function asArray(value: unknown): unknown[] { + assert.ok(Array.isArray(value)); + return value; +} describe("truncateStrings", () => { - it("should truncate strings longer than maxLength", () => { - const input = "Hello, this is a very long string that should be truncated"; - const result = truncateStrings(input, { maxLength: 10 }); - expect(result).toBe("Hello, this..."); + it("keeps the first maxLength characters and marks the truncated value", () => { + const result = truncateStrings("Hello, this is a very long string", { maxLength: 10 }); + assert.equal(result, "Hello, thi..."); + assert.equal(result.length, 13); + }); + + it("leaves strings at or below maxLength untouched", () => { + assert.equal(truncateStrings("Short", { maxLength: 10 }), "Short"); + assert.equal(truncateStrings("ExactlyTen", { maxLength: 10 }), "ExactlyTen"); + }); + + it("does not include the discarded remainder in the result", () => { + const secretTail = "sk_live_do_not_log_me"; + const result = truncateStrings(`prefix-${secretTail}`, { maxLength: 6 }); + assert.equal(result, "prefix..."); + assert.ok(!result.includes("sk_live")); + }); + + it("uses the documented default limit and marker", () => { + const long = "a".repeat(DEFAULT_MAX_LENGTH); + assert.equal(truncateStrings(long), long); + assert.equal( + truncateStrings(`${long}b`), + `${long}${DEFAULT_TRUNCATED_SUFFIX}`, + ); + }); + + it("applies the limit to nested object fields at every depth", () => { + const input = { + round: 42, + message: "Hello world", + nested: { deep: { deeper: "A very deep nested string that needs truncation" } }, + }; + const result = asRecord(truncateStrings(input, { maxLength: 10 })); + assert.equal(result.round, 42); + assert.equal(result.message, "Hello worl..."); + assert.equal(asRecord(asRecord(result.nested).deep).deeper, "A very dee..."); }); - it("should not truncate strings shorter than maxLength", () => { - const input = "Short"; - const result = truncateStrings(input, { maxLength: 10 }); - expect(result).toBe("Short"); + it("truncates strings inside arrays and nested arrays", () => { + const input = ["short", "A very long string that should be truncated", ["Nested array value that is long"]]; + const result = asArray(truncateStrings(input, { maxLength: 10 })); + assert.deepEqual(result[0], "short"); + assert.deepEqual(result[1], "A very lon..."); + assert.deepEqual(asArray(result[2])[0], "Nested arr..."); }); - it("should truncate nested strings in objects", () => { - const input = { message: "Hello world", nested: { deep: "A very deep nested string that needs truncation" } }; - const result = truncateStrings(input, { maxLength: 10 }); - expect(result.message).toBe("Hello world"); - expect(result.nested.deep).toMatch(/A very de.../); + it("passes non-string values through unchanged", () => { + const input = { nullValue: null, undefinedValue: undefined, count: 7, enabled: true, total: 10n }; + assert.deepEqual(truncateStrings(input, { maxLength: 1 }), input); + assert.equal(truncateStrings(null, { maxLength: 1 }), null); + assert.equal(truncateStrings(undefined, { maxLength: 1 }), undefined); + assert.equal(truncateStrings(1234, { maxLength: 1 }), 1234); }); - it("should truncate strings in arrays", () => { - const input = ["short", "A very long string that should be truncated", "another short one"]; - const result = truncateStrings(input, { maxLength: 10 }); - expect(result[0]).toBe("short"); - expect(result[1]).toMatch(/Long stri.../); - expect(result[2]).toBe("another short one"); + it("handles empty strings", () => { + assert.equal(truncateStrings("", { maxLength: 0 }), ""); }); - it("should handle null and undefined", () => { - const result = truncateStrings(null as any, { maxLength: 10 }); - expect(result).toBeNull(); - const result2 = truncateStrings(undefined as any, { maxLength: 10 }); - expect(result2).toBeUndefined(); + it("supports a zero limit by keeping only the marker", () => { + assert.equal(truncateStrings("anything", { maxLength: 0 }), "..."); }); - it("should handle empty strings", () => { - const result = truncateStrings("", { maxLength: 10 }); - expect(result).toBe(""); + it("honours a custom marker", () => { + const options: TruncateOptions = { maxLength: 10, truncatedSuffix: "[TRUNCATED]" }; + assert.equal(truncateStrings("This is a test string", options), "This is a [TRUNCATED]"); }); - it("should use custom maxLength and truncatedSuffix", () => { - const input = "This is a test string that is quite long"; - const result = truncateStrings(input, { maxLength: 10, truncatedSuffix: "[TRUNCATED]" }); - expect(result).toBe("This is a [TRUNCATED]"); + it("rejects an invalid maxLength", () => { + assert.throws(() => truncateStrings("x", { maxLength: -1 }), RangeError); + assert.throws(() => truncateStrings("x", { maxLength: 1.5 }), RangeError); + assert.throws(() => truncateStrings("x", { maxLength: Number.NaN }), RangeError); }); }); describe("truncateError", () => { - it("should truncate error message and preserve name", () => { - const err = new Error("This is a test error message that is quite long to trigger truncation"); + it("truncates the message and keeps the error name", () => { + const err = new Error("This is a test error message that is long enough to truncate"); const result = truncateError(err, { maxLength: 20 }); - expect(result.name).toBe("Error"); - expect(result.message).toMatch(/This is a test/); - expect((result.message as string).length).toBeLessThanOrEqual(20); + assert.equal(result.name, "Error"); + assert.equal(result.message, "This is a test error..."); }); - it("should copy over custom error properties", () => { - const err = new Error("test message"); - err.code = "ERR_TEST"; - err.customField = "some value"; - const result = truncateError(err, { maxLength: 10 }); - expect(result.code).toBe("ERR_TEST"); - expect(result.customField).toBe("some value"); + it("preserves a custom error subclass name", () => { + class DomainError extends Error { + override name = "DomainError"; + } + const result = truncateError(new DomainError("closed"), { maxLength: 20 }); + assert.equal(result.name, "DomainError"); + assert.equal(result.message, "closed"); }); - it("should truncate nested properties in error", () => { - // @ts-expect-error - testing with non-standard error structure - const err = new Error("test"); - err.nested = { deep: "A very deeply nested string that definitely needs truncation" }; + it("copies own properties of every type", () => { + const err = Object.assign(new Error("test message"), { code: "ERR_TEST", attempt: 2 }); + const result = truncateError(err, { maxLength: 100 }); + assert.equal(result.code, "ERR_TEST"); + assert.equal(result.attempt, 2); + }); + + it("truncates custom string properties", () => { + const err = Object.assign(new Error("test"), { detail: "A custom detail string that is too long" }); + assert.equal(truncateError(err, { maxLength: 8 }).detail, "A custom..."); + }); + + it("truncates nested properties and causes", () => { + const cause = new Error("the underlying provider failure"); + const err = Object.assign(new Error("wrapper"), { + nested: { deep: "A very deeply nested string that needs truncation" }, + cause, + }); const result = truncateError(err, { maxLength: 15 }); - expect((result.nested as any).deep).toMatch(/A very de.../); + assert.equal(asRecord(result.nested).deep, "A very deeply n..."); + const serializedCause = asRecord(nestedCause(result)); + assert.equal(serializedCause.name, "Error"); + assert.equal(serializedCause.message, "the underlying ..."); + }); + + it("omits the stack", () => { + const result = truncateError(new Error("boom"), { maxLength: 100 }); + assert.ok(!("stack" in result)); + }); + + it("handles an empty message", () => { + const result = truncateError(new Error(""), { maxLength: 10 }); + assert.equal(result.message, ""); + assert.equal(result.name, "Error"); }); - it("should handle empty error", () => { - const err = new Error(""); - const result = truncateError(err, { maxLength: 10 }); - expect(result.message).toBe(""); - expect(result.name).toBe("Error"); + it("handles errors inside arrays", () => { + const result = truncateStrings([new Error("first"), new Error("second")], { maxLength: 100 }); + const [first, second] = asArray(result); + assert.equal(asRecord(first).message, "first"); + assert.equal(asRecord(second).message, "second"); }); -}); \ No newline at end of file +}); + +function nestedCause(result: Record): unknown { + assert.ok("cause" in result, "cause must be preserved"); + return result.cause; +} diff --git a/packages/sdk/src/truncate.ts b/packages/sdk/src/truncate.ts index 5c1be2ca..1ef3446d 100644 --- a/packages/sdk/src/truncate.ts +++ b/packages/sdk/src/truncate.ts @@ -1,51 +1,69 @@ +// Copyright (c) 2026 Sub Rosa contributors /** - * Truncates oversized string fields in structured data (objects, arrays, error objects) - * to prevent log inflation and accidental retention of sensitive context. + * Truncates oversized string fields in structured data (objects, arrays and + * error objects) so a single large upstream error or malformed input cannot + * inflate log volume or carry more sensitive context than the caller intended. * * Acceptance criteria for issue #667: - * - Add a configurable maximum serialized string length in the shared logging package. - * - Mark truncated values without including discarded content. - * - Handle nested fields consistently. - * - Add tests for strings, arrays, and error objects. + * - A configurable maximum serialized string length. + * - Truncated values are marked without retaining the discarded content. + * - Nested fields are handled consistently. + * - Tests cover strings, arrays and error objects. * - * The `maxLength` parameter is configurable by the caller. - * Truncated values are marked with a suffix so the caller knows content was discarded. + * A string is truncated only when it is strictly longer than `maxLength`. The + * retained prefix is at most `maxLength` characters and the marker records that + * content was dropped. The discarded tail is never copied into the result. */ -export type TruncateOptions = { - /** Maximum length for any string value. Defaults to 100. */ + +/** Marker used when the caller does not supply `truncatedSuffix`. */ +export const DEFAULT_TRUNCATED_SUFFIX = "..."; + +/** Retained characters per string when the caller does not supply `maxLength`. */ +export const DEFAULT_MAX_LENGTH = 100; + +export interface TruncateOptions { + /** Maximum number of characters retained from any single string. Defaults to 100. */ maxLength?: number; - /** Suffix to append to truncated values. */ + /** Marker appended to a truncated string. Defaults to "...". */ truncatedSuffix?: string; -}; +} + +function resolveOptions(options: TruncateOptions): Required { + const maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH; + if (!Number.isInteger(maxLength) || maxLength < 0) { + throw new RangeError(`maxLength must be a non-negative integer; received ${String(options.maxLength)}`); + } + return { + maxLength, + truncatedSuffix: options.truncatedSuffix ?? DEFAULT_TRUNCATED_SUFFIX, + }; +} + +function truncateString(value: string, maxLength: number, truncatedSuffix: string): string { + return value.length > maxLength ? value.slice(0, maxLength) + truncatedSuffix : value; +} /** - * Recursively truncate string values in data structures. + * Recursively truncates string values in a data structure. * - * - Strings longer than `maxLength` are truncated and suffix-appended. - * - Objects and arrays are recursed into, preserving structure. - * - Non-string values are returned as-is. + * - Strings longer than `maxLength` keep their first `maxLength` characters and + * gain the marker; the discarded remainder is dropped. + * - Arrays and plain objects are recursed into, preserving their shape and order. + * - Every other value (null, undefined, numbers, booleans, bigint) is returned as + * it was, so callers can pass a heterogeneous log context directly. * - * @param data The data structure to truncate (object, array, or primitive). - * @param options Configuration for truncation behavior. - * @returns A new data structure with strings truncated beyond `maxLength`. + * @throws RangeError when `maxLength` is negative or not an integer. */ -export function truncateStrings( - data: unknown, - options: TruncateOptions = {}, -): unknown { - const { maxLength = 100, truncatedSuffix = "..." } = options; - const marker = truncatedSuffix; - - if (typeof data === "string") { - return data.length > maxLength - ? data.slice(0, maxLength) + marker - : data; - } - - if (Array.isArray(data)) { - return data.map((item) => truncateStrings(item, options)); - } +export function truncateStrings(value: string, options?: TruncateOptions): string; +export function truncateStrings(value: unknown, options?: TruncateOptions): unknown; +export function truncateStrings(data: unknown, options: TruncateOptions = {}): unknown { + const { maxLength, truncatedSuffix } = resolveOptions(options); + if (typeof data === "string") return truncateString(data, maxLength, truncatedSuffix); + // Error members are non-enumerable, so an Error needs its own pass before the + // generic object walk; callers often nest errors inside log context. + if (data instanceof Error) return truncateError(data, options); + if (Array.isArray(data)) return data.map((item) => truncateStrings(item, options)); if (data !== null && typeof data === "object") { const result: Record = {}; for (const [key, value] of Object.entries(data)) { @@ -53,43 +71,29 @@ export function truncateStrings( } return result; } - return data; } /** - * Truncates string fields in an Error object, preserving the error class and - * non-string properties. Useful for serializing errors in logs without - * leaking large stack traces or sensitive data. + * Serializes an Error for logging with every string field truncated. * - * @param err The Error instance to truncate. - * @param options Configuration for truncation behavior. - * @returns A plain object with all string values truncated, suitable for logging. + * Own enumerable properties are kept (including `cause` and custom fields such + * as `code`), `name` and `message` are preserved, and `stack` is omitted: it is + * the largest and most incidental field of a logged error and its content is + * already represented by the message. + * + * @throws RangeError when `maxLength` is negative or not an integer. */ -export function truncateError( - err: Error, - options: TruncateOptions = {}, -): Record { - const { maxLength = 100, truncatedSuffix = "..." } = options; +export function truncateError(err: Error, options: TruncateOptions = {}): Record { + const { maxLength, truncatedSuffix } = resolveOptions(options); const result: Record = { - name: err.name, - message: truncateStrings(err.message, { maxLength, truncatedSuffix }) as string, + name: truncateString(err.name, maxLength, truncatedSuffix), + message: truncateString(err.message, maxLength, truncatedSuffix), }; - // Copy own enumerable properties that are strings or objects/arrays - // (but not the prototype chain methods like stack, etc.) - for (const key of Object.keys(err) as (keyof Error)[]) { - if (key === "stack" || key === "message") continue; - const value = (err as any)[key]; - if (typeof value === "string") { - result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); - } else if (value !== null && typeof value === "object" && !Array.isArray(value)) { - // Recursively truncate nested objects - result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); - } else if (Array.isArray(value)) { - result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); - } + for (const [key, value] of Object.entries(err)) { + if (key === "name" || key === "message" || key === "stack") continue; + result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); } - return result; -} \ No newline at end of file +}