From f1448ee25365b3cc99208e9fcc0575586308bc81 Mon Sep 17 00:00:00 2001 From: Yehyoung Kang Date: Thu, 16 Jun 2022 21:35:31 +0900 Subject: [PATCH] fix(wasm): support decoding data URL in Node < v16 Node < v16 do not provide a global `atob()` function for decoding base64 strings, and must use `Buffer.from()` instead. Furthermore, `Buffer.from(str, 'base64').toString()` is much faster than `atob()` in Node. Thus, prefer to use `Buffer.from()` if possible. --- packages/vite/src/node/plugins/wasm.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/vite/src/node/plugins/wasm.ts b/packages/vite/src/node/plugins/wasm.ts index 1f64434a5b9781..439a61abb16b3d 100644 --- a/packages/vite/src/node/plugins/wasm.ts +++ b/packages/vite/src/node/plugins/wasm.ts @@ -7,11 +7,21 @@ const wasmHelperId = '/__vite-wasm-helper' const wasmHelper = async (opts = {}, url: string) => { let result if (url.startsWith('data:')) { - // @ts-ignore - const binaryString = atob(url.replace(/^data:.*?base64,/, '')) - const bytes = new Uint8Array(binaryString.length) - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i) + const urlContent = url.replace(/^data:.*?base64,/, '') + let bytes + if (typeof Buffer === 'function' && typeof Buffer.from === 'function') { + bytes = Buffer.from(urlContent, 'base64') + } else if (typeof atob === 'function') { + // @ts-ignore + const binaryString = atob(urlContent) + bytes = new Uint8Array(binaryString.length) + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i) + } + } else { + throw new Error( + 'Failed to decode base64-encoded data URL, Buffer and atob are not supported' + ) } // @ts-ignore result = await WebAssembly.instantiate(bytes, opts)