Skip to content

Commit f92bd22

Browse files
committed
overload decode call to throw our custom error object
1 parent 69c0661 commit f92bd22

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/files/streams.ts

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,16 @@ export class UnicodeDecodeError extends Error {
88
}
99
}
1010

11+
const _decode = TextDecoder.prototype.decode
12+
13+
TextDecoder.prototype.decode = function(input, options) {
14+
try {
15+
return _decode.call(this, input, options)
16+
} catch (error) {
17+
throw { code: 'INVALID_FILE_ENCODING', message: error}
18+
}
19+
}
20+
1121
/**
1222
* A transformer that ensures the input stream is valid UTF-8 and throws
1323
* a UnicodeDecodeError if UTF-16 BOM is detected
@@ -16,23 +26,15 @@ export class UTF8StreamTransformer implements Transformer<Uint8Array, string> {
1626
private decoder: TextDecoder
1727
private firstChunk: boolean
1828

19-
constructor({fatal: boolean = false}) {
20-
this.decoder = new TextDecoder('utf-8', {fatal})
29+
constructor(options = {fatal: false}) {
30+
this.decoder = new TextDecoder('utf-8', options)
2131
this.firstChunk = true
2232
}
2333

2434
transform(chunk: Uint8Array, controller: TransformStreamDefaultController<string>) {
2535
// Check first chunk for UTF-16 BOM
2636
if (this.firstChunk) {
27-
let decoded
28-
try {
29-
decoded = this.decoder.decode(chunk, { stream: true })
30-
} catch {
31-
throw { code: 'INVALID_FILE_ENCODING' }
32-
}
33-
if (decoded === undefined) {
34-
throw { code: 'FILE_DECODING_ERROR' }
35-
}
37+
let decoded = this.decoder.decode(chunk, { stream: true })
3638
if (decoded.startsWith('\uFFFD')) {
3739
throw new UnicodeDecodeError('This file appears to be UTF-16')
3840
}
@@ -54,6 +56,6 @@ export class UTF8StreamTransformer implements Transformer<Uint8Array, string> {
5456
/**
5557
* Creates a TransformStream that validates and decodes UTF-8 text
5658
*/
57-
export function createUTF8Stream({fatal: boolean = false}) {
58-
return new TransformStream(new UTF8StreamTransformer({fatal}))
59+
export function createUTF8Stream(options = {fatal: false}) {
60+
return new TransformStream(new UTF8StreamTransformer(options))
5961
}

0 commit comments

Comments
 (0)