@emnapi/wasi-threads 1.2.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,945 +1,918 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.wasiThreads = {}));
5
- })(this, (function (exports) {
6
- var _WebAssembly = typeof WebAssembly !== 'undefined'
7
- ? WebAssembly
8
- : typeof WXWebAssembly !== 'undefined'
9
- ? WXWebAssembly
1
+ //#region src/util.ts
2
+ const _WebAssembly = typeof WebAssembly !== 'undefined'
3
+ ? WebAssembly
4
+ : typeof WXWebAssembly !== 'undefined'
5
+ ? WXWebAssembly
6
+ : undefined;
7
+ const ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null &&
8
+ typeof process.versions === 'object' && process.versions !== null &&
9
+ typeof process.versions.node === 'string';
10
+ function getPostMessage(options) {
11
+ return typeof options?.postMessage === 'function'
12
+ ? options.postMessage
13
+ : typeof postMessage === 'function'
14
+ ? postMessage
10
15
  : undefined;
11
- var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null &&
12
- typeof process.versions === 'object' && process.versions !== null &&
13
- typeof process.versions.node === 'string';
14
- function getPostMessage(options) {
15
- return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function'
16
- ? options.postMessage
17
- : typeof postMessage === 'function'
18
- ? postMessage
19
- : undefined;
20
- }
21
- function serizeErrorToBuffer(sab, code, error) {
22
- var i32array = new Int32Array(sab);
23
- Atomics.store(i32array, 0, code);
24
- if (code > 1 && error) {
25
- var name_1 = error.name;
26
- var message = error.message;
27
- var stack = error.stack;
28
- var nameBuffer = new TextEncoder().encode(name_1);
29
- var messageBuffer = new TextEncoder().encode(message);
30
- var stackBuffer = new TextEncoder().encode(stack);
31
- Atomics.store(i32array, 1, nameBuffer.length);
32
- Atomics.store(i32array, 2, messageBuffer.length);
33
- Atomics.store(i32array, 3, stackBuffer.length);
34
- var buffer = new Uint8Array(sab);
35
- buffer.set(nameBuffer, 16);
36
- buffer.set(messageBuffer, 16 + nameBuffer.length);
37
- buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length);
38
- }
39
- }
40
- function deserizeErrorFromBuffer(sab) {
41
- var _a, _b;
42
- var i32array = new Int32Array(sab);
43
- var status = Atomics.load(i32array, 0);
44
- if (status <= 1) {
45
- return null;
46
- }
47
- var nameLength = Atomics.load(i32array, 1);
48
- var messageLength = Atomics.load(i32array, 2);
49
- var stackLength = Atomics.load(i32array, 3);
50
- var buffer = new Uint8Array(sab);
51
- var nameBuffer = buffer.slice(16, 16 + nameLength);
52
- var messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength);
53
- var stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength);
54
- var name = new TextDecoder().decode(nameBuffer);
55
- var message = new TextDecoder().decode(messageBuffer);
56
- var stack = new TextDecoder().decode(stackBuffer);
57
- var ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error);
58
- var error = new ErrorConstructor(message);
59
- Object.defineProperty(error, 'stack', {
60
- value: stack,
61
- writable: true,
62
- enumerable: false,
63
- configurable: true
64
- });
65
- return error;
16
+ }
17
+ function serizeErrorToBuffer(sab, code, error) {
18
+ const i32array = new Int32Array(sab);
19
+ Atomics.store(i32array, 0, code);
20
+ if (code > 1 && error) {
21
+ const name = error.name;
22
+ const message = error.message;
23
+ const stack = error.stack;
24
+ const nameBuffer = new TextEncoder().encode(name);
25
+ const messageBuffer = new TextEncoder().encode(message);
26
+ const stackBuffer = new TextEncoder().encode(stack);
27
+ Atomics.store(i32array, 1, nameBuffer.length);
28
+ Atomics.store(i32array, 2, messageBuffer.length);
29
+ Atomics.store(i32array, 3, stackBuffer.length);
30
+ const buffer = new Uint8Array(sab);
31
+ buffer.set(nameBuffer, 16);
32
+ buffer.set(messageBuffer, 16 + nameBuffer.length);
33
+ buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length);
66
34
  }
67
- /** @public */
68
- function isSharedArrayBuffer(value) {
69
- return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) ||
70
- (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'));
35
+ }
36
+ function deserizeErrorFromBuffer(sab) {
37
+ const i32array = new Int32Array(sab);
38
+ const status = Atomics.load(i32array, 0);
39
+ if (status <= 1) {
40
+ return null;
71
41
  }
72
- /** @public */
73
- function isTrapError(e) {
74
- try {
75
- return e instanceof _WebAssembly.RuntimeError;
42
+ const nameLength = Atomics.load(i32array, 1);
43
+ const messageLength = Atomics.load(i32array, 2);
44
+ const stackLength = Atomics.load(i32array, 3);
45
+ const buffer = new Uint8Array(sab);
46
+ const nameBuffer = buffer.slice(16, 16 + nameLength);
47
+ const messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength);
48
+ const stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength);
49
+ const name = new TextDecoder().decode(nameBuffer);
50
+ const message = new TextDecoder().decode(messageBuffer);
51
+ const stack = new TextDecoder().decode(stackBuffer);
52
+ const ErrorConstructor = globalThis[name] ?? (name === 'RuntimeError' ? (_WebAssembly.RuntimeError ?? Error) : Error);
53
+ const error = new ErrorConstructor(message);
54
+ Object.defineProperty(error, 'stack', {
55
+ value: stack,
56
+ writable: true,
57
+ enumerable: false,
58
+ configurable: true
59
+ });
60
+ return error;
61
+ }
62
+ function isSharedArrayBuffer(value) {
63
+ return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) ||
64
+ (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'));
65
+ }
66
+ function isTrapError(e) {
67
+ try {
68
+ return e instanceof _WebAssembly.RuntimeError;
69
+ }
70
+ catch (_) {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ //#endregion src/util.ts
76
+
77
+ //#region src/command.ts
78
+ function createMessage(type, payload) {
79
+ return {
80
+ __emnapi__: {
81
+ type,
82
+ payload
76
83
  }
77
- catch (_) {
78
- return false;
84
+ };
85
+ }
86
+
87
+ //#endregion src/command.ts
88
+
89
+ //#region src/thread-manager.ts
90
+ const WASI_THREADS_MAX_TID = 0x1FFFFFFF;
91
+ function checkSharedWasmMemory(wasmMemory) {
92
+ if (wasmMemory) {
93
+ if (!isSharedArrayBuffer(wasmMemory.buffer)) {
94
+ throw new Error('Multithread features require shared wasm memory. ' +
95
+ 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' +
96
+ 'then create WebAssembly.Memory with `shared: true` option');
79
97
  }
80
98
  }
81
-
82
- function createMessage(type, payload) {
83
- return {
84
- __emnapi__: {
85
- type: type,
86
- payload: payload
87
- }
88
- };
99
+ else {
100
+ if (typeof SharedArrayBuffer === 'undefined') {
101
+ throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!');
102
+ }
89
103
  }
90
-
91
- var WASI_THREADS_MAX_TID = 0x1FFFFFFF;
92
- function checkSharedWasmMemory(wasmMemory) {
93
- if (wasmMemory) {
94
- if (!isSharedArrayBuffer(wasmMemory.buffer)) {
95
- throw new Error('Multithread features require shared wasm memory. ' +
96
- 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' +
97
- 'then create WebAssembly.Memory with `shared: true` option');
98
- }
104
+ }
105
+ function getReuseWorker(value) {
106
+ if (typeof value === 'boolean') {
107
+ return value ? { size: 0, strict: false } : false;
108
+ }
109
+ if (typeof value === 'number') {
110
+ if (!(value >= 0)) {
111
+ throw new RangeError('reuseWorker: size must be a non-negative integer');
112
+ }
113
+ return { size: value, strict: false };
114
+ }
115
+ if (!value) {
116
+ return false;
117
+ }
118
+ const size = Number(value.size) || 0;
119
+ const strict = Boolean(value.strict);
120
+ if (!(size > 0) && strict) {
121
+ throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true');
122
+ }
123
+ return { size, strict };
124
+ }
125
+ let nextWorkerID = 0;
126
+ class ThreadManager {
127
+ get nextWorkerID() { return nextWorkerID; }
128
+ constructor(options) {
129
+ this.unusedWorkers = [];
130
+ this.pthreads = Object.create(null);
131
+ this.wasmModule = null;
132
+ this.wasmMemory = null;
133
+ this.messageEvents = new WeakMap();
134
+ if (!options) {
135
+ throw new TypeError('ThreadManager(): options is not provided');
136
+ }
137
+ if ('childThread' in options) {
138
+ this._childThread = Boolean(options.childThread);
99
139
  }
100
140
  else {
101
- if (typeof SharedArrayBuffer === 'undefined') {
102
- throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!');
103
- }
141
+ this._childThread = false;
142
+ }
143
+ if (this._childThread) {
144
+ this._onCreateWorker = undefined;
145
+ this._reuseWorker = false;
146
+ this._beforeLoad = undefined;
104
147
  }
148
+ else {
149
+ this._onCreateWorker = options.onCreateWorker;
150
+ this._reuseWorker = getReuseWorker(options.reuseWorker);
151
+ this._beforeLoad = options.beforeLoad;
152
+ }
153
+ this.printErr = options.printErr ?? console.error.bind(console);
154
+ this.threadSpawn = options.threadSpawn;
105
155
  }
106
- function getReuseWorker(value) {
107
- var _a;
108
- if (typeof value === 'boolean') {
109
- return value ? { size: 0, strict: false } : false;
156
+ init() {
157
+ if (!this._childThread) {
158
+ this.initMainThread();
110
159
  }
111
- if (typeof value === 'number') {
112
- if (!(value >= 0)) {
113
- throw new RangeError('reuseWorker: size must be a non-negative integer');
114
- }
115
- return { size: value, strict: false };
116
- }
117
- if (!value) {
118
- return false;
119
- }
120
- var size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0;
121
- var strict = Boolean(value.strict);
122
- if (!(size > 0) && strict) {
123
- throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true');
124
- }
125
- return { size: size, strict: strict };
126
- }
127
- var nextWorkerID = 0;
128
- /** @public */
129
- var ThreadManager = /*#__PURE__*/ (function () {
130
- function ThreadManager(options) {
131
- var _a;
132
- this.unusedWorkers = [];
133
- this.pthreads = Object.create(null);
134
- this.wasmModule = null;
135
- this.wasmMemory = null;
136
- this.messageEvents = new WeakMap();
137
- if (!options) {
138
- throw new TypeError('ThreadManager(): options is not provided');
139
- }
140
- if ('childThread' in options) {
141
- this._childThread = Boolean(options.childThread);
142
- }
143
- else {
144
- this._childThread = false;
145
- }
146
- if (this._childThread) {
147
- this._onCreateWorker = undefined;
148
- this._reuseWorker = false;
149
- this._beforeLoad = undefined;
150
- }
151
- else {
152
- this._onCreateWorker = options.onCreateWorker;
153
- this._reuseWorker = getReuseWorker(options.reuseWorker);
154
- this._beforeLoad = options.beforeLoad;
160
+ }
161
+ initMainThread() {
162
+ this.preparePool();
163
+ }
164
+ preparePool() {
165
+ if (this._reuseWorker) {
166
+ if (this._reuseWorker.size) {
167
+ let pthreadPoolSize = this._reuseWorker.size;
168
+ while (pthreadPoolSize--) {
169
+ const worker = this.allocateUnusedWorker();
170
+ if (ENVIRONMENT_IS_NODE) {
171
+ worker.once('message', () => { });
172
+ worker.unref();
173
+ }
174
+ }
155
175
  }
156
- this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console);
157
- this.threadSpawn = options.threadSpawn;
158
176
  }
159
- Object.defineProperty(ThreadManager.prototype, "nextWorkerID", {
160
- get: function () { return nextWorkerID; },
161
- enumerable: false,
162
- configurable: true
177
+ }
178
+ shouldPreloadWorkers() {
179
+ return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0;
180
+ }
181
+ loadWasmModuleToAllWorkers() {
182
+ const promises = Array(this.unusedWorkers.length);
183
+ for (let i = 0; i < this.unusedWorkers.length; ++i) {
184
+ const worker = this.unusedWorkers[i];
185
+ if (ENVIRONMENT_IS_NODE)
186
+ worker.ref();
187
+ promises[i] = this.loadWasmModuleToWorker(worker).then((w) => {
188
+ if (ENVIRONMENT_IS_NODE)
189
+ worker.unref();
190
+ return w;
191
+ }, (e) => {
192
+ if (ENVIRONMENT_IS_NODE)
193
+ worker.unref();
194
+ throw e;
195
+ });
196
+ }
197
+ return Promise.all(promises).catch((err) => {
198
+ this.terminateAllThreads();
199
+ throw err;
163
200
  });
164
- ThreadManager.prototype.init = function () {
165
- if (!this._childThread) {
166
- this.initMainThread();
167
- }
168
- };
169
- ThreadManager.prototype.initMainThread = function () {
170
- this.preparePool();
171
- };
172
- ThreadManager.prototype.preparePool = function () {
173
- if (this._reuseWorker) {
174
- if (this._reuseWorker.size) {
175
- var pthreadPoolSize = this._reuseWorker.size;
176
- while (pthreadPoolSize--) {
177
- var worker = this.allocateUnusedWorker();
178
- if (ENVIRONMENT_IS_NODE) {
179
- // https://github.com/nodejs/node/issues/53036
180
- worker.once('message', function () { });
181
- worker.unref();
201
+ }
202
+ preloadWorkers() {
203
+ if (this.shouldPreloadWorkers()) {
204
+ return this.loadWasmModuleToAllWorkers();
205
+ }
206
+ return Promise.resolve([]);
207
+ }
208
+ setup(wasmModule, wasmMemory) {
209
+ this.wasmModule = wasmModule;
210
+ this.wasmMemory = wasmMemory;
211
+ }
212
+ markId(worker) {
213
+ if (worker.__emnapi_tid)
214
+ return worker.__emnapi_tid;
215
+ const tid = nextWorkerID + 43;
216
+ nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42);
217
+ this.pthreads[tid] = worker;
218
+ worker.__emnapi_tid = tid;
219
+ return tid;
220
+ }
221
+ returnWorkerToPool(worker) {
222
+ var tid = worker.__emnapi_tid;
223
+ if (tid !== undefined) {
224
+ delete this.pthreads[tid];
225
+ }
226
+ this.unusedWorkers.push(worker);
227
+ delete worker.__emnapi_tid;
228
+ if (ENVIRONMENT_IS_NODE) {
229
+ worker.unref();
230
+ }
231
+ }
232
+ loadWasmModuleToWorker(worker, sab) {
233
+ if (worker.whenLoaded)
234
+ return worker.whenLoaded;
235
+ const err = this.printErr;
236
+ const beforeLoad = this._beforeLoad;
237
+ const _this = this;
238
+ worker.whenLoaded = new Promise((resolve, reject) => {
239
+ const handleError = function (e) {
240
+ let message = 'worker sent an error!';
241
+ if (worker.__emnapi_tid !== undefined) {
242
+ message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!';
243
+ }
244
+ if ('message' in e) {
245
+ err(message + ' ' + e.message);
246
+ if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) {
247
+ try {
248
+ _this.terminateAllThreads();
182
249
  }
250
+ catch (_) { }
183
251
  }
184
252
  }
185
- }
186
- };
187
- ThreadManager.prototype.shouldPreloadWorkers = function () {
188
- return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0;
189
- };
190
- ThreadManager.prototype.loadWasmModuleToAllWorkers = function () {
191
- var _this_1 = this;
192
- var promises = Array(this.unusedWorkers.length);
193
- var _loop_1 = function (i) {
194
- var worker = this_1.unusedWorkers[i];
195
- if (ENVIRONMENT_IS_NODE)
196
- worker.ref();
197
- promises[i] = this_1.loadWasmModuleToWorker(worker).then(function (w) {
198
- if (ENVIRONMENT_IS_NODE)
199
- worker.unref();
200
- return w;
201
- }, function (e) {
202
- if (ENVIRONMENT_IS_NODE)
203
- worker.unref();
204
- throw e;
205
- });
253
+ else {
254
+ err(message);
255
+ }
256
+ reject(e);
257
+ throw e;
206
258
  };
207
- var this_1 = this;
208
- for (var i = 0; i < this.unusedWorkers.length; ++i) {
209
- _loop_1(i);
210
- }
211
- return Promise.all(promises).catch(function (err) {
212
- _this_1.terminateAllThreads();
213
- throw err;
214
- });
215
- };
216
- ThreadManager.prototype.preloadWorkers = function () {
217
- if (this.shouldPreloadWorkers()) {
218
- return this.loadWasmModuleToAllWorkers();
219
- }
220
- return Promise.resolve([]);
221
- };
222
- ThreadManager.prototype.setup = function (wasmModule, wasmMemory) {
223
- this.wasmModule = wasmModule;
224
- this.wasmMemory = wasmMemory;
225
- };
226
- ThreadManager.prototype.markId = function (worker) {
227
- if (worker.__emnapi_tid)
228
- return worker.__emnapi_tid;
229
- var tid = nextWorkerID + 43;
230
- nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42);
231
- this.pthreads[tid] = worker;
232
- worker.__emnapi_tid = tid;
233
- return tid;
234
- };
235
- ThreadManager.prototype.returnWorkerToPool = function (worker) {
236
- var tid = worker.__emnapi_tid;
237
- if (tid !== undefined) {
238
- delete this.pthreads[tid];
239
- }
240
- this.unusedWorkers.push(worker);
241
- delete worker.__emnapi_tid;
242
- if (ENVIRONMENT_IS_NODE) {
243
- worker.unref();
244
- }
245
- };
246
- ThreadManager.prototype.loadWasmModuleToWorker = function (worker, sab) {
247
- var _this_1 = this;
248
- if (worker.whenLoaded)
249
- return worker.whenLoaded;
250
- var err = this.printErr;
251
- var beforeLoad = this._beforeLoad;
252
- // eslint-disable-next-line @typescript-eslint/no-this-alias
253
- var _this = this;
254
- worker.whenLoaded = new Promise(function (resolve, reject) {
255
- var handleError = function (e) {
256
- var message = 'worker sent an error!';
257
- if (worker.__emnapi_tid !== undefined) {
258
- message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!';
259
+ const handleMessage = (data) => {
260
+ if (data.__emnapi__) {
261
+ const type = data.__emnapi__.type;
262
+ const payload = data.__emnapi__.payload;
263
+ if (type === 'loaded') {
264
+ worker.loaded = true;
265
+ if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) {
266
+ worker.unref();
267
+ }
268
+ resolve(worker);
259
269
  }
260
- if ('message' in e) {
261
- err(message + ' ' + e.message);
262
- if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) {
263
- try {
264
- _this.terminateAllThreads();
265
- }
266
- catch (_) { }
270
+ else if (type === 'cleanup-thread') {
271
+ if (payload.tid in this.pthreads) {
272
+ this.cleanThread(worker, payload.tid);
267
273
  }
268
274
  }
269
- else {
270
- err(message);
275
+ else if (type === 'spawn-thread') {
276
+ this.threadSpawn(payload.startArg, payload.errorOrTid);
271
277
  }
272
- reject(e);
273
- throw e;
274
- };
275
- var handleMessage = function (data) {
276
- if (data.__emnapi__) {
277
- var type = data.__emnapi__.type;
278
- var payload = data.__emnapi__.payload;
279
- if (type === 'loaded') {
280
- worker.loaded = true;
281
- if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) {
282
- worker.unref();
283
- }
284
- resolve(worker);
285
- // if (payload.err) {
286
- // err('failed to load in child thread: ' + (payload.err.message || payload.err))
287
- // }
288
- }
289
- else if (type === 'cleanup-thread') {
290
- if (payload.tid in _this_1.pthreads) {
291
- _this_1.cleanThread(worker, payload.tid);
292
- }
293
- }
294
- else if (type === 'spawn-thread') {
295
- _this_1.threadSpawn(payload.startArg, payload.errorOrTid);
296
- }
297
- else if (type === 'terminate-all-threads') {
298
- _this_1.terminateAllThreads();
299
- }
278
+ else if (type === 'terminate-all-threads') {
279
+ this.terminateAllThreads();
300
280
  }
301
- };
302
- worker.onmessage = function (e) {
303
- handleMessage(e.data);
304
- _this_1.fireMessageEvent(worker, e);
305
- };
306
- worker.onerror = handleError;
307
- if (ENVIRONMENT_IS_NODE) {
308
- worker.on('message', function (data) {
309
- var _a, _b;
310
- (_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, {
311
- data: data
312
- });
313
- });
314
- worker.on('error', function (e) {
315
- var _a, _b;
316
- (_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e);
317
- });
318
- worker.on('detachedExit', function () { });
319
- }
320
- if (typeof beforeLoad === 'function') {
321
- beforeLoad(worker);
322
281
  }
323
- try {
324
- worker.postMessage(createMessage('load', {
325
- wasmModule: _this_1.wasmModule,
326
- wasmMemory: _this_1.wasmMemory,
327
- sab: sab
328
- }));
329
- }
330
- catch (err) {
331
- checkSharedWasmMemory(_this_1.wasmMemory);
332
- throw err;
333
- }
334
- });
335
- return worker.whenLoaded;
336
- };
337
- ThreadManager.prototype.allocateUnusedWorker = function () {
338
- var _onCreateWorker = this._onCreateWorker;
339
- if (typeof _onCreateWorker !== 'function') {
340
- throw new TypeError('`options.onCreateWorker` is not provided');
282
+ };
283
+ worker.onmessage = (e) => {
284
+ handleMessage(e.data);
285
+ this.fireMessageEvent(worker, e);
286
+ };
287
+ worker.onerror = handleError;
288
+ if (ENVIRONMENT_IS_NODE) {
289
+ worker.on('message', function (data) {
290
+ worker.onmessage?.({
291
+ data
292
+ });
293
+ });
294
+ worker.on('error', function (e) {
295
+ worker.onerror?.(e);
296
+ });
297
+ worker.on('detachedExit', function () { });
341
298
  }
342
- var worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' });
343
- this.unusedWorkers.push(worker);
344
- return worker;
345
- };
346
- ThreadManager.prototype.getNewWorker = function (sab) {
347
- if (this._reuseWorker) {
348
- if (this.unusedWorkers.length === 0) {
349
- if (this._reuseWorker.strict) {
350
- if (!ENVIRONMENT_IS_NODE) {
351
- var err = this.printErr;
352
- err('Tried to spawn a new thread, but the thread pool is exhausted.\n' +
353
- 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.');
354
- return;
355
- }
299
+ if (typeof beforeLoad === 'function') {
300
+ beforeLoad(worker);
301
+ }
302
+ try {
303
+ worker.postMessage(createMessage('load', {
304
+ wasmModule: this.wasmModule,
305
+ wasmMemory: this.wasmMemory,
306
+ sab
307
+ }));
308
+ }
309
+ catch (err) {
310
+ checkSharedWasmMemory(this.wasmMemory);
311
+ throw err;
312
+ }
313
+ });
314
+ return worker.whenLoaded;
315
+ }
316
+ allocateUnusedWorker() {
317
+ const _onCreateWorker = this._onCreateWorker;
318
+ if (typeof _onCreateWorker !== 'function') {
319
+ throw new TypeError('`options.onCreateWorker` is not provided');
320
+ }
321
+ const worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' });
322
+ this.unusedWorkers.push(worker);
323
+ return worker;
324
+ }
325
+ getNewWorker(sab) {
326
+ if (this._reuseWorker) {
327
+ if (this.unusedWorkers.length === 0) {
328
+ if (this._reuseWorker.strict) {
329
+ if (!ENVIRONMENT_IS_NODE) {
330
+ const err = this.printErr;
331
+ err('Tried to spawn a new thread, but the thread pool is exhausted.\n' +
332
+ 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.');
333
+ return;
356
334
  }
357
- var worker_1 = this.allocateUnusedWorker();
358
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
359
- this.loadWasmModuleToWorker(worker_1, sab);
360
335
  }
361
- return this.unusedWorkers.pop();
336
+ const worker = this.allocateUnusedWorker();
337
+ this.loadWasmModuleToWorker(worker, sab);
362
338
  }
363
- var worker = this.allocateUnusedWorker();
364
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
365
- this.loadWasmModuleToWorker(worker, sab);
366
339
  return this.unusedWorkers.pop();
367
- };
368
- ThreadManager.prototype.cleanThread = function (worker, tid, force) {
369
- if (!force && this._reuseWorker) {
370
- this.returnWorkerToPool(worker);
371
- }
372
- else {
373
- delete this.pthreads[tid];
374
- this.terminateWorker(worker);
375
- delete worker.__emnapi_tid;
340
+ }
341
+ const worker = this.allocateUnusedWorker();
342
+ this.loadWasmModuleToWorker(worker, sab);
343
+ return this.unusedWorkers.pop();
344
+ }
345
+ cleanThread(worker, tid, force) {
346
+ if (!force && this._reuseWorker) {
347
+ this.returnWorkerToPool(worker);
348
+ }
349
+ else {
350
+ delete this.pthreads[tid];
351
+ this.terminateWorker(worker);
352
+ delete worker.__emnapi_tid;
353
+ }
354
+ }
355
+ terminateWorker(worker) {
356
+ const tid = worker.__emnapi_tid;
357
+ worker.terminate();
358
+ this.messageEvents.get(worker)?.clear();
359
+ this.messageEvents.delete(worker);
360
+ worker.onmessage = (e) => {
361
+ if (e.data.__emnapi__) {
362
+ const err = this.printErr;
363
+ err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid);
376
364
  }
377
365
  };
378
- ThreadManager.prototype.terminateWorker = function (worker) {
379
- var _this_1 = this;
380
- var _a;
381
- var tid = worker.__emnapi_tid;
382
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
383
- worker.terminate();
384
- (_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear();
385
- this.messageEvents.delete(worker);
386
- worker.onmessage = function (e) {
387
- if (e.data.__emnapi__) {
388
- var err = _this_1.printErr;
389
- err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid);
390
- }
391
- };
366
+ }
367
+ terminateAllThreads() {
368
+ const runningWorkers = Object.values(this.pthreads);
369
+ for (let i = 0; i < runningWorkers.length; ++i) {
370
+ this.terminateWorker(runningWorkers[i]);
371
+ }
372
+ for (let i = 0; i < this.unusedWorkers.length; ++i) {
373
+ this.terminateWorker(this.unusedWorkers[i]);
374
+ }
375
+ this.unusedWorkers = [];
376
+ this.pthreads = Object.create(null);
377
+ this.preparePool();
378
+ }
379
+ addMessageEventListener(worker, onMessage) {
380
+ let listeners = this.messageEvents.get(worker);
381
+ if (!listeners) {
382
+ listeners = new Set();
383
+ this.messageEvents.set(worker, listeners);
384
+ }
385
+ listeners.add(onMessage);
386
+ return () => {
387
+ listeners?.delete(onMessage);
392
388
  };
393
- ThreadManager.prototype.terminateAllThreads = function () {
394
- var runningWorkers = Object.values(this.pthreads);
395
- for (var i = 0; i < runningWorkers.length; ++i) {
396
- this.terminateWorker(runningWorkers[i]);
397
- }
398
- for (var i = 0; i < this.unusedWorkers.length; ++i) {
399
- this.terminateWorker(this.unusedWorkers[i]);
389
+ }
390
+ fireMessageEvent(worker, e) {
391
+ const listeners = this.messageEvents.get(worker);
392
+ if (!listeners)
393
+ return;
394
+ const err = this.printErr;
395
+ listeners.forEach((listener) => {
396
+ try {
397
+ listener(e);
400
398
  }
401
- this.unusedWorkers = [];
402
- this.pthreads = Object.create(null);
403
- this.preparePool();
404
- };
405
- ThreadManager.prototype.addMessageEventListener = function (worker, onMessage) {
406
- var listeners = this.messageEvents.get(worker);
407
- if (!listeners) {
408
- listeners = new Set();
409
- this.messageEvents.set(worker, listeners);
399
+ catch (e) {
400
+ err(e.stack);
410
401
  }
411
- listeners.add(onMessage);
412
- return function () {
413
- listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage);
414
- };
415
- };
416
- ThreadManager.prototype.fireMessageEvent = function (worker, e) {
417
- var listeners = this.messageEvents.get(worker);
418
- if (!listeners)
419
- return;
420
- var err = this.printErr;
421
- listeners.forEach(function (listener) {
422
- try {
423
- listener(e);
424
- }
425
- catch (e) {
426
- err(e.stack);
427
- }
428
- });
429
- };
430
- return ThreadManager;
431
- }());
402
+ });
403
+ }
404
+ }
405
+
406
+ //#endregion src/thread-manager.ts
432
407
 
433
- var kIsProxy = Symbol('kIsProxy');
434
- /** @public */
435
- function createInstanceProxy(instance, memory) {
436
- if (instance[kIsProxy])
437
- return instance;
438
- // https://github.com/nodejs/help/issues/4102
439
- var originalExports = instance.exports;
440
- var createHandler = function (target) {
441
- var handlers = [
442
- 'apply',
443
- 'construct',
444
- 'defineProperty',
445
- 'deleteProperty',
446
- 'get',
447
- 'getOwnPropertyDescriptor',
448
- 'getPrototypeOf',
449
- 'has',
450
- 'isExtensible',
451
- 'ownKeys',
452
- 'preventExtensions',
453
- 'set',
454
- 'setPrototypeOf'
455
- ];
456
- var handler = {};
457
- var _loop_1 = function (i) {
458
- var name_1 = handlers[i];
459
- handler[name_1] = function () {
460
- var args = Array.prototype.slice.call(arguments, 1);
461
- args.unshift(target);
462
- return Reflect[name_1].apply(Reflect, args);
463
- };
408
+ //#region src/proxy.ts
409
+ const kIsProxy = Symbol('kIsProxy');
410
+ function createInstanceProxy(instance, memory) {
411
+ if (instance[kIsProxy])
412
+ return instance;
413
+ const originalExports = instance.exports;
414
+ const createHandler = function (target) {
415
+ const handlers = [
416
+ 'apply',
417
+ 'construct',
418
+ 'defineProperty',
419
+ 'deleteProperty',
420
+ 'get',
421
+ 'getOwnPropertyDescriptor',
422
+ 'getPrototypeOf',
423
+ 'has',
424
+ 'isExtensible',
425
+ 'ownKeys',
426
+ 'preventExtensions',
427
+ 'set',
428
+ 'setPrototypeOf'
429
+ ];
430
+ const handler = {};
431
+ for (let i = 0; i < handlers.length; i++) {
432
+ const name = handlers[i];
433
+ handler[name] = function () {
434
+ const args = Array.prototype.slice.call(arguments, 1);
435
+ args.unshift(target);
436
+ return Reflect[name].apply(Reflect, args);
464
437
  };
465
- for (var i = 0; i < handlers.length; i++) {
466
- _loop_1(i);
467
- }
468
- return handler;
469
- };
470
- var handler = createHandler(originalExports);
471
- var _initialize = function () { };
472
- var _start = function () { return 0; };
473
- handler.get = function (_target, p, receiver) {
474
- var _a;
475
- if (p === 'memory') {
476
- return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver);
477
- }
478
- if (p === '_initialize') {
479
- return p in originalExports ? _initialize : undefined;
480
- }
481
- if (p === '_start') {
482
- return p in originalExports ? _start : undefined;
483
- }
484
- return Reflect.get(originalExports, p, receiver);
485
- };
486
- handler.has = function (_target, p) {
487
- if (p === 'memory')
438
+ }
439
+ return handler;
440
+ };
441
+ const handler = createHandler(originalExports);
442
+ const _initialize = () => { };
443
+ const _start = () => 0;
444
+ handler.get = function (_target, p, receiver) {
445
+ if (p === 'memory') {
446
+ return (typeof memory === 'function' ? memory() : memory) ?? Reflect.get(originalExports, p, receiver);
447
+ }
448
+ if (p === '_initialize') {
449
+ return p in originalExports ? _initialize : undefined;
450
+ }
451
+ if (p === '_start') {
452
+ return p in originalExports ? _start : undefined;
453
+ }
454
+ return Reflect.get(originalExports, p, receiver);
455
+ };
456
+ handler.has = function (_target, p) {
457
+ if (p === 'memory')
458
+ return true;
459
+ return Reflect.has(originalExports, p);
460
+ };
461
+ const exportsProxy = new Proxy(Object.create(null), handler);
462
+ return new Proxy(instance, {
463
+ get(target, p, receiver) {
464
+ if (p === 'exports') {
465
+ return exportsProxy;
466
+ }
467
+ if (p === kIsProxy) {
488
468
  return true;
489
- return Reflect.has(originalExports, p);
490
- };
491
- var exportsProxy = new Proxy(Object.create(null), handler);
492
- return new Proxy(instance, {
493
- get: function (target, p, receiver) {
494
- if (p === 'exports') {
495
- return exportsProxy;
496
- }
497
- if (p === kIsProxy) {
498
- return true;
499
- }
500
- return Reflect.get(target, p, receiver);
501
469
  }
502
- });
503
- }
470
+ return Reflect.get(target, p, receiver);
471
+ }
472
+ });
473
+ }
504
474
 
505
- var patchedWasiInstances = new WeakMap();
506
- /** @public */
507
- var WASIThreads = /*#__PURE__*/ (function () {
508
- function WASIThreads(options) {
509
- var _this_1 = this;
510
- if (!options) {
511
- throw new TypeError('WASIThreads(): options is not provided');
475
+ //#endregion src/proxy.ts
476
+
477
+ //#region src/wasi-threads.ts
478
+ const patchedWasiInstances = new WeakMap();
479
+ const THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2;
480
+ const sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function'
481
+ ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get
482
+ : undefined;
483
+ function isConclusivelySharedArrayBuffer(buffer) {
484
+ if (sharedArrayBufferByteLength === undefined)
485
+ return false;
486
+ try {
487
+ sharedArrayBufferByteLength.call(buffer);
488
+ return true;
489
+ }
490
+ catch (_) {
491
+ return false;
492
+ }
493
+ }
494
+ function getThreadSpawnResultView(memory, address, wasm64) {
495
+ const offset = typeof address === 'bigint' ? Number(address) : address >>> 0;
496
+ let buffer = memory.buffer;
497
+ if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength &&
498
+ isConclusivelySharedArrayBuffer(buffer)) {
499
+ if (wasm64) {
500
+ memory.grow(BigInt(0));
501
+ }
502
+ else {
503
+ memory.grow(0);
504
+ }
505
+ buffer = memory.buffer;
506
+ }
507
+ return new Int32Array(buffer, offset, 2);
508
+ }
509
+ class WASIThreads {
510
+ constructor(options) {
511
+ if (!options) {
512
+ throw new TypeError('WASIThreads(): options is not provided');
513
+ }
514
+ if (!options.wasi) {
515
+ throw new TypeError('WASIThreads(): options.wasi is not provided');
516
+ }
517
+ patchedWasiInstances.set(this, new WeakSet());
518
+ const wasi = options.wasi;
519
+ patchWasiInstance(this, wasi);
520
+ this.wasi = wasi;
521
+ if ('childThread' in options) {
522
+ this.childThread = Boolean(options.childThread);
523
+ }
524
+ else {
525
+ this.childThread = false;
526
+ }
527
+ this.PThread = undefined;
528
+ if ('threadManager' in options) {
529
+ if (typeof options.threadManager === 'function') {
530
+ this.PThread = options.threadManager();
512
531
  }
513
- if (!options.wasi) {
514
- throw new TypeError('WASIThreads(): options.wasi is not provided');
532
+ else {
533
+ this.PThread = options.threadManager;
515
534
  }
516
- patchedWasiInstances.set(this, new WeakSet());
517
- var wasi = options.wasi;
518
- patchWasiInstance(this, wasi);
519
- this.wasi = wasi;
520
- if ('childThread' in options) {
521
- this.childThread = Boolean(options.childThread);
535
+ }
536
+ else {
537
+ if (!this.childThread) {
538
+ this.PThread = new ThreadManager(options);
539
+ this.PThread.init();
522
540
  }
523
- else {
524
- this.childThread = false;
541
+ }
542
+ let waitThreadStart = false;
543
+ if ('waitThreadStart' in options) {
544
+ waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart);
545
+ }
546
+ const postMessage = getPostMessage(options);
547
+ if (this.childThread && typeof postMessage !== 'function') {
548
+ throw new TypeError('options.postMessage is not a function');
549
+ }
550
+ this.postMessage = postMessage;
551
+ const wasm64 = Boolean(options.wasm64);
552
+ const threadSpawn = (startArg, errorOrTid) => {
553
+ const EAGAIN = 6;
554
+ const isNewABI = errorOrTid !== undefined;
555
+ try {
556
+ checkSharedWasmMemory(this.wasmMemory);
525
557
  }
526
- this.PThread = undefined;
527
- if ('threadManager' in options) {
528
- if (typeof options.threadManager === 'function') {
529
- this.PThread = options.threadManager();
558
+ catch (err) {
559
+ this.PThread?.printErr(err.stack);
560
+ if (isNewABI) {
561
+ const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64);
562
+ Atomics.store(struct, 0, 1);
563
+ Atomics.store(struct, 1, EAGAIN);
564
+ Atomics.notify(struct, 1);
565
+ return 1;
530
566
  }
531
567
  else {
532
- this.PThread = options.threadManager;
568
+ return -EAGAIN;
533
569
  }
534
570
  }
535
- else {
536
- if (!this.childThread) {
537
- this.PThread = new ThreadManager(options);
538
- this.PThread.init();
571
+ if (!isNewABI) {
572
+ const malloc = this.wasmInstance.exports.malloc;
573
+ errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0);
574
+ if (!errorOrTid) {
575
+ return -48;
539
576
  }
540
577
  }
541
- var waitThreadStart = false;
542
- if ('waitThreadStart' in options) {
543
- waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart);
578
+ const _free = this.wasmInstance.exports.free;
579
+ const free = wasm64 ? (ptr) => { _free(BigInt(ptr)); } : _free;
580
+ const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64);
581
+ Atomics.store(struct, 0, 0);
582
+ Atomics.store(struct, 1, 0);
583
+ if (this.childThread) {
584
+ postMessage(createMessage('spawn-thread', {
585
+ startArg,
586
+ errorOrTid: errorOrTid
587
+ }));
588
+ Atomics.wait(struct, 1, 0);
589
+ const isError = Atomics.load(struct, 0);
590
+ const result = Atomics.load(struct, 1);
591
+ if (isNewABI) {
592
+ return isError;
593
+ }
594
+ free(errorOrTid);
595
+ return isError ? -result : result;
544
596
  }
545
- var postMessage = getPostMessage(options);
546
- if (this.childThread && typeof postMessage !== 'function') {
547
- throw new TypeError('options.postMessage is not a function');
597
+ const shouldWait = waitThreadStart || (waitThreadStart === 0);
598
+ let sab;
599
+ if (shouldWait) {
600
+ sab = new Int32Array(new SharedArrayBuffer(16 + 8192));
601
+ Atomics.store(sab, 0, 0);
548
602
  }
549
- this.postMessage = postMessage;
550
- var wasm64 = Boolean(options.wasm64);
551
- var threadSpawn = function (startArg, errorOrTid) {
552
- var _a;
553
- var EAGAIN = 6;
554
- var isNewABI = errorOrTid !== undefined;
555
- try {
556
- checkSharedWasmMemory(_this_1.wasmMemory);
557
- }
558
- catch (err) {
559
- (_a = _this_1.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack);
560
- if (isNewABI) {
561
- var struct_1 = new Int32Array(_this_1.wasmMemory.buffer, errorOrTid, 2);
562
- Atomics.store(struct_1, 0, 1);
563
- Atomics.store(struct_1, 1, EAGAIN);
564
- Atomics.notify(struct_1, 1);
565
- return 1;
566
- }
567
- else {
568
- return -EAGAIN;
569
- }
570
- }
571
- if (!isNewABI) {
572
- var malloc = _this_1.wasmInstance.exports.malloc;
573
- errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0);
574
- if (!errorOrTid) {
575
- return -48; /* ENOMEM */
576
- }
603
+ let worker;
604
+ let tid;
605
+ const PThread = this.PThread;
606
+ try {
607
+ worker = PThread.getNewWorker(sab);
608
+ if (!worker) {
609
+ throw new Error('failed to get new worker');
577
610
  }
578
- var _free = _this_1.wasmInstance.exports.free;
579
- var free = wasm64 ? function (ptr) { _free(BigInt(ptr)); } : _free;
580
- var struct = new Int32Array(_this_1.wasmMemory.buffer, errorOrTid, 2);
581
- Atomics.store(struct, 0, 0);
582
- Atomics.store(struct, 1, 0);
583
- if (_this_1.childThread) {
584
- postMessage(createMessage('spawn-thread', {
585
- startArg: startArg,
586
- errorOrTid: errorOrTid
587
- }));
588
- Atomics.wait(struct, 1, 0);
589
- var isError = Atomics.load(struct, 0);
590
- var result = Atomics.load(struct, 1);
591
- if (isNewABI) {
592
- return isError;
593
- }
594
- free(errorOrTid);
595
- return isError ? -result : result;
611
+ tid = PThread.markId(worker);
612
+ if (ENVIRONMENT_IS_NODE) {
613
+ worker.unref();
596
614
  }
597
- var shouldWait = waitThreadStart || (waitThreadStart === 0);
598
- var sab;
615
+ worker.postMessage(createMessage('start', {
616
+ tid,
617
+ arg: startArg,
618
+ sab
619
+ }));
599
620
  if (shouldWait) {
600
- sab = new Int32Array(new SharedArrayBuffer(16 + 8192));
601
- Atomics.store(sab, 0, 0);
602
- }
603
- var worker;
604
- var tid;
605
- var PThread = _this_1.PThread;
606
- try {
607
- worker = PThread.getNewWorker(sab);
608
- if (!worker) {
609
- throw new Error('failed to get new worker');
610
- }
611
- tid = PThread.markId(worker);
612
- if (ENVIRONMENT_IS_NODE) {
613
- worker.unref();
614
- }
615
- worker.postMessage(createMessage('start', {
616
- tid: tid,
617
- arg: startArg,
618
- sab: sab
619
- }));
620
- if (shouldWait) {
621
- if (typeof waitThreadStart === 'number') {
622
- var waitResult = Atomics.wait(sab, 0, 0, waitThreadStart);
623
- if (waitResult === 'timed-out') {
624
- throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.');
625
- }
626
- }
627
- else {
628
- Atomics.wait(sab, 0, 0);
629
- }
630
- var r = Atomics.load(sab, 0);
631
- if (r > 1) {
632
- throw deserizeErrorFromBuffer(sab.buffer);
621
+ if (typeof waitThreadStart === 'number') {
622
+ const waitResult = Atomics.wait(sab, 0, 0, waitThreadStart);
623
+ if (waitResult === 'timed-out') {
624
+ throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.');
633
625
  }
634
626
  }
635
- }
636
- catch (e) {
637
- if (worker !== undefined && tid !== undefined) {
638
- try {
639
- PThread.cleanThread(worker, tid, true);
640
- }
641
- catch (_) { }
627
+ else {
628
+ Atomics.wait(sab, 0, 0);
642
629
  }
643
- Atomics.store(struct, 0, 1);
644
- Atomics.store(struct, 1, EAGAIN);
645
- Atomics.notify(struct, 1);
646
- PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack);
647
- if (isNewABI) {
648
- return 1;
630
+ const r = Atomics.load(sab, 0);
631
+ if (r > 1) {
632
+ throw deserizeErrorFromBuffer(sab.buffer);
649
633
  }
650
- free(errorOrTid);
651
- return -EAGAIN;
652
634
  }
653
- Atomics.store(struct, 0, 0);
654
- Atomics.store(struct, 1, tid);
655
- Atomics.notify(struct, 1);
656
- if (!shouldWait) {
657
- worker.whenLoaded.catch(function (err) {
658
- delete worker.whenLoaded;
635
+ }
636
+ catch (e) {
637
+ if (worker !== undefined && tid !== undefined) {
638
+ try {
659
639
  PThread.cleanThread(worker, tid, true);
660
- throw err;
661
- });
640
+ }
641
+ catch (_) { }
662
642
  }
643
+ Atomics.store(struct, 0, 1);
644
+ Atomics.store(struct, 1, EAGAIN);
645
+ Atomics.notify(struct, 1);
646
+ PThread?.printErr(e.stack);
663
647
  if (isNewABI) {
664
- return 0;
648
+ return 1;
665
649
  }
666
650
  free(errorOrTid);
667
- return tid;
668
- };
669
- this.threadSpawn = threadSpawn;
670
- if (this.PThread) {
671
- this.PThread.threadSpawn = threadSpawn;
651
+ return -EAGAIN;
652
+ }
653
+ Atomics.store(struct, 0, 0);
654
+ Atomics.store(struct, 1, tid);
655
+ Atomics.notify(struct, 1);
656
+ if (!shouldWait) {
657
+ worker.whenLoaded.catch((err) => {
658
+ delete worker.whenLoaded;
659
+ PThread.cleanThread(worker, tid, true);
660
+ throw err;
661
+ });
672
662
  }
673
- }
674
- WASIThreads.prototype.getImportObject = function () {
675
- return {
676
- wasi: {
677
- 'thread-spawn': this.threadSpawn
678
- }
679
- };
680
- };
681
- WASIThreads.prototype.setup = function (wasmInstance, wasmModule, wasmMemory) {
682
- wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory);
683
- this.wasmInstance = wasmInstance;
684
- this.wasmMemory = wasmMemory;
685
- if (this.PThread) {
686
- this.PThread.setup(wasmModule, wasmMemory);
663
+ if (isNewABI) {
664
+ return 0;
687
665
  }
666
+ free(errorOrTid);
667
+ return tid;
688
668
  };
689
- WASIThreads.prototype.preloadWorkers = function () {
690
- if (this.PThread) {
691
- return this.PThread.preloadWorkers();
669
+ this.threadSpawn = threadSpawn;
670
+ if (this.PThread) {
671
+ this.PThread.threadSpawn = threadSpawn;
672
+ }
673
+ }
674
+ getImportObject() {
675
+ return {
676
+ wasi: {
677
+ 'thread-spawn': this.threadSpawn
692
678
  }
693
- return Promise.resolve([]);
694
679
  };
695
- /**
696
- * It's ok to call this method to a WASI command module.
697
- *
698
- * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module
699
- *
700
- * @returns A proxied WebAssembly instance if in child thread, other wise the original instance
701
- */
702
- WASIThreads.prototype.initialize = function (instance, module, memory) {
703
- var exports = instance.exports;
704
- memory !== null && memory !== void 0 ? memory : (memory = exports.memory);
680
+ }
681
+ setup(wasmInstance, wasmModule, wasmMemory) {
682
+ wasmMemory ??= wasmInstance.exports.memory;
683
+ this.wasmInstance = wasmInstance;
684
+ this.wasmMemory = wasmMemory;
685
+ if (this.PThread) {
686
+ this.PThread.setup(wasmModule, wasmMemory);
687
+ }
688
+ }
689
+ preloadWorkers() {
690
+ if (this.PThread) {
691
+ return this.PThread.preloadWorkers();
692
+ }
693
+ return Promise.resolve([]);
694
+ }
695
+ initialize(instance, module, memory) {
696
+ const exports = instance.exports;
697
+ memory ??= exports.memory;
698
+ if (this.childThread) {
699
+ instance = createInstanceProxy(instance, memory);
700
+ }
701
+ this.setup(instance, module, memory);
702
+ const wasi = this.wasi;
703
+ if (('_start' in exports) && (typeof exports._start === 'function')) {
705
704
  if (this.childThread) {
706
- instance = createInstanceProxy(instance, memory);
707
- }
708
- this.setup(instance, module, memory);
709
- var wasi = this.wasi;
710
- if (('_start' in exports) && (typeof exports._start === 'function')) {
711
- if (this.childThread) {
712
- wasi.start(instance);
713
- try {
714
- var kStarted = getWasiSymbol(wasi, 'kStarted');
715
- wasi[kStarted] = false;
716
- }
717
- catch (_) { }
718
- }
719
- else {
720
- setupInstance(wasi, instance);
705
+ wasi.start(instance);
706
+ try {
707
+ const kStarted = getWasiSymbol(wasi, 'kStarted');
708
+ wasi[kStarted] = false;
721
709
  }
710
+ catch (_) { }
722
711
  }
723
712
  else {
724
- wasi.initialize(instance);
725
- }
726
- return instance;
727
- };
728
- /**
729
- * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start}
730
- * ```js
731
- * this.initialize(instance, module, memory)
732
- * this.wasi.start(instance)
733
- * ```
734
- */
735
- WASIThreads.prototype.start = function (instance, module, memory) {
736
- var exports = instance.exports;
737
- memory !== null && memory !== void 0 ? memory : (memory = exports.memory);
738
- if (this.childThread) {
739
- instance = createInstanceProxy(instance, memory);
740
- }
741
- this.setup(instance, module, memory);
742
- var exitCode = this.wasi.start(instance);
743
- return { exitCode: exitCode, instance: instance };
744
- };
745
- WASIThreads.prototype.terminateAllThreads = function () {
746
- var _a;
747
- if (!this.childThread) {
748
- (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads();
713
+ setupInstance(wasi, instance);
749
714
  }
750
- else {
751
- this.postMessage(createMessage('terminate-all-threads', {}));
752
- }
753
- };
754
- return WASIThreads;
755
- }());
756
- function patchWasiInstance(wasiThreads, wasi) {
757
- var patched = patchedWasiInstances.get(wasiThreads);
758
- if (patched.has(wasi)) {
759
- return;
760
715
  }
761
- var _this = wasiThreads;
762
- var wasiImport = wasi.wasiImport;
763
- if (wasiImport) {
764
- var proc_exit_1 = wasiImport.proc_exit;
765
- wasiImport.proc_exit = function (code) {
766
- _this.terminateAllThreads();
767
- return proc_exit_1.call(this, code);
768
- };
716
+ else {
717
+ wasi.initialize(instance);
769
718
  }
770
- if (!_this.childThread) {
771
- var start_1 = wasi.start;
772
- if (typeof start_1 === 'function') {
773
- wasi.start = function (instance) {
774
- try {
775
- return start_1.call(this, instance);
776
- }
777
- catch (err) {
778
- if (isTrapError(err)) {
779
- _this.terminateAllThreads();
780
- }
781
- throw err;
782
- }
783
- };
784
- }
719
+ return instance;
720
+ }
721
+ start(instance, module, memory) {
722
+ const exports = instance.exports;
723
+ memory ??= exports.memory;
724
+ if (this.childThread) {
725
+ instance = createInstanceProxy(instance, memory);
785
726
  }
786
- patched.add(wasi);
727
+ this.setup(instance, module, memory);
728
+ const exitCode = this.wasi.start(instance);
729
+ return { exitCode, instance };
787
730
  }
788
- function getWasiSymbol(wasi, description) {
789
- var symbols = Object.getOwnPropertySymbols(wasi);
790
- var selectDescription = function (description) { return function (s) {
791
- if (s.description) {
792
- return s.description === description;
793
- }
794
- return s.toString() === "Symbol(".concat(description, ")");
795
- }; };
796
- if (Array.isArray(description)) {
797
- return description.map(function (d) { return symbols.filter(selectDescription(d))[0]; });
731
+ terminateAllThreads() {
732
+ if (!this.childThread) {
733
+ this.PThread?.terminateAllThreads();
734
+ }
735
+ else {
736
+ this.postMessage(createMessage('terminate-all-threads', {}));
798
737
  }
799
- return symbols.filter(selectDescription(description))[0];
800
738
  }
801
- function setupInstance(wasi, instance) {
802
- var _a = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']), kInstance = _a[0], kSetMemory = _a[1];
803
- wasi[kInstance] = instance;
804
- wasi[kSetMemory](instance.exports.memory);
739
+ }
740
+ function patchWasiInstance(wasiThreads, wasi) {
741
+ const patched = patchedWasiInstances.get(wasiThreads);
742
+ if (patched.has(wasi)) {
743
+ return;
805
744
  }
806
-
807
- /** @public */
808
- var ThreadMessageHandler = /*#__PURE__*/ (function () {
809
- function ThreadMessageHandler(options) {
810
- var postMsg = getPostMessage(options);
811
- if (typeof postMsg !== 'function') {
812
- throw new TypeError('options.postMessage is not a function');
813
- }
814
- this.postMessage = postMsg;
815
- this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad;
816
- this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : function (_type, err) { throw err; };
817
- this.instance = undefined;
818
- // this.module = undefined
819
- this.messagesBeforeLoad = [];
820
- }
821
- /** @virtual */
822
- ThreadMessageHandler.prototype.instantiate = function (data) {
823
- if (typeof this.onLoad === 'function') {
824
- return this.onLoad(data);
825
- }
826
- throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented');
745
+ const _this = wasiThreads;
746
+ const wasiImport = wasi.wasiImport;
747
+ if (wasiImport) {
748
+ const proc_exit = wasiImport.proc_exit;
749
+ wasiImport.proc_exit = function (code) {
750
+ _this.terminateAllThreads();
751
+ return proc_exit.call(this, code);
827
752
  };
828
- /** @virtual */
829
- ThreadMessageHandler.prototype.handle = function (e) {
830
- var _this = this;
831
- var _a;
832
- if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) {
833
- var type = e.data.__emnapi__.type;
834
- var payload_1 = e.data.__emnapi__.payload;
753
+ }
754
+ if (!_this.childThread) {
755
+ const start = wasi.start;
756
+ if (typeof start === 'function') {
757
+ wasi.start = function (instance) {
835
758
  try {
836
- if (type === 'load') {
837
- this._load(payload_1);
838
- }
839
- else if (type === 'start') {
840
- this.handleAfterLoad(e, function () {
841
- _this._start(payload_1);
842
- });
843
- }
759
+ return start.call(this, instance);
844
760
  }
845
761
  catch (err) {
846
- this.onError(err, type);
762
+ if (isTrapError(err)) {
763
+ _this.terminateAllThreads();
764
+ }
765
+ throw err;
847
766
  }
848
- }
849
- };
850
- ThreadMessageHandler.prototype._load = function (payload) {
851
- var _this = this;
852
- if (this.instance !== undefined)
853
- return;
854
- var source;
855
- try {
856
- source = this.instantiate(payload);
857
- }
858
- catch (err) {
859
- this._loaded(err, null, payload);
860
- return;
861
- }
862
- var then = source && 'then' in source ? source.then : undefined;
863
- if (typeof then === 'function') {
864
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
865
- then.call(source, function (source) { _this._loaded(null, source, payload); }, function (err) { _this._loaded(err, null, payload); });
866
- }
867
- else {
868
- this._loaded(null, source, payload);
869
- }
870
- };
871
- ThreadMessageHandler.prototype._start = function (payload) {
872
- var wasi_thread_start = this.instance.exports.wasi_thread_start;
873
- if (typeof wasi_thread_start !== 'function') {
874
- var err = new TypeError('wasi_thread_start is not exported');
875
- notifyPthreadCreateResult(payload.sab, 2, err);
876
- throw err;
877
- }
878
- var postMessage = this.postMessage;
879
- var tid = payload.tid;
880
- var startArg = payload.arg;
881
- notifyPthreadCreateResult(payload.sab, 1);
767
+ };
768
+ }
769
+ }
770
+ patched.add(wasi);
771
+ }
772
+ function getWasiSymbol(wasi, description) {
773
+ const symbols = Object.getOwnPropertySymbols(wasi);
774
+ const selectDescription = (description) => (s) => {
775
+ if (s.description) {
776
+ return s.description === description;
777
+ }
778
+ return s.toString() === `Symbol(${description})`;
779
+ };
780
+ if (Array.isArray(description)) {
781
+ return description.map(d => symbols.filter(selectDescription(d))[0]);
782
+ }
783
+ return symbols.filter(selectDescription(description))[0];
784
+ }
785
+ function setupInstance(wasi, instance) {
786
+ const [kInstance, kSetMemory] = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']);
787
+ wasi[kInstance] = instance;
788
+ wasi[kSetMemory](instance.exports.memory);
789
+ }
790
+
791
+ //#endregion src/wasi-threads.ts
792
+
793
+ //#region src/worker.ts
794
+ class ThreadMessageHandler {
795
+ constructor(options) {
796
+ const postMsg = getPostMessage(options);
797
+ if (typeof postMsg !== 'function') {
798
+ throw new TypeError('options.postMessage is not a function');
799
+ }
800
+ this.postMessage = postMsg;
801
+ this.onLoad = options?.onLoad;
802
+ this.onError = typeof options?.onError === 'function' ? options.onError : (_type, err) => { throw err; };
803
+ this.instance = undefined;
804
+ this.messagesBeforeLoad = [];
805
+ }
806
+ instantiate(data) {
807
+ if (typeof this.onLoad === 'function') {
808
+ return this.onLoad(data);
809
+ }
810
+ throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented');
811
+ }
812
+ handle(e) {
813
+ if (e?.data?.__emnapi__) {
814
+ const type = e.data.__emnapi__.type;
815
+ const payload = e.data.__emnapi__.payload;
882
816
  try {
883
- wasi_thread_start(tid, startArg);
884
- }
885
- catch (err) {
886
- if (err !== 'unwind') {
887
- throw err;
817
+ if (type === 'load') {
818
+ this._load(payload);
888
819
  }
889
- else {
890
- return;
820
+ else if (type === 'start') {
821
+ this.handleAfterLoad(e, () => {
822
+ this._start(payload);
823
+ });
891
824
  }
892
825
  }
893
- postMessage(createMessage('cleanup-thread', { tid: tid }));
894
- };
895
- ThreadMessageHandler.prototype._loaded = function (err, source, payload) {
896
- if (err) {
897
- notifyPthreadCreateResult(payload.sab, 2, err);
898
- throw err;
899
- }
900
- if (source == null) {
901
- var err_1 = new TypeError('onLoad should return an object');
902
- notifyPthreadCreateResult(payload.sab, 2, err_1);
903
- throw err_1;
904
- }
905
- var instance = source.instance;
906
- if (!instance) {
907
- var err_2 = new TypeError('onLoad should return an object which includes "instance"');
908
- notifyPthreadCreateResult(payload.sab, 2, err_2);
909
- throw err_2;
910
- }
911
- this.instance = instance;
912
- var postMessage = this.postMessage;
913
- postMessage(createMessage('loaded', {}));
914
- var messages = this.messagesBeforeLoad;
915
- this.messagesBeforeLoad = [];
916
- for (var i = 0; i < messages.length; i++) {
917
- var data = messages[i];
918
- this.handle({ data: data });
826
+ catch (err) {
827
+ this.onError(err, type);
919
828
  }
920
- };
921
- ThreadMessageHandler.prototype.handleAfterLoad = function (e, f) {
922
- if (this.instance !== undefined) {
923
- f.call(this, e);
829
+ }
830
+ }
831
+ _load(payload) {
832
+ if (this.instance !== undefined)
833
+ return;
834
+ let source;
835
+ try {
836
+ source = this.instantiate(payload);
837
+ }
838
+ catch (err) {
839
+ this._loaded(err, null, payload);
840
+ return;
841
+ }
842
+ const then = source && 'then' in source ? source.then : undefined;
843
+ if (typeof then === 'function') {
844
+ then.call(source, (source) => { this._loaded(null, source, payload); }, (err) => { this._loaded(err, null, payload); });
845
+ }
846
+ else {
847
+ this._loaded(null, source, payload);
848
+ }
849
+ }
850
+ _start(payload) {
851
+ const wasi_thread_start = this.instance.exports.wasi_thread_start;
852
+ if (typeof wasi_thread_start !== 'function') {
853
+ const err = new TypeError('wasi_thread_start is not exported');
854
+ notifyPthreadCreateResult(payload.sab, 2, err);
855
+ throw err;
856
+ }
857
+ const postMessage = this.postMessage;
858
+ const tid = payload.tid;
859
+ const startArg = payload.arg;
860
+ notifyPthreadCreateResult(payload.sab, 1);
861
+ try {
862
+ wasi_thread_start(tid, startArg);
863
+ }
864
+ catch (err) {
865
+ if (err !== 'unwind') {
866
+ throw err;
924
867
  }
925
868
  else {
926
- this.messagesBeforeLoad.push(e.data);
869
+ return;
927
870
  }
928
- };
929
- return ThreadMessageHandler;
930
- }());
931
- function notifyPthreadCreateResult(sab, result, error) {
932
- if (sab) {
933
- serizeErrorToBuffer(sab.buffer, result, error);
934
- Atomics.notify(sab, 0);
935
871
  }
872
+ postMessage(createMessage('cleanup-thread', { tid }));
873
+ }
874
+ _loaded(err, source, payload) {
875
+ if (err) {
876
+ notifyPthreadCreateResult(payload.sab, 2, err);
877
+ throw err;
878
+ }
879
+ if (source == null) {
880
+ const err = new TypeError('onLoad should return an object');
881
+ notifyPthreadCreateResult(payload.sab, 2, err);
882
+ throw err;
883
+ }
884
+ const instance = source.instance;
885
+ if (!instance) {
886
+ const err = new TypeError('onLoad should return an object which includes "instance"');
887
+ notifyPthreadCreateResult(payload.sab, 2, err);
888
+ throw err;
889
+ }
890
+ this.instance = instance;
891
+ const postMessage = this.postMessage;
892
+ postMessage(createMessage('loaded', {}));
893
+ const messages = this.messagesBeforeLoad;
894
+ this.messagesBeforeLoad = [];
895
+ for (let i = 0; i < messages.length; i++) {
896
+ const data = messages[i];
897
+ this.handle({ data });
898
+ }
899
+ }
900
+ handleAfterLoad(e, f) {
901
+ if (this.instance !== undefined) {
902
+ f.call(this, e);
903
+ }
904
+ else {
905
+ this.messagesBeforeLoad.push(e.data);
906
+ }
907
+ }
908
+ }
909
+ function notifyPthreadCreateResult(sab, result, error) {
910
+ if (sab) {
911
+ serizeErrorToBuffer(sab.buffer, result, error);
912
+ Atomics.notify(sab, 0);
936
913
  }
914
+ }
937
915
 
938
- exports.ThreadManager = ThreadManager;
939
- exports.ThreadMessageHandler = ThreadMessageHandler;
940
- exports.WASIThreads = WASIThreads;
941
- exports.createInstanceProxy = createInstanceProxy;
942
- exports.isSharedArrayBuffer = isSharedArrayBuffer;
943
- exports.isTrapError = isTrapError;
916
+ //#endregion src/worker.ts
944
917
 
945
- }));
918
+ export { ThreadManager, ThreadMessageHandler, WASIThreads, createInstanceProxy, isSharedArrayBuffer, isTrapError };