| 1 | // Stand-in for @vscode/iconv-lite-umd: UTF-8 only, on TextEncoder and |
| 2 | // TextDecoder. The sandbox only ever sees text that Code's page sent it, and |
| 3 | // that text is UTF-8; any other encoding is refused instead of shipping the |
| 4 | // full code-page tables. |
| 5 | const isUtf8 = enc => String(enc || '').toLowerCase().replace(/[^a-z0-9]/g, '') === 'utf8'; |
| 6 | const unsupported = enc => Object.assign(new Error('Encoding not available in Elffuss Code: ' + String(enc)), { code: 'ENOTSUP' }); |
| 7 | |
| 8 | export function encodingExists(enc) { return isUtf8(enc); } |
| 9 | |
| 10 | export function getDecoder(enc, options = {}) { |
| 11 | if (!isUtf8(enc)) throw unsupported(enc); |
| 12 | const decoder = new TextDecoder('utf-8', { ignoreBOM: options.stripBOM === false }); |
| 13 | return { |
| 14 | write: buf => decoder.decode(buf, { stream: true }), |
| 15 | end: () => decoder.decode() || undefined, |
| 16 | }; |
| 17 | } |
| 18 | |
| 19 | export function getEncoder(enc, options = {}) { |
| 20 | if (!isUtf8(enc)) throw unsupported(enc); |
| 21 | const encoder = new TextEncoder(); |
| 22 | let first = !!options.addBOM; |
| 23 | return { |
| 24 | write(text) { |
| 25 | const bytes = encoder.encode(String(text)); |
| 26 | if (!first) return bytes; |
| 27 | first = false; |
| 28 | const out = new Uint8Array(bytes.length + 3); |
| 29 | out.set([0xef, 0xbb, 0xbf]); |
| 30 | out.set(bytes, 3); |
| 31 | return out; |
| 32 | }, |
| 33 | end: () => undefined, |
| 34 | }; |
| 35 | } |
| 36 | |
| 37 | export function decode(buf, enc) { return getDecoder(enc).write(buf); } |
| 38 | export function encode(text, enc) { return getEncoder(enc).write(text); } |
| 39 | export default { encodingExists, getDecoder, getEncoder, decode, encode }; |