-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
75 lines (61 loc) · 1.98 KB
/
index.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
const { writeFileSync, existsSync, mkdirSync } = require("fs");
const { join, basename } = require("path");
const loaderUtils = require("loader-utils");
module.exports = function(bin) {
this.addDependency(this.resourcePath);
const options = loaderUtils.getOptions(this) || {};
const publicPath =
typeof options.publicPath === "string"
? options.publicPath === "" || options.publicPath.endsWith("/")
? options.publicPath
: `${options.publicPath}/`
: typeof options.publicPath === "function"
? options.publicPath(this.resourcePath, this.rootContext)
: this._compilation.outputOptions.publicPath || "dist";
if (!existsSync(publicPath)) {
mkdirSync(publicPath);
}
const filename = basename(this.resourcePath);
const wasmPath = join(publicPath, filename);
writeFileSync(wasmPath, bin);
return `
const { WASI } = require("@wasmer/wasi");
const Wasmfs = require("@wasmer/wasmfs").default;
const fs = new Wasmfs;
const textDecoder = new TextDecoder("utf-8");
export async function then(cb) {
const env = {};
const oldWriteSync = fs.fs.writeSync;
fs.fs.writeSync = function (fd, buffer, ...rest) {
if (fd === 1) {
const str = textDecoder.decode(buffer);
console.log(str);
return buffer.length;
}
if (fd === 2) {
const str = textDecoder.decode(buffer);
console.error(str);
return buffer.length;
}
return oldWriteSync(fd, buffer, ...rest);
}
const wasi = new WASI({
args: ["${filename}"],
env,
bindings: {
...WASI.defaultBindings,
fs: fs.fs,
}
});
const imports = {
wasi_unstable: wasi.wasiImport,
env
};
const { instance } =
await WebAssembly.instantiateStreaming(fetch("${filename}"), imports);
wasi.start(instance);
cb(instance.exports);
}
`;
};
module.exports.raw = true;