diff --git a/packages/typescript/src/api/node/wtf8.ts b/packages/typescript/src/api/node/wtf8.ts index f73ac298e35f6..77185c77becd7 100644 --- a/packages/typescript/src/api/node/wtf8.ts +++ b/packages/typescript/src/api/node/wtf8.ts @@ -119,6 +119,12 @@ export function encodeWtf8(text: string): Uint8Array { } export class Wtf8Decoder extends TextDecoder { + constructor(label = "utf-8") { + // U+FEFF inside a payload is data. TextDecoder otherwise drops it at the + // start of each segment, including the segment after a lone surrogate. + super(label, { ignoreBOM: true }); + } + override decode(input?: DecodeInput, options?: DecodeOptions): string { if (input == null) { return super.decode(undefined, options); diff --git a/packages/typescript/src/wasm/transport.ts b/packages/typescript/src/wasm/transport.ts index 1882dde34e979..78ba577d5b6e6 100644 --- a/packages/typescript/src/wasm/transport.ts +++ b/packages/typescript/src/wasm/transport.ts @@ -84,7 +84,7 @@ type Frame = RequestFrame | CallFrame; const encoder = new TextEncoder(); const decoder = new TextDecoder(); -const fileContentDecoder = new Wtf8Decoder("utf-8", { ignoreBOM: true }); +const fileContentDecoder = new Wtf8Decoder("utf-8"); /** * API transport backed by an in-process TypeScript WebAssembly reactor. diff --git a/packages/typescript/test/wtf8.test.ts b/packages/typescript/test/wtf8.test.ts index 94480e2fd1c1a..1c24269ce1eee 100644 --- a/packages/typescript/test/wtf8.test.ts +++ b/packages/typescript/test/wtf8.test.ts @@ -87,6 +87,25 @@ describe("Wtf8Decoder", { concurrency }, () => { [0xD83E, 0xDD80, 0xD7FF, 0xD800, 0xD801, 0xDC00, 0xD83E, 0xDD80], ); }); + + test("preserves U+FEFF at the start of a decoded segment", () => { + const decoder = new Wtf8Decoder(); + const cases: readonly [string, string, readonly number[]][] = [ + ["leading", "\uFEFFx", [0xFEFF, 0x78]], + ["only", "\uFEFF", [0xFEFF]], + ["after a lone surrogate", "\uD800\uFEFF", [0xD800, 0xFEFF]], + ["middle", "a\uFEFFb", [0x61, 0xFEFF, 0x62]], + ["template text", "\uFEFFtail", [0xFEFF, 0x74, 0x61, 0x69, 0x6C]], + ]; + + for (const [name, text, expected] of cases) { + assert.deepStrictEqual( + Array.from(decoder.decode(encodeWtf8(text)), c => c.codePointAt(0)), + expected, + name, + ); + } + }); }); describe("Msgpack strings", { concurrency }, () => {