Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

๐Ÿ› fix(agent-runtime): stop sanitizeNullBytes from corrupting escape text (#18507)

Arvin Xu5072403ae0c7
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
index 3bc59199f00..ddfda5ebfe3 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
@@ -52,7 +52,54 @@ describe('formatErrorForState', () => {
expect(result.type).toBe(ChatErrorType.InternalServerError);
expect(result.message).toBe('boom');
- expect(result.body).toEqual({ name: 'TypeError' });
+ expect(result.body).toMatchObject({ name: 'TypeError' });
+ });
+
+ it('persists the stack of an unclassified Error so the throw site is locatable', () => {
+ // `name` + `message` alone are useless for a recurring harness 500 โ€” the
+ // only thing that identifies where it blew up is the stack.
+ const result = formatErrorForState(new Error('some opaque internal failure'));
+
+ expect(result.type).toBe(ChatErrorType.InternalServerError);
+ expect((result.body as { stack?: string }).stack).toContain('formatErrorForState.test');
+ });
+
+ it('classifies a harness JSON.parse throw instead of leaving a bare 500', () => {
+ // The production shape: `SyntaxError` out of a harness `JSON.parse`,
+ // previously stored as `{ type: 500, body: { name: 'SyntaxError' } }` with
+ // no attribution, category or failure accounting at all.
+ const result = formatErrorForState(
+ new SyntaxError('Bad escaped character in JSON at position 46269 (line 1 column 46270)'),
+ );
+
+ expect(result.type).toBe(AgentRuntimeErrorType.HarnessJsonParseError);
+ expect(result.attribution).toBe('harness');
+ expect(result.category).toBe('stream');
+ expect(result.numericId).toBe(7008);
+ expect(result.countAsFailure).toBe(true);
+ // Deterministic โ€” the same corrupt payload re-parses to the same failure,
+ // so a transport retry would only re-burn the run's tokens.
+ expect(result.retryable).toBe(false);
+ // Classification must not cost us the throw site.
+ expect((result.body as { name?: string; stack?: string }).name).toBe('SyntaxError');
+ expect((result.body as { stack?: string }).stack).toContain('formatErrorForState.test');
+ });
+
+ it('truncates an oversized stack instead of storing it whole', () => {
+ const error = new Error('boom');
+ error.stack = 'x'.repeat(10_000);
+
+ const stack = (formatErrorForState(error).body as { stack?: string }).stack;
+
+ expect(stack).toHaveLength(1001);
+ expect(stack?.endsWith('โ€ฆ')).toBe(true);
+ });
+
+ it('omits `stack` when the thrown Error carries none', () => {
+ const error = new Error('boom');
+ error.stack = undefined;
+
+ expect((formatErrorForState(error).body as { stack?: string }).stack).toBeUndefined();
});
it('falls back to AgentRuntimeError for unknown thrown values', () => {
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.ts
index 84514986dea..96b9da803ee 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.ts
@@ -96,6 +96,18 @@ const buildPayloadBody = (
};
};
+/**
+ * Cap a stack before it lands in `agent_operations.error` / trace snapshots.
+ * The top frames identify the throw site; the rest is runtime plumbing that
+ * would only bloat every stored error row.
+ */
+const STACK_MAX_CHARS = 1000;
+
+const truncateStack = (stack: string | undefined): string | undefined => {
+ if (!stack) return undefined;
+ return stack.length > STACK_MAX_CHARS ? `${stack.slice(0, STACK_MAX_CHARS)}โ€ฆ` : stack;
+};
+
/**
* Merge classification metadata from `ERROR_CODE_SPECS` onto a normalized
* `ChatMessageError`. Codes that aren't in the spec table (fallbacks like
@@ -208,8 +220,14 @@ export const formatErrorForState = (error: unknown): ChatMessageError => {
};
}
+ // Unclassified harness throw: nothing upstream recognized it, so `name` +
+ // `message` are all the triage signal there is โ€” and for a `SyntaxError`
+ // out of some `JSON.parse` those two say nothing about WHERE it blew up.
+ // Persist the stack (bounded; frames are what matter, not a runaway trace)
+ // the way the pg branch already persists `pg`, so a recurring 500 is
+ // locatable from the stored operation instead of needing a live repro.
return enrichWithSpec({
- body: { name: error.name },
+ body: { name: error.name, stack: truncateStack(error.stack) },
message: error.message,
type: ChatErrorType.InternalServerError,
});
diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.json
index e89aa4ef050..7261621c290 100644
--- a/locales/en-US/modelRuntime.json
+++ b/locales/en-US/modelRuntime.json
@@ -13,6 +13,7 @@
"ContextEnginePipelineError": "Failed to assemble the conversation context for this request. Please try again; if it persists, contact support.",
"DatabasePersistError": "A database operation failed while saving or loading this conversation. Please try again; if it persists, contact support.",
"ExceededContextWindow": "The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.",
+ "HarnessJsonParseError": "An internal payload could not be read back, so this operation stopped. Retrying the same request will hit the same failure โ€” please start a new message; if it persists, contact support.",
"InsufficientQuota": "Sorry, the quota for this key has been reached. Please check if your account balance is sufficient or try again after increasing the key's quota.",
"InvalidBedrockCredentials": "Bedrock authentication failed. Please check the AccessKeyId/SecretAccessKey and retry.",
"InvalidComfyUIArgs": "Invalid ComfyUI configuration. Please check the settings and try again.",
diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.json
index 382285d4da3..0cbb22f1e1f 100644
--- a/locales/zh-CN/modelRuntime.json
+++ b/locales/zh-CN/modelRuntime.json
@@ -13,6 +13,7 @@
"ContextEnginePipelineError": "็ป„่ฃ…ๆญค่ฏทๆฑ‚็š„ๅฏน่ฏไธŠไธ‹ๆ–‡ๅคฑ่ดฅใ€‚่ฏท้‡่ฏ•๏ผ›ๅฆ‚ๆžœ้—ฎ้ข˜ไป็„ถๅญ˜ๅœจ๏ผŒ่ฏท่”็ณปๆ”ฏๆŒใ€‚",
"DatabasePersistError": "ไฟๅญ˜ๆˆ–ๅŠ ่ฝฝๆญคๅฏน่ฏๆ—ถๆ•ฐๆฎๅบ“ๆ“ไฝœๅคฑ่ดฅใ€‚่ฏท้‡่ฏ•๏ผ›ๅฆ‚ๆžœ้—ฎ้ข˜ไป็„ถๅญ˜ๅœจ๏ผŒ่ฏท่”็ณปๆ”ฏๆŒใ€‚",
"ExceededContextWindow": "ๅฝ“ๅ‰่ฏทๆฑ‚ๅ†…ๅฎน่ถ…ๅ‡บไบ†ๆจกๅž‹ๅฏๅค„็†็š„้•ฟๅบฆใ€‚่ฏทๅ‡ๅฐ‘ๅ†…ๅฎน้‡ๅนถ้‡่ฏ•ใ€‚",
+ "HarnessJsonParseError": "ๅ†…้ƒจๆ•ฐๆฎๅ›ž่ฏปๅคฑ่ดฅ๏ผŒๆœฌๆฌกๆ“ไฝœๅทฒไธญๆญขใ€‚้‡่ฏ•ๅŒไธ€่ฏทๆฑ‚ไผš้‡ๅˆฐๅŒๆ ท็š„ๅคฑ่ดฅ๏ผŒ่ฏท้‡ๆ–ฐๅ‘่ตทไธ€ๆกๆถˆๆฏ๏ผ›ๅฆ‚ๆžœ้—ฎ้ข˜ไป็„ถๅญ˜ๅœจ๏ผŒ่ฏท่”็ณปๆ”ฏๆŒใ€‚",
"InsufficientQuota": "ๆŠฑๆญ‰๏ผŒๆญคๅฏ†้’ฅ็š„้…้ขๅทฒ็”จๅฐฝใ€‚่ฏทๆฃ€ๆŸฅๆ‚จ็š„่ดฆๆˆทไฝ™้ขๆ˜ฏๅฆๅ……่ถณๆˆ–ๅœจๅขžๅŠ ๅฏ†้’ฅ้…้ขๅŽ้‡่ฏ•ใ€‚",
"InvalidBedrockCredentials": "Bedrock่บซไปฝ้ชŒ่ฏๅคฑ่ดฅใ€‚่ฏทๆฃ€ๆŸฅAccessKeyId/SecretAccessKeyๅนถ้‡่ฏ•ใ€‚",
"InvalidComfyUIArgs": "ComfyUI้…็ฝฎๆ— ๆ•ˆใ€‚่ฏทๆฃ€ๆŸฅ่ฎพ็ฝฎๅนถ้‡่ฏ•ใ€‚",
diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.ts
index e6503f53fd0..78fb72e7e4d 100644
--- a/packages/locales/src/default/modelRuntime.ts
+++ b/packages/locales/src/default/modelRuntime.ts
@@ -26,6 +26,8 @@ export default {
'A database operation failed while saving or loading this conversation. Please try again; if it persists, contact support.',
ExceededContextWindow:
'The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.',
+ HarnessJsonParseError:
+ 'An internal payload could not be read back, so this operation stopped. Retrying the same request will hit the same failure โ€” please start a new message; if it persists, contact support.',
InsufficientQuota:
"Sorry, the quota for this key has been reached. Please check if your account balance is sufficient or try again after increasing the key's quota.",
InvalidBedrockCredentials:
diff --git a/packages/model-runtime/src/errors/patterns.ts b/packages/model-runtime/src/errors/patterns.ts
index c866189eed3..e5e41977e2f 100644
--- a/packages/model-runtime/src/errors/patterns.ts
+++ b/packages/model-runtime/src/errors/patterns.ts
@@ -1258,6 +1258,30 @@ export const ERROR_PATTERNS: ErrorPattern[] = [
note: 'context-engine PipelineError: `Processor [<name>] execution failed`.',
},
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // HarnessJsonParseError โ€” a `JSON.parse` inside the harness threw. Sits after
+ // every provider section so an upstream body that merely quotes a JSON parse
+ // failure is claimed by its provider pattern first, and before the
+ // AgentRuntimeError fallbacks so this class keeps its own code instead of
+ // dissolving into the generic crash bucket.
+ //
+ // V8 phrases every JSON.parse failure one of two ways, so these two patterns
+ // cover the whole family: "Bad escaped character in JSON at position N",
+ // "Unterminated string in JSON at position N", "Unexpected token 'x', โ€ฆ is
+ // not valid JSON", "Expected ',' or '}' after property value in JSON at
+ // position N" โ€” and the position-less "Unexpected end of JSON input".
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ {
+ code: AgentRuntimeErrorType.HarnessJsonParseError,
+ match: sub(' in JSON at position '),
+ note: 'V8 JSON.parse SyntaxError carrying a byte offset.',
+ },
+ {
+ code: AgentRuntimeErrorType.HarnessJsonParseError,
+ match: sub('Unexpected end of JSON input'),
+ note: 'V8 JSON.parse SyntaxError on a truncated payload (no offset).',
+ },
+
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// AgentRuntimeError โ€” harness-side JS runtime crashes (V8 TypeError /
// RangeError). Our bugs, not upstream provider errors, so they stay LAST: a
diff --git a/packages/model-runtime/src/errors/refine.test.ts b/packages/model-runtime/src/errors/refine.test.ts
index 882ada6ece7..72f4d965c58 100644
--- a/packages/model-runtime/src/errors/refine.test.ts
+++ b/packages/model-runtime/src/errors/refine.test.ts
@@ -35,6 +35,38 @@ describe('refineErrorCode', () => {
).toBe(AgentRuntimeErrorType.DatabasePersistError);
});
+ it('reclassifies a 500-wrapped V8 JSON.parse throw into HarnessJsonParseError', () => {
+ // The production shape: a `SyntaxError` out of some harness `JSON.parse`,
+ // wrapped as a bare 500 and therefore invisible to every dashboard.
+ expect(
+ refineErrorCode({
+ errorType: String(ChatErrorType.InternalServerError),
+ message: 'Bad escaped character in JSON at position 46269 (line 1 column 46270)',
+ }),
+ ).toBe(AgentRuntimeErrorType.HarnessJsonParseError);
+ });
+
+ it.each([
+ 'Unterminated string in JSON at position 12 (line 1 column 13)',
+ "Expected ',' or '}' after property value in JSON at position 23",
+ 'Unexpected end of JSON input',
+ ])('covers the other V8 JSON.parse phrasings: %s', (message) => {
+ expect(
+ refineErrorCode({ errorType: String(ChatErrorType.InternalServerError), message }),
+ ).toBe(AgentRuntimeErrorType.HarnessJsonParseError);
+ });
+
+ it('does not claim a JSON-parse phrase coming from a typed provider error', () => {
+ // Only the catch-all wrappers are refinable, so an upstream body that
+ // merely quotes a parse failure keeps its own provider code.
+ expect(
+ refineErrorCode({
+ errorType: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ message: 'upstream said: Unexpected end of JSON input',
+ }),
+ ).toBeUndefined();
+ });
+
it('leaves a 500 wrapper unrefined when nothing matches', () => {
expect(
refineErrorCode({
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index 8c10e8d6799..671a79477bd 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -431,6 +431,21 @@ export const ERROR_CODE_SPECS: SpecMap = {
'State-store (Redis / Upstash) read failed: a blocking read (XREAD / BLPOP) aborted because the caller disconnected ("ERR caller gone"), or the operation\'s agent state could not be loaded ("Agent state not found for operation โ€ฆ"). System-side โ€” counts as a failure.',
},
+ [AgentRuntimeErrorType.HarnessJsonParseError]: {
+ code: AgentRuntimeErrorType.HarnessJsonParseError,
+ numericId: 7008,
+ category: 'stream',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 500,
+ // Deterministic: the same corrupt payload re-parses to the same failure, so
+ // a transport retry only re-burns the run's tokens.
+ retryable: false,
+ countAsFailure: true,
+ description:
+ 'A harness-side `JSON.parse` threw on data the harness produced or stored ("โ€ฆ in JSON at position N" / "Unexpected end of JSON input") โ€” a serialization bug, not an upstream response.',
+ },
+
// โ”€โ”€โ”€ 8xxx Provider (catch-all) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
[AgentRuntimeErrorType.AgentRuntimeError]: {
code: AgentRuntimeErrorType.AgentRuntimeError,
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 6dcd9f116ab..f936767ebbd 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -163,6 +163,16 @@ export const AgentRuntimeErrorType = {
* to this code in the spec table).
*/
ContextEnginePipelineError: 'ContextEnginePipelineError',
+ /**
+ * A `JSON.parse` inside the harness threw on data the harness itself
+ * produced, stored or round-tripped โ€” V8 reports it as `SyntaxError: โ€ฆ in
+ * JSON at position N` / `Unexpected end of JSON input`. Always our bug: the
+ * value should have been valid JSON by construction, so a failure means some
+ * serialization step corrupted or truncated it. Kept out of the
+ * `AgentRuntimeError` catch-all so this class stays countable on its own
+ * instead of hiding inside the generic fallback bucket.
+ */
+ HarnessJsonParseError: 'HarnessJsonParseError',
InvalidGithubToken: 'InvalidGithubToken',
InvalidGithubCopilotToken: 'InvalidGithubCopilotToken',
diff --git a/packages/utils/src/sanitizeNullBytes.test.ts b/packages/utils/src/sanitizeNullBytes.test.ts
index 3b3021199e1..cfb0fa5cd1b 100644
--- a/packages/utils/src/sanitizeNullBytes.test.ts
+++ b/packages/utils/src/sanitizeNullBytes.test.ts
@@ -65,4 +65,46 @@ describe('sanitizeNullBytes', () => {
const result = sanitizeNullBytes(arr);
expect(result).toEqual(['ab', 'cd']);
});
+
+ // --- regression: text that SPELLS OUT a \u0000 escape must survive ---
+
+ it('should not throw on a string containing a literal \u0000 escape sequence', () => {
+ // Real tool results carry this text verbatim: regex character classes,
+ // `GROUP_KEY_SEP = "\u0000"`, smali metadata, base64 dumps. The old
+ // stringify -> strip -> parse implementation doubled the leading backslash,
+ // matched the needle one character late, ate the escape's own backslash and
+ // died with `Bad escaped character in JSON at position N` โ€” failing the
+ // whole agent operation from the tool-result persist path.
+ const state = { content: "key = x.theme + '\\u0000' + x.category" };
+
+ expect(() => sanitizeNullBytes(state)).not.toThrow();
+ expect(sanitizeNullBytes(state).content).toBe(state.content);
+ });
+
+ it('should preserve a literal \u0000 escape followed by an invalid escape char', () => {
+ // The orphan backslash used to land in front of `U`, which is not a legal
+ // JSON escape โ€” the exact shape reported from Windows agents.
+ const state = { path: 'C:\\u0000Users' };
+
+ expect(sanitizeNullBytes(state).path).toBe('C:\\u0000Users');
+ });
+
+ it('should preserve a literal \u0000 escape at the end of a string', () => {
+ // The orphan backslash used to swallow the closing quote instead.
+ const state = { snippet: 'SEP = "\\u0000"' };
+
+ expect(sanitizeNullBytes(state).snippet).toBe('SEP = "\\u0000"');
+ });
+
+ it('should strip real null bytes while leaving literal escape text alone', () => {
+ const state = { line: 'a\u0000b, literal: \\u0000' };
+
+ expect(sanitizeNullBytes(state).line).toBe('ab, literal: \\u0000');
+ });
+
+ it('should sanitize null bytes in object keys', () => {
+ const obj = { ['a\u0000b']: 1 };
+
+ expect(Object.keys(sanitizeNullBytes(obj))).toEqual(['ab']);
+ });
});
diff --git a/packages/utils/src/sanitizeNullBytes.ts b/packages/utils/src/sanitizeNullBytes.ts
index 8347de23857..a412546c531 100644
--- a/packages/utils/src/sanitizeNullBytes.ts
+++ b/packages/utils/src/sanitizeNullBytes.ts
@@ -1,23 +1,54 @@
+/** A real U+0000 character. Built at runtime so no source file carries one. */
+const NUL = String.fromCodePoint(0);
+
+/**
+ * A NUL immediately followed by two hex digits is a double-decoding artifact:
+ * an `รฉ` that round-tripped as NUL + `e9` instead of `รฉ`. Fold those back into
+ * the character they meant.
+ */
+const CORRUPTED_ESCAPE = new RegExp(`${NUL}([0-9a-f]{2})`, 'gi');
+
+const sanitizeString = (value: string): string =>
+ value.includes(NUL)
+ ? value
+ .replaceAll(CORRUPTED_ESCAPE, (_match, hex: string) =>
+ String.fromCharCode(Number.parseInt(hex, 16)),
+ )
+ .replaceAll(NUL, '')
+ : value;
+
/**
- * Sanitize null bytes (\u0000) from values before PostgreSQL insertion.
- * PostgreSQL cannot store \u0000 in text/jsonb columns.
+ * Sanitize null bytes from values before PostgreSQL insertion โ€” PostgreSQL
+ * cannot store U+0000 in text/jsonb columns.
*
- * For strings: directly removes null bytes.
- * For objects: serializes to JSON, recovers corrupted Unicode escapes
- * (e.g. \u0000e9 โ†’ \u00e9 = รฉ), strips remaining null escapes, then parses back.
+ * Walks the value and rewrites every string in place. It deliberately does NOT
+ * round-trip through `JSON.stringify` -> string surgery -> `JSON.parse`.
+ *
+ * That round trip corrupts any payload whose TEXT spells out a unicode escape
+ * for U+0000 (regex character classes, `GROUP_KEY_SEP` constants, smali /
+ * Kotlin metadata, base64 dumps โ€” everything a coding agent reads out of real
+ * source files). `stringify` doubles that text's leading backslash, so the
+ * six-character needle then matches one character late; stripping it eats the
+ * escape's own backslash and leaves an orphan trailing backslash, and the
+ * re-parse dies with `SyntaxError: Bad escaped character in JSON at position
+ * N`. Thrown from the tool-result persist path, that killed the whole agent
+ * operation. Operating on decoded values can never reach an escape sequence,
+ * so the literal text is left untouched.
+ *
+ * Mirrors `stripNulDeep` in `@lobechat/heterogeneous-agents`, plus the
+ * corrupted-Unicode recovery above.
*/
export const sanitizeNullBytes = <T>(val: T): T => {
if (val == null) return val;
- if (typeof val === 'string') {
- return val.replaceAll('\0', '') as T;
- }
+ if (typeof val === 'string') return sanitizeString(val) as T;
+
+ if (Array.isArray(val)) return val.map((item) => sanitizeNullBytes(item)) as T;
if (typeof val === 'object') {
- const json = JSON.stringify(val);
- // Recover corrupted Unicode: \u0000XX โ†’ \u00XX, then strip remaining \u0000
- const fixed = json.replaceAll(/\\u0000([0-9a-fA-F]{2})/g, '\\u00$1').replaceAll('\\u0000', '');
- return JSON.parse(fixed);
+ return Object.fromEntries(
+ Object.entries(val).map(([key, value]) => [sanitizeString(key), sanitizeNullBytes(value)]),
+ ) as T;
}
return val;