@oxc-minify/binding-wasm32-wasi 0.150.0 → 0.151.0

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
 
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
  const __wasi = new __WASI({
13
62
  version: 'preview1',
@@ -42,14 +91,45 @@ let __emnapiContext
42
91
 
43
92
  const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
44
93
  const __wasiWorkers = new Set()
94
+ // The thread manager has to be reachable *before* anything that can throw
95
+ // during load or registration. Initialization can fail after the pool has
96
+ // already spawned workers, and the rollback still has to mark their
97
+ // terminations as expected — but `__napiModule` is assigned only when
98
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
99
+ // plugin factory runs while the emnapi module is being created, before the
100
+ // wasm is loaded and before any registration function runs, and its context
101
+ // carries the very same manager instance.
102
+ let __wasiThreadManager
103
+
104
+ function __captureWasiThreadManager(context) {
105
+ if (context && context.PThread) {
106
+ __wasiThreadManager = context.PThread
107
+ }
108
+ return {}
109
+ }
110
+
111
+ function __getWasiThreadManager() {
112
+ const manager =
113
+ __wasiThreadManager !== undefined
114
+ ? __wasiThreadManager
115
+ : __napiModule
116
+ ? __napiModule.PThread
117
+ : undefined
118
+ if (manager && typeof manager.terminateWorker === 'function') {
119
+ return manager
120
+ }
121
+ return undefined
122
+ }
45
123
  let __napiInstance
46
124
  let __emnapiContextDestroyed = false
47
125
  let __emnapiContextDestroyPromise
48
126
  let __emnapiWasmEnvCleanupPrepared = false
127
+ let __emnapiWasmEnvCleanupPreparing = false
49
128
  let __emnapiWasmEnvCleanupRan = false
50
129
  let __emnapiWasmEnvCleanupDrained = false
51
130
  let __emnapiWasmEnvCleanupDrainPromise
52
131
  let __wasiDisposed = false
132
+ let __wasiAsyncWorkDrainPromise
53
133
  let __wasiDisposePromise
54
134
  let __completeWasiDisposal = function () {}
55
135
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
@@ -119,13 +199,58 @@ function __attachCleanupErrors(error, cleanupErrors) {
119
199
  return aggregate
120
200
  }
121
201
 
202
+ function __wrapEmnapiContextDestroyForSettlement(
203
+ context,
204
+ prepareEnvCleanup,
205
+ isPreparingEnvCleanup,
206
+ ) {
207
+ let destroy
208
+ try {
209
+ destroy = context.destroy
210
+ } catch {
211
+ return context
212
+ }
213
+ if (typeof destroy !== 'function') {
214
+ return context
215
+ }
216
+ try {
217
+ Object.defineProperty(context, 'destroy', {
218
+ configurable: true,
219
+ enumerable: false,
220
+ writable: true,
221
+ value: function () {
222
+ // Reentered from a promise hook that fired inside the barrier: the
223
+ // frame running it destroys as soon as it returns.
224
+ if (isPreparingEnvCleanup?.()) {
225
+ return
226
+ }
227
+ prepareEnvCleanup?.()
228
+ return Reflect.apply(destroy, this, arguments)
229
+ },
230
+ })
231
+ } catch {}
232
+ return context
233
+ }
234
+
235
+ function __isPreparingWasmEnvCleanup() {
236
+ return __emnapiWasmEnvCleanupPreparing
237
+ }
238
+
122
239
  function __prepareWasmEnvCleanup() {
123
- if (__emnapiWasmEnvCleanupPrepared) {
240
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
124
241
  return
125
242
  }
126
243
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
127
244
  if (typeof prepare === 'function') {
128
- prepare()
245
+ // The addon settles the promises it cancels synchronously, under a
246
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
247
+ // here must not reach this export again.
248
+ __emnapiWasmEnvCleanupPreparing = true
249
+ try {
250
+ prepare()
251
+ } finally {
252
+ __emnapiWasmEnvCleanupPreparing = false
253
+ }
129
254
  __emnapiWasmEnvCleanupRan = true
130
255
  }
131
256
  __emnapiWasmEnvCleanupPrepared = true
@@ -162,6 +287,24 @@ const __scheduleMacrotask = (function () {
162
287
  }
163
288
  })()
164
289
 
290
+ // A real, *referenced* timer, for waits that must let the whole host make
291
+ // progress between looks — the async-work drain polls the addon rather than
292
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
293
+ // would spin the loop instead of yielding it. Falls back to the macrotask
294
+ // scheduler on a host without timers.
295
+ function __scheduleTimer(callback, delay) {
296
+ const setTimer = globalThis.setTimeout
297
+ if (typeof setTimer !== 'function') {
298
+ __scheduleMacrotask(callback)
299
+ return
300
+ }
301
+ try {
302
+ setTimer(callback, delay)
303
+ } catch {
304
+ __scheduleMacrotask(callback)
305
+ }
306
+ }
307
+
165
308
  // Turns to wait for while the addon still reports queued settlements. Reaching
166
309
  // zero is the only success. A counter still nonzero at this bound rejects the
167
310
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -318,13 +461,209 @@ function __destroyEmnapiContext() {
318
461
  return destroyPromise
319
462
  }
320
463
 
464
+ /**
465
+ * Holds the event loop open until `work` settles.
466
+ *
467
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
468
+ * binding cannot keep a process alive, and referencing them again for the
469
+ * termination does not hold either — emnapi unreferences a worker the moment it
470
+ * reports `async-thread-ready`, which for a worker that was still starting
471
+ * lands *after* the termination began. Without a handle of its own, an
472
+ * `await dispose()` with nothing else pending exits the process with its
473
+ * promise unsettled, and everything after the `await` is skipped.
474
+ *
475
+ * The timer is cleared as soon as the work settles, so this never outlives the
476
+ * disposal that asked for it.
477
+ */
478
+ function __keepEventLoopAliveUntil(work) {
479
+ const setTimer = globalThis.setInterval
480
+ const clearTimer = globalThis.clearInterval
481
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
482
+ return work
483
+ }
484
+ let timer
485
+ try {
486
+ timer = setTimer(function () {}, 50)
487
+ } catch {
488
+ return work
489
+ }
490
+ const release = function () {
491
+ try {
492
+ clearTimer(timer)
493
+ } catch {}
494
+ }
495
+ return work.then(
496
+ (value) => {
497
+ release()
498
+ return value
499
+ },
500
+ (error) => {
501
+ release()
502
+ throw error
503
+ },
504
+ )
505
+ }
506
+
507
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
508
+ // ends when the addon reports zero, so this only decides how promptly disposal
509
+ // notices — not how long it waits.
510
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
511
+
512
+ /**
513
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
514
+ * would strand it.
515
+ *
516
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
517
+ * it is observable from JavaScript: the threadless archive resolves
518
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
519
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
520
+ * imports nor exports those symbols and the only brackets a loader could watch
521
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
522
+ * functions. The addon is the one place both flavors go through, so it answers
523
+ * for both, through the same kind of handshake the settlement drain uses:
524
+ *
525
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
526
+ * started. Those completion callbacks run with `napi_cancelled`, which
527
+ * napi-rs turns into a promise rejected with an `AbortError`.
528
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
529
+ * callback. Work already executing refuses cancellation and stays counted
530
+ * until it finishes normally — which it can, because this runs before the
531
+ * barrier, before `Context.destroy()` and before anything is terminated.
532
+ *
533
+ * Both exports are optional: an addon built against a napi crate that predates
534
+ * them drains nothing and keeps the previous behavior, exactly as the
535
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
536
+ *
537
+ * Returns nothing when there is nothing outstanding, which keeps disposal
538
+ * synchronous in the common case. The promise it returns otherwise never
539
+ * rejects.
540
+ *
541
+ * The wait has no deadline, and that is the point: giving up would destroy the
542
+ * environment with a completion callback still owed, which is the stranding
543
+ * this exists to prevent. A task whose `execute` never returns already keeps an
544
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
545
+ * rather than inventing a bound it cannot honor.
546
+ *
547
+ * Safe to call from inside a completion callback, which is reachable: settling
548
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
549
+ * being handed back, a threadsafe-function callback — and that JavaScript can
550
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
551
+ *
552
+ * - The addon keeps a work registered until its completion callback
553
+ * *finishes*, so the count read here is at least one and this takes the
554
+ * polling path instead of declaring the environment drained and tearing it
555
+ * down from inside the frame that is still settling a promise.
556
+ * - The poll is a timer, so it cannot run until the callback has returned to
557
+ * the host — by which time that work has left the registry. The count the
558
+ * next poll reads is the one taken after the callback finished.
559
+ *
560
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
561
+ * nested call joins this disposal rather than starting a second one.
562
+ */
563
+ function __drainWasiAsyncWork() {
564
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
565
+ return __wasiAsyncWorkDrainPromise
566
+ }
567
+ const exports = __napiInstance?.exports
568
+ const pending = exports?.napi_wasm_async_work_pending
569
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
570
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
571
+ return
572
+ }
573
+
574
+ const readPending = () => {
575
+ try {
576
+ return pending()
577
+ } catch (error) {
578
+ // A trap is the only way this call fails: it reads a counter and cannot
579
+ // allocate or call back into JavaScript. A trapped instance can no longer
580
+ // run anything, so its outstanding work is unreachable by definition —
581
+ // there is nothing left to wait for, and refusing to dispose would only
582
+ // keep a dead instance and its stuck counter alive. Best-effort here is
583
+ // the honest answer, and it is what disposal did before this drain
584
+ // existed.
585
+ //
586
+ // Only a trap. Anything else means the export is not what this loader
587
+ // thinks it is, which is a defect worth surfacing rather than disposing
588
+ // over.
589
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
590
+ return 0
591
+ }
592
+ throw error
593
+ }
594
+ }
595
+
596
+ if (!readPending()) {
597
+ return
598
+ }
599
+ try {
600
+ cancelPending()
601
+ } catch {
602
+ // Cancellation is an optimization: it bounds the wait by the work already
603
+ // executing. Failing it only means waiting for the whole queue instead.
604
+ }
605
+ if (!readPending()) {
606
+ return
607
+ }
608
+
609
+ const drainPromise = __keepEventLoopAliveUntil(
610
+ (async () => {
611
+ while (readPending()) {
612
+ await new Promise((resolve) => {
613
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
614
+ })
615
+ }
616
+ })(),
617
+ ).then(
618
+ () => {
619
+ __wasiAsyncWorkDrainPromise = undefined
620
+ },
621
+ (error) => {
622
+ // A wait that could not run is not a wait that finished. The only way
623
+ // here is a host whose timers and macrotask primitives all refuse, and
624
+ // the work is still outstanding — reporting success would destroy the
625
+ // environment over it, which is the stranding this exists to prevent.
626
+ // Reject instead: disposal stays retryable, and the context is not
627
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
628
+ __wasiAsyncWorkDrainPromise = undefined
629
+ throw error
630
+ },
631
+ )
632
+ __wasiAsyncWorkDrainPromise = drainPromise
633
+ return drainPromise
634
+ }
635
+
636
+ /**
637
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
638
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
639
+ * the manager's `exit` listener instead, which reports
640
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
641
+ * inside the emit — aborting the `once('exit')` that backs the terminate
642
+ * promise, so disposal never settles and the process dies with an uncaught
643
+ * exception. Mark the termination through the manager first.
644
+ *
645
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
646
+ * the initialization rollback runs on the one path where instantiation never
647
+ * returned, so `__napiModule` is still undefined there while the workers it
648
+ * spawned are already registered and loaded.
649
+ *
650
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
651
+ */
321
652
  function __terminateWasiWorkers() {
322
653
  const cleanupErrors = []
323
654
  const pending = []
655
+ const threadManager = __getWasiThreadManager()
324
656
 
325
657
  for (const worker of __wasiWorkers) {
326
658
  let result
327
659
  try {
660
+ if (threadManager) {
661
+ threadManager.terminateWorker(worker)
662
+ // `terminateWorker` leaves behind a reporter that logs every message
663
+ // still queued on the port, which Node flushes on exit. Nothing is
664
+ // listening for those any more.
665
+ worker.onmessage = undefined
666
+ }
328
667
  result = worker.terminate()
329
668
  } catch (error) {
330
669
  cleanupErrors.push(error)
@@ -354,7 +693,9 @@ function __terminateWasiWorkers() {
354
693
  )
355
694
  }
356
695
  }
357
- return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
696
+ return pending.length > 0
697
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
698
+ : finish()
358
699
  }
359
700
 
360
701
  function __finishWasiDisposal() {
@@ -373,7 +714,7 @@ function __continueWasiDisposal() {
373
714
  return __finishWasiDisposal()
374
715
  }
375
716
 
376
- function __startWasiDisposal() {
717
+ function __cleanUpWasmEnvForWasiDisposal() {
377
718
  // Run the pre-teardown barrier, then let the settlements it queued actually
378
719
  // reach JavaScript, and only then destroy the environment. Doing these two
379
720
  // back to back is what strands them.
@@ -385,6 +726,21 @@ function __startWasiDisposal() {
385
726
  return __continueWasiDisposal()
386
727
  }
387
728
 
729
+ function __startWasiDisposal() {
730
+ // Outstanding `napi_async_work` goes first, while the environment is still
731
+ // completely live: the completion callbacks run addon code, and everything
732
+ // after this point takes that away from them — the barrier shuts the async
733
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
734
+ // the pool threads removes what would have reported the work finished.
735
+ const asyncWorkResult = __drainWasiAsyncWork()
736
+ if (__isThenable(asyncWorkResult)) {
737
+ return Promise.resolve(asyncWorkResult).then(
738
+ __cleanUpWasmEnvForWasiDisposal,
739
+ )
740
+ }
741
+ return __cleanUpWasmEnvForWasiDisposal()
742
+ }
743
+
388
744
  /**
389
745
  * Disposes this generated WASI binding.
390
746
  *
@@ -526,36 +882,71 @@ function __retainFailedWasiRollback(cleanupErrors) {
526
882
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
527
883
  */
528
884
  function __rollbackWasiInitialization() {
529
- const cleanupErrors = []
530
- let drainResult
531
- let settlementsUnreached = false
885
+ // The environment teardown this rollback performs, kept nested so it cannot
886
+ // be reached without the async-work drain below running first.
887
+ function __rollbackWasmEnvForWasiInitialization() {
888
+ const cleanupErrors = []
889
+ let drainResult
890
+ let settlementsUnreached = false
891
+ try {
892
+ __prepareWasmEnvCleanup()
893
+ drainResult = __drainWasmEnvCleanup()
894
+ } catch (cleanupError) {
895
+ cleanupErrors.push(cleanupError)
896
+ settlementsUnreached = true
897
+ }
898
+ if (__isThenable(drainResult)) {
899
+ return Promise.resolve(drainResult).then(
900
+ () => __destroyContextForWasiRollback(cleanupErrors),
901
+ (cleanupError) => {
902
+ cleanupErrors.push(cleanupError)
903
+ return __retainFailedWasiRollback(cleanupErrors)
904
+ },
905
+ )
906
+ }
907
+ if (settlementsUnreached) {
908
+ return __retainFailedWasiRollback(cleanupErrors)
909
+ }
910
+ return __destroyContextForWasiRollback(cleanupErrors)
911
+ }
912
+
913
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
914
+ // work before the load goes on to fail, and this rollback tears down exactly
915
+ // what those completions need. Settle them while everything is still live,
916
+ // before the barrier and the teardown above take that away.
917
+ //
918
+ // A drain that could not finish leaves async work possibly outstanding, and
919
+ // destroying the context over it would strand exactly what this rollback is
920
+ // there to settle. Stop short and retain instead — the same trade
921
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
922
+ // the context stays reclaimable by a retry or by this flavor's own
923
+ // last-resort teardown.
924
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
925
+ __retainFailedWasiRollback([cleanupError])
926
+ let asyncWorkResult
532
927
  try {
533
- __prepareWasmEnvCleanup()
534
- drainResult = __drainWasmEnvCleanup()
928
+ asyncWorkResult = __drainWasiAsyncWork()
535
929
  } catch (cleanupError) {
536
- cleanupErrors.push(cleanupError)
537
- settlementsUnreached = true
930
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
538
931
  }
539
- if (__isThenable(drainResult)) {
540
- return Promise.resolve(drainResult).then(
541
- () => __destroyContextForWasiRollback(cleanupErrors),
542
- (cleanupError) => {
543
- cleanupErrors.push(cleanupError)
544
- return __retainFailedWasiRollback(cleanupErrors)
545
- },
932
+ if (__isThenable(asyncWorkResult)) {
933
+ return Promise.resolve(asyncWorkResult).then(
934
+ __rollbackWasmEnvForWasiInitialization,
935
+ __retainAfterAsyncWorkDrainFailure,
546
936
  )
547
937
  }
548
- if (settlementsUnreached) {
549
- return __retainFailedWasiRollback(cleanupErrors)
550
- }
551
- return __destroyContextForWasiRollback(cleanupErrors)
938
+ return __rollbackWasmEnvForWasiInitialization()
552
939
  }
553
940
 
554
941
  let __wasiModule
555
942
  let __napiModule
556
943
 
557
944
  try {
558
- __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
945
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
946
+ __emnapiCreateContext({ autoDestroy: false }),
947
+ __prepareWasmEnvCleanup,
948
+ __isPreparingWasmEnvCleanup,
949
+ )
559
950
  __emnapiContext.suppressDestroy()
560
951
 
561
952
  ;({
@@ -566,7 +957,11 @@ try {
566
957
  context: __emnapiContext,
567
958
  asyncWorkPoolSize: __asyncWorkPoolSize,
568
959
  reuseWorker: false,
569
- plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
960
+ plugins: [
961
+ __captureWasiThreadManager,
962
+ __emnapiAsyncWorkPlugin,
963
+ __emnapiTSFNPlugin,
964
+ ],
570
965
  wasi: __wasi,
571
966
  onCreateWorker() {
572
967
  const worker = new Worker(new URL('@oxc-minify/binding-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url), {
@@ -596,6 +991,12 @@ try {
596
991
  },
597
992
  }))
598
993
  __publishWasiDispose(__napiModule.exports)
994
+ // The default export hands out this object; a named module export does not
995
+ // travel with it, so carry the marker on the binding itself too. After the
996
+ // host install, which hands the same object to addon-provided registration
997
+ // functions that may put anything on it, and inside this `try`, so a claimed
998
+ // name fails the load through the rollback below rather than past it.
999
+ __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
599
1000
  } catch (error) {
600
1001
  const cleanupErrors = await __rollbackWasiInitialization()
601
1002
  throw __attachCleanupErrors(error, cleanupErrors)
package/minify.wasi.cjs CHANGED
@@ -2,6 +2,56 @@
2
2
  /* eslint-disable */
3
3
  /* auto-generated by NAPI-RS */
4
4
 
5
+ const __napiBindingTarget = 'wasm32-wasi'
6
+ function __napiStampBindingTarget(exportsObject, target) {
7
+ if (
8
+ Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
9
+ ) {
10
+ if (exportsObject.__napiBindingTarget === target) {
11
+ // Already ours: the root entry aliases the object it loaded, so a WASI
12
+ // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
13
+ // is a generated loader — arrives already stamped with this same value.
14
+ return target
15
+ }
16
+ const error = new Error(
17
+ '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
18
+ )
19
+ error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
20
+ throw error
21
+ }
22
+ if (!Object.isExtensible(exportsObject)) {
23
+ // A `#[napi(module_exports)]` hook may seal or freeze this object
24
+ // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
25
+ // never a reason to fail an otherwise successful load, so the stamp is
26
+ // skipped. What a consumer still sees then follows the entry point: the
27
+ // browser and deferred loaders declare `__napiBindingTarget` at module
28
+ // level and go on reporting it, while the CommonJS entries hand back this
29
+ // very object as `module.exports`, so there the value is absent.
30
+ return target
31
+ }
32
+ try {
33
+ // [[Define]], not [[Set]]: an ordinary assignment walks the prototype
34
+ // chain, so an inherited accessor could swallow the value or throw and
35
+ // fail an otherwise successful load. The descriptor is what a successful
36
+ // assignment would have produced.
37
+ Object.defineProperty(exportsObject, '__napiBindingTarget', {
38
+ configurable: true,
39
+ enumerable: true,
40
+ value: target,
41
+ writable: true,
42
+ })
43
+ } catch {
44
+ // Same rule as the non-extensible skip above: reporting the artifact is
45
+ // metadata, never a reason to fail an otherwise successful load. An exotic
46
+ // object (a Proxy whose defineProperty trap refuses) is skipped, not
47
+ // thrown over.
48
+ }
49
+ // The CommonJS loaders assign this return value so `cjs-module-lexer` — and
50
+ // therefore Node's CJS -> ESM named export detection — can see
51
+ // `__napiBindingTarget` statically.
52
+ return target
53
+ }
54
+
5
55
  const __nodeFs = require('node:fs')
6
56
  const __nodePath = require('node:path')
7
57
  const { WASI: __nodeWASI } = require('node:wasi')
@@ -149,14 +199,45 @@ let __emnapiContext
149
199
 
150
200
  const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
151
201
  const __wasiWorkers = new Set()
202
+ // The thread manager has to be reachable *before* anything that can throw
203
+ // during load or registration. Initialization can fail after the pool has
204
+ // already spawned workers, and the rollback still has to mark their
205
+ // terminations as expected — but `__napiModule` is assigned only when
206
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
207
+ // plugin factory runs while the emnapi module is being created, before the
208
+ // wasm is loaded and before any registration function runs, and its context
209
+ // carries the very same manager instance.
210
+ let __wasiThreadManager
211
+
212
+ function __captureWasiThreadManager(context) {
213
+ if (context && context.PThread) {
214
+ __wasiThreadManager = context.PThread
215
+ }
216
+ return {}
217
+ }
218
+
219
+ function __getWasiThreadManager() {
220
+ const manager =
221
+ __wasiThreadManager !== undefined
222
+ ? __wasiThreadManager
223
+ : __napiModule
224
+ ? __napiModule.PThread
225
+ : undefined
226
+ if (manager && typeof manager.terminateWorker === 'function') {
227
+ return manager
228
+ }
229
+ return undefined
230
+ }
152
231
  let __napiInstance
153
232
  let __emnapiContextDestroyed = false
154
233
  let __emnapiContextDestroyPromise
155
234
  let __emnapiWasmEnvCleanupPrepared = false
235
+ let __emnapiWasmEnvCleanupPreparing = false
156
236
  let __emnapiWasmEnvCleanupRan = false
157
237
  let __emnapiWasmEnvCleanupDrained = false
158
238
  let __emnapiWasmEnvCleanupDrainPromise
159
239
  let __wasiDisposed = false
240
+ let __wasiAsyncWorkDrainPromise
160
241
  let __wasiDisposePromise
161
242
  let __completeWasiDisposal = function () {}
162
243
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
@@ -226,13 +307,58 @@ function __attachCleanupErrors(error, cleanupErrors) {
226
307
  return aggregate
227
308
  }
228
309
 
310
+ function __wrapEmnapiContextDestroyForSettlement(
311
+ context,
312
+ prepareEnvCleanup,
313
+ isPreparingEnvCleanup,
314
+ ) {
315
+ let destroy
316
+ try {
317
+ destroy = context.destroy
318
+ } catch {
319
+ return context
320
+ }
321
+ if (typeof destroy !== 'function') {
322
+ return context
323
+ }
324
+ try {
325
+ Object.defineProperty(context, 'destroy', {
326
+ configurable: true,
327
+ enumerable: false,
328
+ writable: true,
329
+ value: function () {
330
+ // Reentered from a promise hook that fired inside the barrier: the
331
+ // frame running it destroys as soon as it returns.
332
+ if (isPreparingEnvCleanup?.()) {
333
+ return
334
+ }
335
+ prepareEnvCleanup?.()
336
+ return Reflect.apply(destroy, this, arguments)
337
+ },
338
+ })
339
+ } catch {}
340
+ return context
341
+ }
342
+
343
+ function __isPreparingWasmEnvCleanup() {
344
+ return __emnapiWasmEnvCleanupPreparing
345
+ }
346
+
229
347
  function __prepareWasmEnvCleanup() {
230
- if (__emnapiWasmEnvCleanupPrepared) {
348
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
231
349
  return
232
350
  }
233
351
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
234
352
  if (typeof prepare === 'function') {
235
- prepare()
353
+ // The addon settles the promises it cancels synchronously, under a
354
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
355
+ // here must not reach this export again.
356
+ __emnapiWasmEnvCleanupPreparing = true
357
+ try {
358
+ prepare()
359
+ } finally {
360
+ __emnapiWasmEnvCleanupPreparing = false
361
+ }
236
362
  __emnapiWasmEnvCleanupRan = true
237
363
  }
238
364
  __emnapiWasmEnvCleanupPrepared = true
@@ -269,6 +395,24 @@ const __scheduleMacrotask = (function () {
269
395
  }
270
396
  })()
271
397
 
398
+ // A real, *referenced* timer, for waits that must let the whole host make
399
+ // progress between looks — the async-work drain polls the addon rather than
400
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
401
+ // would spin the loop instead of yielding it. Falls back to the macrotask
402
+ // scheduler on a host without timers.
403
+ function __scheduleTimer(callback, delay) {
404
+ const setTimer = globalThis.setTimeout
405
+ if (typeof setTimer !== 'function') {
406
+ __scheduleMacrotask(callback)
407
+ return
408
+ }
409
+ try {
410
+ setTimer(callback, delay)
411
+ } catch {
412
+ __scheduleMacrotask(callback)
413
+ }
414
+ }
415
+
272
416
  // Turns to wait for while the addon still reports queued settlements. Reaching
273
417
  // zero is the only success. A counter still nonzero at this bound rejects the
274
418
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -425,13 +569,209 @@ function __destroyEmnapiContext() {
425
569
  return destroyPromise
426
570
  }
427
571
 
572
+ /**
573
+ * Holds the event loop open until `work` settles.
574
+ *
575
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
576
+ * binding cannot keep a process alive, and referencing them again for the
577
+ * termination does not hold either — emnapi unreferences a worker the moment it
578
+ * reports `async-thread-ready`, which for a worker that was still starting
579
+ * lands *after* the termination began. Without a handle of its own, an
580
+ * `await dispose()` with nothing else pending exits the process with its
581
+ * promise unsettled, and everything after the `await` is skipped.
582
+ *
583
+ * The timer is cleared as soon as the work settles, so this never outlives the
584
+ * disposal that asked for it.
585
+ */
586
+ function __keepEventLoopAliveUntil(work) {
587
+ const setTimer = globalThis.setInterval
588
+ const clearTimer = globalThis.clearInterval
589
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
590
+ return work
591
+ }
592
+ let timer
593
+ try {
594
+ timer = setTimer(function () {}, 50)
595
+ } catch {
596
+ return work
597
+ }
598
+ const release = function () {
599
+ try {
600
+ clearTimer(timer)
601
+ } catch {}
602
+ }
603
+ return work.then(
604
+ (value) => {
605
+ release()
606
+ return value
607
+ },
608
+ (error) => {
609
+ release()
610
+ throw error
611
+ },
612
+ )
613
+ }
614
+
615
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
616
+ // ends when the addon reports zero, so this only decides how promptly disposal
617
+ // notices — not how long it waits.
618
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
619
+
620
+ /**
621
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
622
+ * would strand it.
623
+ *
624
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
625
+ * it is observable from JavaScript: the threadless archive resolves
626
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
627
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
628
+ * imports nor exports those symbols and the only brackets a loader could watch
629
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
630
+ * functions. The addon is the one place both flavors go through, so it answers
631
+ * for both, through the same kind of handshake the settlement drain uses:
632
+ *
633
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
634
+ * started. Those completion callbacks run with `napi_cancelled`, which
635
+ * napi-rs turns into a promise rejected with an `AbortError`.
636
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
637
+ * callback. Work already executing refuses cancellation and stays counted
638
+ * until it finishes normally — which it can, because this runs before the
639
+ * barrier, before `Context.destroy()` and before anything is terminated.
640
+ *
641
+ * Both exports are optional: an addon built against a napi crate that predates
642
+ * them drains nothing and keeps the previous behavior, exactly as the
643
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
644
+ *
645
+ * Returns nothing when there is nothing outstanding, which keeps disposal
646
+ * synchronous in the common case. The promise it returns otherwise never
647
+ * rejects.
648
+ *
649
+ * The wait has no deadline, and that is the point: giving up would destroy the
650
+ * environment with a completion callback still owed, which is the stranding
651
+ * this exists to prevent. A task whose `execute` never returns already keeps an
652
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
653
+ * rather than inventing a bound it cannot honor.
654
+ *
655
+ * Safe to call from inside a completion callback, which is reachable: settling
656
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
657
+ * being handed back, a threadsafe-function callback — and that JavaScript can
658
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
659
+ *
660
+ * - The addon keeps a work registered until its completion callback
661
+ * *finishes*, so the count read here is at least one and this takes the
662
+ * polling path instead of declaring the environment drained and tearing it
663
+ * down from inside the frame that is still settling a promise.
664
+ * - The poll is a timer, so it cannot run until the callback has returned to
665
+ * the host — by which time that work has left the registry. The count the
666
+ * next poll reads is the one taken after the callback finished.
667
+ *
668
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
669
+ * nested call joins this disposal rather than starting a second one.
670
+ */
671
+ function __drainWasiAsyncWork() {
672
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
673
+ return __wasiAsyncWorkDrainPromise
674
+ }
675
+ const exports = __napiInstance?.exports
676
+ const pending = exports?.napi_wasm_async_work_pending
677
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
678
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
679
+ return
680
+ }
681
+
682
+ const readPending = () => {
683
+ try {
684
+ return pending()
685
+ } catch (error) {
686
+ // A trap is the only way this call fails: it reads a counter and cannot
687
+ // allocate or call back into JavaScript. A trapped instance can no longer
688
+ // run anything, so its outstanding work is unreachable by definition —
689
+ // there is nothing left to wait for, and refusing to dispose would only
690
+ // keep a dead instance and its stuck counter alive. Best-effort here is
691
+ // the honest answer, and it is what disposal did before this drain
692
+ // existed.
693
+ //
694
+ // Only a trap. Anything else means the export is not what this loader
695
+ // thinks it is, which is a defect worth surfacing rather than disposing
696
+ // over.
697
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
698
+ return 0
699
+ }
700
+ throw error
701
+ }
702
+ }
703
+
704
+ if (!readPending()) {
705
+ return
706
+ }
707
+ try {
708
+ cancelPending()
709
+ } catch {
710
+ // Cancellation is an optimization: it bounds the wait by the work already
711
+ // executing. Failing it only means waiting for the whole queue instead.
712
+ }
713
+ if (!readPending()) {
714
+ return
715
+ }
716
+
717
+ const drainPromise = __keepEventLoopAliveUntil(
718
+ (async () => {
719
+ while (readPending()) {
720
+ await new Promise((resolve) => {
721
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
722
+ })
723
+ }
724
+ })(),
725
+ ).then(
726
+ () => {
727
+ __wasiAsyncWorkDrainPromise = undefined
728
+ },
729
+ (error) => {
730
+ // A wait that could not run is not a wait that finished. The only way
731
+ // here is a host whose timers and macrotask primitives all refuse, and
732
+ // the work is still outstanding — reporting success would destroy the
733
+ // environment over it, which is the stranding this exists to prevent.
734
+ // Reject instead: disposal stays retryable, and the context is not
735
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
736
+ __wasiAsyncWorkDrainPromise = undefined
737
+ throw error
738
+ },
739
+ )
740
+ __wasiAsyncWorkDrainPromise = drainPromise
741
+ return drainPromise
742
+ }
743
+
744
+ /**
745
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
746
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
747
+ * the manager's `exit` listener instead, which reports
748
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
749
+ * inside the emit — aborting the `once('exit')` that backs the terminate
750
+ * promise, so disposal never settles and the process dies with an uncaught
751
+ * exception. Mark the termination through the manager first.
752
+ *
753
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
754
+ * the initialization rollback runs on the one path where instantiation never
755
+ * returned, so `__napiModule` is still undefined there while the workers it
756
+ * spawned are already registered and loaded.
757
+ *
758
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
759
+ */
428
760
  function __terminateWasiWorkers() {
429
761
  const cleanupErrors = []
430
762
  const pending = []
763
+ const threadManager = __getWasiThreadManager()
431
764
 
432
765
  for (const worker of __wasiWorkers) {
433
766
  let result
434
767
  try {
768
+ if (threadManager) {
769
+ threadManager.terminateWorker(worker)
770
+ // `terminateWorker` leaves behind a reporter that logs every message
771
+ // still queued on the port, which Node flushes on exit. Nothing is
772
+ // listening for those any more.
773
+ worker.onmessage = undefined
774
+ }
435
775
  result = worker.terminate()
436
776
  } catch (error) {
437
777
  cleanupErrors.push(error)
@@ -461,7 +801,9 @@ function __terminateWasiWorkers() {
461
801
  )
462
802
  }
463
803
  }
464
- return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
804
+ return pending.length > 0
805
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
806
+ : finish()
465
807
  }
466
808
 
467
809
  function __finishWasiDisposal() {
@@ -480,7 +822,7 @@ function __continueWasiDisposal() {
480
822
  return __finishWasiDisposal()
481
823
  }
482
824
 
483
- function __startWasiDisposal() {
825
+ function __cleanUpWasmEnvForWasiDisposal() {
484
826
  // Run the pre-teardown barrier, then let the settlements it queued actually
485
827
  // reach JavaScript, and only then destroy the environment. Doing these two
486
828
  // back to back is what strands them.
@@ -492,6 +834,21 @@ function __startWasiDisposal() {
492
834
  return __continueWasiDisposal()
493
835
  }
494
836
 
837
+ function __startWasiDisposal() {
838
+ // Outstanding `napi_async_work` goes first, while the environment is still
839
+ // completely live: the completion callbacks run addon code, and everything
840
+ // after this point takes that away from them — the barrier shuts the async
841
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
842
+ // the pool threads removes what would have reported the work finished.
843
+ const asyncWorkResult = __drainWasiAsyncWork()
844
+ if (__isThenable(asyncWorkResult)) {
845
+ return Promise.resolve(asyncWorkResult).then(
846
+ __cleanUpWasmEnvForWasiDisposal,
847
+ )
848
+ }
849
+ return __cleanUpWasmEnvForWasiDisposal()
850
+ }
851
+
495
852
  /**
496
853
  * Disposes this generated WASI binding.
497
854
  *
@@ -633,29 +990,60 @@ function __retainFailedWasiRollback(cleanupErrors) {
633
990
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
634
991
  */
635
992
  function __rollbackWasiInitialization() {
636
- const cleanupErrors = []
637
- let drainResult
638
- let settlementsUnreached = false
993
+ // The environment teardown this rollback performs, kept nested so it cannot
994
+ // be reached without the async-work drain below running first.
995
+ function __rollbackWasmEnvForWasiInitialization() {
996
+ const cleanupErrors = []
997
+ let drainResult
998
+ let settlementsUnreached = false
999
+ try {
1000
+ __prepareWasmEnvCleanup()
1001
+ drainResult = __drainWasmEnvCleanup()
1002
+ } catch (cleanupError) {
1003
+ cleanupErrors.push(cleanupError)
1004
+ settlementsUnreached = true
1005
+ }
1006
+ if (__isThenable(drainResult)) {
1007
+ return Promise.resolve(drainResult).then(
1008
+ () => __destroyContextForWasiRollback(cleanupErrors),
1009
+ (cleanupError) => {
1010
+ cleanupErrors.push(cleanupError)
1011
+ return __retainFailedWasiRollback(cleanupErrors)
1012
+ },
1013
+ )
1014
+ }
1015
+ if (settlementsUnreached) {
1016
+ return __retainFailedWasiRollback(cleanupErrors)
1017
+ }
1018
+ return __destroyContextForWasiRollback(cleanupErrors)
1019
+ }
1020
+
1021
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1022
+ // work before the load goes on to fail, and this rollback tears down exactly
1023
+ // what those completions need. Settle them while everything is still live,
1024
+ // before the barrier and the teardown above take that away.
1025
+ //
1026
+ // A drain that could not finish leaves async work possibly outstanding, and
1027
+ // destroying the context over it would strand exactly what this rollback is
1028
+ // there to settle. Stop short and retain instead — the same trade
1029
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1030
+ // the context stays reclaimable by a retry or by this flavor's own
1031
+ // last-resort teardown.
1032
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1033
+ __retainFailedWasiRollback([cleanupError])
1034
+ let asyncWorkResult
639
1035
  try {
640
- __prepareWasmEnvCleanup()
641
- drainResult = __drainWasmEnvCleanup()
1036
+ asyncWorkResult = __drainWasiAsyncWork()
642
1037
  } catch (cleanupError) {
643
- cleanupErrors.push(cleanupError)
644
- settlementsUnreached = true
1038
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
645
1039
  }
646
- if (__isThenable(drainResult)) {
647
- return Promise.resolve(drainResult).then(
648
- () => __destroyContextForWasiRollback(cleanupErrors),
649
- (cleanupError) => {
650
- cleanupErrors.push(cleanupError)
651
- return __retainFailedWasiRollback(cleanupErrors)
652
- },
1040
+ if (__isThenable(asyncWorkResult)) {
1041
+ return Promise.resolve(asyncWorkResult).then(
1042
+ __rollbackWasmEnvForWasiInitialization,
1043
+ __retainAfterAsyncWorkDrainFailure,
653
1044
  )
654
1045
  }
655
- if (settlementsUnreached) {
656
- return __retainFailedWasiRollback(cleanupErrors)
657
- }
658
- return __destroyContextForWasiRollback(cleanupErrors)
1046
+ return __rollbackWasmEnvForWasiInitialization()
659
1047
  }
660
1048
 
661
1049
  const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
@@ -831,7 +1219,11 @@ function __captureEmnapiAutoDestroyListener() {
831
1219
  try {
832
1220
  const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
833
1221
  try {
834
- __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
1222
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1223
+ __emnapiCreateContext({ autoDestroy: false }),
1224
+ __prepareWasmEnvCleanup,
1225
+ __isPreparingWasmEnvCleanup,
1226
+ )
835
1227
  // emnapi 2.x still registers an unconditional once-listener for
836
1228
  // beforeExit that auto-destroys the context, and suppressDestroy() only
837
1229
  // neutralizes its callback without removing it. This loader owns cleanup
@@ -859,7 +1251,11 @@ try {
859
1251
  }
860
1252
  })(),
861
1253
  reuseWorker: true,
862
- plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
1254
+ plugins: [
1255
+ __captureWasiThreadManager,
1256
+ __emnapiAsyncWorkPlugin,
1257
+ __emnapiTSFNPlugin,
1258
+ ],
863
1259
  wasi: __wasi,
864
1260
  onCreateWorker() {
865
1261
  const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
@@ -889,6 +1285,10 @@ try {
889
1285
  }
890
1286
 
891
1287
  worker.unref()
1288
+ // These stubs stay in place for the worker's whole life, disposal
1289
+ // included: `__keepEventLoopAliveUntil` is what holds the process open
1290
+ // while a termination is pending, precisely because a worker's own
1291
+ // references cannot be relied on for it.
892
1292
  }
893
1293
  return worker
894
1294
  },
@@ -911,6 +1311,22 @@ try {
911
1311
  },
912
1312
  }))
913
1313
  __publishWasiDispose(__napiModule.exports)
1314
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
1315
+ // export does not travel with it, so carry the marker on the binding itself
1316
+ // too. Three things pin the stamp to exactly this spot:
1317
+ // - inside this `try`, because the guard throws on a
1318
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
1319
+ // catch below tears the environment — context, workers, exit listener —
1320
+ // back down;
1321
+ // - after the async runtime host install, which hands this same object to
1322
+ // addon-provided registration functions that may put anything on it;
1323
+ // - assigning onto the loader's own `module.exports`, which is still the
1324
+ // original object here, so an addon accessor with a refusing setter is
1325
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
1326
+ // export detection — reads the static `module.exports.<name> =` either
1327
+ // way, and the later `module.exports = __napiModule.exports` does not
1328
+ // undo that.
1329
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
914
1330
  __registerWasiExitListener()
915
1331
  } catch (error) {
916
1332
  const rollback = {
package/minify.wasi.d.cts CHANGED
@@ -1,6 +1,9 @@
1
1
  /* auto-generated by NAPI-RS */
2
2
  /* eslint-disable */
3
3
 
4
+ /** The WASI flavor this loader instantiates. */
5
+ export declare const __napiBindingTarget: 'wasm32-wasi'
6
+
4
7
  export interface CodegenOptions {
5
8
  /**
6
9
  * Remove whitespace.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxc-minify/binding-wasm32-wasi",
3
- "version": "0.150.0",
3
+ "version": "0.151.0",
4
4
  "main": "minify.wasi.cjs",
5
5
  "files": [
6
6
  "minify.wasm32-wasi.wasm",