-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wasc.ts
321 lines (287 loc) · 10.4 KB
/
Wasc.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* @author Matteo Basso @https://github.com/mbasso
* @author hexxone / https://hexx.one
*
* @license
* Copyright (c) 2024 hexxone All rights reserved.
* Licensed under the GNU GENERAL PUBLIC LICENSE.
* See LICENSE file in the project root for full license information.
*
*/
import { Smallog } from '../Smallog';
import { WascInterface } from './WascInterface';
import { WascLoader } from './WascLoader';
import { WascUtil } from './WascUtil';
const LOGHEAD = '[WASC] ';
const NO_SUPP = '>>> WebAssembly failed! Initialization cannot continue. <<<';
import WascWorker from 'worker-loader!./Wasc.worker';
// const WascWorker = () => new Worker(new URL("./Wasc.worker.js", import.meta.url));
const wasmSupport = (() => {
try {
if (
typeof WebAssembly === 'object'
&& typeof WebAssembly.instantiate === 'function'
) {
const module = new WebAssembly.Module(
Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00)
);
return (
module instanceof WebAssembly.Module
&& new WebAssembly.Instance(module) instanceof WebAssembly.Instance
);
}
} catch (e) {
Smallog.error(`${NO_SUPP}\r\nReason: ${e}`, LOGHEAD);
}
return false;
})();
/**
* Initializes a new WebAssembly instance.
* @param {string} source compiled .wasm module path
* @param {number} memSize initial webassembly memory (default 4096)
* @param {boolean} shared shared mem?
* @param {Object} options passed to the module init
* @param {boolean} useWorker use worker or inline
* @returns {Promise<WascInterface>} the initialized context
* @public
*/
export function wascWorker(
source: string,
memSize = 4096,
shared = false,
options: any = {},
useWorker = true
): Promise<WascInterface> {
return new Promise((resolve, reject) => {
if (!wasmSupport) {
reject(NO_SUPP);
return;
}
// decide whether to use worker-threading or inline embedding.
const hasWrk = typeof Worker !== 'undefined';
if (useWorker && !hasWrk) {
Smallog.error(
'WebWorkers are not supported? Using inline loading as fallback...'
);
}
const loadWrk = useWorker && hasWrk;
Smallog.debug(
`Loading ${source} as ${
loadWrk ? 'worker' : 'inline'
} with data=${JSON.stringify(options)}`,
LOGHEAD
);
// initialize the actual module
const doLoad = loadWrk ? loadWorker : loadInline;
doLoad(source, memSize, shared, options)
.then((loaded) => {
resolve(loaded);
})
.catch((err) => {
// something went south?
Smallog.error(`init error: ${err}`, LOGHEAD);
reject(err);
});
});
}
/**
* @ignore
* Inline loads a compiled webassembly module.
* Basically the normal WebAssembly usage,
* just with api- and "run()"-compatibility
* @param {string} path compiled module path
* @param {number} memSize initial memory pages *(64KiB)
* @param {boolean} shared shared mem?
* @param {Object} options import Objects
* @returns {Promise<WascInterface>} module
* @public
*/
function loadInline(
path: string,
memSize: number,
shared = false,
options?: any
): Promise<WascInterface> {
return new Promise((resolve) => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/Planned_changes
const memory = new WebAssembly.Memory({
initial: memSize,
maximum: memSize,
shared
});
/**
* gather imports
* @public
*/
let myImports = {
env: {
memory,
logf(value) {
console.log(`F64: ${value}`);
},
logi(value) {
console.log(`U32: ${value}`);
}
}
};
const { getImportObject } = options;
if (getImportObject) {
myImports = Object.assign(myImports, getImportObject);
}
// get & make module
return WascUtil.myFetch(path)
.then((res) => {
return new WascLoader().instantiate(res, myImports);
})
.then((inst) => {
// eslint-disable-next-line no-trailing-spaces
/**
* Run a function inside the worker.
* @warning This is potentially dangerous due to eval!
* @param {string} func stringified function to eval inside worker context
* @param {Object} params Data to pass in
* @returns {Object} eval result
*/
const run = (func, ...params) => {
return new Promise((res_) => {
const fun_ = new Function(`return ${func}`)();
res_(
fun_({
module: inst.module,
instance: inst.instance,
exports: inst.exports,
params
})
);
});
};
// we done here
resolve({
shared: shared
? new WascLoader().postInstantiate({}, {
exports: {
memory
}
} as any)
: null,
exports: inst.exports,
run
});
});
});
}
/**
* @ignore
* Creates a Worker, then loads a compiled webassembly module inside,
* then creates a Promise-interface for all functions and additionally
* wraps a "run" function inside the worker.
* @param {string} source compiled module path
* @param {number} memSize initial memory pages
* @param {boolean} shared shared mem?
* @param {Object} options import Objects
* @returns {Promise<WascInterface>} module
* @public
*/
function loadWorker(
source: string,
memSize: number,
shared = false,
options?: any
): Promise<WascInterface> {
return new Promise((...reslv) => {
// create shared memory?
const memOpts: WebAssembly.MemoryDescriptor = {
initial: memSize,
maximum: memSize,
shared
};
// WRAP IN WORKER
let promCnt = 0;
const promises = {};
const worker = new WascWorker();
worker.onmessage = (e) => {
// console.log('main-message', e.data);
const { id, result, action, payload } = e.data;
if (action === WascUtil.ACTIONS.COMPILE_MODULE) {
// COMPILE MODULE & RESOLVE EXPORTS
if (result === 0) {
// SUCCESS
const { exports, sharedMemory } = payload;
promises[id][0]({
// module memory
sharedMemory,
shared: shared
? new WascLoader().postInstantiate({}, {
exports: {
memory: sharedMemory
}
} as any)
: null,
// wrap the returned context/thread exports into postMessage-promises
exports: exports.reduce((acc, exp) => {
return {
...acc,
[exp]: (...params) => {
return new Promise((...rest) => {
promises[++promCnt] = rest;
worker.postMessage(
{
id: promCnt,
action: WascUtil.ACTIONS
.CALL_FUNCTION_EXPORT,
payload: {
func: exp,
params
}
},
WascUtil.getTransferableParams(
params
)
);
});
}
};
}, {}),
// export context/thread run function
run: (func, ...params) => {
return new Promise((...rest) => {
promises[++promCnt] = rest;
worker.postMessage(
{
id: promCnt,
action: WascUtil.ACTIONS.RUN_FUNCTION,
payload: {
func: func.toString(),
params
}
},
WascUtil.getTransferableParams(params)
);
});
}
});
} else if (result === 1) {
// ERROR
promises[id][1](payload);
}
// CALL FUNCTION
} else if (
action === WascUtil.ACTIONS.CALL_FUNCTION_EXPORT
|| action === WascUtil.ACTIONS.RUN_FUNCTION
) {
promises[id][result](payload);
}
promises[id] = null;
};
promises[++promCnt] = reslv;
worker.postMessage({
id: promCnt,
action: WascUtil.ACTIONS.COMPILE_MODULE,
payload: {
source
},
getImportObject: options,
memOpts
});
});
}