-
Notifications
You must be signed in to change notification settings - Fork 3
/
worker.ts
88 lines (68 loc) · 2.4 KB
/
worker.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
import WASI from "@wasmer/wasi";
import wasiBindings from "@wasmer/wasi/lib/bindings/browser";
import { lowerI64Imports } from "@wasmer/wasm-transformer";
import { WorkerFS } from './fs';
declare var self: Worker;
const workerUrl = "worker.wasm"; //"wabench_app_wasi.wasm"; //
let iamWorker = self;
let instance: any = null;
const workerFs = new WorkerFS();
let wasi = new WASI({
preopenDirectories: {
"/": "/"
},
args: [],
env: {},
bindings: {
// @ts-ignore
...wasiBindings.default,
fs: workerFs.getFs()
}
});
const fetchAndTransformWasmBinary = async (url: string) => {
// Get the original Wasm binary
const fetchedOriginalWasmBinary = await fetch(url);
const originalWasmBinaryBuffer = await fetchedOriginalWasmBinary.arrayBuffer();
const originalWasmBinary = new Uint8Array(originalWasmBinaryBuffer);
// Initialize our wasm-transformer
// await wasmTransformerInit(wasmTransformerUrl);
// IMPORTANT: This URL points to wherever the wasm-transformer.wasm is hosted
// Transform the binary, by running the lower_i64_imports from the wasm-transformer
const transformedBinary = await lowerI64Imports(originalWasmBinary);
// Compile the transformed binary
const transformedWasmModule = await WebAssembly.compile(transformedBinary);
return transformedWasmModule;
};
const startWasiTask = async (file: string) => {
try {
// Fetch our Wasm File
const module = await fetchAndTransformWasmBinary(file);
console.log("Module transformed and compiled, starting...");
// Instantiate the WebAssembly file
instance = await WebAssembly.instantiate(module, {
wasi_snapshot_preview1: wasi.wasiImport
});
// Start the WebAssembly WASI instance!
wasi.start(instance);
console.log("worker has started");
// @ts-ignore
//workerFs.stdout.fd.write(Uint8Array.from([1,2,3]));
//stdin.push(Uint8Array.from([1,2,3,4,5,6]));
//console.log(instance.exports.same(124));
} catch (e) {
console.error(e);
console.error(e.stack);
}
};
workerFs.output.mapBinFn((buffer: Uint8Array) => {
console.log("Worker outgoing> " + buffer);
if (typeof iamWorker.postMessage === "function") {
iamWorker.postMessage(Array.from(buffer));
}
})
iamWorker.onmessage = function(event) {
console.log("Worker incoming> "+ event.data);
workerFs.stdin.push(event.data);
console.log(instance.exports.message_ready());
};
startWasiTask(workerUrl);