-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathloader.mjs
executable file
·62 lines (48 loc) · 1.42 KB
/
loader.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import fs from "fs"
import path from "path"
async function loadDependency(base, specifier, name) {
const dep = await import(new URL(specifier, base));
return dep[name];
}
function readFile(path) {
return fs.readFileSync(path, null);
}
export async function dynamicInstantiate(url) {
const buffer = readFile(new URL(url));
const module = new WebAssembly.Module(buffer);
/**
* generate importObject
*/
const importObject = {};
await Promise.all(WebAssembly.Module.imports(module).map(async ({ module: importURL, name }) => {
if (typeof importObject[importURL] === "undefined") {
importObject[importURL] = {};
}
importObject[importURL][name] = await loadDependency(url, importURL, name);
}));
/**
* instantiation
*/
const wasmInstance = new WebAssembly.Instance(module, importObject);
const wasmExports = WebAssembly.Module.exports(module).map(({ name }) => name);
return {
exports: wasmExports,
execute: exports => {
wasmExports.forEach(name => {
exports[name].set(wasmInstance.exports[name]);
});
}
};
}
const baseURL = new URL('file://');
baseURL.pathname = `${process.cwd()}/`;
export function resolve(specifier, base, defaultResolver) {
const ext = path.extname(specifier);
if (ext === ".wasm") {
return {
url: new URL(specifier, base || baseURL).href,
format: 'dynamic'
};
}
return defaultResolver(specifier, base);
}