@napi-rs/cli 3.8.2 → 3.8.4

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,9 +8,16 @@ let __napiInstance
8
8
  let __emnapiContextDestroyed = false
9
9
  let __emnapiContextDestroyPromise
10
10
  let __emnapiWasmEnvCleanupPrepared = false
11
+ let __emnapiWasmEnvCleanupRan = false
12
+ let __emnapiWasmEnvCleanupDrained = false
13
+ let __emnapiWasmEnvCleanupDrainPromise
11
14
  let __wasiDisposed = false
12
15
  let __wasiDisposePromise
13
16
  let __completeWasiDisposal = function() {}
17
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
18
+ // that stopped short of destroying the context. See
19
+ // \`__rollbackWasiInitialization\`.
20
+ let __retainWasiRollbackForRetry = function() {}
14
21
 
15
22
  function __isThenable(value) {
16
23
  return (
@@ -81,10 +88,168 @@ function __prepareWasmEnvCleanup() {
81
88
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
82
89
  if (typeof prepare === 'function') {
83
90
  prepare()
91
+ __emnapiWasmEnvCleanupRan = true
84
92
  }
85
93
  __emnapiWasmEnvCleanupPrepared = true
86
94
  }
87
95
 
96
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
97
+ // on, so the drain turns below interleave with that dispatch instead of racing
98
+ // ahead of it on a faster queue.
99
+ const __scheduleMacrotask = (function () {
100
+ if (typeof setImmediate === 'function') {
101
+ return function (callback) {
102
+ setImmediate(callback)
103
+ }
104
+ }
105
+ const __MessageChannel = globalThis.MessageChannel
106
+ if (typeof __MessageChannel === 'function') {
107
+ return function (callback) {
108
+ const channel = new __MessageChannel()
109
+ channel.port1.onmessage = function () {
110
+ channel.port1.onmessage = null
111
+ try {
112
+ channel.port1.close()
113
+ } catch {}
114
+ try {
115
+ channel.port2.close()
116
+ } catch {}
117
+ callback()
118
+ }
119
+ channel.port2.postMessage(null)
120
+ }
121
+ }
122
+ return function (callback) {
123
+ setTimeout(callback, 0)
124
+ }
125
+ })()
126
+
127
+ // Turns to wait for while the addon still reports queued settlements. Reaching
128
+ // zero is the only success. A counter still nonzero at this bound rejects the
129
+ // disposal as retryable (\`ERR_NAPI_WASI_CLEANUP_PENDING\`) rather than
130
+ // destroying the context over a still-queued settlement — the wait stays
131
+ // bounded either way.
132
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
133
+ // Without \`napi_wasm_env_cleanup_pending\` the queue is not observable. Fall
134
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
135
+ // call made on this thread (two), plus a margin.
136
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
137
+
138
+ /**
139
+ * \`napi_prepare_wasm_env_cleanup\` only *queues* the promise settlements of the
140
+ * tasks it cancelled: \`napi_call_threadsafe_function\` appends to the
141
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
142
+ * macrotask — two coalescing turns later, even for a call made on this very
143
+ * thread. \`Context.destroy()\` then runs the threadsafe function's cleanup hook,
144
+ * which drains the queue with a null env and *discards* whatever is still in it.
145
+ *
146
+ * So destroying without yielding first strands exactly the promises the barrier
147
+ * exists to settle. Yield real event-loop turns until the addon reports the
148
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
149
+ * macrotask run.
150
+ *
151
+ * Returns nothing when there is nothing to wait for, which keeps disposal
152
+ * synchronous in the common case.
153
+ *
154
+ * The "already drained" flag is set only once a wait has actually finished.
155
+ * Scheduling a macrotask can fail — a host-provided or patched \`setImmediate\`
156
+ * that throws is enough — and a disposal that rejects stays retryable, so
157
+ * marking the drain complete up front would make the retry skip it and destroy
158
+ * the context with the barrier's settlements still queued.
159
+ *
160
+ * A wait that runs out of turns with the counter still nonzero rejects with
161
+ * \`ERR_NAPI_WASI_CLEANUP_PENDING\` for the same reason: at that point
162
+ * "finished" is indistinguishable from the stranding above, and destroying
163
+ * would discard the very settlement the wait was for. The rejection leaves the
164
+ * flag unset and disposal retryable.
165
+ */
166
+ function __drainWasmEnvCleanup() {
167
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
168
+ return
169
+ }
170
+ if (__emnapiWasmEnvCleanupDrainPromise) {
171
+ return __emnapiWasmEnvCleanupDrainPromise
172
+ }
173
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
174
+ const observable = typeof pending === 'function'
175
+ if (observable) {
176
+ let queued
177
+ try {
178
+ queued = pending()
179
+ } catch {
180
+ __emnapiWasmEnvCleanupDrained = true
181
+ return
182
+ }
183
+ if (!queued) {
184
+ __emnapiWasmEnvCleanupDrained = true
185
+ return
186
+ }
187
+ }
188
+ const limit = observable
189
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
190
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
191
+ const drainPromise = (async () => {
192
+ let queued = 0
193
+ for (let turn = 0; turn < limit; turn++) {
194
+ await new Promise((resolve) => {
195
+ __scheduleMacrotask(resolve)
196
+ })
197
+ if (!observable) {
198
+ continue
199
+ }
200
+ try {
201
+ queued = pending()
202
+ } catch {
203
+ return
204
+ }
205
+ if (!queued) {
206
+ return
207
+ }
208
+ }
209
+ if (!observable) {
210
+ // Blind wait: without \`napi_wasm_env_cleanup_pending\` the bound IS the
211
+ // contract — there is nothing to consult, so finishing the turns is
212
+ // finishing the drain.
213
+ return
214
+ }
215
+ // The counter is still nonzero after every turn the bound allows. The wait
216
+ // stays bounded — but claiming success here would be indistinguishable from
217
+ // the stranding this drain exists to prevent: disposal would go on to
218
+ // destroy the context, whose cleanup hook discards the still-queued
219
+ // settlement with a null env, and the promise it was for hangs forever.
220
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
221
+ // unset, dispose() (and the rollback) decline to destroy, and a later
222
+ // dispose() runs the drain again — by which time the queue has usually been
223
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
224
+ // attempt at most another bounded wait and a rejection, never a stranded
225
+ // promise; the process-exit teardown still reclaims the context.
226
+ const drainError = new Error(
227
+ 'the wasm environment still reports ' +
228
+ queued +
229
+ ' queued settlement(s) after ' +
230
+ limit +
231
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
232
+ )
233
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
234
+ throw drainError
235
+ })().then(
236
+ (value) => {
237
+ // Set only when the wait actually finished AND the queue was seen empty
238
+ // (or is unobservable): a drain that timed out with settlements still
239
+ // queued rejects above and must stay repeatable.
240
+ __emnapiWasmEnvCleanupDrained = true
241
+ __emnapiWasmEnvCleanupDrainPromise = undefined
242
+ return value
243
+ },
244
+ (error) => {
245
+ __emnapiWasmEnvCleanupDrainPromise = undefined
246
+ throw error
247
+ },
248
+ )
249
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
250
+ return drainPromise
251
+ }
252
+
88
253
  function __destroyEmnapiContext() {
89
254
  if (__emnapiContextDestroyed || __emnapiContext === undefined) {
90
255
  __emnapiContextDestroyed = true
@@ -162,7 +327,7 @@ function __finishWasiDisposal() {
162
327
  return __completeWasiDisposal()
163
328
  }
164
329
 
165
- function __startWasiDisposal() {
330
+ function __continueWasiDisposal() {
166
331
  const destroyResult = __destroyEmnapiContext()
167
332
  if (__isThenable(destroyResult)) {
168
333
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -170,6 +335,18 @@ function __startWasiDisposal() {
170
335
  return __finishWasiDisposal()
171
336
  }
172
337
 
338
+ function __startWasiDisposal() {
339
+ // Run the pre-teardown barrier, then let the settlements it queued actually
340
+ // reach JavaScript, and only then destroy the environment. Doing these two
341
+ // back to back is what strands them.
342
+ __prepareWasmEnvCleanup()
343
+ const drainResult = __drainWasmEnvCleanup()
344
+ if (__isThenable(drainResult)) {
345
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
346
+ }
347
+ return __continueWasiDisposal()
348
+ }
349
+
173
350
  /**
174
351
  * Disposes this generated WASI binding.
175
352
  *
@@ -241,8 +418,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
241
418
  return cleanupErrors
242
419
  }
243
420
 
244
- function __rollbackWasiInitialization() {
245
- const cleanupErrors = []
421
+ function __destroyContextForWasiRollback(cleanupErrors) {
246
422
  let destroyResult
247
423
  try {
248
424
  destroyResult = __destroyEmnapiContext()
@@ -259,6 +435,83 @@ function __rollbackWasiInitialization() {
259
435
  }
260
436
  return __finishWasiInitializationRollback(cleanupErrors)
261
437
  }
438
+
439
+ /**
440
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
441
+ * hands it to whatever this flavor has that can still reclaim it.
442
+ */
443
+ function __retainFailedWasiRollback(cleanupErrors) {
444
+ try {
445
+ __retainWasiRollbackForRetry()
446
+ } catch (cleanupError) {
447
+ cleanupErrors.push(cleanupError)
448
+ }
449
+ return cleanupErrors
450
+ }
451
+
452
+ /**
453
+ * Initialization can fail *after* registration has already run, and registration
454
+ * runs with a live environment: a module-init hook can start async work and then
455
+ * return an error, and the promise it created may already have escaped into
456
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
457
+ * path needs the same drain the ordinary disposal does — destroying without
458
+ * yielding discards the queue with a null env and strands the promise.
459
+ *
460
+ * Stays synchronous when nothing is queued, which covers every failure before
461
+ * \`beforeInit\`: there is no instance to run the barrier on, so nothing to drain.
462
+ *
463
+ * A barrier or drain that did *not* finish stops the rollback short of
464
+ * destroying, which is what \`dispose()\` already does — a rejected drain there
465
+ * never reaches \`__continueWasiDisposal\`. Destroying anyway is the worse of the
466
+ * two trades, and not because of what it saves:
467
+ *
468
+ * - It cannot deliver the settlements. \`Context.destroy()\` runs the
469
+ * threadsafe function's cleanup hook, which drains the queue with a null env
470
+ * and discards it, so a promise that already escaped into JavaScript hangs
471
+ * forever with nothing left that could ever settle it.
472
+ * - It saves less than it looks. \`Context.destroy()\` stops JavaScript calls
473
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
474
+ * which this module's scope holds either way. What stopping short retains is
475
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
476
+ * - Retry is not theoretical. A rollback that records a cleanup error is
477
+ * already kept in the process-wide registry above, so re-\`require()\`ing this
478
+ * file replays it instead of re-instantiating — and the \`6e15de6f\` flag fix
479
+ * means the replay drains again rather than skipping it. Destroying first is
480
+ * what makes that retained record useless.
481
+ *
482
+ * The residual cost is honest: the CJS flavor hands the context to its
483
+ * \`process.on('exit')\` teardown, so a process that never retries still reclaims
484
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
485
+ * throws while evaluating is permanently errored, so re-importing rethrows
486
+ * without re-running this file — and there the context stays until the realm
487
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
488
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
489
+ */
490
+ function __rollbackWasiInitialization() {
491
+ const cleanupErrors = []
492
+ let drainResult
493
+ let settlementsUnreached = false
494
+ try {
495
+ __prepareWasmEnvCleanup()
496
+ drainResult = __drainWasmEnvCleanup()
497
+ } catch (cleanupError) {
498
+ cleanupErrors.push(cleanupError)
499
+ settlementsUnreached = true
500
+ }
501
+ if (__isThenable(drainResult)) {
502
+ return Promise.resolve(drainResult).then(
503
+ () => __destroyContextForWasiRollback(cleanupErrors),
504
+ (cleanupError) => {
505
+ cleanupErrors.push(cleanupError)
506
+ return __retainFailedWasiRollback(cleanupErrors)
507
+ },
508
+ )
509
+ }
510
+ if (settlementsUnreached) {
511
+ return __retainFailedWasiRollback(cleanupErrors)
512
+ }
513
+ return __destroyContextForWasiRollback(cleanupErrors)
514
+ }
262
515
  `
263
516
 
264
517
  export const createWasiBrowserBinding = (
@@ -271,6 +524,10 @@ export const createWasiBrowserBinding = (
271
524
  errorEvent = false,
272
525
  threads = true,
273
526
  ) => {
527
+ // Threaded builds always get a pre-created worker pool (see
528
+ // `reuseWorkerOption` below), and pool pre-creation is asynchronous, so
529
+ // they always initialize asynchronously.
530
+ const effectiveAsyncInit = asyncInit || threads
274
531
  const fsImport = fs
275
532
  ? buffer
276
533
  ? `import { memfs, Buffer } from '@napi-rs/wasm-runtime/fs'`
@@ -317,17 +574,55 @@ const __wasi = new __WASI({
317
574
  const emnapiInjectBuffer = buffer
318
575
  ? ' __emnapiContext.features.Buffer = Buffer\n'
319
576
  : ''
320
- const emnapiInstantiateImport = asyncInit
577
+ const emnapiInstantiateImport = effectiveAsyncInit
321
578
  ? `instantiateNapiModule as __emnapiInstantiateNapiModule`
322
579
  : `instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync`
323
- const emnapiInstantiateCall = asyncInit
580
+ const emnapiInstantiateCall = effectiveAsyncInit
324
581
  ? `await __emnapiInstantiateNapiModule`
325
582
  : `__emnapiInstantiateNapiModuleSync`
583
+ // The `reuseWorker` pool is what lets addon Rust code spawn threads while
584
+ // the calling thread is blocked inside the wasm call: a browser cannot
585
+ // start a worker until the blocking thread returns to its event loop, so
586
+ // a thread spawned mid-call can never boot and the caller deadlocks
587
+ // waiting for it. With a pre-created pool, spawning is only a message to
588
+ // an already-running worker.
589
+ //
590
+ // Its size comes from `navigator.hardwareConcurrency` at runtime (logical
591
+ // cores, floored at 2, with a fallback for privacy-fuzzed or missing
592
+ // values): a constant undersizes both ends of the range — big desktops
593
+ // leave parallelism on the table, and a fuzzed "2 cores" would
594
+ // oversubscribe.
595
+ //
596
+ // The reuse pool is sized as `__asyncWorkPoolSize + __workerPoolSize`
597
+ // because emnapi's async-work pool draws its workers from the SAME reuse
598
+ // pool: the async reservation must be included or async-work
599
+ // initialization can starve the reuse pool before addon threads spawn.
600
+ //
601
+ // `strict` is deliberately NOT set. Review suggested it so exhaustion
602
+ // errors instead of allocating a fresh worker, but it breaks
603
+ // spawn-and-return workloads (e.g. `testWorkers` in examples/napi, which
604
+ // spawns workers and joins them on a helper thread): at exhaustion their
605
+ // `std::thread::spawn` panics on EAGAIN. Without `strict` the fallback
606
+ // allocates a fresh worker, which boots normally once the spawning
607
+ // parent returns to its event loop — and for joins inside a blocked
608
+ // call, the pre-created pool is what those calls draw from anyway.
609
+ const workerPoolSizeBinding = threads
610
+ ? `const __asyncWorkPoolSize = 4
611
+ const __workerPoolSize = Math.max(
612
+ 2,
613
+ globalThis.navigator?.hardwareConcurrency ?? 4,
614
+ )
615
+
616
+ `
617
+ : ''
618
+ const reuseWorkerOption = threads
619
+ ? ` reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },\n`
620
+ : ''
326
621
  const workerRuntimeImport = threads
327
622
  ? ` createOnMessage as __wasmCreateOnMessageForFsProxy,\n`
328
623
  : ''
329
624
  const memoryName = threads ? '__sharedMemory' : '__wasmMemory'
330
- const asyncWorkPoolOption = ` asyncWorkPoolSize: ${threads ? 4 : 0},
625
+ const asyncWorkPoolOption = ` asyncWorkPoolSize: ${threads ? '__asyncWorkPoolSize' : 0},
331
626
  `
332
627
  // Every build links a "basic" emnapi archive without the C async-work and
333
628
  // threadsafe-function implementations (the `emnapi-napi-rs(-mt)` archives shipped by the emnapi package), so the
@@ -380,7 +675,7 @@ const ${memoryName} = new WebAssembly.Memory({
380
675
  maximum: ${maximumMemory},
381
676
  ${threads ? ' shared: true,\n' : ''}\
382
677
  })
383
-
678
+ ${workerPoolSizeBinding}\
384
679
  let __emnapiContext
385
680
  ${emnapiContextLifecycle}
386
681
  let __wasiModule
@@ -397,6 +692,7 @@ try {
397
692
  } = ${emnapiInstantiateCall}(__wasmFile, {
398
693
  context: __emnapiContext,
399
694
  ${asyncWorkPoolOption}\
695
+ ${reuseWorkerOption}\
400
696
  ${emnapiPluginOption}\
401
697
  wasi: __wasi,
402
698
  ${workerOption}\
@@ -591,6 +887,129 @@ function __attachCleanupError(__error, __cleanupError) {
591
887
  } catch {}
592
888
  }
593
889
 
890
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
891
+ // on, so the drain turns below interleave with that dispatch instead of racing
892
+ // ahead of it on a faster queue.
893
+ const __scheduleMacrotask = (function () {
894
+ if (typeof setImmediate === 'function') {
895
+ return function (__callback) {
896
+ setImmediate(__callback)
897
+ }
898
+ }
899
+ const __MessageChannel = globalThis.MessageChannel
900
+ if (typeof __MessageChannel === 'function') {
901
+ return function (__callback) {
902
+ const __channel = new __MessageChannel()
903
+ __channel.port1.onmessage = function () {
904
+ __channel.port1.onmessage = null
905
+ try {
906
+ __channel.port1.close()
907
+ } catch {}
908
+ try {
909
+ __channel.port2.close()
910
+ } catch {}
911
+ __callback()
912
+ }
913
+ __channel.port2.postMessage(null)
914
+ }
915
+ }
916
+ return function (__callback) {
917
+ setTimeout(__callback, 0)
918
+ }
919
+ })()
920
+
921
+ // Turns to wait for while the addon still reports queued settlements. Reaching
922
+ // zero is the only success. A counter still nonzero at this bound rejects the
923
+ // disposal as retryable (\`ERR_NAPI_WASI_CLEANUP_PENDING\`) rather than
924
+ // destroying the context over a still-queued settlement — the wait stays
925
+ // bounded either way.
926
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
927
+ // Without \`napi_wasm_env_cleanup_pending\` the queue is not observable. Fall
928
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
929
+ // call made on this thread (two), plus a margin.
930
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
931
+
932
+ /**
933
+ * \`napi_prepare_wasm_env_cleanup\` only *queues* the promise settlements of the
934
+ * tasks it cancelled: \`napi_call_threadsafe_function\` appends to the
935
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
936
+ * macrotask — two coalescing turns later, even for a call made on this very
937
+ * thread. \`Context.destroy()\` then runs the threadsafe function's cleanup hook,
938
+ * which drains the queue with a null env and *discards* whatever is still in it.
939
+ *
940
+ * So destroying without yielding first strands exactly the promises the barrier
941
+ * exists to settle. Yield real event-loop turns until the addon reports the
942
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
943
+ * macrotask run.
944
+ *
945
+ * Returns nothing when there is nothing to wait for, which keeps disposal
946
+ * synchronous in the common case.
947
+ */
948
+ function __drainWasmEnvCleanup(__instance) {
949
+ const __pending = __instance?.exports.napi_wasm_env_cleanup_pending
950
+ const __observable = typeof __pending === 'function'
951
+ if (__observable) {
952
+ let __queued
953
+ try {
954
+ __queued = __pending()
955
+ } catch {
956
+ return
957
+ }
958
+ if (!__queued) {
959
+ return
960
+ }
961
+ }
962
+ const __limit = __observable
963
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
964
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
965
+ return (async () => {
966
+ let __queued = 0
967
+ for (let __turn = 0; __turn < __limit; __turn++) {
968
+ await new Promise((resolve) => {
969
+ __scheduleMacrotask(resolve)
970
+ })
971
+ if (!__observable) {
972
+ continue
973
+ }
974
+ try {
975
+ __queued = __pending()
976
+ } catch {
977
+ return
978
+ }
979
+ if (!__queued) {
980
+ return
981
+ }
982
+ }
983
+ if (!__observable) {
984
+ // Blind wait: without \`napi_wasm_env_cleanup_pending\` the bound IS the
985
+ // contract — there is nothing to consult, so finishing the turns is
986
+ // finishing the drain.
987
+ return
988
+ }
989
+ // The counter is still nonzero after every turn the bound allows. The wait
990
+ // stays bounded — but claiming success here would be indistinguishable from
991
+ // the stranding this drain exists to prevent: disposal would go on to
992
+ // destroy the context, whose cleanup hook discards the still-queued
993
+ // settlement with a null env, and the promise it was for hangs forever.
994
+ // Reject instead, as a retryable cleanup failure: \`__prepareForDisposal\`
995
+ // leaves its drained flag unset, dispose() (and the instantiation-failure
996
+ // path) decline to destroy, and a later dispose() runs the drain again — by
997
+ // which time the queue has usually been delivered. A counter that is
998
+ // somehow stuck nonzero therefore costs each attempt at most another
999
+ // bounded wait and a rejection, never a stranded promise; the managed
1000
+ // beforeExit destroyer still reclaims the context.
1001
+ const __drainError = new Error(
1002
+ 'the wasm environment still reports ' +
1003
+ __queued +
1004
+ ' queued settlement(s) after ' +
1005
+ __limit +
1006
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
1007
+ )
1008
+ __drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
1009
+ throw __drainError
1010
+ })()
1011
+ }
1012
+
594
1013
  function __createLifecycleReentryError(__operation) {
595
1014
  const __error = new Error(
596
1015
  __operation +
@@ -995,6 +1414,64 @@ async function __createInstance(
995
1414
  let __destroyOwnedContext
996
1415
  let __destroyManagedOwnedContext
997
1416
  let __napiInstance
1417
+ let __wasmEnvCleanupRan = false
1418
+ let __wasmEnvCleanupPrepared = false
1419
+ let __wasmEnvCleanupDrained = false
1420
+ let __wasmEnvCleanupDrainPromise
1421
+ const __prepareEnvCleanup = () => {
1422
+ if (__wasmEnvCleanupPrepared) {
1423
+ return
1424
+ }
1425
+ const __prepareWasmEnvCleanup =
1426
+ __napiInstance?.exports.napi_prepare_wasm_env_cleanup
1427
+ if (typeof __prepareWasmEnvCleanup === 'function') {
1428
+ __prepareWasmEnvCleanup()
1429
+ __wasmEnvCleanupRan = true
1430
+ }
1431
+ __wasmEnvCleanupPrepared = true
1432
+ }
1433
+ // The barrier + settlement drain, hoisted out of the context destroyer so the
1434
+ // drain can yield without widening the destroyer's reentry window. Both
1435
+ // yielding paths run it — dispose() and the initialization-failure rollback.
1436
+ // The destroyer still runs the barrier itself (idempotently) for the one path
1437
+ // that cannot yield: managed beforeExit cleanup of an instance whose rollback
1438
+ // is being retried.
1439
+ //
1440
+ // "Drained" is recorded only once a wait has actually finished. Scheduling a
1441
+ // macrotask can fail — a host-provided or patched \`setImmediate\` that throws
1442
+ // is enough — and dispose() stays retryable after it rejects, so marking the
1443
+ // drain complete up front would make the retry skip it and destroy the context
1444
+ // with the barrier's settlements still queued.
1445
+ const __prepareForDisposal = () => {
1446
+ if (__wasmEnvCleanupDrained) {
1447
+ return
1448
+ }
1449
+ if (__wasmEnvCleanupDrainPromise) {
1450
+ return __wasmEnvCleanupDrainPromise
1451
+ }
1452
+ __prepareEnvCleanup()
1453
+ if (!__wasmEnvCleanupRan) {
1454
+ return
1455
+ }
1456
+ const __drained = __drainWasmEnvCleanup(__napiInstance)
1457
+ if (!__drained || typeof __drained.then !== 'function') {
1458
+ __wasmEnvCleanupDrained = true
1459
+ return
1460
+ }
1461
+ const __tracked = __drained.then(
1462
+ (__value) => {
1463
+ __wasmEnvCleanupDrained = true
1464
+ __wasmEnvCleanupDrainPromise = undefined
1465
+ return __value
1466
+ },
1467
+ (__error) => {
1468
+ __wasmEnvCleanupDrainPromise = undefined
1469
+ throw __error
1470
+ },
1471
+ )
1472
+ __wasmEnvCleanupDrainPromise = __tracked
1473
+ return __tracked
1474
+ }
998
1475
  const __destroyBeforeExit = __beforeExitDestroy
999
1476
  ? async () => {
1000
1477
  if (__lifecycleState === 'failed') {
@@ -1020,13 +1497,7 @@ async function __createInstance(
1020
1497
  destroy,
1021
1498
  destroyForModuleLifecycle,
1022
1499
  registerCleanup: __registerCleanup,
1023
- } = await __createManagedEmnapiContext(() => {
1024
- const __prepareWasmEnvCleanup =
1025
- __napiInstance?.exports.napi_prepare_wasm_env_cleanup
1026
- if (typeof __prepareWasmEnvCleanup === 'function') {
1027
- __prepareWasmEnvCleanup()
1028
- }
1029
- })
1500
+ } = await __createManagedEmnapiContext(__prepareEnvCleanup)
1030
1501
  __destroyEmnapiContext = destroy
1031
1502
  __destroyOwnedContext = () => __destroyEmnapiContext()
1032
1503
  __destroyManagedOwnedContext = destroyForModuleLifecycle
@@ -1072,6 +1543,13 @@ ${emnapiInjectBuffer}\
1072
1543
  if (__lifecycleState !== 'failed') {
1073
1544
  __lifecycleState = 'disposal'
1074
1545
  }
1546
+ // Settle what the barrier cancelled before the environment stops
1547
+ // accepting JavaScript calls. Undefined unless something is queued, so
1548
+ // an idle disposal is not delayed by a single turn.
1549
+ const __drained = __prepareForDisposal()
1550
+ if (__drained) {
1551
+ await __drained
1552
+ }
1075
1553
  return __beforeExitDestroy
1076
1554
  ? __destroyManagedOwnedContext()
1077
1555
  : __destroyOwnedContext()
@@ -1079,6 +1557,23 @@ ${emnapiInjectBuffer}\
1079
1557
  }
1080
1558
  } catch (error) {
1081
1559
  __lifecycleState = 'failed'
1560
+ // Instantiation can fail *after* registration has run, and registration runs
1561
+ // with a live environment: a module-init hook can start async work and then
1562
+ // return an error, and the promise it created may already have escaped into
1563
+ // JavaScript. Settle what the barrier cancels before the context is
1564
+ // destroyed, exactly like dispose() does; destroying without yielding
1565
+ // discards the queue with a null env. Undefined unless something is queued,
1566
+ // so a failure before beforeInit costs no extra turn.
1567
+ let __settlementsUnreached = false
1568
+ try {
1569
+ const __drained = __prepareForDisposal()
1570
+ if (__drained) {
1571
+ await __drained
1572
+ }
1573
+ } catch (drainError) {
1574
+ __attachCleanupError(error, drainError)
1575
+ __settlementsUnreached = true
1576
+ }
1082
1577
  let __registrationError
1083
1578
  let __registrationFailed = false
1084
1579
  if (!__beforeExitDestroy) {
@@ -1092,6 +1587,25 @@ ${emnapiInjectBuffer}\
1092
1587
  __registrationFailed = true
1093
1588
  }
1094
1589
  }
1590
+ if (__settlementsUnreached) {
1591
+ // The barrier or the drain did not finish, so the settlements it queued
1592
+ // are still in the threadsafe-function queue. Destroying now runs the
1593
+ // cleanup hook that drains that queue with a null env and discards it,
1594
+ // stranding a promise that already escaped into JavaScript — with nothing
1595
+ // left that could ever settle it. dispose() refuses to destroy for exactly
1596
+ // this reason (a rejected drain there never reaches the destroy), so this
1597
+ // path refuses too.
1598
+ //
1599
+ // Nothing leaks. The registration just above — and, for the singleton, the
1600
+ // one made before instantiation — leaves this context in
1601
+ // \`__managedEmnapiContextDestroyers\`, so beforeExit destroys it and
1602
+ // dispose() can retry it. Only the destruction is deferred, and the turns
1603
+ // that pass in the meantime are exactly what the queue needed.
1604
+ try {
1605
+ __registerManagedBeforeExitListener()
1606
+ } catch {}
1607
+ throw error
1608
+ }
1095
1609
  try {
1096
1610
  await __destroyManagedOwnedContext()
1097
1611
  } catch (disposeError) {
@@ -1646,10 +2160,18 @@ function __removeWasiExitListener() {
1646
2160
 
1647
2161
  function __disposeWasiBindingAtExit() {
1648
2162
  __wasiExitListenerRegistered = false
2163
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
2164
+ // settlements the way __startWasiDisposal does — the process is leaving and
2165
+ // those promises have no observer left anyway. Run the synchronous teardown
2166
+ // directly. Every step is idempotent, which also makes this the synchronous
2167
+ // finish for a disposal that is still waiting for its drain.
1649
2168
  try {
1650
- const result = __disposeWasiBinding()
1651
- if (__isThenable(result)) {
1652
- void Promise.resolve(result).catch(() => {})
2169
+ __destroyEmnapiContext()
2170
+ } catch {}
2171
+ try {
2172
+ const workerResult = __terminateWasiWorkers()
2173
+ if (__isThenable(workerResult)) {
2174
+ void Promise.resolve(workerResult).catch(() => {})
1653
2175
  }
1654
2176
  } catch {}
1655
2177
  }
@@ -1665,6 +2187,13 @@ function __registerWasiExitListener() {
1665
2187
  }
1666
2188
 
1667
2189
  __completeWasiDisposal = __removeWasiExitListener
2190
+ // A rollback that could not reach the queued settlements keeps the context so
2191
+ // the registry replay above can retry it. Nothing forces that replay to happen,
2192
+ // so hand the context to the same synchronous teardown a successful load uses:
2193
+ // a process that exits without ever retrying still runs the cleanup hooks. The
2194
+ // handler cannot yield, so it does not settle anything — but by then the process
2195
+ // is leaving and those promises have no observer left anyway.
2196
+ __retainWasiRollbackForRetry = __registerWasiExitListener
1668
2197
 
1669
2198
  function __captureEmnapiAutoDestroyListener() {
1670
2199
  if (