@solidjs/compiler-wasm32-wasi 2.0.0-rc.11 → 2.0.0-rc.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/compiler.wasi.cjs CHANGED
@@ -1,9 +1,57 @@
1
1
  // napi-rs-artifact-metadata:{"version":2,"rootEntry":"index.js","exports":["projectTsrxForTypecheck","transform","transformDirectives","transformLazy","transformRefresh","transformSourceNames"],"managedRootEntries":["browser.js","index.js","compiler.wasm","compiler.debug.wasm"]}
2
2
  /* eslint-disable */
3
- /* prettier-ignore */
4
-
5
3
  /* auto-generated by NAPI-RS */
6
4
 
5
+ const __napiBindingTarget = 'wasm32-wasi'
6
+ function __napiStampBindingTarget(exportsObject, target) {
7
+ if (
8
+ Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
9
+ ) {
10
+ if (exportsObject.__napiBindingTarget === target) {
11
+ // Already ours: the root entry aliases the object it loaded, so a WASI
12
+ // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
13
+ // is a generated loader — arrives already stamped with this same value.
14
+ return target
15
+ }
16
+ const error = new Error(
17
+ '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
18
+ )
19
+ error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
20
+ throw error
21
+ }
22
+ if (!Object.isExtensible(exportsObject)) {
23
+ // A `#[napi(module_exports)]` hook may seal or freeze this object
24
+ // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
25
+ // never a reason to fail an otherwise successful load, so the stamp is
26
+ // skipped. What a consumer still sees then follows the entry point: the
27
+ // browser and deferred loaders declare `__napiBindingTarget` at module
28
+ // level and go on reporting it, while the CommonJS entries hand back this
29
+ // very object as `module.exports`, so there the value is absent.
30
+ return target
31
+ }
32
+ try {
33
+ // [[Define]], not [[Set]]: an ordinary assignment walks the prototype
34
+ // chain, so an inherited accessor could swallow the value or throw and
35
+ // fail an otherwise successful load. The descriptor is what a successful
36
+ // assignment would have produced.
37
+ Object.defineProperty(exportsObject, '__napiBindingTarget', {
38
+ configurable: true,
39
+ enumerable: true,
40
+ value: target,
41
+ writable: true,
42
+ })
43
+ } catch {
44
+ // Same rule as the non-extensible skip above: reporting the artifact is
45
+ // metadata, never a reason to fail an otherwise successful load. An exotic
46
+ // object (a Proxy whose defineProperty trap refuses) is skipped, not
47
+ // thrown over.
48
+ }
49
+ // The CommonJS loaders assign this return value so `cjs-module-lexer` — and
50
+ // therefore Node's CJS -> ESM named export detection — can see
51
+ // `__napiBindingTarget` statically.
52
+ return target
53
+ }
54
+
7
55
  const __nodeFs = require('node:fs')
8
56
  const __nodePath = require('node:path')
9
57
  const { WASI: __nodeWASI } = require('node:wasi')
@@ -91,6 +139,13 @@ function __createWasiWorker(filename) {
91
139
  return new Worker(filename, {
92
140
  env: process.env,
93
141
  execArgv: __workerExecArgv,
142
+ workerData: {
143
+ hostRoot: __hostRoot,
144
+ rootDir: __rootDir,
145
+ crashFlag: __wasiThreadCrashFlag,
146
+ crashReport: __wasiThreadCrashReport,
147
+ addonCrashFlag: __wasiAddonCrashFlag,
148
+ },
94
149
  })
95
150
  } catch (error) {
96
151
  if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
@@ -106,14 +161,312 @@ function __createWasiWorker(filename) {
106
161
  }
107
162
  }
108
163
 
109
- const __rootDir = __nodePath.parse(process.cwd()).root
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
+
226
+ /**
227
+ * Stores the first error a pool worker reported, with the worker's id. Called
228
+ * from the loader's own 'error' listener, which runs before emnapi's.
229
+ */
230
+ function __recordWasiThreadCrashError(error, workerId) {
231
+ if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
232
+ return
233
+ }
234
+ __wasiThreadCrashWorkerError = error
235
+ __wasiThreadCrashWorkerId = workerId
236
+ __fillWasiThreadCrashError()
237
+ }
238
+
239
+ /**
240
+ * The error in the shared crash report, rebuilt once it is complete: the
241
+ * worker writes it before it raises the flag, so it is there as soon as the
242
+ * crash is seen. Plain JavaScript over shared memory; never enters wasm.
243
+ */
244
+ function __readWasiThreadCrashReport() {
245
+ if (__wasiThreadCrashReportRead !== undefined) {
246
+ return __wasiThreadCrashReportRead
247
+ }
248
+ try {
249
+ const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
250
+ if (Atomics.load(header, 0) !== 2) {
251
+ return
252
+ }
253
+ const length = Atomics.load(header, 1)
254
+ const threadId = Atomics.load(header, 2)
255
+ let error
256
+ if (length > 0) {
257
+ // Copied out of shared memory: TextDecoder does not take a shared view.
258
+ const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
259
+ const report = JSON.parse(new TextDecoder().decode(bytes))
260
+ error = new Error(String(report.message))
261
+ if (typeof report.name === 'string') {
262
+ error.name = report.name
263
+ }
264
+ if (typeof report.stack === 'string') {
265
+ error.stack = report.stack
266
+ }
267
+ }
268
+ __wasiThreadCrashReportRead = { error, threadId }
269
+ } catch {
270
+ __wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
271
+ }
272
+ return __wasiThreadCrashReportRead
273
+ }
274
+
275
+ /**
276
+ * The one error every crash path of this binding reports, created on first
277
+ * use.
278
+ *
279
+ * The shared flag is raised before this thread has processed the worker's
280
+ * 'error' event, and once the workers are terminated that event is often
281
+ * never delivered, so neither it nor emnapi's `_fatalError` can be counted
282
+ * on. The cause is filled in from the first source that has it: the error the
283
+ * 'error' listener kept, else the worker's shared crash report, else
284
+ * `_fatalError` — here, and again from the 'error' listener when it arrives
285
+ * later. Until then the error carries only its message.
286
+ */
287
+ function __getWasiThreadCrashError() {
288
+ if (__wasiThreadCrashError === undefined) {
289
+ __wasiThreadCrashError = new Error(
290
+ 'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
291
+ )
292
+ }
293
+ __fillWasiThreadCrashError()
294
+ return __wasiThreadCrashError
295
+ }
296
+
297
+ function __fillWasiThreadCrashError() {
298
+ const crashError = __wasiThreadCrashError
299
+ if (crashError === undefined) {
300
+ return
301
+ }
302
+ try {
303
+ if (crashError.cause === undefined) {
304
+ let cause = __wasiThreadCrashWorkerError
305
+ if (cause === undefined) {
306
+ const report = __readWasiThreadCrashReport()
307
+ cause = report ? report.error : undefined
308
+ }
309
+ if (cause === undefined) {
310
+ const manager = __getWasiThreadManager()
311
+ cause = manager ? manager._fatalError : undefined
312
+ }
313
+ if (cause !== undefined && cause !== null) {
314
+ crashError.cause = cause
315
+ }
316
+ }
317
+ if (crashError.workerThreadId === undefined) {
318
+ let workerId = __wasiThreadCrashWorkerId
319
+ if (workerId === undefined) {
320
+ const report = __readWasiThreadCrashReport()
321
+ workerId = report && report.threadId > 0 ? report.threadId : undefined
322
+ }
323
+ if (workerId !== undefined) {
324
+ crashError.workerThreadId = workerId
325
+ }
326
+ }
327
+ } catch {}
328
+ }
329
+
330
+ /**
331
+ * Let the event loop drain after a wasm thread died, without entering wasm.
332
+ *
333
+ * emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
334
+ * `MessagePort` (`refCounter.refHandle`) that it refs when the count of
335
+ * in-flight async work and threadsafe-function requests leaves zero and unrefs
336
+ * when it comes back. The requests the dead thread held never complete, so the
337
+ * count never returns to zero and the port holds the process open for good.
338
+ * `Context.destroy()` would not release it either — and it runs cleanup
339
+ * hooks, which is exactly what must not happen now. So unref the port directly.
340
+ * The count is left as is: it stays above zero, so a later request never refs
341
+ * the port again.
342
+ *
343
+ * The field is private in emnapi's typings, so read it defensively; a context
344
+ * without it (a non-Node host, a future emnapi) is left alone.
345
+ */
346
+ function __releaseEmnapiWaitingRequestHandle() {
347
+ try {
348
+ const refCounter = __emnapiContext && __emnapiContext.refCounter
349
+ const refHandle = refCounter && refCounter.refHandle
350
+ if (refHandle && typeof refHandle.unref === 'function') {
351
+ refHandle.unref()
352
+ }
353
+ } catch {}
354
+ }
355
+
356
+ /**
357
+ * The public disposer after a wasm thread died. The normal chain drains async
358
+ * work, runs the environment cleanup barrier and destroys the context — every
359
+ * one of those re-enters wasm, and the barrier's shutdown waits for the dead
360
+ * thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
361
+ * avoids. An app that handled the worker's error and then disposes would block
362
+ * there for good. Only stop the workers, then reject: the binding was not
363
+ * cleaned up and cannot be, so reporting success would be a lie. The context
364
+ * is not destroyed — only its waiting-request port is unrefed, so the process
365
+ * can exit on its own — and the 'exit' listener takes its short path too.
366
+ *
367
+ * Latched: every later call returns the same promise.
368
+ */
369
+ function __disposeWasiBindingAfterThreadCrash() {
370
+ if (__wasiThreadCrashDisposePromise) {
371
+ return __wasiThreadCrashDisposePromise
372
+ }
373
+ __releaseEmnapiWaitingRequestHandle()
374
+ let workerResult
375
+ try {
376
+ workerResult = __terminateWasiWorkers()
377
+ } catch (terminateError) {
378
+ workerResult = Promise.reject(terminateError)
379
+ }
380
+ // Built at settlement, after the workers stopped: by then the 'error' event
381
+ // has usually delivered the worker's error.
382
+ __wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
383
+ () => {
384
+ throw __getWasiThreadCrashError()
385
+ },
386
+ (terminateError) => {
387
+ throw __attachCleanupErrors(__getWasiThreadCrashError(), [
388
+ terminateError,
389
+ ])
390
+ },
391
+ )
392
+ return __wasiThreadCrashDisposePromise
393
+ }
394
+
395
+ /**
396
+ * Stops a public disposal that a thread crash overtook.
397
+ *
398
+ * The check at the top of `__disposeWasiBinding` only sees a crash that came
399
+ * first. A thread that dies once the chain is running leaves it polling for
400
+ * work the dead thread still counts — the async-work drain for
401
+ * `napi_wasm_async_work_pending`, the barrier's poll for
402
+ * `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
403
+ * the poll's referenced timers keep the process alive forever with the
404
+ * disposal promise pending. Each poll turn and each step boundary calls this,
405
+ * and the throw ends the chain before anything re-enters wasm again; the
406
+ * disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
407
+ *
408
+ * The initialization rollback runs the same polls and steps, so they stop while
409
+ * it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
410
+ * through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
411
+ * neither in flight is left alone.
412
+ */
413
+ function __abortWasiDisposalIfThreadCrashed() {
414
+ if (
415
+ (__wasiDisposePromise !== undefined ||
416
+ __wasiInitializationRollbackActive) &&
417
+ __hasWasiThreadCrashed()
418
+ ) {
419
+ throw new Error(
420
+ 'napi-rs: WASI disposal stopped because a worker thread crashed',
421
+ )
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Settles an in-flight public disposal whose chain failed after a thread
427
+ * died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
428
+ * way — through the crash disposal: it releases the waiting-request port,
429
+ * terminates the workers and rejects with the same error an entry-time crash
430
+ * gets. `__wasiDisposePromise` stays set, so this caller, every caller that
431
+ * joined it and every later one hold the same promise. Returns false when no
432
+ * thread died, leaving the ordinary failure handling alone.
433
+ */
434
+ function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
435
+ if (!__hasWasiThreadCrashed()) {
436
+ return false
437
+ }
438
+ __disposeWasiBindingAfterThreadCrash().then(resolve, reject)
439
+ return true
440
+ }
441
+
442
+ /**
443
+ * Ends an initialization rollback after a wasm thread died, without entering
444
+ * wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
445
+ * crash disposal releases the waiting-request port and terminates the workers,
446
+ * once. The initialization error itself is left to propagate: the crash error
447
+ * is returned as the rollback's cleanup error, so
448
+ * `__completeWasiInitializationRollback` attaches it — as the cause when the
449
+ * error has none — and keeps the record, since the context was not destroyed.
450
+ */
451
+ function __rollbackWasiInitializationAfterThreadCrash() {
452
+ const crashError = __getWasiThreadCrashError()
453
+ // Its rejection is `crashError` itself, which the caller reports.
454
+ void __disposeWasiBindingAfterThreadCrash().catch(() => {})
455
+ return [crashError]
456
+ }
457
+
458
+ const __cwd = process.cwd()
459
+ const __rootDir = __nodePath.parse(__cwd).root
460
+ const __hostRoot =
461
+ process.platform === 'android' ? __cwd : __rootDir
110
462
 
111
463
  const __wasi = new __nodeWASI({
112
464
  version: 'preview1',
113
465
  env: process.env,
114
466
  preopens: {
115
- [__rootDir]: __rootDir,
116
- }
467
+ [__rootDir]: __hostRoot,
468
+ [__hostRoot]: __hostRoot,
469
+ },
117
470
  })
118
471
 
119
472
  const __sharedMemory = new WebAssembly.Memory({
@@ -146,20 +499,65 @@ let __emnapiContext
146
499
 
147
500
  const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
148
501
  const __wasiWorkers = new Set()
502
+ // The thread manager has to be reachable *before* anything that can throw
503
+ // during load or registration. Initialization can fail after the pool has
504
+ // already spawned workers, and the rollback still has to mark their
505
+ // terminations as expected — but `__napiModule` is assigned only when
506
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
507
+ // plugin factory runs while the emnapi module is being created, before the
508
+ // wasm is loaded and before any registration function runs, and its context
509
+ // carries the very same manager instance.
510
+ let __wasiThreadManager
511
+
512
+ function __captureWasiThreadManager(context) {
513
+ if (context && context.PThread) {
514
+ __wasiThreadManager = context.PThread
515
+ }
516
+ return {}
517
+ }
518
+
519
+ function __getWasiThreadManager() {
520
+ const manager =
521
+ __wasiThreadManager !== undefined
522
+ ? __wasiThreadManager
523
+ : __napiModule
524
+ ? __napiModule.PThread
525
+ : undefined
526
+ if (manager && typeof manager.terminateWorker === 'function') {
527
+ return manager
528
+ }
529
+ return undefined
530
+ }
149
531
  let __napiInstance
150
532
  let __emnapiContextDestroyed = false
151
533
  let __emnapiContextDestroyPromise
152
534
  let __emnapiWasmEnvCleanupPrepared = false
535
+ let __emnapiWasmEnvCleanupPreparing = false
536
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
537
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
538
+ // tell those two apart on its own: it is raised both for a purely synchronous
539
+ // frame — which must not be re-entered, and which nothing outside it can
540
+ // finish — and across this window, which spans real event-loop turns, so a
541
+ // caller that cannot yield can land in the middle of one. That caller can close
542
+ // this window, because `…_finish` is idempotent and joins, which is exactly
543
+ // what the single call does. See `__prepareWasmEnvCleanup`.
544
+ let __finishParkedWasmEnvCleanup
545
+ // Raised while a caller that can still yield is driving the barrier, so the
546
+ // queue it leaves behind is expected rather than lost. See
547
+ // `__reportUnreachedWasmEnvSettlements`.
548
+ let __emnapiWasmEnvCleanupYielding = false
549
+ let __emnapiWasmEnvSettlementLossReported = false
153
550
  let __emnapiWasmEnvCleanupRan = false
154
551
  let __emnapiWasmEnvCleanupDrained = false
155
552
  let __emnapiWasmEnvCleanupDrainPromise
156
553
  let __wasiDisposed = false
554
+ let __wasiAsyncWorkDrainPromise
157
555
  let __wasiDisposePromise
158
- let __completeWasiDisposal = function() {}
556
+ let __completeWasiDisposal = function () {}
159
557
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
160
558
  // that stopped short of destroying the context. See
161
559
  // `__rollbackWasiInitialization`.
162
- let __retainWasiRollbackForRetry = function() {}
560
+ let __retainWasiRollbackForRetry = function () {}
163
561
 
164
562
  function __isThenable(value) {
165
563
  return (
@@ -223,18 +621,127 @@ function __attachCleanupErrors(error, cleanupErrors) {
223
621
  return aggregate
224
622
  }
225
623
 
624
+ function __wrapEmnapiContextDestroyForSettlement(
625
+ context,
626
+ prepareEnvCleanup,
627
+ isPreparingEnvCleanup,
628
+ ) {
629
+ let destroy
630
+ try {
631
+ destroy = context.destroy
632
+ } catch {
633
+ return context
634
+ }
635
+ if (typeof destroy !== 'function') {
636
+ return context
637
+ }
638
+ try {
639
+ Object.defineProperty(context, 'destroy', {
640
+ configurable: true,
641
+ enumerable: false,
642
+ writable: true,
643
+ value: function () {
644
+ // Reentered from a promise hook that fired inside the barrier: the
645
+ // frame running it destroys as soon as it returns.
646
+ if (isPreparingEnvCleanup?.()) {
647
+ return
648
+ }
649
+ prepareEnvCleanup?.()
650
+ return Reflect.apply(destroy, this, arguments)
651
+ },
652
+ })
653
+ } catch {}
654
+ return context
655
+ }
656
+
657
+ function __isPreparingWasmEnvCleanup() {
658
+ return __emnapiWasmEnvCleanupPreparing
659
+ }
660
+
226
661
  function __prepareWasmEnvCleanup() {
227
662
  if (__emnapiWasmEnvCleanupPrepared) {
228
663
  return
229
664
  }
665
+ // A handshake parked between its two halves is one this frame can close, and
666
+ // must: every caller of this function is about to destroy the context, and
667
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
668
+ // the last thing the process runs, and `Context.destroy()` takes the
669
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
670
+ // this degrades to exactly the single call below. Leaving it open instead
671
+ // destroys the context with the barrier still raised, the runtime never
672
+ // joined and the workers never drained.
673
+ const finishParked = __finishParkedWasmEnvCleanup
674
+ if (finishParked !== undefined) {
675
+ finishParked()
676
+ __reportUnreachedWasmEnvSettlements()
677
+ return
678
+ }
679
+ if (__emnapiWasmEnvCleanupPreparing) {
680
+ return
681
+ }
230
682
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
231
683
  if (typeof prepare === 'function') {
232
- prepare()
684
+ // The addon settles the promises it cancels synchronously, under a
685
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
686
+ // here must not reach this export again.
687
+ __emnapiWasmEnvCleanupPreparing = true
688
+ try {
689
+ prepare()
690
+ } finally {
691
+ __emnapiWasmEnvCleanupPreparing = false
692
+ }
233
693
  __emnapiWasmEnvCleanupRan = true
694
+ __reportUnreachedWasmEnvSettlements()
234
695
  }
235
696
  __emnapiWasmEnvCleanupPrepared = true
236
697
  }
237
698
 
699
+ /**
700
+ * Say so when the barrier leaves settlements queued and nothing is left that
701
+ * could deliver them.
702
+ *
703
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
704
+ * dispatch its queue. Every other caller of the barrier destroys in the same
705
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
706
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
707
+ * that queue with a null env and discards it. The promises those settlements
708
+ * were for then hang forever, silently.
709
+ *
710
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
711
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
712
+ * teardown down with it. Destroying anyway is still the right trade — the queue
713
+ * is already unreachable by then.
714
+ */
715
+ function __reportUnreachedWasmEnvSettlements() {
716
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
717
+ return
718
+ }
719
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
720
+ if (typeof pending !== 'function') {
721
+ return
722
+ }
723
+ let queued
724
+ try {
725
+ queued = pending()
726
+ } catch {
727
+ return
728
+ }
729
+ if (!queued) {
730
+ return
731
+ }
732
+ __emnapiWasmEnvSettlementLossReported = true
733
+ try {
734
+ const consoleHost = globalThis.console
735
+ if (consoleHost && typeof consoleHost.error === 'function') {
736
+ consoleHost.error(
737
+ "napi-rs: the wasm environment is being destroyed with " +
738
+ queued +
739
+ " queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.",
740
+ )
741
+ }
742
+ } catch {}
743
+ }
744
+
238
745
  // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
239
746
  // on, so the drain turns below interleave with that dispatch instead of racing
240
747
  // ahead of it on a faster queue.
@@ -266,6 +773,319 @@ const __scheduleMacrotask = (function () {
266
773
  }
267
774
  })()
268
775
 
776
+ // A real, *referenced* timer, for waits that must let the whole host make
777
+ // progress between looks — the async-work drain polls the addon rather than
778
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
779
+ // would spin the loop instead of yielding it. Falls back to the macrotask
780
+ // scheduler on a host without timers.
781
+ function __scheduleTimer(callback, delay) {
782
+ const setTimer = globalThis.setTimeout
783
+ if (typeof setTimer !== 'function') {
784
+ __scheduleMacrotask(callback)
785
+ return
786
+ }
787
+ try {
788
+ setTimer(callback, delay)
789
+ } catch {
790
+ __scheduleMacrotask(callback)
791
+ }
792
+ }
793
+
794
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
795
+ // reason the async-work drain uses one: this polls the addon instead of
796
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
797
+ // the loop instead of yielding it.
798
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
799
+ // Arrivals it takes before the poll paces on the host's timers alone. One
800
+ // proves nothing: a timer armed before the host's timers stopped still fires.
801
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
802
+ // How long a parked turn's own timer must already have been due before a
803
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
804
+ // against the event loop's clock, which is read once per iteration, while
805
+ // these are `Date.now()` readings taken part-way through one, so the two
806
+ // drift apart by however long the loop has been inside the current iteration.
807
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
808
+ // How long a backup itself waits. What is left of it after the slack and one
809
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
810
+ // parked turn from the last backup armed while the host's timers still
811
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
812
+ // `__armWasmRuntimePollStallBackup`.
813
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
814
+
815
+ /**
816
+ * Pacing state for one runtime-work poll.
817
+ *
818
+ * Per poll, never per module: whether the host's timers arrive is not a
819
+ * property of the module. A host can lose its timers between two disposals,
820
+ * and in the deferred shape every instance shares this module — one healthy
821
+ * instance must not disarm the fallback for the next one.
822
+ */
823
+ function __createWasmRuntimePollPace() {
824
+ return {
825
+ // Timers armed by *this* poll that have actually arrived.
826
+ arrivals: 0,
827
+ // The turn waiting on a timer alone *right now* — undefined whenever no
828
+ // turn is parked — and when that turn's own timer came due.
829
+ settleTurn: undefined,
830
+ turnTimerDueAt: 0,
831
+ }
832
+ }
833
+
834
+ /**
835
+ * The backup that ends a turn whose timer is never going to arrive.
836
+ *
837
+ * Once the poll paces on the timer alone it has nothing left to fall back on
838
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
839
+ * the turn that parks, and a parked poll schedules nothing that could notice.
840
+ * So every turn arms one of these before it yields, and each one compares due
841
+ * times instead of measuring how long the parked turn has been waiting.
842
+ *
843
+ * Invariant: a parked turn is ended by the newest backup that was armed while
844
+ * the host's timers still worked, and a backup ends a turn only when that
845
+ * turn's own timer was already due a whole window before the backup itself.
846
+ * Neither half turns on how far apart the arms happen to fall — what bounds
847
+ * the rescue is how far back that newest live backup is:
848
+ *
849
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
850
+ * turn due a whole window earlier is still parked proves that turn's timer
851
+ * was dropped rather than merely late. That same comparison is what leaves a
852
+ * healthy host alone: there the turn's timer has already run and cleared
853
+ * `settleTurn` before any backup due after it can look.
854
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
855
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
856
+ * primitives and the macrotask wins, so such a turn can end with its own
857
+ * timer — and the backup armed one line before it — already dead. The
858
+ * arrival that then flips the poll onto the timer alone can itself be a
859
+ * timer armed before the host's timers died. So the turn that parks can sit
860
+ * two turns past the last live arm, and the newest live backup is due
861
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
862
+ * Arming on every turn is what holds it to two, rather than however far back
863
+ * a throttle last let one through.
864
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
865
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
866
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
867
+ * Past that the turn stays parked and the disposal promise never settles.
868
+ * The bound is deliberate: reaching it takes a host that drops timers
869
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
870
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
871
+ * the second.
872
+ *
873
+ * The poll then goes back to arming both primitives until two fresh arrivals
874
+ * prove the timers again. A host that stops running the timers it has
875
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
876
+ * pending rather than wedging the thread — the same outcome as a blocking
877
+ * closure that never returns. Unreferenced wherever the host allows it: the
878
+ * poll's own turn timers are what keep the loop alive, never these.
879
+ */
880
+ function __armWasmRuntimePollStallBackup(pace) {
881
+ const setTimer = globalThis.setTimeout
882
+ if (typeof setTimer !== 'function') {
883
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
884
+ // already, and that one cannot park.
885
+ return
886
+ }
887
+ // Read before arming, so this never claims to be due earlier than the timer
888
+ // actually is: a backup ends a turn only when it is provably due after it.
889
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
890
+ let handle
891
+ try {
892
+ handle = setTimer(() => {
893
+ const settleTurn = pace.settleTurn
894
+ if (
895
+ !settleTurn ||
896
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
897
+ ) {
898
+ // No turn is parked, or the parked one's timer came due too close to
899
+ // this backup to call it dropped — it may still arrive, and the turn
900
+ // that armed it armed a backup due a whole window after *that*.
901
+ return
902
+ }
903
+ pace.arrivals = 0
904
+ pace.settleTurn = undefined
905
+ settleTurn()
906
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
907
+ } catch {
908
+ return
909
+ }
910
+ if (handle && typeof handle.unref === 'function') {
911
+ try {
912
+ handle.unref()
913
+ } catch {}
914
+ }
915
+ }
916
+
917
+ /**
918
+ * One turn of the runtime-work poll.
919
+ *
920
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
921
+ * missing or throws, but not when it is present, returns a handle and never
922
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
923
+ * host whose timers belong to an IO context that is already gone. That host
924
+ * would park this poll forever, and the poll is unbounded, so nothing would
925
+ * ever call `…_finish`.
926
+ *
927
+ * Arm both primitives until timers armed by this poll have arrived twice, and
928
+ * let whichever lands first end the turn; the loser resolves nothing. A host
929
+ * with working timers therefore pays the double arming for the first turn or
930
+ * two — the macrotask wins the race, but the timers behind it still arrive and
931
+ * are counted — and paces on the timer alone from then on, instead of spinning
932
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
933
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
934
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
935
+ * which ends the parked turn and puts this poll back on both.
936
+ */
937
+ function __yieldWasmRuntimePollTurn(pace) {
938
+ // Armed before the turn yields, and by every turn: what rescues a parked
939
+ // turn has to have been armed while the host's timers still worked, and the
940
+ // turn that parks is the one whose own timer is already dead.
941
+ __armWasmRuntimePollStallBackup(pace)
942
+ return new Promise((resolve) => {
943
+ let settled = false
944
+ const settle = () => {
945
+ if (settled) {
946
+ return
947
+ }
948
+ settled = true
949
+ if (pace.settleTurn === settle) {
950
+ // Nothing is parked any more: a backup running later must not read a
951
+ // due time this turn has already answered.
952
+ pace.settleTurn = undefined
953
+ }
954
+ resolve()
955
+ }
956
+ __scheduleTimer(() => {
957
+ pace.arrivals++
958
+ settle()
959
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
960
+ // Read next to the arming it describes; see
961
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
962
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
963
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
964
+ __scheduleMacrotask(settle)
965
+ return
966
+ }
967
+ // Paced by the timer alone from here; the backup is what ends this turn if
968
+ // the timer never arrives.
969
+ pace.settleTurn = settle
970
+ pace.turnTimerDueAt = turnTimerDueAt
971
+ })
972
+ }
973
+
974
+ /**
975
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
976
+ * event-loop turns in the middle.
977
+ *
978
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
979
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
980
+ * waits on is this one, the only thread that can give a running blocking
981
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
982
+ * for work that can never finish. The addon's two-phase form splits that:
983
+ * `…_begin` stops the runtime without joining and reports whether anything is
984
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
985
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
986
+ * entire point.
987
+ *
988
+ * The poll has no deadline, for the same reason the async-work drain below has
989
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
990
+ * work it would join is the work that is waiting for a turn from this thread —
991
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
992
+ * thread can no longer be reached. A blocking closure that never returns keeps
993
+ * the disposal promise pending instead, exactly as a task whose `execute` never
994
+ * returns already keeps an *undisposed* process alive. The host contract is in
995
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
996
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
997
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
998
+ *
999
+ * Feature-detected like every other export in this teardown, so an addon built
1000
+ * against a napi crate that predates the split keeps the single blocking call.
1001
+ * Returns nothing whenever the handshake finished without yielding, which keeps
1002
+ * an idle disposal synchronous.
1003
+ */
1004
+ function __prepareWasmEnvCleanupWithTurns() {
1005
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
1006
+ return
1007
+ }
1008
+ const exports = __napiInstance?.exports
1009
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
1010
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
1011
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
1012
+ // No split to use. The settlement drain still follows this, so the queue
1013
+ // the single call leaves behind is expected rather than lost.
1014
+ __emnapiWasmEnvCleanupYielding = true
1015
+ try {
1016
+ __prepareWasmEnvCleanup()
1017
+ } finally {
1018
+ __emnapiWasmEnvCleanupYielding = false
1019
+ }
1020
+ return
1021
+ }
1022
+ const workPending = exports?.napi_wasm_runtime_work_pending
1023
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
1024
+ // from one of the JavaScript handlers they run is the same no-op it is inside
1025
+ // the single call: the barrier is up and the runtime is mid-teardown, and
1026
+ // destroying between the halves would strand exactly what this delivers.
1027
+ __emnapiWasmEnvCleanupPreparing = true
1028
+ let live
1029
+ try {
1030
+ live = begin()
1031
+ } catch (error) {
1032
+ __emnapiWasmEnvCleanupPreparing = false
1033
+ throw error
1034
+ }
1035
+ __emnapiWasmEnvCleanupRan = true
1036
+ const finishCleanup = () => {
1037
+ if (__emnapiWasmEnvCleanupPrepared) {
1038
+ // Already closed by a caller that could not yield — the 'exit' teardown
1039
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
1040
+ // is idempotent, but the flags it lowers are not: running it again here
1041
+ // would clear a `preparing` some later barrier had raised.
1042
+ return
1043
+ }
1044
+ __finishParkedWasmEnvCleanup = undefined
1045
+ try {
1046
+ finish()
1047
+ } finally {
1048
+ __emnapiWasmEnvCleanupPreparing = false
1049
+ }
1050
+ __emnapiWasmEnvCleanupPrepared = true
1051
+ }
1052
+ if (!live || typeof workPending !== 'function') {
1053
+ finishCleanup()
1054
+ return
1055
+ }
1056
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
1057
+ // a caller that cannot yield is entitled to end this handshake itself.
1058
+ __finishParkedWasmEnvCleanup = finishCleanup
1059
+ const finishCleanupUnlessCrashed = () => {
1060
+ try {
1061
+ __abortWasiDisposalIfThreadCrashed()
1062
+ } catch (error) {
1063
+ __finishParkedWasmEnvCleanup = undefined
1064
+ throw error
1065
+ }
1066
+ finishCleanup()
1067
+ }
1068
+ return (async () => {
1069
+ // Unbounded, exactly like the async-work drain below. The wait ends when
1070
+ // the addon reports its runtime work finished; the turns spent here are
1071
+ // what let that happen at all.
1072
+ const pace = __createWasmRuntimePollPace()
1073
+ for (;;) {
1074
+ await __yieldWasmRuntimePollTurn(pace)
1075
+ __abortWasiDisposalIfThreadCrashed()
1076
+ try {
1077
+ if (!workPending()) {
1078
+ return
1079
+ }
1080
+ } catch {
1081
+ // A trap is the only way this fails, and a trapped instance has no
1082
+ // reachable work left. Stop polling and finish.
1083
+ return
1084
+ }
1085
+ }
1086
+ })().then(finishCleanupUnlessCrashed, finishCleanupUnlessCrashed)
1087
+ }
1088
+
269
1089
  // Turns to wait for while the addon still reports queued settlements. Reaching
270
1090
  // zero is the only success. A counter still nonzero at this bound rejects the
271
1091
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -402,6 +1222,19 @@ function __destroyEmnapiContext() {
402
1222
  }
403
1223
 
404
1224
  __prepareWasmEnvCleanup()
1225
+ if (__isPreparingWasmEnvCleanup()) {
1226
+ // Reached from inside the synchronous barrier — a promise hook one of the
1227
+ // settlements above ran, which is the reentrancy the destroy wrapper
1228
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
1229
+ // no-op and answer `undefined`, and recording that as a completed destroy
1230
+ // is what makes the frame that *did* start the barrier skip the real one
1231
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
1232
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
1233
+ // moment it returns. The deferred loader carries the same backstop. A
1234
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
1235
+ // rather than skipping it.
1236
+ return
1237
+ }
405
1238
  const result = __emnapiContext.destroy()
406
1239
  if (!__isThenable(result)) {
407
1240
  __emnapiContextDestroyed = true
@@ -422,13 +1255,210 @@ function __destroyEmnapiContext() {
422
1255
  return destroyPromise
423
1256
  }
424
1257
 
1258
+ /**
1259
+ * Holds the event loop open until `work` settles.
1260
+ *
1261
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
1262
+ * binding cannot keep a process alive, and referencing them again for the
1263
+ * termination does not hold either — emnapi unreferences a worker the moment it
1264
+ * reports `async-thread-ready`, which for a worker that was still starting
1265
+ * lands *after* the termination began. Without a handle of its own, an
1266
+ * `await dispose()` with nothing else pending exits the process with its
1267
+ * promise unsettled, and everything after the `await` is skipped.
1268
+ *
1269
+ * The timer is cleared as soon as the work settles, so this never outlives the
1270
+ * disposal that asked for it.
1271
+ */
1272
+ function __keepEventLoopAliveUntil(work) {
1273
+ const setTimer = globalThis.setInterval
1274
+ const clearTimer = globalThis.clearInterval
1275
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
1276
+ return work
1277
+ }
1278
+ let timer
1279
+ try {
1280
+ timer = setTimer(function () {}, 50)
1281
+ } catch {
1282
+ return work
1283
+ }
1284
+ const release = function () {
1285
+ try {
1286
+ clearTimer(timer)
1287
+ } catch {}
1288
+ }
1289
+ return work.then(
1290
+ (value) => {
1291
+ release()
1292
+ return value
1293
+ },
1294
+ (error) => {
1295
+ release()
1296
+ throw error
1297
+ },
1298
+ )
1299
+ }
1300
+
1301
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
1302
+ // ends when the addon reports zero, so this only decides how promptly disposal
1303
+ // notices — not how long it waits.
1304
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
1305
+
1306
+ /**
1307
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
1308
+ * would strand it.
1309
+ *
1310
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
1311
+ * it is observable from JavaScript: the threadless archive resolves
1312
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
1313
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
1314
+ * imports nor exports those symbols and the only brackets a loader could watch
1315
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
1316
+ * functions. The addon is the one place both flavors go through, so it answers
1317
+ * for both, through the same kind of handshake the settlement drain uses:
1318
+ *
1319
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
1320
+ * started. Those completion callbacks run with `napi_cancelled`, which
1321
+ * napi-rs turns into a promise rejected with an `AbortError`.
1322
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
1323
+ * callback. Work already executing refuses cancellation and stays counted
1324
+ * until it finishes normally — which it can, because this runs before the
1325
+ * barrier, before `Context.destroy()` and before anything is terminated.
1326
+ *
1327
+ * Both exports are optional: an addon built against a napi crate that predates
1328
+ * them drains nothing and keeps the previous behavior, exactly as the
1329
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
1330
+ *
1331
+ * Returns nothing when there is nothing outstanding, which keeps disposal
1332
+ * synchronous in the common case. The promise it returns otherwise never
1333
+ * rejects.
1334
+ *
1335
+ * The wait has no deadline, and that is the point: giving up would destroy the
1336
+ * environment with a completion callback still owed, which is the stranding
1337
+ * this exists to prevent. A task whose `execute` never returns already keeps an
1338
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
1339
+ * rather than inventing a bound it cannot honor.
1340
+ *
1341
+ * Safe to call from inside a completion callback, which is reachable: settling
1342
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
1343
+ * being handed back, a threadsafe-function callback — and that JavaScript can
1344
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
1345
+ *
1346
+ * - The addon keeps a work registered until its completion callback
1347
+ * *finishes*, so the count read here is at least one and this takes the
1348
+ * polling path instead of declaring the environment drained and tearing it
1349
+ * down from inside the frame that is still settling a promise.
1350
+ * - The poll is a timer, so it cannot run until the callback has returned to
1351
+ * the host — by which time that work has left the registry. The count the
1352
+ * next poll reads is the one taken after the callback finished.
1353
+ *
1354
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
1355
+ * nested call joins this disposal rather than starting a second one.
1356
+ */
1357
+ function __drainWasiAsyncWork() {
1358
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
1359
+ return __wasiAsyncWorkDrainPromise
1360
+ }
1361
+ const exports = __napiInstance?.exports
1362
+ const pending = exports?.napi_wasm_async_work_pending
1363
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
1364
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
1365
+ return
1366
+ }
1367
+
1368
+ const readPending = () => {
1369
+ try {
1370
+ return pending()
1371
+ } catch (error) {
1372
+ // A trap is the only way this call fails: it reads a counter and cannot
1373
+ // allocate or call back into JavaScript. A trapped instance can no longer
1374
+ // run anything, so its outstanding work is unreachable by definition —
1375
+ // there is nothing left to wait for, and refusing to dispose would only
1376
+ // keep a dead instance and its stuck counter alive. Best-effort here is
1377
+ // the honest answer, and it is what disposal did before this drain
1378
+ // existed.
1379
+ //
1380
+ // Only a trap. Anything else means the export is not what this loader
1381
+ // thinks it is, which is a defect worth surfacing rather than disposing
1382
+ // over.
1383
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
1384
+ return 0
1385
+ }
1386
+ throw error
1387
+ }
1388
+ }
1389
+
1390
+ if (!readPending()) {
1391
+ return
1392
+ }
1393
+ try {
1394
+ cancelPending()
1395
+ } catch {
1396
+ // Cancellation is an optimization: it bounds the wait by the work already
1397
+ // executing. Failing it only means waiting for the whole queue instead.
1398
+ }
1399
+ if (!readPending()) {
1400
+ return
1401
+ }
1402
+
1403
+ const drainPromise = __keepEventLoopAliveUntil(
1404
+ (async () => {
1405
+ while (readPending()) {
1406
+ await new Promise((resolve) => {
1407
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1408
+ })
1409
+ __abortWasiDisposalIfThreadCrashed()
1410
+ }
1411
+ })(),
1412
+ ).then(
1413
+ () => {
1414
+ __wasiAsyncWorkDrainPromise = undefined
1415
+ },
1416
+ (error) => {
1417
+ // A wait that could not run is not a wait that finished. The only way
1418
+ // here is a host whose timers and macrotask primitives all refuse, and
1419
+ // the work is still outstanding — reporting success would destroy the
1420
+ // environment over it, which is the stranding this exists to prevent.
1421
+ // Reject instead: disposal stays retryable, and the context is not
1422
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1423
+ __wasiAsyncWorkDrainPromise = undefined
1424
+ throw error
1425
+ },
1426
+ )
1427
+ __wasiAsyncWorkDrainPromise = drainPromise
1428
+ return drainPromise
1429
+ }
1430
+
1431
+ /**
1432
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1433
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1434
+ * the manager's `exit` listener instead, which reports
1435
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1436
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1437
+ * promise, so disposal never settles and the process dies with an uncaught
1438
+ * exception. Mark the termination through the manager first.
1439
+ *
1440
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1441
+ * the initialization rollback runs on the one path where instantiation never
1442
+ * returned, so `__napiModule` is still undefined there while the workers it
1443
+ * spawned are already registered and loaded.
1444
+ *
1445
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1446
+ */
425
1447
  function __terminateWasiWorkers() {
426
1448
  const cleanupErrors = []
427
1449
  const pending = []
1450
+ const threadManager = __getWasiThreadManager()
428
1451
 
429
1452
  for (const worker of __wasiWorkers) {
430
1453
  let result
431
1454
  try {
1455
+ if (threadManager) {
1456
+ threadManager.terminateWorker(worker)
1457
+ // `terminateWorker` leaves behind a reporter that logs every message
1458
+ // still queued on the port, which Node flushes on exit. Nothing is
1459
+ // listening for those any more.
1460
+ worker.onmessage = undefined
1461
+ }
432
1462
  result = worker.terminate()
433
1463
  } catch (error) {
434
1464
  cleanupErrors.push(error)
@@ -458,7 +1488,9 @@ function __terminateWasiWorkers() {
458
1488
  )
459
1489
  }
460
1490
  }
461
- return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
1491
+ return pending.length > 0
1492
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1493
+ : finish()
462
1494
  }
463
1495
 
464
1496
  function __finishWasiDisposal() {
@@ -470,6 +1502,7 @@ function __finishWasiDisposal() {
470
1502
  }
471
1503
 
472
1504
  function __continueWasiDisposal() {
1505
+ __abortWasiDisposalIfThreadCrashed()
473
1506
  const destroyResult = __destroyEmnapiContext()
474
1507
  if (__isThenable(destroyResult)) {
475
1508
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -477,11 +1510,8 @@ function __continueWasiDisposal() {
477
1510
  return __finishWasiDisposal()
478
1511
  }
479
1512
 
480
- function __startWasiDisposal() {
481
- // Run the pre-teardown barrier, then let the settlements it queued actually
482
- // reach JavaScript, and only then destroy the environment. Doing these two
483
- // back to back is what strands them.
484
- __prepareWasmEnvCleanup()
1513
+ function __drainWasmEnvForWasiDisposal() {
1514
+ __abortWasiDisposalIfThreadCrashed()
485
1515
  const drainResult = __drainWasmEnvCleanup()
486
1516
  if (__isThenable(drainResult)) {
487
1517
  return Promise.resolve(drainResult).then(__continueWasiDisposal)
@@ -489,6 +1519,34 @@ function __startWasiDisposal() {
489
1519
  return __continueWasiDisposal()
490
1520
  }
491
1521
 
1522
+ function __cleanUpWasmEnvForWasiDisposal() {
1523
+ __abortWasiDisposalIfThreadCrashed()
1524
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1525
+ // for, when the addon has one — then let the settlements it queued actually
1526
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1527
+ // these back to back is what strands them.
1528
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1529
+ if (__isThenable(prepareResult)) {
1530
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1531
+ }
1532
+ return __drainWasmEnvForWasiDisposal()
1533
+ }
1534
+
1535
+ function __startWasiDisposal() {
1536
+ // Outstanding `napi_async_work` goes first, while the environment is still
1537
+ // completely live: the completion callbacks run addon code, and everything
1538
+ // after this point takes that away from them — the barrier shuts the async
1539
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1540
+ // the pool threads removes what would have reported the work finished.
1541
+ const asyncWorkResult = __drainWasiAsyncWork()
1542
+ if (__isThenable(asyncWorkResult)) {
1543
+ return Promise.resolve(asyncWorkResult).then(
1544
+ __cleanUpWasmEnvForWasiDisposal,
1545
+ )
1546
+ }
1547
+ return __cleanUpWasmEnvForWasiDisposal()
1548
+ }
1549
+
492
1550
  /**
493
1551
  * Disposes this generated WASI binding.
494
1552
  *
@@ -499,6 +1557,9 @@ function __disposeWasiBinding() {
499
1557
  if (__wasiDisposePromise) {
500
1558
  return __wasiDisposePromise
501
1559
  }
1560
+ if (!__wasiDisposed && __hasWasiThreadCrashed()) {
1561
+ return __disposeWasiBindingAfterThreadCrash()
1562
+ }
502
1563
  if (__wasiDisposed) {
503
1564
  return Promise.resolve()
504
1565
  }
@@ -515,6 +1576,9 @@ function __disposeWasiBinding() {
515
1576
  try {
516
1577
  result = __startWasiDisposal()
517
1578
  } catch (error) {
1579
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1580
+ return disposePromise
1581
+ }
518
1582
  __wasiDisposePromise = undefined
519
1583
  rejectDispose(error)
520
1584
  return disposePromise
@@ -526,6 +1590,9 @@ function __disposeWasiBinding() {
526
1590
  resolveDispose(value)
527
1591
  },
528
1592
  (error) => {
1593
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1594
+ return
1595
+ }
529
1596
  __wasiDisposePromise = undefined
530
1597
  rejectDispose(error)
531
1598
  },
@@ -561,6 +1628,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
561
1628
  }
562
1629
 
563
1630
  function __destroyContextForWasiRollback(cleanupErrors) {
1631
+ __abortWasiDisposalIfThreadCrashed()
564
1632
  let destroyResult
565
1633
  try {
566
1634
  destroyResult = __destroyEmnapiContext()
@@ -629,30 +1697,131 @@ function __retainFailedWasiRollback(cleanupErrors) {
629
1697
  * goes away. That is the deliberate choice: a hung promise is a silent liveness
630
1698
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
631
1699
  */
632
- function __rollbackWasiInitialization() {
633
- const cleanupErrors = []
634
- let drainResult
635
- let settlementsUnreached = false
1700
+ function __runWasiInitializationRollbackSteps() {
1701
+ // The environment teardown this rollback performs, kept nested so it cannot
1702
+ // be reached without the async-work drain below running first.
1703
+ function __rollbackWasmEnvForWasiInitialization() {
1704
+ __abortWasiDisposalIfThreadCrashed()
1705
+ const cleanupErrors = []
1706
+ let prepareResult
1707
+ try {
1708
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1709
+ } catch (cleanupError) {
1710
+ cleanupErrors.push(cleanupError)
1711
+ return __retainFailedWasiRollback(cleanupErrors)
1712
+ }
1713
+ if (__isThenable(prepareResult)) {
1714
+ return Promise.resolve(prepareResult).then(
1715
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1716
+ (cleanupError) => {
1717
+ cleanupErrors.push(cleanupError)
1718
+ return __retainFailedWasiRollback(cleanupErrors)
1719
+ },
1720
+ )
1721
+ }
1722
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1723
+ }
1724
+
1725
+ // The settlement drain of the rollback above, reached either straight away or
1726
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1727
+ // did not finish never gets here: it retains instead, exactly as a drain that
1728
+ // did not finish does.
1729
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1730
+ __abortWasiDisposalIfThreadCrashed()
1731
+ let drainResult
1732
+ try {
1733
+ drainResult = __drainWasmEnvCleanup()
1734
+ } catch (cleanupError) {
1735
+ cleanupErrors.push(cleanupError)
1736
+ return __retainFailedWasiRollback(cleanupErrors)
1737
+ }
1738
+ if (__isThenable(drainResult)) {
1739
+ return Promise.resolve(drainResult).then(
1740
+ () => __destroyContextForWasiRollback(cleanupErrors),
1741
+ (cleanupError) => {
1742
+ cleanupErrors.push(cleanupError)
1743
+ return __retainFailedWasiRollback(cleanupErrors)
1744
+ },
1745
+ )
1746
+ }
1747
+ return __destroyContextForWasiRollback(cleanupErrors)
1748
+ }
1749
+
1750
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1751
+ // work before the load goes on to fail, and this rollback tears down exactly
1752
+ // what those completions need. Settle them while everything is still live,
1753
+ // before the barrier and the teardown above take that away.
1754
+ //
1755
+ // A drain that could not finish leaves async work possibly outstanding, and
1756
+ // destroying the context over it would strand exactly what this rollback is
1757
+ // there to settle. Stop short and retain instead — the same trade
1758
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1759
+ // the context stays reclaimable by a retry or by this flavor's own
1760
+ // last-resort teardown.
1761
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1762
+ __retainFailedWasiRollback([cleanupError])
1763
+ let asyncWorkResult
636
1764
  try {
637
- __prepareWasmEnvCleanup()
638
- drainResult = __drainWasmEnvCleanup()
1765
+ asyncWorkResult = __drainWasiAsyncWork()
639
1766
  } catch (cleanupError) {
640
- cleanupErrors.push(cleanupError)
641
- settlementsUnreached = true
1767
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
642
1768
  }
643
- if (__isThenable(drainResult)) {
644
- return Promise.resolve(drainResult).then(
645
- () => __destroyContextForWasiRollback(cleanupErrors),
646
- (cleanupError) => {
647
- cleanupErrors.push(cleanupError)
648
- return __retainFailedWasiRollback(cleanupErrors)
649
- },
1769
+ if (__isThenable(asyncWorkResult)) {
1770
+ return Promise.resolve(asyncWorkResult).then(
1771
+ __rollbackWasmEnvForWasiInitialization,
1772
+ __retainAfterAsyncWorkDrainFailure,
650
1773
  )
651
1774
  }
652
- if (settlementsUnreached) {
653
- return __retainFailedWasiRollback(cleanupErrors)
1775
+ return __rollbackWasmEnvForWasiInitialization()
1776
+ }
1777
+
1778
+ /**
1779
+ * The rollback above, stopped when a wasm thread has died.
1780
+ *
1781
+ * Its polls wait for work the dead thread still counts, so they never end, and
1782
+ * the barrier's `…_finish` and `Context.destroy()` would re-enter wasm
1783
+ * and wait on that thread for good. While the rollback runs, the poll turns
1784
+ * and step boundaries stop it (`__abortWasiDisposalIfThreadCrashed`), and a
1785
+ * crash seen before, during or after it ends it through
1786
+ * `__rollbackWasiInitializationAfterThreadCrash`. Without a crash the
1787
+ * result — synchronous or not — is passed through unchanged.
1788
+ */
1789
+ function __rollbackWasiInitialization() {
1790
+ if (__hasWasiThreadCrashed()) {
1791
+ return __rollbackWasiInitializationAfterThreadCrash()
654
1792
  }
655
- return __destroyContextForWasiRollback(cleanupErrors)
1793
+ __wasiInitializationRollbackActive = true
1794
+ let result
1795
+ try {
1796
+ result = __runWasiInitializationRollbackSteps()
1797
+ } catch (error) {
1798
+ __wasiInitializationRollbackActive = false
1799
+ if (__hasWasiThreadCrashed()) {
1800
+ return __rollbackWasiInitializationAfterThreadCrash()
1801
+ }
1802
+ throw error
1803
+ }
1804
+ if (!__isThenable(result)) {
1805
+ __wasiInitializationRollbackActive = false
1806
+ return __hasWasiThreadCrashed()
1807
+ ? __rollbackWasiInitializationAfterThreadCrash()
1808
+ : result
1809
+ }
1810
+ return Promise.resolve(result).then(
1811
+ (cleanupErrors) => {
1812
+ __wasiInitializationRollbackActive = false
1813
+ return __hasWasiThreadCrashed()
1814
+ ? __rollbackWasiInitializationAfterThreadCrash()
1815
+ : cleanupErrors
1816
+ },
1817
+ (error) => {
1818
+ __wasiInitializationRollbackActive = false
1819
+ if (__hasWasiThreadCrashed()) {
1820
+ return __rollbackWasiInitializationAfterThreadCrash()
1821
+ }
1822
+ throw error
1823
+ },
1824
+ )
656
1825
  }
657
1826
 
658
1827
  const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
@@ -758,11 +1927,24 @@ function __removeWasiExitListener() {
758
1927
 
759
1928
  function __disposeWasiBindingAtExit() {
760
1929
  __wasiExitListenerRegistered = false
1930
+ if (__hasWasiThreadCrashed()) {
1931
+ // Never re-enter wasm after a thread died: the environment cleanup joins
1932
+ // the dead thread's work and would hang the exit forever — SIGTERM
1933
+ // included, since its JavaScript listener never gets a turn. Stop the
1934
+ // workers and leave.
1935
+ try {
1936
+ void Promise.resolve(__terminateWasiWorkers()).catch(() => {})
1937
+ } catch {}
1938
+ return
1939
+ }
761
1940
  // An 'exit' handler cannot yield, so it cannot wait for queued promise
762
1941
  // settlements the way __startWasiDisposal does — the process is leaving and
763
1942
  // those promises have no observer left anyway. Run the synchronous teardown
764
1943
  // directly. Every step is idempotent, which also makes this the synchronous
765
- // finish for a disposal that is still waiting for its drain.
1944
+ // finish for a disposal that is still waiting for its drain — and, through
1945
+ // __prepareWasmEnvCleanup, for one still parked between the two halves of
1946
+ // the environment cleanup barrier: there are no turns left to poll with, so
1947
+ // this closes that handshake with `…_finish`, which joins.
766
1948
  try {
767
1949
  __destroyEmnapiContext()
768
1950
  } catch {}
@@ -828,7 +2010,11 @@ function __captureEmnapiAutoDestroyListener() {
828
2010
  try {
829
2011
  const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
830
2012
  try {
831
- __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
2013
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
2014
+ __emnapiCreateContext({ autoDestroy: false }),
2015
+ __prepareWasmEnvCleanup,
2016
+ __isPreparingWasmEnvCleanup,
2017
+ )
832
2018
  // emnapi 2.x still registers an unconditional once-listener for
833
2019
  // beforeExit that auto-destroys the context, and suppressDestroy() only
834
2020
  // neutralizes its callback without removing it. This loader owns cleanup
@@ -846,7 +2032,7 @@ try {
846
2032
  napiModule: __napiModule,
847
2033
  } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
848
2034
  context: __emnapiContext,
849
- asyncWorkPoolSize: (function() {
2035
+ asyncWorkPoolSize: (function () {
850
2036
  const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
851
2037
  // NaN > 0 is false
852
2038
  if (threadsSizeFromEnv > 0) {
@@ -856,11 +2042,20 @@ try {
856
2042
  }
857
2043
  })(),
858
2044
  reuseWorker: true,
859
- plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
2045
+ plugins: [
2046
+ __captureWasiThreadManager,
2047
+ __emnapiAsyncWorkPlugin,
2048
+ __emnapiTSFNPlugin,
2049
+ ],
860
2050
  wasi: __wasi,
861
2051
  onCreateWorker() {
862
2052
  const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
863
2053
  __wasiWorkers.add(worker)
2054
+ // Registered before emnapi's own listeners, which rethrow the error.
2055
+ worker.on('error', (error) => {
2056
+ __wasiThreadCrashed = true
2057
+ __recordWasiThreadCrashError(error, worker.threadId)
2058
+ })
864
2059
  worker.onmessage = ({ data }) => {
865
2060
  __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
866
2061
  }
@@ -871,21 +2066,25 @@ try {
871
2066
  // According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415,
872
2067
  // a worker is consist of two handles: kPublicPort and kHandle.
873
2068
  {
874
- const kPublicPort = Object.getOwnPropertySymbols(worker).find(s =>
875
- s.toString().includes("kPublicPort")
876
- );
2069
+ const kPublicPort = Object.getOwnPropertySymbols(worker).find((s) =>
2070
+ s.toString().includes('kPublicPort'),
2071
+ )
877
2072
  if (kPublicPort) {
878
- worker[kPublicPort].ref = () => {};
2073
+ worker[kPublicPort].ref = () => {}
879
2074
  }
880
2075
 
881
- const kHandle = Object.getOwnPropertySymbols(worker).find(s =>
882
- s.toString().includes("kHandle")
883
- );
2076
+ const kHandle = Object.getOwnPropertySymbols(worker).find((s) =>
2077
+ s.toString().includes('kHandle'),
2078
+ )
884
2079
  if (kHandle) {
885
- worker[kHandle].ref = () => {};
2080
+ worker[kHandle].ref = () => {}
886
2081
  }
887
2082
 
888
- worker.unref();
2083
+ worker.unref()
2084
+ // These stubs stay in place for the worker's whole life, disposal
2085
+ // included: `__keepEventLoopAliveUntil` is what holds the process open
2086
+ // while a termination is pending, precisely because a worker's own
2087
+ // references cannot be relied on for it.
889
2088
  }
890
2089
  return worker
891
2090
  },
@@ -900,6 +2099,7 @@ try {
900
2099
  },
901
2100
  beforeInit({ instance }) {
902
2101
  __napiInstance = instance
2102
+ __captureWasiAddonCrashFlag(instance)
903
2103
  for (const name of Object.keys(instance.exports)) {
904
2104
  if (name.startsWith('__napi_register__')) {
905
2105
  instance.exports[name]()
@@ -908,6 +2108,22 @@ try {
908
2108
  },
909
2109
  }))
910
2110
  __publishWasiDispose(__napiModule.exports)
2111
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
2112
+ // export does not travel with it, so carry the marker on the binding itself
2113
+ // too. Three things pin the stamp to exactly this spot:
2114
+ // - inside this `try`, because the guard throws on a
2115
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
2116
+ // catch below tears the environment — context, workers, exit listener —
2117
+ // back down;
2118
+ // - after the async runtime host install, which hands this same object to
2119
+ // addon-provided registration functions that may put anything on it;
2120
+ // - assigning onto the loader's own `module.exports`, which is still the
2121
+ // original object here, so an addon accessor with a refusing setter is
2122
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
2123
+ // export detection — reads the static `module.exports.<name> =` either
2124
+ // way, and the later `module.exports = __napiModule.exports` does not
2125
+ // undo that.
2126
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
911
2127
  __registerWasiExitListener()
912
2128
  } catch (error) {
913
2129
  const rollback = {