Skip to content

Commit e0c250a

Browse files
committed
fix: TextDecoder polyfill for Uint16Array and above
1 parent d0ff051 commit e0c250a

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

bundler/modules/text-encoding-utf.cjs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,13 @@ const assertUTF8orUTF16LE = (enc) => {
2929
if (enc !== UTF8 && enc !== UTF16LE) throw new Error('only utf-8 and utf-16le are supported')
3030
}
3131

32-
const assertBufferSource = (buf) => {
33-
if (buf instanceof ArrayBuffer || ArrayBuffer.isView(buf)) return
34-
if (globalThis.SharedArrayBuffer && buf instanceof globalThis.SharedArrayBuffer) return
32+
const fromBufferSouce = (buf) => {
33+
if (buf instanceof ArrayBuffer) return Buffer.from(buf)
34+
if (ArrayBuffer.isView(buf)) return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
35+
if (globalThis.SharedArrayBuffer && buf instanceof globalThis.SharedArrayBuffer) {
36+
return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
37+
}
38+
3539
throw new Error('argument must be a SharedArrayBuffer, ArrayBuffer or ArrayBufferView')
3640
}
3741

@@ -71,8 +75,7 @@ function TextDecoder(encoding = UTF8, options = {}) {
7175
// Buffer.from([0xf0, 0x80, 0x80]).toString().length should be 3, see https://github.com/nodejs/node/issues/16894
7276
TextDecoder.prototype.decode = function (buf) {
7377
if (buf === undefined) return ''
74-
assertBufferSource(buf)
75-
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
78+
buf = fromBufferSouce(buf)
7679
const res = buf.toString(this.encoding)
7780
if (this.fatal && res.includes('\uFFFD')) {
7881
// We have a replacement symbol, recheck if output matches input

0 commit comments

Comments
 (0)