@rolldown/binding-wasm32-wasi 1.2.12 → 1.2.14

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rolldown/binding-wasm32-wasi",
3
- "version": "1.2.12",
3
+ "version": "1.2.14",
4
4
  "main": "rolldown-binding.wasi.cjs",
5
5
  "files": [
6
6
  "rolldown-binding.wasm32-wasi.wasm",
@@ -40,7 +40,7 @@
40
40
  "browser": "rolldown-binding.wasi-browser.js",
41
41
  "type": "module",
42
42
  "dependencies": {
43
- "@napi-rs/wasm-runtime": "~1.2.4",
43
+ "@napi-rs/wasm-runtime": "~1.2.5",
44
44
  "@emnapi/core": "2.0.0-alpha.5",
45
45
  "@emnapi/runtime": "2.0.0-alpha.5"
46
46
  }
@@ -1347,6 +1347,36 @@ function __rollbackWasiInitialization() {
1347
1347
  return __rollbackWasmEnvForWasiInitialization()
1348
1348
  }
1349
1349
 
1350
+ // A view of the addon's crash flag, one word of the shared wasm memory, for the
1351
+ // pool workers: they raise it when their wasm thread dies, and the shutdown
1352
+ // waits inside the cleanup calls on this thread then trap instead of waiting on
1353
+ // the dead thread for good. Undefined for an addon built with an older napi.
1354
+ let __wasiAddonCrashFlag
1355
+
1356
+ function __captureWasiAddonCrashFlag(instance) {
1357
+ try {
1358
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
1359
+ if (typeof getAddress !== 'function') {
1360
+ return
1361
+ }
1362
+ const address = getAddress() >>> 0
1363
+ const buffer = __sharedMemory.buffer
1364
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
1365
+ return
1366
+ }
1367
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
1368
+ } catch {}
1369
+ }
1370
+
1371
+ function __shareWasiAddonCrashFlag(worker) {
1372
+ if (__wasiAddonCrashFlag === undefined) {
1373
+ return
1374
+ }
1375
+ try {
1376
+ worker.postMessage({ __napiRsAddonCrashFlag: __wasiAddonCrashFlag })
1377
+ } catch {}
1378
+ }
1379
+
1350
1380
  let __wasiModule
1351
1381
  let __napiModule
1352
1382
 
@@ -1377,6 +1407,7 @@ try {
1377
1407
  type: 'module',
1378
1408
  })
1379
1409
  __wasiWorkers.add(worker)
1410
+ __shareWasiAddonCrashFlag(worker)
1380
1411
  worker.addEventListener('message', __wasmCreateOnMessageForFsProxy(__fs))
1381
1412
 
1382
1413
  worker.addEventListener('message', (event) => {
@@ -1406,6 +1437,10 @@ try {
1406
1437
  },
1407
1438
  beforeInit({ instance }) {
1408
1439
  __napiInstance = instance
1440
+ __captureWasiAddonCrashFlag(instance)
1441
+ for (const worker of __wasiWorkers) {
1442
+ __shareWasiAddonCrashFlag(worker)
1443
+ }
1409
1444
  for (const name of Object.keys(instance.exports)) {
1410
1445
  if (name.startsWith('__napi_register__')) {
1411
1446
  instance.exports[name]()
@@ -139,7 +139,13 @@ function __createWasiWorker(filename) {
139
139
  return new Worker(filename, {
140
140
  env: process.env,
141
141
  execArgv: __workerExecArgv,
142
- workerData: { hostRoot: __hostRoot, rootDir: __rootDir },
142
+ workerData: {
143
+ hostRoot: __hostRoot,
144
+ rootDir: __rootDir,
145
+ crashFlag: __wasiThreadCrashFlag,
146
+ crashReport: __wasiThreadCrashReport,
147
+ addonCrashFlag: __wasiAddonCrashFlag,
148
+ },
143
149
  })
144
150
  } catch (error) {
145
151
  if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
@@ -155,6 +161,454 @@ function __createWasiWorker(filename) {
155
161
  }
156
162
  }
157
163
 
164
+ // Set to 1 by a pool worker (see wasi-worker.mjs) right before it reports that
165
+ // its wasm thread died. Shared memory, so this thread reads it synchronously even
166
+ // while the worker's 'error' event is still queued behind the code that is
167
+ // exiting right now.
168
+ const __wasiThreadCrashFlag = new Int32Array(new SharedArrayBuffer(4))
169
+ // Written by the first pool worker whose wasm thread dies, before it raises the
170
+ // flag: its error and `threadId` (layout in wasi-worker.mjs). Read without
171
+ // waiting for any event, see `__readWasiThreadCrashReport`.
172
+ const __wasiThreadCrashReport = new SharedArrayBuffer(4096)
173
+ let __wasiThreadCrashReportRead
174
+ // The first error a pool worker reported through its 'error' event, and that
175
+ // worker's `threadId`. See `__getWasiThreadCrashError`.
176
+ let __wasiThreadCrashWorkerError
177
+ let __wasiThreadCrashWorkerId
178
+ let __wasiThreadCrashError
179
+ // Raised while `__runWasiInitializationRollbackSteps` runs, so its polls and
180
+ // steps stop after a crash the way a public disposal's do.
181
+ let __wasiInitializationRollbackActive = false
182
+ let __wasiThreadCrashed = false
183
+
184
+ // A view of the addon's crash flag, one word of the shared wasm memory, for the
185
+ // pool workers: they raise it when their wasm thread dies, and the shutdown
186
+ // waits inside the cleanup calls on this thread then trap instead of waiting on
187
+ // the dead thread for good. Undefined for an addon built with an older napi.
188
+ let __wasiAddonCrashFlag
189
+
190
+ function __captureWasiAddonCrashFlag(instance) {
191
+ try {
192
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
193
+ if (typeof getAddress !== 'function') {
194
+ return
195
+ }
196
+ const address = getAddress() >>> 0
197
+ const buffer = __sharedMemory.buffer
198
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
199
+ return
200
+ }
201
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
202
+ } catch {}
203
+ }
204
+
205
+ /**
206
+ * Whether any wasm thread of this binding has died: a trap or an uncaught error
207
+ * in a pool worker, including one that failed to load after its thread spawn
208
+ * had already been reported as started.
209
+ *
210
+ * After that the shared wasm state cannot be trusted: a lock the dead thread
211
+ * held stays held, and a join or park that waits on it — the async runtime's
212
+ * `finish_shutdown` waiting for the dead thread's work to go idle — blocks
213
+ * this thread forever in a raw `memory.atomic.wait32`, which neither
214
+ * emnapi's crash check nor a signal can interrupt.
215
+ */
216
+ function __hasWasiThreadCrashed() {
217
+ if (__wasiThreadCrashed || Atomics.load(__wasiThreadCrashFlag, 0) !== 0) {
218
+ return true
219
+ }
220
+ const manager = __getWasiThreadManager()
221
+ return Boolean(manager && manager._fatalError)
222
+ }
223
+
224
+ let __wasiThreadCrashDisposePromise
225
+ // Raised by the crash disposal right before it terminates the workers. See
226
+ // `__wasiSetImmediate`.
227
+ let __wasiReentryClosed = false
228
+
229
+ /**
230
+ * emnapi's `features.setImmediate` for this binding's context. emnapi defers
231
+ * its calls back into wasm through it: `_emnapi_set_immediate` (libuv handle
232
+ * closes, threadsafe-function finalizers), threadsafe-function dispatch
233
+ * (`async-send`) and the finalizer queue. One queued before a crash disposal
234
+ * terminates the workers still runs after it, and a worker terminated while it
235
+ * held a lock in the wasm heap (napi's heap-sync allocator lock spins and never
236
+ * gives up) leaves that call spinning on this thread for good. The binding is
237
+ * unusable after a crash disposal, so those calls are dropped.
238
+ *
239
+ * Known residual, still able to enter wasm after a crash disposal because emnapi
240
+ * offers no hook for them: the `FinalizationRegistry` callbacks that free
241
+ * external memory when GC collects a value (`_free`, the shared-buffer meta
242
+ * release), threadsafe-function dispatch of `async-send` type 1 and
243
+ * `_emnapi_next_tick` (both `Promise.resolve().then`), and every deferred
244
+ * call under emnapi 1.x, whose `createContext` ignores `features`.
245
+ */
246
+ function __wasiSetImmediate(callback) {
247
+ return setImmediate(function () {
248
+ if (!__wasiReentryClosed) {
249
+ callback()
250
+ }
251
+ })
252
+ }
253
+
254
+ /**
255
+ * Stores the first error a pool worker reported, with the worker's id. Called
256
+ * from the loader's own 'error' listener, which runs before emnapi's.
257
+ */
258
+ function __recordWasiThreadCrashError(error, workerId) {
259
+ if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
260
+ return
261
+ }
262
+ __wasiThreadCrashWorkerError = error
263
+ __wasiThreadCrashWorkerId = workerId
264
+ __fillWasiThreadCrashError()
265
+ }
266
+
267
+ /**
268
+ * The error in the shared crash report, rebuilt once it is complete: the
269
+ * worker writes it before it raises the flag, so it is there as soon as the
270
+ * crash is seen. Plain JavaScript over shared memory; never enters wasm.
271
+ */
272
+ function __readWasiThreadCrashReport() {
273
+ if (__wasiThreadCrashReportRead !== undefined) {
274
+ return __wasiThreadCrashReportRead
275
+ }
276
+ try {
277
+ const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
278
+ if (Atomics.load(header, 0) !== 2) {
279
+ return
280
+ }
281
+ const length = Atomics.load(header, 1)
282
+ const threadId = Atomics.load(header, 2)
283
+ let error
284
+ if (length > 0) {
285
+ // Copied out of shared memory: TextDecoder does not take a shared view.
286
+ const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
287
+ const report = JSON.parse(new TextDecoder().decode(bytes))
288
+ error = new Error(String(report.message))
289
+ if (typeof report.name === 'string') {
290
+ error.name = report.name
291
+ }
292
+ if (typeof report.stack === 'string') {
293
+ error.stack = report.stack
294
+ }
295
+ }
296
+ __wasiThreadCrashReportRead = { error, threadId }
297
+ } catch {
298
+ __wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
299
+ }
300
+ return __wasiThreadCrashReportRead
301
+ }
302
+
303
+ /**
304
+ * The one error every crash path of this binding reports, created on first
305
+ * use.
306
+ *
307
+ * The shared flag is raised before this thread has processed the worker's
308
+ * 'error' event, and once the workers are terminated that event is often
309
+ * never delivered, so neither it nor emnapi's `_fatalError` can be counted
310
+ * on. The cause is filled in from the first source that has it: the error the
311
+ * 'error' listener kept, else the worker's shared crash report, else
312
+ * `_fatalError` — here, and again from the 'error' listener when it arrives
313
+ * later. Until then the error carries only its message.
314
+ */
315
+ function __getWasiThreadCrashError() {
316
+ if (__wasiThreadCrashError === undefined) {
317
+ __wasiThreadCrashError = new Error(
318
+ 'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
319
+ )
320
+ }
321
+ __fillWasiThreadCrashError()
322
+ return __wasiThreadCrashError
323
+ }
324
+
325
+ function __fillWasiThreadCrashError() {
326
+ const crashError = __wasiThreadCrashError
327
+ if (crashError === undefined) {
328
+ return
329
+ }
330
+ try {
331
+ if (crashError.cause === undefined) {
332
+ let cause = __wasiThreadCrashWorkerError
333
+ if (cause === undefined) {
334
+ const report = __readWasiThreadCrashReport()
335
+ cause = report ? report.error : undefined
336
+ }
337
+ if (cause === undefined) {
338
+ const manager = __getWasiThreadManager()
339
+ cause = manager ? manager._fatalError : undefined
340
+ }
341
+ if (cause !== undefined && cause !== null) {
342
+ crashError.cause = cause
343
+ }
344
+ }
345
+ if (crashError.workerThreadId === undefined) {
346
+ let workerId = __wasiThreadCrashWorkerId
347
+ if (workerId === undefined) {
348
+ const report = __readWasiThreadCrashReport()
349
+ workerId = report && report.threadId > 0 ? report.threadId : undefined
350
+ }
351
+ if (workerId !== undefined) {
352
+ crashError.workerThreadId = workerId
353
+ }
354
+ }
355
+ } catch {}
356
+ }
357
+
358
+ /**
359
+ * Let the event loop drain after a wasm thread died, without entering wasm.
360
+ *
361
+ * emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
362
+ * `MessagePort` (`refCounter.refHandle`) that it refs when the count of
363
+ * in-flight async work and threadsafe-function requests leaves zero and unrefs
364
+ * when it comes back. The requests the dead thread held never complete, so the
365
+ * count never returns to zero and the port holds the process open for good.
366
+ * `Context.destroy()` would not release it either — and it runs cleanup
367
+ * hooks, which is exactly what must not happen now. So unref the port directly.
368
+ * The count is left as is: it stays above zero, so a later request never refs
369
+ * the port again.
370
+ *
371
+ * The field is private in emnapi's typings, so read it defensively; a context
372
+ * without it (a non-Node host, a future emnapi) is left alone.
373
+ */
374
+ function __releaseEmnapiWaitingRequestHandle() {
375
+ try {
376
+ const refCounter = __emnapiContext && __emnapiContext.refCounter
377
+ const refHandle = refCounter && refCounter.refHandle
378
+ if (refHandle && typeof refHandle.unref === 'function') {
379
+ refHandle.unref()
380
+ }
381
+ } catch {}
382
+ }
383
+
384
+ /**
385
+ * The public disposer after a wasm thread died. The normal chain drains async
386
+ * work, runs the environment cleanup barrier and destroys the context — every
387
+ * one of those re-enters wasm, and the barrier's shutdown waits for the dead
388
+ * thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
389
+ * avoids. An app that handled the worker's error and then disposes would block
390
+ * there for good. Only stop the workers, then reject: the binding was not
391
+ * cleaned up and cannot be, so reporting success would be a lie. The context
392
+ * is not destroyed — only its waiting-request port is unrefed, so the process
393
+ * can exit on its own — and the 'exit' listener takes its short path too.
394
+ *
395
+ * Latched: every later call returns the same promise.
396
+ */
397
+ function __disposeWasiBindingAfterThreadCrash() {
398
+ if (__wasiThreadCrashDisposePromise) {
399
+ return __wasiThreadCrashDisposePromise
400
+ }
401
+ __releaseEmnapiWaitingRequestHandle()
402
+ // No call into wasm after this: see `__wasiSetImmediate`.
403
+ __wasiReentryClosed = true
404
+ let workerResult
405
+ try {
406
+ workerResult = __terminateWasiWorkers()
407
+ } catch (terminateError) {
408
+ workerResult = Promise.reject(terminateError)
409
+ }
410
+ // Built at settlement, after the workers stopped: by then the 'error' event
411
+ // has usually delivered the worker's error.
412
+ __wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
413
+ () => {
414
+ throw __getWasiThreadCrashError()
415
+ },
416
+ (terminateError) => {
417
+ throw __attachCleanupErrors(__getWasiThreadCrashError(), [
418
+ terminateError,
419
+ ])
420
+ },
421
+ )
422
+ return __wasiThreadCrashDisposePromise
423
+ }
424
+
425
+ /**
426
+ * Stops a public disposal that a thread crash overtook.
427
+ *
428
+ * The check at the top of `__disposeWasiBinding` only sees a crash that came
429
+ * first. A thread that dies once the chain is running leaves it polling for
430
+ * work the dead thread still counts — the async-work drain for
431
+ * `napi_wasm_async_work_pending`, the barrier's poll for
432
+ * `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
433
+ * the poll's referenced timers keep the process alive forever with the
434
+ * disposal promise pending. Each poll turn and each step boundary calls this,
435
+ * and the throw ends the chain before anything re-enters wasm again; the
436
+ * disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
437
+ *
438
+ * The initialization rollback runs the same polls and steps, so they stop while
439
+ * it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
440
+ * through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
441
+ * neither in flight is left alone.
442
+ */
443
+ function __abortWasiDisposalIfThreadCrashed() {
444
+ if (
445
+ (__wasiDisposePromise !== undefined ||
446
+ __wasiInitializationRollbackActive) &&
447
+ __hasWasiThreadCrashed()
448
+ ) {
449
+ throw new Error(
450
+ 'napi-rs: WASI disposal stopped because a worker thread crashed',
451
+ )
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Settles an in-flight public disposal whose chain failed after a thread
457
+ * died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
458
+ * way — through the crash disposal: it releases the waiting-request port,
459
+ * terminates the workers and rejects with the same error an entry-time crash
460
+ * gets. `__wasiDisposePromise` stays set, so this caller, every caller that
461
+ * joined it and every later one hold the same promise. Returns false when no
462
+ * thread died, leaving the ordinary failure handling alone.
463
+ */
464
+ function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
465
+ if (!__hasWasiThreadCrashed()) {
466
+ return false
467
+ }
468
+ __disposeWasiBindingAfterThreadCrash().then(resolve, reject)
469
+ return true
470
+ }
471
+
472
+ /**
473
+ * Ends an initialization rollback after a wasm thread died, without entering
474
+ * wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
475
+ * crash disposal releases the waiting-request port and terminates the workers,
476
+ * once. The initialization error itself is left to propagate: the crash error
477
+ * is returned as the rollback's cleanup error, so
478
+ * `__completeWasiInitializationRollback` attaches it — as the cause when the
479
+ * error has none — and keeps the record, since the context was not destroyed.
480
+ */
481
+ function __rollbackWasiInitializationAfterThreadCrash() {
482
+ const crashError = __getWasiThreadCrashError()
483
+ // Its rejection is `crashError` itself, which the caller reports.
484
+ void __disposeWasiBindingAfterThreadCrash().catch(() => {})
485
+ return [crashError]
486
+ }
487
+
488
+ const __wasiThreadPoolReconcileSymbol = Symbol.for('napi.rs.wasi.reconcileThreadPool')
489
+
490
+ /**
491
+ * Takes a Worker out of emnapi's reuse pool, if it is still there. emnapi
492
+ * terminates a pooled Worker that failed to load but (up to
493
+ * @emnapi/wasi-threads 2.1.0) leaves it in the pool, where the next thread
494
+ * spawn would pop it. A newer emnapi removes it itself, so this is a no-op
495
+ * then.
496
+ */
497
+ function __removeWasiPoolWorker(manager, worker) {
498
+ const index = manager.unusedWorkers.indexOf(worker)
499
+ if (index !== -1) {
500
+ manager.unusedWorkers.splice(index, 1)
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Takes a Worker the thread manager just terminated out of `__wasiWorkers`
506
+ * once it has exited, not before. `terminateWorker` only starts Node's
507
+ * asynchronous `worker.terminate()` and drops its promise, so a disposal that
508
+ * begins before the exit has to find this Worker in the set and wait for it
509
+ * like any other. A second `terminate()` settles when the Worker has exited,
510
+ * the way `__terminateWasiWorkers` waits.
511
+ */
512
+ function __untrackWasiWorkerOnExit(worker) {
513
+ const terminated = worker.terminate()
514
+ if (__isThenable(terminated)) {
515
+ Promise.resolve(terminated).then(
516
+ () => {
517
+ __wasiWorkers.delete(worker)
518
+ },
519
+ // Left tracked: disposal terminates it again and reports the error.
520
+ () => {},
521
+ )
522
+ } else {
523
+ __wasiWorkers.delete(worker)
524
+ }
525
+ }
526
+
527
+ /**
528
+ * Matches emnapi's idle reuse pool to the addon's configured MultiThread worker
529
+ * count, which the addon exports as `napi_wasm_runtime_pool_workers`
530
+ * (napi-async-runtime; 0 under CurrentThread). `reuseWorker: true` starts the
531
+ * pool empty, so without this every pool thread the first async call spawns
532
+ * boots a Worker and loads the wasm into it first. Here each missing Worker is
533
+ * created and starts loading now; a spawn later pops one that is already
534
+ * booting. Idle Workers above the count are terminated, last in first out,
535
+ * the way a spawn takes them. A Worker a spawn already took is not in the pool
536
+ * and is left alone.
537
+ *
538
+ * Runs once after a successful load and, when the loader wraps it, after every
539
+ * successful `configureAsyncRuntime`. Also reachable as
540
+ * binding[Symbol.for('napi.rs.wasi.reconcileThreadPool')]().
541
+ * It never throws and never waits on a Worker: a Worker whose load fails is
542
+ * dropped from the pool when its load rejects. Nothing at all happens after a
543
+ * thread crash, once disposal started, or for an addon without the export.
544
+ */
545
+ function __reconcileWasiThreadPool() {
546
+ try {
547
+ if (__wasiDisposed || __wasiDisposePromise || __hasWasiThreadCrashed()) {
548
+ return
549
+ }
550
+ const read = __napiInstance?.exports?.napi_wasm_runtime_pool_workers
551
+ if (typeof read !== 'function') {
552
+ return
553
+ }
554
+ const count = read() >>> 0
555
+ const manager = __getWasiThreadManager()
556
+ if (
557
+ !manager ||
558
+ !Array.isArray(manager.unusedWorkers) ||
559
+ typeof manager.allocateUnusedWorker !== 'function' ||
560
+ typeof manager.loadWasmModuleToWorker !== 'function'
561
+ ) {
562
+ return
563
+ }
564
+ // Both loops are bounded by the difference they start from, so a manager
565
+ // that does not update `unusedWorkers` the way emnapi does cannot spin.
566
+ for (let excess = manager.unusedWorkers.length - count; excess > 0; excess--) {
567
+ const worker = manager.unusedWorkers[manager.unusedWorkers.length - 1]
568
+ manager.terminateWorker(worker)
569
+ __removeWasiPoolWorker(manager, worker)
570
+ __untrackWasiWorkerOnExit(worker)
571
+ // Compatibility with @emnapi/wasi-threads 2.1.0 and older:
572
+ // `terminateWorker` installs a reporter that logs every emnapi message
573
+ // still queued on the port, so a Worker that finished loading just
574
+ // before it was terminated prints 'received "loaded" command from
575
+ // terminated worker'. Nothing listens for that Worker any more, and a
576
+ // newer emnapi ignores the late 'loaded' itself, so this is harmless
577
+ // there. `__terminateWasiWorkers` does the same.
578
+ worker.onmessage = undefined
579
+ }
580
+ for (let missing = count - manager.unusedWorkers.length; missing > 0; missing--) {
581
+ let worker
582
+ try {
583
+ // Through `onCreateWorker`: tracked in `__wasiWorkers`, unref'd, and
584
+ // handed the crash flags like any pool Worker.
585
+ worker = manager.allocateUnusedWorker()
586
+ manager
587
+ .loadWasmModuleToWorker(worker)
588
+ .then(undefined, () => __removeWasiPoolWorker(manager, worker))
589
+ } catch {
590
+ if (worker !== undefined) {
591
+ __removeWasiPoolWorker(manager, worker)
592
+ try {
593
+ manager.terminateWorker(worker)
594
+ __untrackWasiWorkerOnExit(worker)
595
+ } catch {}
596
+ }
597
+ return
598
+ }
599
+ }
600
+ } catch {}
601
+ }
602
+
603
+ function __publishWasiThreadPoolReconcile(exports) {
604
+ Object.defineProperty(exports, __wasiThreadPoolReconcileSymbol, {
605
+ configurable: false,
606
+ enumerable: false,
607
+ value: __reconcileWasiThreadPool,
608
+ writable: false,
609
+ })
610
+ }
611
+
158
612
  const __cwd = process.cwd()
159
613
  const __rootDir = __nodePath.parse(__cwd).root
160
614
  const __hostRoot =
@@ -756,6 +1210,15 @@ function __prepareWasmEnvCleanupWithTurns() {
756
1210
  // Publish the closer before yielding: from here until `finishCleanup` runs,
757
1211
  // a caller that cannot yield is entitled to end this handshake itself.
758
1212
  __finishParkedWasmEnvCleanup = finishCleanup
1213
+ const finishCleanupUnlessCrashed = () => {
1214
+ try {
1215
+ __abortWasiDisposalIfThreadCrashed()
1216
+ } catch (error) {
1217
+ __finishParkedWasmEnvCleanup = undefined
1218
+ throw error
1219
+ }
1220
+ finishCleanup()
1221
+ }
759
1222
  return (async () => {
760
1223
  // Unbounded, exactly like the async-work drain below. The wait ends when
761
1224
  // the addon reports its runtime work finished; the turns spent here are
@@ -763,6 +1226,7 @@ function __prepareWasmEnvCleanupWithTurns() {
763
1226
  const pace = __createWasmRuntimePollPace()
764
1227
  for (;;) {
765
1228
  await __yieldWasmRuntimePollTurn(pace)
1229
+ __abortWasiDisposalIfThreadCrashed()
766
1230
  try {
767
1231
  if (!workPending()) {
768
1232
  return
@@ -773,7 +1237,7 @@ function __prepareWasmEnvCleanupWithTurns() {
773
1237
  return
774
1238
  }
775
1239
  }
776
- })().then(finishCleanup, finishCleanup)
1240
+ })().then(finishCleanupUnlessCrashed, finishCleanupUnlessCrashed)
777
1241
  }
778
1242
 
779
1243
  // Turns to wait for while the addon still reports queued settlements. Reaching
@@ -1096,6 +1560,7 @@ function __drainWasiAsyncWork() {
1096
1560
  await new Promise((resolve) => {
1097
1561
  __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1098
1562
  })
1563
+ __abortWasiDisposalIfThreadCrashed()
1099
1564
  }
1100
1565
  })(),
1101
1566
  ).then(
@@ -1191,6 +1656,7 @@ function __finishWasiDisposal() {
1191
1656
  }
1192
1657
 
1193
1658
  function __continueWasiDisposal() {
1659
+ __abortWasiDisposalIfThreadCrashed()
1194
1660
  const destroyResult = __destroyEmnapiContext()
1195
1661
  if (__isThenable(destroyResult)) {
1196
1662
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -1199,6 +1665,7 @@ function __continueWasiDisposal() {
1199
1665
  }
1200
1666
 
1201
1667
  function __drainWasmEnvForWasiDisposal() {
1668
+ __abortWasiDisposalIfThreadCrashed()
1202
1669
  const drainResult = __drainWasmEnvCleanup()
1203
1670
  if (__isThenable(drainResult)) {
1204
1671
  return Promise.resolve(drainResult).then(__continueWasiDisposal)
@@ -1207,6 +1674,7 @@ function __drainWasmEnvForWasiDisposal() {
1207
1674
  }
1208
1675
 
1209
1676
  function __cleanUpWasmEnvForWasiDisposal() {
1677
+ __abortWasiDisposalIfThreadCrashed()
1210
1678
  // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1211
1679
  // for, when the addon has one — then let the settlements it queued actually
1212
1680
  // reach JavaScript, and only then destroy the environment. Doing any two of
@@ -1243,6 +1711,9 @@ function __disposeWasiBinding() {
1243
1711
  if (__wasiDisposePromise) {
1244
1712
  return __wasiDisposePromise
1245
1713
  }
1714
+ if (!__wasiDisposed && __hasWasiThreadCrashed()) {
1715
+ return __disposeWasiBindingAfterThreadCrash()
1716
+ }
1246
1717
  if (__wasiDisposed) {
1247
1718
  return Promise.resolve()
1248
1719
  }
@@ -1259,6 +1730,9 @@ function __disposeWasiBinding() {
1259
1730
  try {
1260
1731
  result = __startWasiDisposal()
1261
1732
  } catch (error) {
1733
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1734
+ return disposePromise
1735
+ }
1262
1736
  __wasiDisposePromise = undefined
1263
1737
  rejectDispose(error)
1264
1738
  return disposePromise
@@ -1270,6 +1744,9 @@ function __disposeWasiBinding() {
1270
1744
  resolveDispose(value)
1271
1745
  },
1272
1746
  (error) => {
1747
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1748
+ return
1749
+ }
1273
1750
  __wasiDisposePromise = undefined
1274
1751
  rejectDispose(error)
1275
1752
  },
@@ -1305,6 +1782,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
1305
1782
  }
1306
1783
 
1307
1784
  function __destroyContextForWasiRollback(cleanupErrors) {
1785
+ __abortWasiDisposalIfThreadCrashed()
1308
1786
  let destroyResult
1309
1787
  try {
1310
1788
  destroyResult = __destroyEmnapiContext()
@@ -1373,10 +1851,11 @@ function __retainFailedWasiRollback(cleanupErrors) {
1373
1851
  * goes away. That is the deliberate choice: a hung promise is a silent liveness
1374
1852
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
1375
1853
  */
1376
- function __rollbackWasiInitialization() {
1854
+ function __runWasiInitializationRollbackSteps() {
1377
1855
  // The environment teardown this rollback performs, kept nested so it cannot
1378
1856
  // be reached without the async-work drain below running first.
1379
1857
  function __rollbackWasmEnvForWasiInitialization() {
1858
+ __abortWasiDisposalIfThreadCrashed()
1380
1859
  const cleanupErrors = []
1381
1860
  let prepareResult
1382
1861
  try {
@@ -1402,6 +1881,7 @@ function __rollbackWasiInitialization() {
1402
1881
  // did not finish never gets here: it retains instead, exactly as a drain that
1403
1882
  // did not finish does.
1404
1883
  function __drainWasmEnvForWasiRollback(cleanupErrors) {
1884
+ __abortWasiDisposalIfThreadCrashed()
1405
1885
  let drainResult
1406
1886
  try {
1407
1887
  drainResult = __drainWasmEnvCleanup()
@@ -1449,6 +1929,55 @@ function __rollbackWasiInitialization() {
1449
1929
  return __rollbackWasmEnvForWasiInitialization()
1450
1930
  }
1451
1931
 
1932
+ /**
1933
+ * The rollback above, stopped when a wasm thread has died.
1934
+ *
1935
+ * Its polls wait for work the dead thread still counts, so they never end, and
1936
+ * the barrier's `…_finish` and `Context.destroy()` would re-enter wasm
1937
+ * and wait on that thread for good. While the rollback runs, the poll turns
1938
+ * and step boundaries stop it (`__abortWasiDisposalIfThreadCrashed`), and a
1939
+ * crash seen before, during or after it ends it through
1940
+ * `__rollbackWasiInitializationAfterThreadCrash`. Without a crash the
1941
+ * result — synchronous or not — is passed through unchanged.
1942
+ */
1943
+ function __rollbackWasiInitialization() {
1944
+ if (__hasWasiThreadCrashed()) {
1945
+ return __rollbackWasiInitializationAfterThreadCrash()
1946
+ }
1947
+ __wasiInitializationRollbackActive = true
1948
+ let result
1949
+ try {
1950
+ result = __runWasiInitializationRollbackSteps()
1951
+ } catch (error) {
1952
+ __wasiInitializationRollbackActive = false
1953
+ if (__hasWasiThreadCrashed()) {
1954
+ return __rollbackWasiInitializationAfterThreadCrash()
1955
+ }
1956
+ throw error
1957
+ }
1958
+ if (!__isThenable(result)) {
1959
+ __wasiInitializationRollbackActive = false
1960
+ return __hasWasiThreadCrashed()
1961
+ ? __rollbackWasiInitializationAfterThreadCrash()
1962
+ : result
1963
+ }
1964
+ return Promise.resolve(result).then(
1965
+ (cleanupErrors) => {
1966
+ __wasiInitializationRollbackActive = false
1967
+ return __hasWasiThreadCrashed()
1968
+ ? __rollbackWasiInitializationAfterThreadCrash()
1969
+ : cleanupErrors
1970
+ },
1971
+ (error) => {
1972
+ __wasiInitializationRollbackActive = false
1973
+ if (__hasWasiThreadCrashed()) {
1974
+ return __rollbackWasiInitializationAfterThreadCrash()
1975
+ }
1976
+ throw error
1977
+ },
1978
+ )
1979
+ }
1980
+
1452
1981
  const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
1453
1982
  const __wasiRollbackRegistryKey =
1454
1983
  typeof __filename === 'string' ? __filename : __wasmFilePath
@@ -1552,6 +2081,16 @@ function __removeWasiExitListener() {
1552
2081
 
1553
2082
  function __disposeWasiBindingAtExit() {
1554
2083
  __wasiExitListenerRegistered = false
2084
+ if (__hasWasiThreadCrashed()) {
2085
+ // Never re-enter wasm after a thread died: the environment cleanup joins
2086
+ // the dead thread's work and would hang the exit forever — SIGTERM
2087
+ // included, since its JavaScript listener never gets a turn. Stop the
2088
+ // workers and leave.
2089
+ try {
2090
+ void Promise.resolve(__terminateWasiWorkers()).catch(() => {})
2091
+ } catch {}
2092
+ return
2093
+ }
1555
2094
  // An 'exit' handler cannot yield, so it cannot wait for queued promise
1556
2095
  // settlements the way __startWasiDisposal does — the process is leaving and
1557
2096
  // those promises have no observer left anyway. Run the synchronous teardown
@@ -1626,7 +2165,7 @@ try {
1626
2165
  const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
1627
2166
  try {
1628
2167
  __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1629
- __emnapiCreateContext({ autoDestroy: false }),
2168
+ __emnapiCreateContext({ autoDestroy: false, features: { setImmediate: __wasiSetImmediate } }),
1630
2169
  __prepareWasmEnvCleanup,
1631
2170
  __isPreparingWasmEnvCleanup,
1632
2171
  )
@@ -1666,6 +2205,11 @@ try {
1666
2205
  onCreateWorker() {
1667
2206
  const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
1668
2207
  __wasiWorkers.add(worker)
2208
+ // Registered before emnapi's own listeners, which rethrow the error.
2209
+ worker.on('error', (error) => {
2210
+ __wasiThreadCrashed = true
2211
+ __recordWasiThreadCrashError(error, worker.threadId)
2212
+ })
1669
2213
  worker.onmessage = ({ data }) => {
1670
2214
  __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
1671
2215
  }
@@ -1709,6 +2253,7 @@ try {
1709
2253
  },
1710
2254
  beforeInit({ instance }) {
1711
2255
  __napiInstance = instance
2256
+ __captureWasiAddonCrashFlag(instance)
1712
2257
  for (const name of Object.keys(instance.exports)) {
1713
2258
  if (name.startsWith('__napi_register__')) {
1714
2259
  instance.exports[name]()
@@ -1717,6 +2262,7 @@ try {
1717
2262
  },
1718
2263
  }))
1719
2264
  __publishWasiDispose(__napiModule.exports)
2265
+ __publishWasiThreadPoolReconcile(__napiModule.exports)
1720
2266
  // The CommonJS tail below aliases `__napiModule.exports`; a named module
1721
2267
  // export does not travel with it, so carry the marker on the binding itself
1722
2268
  // too. Three things pin the stamp to exactly this spot:
@@ -1745,6 +2291,11 @@ try {
1745
2291
  __runWasiInitializationRollback(rollback)
1746
2292
  throw rollback.error
1747
2293
  }
2294
+ // Preload the pool for the count the addon configured during registration.
2295
+ // See `__reconcileWasiThreadPool`.
2296
+ try {
2297
+ __reconcileWasiThreadPool()
2298
+ } catch {}
1748
2299
  module.exports = __napiModule.exports
1749
2300
  module.exports.LegalCommentsMode = __napiModule.exports.LegalCommentsMode
1750
2301
  module.exports.minify = __napiModule.exports.minify
@@ -1755,6 +1755,7 @@ export declare class BindingNormalizedOptions {
1755
1755
  get assetFilenames(): string | undefined
1756
1756
  get dir(): string | null
1757
1757
  get file(): string | null
1758
+ get charset(): 'ascii' | 'utf8'
1758
1759
  get format(): 'es' | 'cjs' | 'iife' | 'umd'
1759
1760
  get exports(): 'default' | 'named' | 'none' | 'auto'
1760
1761
  get esModule(): boolean | 'if-default-prop'
@@ -2009,6 +2010,7 @@ export interface BindingChecksOptions {
2009
2010
  largeBarrelModules?: boolean
2010
2011
  sourcemapBroken?: boolean
2011
2012
  namespaceConflict?: boolean
2013
+ shimmedExport?: boolean
2012
2014
  }
2013
2015
 
2014
2016
  export interface BindingChunkImportMap {
@@ -2280,6 +2282,7 @@ export interface BindingExperimentalDevModeOptions {
2280
2282
  /** @deprecated Common runtime injection will be disabled by default in the future. */
2281
2283
  skipCommonRuntimeInjection?: boolean
2282
2284
  lazy?: boolean
2285
+ hotUpdate?: boolean
2283
2286
  }
2284
2287
 
2285
2288
  export interface BindingExperimentalOptions {
@@ -2542,6 +2545,7 @@ export interface BindingLog {
2542
2545
  id?: string
2543
2546
  code?: string
2544
2547
  exporter?: string
2548
+ binding?: string
2545
2549
  plugin?: string
2546
2550
  /** Location information (line, column, file) */
2547
2551
  loc?: BindingLogLocation
@@ -2648,6 +2652,7 @@ export interface BindingOutputOptions {
2648
2652
  postFooter?: string | ((chunk: BindingRenderedChunk) => MaybePromise<VoidNullable<string>>)
2649
2653
  dir?: string
2650
2654
  file?: string
2655
+ charset?: 'ascii' | 'utf8'
2651
2656
  esModule?: boolean | 'if-default-prop'
2652
2657
  exports?: 'default' | 'named' | 'none' | 'auto'
2653
2658
  extend?: boolean
Binary file
@@ -53,6 +53,30 @@ const handler = new MessageHandler({
53
53
  }
54
54
  })
55
55
 
56
+ // When this wasm thread dies, raise the addon's crash flag before emnapi reports
57
+ // it. The loader thread may be inside wasm, in a cleanup call that waits on this
58
+ // thread; the flag is what those waits check between short slices, and once it
59
+ // is up they trap instead of waiting for good. It is a word in the shared wasm
60
+ // memory, and the loader posts a view of it (see
61
+ // napi_wasm_thread_crash_flag_address) after it instantiated the wasm, or right
62
+ // after it created this worker. No view, no flag: an addon built with an older
63
+ // napi, or a failure before the view arrived.
64
+ let __addonCrashFlag
65
+ const __beforeReportError = handler.beforeReportError
66
+ handler.beforeReportError = function (...args) {
67
+ if (__addonCrashFlag !== undefined) {
68
+ try {
69
+ Atomics.store(__addonCrashFlag, 0, 1)
70
+ } catch {}
71
+ }
72
+ return __beforeReportError.apply(this, args)
73
+ }
74
+
56
75
  globalThis.onmessage = function (e) {
76
+ const data = e && e.data
77
+ if (data && data.__napiRsAddonCrashFlag instanceof Int32Array) {
78
+ __addonCrashFlag = data.__napiRsAddonCrashFlag
79
+ return
80
+ }
57
81
  handler.handle(e)
58
82
  }
package/wasi-worker.mjs CHANGED
@@ -2,80 +2,184 @@ import fs from 'node:fs'
2
2
  import { createRequire } from 'node:module'
3
3
  import { parse } from 'node:path'
4
4
  import { WASI } from 'node:wasi'
5
- import { parentPort, Worker, workerData } from 'node:worker_threads'
5
+ import { parentPort, threadId, Worker, workerData } from 'node:worker_threads'
6
6
 
7
7
  const require = createRequire(import.meta.url)
8
8
 
9
- const {
10
- instantiateNapiModuleSync,
11
- MessageHandler,
12
- getDefaultContext,
13
- emnapiAsyncWorkPlugin,
14
- emnapiTSFNPlugin,
15
- } = require('@napi-rs/wasm-runtime')
9
+ // The thread spawn that created this worker has already returned, so the loader
10
+ // thread may be waiting on this thread. A failure before the crash hook below is
11
+ // in place (a missing '@napi-rs/wasm-runtime', say) has to raise the crash flags
12
+ // too, then fail the worker as before.
13
+ let handler
14
+ try {
15
+ const {
16
+ instantiateNapiModuleSync,
17
+ MessageHandler,
18
+ getDefaultContext,
19
+ emnapiAsyncWorkPlugin,
20
+ emnapiTSFNPlugin,
21
+ } = require('@napi-rs/wasm-runtime')
16
22
 
17
- if (parentPort) {
18
- parentPort.on('message', (data) => {
19
- globalThis.onmessage({ data })
23
+ if (parentPort) {
24
+ parentPort.on('message', (data) => {
25
+ globalThis.onmessage({ data })
26
+ })
27
+ }
28
+
29
+ Object.assign(globalThis, {
30
+ self: globalThis,
31
+ require,
32
+ Worker,
33
+ importScripts: function (f) {
34
+ // oxlint-disable-next-line no-eval -- WASI importScripts polyfill
35
+ ;(0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f)
36
+ },
37
+ postMessage: function (msg) {
38
+ if (parentPort) {
39
+ parentPort.postMessage(msg)
40
+ }
41
+ },
20
42
  })
21
- }
22
43
 
23
- Object.assign(globalThis, {
24
- self: globalThis,
25
- require,
26
- Worker,
27
- importScripts: function (f) {
28
- // oxlint-disable-next-line no-eval -- WASI importScripts polyfill
29
- ;(0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f)
30
- },
31
- postMessage: function (msg) {
32
- if (parentPort) {
33
- parentPort.postMessage(msg)
34
- }
35
- },
36
- })
44
+ const emnapiContext = getDefaultContext()
37
45
 
38
- const emnapiContext = getDefaultContext()
46
+ const __cwd = process.cwd()
47
+ const __rootDir =
48
+ (workerData && typeof workerData.rootDir === 'string' && workerData.rootDir) ||
49
+ parse(__cwd).root
50
+ const __hostRoot =
51
+ (workerData && typeof workerData.hostRoot === 'string' && workerData.hostRoot) ||
52
+ (process.platform === 'android' ? __cwd : __rootDir)
39
53
 
40
- const __cwd = process.cwd()
41
- const __rootDir =
42
- (workerData && typeof workerData.rootDir === 'string' && workerData.rootDir) ||
43
- parse(__cwd).root
44
- const __hostRoot =
45
- (workerData && typeof workerData.hostRoot === 'string' && workerData.hostRoot) ||
46
- (process.platform === 'android' ? __cwd : __rootDir)
54
+ handler = new MessageHandler({
55
+ onLoad({ wasmModule, wasmMemory }) {
56
+ const wasi = new WASI({
57
+ version: 'preview1',
58
+ env: process.env,
59
+ preopens: {
60
+ [__rootDir]: __hostRoot,
61
+ [__hostRoot]: __hostRoot,
62
+ },
63
+ })
47
64
 
48
- const handler = new MessageHandler({
49
- onLoad({ wasmModule, wasmMemory }) {
50
- const wasi = new WASI({
51
- version: 'preview1',
52
- env: process.env,
53
- preopens: {
54
- [__rootDir]: __hostRoot,
55
- [__hostRoot]: __hostRoot,
56
- },
57
- })
65
+ return instantiateNapiModuleSync(wasmModule, {
66
+ childThread: true,
67
+ wasi,
68
+ context: emnapiContext,
69
+ // The wasm links a "basic" emnapi archive (no C async-work /
70
+ // threadsafe-function implementations), so every thread that
71
+ // instantiates it must provide the JavaScript implementations
72
+ // through the emnapi plugins.
73
+ plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin],
74
+ overwriteImports(importObject) {
75
+ importObject.env = {
76
+ ...importObject.env,
77
+ ...importObject.napi,
78
+ ...importObject.emnapi,
79
+ memory: wasmMemory,
80
+ }
81
+ },
82
+ })
83
+ },
84
+ })
85
+ } catch (error) {
86
+ if (workerData && workerData.crashFlag instanceof Int32Array) {
87
+ __raiseWasiThreadCrashFlags(error)
88
+ }
89
+ throw error
90
+ }
58
91
 
59
- return instantiateNapiModuleSync(wasmModule, {
60
- childThread: true,
61
- wasi,
62
- context: emnapiContext,
63
- // The wasm links a "basic" emnapi archive (no C async-work /
64
- // threadsafe-function implementations), so every thread that
65
- // instantiates it must provide the JavaScript implementations
66
- // through the emnapi plugins.
67
- plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin],
68
- overwriteImports(importObject) {
69
- importObject.env = {
70
- ...importObject.env,
71
- ...importObject.napi,
72
- ...importObject.emnapi,
73
- memory: wasmMemory,
92
+ // Tell the loader thread synchronously that this wasm thread died, so its 'exit'
93
+ // teardown does not re-enter wasm and wait on this thread forever. emnapi calls
94
+ // beforeReportError (which runs emnapi_thread_crashed, so the main thread may
95
+ // throw 'unwind' and start exiting) before the 'error' event is even posted.
96
+ // A loader that predates the flag passes none.
97
+ if (workerData && workerData.crashFlag instanceof Int32Array) {
98
+ const __beforeReportError = handler.beforeReportError
99
+ handler.beforeReportError = function (...args) {
100
+ if (!__raiseWasiThreadCrashFlags(args[0])) {
101
+ // No view (the thread was spawned before the loader read the address,
102
+ // say): the export stores into the same word, but only a worker that
103
+ // loaded has an instance to call it on.
104
+ try {
105
+ const __napiThreadCrashed = this.instance?.exports?.napi_wasm_thread_crashed
106
+ if (typeof __napiThreadCrashed === 'function') {
107
+ __napiThreadCrashed()
74
108
  }
75
- },
76
- })
77
- },
78
- })
109
+ } catch {}
110
+ }
111
+ return __beforeReportError.apply(this, args)
112
+ }
113
+ }
114
+
115
+ // The error goes into the shared crash report first. The 'error' event that
116
+ // would carry it is dropped when the loader terminates this worker before the
117
+ // event is sent, so the report is the only copy the loader can count on.
118
+ // Layout: three Int32 words — state (0 empty, 1 writing, 2 written), byte
119
+ // length, threadId — then the UTF-8 JSON of { name, message, stack }. Only the
120
+ // first worker to crash writes it, and it is complete before the flag is raised.
121
+ //
122
+ // Then the loader's flag, then the addon's. The loader thread may already be
123
+ // inside wasm, in a cleanup call that waits on this thread; the addon's flag is
124
+ // what those waits check between short slices. It is a word in the shared wasm
125
+ // memory (the loader passes a view of it, see napi_wasm_thread_crash_flag_address),
126
+ // so no instance is needed: a worker that failed while loading raises it too.
127
+ // Once it is up the waits trap, and the loader, whose flag is already up, turns
128
+ // the throw into its crash rejection. Returns whether the addon's flag was raised.
129
+ function __raiseWasiThreadCrashFlags(error) {
130
+ try {
131
+ __writeCrashReport(workerData.crashReport, error)
132
+ } catch {}
133
+ try {
134
+ Atomics.store(workerData.crashFlag, 0, 1)
135
+ } catch {}
136
+ const addonCrashFlag = workerData.addonCrashFlag
137
+ if (!(addonCrashFlag instanceof Int32Array)) {
138
+ return false
139
+ }
140
+ try {
141
+ Atomics.store(addonCrashFlag, 0, 1)
142
+ return true
143
+ } catch {
144
+ return false
145
+ }
146
+ }
147
+
148
+ function __writeCrashReport(report, error) {
149
+ if (!(report instanceof SharedArrayBuffer) || report.byteLength <= 12) {
150
+ return
151
+ }
152
+ const header = new Int32Array(report, 0, 3)
153
+ if (Atomics.compareExchange(header, 0, 0, 1) !== 0) {
154
+ return
155
+ }
156
+ let length = 0
157
+ try {
158
+ const body = new Uint8Array(report, 12)
159
+ const isObject =
160
+ error !== null && (typeof error === 'object' || typeof error === 'function')
161
+ const name = isObject && typeof error.name === 'string' ? error.name : 'Error'
162
+ const message = isObject && typeof error.message === 'string'
163
+ ? error.message
164
+ : String(error)
165
+ const stack = isObject && typeof error.stack === 'string' ? error.stack : undefined
166
+ const encoder = new TextEncoder()
167
+ let bytes = encoder.encode(JSON.stringify({ name, message, stack }))
168
+ if (bytes.length > body.length) {
169
+ bytes = encoder.encode(
170
+ JSON.stringify({ name, message: message.slice(0, body.length >> 3) }),
171
+ )
172
+ }
173
+ if (bytes.length <= body.length) {
174
+ body.set(bytes)
175
+ length = bytes.length
176
+ }
177
+ Atomics.store(header, 2, threadId)
178
+ } finally {
179
+ Atomics.store(header, 1, length)
180
+ Atomics.store(header, 0, 2)
181
+ }
182
+ }
79
183
 
80
184
  globalThis.onmessage = function (e) {
81
185
  handler.handle(e)