Files: 8ced6c46cc8f744d128a65d00c117a79e68918b8 / wasmAgent.js
1817 bytesRaw
1 | module.exports = class Wasm { |
2 | /** |
3 | * The interface API is the api the exposed to interfaces. All queries about |
4 | * the enviroment and call to the kernel go through this API |
5 | */ |
6 | constructor (code) { |
7 | this._module = WebAssembly.Module(code) |
8 | } |
9 | /** |
10 | * Runs the core VM with a given environment and imports |
11 | */ |
12 | async run (message, kernel, imports) { |
13 | const responses = {} |
14 | /** |
15 | * Builds a import map with an array of given interfaces |
16 | */ |
17 | function buildImports (kernelApi, kernel, imports) { |
18 | const importMap = {} |
19 | for (const Import of imports) { |
20 | const response = responses[Import.name] = {} |
21 | const newIterface = new Import(kernelApi, message, response) |
22 | importMap[Import.name] = newIterface.exports |
23 | } |
24 | return importMap |
25 | } |
26 | |
27 | let instance |
28 | const interfaceApi = { |
29 | /** |
30 | * adds an aync operation to the operations queue |
31 | */ |
32 | pushOpsQueue: (promise, callbackIndex, intefaceCallback) => { |
33 | this._opsQueue = Promise.all([this._opsQueue, promise]).then(values => { |
34 | const result = intefaceCallback(values.pop()) |
35 | instance.exports.callback.get(callbackIndex)(result) |
36 | }) |
37 | }, |
38 | memory: () => { |
39 | return instance.exports.memory.buffer |
40 | }, |
41 | kernel: kernel |
42 | } |
43 | |
44 | const initializedImports = buildImports(interfaceApi, kernel, imports) |
45 | instance = WebAssembly.Instance(this._module, initializedImports) |
46 | |
47 | if (instance.exports.main) { |
48 | instance.exports.main() |
49 | } |
50 | await this.onDone() |
51 | return responses |
52 | } |
53 | |
54 | /** |
55 | * returns a promise that resolves when the wasm instance is done running |
56 | */ |
57 | async onDone () { |
58 | let prevOps |
59 | while (prevOps !== this._opsQueue) { |
60 | prevOps = this._opsQueue |
61 | await this._opsQueue |
62 | } |
63 | } |
64 | } |
65 |
Built with git-ssb-web