From 8f8a8539fc066a3d7f330ea2658171b455fa303b Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Wed, 2 Dec 2026 11:59:29 +0800 Subject: [PATCH] refactor(text): share unpaired surrogate checks (#15770) --- src/cli/cliOutputFormatter.ts | 5 +---- src/cli/cliResultOutput.ts | 2 +- src/domain/stringPatterns.ts | 7 ++----- src/kernel/hasUnpairedSurrogate.ts | 3 +++ src/model/SafetensorsHeader.ts | 18 +++------------- src/native/apple/losslessJson.ts | 33 ++++++------------------------ 6 files changed, 16 insertions(+), 52 deletions(-) create mode 100644 src/kernel/hasUnpairedSurrogate.ts diff --git a/src/cli/cliOutputFormatter.ts b/src/cli/cliOutputFormatter.ts index 6c3cac0ac00..8c2226f358d 100644 --- a/src/cli/cliOutputFormatter.ts +++ b/src/cli/cliOutputFormatter.ts @@ -1,3 +1,4 @@ +import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js"; /* * The TOON, JSON, YAML and JSON Lines encodings and the Markdown layout are * adapted from Incur's Formatter. @@ -41,10 +42,6 @@ export interface CliDelimitedOutputOptions { type DelimitedScalar = string | number | boolean | null | undefined; -/** UTF-8 cannot encode a lone UTF-16 surrogate without replacing it. */ -export const hasUnpairedSurrogate = (value: string): boolean => - /[\ud800-\udfff]/u.test(value); - /** Check selected output, including keys, before using a non-JSON text format. */ export const containsUnpairedSurrogate = (value: unknown): boolean => { return containsText(value, hasUnpairedSurrogate); diff --git a/src/cli/cliResultOutput.ts b/src/cli/cliResultOutput.ts index 0070d4ce091..f4ec8500604 100644 --- a/src/cli/cliResultOutput.ts +++ b/src/cli/cliResultOutput.ts @@ -1,3 +1,4 @@ +import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js"; import { constants } from "node:buffer"; import type { Writable } from "node:stream"; @@ -30,7 +31,6 @@ import { delimitedOutputInputError, containsUnpairedSurrogate, containsUnrepresentableMarkdown, - hasUnpairedSurrogate, } from "./cliOutputFormatter.js"; import { cliEvidencePublicationReceipt, diff --git a/src/domain/stringPatterns.ts b/src/domain/stringPatterns.ts index 91ff5bf1c6c..a05c8d4cc47 100644 --- a/src/domain/stringPatterns.ts +++ b/src/domain/stringPatterns.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js"; import { declaredByPatterns } from "./schemaConstraints.js"; @@ -26,10 +27,6 @@ export const INVALID_BASE64_PADDING_PATTERN = /(?:=[^=]|===)/; export const INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN = /(?:[^AQgw]==$|[BCDFGHJKLNOPRSTVWXZabdefhijlmnpqrtuvxyz1235679+\x2f]=$)/; -// In `u` mode a well-formed surrogate pair is one code point outside this -// range, so the class matches only unpaired surrogates. -const UNPAIRED_SURROGATE_PATTERN = /[\uD800-\uDFFF]/u; - /** * Reject unpaired UTF-16 surrogates without advertising a pattern. * @@ -45,7 +42,7 @@ export const rejectUnpairedSurrogates = ( message: string, ): Schema => schema.superRefine((value, context) => { - if (UNPAIRED_SURROGATE_PATTERN.test(value)) + if (hasUnpairedSurrogate(value)) context.addIssue({ code: "invalid_format", format: "regex", diff --git a/src/kernel/hasUnpairedSurrogate.ts b/src/kernel/hasUnpairedSurrogate.ts new file mode 100644 index 00000000000..7715921e957 --- /dev/null +++ b/src/kernel/hasUnpairedSurrogate.ts @@ -0,0 +1,3 @@ +/** A Unicode-mode match treats a valid surrogate pair as one code point. */ +export const hasUnpairedSurrogate = (value: string): boolean => + /[\uD800-\uDFFF]/u.test(value); diff --git a/src/model/SafetensorsHeader.ts b/src/model/SafetensorsHeader.ts index 5222796e62d..a090dd11412 100644 --- a/src/model/SafetensorsHeader.ts +++ b/src/model/SafetensorsHeader.ts @@ -1,3 +1,4 @@ +import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js"; import { BinaryReader } from "../domain/binaryContainer.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; import { parseJsonStringLiteral } from "../domain/jsonDuplicateMember.js"; @@ -67,21 +68,8 @@ class HeaderJson { return rejectModel("Invalid JSON string"); // `text` was decoded via strict UTF-8, so only `\u` escapes can // introduce unpaired UTF-16 surrogates. - if (raw.includes("\\u")) { - for (let i = 0; i < value.length; i++) { - const code = value.charCodeAt(i); - if (code >= 0xd800 && code <= 0xdbff) { - const next = value.charCodeAt(i + 1); - if (next >= 0xdc00 && next <= 0xdfff) i++; - else - rejectModel( - "Safetensors JSON contains an unpaired surrogate", - ); - } else if (code >= 0xdc00 && code <= 0xdfff) { - rejectModel("Safetensors JSON contains an unpaired surrogate"); - } - } - } + if (raw.includes("\\u") && hasUnpairedSurrogate(value)) + rejectModel("Safetensors JSON contains an unpaired surrogate"); return value; } catch (cause) { if (cause instanceof SyntaxError) diff --git a/src/native/apple/losslessJson.ts b/src/native/apple/losslessJson.ts index 7b9b2d720df..347ea23799d 100644 --- a/src/native/apple/losslessJson.ts +++ b/src/native/apple/losslessJson.ts @@ -1,3 +1,4 @@ +import { hasUnpairedSurrogate } from "../../kernel/hasUnpairedSurrogate.js"; import { parseJsonStringLiteral } from "../../domain/jsonDuplicateMember.js"; /** JSON container type a projection declined to materialize. */ @@ -280,33 +281,11 @@ class Parser { : this.text.slice(start + 1, this.position - 1); if (typeof decoded !== "string") throw new LosslessJsonFailure("Expected a JSON string"); - return this.requirePairedSurrogates(decoded); - } - - /** - * JSON admits \uXXXX escapes for unpaired surrogates, but the decoded text is - * not valid Unicode. Evidence carrying one would report malformed text as - * complete, so the parser refuses the string like any other malformed input. - * A high surrogate followed by its low surrogate escape stays valid text. - */ - private requirePairedSurrogates(value: string): string { - for (let index = 0; index < value.length; index += 1) { - const unit = value.charCodeAt(index); - if (unit >= 0xd800 && unit <= 0xdbff) { - const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0; - if (next < 0xdc00 || next > 0xdfff) - throw new LosslessJsonFailure( - "JSON string contains an unpaired surrogate", - ); - index += 1; - continue; - } - if (unit >= 0xdc00 && unit <= 0xdfff) - throw new LosslessJsonFailure( - "JSON string contains an unpaired surrogate", - ); - } - return value; + if (hasUnpairedSurrogate(decoded)) + throw new LosslessJsonFailure( + "JSON string contains an unpaired surrogate", + ); + return decoded; } private skipString(): boolean {