From 9fb8414f0343a6c5be8b58a66b6bce639585c4b0 Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:30:25 -0600 Subject: [PATCH] Encode lone surrogates as U+FFFD --- src/utils/utf8.ts | 4 ++++ test/encode.test.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/utils/utf8.ts b/src/utils/utf8.ts index 1494f70..19ec87d 100644 --- a/src/utils/utf8.ts +++ b/src/utils/utf8.ts @@ -65,6 +65,10 @@ export function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: numb } } + if (value >= 0xd800 && value <= 0xdfff) { + value = 0xfffd; + } + if ((value & 0xffff0000) === 0) { // 3-byte output[offset++] = ((value >> 12) & 0x0f) | 0xe0; diff --git a/test/encode.test.ts b/test/encode.test.ts index f1b6ffe..4198df7 100644 --- a/test/encode.test.ts +++ b/test/encode.test.ts @@ -49,6 +49,18 @@ describe("encode", () => { }); }); + context("strings", () => { + it("encodes lone surrogates as U+FFFD in short strings", () => { + assert.deepStrictEqual(encode("a\ud800"), Uint8Array.from([0xa4, 0x61, 0xef, 0xbf, 0xbd])); + assert.deepStrictEqual(encode("a\udc00b"), Uint8Array.from([0xa5, 0x61, 0xef, 0xbf, 0xbd, 0x62])); + assert.deepStrictEqual(encode("\udc00\ud800"), Uint8Array.from([0xa6, 0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd])); + }); + + it("keeps surrogate pairs intact in short strings", () => { + assert.deepStrictEqual(encode("a\ud83d\ude00"), Uint8Array.from([0xa5, 0x61, 0xf0, 0x9f, 0x98, 0x80])); + }); + }); + context("ignoreUndefined", () => { it("encodes { foo: undefined } as is by default", () => { assert.deepStrictEqual(decode(encode({ foo: undefined, bar: 42 })), { foo: null, bar: 42 });