@rolldown/binding-wasm32-wasi 1.2.8 → 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.
@@ -8,6 +8,55 @@ import {
8
8
  import { createContext as __emnapiCreateContext } from '@emnapi/runtime'
9
9
  import { memfs } from '@napi-rs/wasm-runtime/fs'
10
10
 
11
+ export const __napiBindingTarget = 'wasm32-wasi'
12
+ function __napiStampBindingTarget(exportsObject, target) {
13
+ if (
14
+ Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
15
+ ) {
16
+ if (exportsObject.__napiBindingTarget === target) {
17
+ // Already ours: the root entry aliases the object it loaded, so a WASI
18
+ // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
19
+ // is a generated loader — arrives already stamped with this same value.
20
+ return target
21
+ }
22
+ const error = new Error(
23
+ '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
24
+ )
25
+ error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
26
+ throw error
27
+ }
28
+ if (!Object.isExtensible(exportsObject)) {
29
+ // A `#[napi(module_exports)]` hook may seal or freeze this object
30
+ // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
31
+ // never a reason to fail an otherwise successful load, so the stamp is
32
+ // skipped. What a consumer still sees then follows the entry point: the
33
+ // browser and deferred loaders declare `__napiBindingTarget` at module
34
+ // level and go on reporting it, while the CommonJS entries hand back this
35
+ // very object as `module.exports`, so there the value is absent.
36
+ return target
37
+ }
38
+ try {
39
+ // [[Define]], not [[Set]]: an ordinary assignment walks the prototype
40
+ // chain, so an inherited accessor could swallow the value or throw and
41
+ // fail an otherwise successful load. The descriptor is what a successful
42
+ // assignment would have produced.
43
+ Object.defineProperty(exportsObject, '__napiBindingTarget', {
44
+ configurable: true,
45
+ enumerable: true,
46
+ value: target,
47
+ writable: true,
48
+ })
49
+ } catch {
50
+ // Same rule as the non-extensible skip above: reporting the artifact is
51
+ // metadata, never a reason to fail an otherwise successful load. An exotic
52
+ // object (a Proxy whose defineProperty trap refuses) is skipped, not
53
+ // thrown over.
54
+ }
55
+ // The CommonJS loaders assign this return value so `cjs-module-lexer` — and
56
+ // therefore Node's CJS -> ESM named export detection — can see
57
+ // `__napiBindingTarget` statically.
58
+ return target
59
+ }
11
60
 
12
61
  export const { fs: __fs, vol: __volume } = memfs()
13
62
 
@@ -48,20 +97,65 @@ let __emnapiContext
48
97
 
49
98
  const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
50
99
  const __wasiWorkers = new Set()
100
+ // The thread manager has to be reachable *before* anything that can throw
101
+ // during load or registration. Initialization can fail after the pool has
102
+ // already spawned workers, and the rollback still has to mark their
103
+ // terminations as expected — but `__napiModule` is assigned only when
104
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
105
+ // plugin factory runs while the emnapi module is being created, before the
106
+ // wasm is loaded and before any registration function runs, and its context
107
+ // carries the very same manager instance.
108
+ let __wasiThreadManager
109
+
110
+ function __captureWasiThreadManager(context) {
111
+ if (context && context.PThread) {
112
+ __wasiThreadManager = context.PThread
113
+ }
114
+ return {}
115
+ }
116
+
117
+ function __getWasiThreadManager() {
118
+ const manager =
119
+ __wasiThreadManager !== undefined
120
+ ? __wasiThreadManager
121
+ : __napiModule
122
+ ? __napiModule.PThread
123
+ : undefined
124
+ if (manager && typeof manager.terminateWorker === 'function') {
125
+ return manager
126
+ }
127
+ return undefined
128
+ }
51
129
  let __napiInstance
52
130
  let __emnapiContextDestroyed = false
53
131
  let __emnapiContextDestroyPromise
54
132
  let __emnapiWasmEnvCleanupPrepared = false
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
55
148
  let __emnapiWasmEnvCleanupRan = false
56
149
  let __emnapiWasmEnvCleanupDrained = false
57
150
  let __emnapiWasmEnvCleanupDrainPromise
58
151
  let __wasiDisposed = false
152
+ let __wasiAsyncWorkDrainPromise
59
153
  let __wasiDisposePromise
60
- let __completeWasiDisposal = function() {}
154
+ let __completeWasiDisposal = function () {}
61
155
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
62
156
  // that stopped short of destroying the context. See
63
157
  // `__rollbackWasiInitialization`.
64
- let __retainWasiRollbackForRetry = function() {}
158
+ let __retainWasiRollbackForRetry = function () {}
65
159
 
66
160
  function __isThenable(value) {
67
161
  return (
@@ -125,18 +219,127 @@ function __attachCleanupErrors(error, cleanupErrors) {
125
219
  return aggregate
126
220
  }
127
221
 
222
+ function __wrapEmnapiContextDestroyForSettlement(
223
+ context,
224
+ prepareEnvCleanup,
225
+ isPreparingEnvCleanup,
226
+ ) {
227
+ let destroy
228
+ try {
229
+ destroy = context.destroy
230
+ } catch {
231
+ return context
232
+ }
233
+ if (typeof destroy !== 'function') {
234
+ return context
235
+ }
236
+ try {
237
+ Object.defineProperty(context, 'destroy', {
238
+ configurable: true,
239
+ enumerable: false,
240
+ writable: true,
241
+ value: function () {
242
+ // Reentered from a promise hook that fired inside the barrier: the
243
+ // frame running it destroys as soon as it returns.
244
+ if (isPreparingEnvCleanup?.()) {
245
+ return
246
+ }
247
+ prepareEnvCleanup?.()
248
+ return Reflect.apply(destroy, this, arguments)
249
+ },
250
+ })
251
+ } catch {}
252
+ return context
253
+ }
254
+
255
+ function __isPreparingWasmEnvCleanup() {
256
+ return __emnapiWasmEnvCleanupPreparing
257
+ }
258
+
128
259
  function __prepareWasmEnvCleanup() {
129
260
  if (__emnapiWasmEnvCleanupPrepared) {
130
261
  return
131
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) {
278
+ return
279
+ }
132
280
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
133
281
  if (typeof prepare === 'function') {
134
- prepare()
282
+ // The addon settles the promises it cancels synchronously, under a
283
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
284
+ // here must not reach this export again.
285
+ __emnapiWasmEnvCleanupPreparing = true
286
+ try {
287
+ prepare()
288
+ } finally {
289
+ __emnapiWasmEnvCleanupPreparing = false
290
+ }
135
291
  __emnapiWasmEnvCleanupRan = true
292
+ __reportUnreachedWasmEnvSettlements()
136
293
  }
137
294
  __emnapiWasmEnvCleanupPrepared = true
138
295
  }
139
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
+
140
343
  // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
141
344
  // on, so the drain turns below interleave with that dispatch instead of racing
142
345
  // ahead of it on a faster queue.
@@ -168,6 +371,309 @@ const __scheduleMacrotask = (function () {
168
371
  }
169
372
  })()
170
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
+
171
677
  // Turns to wait for while the addon still reports queued settlements. Reaching
172
678
  // zero is the only success. A counter still nonzero at this bound rejects the
173
679
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -304,6 +810,19 @@ function __destroyEmnapiContext() {
304
810
  }
305
811
 
306
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
+ }
307
826
  const result = __emnapiContext.destroy()
308
827
  if (!__isThenable(result)) {
309
828
  __emnapiContextDestroyed = true
@@ -324,13 +843,209 @@ function __destroyEmnapiContext() {
324
843
  return destroyPromise
325
844
  }
326
845
 
846
+ /**
847
+ * Holds the event loop open until `work` settles.
848
+ *
849
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
850
+ * binding cannot keep a process alive, and referencing them again for the
851
+ * termination does not hold either — emnapi unreferences a worker the moment it
852
+ * reports `async-thread-ready`, which for a worker that was still starting
853
+ * lands *after* the termination began. Without a handle of its own, an
854
+ * `await dispose()` with nothing else pending exits the process with its
855
+ * promise unsettled, and everything after the `await` is skipped.
856
+ *
857
+ * The timer is cleared as soon as the work settles, so this never outlives the
858
+ * disposal that asked for it.
859
+ */
860
+ function __keepEventLoopAliveUntil(work) {
861
+ const setTimer = globalThis.setInterval
862
+ const clearTimer = globalThis.clearInterval
863
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
864
+ return work
865
+ }
866
+ let timer
867
+ try {
868
+ timer = setTimer(function () {}, 50)
869
+ } catch {
870
+ return work
871
+ }
872
+ const release = function () {
873
+ try {
874
+ clearTimer(timer)
875
+ } catch {}
876
+ }
877
+ return work.then(
878
+ (value) => {
879
+ release()
880
+ return value
881
+ },
882
+ (error) => {
883
+ release()
884
+ throw error
885
+ },
886
+ )
887
+ }
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
+
1018
+ /**
1019
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1020
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1021
+ * the manager's `exit` listener instead, which reports
1022
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1023
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1024
+ * promise, so disposal never settles and the process dies with an uncaught
1025
+ * exception. Mark the termination through the manager first.
1026
+ *
1027
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1028
+ * the initialization rollback runs on the one path where instantiation never
1029
+ * returned, so `__napiModule` is still undefined there while the workers it
1030
+ * spawned are already registered and loaded.
1031
+ *
1032
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1033
+ */
327
1034
  function __terminateWasiWorkers() {
328
1035
  const cleanupErrors = []
329
1036
  const pending = []
1037
+ const threadManager = __getWasiThreadManager()
330
1038
 
331
1039
  for (const worker of __wasiWorkers) {
332
1040
  let result
333
1041
  try {
1042
+ if (threadManager) {
1043
+ threadManager.terminateWorker(worker)
1044
+ // `terminateWorker` leaves behind a reporter that logs every message
1045
+ // still queued on the port, which Node flushes on exit. Nothing is
1046
+ // listening for those any more.
1047
+ worker.onmessage = undefined
1048
+ }
334
1049
  result = worker.terminate()
335
1050
  } catch (error) {
336
1051
  cleanupErrors.push(error)
@@ -360,7 +1075,9 @@ function __terminateWasiWorkers() {
360
1075
  )
361
1076
  }
362
1077
  }
363
- return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
1078
+ return pending.length > 0
1079
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1080
+ : finish()
364
1081
  }
365
1082
 
366
1083
  function __finishWasiDisposal() {
@@ -379,11 +1096,7 @@ function __continueWasiDisposal() {
379
1096
  return __finishWasiDisposal()
380
1097
  }
381
1098
 
382
- function __startWasiDisposal() {
383
- // Run the pre-teardown barrier, then let the settlements it queued actually
384
- // reach JavaScript, and only then destroy the environment. Doing these two
385
- // back to back is what strands them.
386
- __prepareWasmEnvCleanup()
1099
+ function __drainWasmEnvForWasiDisposal() {
387
1100
  const drainResult = __drainWasmEnvCleanup()
388
1101
  if (__isThenable(drainResult)) {
389
1102
  return Promise.resolve(drainResult).then(__continueWasiDisposal)
@@ -391,6 +1104,33 @@ function __startWasiDisposal() {
391
1104
  return __continueWasiDisposal()
392
1105
  }
393
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
+
394
1134
  /**
395
1135
  * Disposes this generated WASI binding.
396
1136
  *
@@ -532,36 +1272,90 @@ function __retainFailedWasiRollback(cleanupErrors) {
532
1272
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
533
1273
  */
534
1274
  function __rollbackWasiInitialization() {
535
- const cleanupErrors = []
536
- let drainResult
537
- 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
538
1336
  try {
539
- __prepareWasmEnvCleanup()
540
- drainResult = __drainWasmEnvCleanup()
1337
+ asyncWorkResult = __drainWasiAsyncWork()
541
1338
  } catch (cleanupError) {
542
- cleanupErrors.push(cleanupError)
543
- settlementsUnreached = true
1339
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
544
1340
  }
545
- if (__isThenable(drainResult)) {
546
- return Promise.resolve(drainResult).then(
547
- () => __destroyContextForWasiRollback(cleanupErrors),
548
- (cleanupError) => {
549
- cleanupErrors.push(cleanupError)
550
- return __retainFailedWasiRollback(cleanupErrors)
551
- },
1341
+ if (__isThenable(asyncWorkResult)) {
1342
+ return Promise.resolve(asyncWorkResult).then(
1343
+ __rollbackWasmEnvForWasiInitialization,
1344
+ __retainAfterAsyncWorkDrainFailure,
552
1345
  )
553
1346
  }
554
- if (settlementsUnreached) {
555
- return __retainFailedWasiRollback(cleanupErrors)
556
- }
557
- return __destroyContextForWasiRollback(cleanupErrors)
1347
+ return __rollbackWasmEnvForWasiInitialization()
558
1348
  }
559
1349
 
560
1350
  let __wasiModule
561
1351
  let __napiModule
562
1352
 
563
1353
  try {
564
- __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
1354
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1355
+ __emnapiCreateContext({ autoDestroy: false }),
1356
+ __prepareWasmEnvCleanup,
1357
+ __isPreparingWasmEnvCleanup,
1358
+ )
565
1359
  __emnapiContext.suppressDestroy()
566
1360
 
567
1361
  ;({
@@ -572,7 +1366,11 @@ try {
572
1366
  context: __emnapiContext,
573
1367
  asyncWorkPoolSize: __asyncWorkPoolSize,
574
1368
  reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },
575
- plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
1369
+ plugins: [
1370
+ __captureWasiThreadManager,
1371
+ __emnapiAsyncWorkPlugin,
1372
+ __emnapiTSFNPlugin,
1373
+ ],
576
1374
  wasi: __wasi,
577
1375
  onCreateWorker() {
578
1376
  const worker = new Worker(new URL('@rolldown/binding-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url), {
@@ -616,6 +1414,12 @@ try {
616
1414
  },
617
1415
  }))
618
1416
  __publishWasiDispose(__napiModule.exports)
1417
+ // The default export hands out this object; a named module export does not
1418
+ // travel with it, so carry the marker on the binding itself too. After the
1419
+ // host install, which hands the same object to addon-provided registration
1420
+ // functions that may put anything on it, and inside this `try`, so a claimed
1421
+ // name fails the load through the rollback below rather than past it.
1422
+ __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
619
1423
  } catch (error) {
620
1424
  const cleanupErrors = await __rollbackWasiInitialization()
621
1425
  throw __attachCleanupErrors(error, cleanupErrors)
@@ -670,6 +1474,7 @@ export const BindingWatcherEvent = __napiModule.exports.BindingWatcherEvent
670
1474
  export const ParallelJsPluginRegistry = __napiModule.exports.ParallelJsPluginRegistry
671
1475
  export const TraceSubscriberGuard = __napiModule.exports.TraceSubscriberGuard
672
1476
  export const TsconfigCache = __napiModule.exports.TsconfigCache
1477
+ export const __internalForcePanic = __napiModule.exports.__internalForcePanic
673
1478
  export const BindingAttachDebugInfo = __napiModule.exports.BindingAttachDebugInfo
674
1479
  export const BindingBuiltinPluginName = __napiModule.exports.BindingBuiltinPluginName
675
1480
  export const BindingChunkModuleOrderBy = __napiModule.exports.BindingChunkModuleOrderBy