Skip to content

Commit

Permalink
fix: support decoding data URL in Node < v16 (#3)
Browse files Browse the repository at this point in the history
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, we should use `Buffer.from()` whenever it is available.
  • Loading branch information
pastelmind authored Jun 29, 2022
1 parent 0c7c4a9 commit 21f71c2
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/wasm-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,18 @@ export const id = "/__vite-plugin-wasm-helper";
const wasmHelper = async (opts = {}, url: string) => {
let result: WebAssembly.WebAssemblyInstantiatedSource;
if (url.startsWith("data:")) {
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") {
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("Cannot decode base64-encoded data URL");
}
result = await WebAssembly.instantiate(bytes, opts);
} else {
Expand Down

0 comments on commit 21f71c2

Please sign in to comment.