@rolldown/binding-wasm32-wasi 1.2.9 → 1.2.10

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.
@@ -131,10 +131,25 @@ let __emnapiContextDestroyed = false
131
131
  let __emnapiContextDestroyPromise
132
132
  let __emnapiWasmEnvCleanupPrepared = false
133
133
  let __emnapiWasmEnvCleanupPreparing = false
134
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
135
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
136
+ // tell those two apart on its own: it is raised both for a purely synchronous
137
+ // frame — which must not be re-entered, and which nothing outside it can
138
+ // finish — and across this window, which spans real event-loop turns, so a
139
+ // caller that cannot yield can land in the middle of one. That caller can close
140
+ // this window, because `…_finish` is idempotent and joins, which is exactly
141
+ // what the single call does. See `__prepareWasmEnvCleanup`.
142
+ let __finishParkedWasmEnvCleanup
143
+ // Raised while a caller that can still yield is driving the barrier, so the
144
+ // queue it leaves behind is expected rather than lost. See
145
+ // `__reportUnreachedWasmEnvSettlements`.
146
+ let __emnapiWasmEnvCleanupYielding = false
147
+ let __emnapiWasmEnvSettlementLossReported = false
134
148
  let __emnapiWasmEnvCleanupRan = false
135
149
  let __emnapiWasmEnvCleanupDrained = false
136
150
  let __emnapiWasmEnvCleanupDrainPromise
137
151
  let __wasiDisposed = false
152
+ let __wasiAsyncWorkDrainPromise
138
153
  let __wasiDisposePromise
139
154
  let __completeWasiDisposal = function () {}
140
155
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
@@ -242,7 +257,24 @@ function __isPreparingWasmEnvCleanup() {
242
257
  }
243
258
 
244
259
  function __prepareWasmEnvCleanup() {
245
- if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
260
+ if (__emnapiWasmEnvCleanupPrepared) {
261
+ return
262
+ }
263
+ // A handshake parked between its two halves is one this frame can close, and
264
+ // must: every caller of this function is about to destroy the context, and
265
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
266
+ // the last thing the process runs, and `Context.destroy()` takes the
267
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
268
+ // this degrades to exactly the single call below. Leaving it open instead
269
+ // destroys the context with the barrier still raised, the runtime never
270
+ // joined and the workers never drained.
271
+ const finishParked = __finishParkedWasmEnvCleanup
272
+ if (finishParked !== undefined) {
273
+ finishParked()
274
+ __reportUnreachedWasmEnvSettlements()
275
+ return
276
+ }
277
+ if (__emnapiWasmEnvCleanupPreparing) {
246
278
  return
247
279
  }
248
280
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
@@ -257,10 +289,57 @@ function __prepareWasmEnvCleanup() {
257
289
  __emnapiWasmEnvCleanupPreparing = false
258
290
  }
259
291
  __emnapiWasmEnvCleanupRan = true
292
+ __reportUnreachedWasmEnvSettlements()
260
293
  }
261
294
  __emnapiWasmEnvCleanupPrepared = true
262
295
  }
263
296
 
297
+ /**
298
+ * Say so when the barrier leaves settlements queued and nothing is left that
299
+ * could deliver them.
300
+ *
301
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
302
+ * dispatch its queue. Every other caller of the barrier destroys in the same
303
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
304
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
305
+ * that queue with a null env and discards it. The promises those settlements
306
+ * were for then hang forever, silently.
307
+ *
308
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
309
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
310
+ * teardown down with it. Destroying anyway is still the right trade — the queue
311
+ * is already unreachable by then.
312
+ */
313
+ function __reportUnreachedWasmEnvSettlements() {
314
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
315
+ return
316
+ }
317
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
318
+ if (typeof pending !== 'function') {
319
+ return
320
+ }
321
+ let queued
322
+ try {
323
+ queued = pending()
324
+ } catch {
325
+ return
326
+ }
327
+ if (!queued) {
328
+ return
329
+ }
330
+ __emnapiWasmEnvSettlementLossReported = true
331
+ try {
332
+ const consoleHost = globalThis.console
333
+ if (consoleHost && typeof consoleHost.error === 'function') {
334
+ consoleHost.error(
335
+ "napi-rs: the wasm environment is being destroyed with " +
336
+ queued +
337
+ " 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.",
338
+ )
339
+ }
340
+ } catch {}
341
+ }
342
+
264
343
  // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
265
344
  // on, so the drain turns below interleave with that dispatch instead of racing
266
345
  // ahead of it on a faster queue.
@@ -292,6 +371,309 @@ const __scheduleMacrotask = (function () {
292
371
  }
293
372
  })()
294
373
 
374
+ // A real, *referenced* timer, for waits that must let the whole host make
375
+ // progress between looks — the async-work drain polls the addon rather than
376
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
377
+ // would spin the loop instead of yielding it. Falls back to the macrotask
378
+ // scheduler on a host without timers.
379
+ function __scheduleTimer(callback, delay) {
380
+ const setTimer = globalThis.setTimeout
381
+ if (typeof setTimer !== 'function') {
382
+ __scheduleMacrotask(callback)
383
+ return
384
+ }
385
+ try {
386
+ setTimer(callback, delay)
387
+ } catch {
388
+ __scheduleMacrotask(callback)
389
+ }
390
+ }
391
+
392
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
393
+ // reason the async-work drain uses one: this polls the addon instead of
394
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
395
+ // the loop instead of yielding it.
396
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
397
+ // Arrivals it takes before the poll paces on the host's timers alone. One
398
+ // proves nothing: a timer armed before the host's timers stopped still fires.
399
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
400
+ // How long a parked turn's own timer must already have been due before a
401
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
402
+ // against the event loop's clock, which is read once per iteration, while
403
+ // these are `Date.now()` readings taken part-way through one, so the two
404
+ // drift apart by however long the loop has been inside the current iteration.
405
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
406
+ // How long a backup itself waits. What is left of it after the slack and one
407
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
408
+ // parked turn from the last backup armed while the host's timers still
409
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
410
+ // `__armWasmRuntimePollStallBackup`.
411
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
412
+
413
+ /**
414
+ * Pacing state for one runtime-work poll.
415
+ *
416
+ * Per poll, never per module: whether the host's timers arrive is not a
417
+ * property of the module. A host can lose its timers between two disposals,
418
+ * and in the deferred shape every instance shares this module — one healthy
419
+ * instance must not disarm the fallback for the next one.
420
+ */
421
+ function __createWasmRuntimePollPace() {
422
+ return {
423
+ // Timers armed by *this* poll that have actually arrived.
424
+ arrivals: 0,
425
+ // The turn waiting on a timer alone *right now* — undefined whenever no
426
+ // turn is parked — and when that turn's own timer came due.
427
+ settleTurn: undefined,
428
+ turnTimerDueAt: 0,
429
+ }
430
+ }
431
+
432
+ /**
433
+ * The backup that ends a turn whose timer is never going to arrive.
434
+ *
435
+ * Once the poll paces on the timer alone it has nothing left to fall back on
436
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
437
+ * the turn that parks, and a parked poll schedules nothing that could notice.
438
+ * So every turn arms one of these before it yields, and each one compares due
439
+ * times instead of measuring how long the parked turn has been waiting.
440
+ *
441
+ * Invariant: a parked turn is ended by the newest backup that was armed while
442
+ * the host's timers still worked, and a backup ends a turn only when that
443
+ * turn's own timer was already due a whole window before the backup itself.
444
+ * Neither half turns on how far apart the arms happen to fall — what bounds
445
+ * the rescue is how far back that newest live backup is:
446
+ *
447
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
448
+ * turn due a whole window earlier is still parked proves that turn's timer
449
+ * was dropped rather than merely late. That same comparison is what leaves a
450
+ * healthy host alone: there the turn's timer has already run and cleared
451
+ * `settleTurn` before any backup due after it can look.
452
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
453
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
454
+ * primitives and the macrotask wins, so such a turn can end with its own
455
+ * timer — and the backup armed one line before it — already dead. The
456
+ * arrival that then flips the poll onto the timer alone can itself be a
457
+ * timer armed before the host's timers died. So the turn that parks can sit
458
+ * two turns past the last live arm, and the newest live backup is due
459
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
460
+ * Arming on every turn is what holds it to two, rather than however far back
461
+ * a throttle last let one through.
462
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
463
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
464
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
465
+ * Past that the turn stays parked and the disposal promise never settles.
466
+ * The bound is deliberate: reaching it takes a host that drops timers
467
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
468
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
469
+ * the second.
470
+ *
471
+ * The poll then goes back to arming both primitives until two fresh arrivals
472
+ * prove the timers again. A host that stops running the timers it has
473
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
474
+ * pending rather than wedging the thread — the same outcome as a blocking
475
+ * closure that never returns. Unreferenced wherever the host allows it: the
476
+ * poll's own turn timers are what keep the loop alive, never these.
477
+ */
478
+ function __armWasmRuntimePollStallBackup(pace) {
479
+ const setTimer = globalThis.setTimeout
480
+ if (typeof setTimer !== 'function') {
481
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
482
+ // already, and that one cannot park.
483
+ return
484
+ }
485
+ // Read before arming, so this never claims to be due earlier than the timer
486
+ // actually is: a backup ends a turn only when it is provably due after it.
487
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
488
+ let handle
489
+ try {
490
+ handle = setTimer(() => {
491
+ const settleTurn = pace.settleTurn
492
+ if (
493
+ !settleTurn ||
494
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
495
+ ) {
496
+ // No turn is parked, or the parked one's timer came due too close to
497
+ // this backup to call it dropped — it may still arrive, and the turn
498
+ // that armed it armed a backup due a whole window after *that*.
499
+ return
500
+ }
501
+ pace.arrivals = 0
502
+ pace.settleTurn = undefined
503
+ settleTurn()
504
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
505
+ } catch {
506
+ return
507
+ }
508
+ if (handle && typeof handle.unref === 'function') {
509
+ try {
510
+ handle.unref()
511
+ } catch {}
512
+ }
513
+ }
514
+
515
+ /**
516
+ * One turn of the runtime-work poll.
517
+ *
518
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
519
+ * missing or throws, but not when it is present, returns a handle and never
520
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
521
+ * host whose timers belong to an IO context that is already gone. That host
522
+ * would park this poll forever, and the poll is unbounded, so nothing would
523
+ * ever call `…_finish`.
524
+ *
525
+ * Arm both primitives until timers armed by this poll have arrived twice, and
526
+ * let whichever lands first end the turn; the loser resolves nothing. A host
527
+ * with working timers therefore pays the double arming for the first turn or
528
+ * two — the macrotask wins the race, but the timers behind it still arrive and
529
+ * are counted — and paces on the timer alone from then on, instead of spinning
530
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
531
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
532
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
533
+ * which ends the parked turn and puts this poll back on both.
534
+ */
535
+ function __yieldWasmRuntimePollTurn(pace) {
536
+ // Armed before the turn yields, and by every turn: what rescues a parked
537
+ // turn has to have been armed while the host's timers still worked, and the
538
+ // turn that parks is the one whose own timer is already dead.
539
+ __armWasmRuntimePollStallBackup(pace)
540
+ return new Promise((resolve) => {
541
+ let settled = false
542
+ const settle = () => {
543
+ if (settled) {
544
+ return
545
+ }
546
+ settled = true
547
+ if (pace.settleTurn === settle) {
548
+ // Nothing is parked any more: a backup running later must not read a
549
+ // due time this turn has already answered.
550
+ pace.settleTurn = undefined
551
+ }
552
+ resolve()
553
+ }
554
+ __scheduleTimer(() => {
555
+ pace.arrivals++
556
+ settle()
557
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
558
+ // Read next to the arming it describes; see
559
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
560
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
561
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
562
+ __scheduleMacrotask(settle)
563
+ return
564
+ }
565
+ // Paced by the timer alone from here; the backup is what ends this turn if
566
+ // the timer never arrives.
567
+ pace.settleTurn = settle
568
+ pace.turnTimerDueAt = turnTimerDueAt
569
+ })
570
+ }
571
+
572
+ /**
573
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
574
+ * event-loop turns in the middle.
575
+ *
576
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
577
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
578
+ * waits on is this one, the only thread that can give a running blocking
579
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
580
+ * for work that can never finish. The addon's two-phase form splits that:
581
+ * `…_begin` stops the runtime without joining and reports whether anything is
582
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
583
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
584
+ * entire point.
585
+ *
586
+ * The poll has no deadline, for the same reason the async-work drain below has
587
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
588
+ * work it would join is the work that is waiting for a turn from this thread —
589
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
590
+ * thread can no longer be reached. A blocking closure that never returns keeps
591
+ * the disposal promise pending instead, exactly as a task whose `execute` never
592
+ * returns already keeps an *undisposed* process alive. The host contract is in
593
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
594
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
595
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
596
+ *
597
+ * Feature-detected like every other export in this teardown, so an addon built
598
+ * against a napi crate that predates the split keeps the single blocking call.
599
+ * Returns nothing whenever the handshake finished without yielding, which keeps
600
+ * an idle disposal synchronous.
601
+ */
602
+ function __prepareWasmEnvCleanupWithTurns() {
603
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
604
+ return
605
+ }
606
+ const exports = __napiInstance?.exports
607
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
608
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
609
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
610
+ // No split to use. The settlement drain still follows this, so the queue
611
+ // the single call leaves behind is expected rather than lost.
612
+ __emnapiWasmEnvCleanupYielding = true
613
+ try {
614
+ __prepareWasmEnvCleanup()
615
+ } finally {
616
+ __emnapiWasmEnvCleanupYielding = false
617
+ }
618
+ return
619
+ }
620
+ const workPending = exports?.napi_wasm_runtime_work_pending
621
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
622
+ // from one of the JavaScript handlers they run is the same no-op it is inside
623
+ // the single call: the barrier is up and the runtime is mid-teardown, and
624
+ // destroying between the halves would strand exactly what this delivers.
625
+ __emnapiWasmEnvCleanupPreparing = true
626
+ let live
627
+ try {
628
+ live = begin()
629
+ } catch (error) {
630
+ __emnapiWasmEnvCleanupPreparing = false
631
+ throw error
632
+ }
633
+ __emnapiWasmEnvCleanupRan = true
634
+ const finishCleanup = () => {
635
+ if (__emnapiWasmEnvCleanupPrepared) {
636
+ // Already closed by a caller that could not yield — the 'exit' teardown
637
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
638
+ // is idempotent, but the flags it lowers are not: running it again here
639
+ // would clear a `preparing` some later barrier had raised.
640
+ return
641
+ }
642
+ __finishParkedWasmEnvCleanup = undefined
643
+ try {
644
+ finish()
645
+ } finally {
646
+ __emnapiWasmEnvCleanupPreparing = false
647
+ }
648
+ __emnapiWasmEnvCleanupPrepared = true
649
+ }
650
+ if (!live || typeof workPending !== 'function') {
651
+ finishCleanup()
652
+ return
653
+ }
654
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
655
+ // a caller that cannot yield is entitled to end this handshake itself.
656
+ __finishParkedWasmEnvCleanup = finishCleanup
657
+ return (async () => {
658
+ // Unbounded, exactly like the async-work drain below. The wait ends when
659
+ // the addon reports its runtime work finished; the turns spent here are
660
+ // what let that happen at all.
661
+ const pace = __createWasmRuntimePollPace()
662
+ for (;;) {
663
+ await __yieldWasmRuntimePollTurn(pace)
664
+ try {
665
+ if (!workPending()) {
666
+ return
667
+ }
668
+ } catch {
669
+ // A trap is the only way this fails, and a trapped instance has no
670
+ // reachable work left. Stop polling and finish.
671
+ return
672
+ }
673
+ }
674
+ })().then(finishCleanup, finishCleanup)
675
+ }
676
+
295
677
  // Turns to wait for while the addon still reports queued settlements. Reaching
296
678
  // zero is the only success. A counter still nonzero at this bound rejects the
297
679
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -428,6 +810,19 @@ function __destroyEmnapiContext() {
428
810
  }
429
811
 
430
812
  __prepareWasmEnvCleanup()
813
+ if (__isPreparingWasmEnvCleanup()) {
814
+ // Reached from inside the synchronous barrier — a promise hook one of the
815
+ // settlements above ran, which is the reentrancy the destroy wrapper
816
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
817
+ // no-op and answer `undefined`, and recording that as a completed destroy
818
+ // is what makes the frame that *did* start the barrier skip the real one
819
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
820
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
821
+ // moment it returns. The deferred loader carries the same backstop. A
822
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
823
+ // rather than skipping it.
824
+ return
825
+ }
431
826
  const result = __emnapiContext.destroy()
432
827
  if (!__isThenable(result)) {
433
828
  __emnapiContextDestroyed = true
@@ -491,6 +886,135 @@ function __keepEventLoopAliveUntil(work) {
491
886
  )
492
887
  }
493
888
 
889
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
890
+ // ends when the addon reports zero, so this only decides how promptly disposal
891
+ // notices — not how long it waits.
892
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
893
+
894
+ /**
895
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
896
+ * would strand it.
897
+ *
898
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
899
+ * it is observable from JavaScript: the threadless archive resolves
900
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
901
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
902
+ * imports nor exports those symbols and the only brackets a loader could watch
903
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
904
+ * functions. The addon is the one place both flavors go through, so it answers
905
+ * for both, through the same kind of handshake the settlement drain uses:
906
+ *
907
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
908
+ * started. Those completion callbacks run with `napi_cancelled`, which
909
+ * napi-rs turns into a promise rejected with an `AbortError`.
910
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
911
+ * callback. Work already executing refuses cancellation and stays counted
912
+ * until it finishes normally — which it can, because this runs before the
913
+ * barrier, before `Context.destroy()` and before anything is terminated.
914
+ *
915
+ * Both exports are optional: an addon built against a napi crate that predates
916
+ * them drains nothing and keeps the previous behavior, exactly as the
917
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
918
+ *
919
+ * Returns nothing when there is nothing outstanding, which keeps disposal
920
+ * synchronous in the common case. The promise it returns otherwise never
921
+ * rejects.
922
+ *
923
+ * The wait has no deadline, and that is the point: giving up would destroy the
924
+ * environment with a completion callback still owed, which is the stranding
925
+ * this exists to prevent. A task whose `execute` never returns already keeps an
926
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
927
+ * rather than inventing a bound it cannot honor.
928
+ *
929
+ * Safe to call from inside a completion callback, which is reachable: settling
930
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
931
+ * being handed back, a threadsafe-function callback — and that JavaScript can
932
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
933
+ *
934
+ * - The addon keeps a work registered until its completion callback
935
+ * *finishes*, so the count read here is at least one and this takes the
936
+ * polling path instead of declaring the environment drained and tearing it
937
+ * down from inside the frame that is still settling a promise.
938
+ * - The poll is a timer, so it cannot run until the callback has returned to
939
+ * the host — by which time that work has left the registry. The count the
940
+ * next poll reads is the one taken after the callback finished.
941
+ *
942
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
943
+ * nested call joins this disposal rather than starting a second one.
944
+ */
945
+ function __drainWasiAsyncWork() {
946
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
947
+ return __wasiAsyncWorkDrainPromise
948
+ }
949
+ const exports = __napiInstance?.exports
950
+ const pending = exports?.napi_wasm_async_work_pending
951
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
952
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
953
+ return
954
+ }
955
+
956
+ const readPending = () => {
957
+ try {
958
+ return pending()
959
+ } catch (error) {
960
+ // A trap is the only way this call fails: it reads a counter and cannot
961
+ // allocate or call back into JavaScript. A trapped instance can no longer
962
+ // run anything, so its outstanding work is unreachable by definition —
963
+ // there is nothing left to wait for, and refusing to dispose would only
964
+ // keep a dead instance and its stuck counter alive. Best-effort here is
965
+ // the honest answer, and it is what disposal did before this drain
966
+ // existed.
967
+ //
968
+ // Only a trap. Anything else means the export is not what this loader
969
+ // thinks it is, which is a defect worth surfacing rather than disposing
970
+ // over.
971
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
972
+ return 0
973
+ }
974
+ throw error
975
+ }
976
+ }
977
+
978
+ if (!readPending()) {
979
+ return
980
+ }
981
+ try {
982
+ cancelPending()
983
+ } catch {
984
+ // Cancellation is an optimization: it bounds the wait by the work already
985
+ // executing. Failing it only means waiting for the whole queue instead.
986
+ }
987
+ if (!readPending()) {
988
+ return
989
+ }
990
+
991
+ const drainPromise = __keepEventLoopAliveUntil(
992
+ (async () => {
993
+ while (readPending()) {
994
+ await new Promise((resolve) => {
995
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
996
+ })
997
+ }
998
+ })(),
999
+ ).then(
1000
+ () => {
1001
+ __wasiAsyncWorkDrainPromise = undefined
1002
+ },
1003
+ (error) => {
1004
+ // A wait that could not run is not a wait that finished. The only way
1005
+ // here is a host whose timers and macrotask primitives all refuse, and
1006
+ // the work is still outstanding — reporting success would destroy the
1007
+ // environment over it, which is the stranding this exists to prevent.
1008
+ // Reject instead: disposal stays retryable, and the context is not
1009
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1010
+ __wasiAsyncWorkDrainPromise = undefined
1011
+ throw error
1012
+ },
1013
+ )
1014
+ __wasiAsyncWorkDrainPromise = drainPromise
1015
+ return drainPromise
1016
+ }
1017
+
494
1018
  /**
495
1019
  * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
496
1020
  * thread manager performed the termination. A bare `worker.terminate()` reaches
@@ -572,11 +1096,7 @@ function __continueWasiDisposal() {
572
1096
  return __finishWasiDisposal()
573
1097
  }
574
1098
 
575
- function __startWasiDisposal() {
576
- // Run the pre-teardown barrier, then let the settlements it queued actually
577
- // reach JavaScript, and only then destroy the environment. Doing these two
578
- // back to back is what strands them.
579
- __prepareWasmEnvCleanup()
1099
+ function __drainWasmEnvForWasiDisposal() {
580
1100
  const drainResult = __drainWasmEnvCleanup()
581
1101
  if (__isThenable(drainResult)) {
582
1102
  return Promise.resolve(drainResult).then(__continueWasiDisposal)
@@ -584,6 +1104,33 @@ function __startWasiDisposal() {
584
1104
  return __continueWasiDisposal()
585
1105
  }
586
1106
 
1107
+ function __cleanUpWasmEnvForWasiDisposal() {
1108
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1109
+ // for, when the addon has one — then let the settlements it queued actually
1110
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1111
+ // these back to back is what strands them.
1112
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1113
+ if (__isThenable(prepareResult)) {
1114
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1115
+ }
1116
+ return __drainWasmEnvForWasiDisposal()
1117
+ }
1118
+
1119
+ function __startWasiDisposal() {
1120
+ // Outstanding `napi_async_work` goes first, while the environment is still
1121
+ // completely live: the completion callbacks run addon code, and everything
1122
+ // after this point takes that away from them — the barrier shuts the async
1123
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1124
+ // the pool threads removes what would have reported the work finished.
1125
+ const asyncWorkResult = __drainWasiAsyncWork()
1126
+ if (__isThenable(asyncWorkResult)) {
1127
+ return Promise.resolve(asyncWorkResult).then(
1128
+ __cleanUpWasmEnvForWasiDisposal,
1129
+ )
1130
+ }
1131
+ return __cleanUpWasmEnvForWasiDisposal()
1132
+ }
1133
+
587
1134
  /**
588
1135
  * Disposes this generated WASI binding.
589
1136
  *
@@ -725,29 +1272,79 @@ function __retainFailedWasiRollback(cleanupErrors) {
725
1272
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
726
1273
  */
727
1274
  function __rollbackWasiInitialization() {
728
- const cleanupErrors = []
729
- let drainResult
730
- let settlementsUnreached = false
1275
+ // The environment teardown this rollback performs, kept nested so it cannot
1276
+ // be reached without the async-work drain below running first.
1277
+ function __rollbackWasmEnvForWasiInitialization() {
1278
+ const cleanupErrors = []
1279
+ let prepareResult
1280
+ try {
1281
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1282
+ } catch (cleanupError) {
1283
+ cleanupErrors.push(cleanupError)
1284
+ return __retainFailedWasiRollback(cleanupErrors)
1285
+ }
1286
+ if (__isThenable(prepareResult)) {
1287
+ return Promise.resolve(prepareResult).then(
1288
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1289
+ (cleanupError) => {
1290
+ cleanupErrors.push(cleanupError)
1291
+ return __retainFailedWasiRollback(cleanupErrors)
1292
+ },
1293
+ )
1294
+ }
1295
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1296
+ }
1297
+
1298
+ // The settlement drain of the rollback above, reached either straight away or
1299
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1300
+ // did not finish never gets here: it retains instead, exactly as a drain that
1301
+ // did not finish does.
1302
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1303
+ let drainResult
1304
+ try {
1305
+ drainResult = __drainWasmEnvCleanup()
1306
+ } catch (cleanupError) {
1307
+ cleanupErrors.push(cleanupError)
1308
+ return __retainFailedWasiRollback(cleanupErrors)
1309
+ }
1310
+ if (__isThenable(drainResult)) {
1311
+ return Promise.resolve(drainResult).then(
1312
+ () => __destroyContextForWasiRollback(cleanupErrors),
1313
+ (cleanupError) => {
1314
+ cleanupErrors.push(cleanupError)
1315
+ return __retainFailedWasiRollback(cleanupErrors)
1316
+ },
1317
+ )
1318
+ }
1319
+ return __destroyContextForWasiRollback(cleanupErrors)
1320
+ }
1321
+
1322
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1323
+ // work before the load goes on to fail, and this rollback tears down exactly
1324
+ // what those completions need. Settle them while everything is still live,
1325
+ // before the barrier and the teardown above take that away.
1326
+ //
1327
+ // A drain that could not finish leaves async work possibly outstanding, and
1328
+ // destroying the context over it would strand exactly what this rollback is
1329
+ // there to settle. Stop short and retain instead — the same trade
1330
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1331
+ // the context stays reclaimable by a retry or by this flavor's own
1332
+ // last-resort teardown.
1333
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1334
+ __retainFailedWasiRollback([cleanupError])
1335
+ let asyncWorkResult
731
1336
  try {
732
- __prepareWasmEnvCleanup()
733
- drainResult = __drainWasmEnvCleanup()
1337
+ asyncWorkResult = __drainWasiAsyncWork()
734
1338
  } catch (cleanupError) {
735
- cleanupErrors.push(cleanupError)
736
- settlementsUnreached = true
1339
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
737
1340
  }
738
- if (__isThenable(drainResult)) {
739
- return Promise.resolve(drainResult).then(
740
- () => __destroyContextForWasiRollback(cleanupErrors),
741
- (cleanupError) => {
742
- cleanupErrors.push(cleanupError)
743
- return __retainFailedWasiRollback(cleanupErrors)
744
- },
1341
+ if (__isThenable(asyncWorkResult)) {
1342
+ return Promise.resolve(asyncWorkResult).then(
1343
+ __rollbackWasmEnvForWasiInitialization,
1344
+ __retainAfterAsyncWorkDrainFailure,
745
1345
  )
746
1346
  }
747
- if (settlementsUnreached) {
748
- return __retainFailedWasiRollback(cleanupErrors)
749
- }
750
- return __destroyContextForWasiRollback(cleanupErrors)
1347
+ return __rollbackWasmEnvForWasiInitialization()
751
1348
  }
752
1349
 
753
1350
  let __wasiModule
@@ -769,7 +1366,11 @@ try {
769
1366
  context: __emnapiContext,
770
1367
  asyncWorkPoolSize: __asyncWorkPoolSize,
771
1368
  reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },
772
- plugins: [__captureWasiThreadManager, __emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
1369
+ plugins: [
1370
+ __captureWasiThreadManager,
1371
+ __emnapiAsyncWorkPlugin,
1372
+ __emnapiTSFNPlugin,
1373
+ ],
773
1374
  wasi: __wasi,
774
1375
  onCreateWorker() {
775
1376
  const worker = new Worker(new URL('@rolldown/binding-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url), {