@oxc-transform-react/binding-wasm32-wasi 0.0.1 → 0.144.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.
@@ -0,0 +1,926 @@
1
+ // napi-rs-artifact-metadata:{"version":2,"rootEntry":"index.js","exports":["Severity","transform","transformSync"],"managedRootEntries":["browser.js","index.js","transform-react.wasm","transform-react.debug.wasm"]}
2
+ /* eslint-disable */
3
+ /* prettier-ignore */
4
+
5
+ /* auto-generated by NAPI-RS */
6
+
7
+ const __nodeFs = require('node:fs')
8
+ const __nodePath = require('node:path')
9
+ const { WASI: __nodeWASI } = require('node:wasi')
10
+ const { Worker } = require('node:worker_threads')
11
+
12
+ const {
13
+ emnapiAsyncWorkPlugin: __emnapiAsyncWorkPlugin,
14
+ emnapiTSFNPlugin: __emnapiTSFNPlugin,
15
+ createOnMessage: __wasmCreateOnMessageForFsProxy,
16
+ instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
17
+ } = require('@napi-rs/wasm-runtime')
18
+ const { createContext: __emnapiCreateContext } = require('@emnapi/runtime')
19
+
20
+ function __getWasiWorkerExecArgv() {
21
+ const __workerExecArgv = []
22
+ for (let __index = 0; __index < process.execArgv.length; __index += 1) {
23
+ const __arg = process.execArgv[__index]
24
+ if (
25
+ __arg === '--input-type' ||
26
+ __arg === '--eval' ||
27
+ __arg === '-e' ||
28
+ __arg === '--print' ||
29
+ __arg === '-p'
30
+ ) {
31
+ __index += 1
32
+ continue
33
+ }
34
+ if (
35
+ __arg.startsWith('--input-type=') ||
36
+ __arg.startsWith('--eval=') ||
37
+ __arg.startsWith('--print=')
38
+ ) {
39
+ continue
40
+ }
41
+ __workerExecArgv.push(__arg)
42
+ }
43
+ return __workerExecArgv
44
+ }
45
+
46
+ function __isInvalidWasiWorkerExecArgv(errorMessage, argument) {
47
+ const __equalsIndex = argument.indexOf('=')
48
+ const __argumentName =
49
+ __equalsIndex === -1 ? argument : argument.slice(0, __equalsIndex)
50
+ return (
51
+ errorMessage.includes(': ' + __argumentName + ',') ||
52
+ errorMessage.includes(': ' + __argumentName + '=') ||
53
+ errorMessage.endsWith(': ' + __argumentName) ||
54
+ errorMessage.includes(', ' + __argumentName + ',') ||
55
+ errorMessage.includes(', ' + __argumentName + '=') ||
56
+ errorMessage.endsWith(', ' + __argumentName)
57
+ )
58
+ }
59
+
60
+ function __removeInvalidWasiWorkerExecArgv(execArgv, error) {
61
+ if (typeof error.message !== 'string') {
62
+ return
63
+ }
64
+ const __workerExecArgv = []
65
+ let __removed = false
66
+ for (let __index = 0; __index < execArgv.length; __index += 1) {
67
+ const __arg = execArgv[__index]
68
+ if (
69
+ __arg.startsWith('-') &&
70
+ __isInvalidWasiWorkerExecArgv(error.message, __arg)
71
+ ) {
72
+ __removed = true
73
+ if (
74
+ !__arg.includes('=') &&
75
+ __index + 1 < execArgv.length &&
76
+ !execArgv[__index + 1].startsWith('-')
77
+ ) {
78
+ __index += 1
79
+ }
80
+ continue
81
+ }
82
+ __workerExecArgv.push(__arg)
83
+ }
84
+ return __removed ? __workerExecArgv : undefined
85
+ }
86
+
87
+ function __createWasiWorker(filename) {
88
+ let __workerExecArgv = __getWasiWorkerExecArgv()
89
+ while (true) {
90
+ try {
91
+ return new Worker(filename, {
92
+ env: process.env,
93
+ execArgv: __workerExecArgv,
94
+ })
95
+ } catch (error) {
96
+ if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
97
+ throw error
98
+ }
99
+ const __nextWorkerExecArgv =
100
+ __removeInvalidWasiWorkerExecArgv(__workerExecArgv, error)
101
+ if (!__nextWorkerExecArgv) {
102
+ throw error
103
+ }
104
+ __workerExecArgv = __nextWorkerExecArgv
105
+ }
106
+ }
107
+ }
108
+
109
+ const __rootDir = __nodePath.parse(process.cwd()).root
110
+
111
+ const __wasi = new __nodeWASI({
112
+ version: 'preview1',
113
+ env: process.env,
114
+ preopens: {
115
+ [__rootDir]: __rootDir,
116
+ }
117
+ })
118
+
119
+ const __sharedMemory = new WebAssembly.Memory({
120
+ initial: 4000,
121
+ maximum: 65536,
122
+ shared: true,
123
+ })
124
+
125
+ let __wasmFilePath = __nodePath.join(__dirname, 'transform-react.wasm32-wasi.wasm')
126
+ const __wasmDebugFilePath = __nodePath.join(__dirname, 'transform-react.wasm32-wasi.debug.wasm')
127
+
128
+ if (__nodeFs.existsSync(__wasmDebugFilePath)) {
129
+ __wasmFilePath = __wasmDebugFilePath
130
+ } else if (!__nodeFs.existsSync(__wasmFilePath)) {
131
+ const __wasiPackageEntry = require.resolve('@oxc-transform-react/binding-wasm32-wasi')
132
+ const __packagedWasmFilePath = __nodePath.join(
133
+ __nodePath.dirname(__wasiPackageEntry),
134
+ 'transform-react.wasm32-wasi.wasm',
135
+ )
136
+ if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
137
+ throw new Error(
138
+ '@oxc-transform-react/binding-wasm32-wasi is installed but is missing transform-react.wasm32-wasi.wasm.',
139
+ )
140
+ }
141
+ __wasmFilePath = __packagedWasmFilePath
142
+ }
143
+
144
+ const __wasmFile = __nodeFs.readFileSync(__wasmFilePath)
145
+ let __emnapiContext
146
+
147
+ const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
148
+ const __wasiWorkers = new Set()
149
+ let __napiInstance
150
+ let __emnapiContextDestroyed = false
151
+ let __emnapiContextDestroyPromise
152
+ let __emnapiWasmEnvCleanupPrepared = false
153
+ let __emnapiWasmEnvCleanupRan = false
154
+ let __emnapiWasmEnvCleanupDrained = false
155
+ let __emnapiWasmEnvCleanupDrainPromise
156
+ let __wasiDisposed = false
157
+ let __wasiDisposePromise
158
+ let __completeWasiDisposal = function() {}
159
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
160
+ // that stopped short of destroying the context. See
161
+ // `__rollbackWasiInitialization`.
162
+ let __retainWasiRollbackForRetry = function() {}
163
+
164
+ function __isThenable(value) {
165
+ return (
166
+ value !== null &&
167
+ (typeof value === 'object' || typeof value === 'function') &&
168
+ typeof value.then === 'function'
169
+ )
170
+ }
171
+
172
+ function __createCleanupError(errors, message) {
173
+ if (errors.length === 1) {
174
+ return errors[0]
175
+ }
176
+ const __AggregateError = globalThis.AggregateError
177
+ if (typeof __AggregateError === 'function') {
178
+ return new __AggregateError(errors, message)
179
+ }
180
+ const error = new Error(message)
181
+ error.errors = errors
182
+ return error
183
+ }
184
+
185
+ function __attachCleanupErrors(error, cleanupErrors) {
186
+ if (cleanupErrors.length === 0) {
187
+ return error
188
+ }
189
+ const cleanupError = __createCleanupError(
190
+ cleanupErrors,
191
+ 'WASI binding cleanup failed',
192
+ )
193
+ try {
194
+ if (
195
+ error &&
196
+ (typeof error === 'object' || typeof error === 'function')
197
+ ) {
198
+ if (error.cause === undefined) {
199
+ error.cause = cleanupError
200
+ if (error.cause === cleanupError) {
201
+ return error
202
+ }
203
+ }
204
+ if (Array.isArray(error.cleanupErrors)) {
205
+ error.cleanupErrors.push(cleanupError)
206
+ return error
207
+ } else {
208
+ const attachedCleanupErrors = [cleanupError]
209
+ error.cleanupErrors = attachedCleanupErrors
210
+ if (error.cleanupErrors === attachedCleanupErrors) {
211
+ return error
212
+ }
213
+ }
214
+ }
215
+ } catch {}
216
+ const aggregate = __createCleanupError(
217
+ [error, cleanupError],
218
+ 'WASI binding initialization and cleanup failed',
219
+ )
220
+ try {
221
+ aggregate.cause = error
222
+ } catch {}
223
+ return aggregate
224
+ }
225
+
226
+ function __prepareWasmEnvCleanup() {
227
+ if (__emnapiWasmEnvCleanupPrepared) {
228
+ return
229
+ }
230
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
231
+ if (typeof prepare === 'function') {
232
+ prepare()
233
+ __emnapiWasmEnvCleanupRan = true
234
+ }
235
+ __emnapiWasmEnvCleanupPrepared = true
236
+ }
237
+
238
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
239
+ // on, so the drain turns below interleave with that dispatch instead of racing
240
+ // ahead of it on a faster queue.
241
+ const __scheduleMacrotask = (function () {
242
+ if (typeof setImmediate === 'function') {
243
+ return function (callback) {
244
+ setImmediate(callback)
245
+ }
246
+ }
247
+ const __MessageChannel = globalThis.MessageChannel
248
+ if (typeof __MessageChannel === 'function') {
249
+ return function (callback) {
250
+ const channel = new __MessageChannel()
251
+ channel.port1.onmessage = function () {
252
+ channel.port1.onmessage = null
253
+ try {
254
+ channel.port1.close()
255
+ } catch {}
256
+ try {
257
+ channel.port2.close()
258
+ } catch {}
259
+ callback()
260
+ }
261
+ channel.port2.postMessage(null)
262
+ }
263
+ }
264
+ return function (callback) {
265
+ setTimeout(callback, 0)
266
+ }
267
+ })()
268
+
269
+ // Turns to wait for while the addon still reports queued settlements. Reaching
270
+ // zero is the only success. A counter still nonzero at this bound rejects the
271
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
272
+ // destroying the context over a still-queued settlement — the wait stays
273
+ // bounded either way.
274
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
275
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
276
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
277
+ // call made on this thread (two), plus a margin.
278
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
279
+
280
+ /**
281
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
282
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
283
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
284
+ * macrotask — two coalescing turns later, even for a call made on this very
285
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
286
+ * which drains the queue with a null env and *discards* whatever is still in it.
287
+ *
288
+ * So destroying without yielding first strands exactly the promises the barrier
289
+ * exists to settle. Yield real event-loop turns until the addon reports the
290
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
291
+ * macrotask run.
292
+ *
293
+ * Returns nothing when there is nothing to wait for, which keeps disposal
294
+ * synchronous in the common case.
295
+ *
296
+ * The "already drained" flag is set only once a wait has actually finished.
297
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
298
+ * that throws is enough — and a disposal that rejects stays retryable, so
299
+ * marking the drain complete up front would make the retry skip it and destroy
300
+ * the context with the barrier's settlements still queued.
301
+ *
302
+ * A wait that runs out of turns with the counter still nonzero rejects with
303
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
304
+ * "finished" is indistinguishable from the stranding above, and destroying
305
+ * would discard the very settlement the wait was for. The rejection leaves the
306
+ * flag unset and disposal retryable.
307
+ */
308
+ function __drainWasmEnvCleanup() {
309
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
310
+ return
311
+ }
312
+ if (__emnapiWasmEnvCleanupDrainPromise) {
313
+ return __emnapiWasmEnvCleanupDrainPromise
314
+ }
315
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
316
+ const observable = typeof pending === 'function'
317
+ if (observable) {
318
+ let queued
319
+ try {
320
+ queued = pending()
321
+ } catch {
322
+ __emnapiWasmEnvCleanupDrained = true
323
+ return
324
+ }
325
+ if (!queued) {
326
+ __emnapiWasmEnvCleanupDrained = true
327
+ return
328
+ }
329
+ }
330
+ const limit = observable
331
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
332
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
333
+ const drainPromise = (async () => {
334
+ let queued = 0
335
+ for (let turn = 0; turn < limit; turn++) {
336
+ await new Promise((resolve) => {
337
+ __scheduleMacrotask(resolve)
338
+ })
339
+ if (!observable) {
340
+ continue
341
+ }
342
+ try {
343
+ queued = pending()
344
+ } catch {
345
+ return
346
+ }
347
+ if (!queued) {
348
+ return
349
+ }
350
+ }
351
+ if (!observable) {
352
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
353
+ // contract — there is nothing to consult, so finishing the turns is
354
+ // finishing the drain.
355
+ return
356
+ }
357
+ // The counter is still nonzero after every turn the bound allows. The wait
358
+ // stays bounded — but claiming success here would be indistinguishable from
359
+ // the stranding this drain exists to prevent: disposal would go on to
360
+ // destroy the context, whose cleanup hook discards the still-queued
361
+ // settlement with a null env, and the promise it was for hangs forever.
362
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
363
+ // unset, dispose() (and the rollback) decline to destroy, and a later
364
+ // dispose() runs the drain again — by which time the queue has usually been
365
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
366
+ // attempt at most another bounded wait and a rejection, never a stranded
367
+ // promise; the process-exit teardown still reclaims the context.
368
+ const drainError = new Error(
369
+ 'the wasm environment still reports ' +
370
+ queued +
371
+ ' queued settlement(s) after ' +
372
+ limit +
373
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
374
+ )
375
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
376
+ throw drainError
377
+ })().then(
378
+ (value) => {
379
+ // Set only when the wait actually finished AND the queue was seen empty
380
+ // (or is unobservable): a drain that timed out with settlements still
381
+ // queued rejects above and must stay repeatable.
382
+ __emnapiWasmEnvCleanupDrained = true
383
+ __emnapiWasmEnvCleanupDrainPromise = undefined
384
+ return value
385
+ },
386
+ (error) => {
387
+ __emnapiWasmEnvCleanupDrainPromise = undefined
388
+ throw error
389
+ },
390
+ )
391
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
392
+ return drainPromise
393
+ }
394
+
395
+ function __destroyEmnapiContext() {
396
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
397
+ __emnapiContextDestroyed = true
398
+ return
399
+ }
400
+ if (__emnapiContextDestroyPromise) {
401
+ return __emnapiContextDestroyPromise
402
+ }
403
+
404
+ __prepareWasmEnvCleanup()
405
+ const result = __emnapiContext.destroy()
406
+ if (!__isThenable(result)) {
407
+ __emnapiContextDestroyed = true
408
+ return
409
+ }
410
+
411
+ const destroyPromise = Promise.resolve(result).then(
412
+ (value) => {
413
+ __emnapiContextDestroyed = true
414
+ return value
415
+ },
416
+ (error) => {
417
+ __emnapiContextDestroyPromise = undefined
418
+ throw error
419
+ },
420
+ )
421
+ __emnapiContextDestroyPromise = destroyPromise
422
+ return destroyPromise
423
+ }
424
+
425
+ function __terminateWasiWorkers() {
426
+ const cleanupErrors = []
427
+ const pending = []
428
+
429
+ for (const worker of __wasiWorkers) {
430
+ let result
431
+ try {
432
+ result = worker.terminate()
433
+ } catch (error) {
434
+ cleanupErrors.push(error)
435
+ continue
436
+ }
437
+ if (__isThenable(result)) {
438
+ pending.push(
439
+ Promise.resolve(result).then(
440
+ () => {
441
+ __wasiWorkers.delete(worker)
442
+ },
443
+ (error) => {
444
+ cleanupErrors.push(error)
445
+ },
446
+ ),
447
+ )
448
+ } else {
449
+ __wasiWorkers.delete(worker)
450
+ }
451
+ }
452
+
453
+ const finish = () => {
454
+ if (cleanupErrors.length > 0) {
455
+ throw __createCleanupError(
456
+ cleanupErrors,
457
+ 'Failed to terminate WASI workers',
458
+ )
459
+ }
460
+ }
461
+ return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
462
+ }
463
+
464
+ function __finishWasiDisposal() {
465
+ const workerResult = __terminateWasiWorkers()
466
+ if (__isThenable(workerResult)) {
467
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
468
+ }
469
+ return __completeWasiDisposal()
470
+ }
471
+
472
+ function __continueWasiDisposal() {
473
+ const destroyResult = __destroyEmnapiContext()
474
+ if (__isThenable(destroyResult)) {
475
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
476
+ }
477
+ return __finishWasiDisposal()
478
+ }
479
+
480
+ function __startWasiDisposal() {
481
+ // Run the pre-teardown barrier, then let the settlements it queued actually
482
+ // reach JavaScript, and only then destroy the environment. Doing these two
483
+ // back to back is what strands them.
484
+ __prepareWasmEnvCleanup()
485
+ const drainResult = __drainWasmEnvCleanup()
486
+ if (__isThenable(drainResult)) {
487
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
488
+ }
489
+ return __continueWasiDisposal()
490
+ }
491
+
492
+ /**
493
+ * Disposes this generated WASI binding.
494
+ *
495
+ * Access this function with:
496
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
497
+ */
498
+ function __disposeWasiBinding() {
499
+ if (__wasiDisposePromise) {
500
+ return __wasiDisposePromise
501
+ }
502
+ if (__wasiDisposed) {
503
+ return Promise.resolve()
504
+ }
505
+
506
+ let resolveDispose
507
+ let rejectDispose
508
+ const disposePromise = new Promise((resolve, reject) => {
509
+ resolveDispose = resolve
510
+ rejectDispose = reject
511
+ })
512
+ __wasiDisposePromise = disposePromise
513
+
514
+ let result
515
+ try {
516
+ result = __startWasiDisposal()
517
+ } catch (error) {
518
+ __wasiDisposePromise = undefined
519
+ rejectDispose(error)
520
+ return disposePromise
521
+ }
522
+
523
+ Promise.resolve(result).then(
524
+ (value) => {
525
+ __wasiDisposed = true
526
+ resolveDispose(value)
527
+ },
528
+ (error) => {
529
+ __wasiDisposePromise = undefined
530
+ rejectDispose(error)
531
+ },
532
+ )
533
+ return disposePromise
534
+ }
535
+
536
+ function __publishWasiDispose(exports) {
537
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
538
+ configurable: false,
539
+ enumerable: false,
540
+ value: __disposeWasiBinding,
541
+ writable: false,
542
+ })
543
+ }
544
+
545
+ function __finishWasiInitializationRollback(cleanupErrors) {
546
+ let workerResult
547
+ try {
548
+ workerResult = __terminateWasiWorkers()
549
+ } catch (cleanupError) {
550
+ cleanupErrors.push(cleanupError)
551
+ return cleanupErrors
552
+ }
553
+ if (__isThenable(workerResult)) {
554
+ return Promise.resolve(workerResult)
555
+ .catch((cleanupError) => {
556
+ cleanupErrors.push(cleanupError)
557
+ })
558
+ .then(() => cleanupErrors)
559
+ }
560
+ return cleanupErrors
561
+ }
562
+
563
+ function __destroyContextForWasiRollback(cleanupErrors) {
564
+ let destroyResult
565
+ try {
566
+ destroyResult = __destroyEmnapiContext()
567
+ } catch (cleanupError) {
568
+ cleanupErrors.push(cleanupError)
569
+ return __finishWasiInitializationRollback(cleanupErrors)
570
+ }
571
+ if (__isThenable(destroyResult)) {
572
+ return Promise.resolve(destroyResult)
573
+ .catch((cleanupError) => {
574
+ cleanupErrors.push(cleanupError)
575
+ })
576
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
577
+ }
578
+ return __finishWasiInitializationRollback(cleanupErrors)
579
+ }
580
+
581
+ /**
582
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
583
+ * hands it to whatever this flavor has that can still reclaim it.
584
+ */
585
+ function __retainFailedWasiRollback(cleanupErrors) {
586
+ try {
587
+ __retainWasiRollbackForRetry()
588
+ } catch (cleanupError) {
589
+ cleanupErrors.push(cleanupError)
590
+ }
591
+ return cleanupErrors
592
+ }
593
+
594
+ /**
595
+ * Initialization can fail *after* registration has already run, and registration
596
+ * runs with a live environment: a module-init hook can start async work and then
597
+ * return an error, and the promise it created may already have escaped into
598
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
599
+ * path needs the same drain the ordinary disposal does — destroying without
600
+ * yielding discards the queue with a null env and strands the promise.
601
+ *
602
+ * Stays synchronous when nothing is queued, which covers every failure before
603
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
604
+ *
605
+ * A barrier or drain that did *not* finish stops the rollback short of
606
+ * destroying, which is what `dispose()` already does — a rejected drain there
607
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
608
+ * two trades, and not because of what it saves:
609
+ *
610
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
611
+ * threadsafe function's cleanup hook, which drains the queue with a null env
612
+ * and discards it, so a promise that already escaped into JavaScript hangs
613
+ * forever with nothing left that could ever settle it.
614
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
615
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
616
+ * which this module's scope holds either way. What stopping short retains is
617
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
618
+ * - Retry is not theoretical. A rollback that records a cleanup error is
619
+ * already kept in the process-wide registry above, so re-`require()`ing this
620
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
621
+ * means the replay drains again rather than skipping it. Destroying first is
622
+ * what makes that retained record useless.
623
+ *
624
+ * The residual cost is honest: the CJS flavor hands the context to its
625
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
626
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
627
+ * throws while evaluating is permanently errored, so re-importing rethrows
628
+ * without re-running this file — and there the context stays until the realm
629
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
630
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
631
+ */
632
+ function __rollbackWasiInitialization() {
633
+ const cleanupErrors = []
634
+ let drainResult
635
+ let settlementsUnreached = false
636
+ try {
637
+ __prepareWasmEnvCleanup()
638
+ drainResult = __drainWasmEnvCleanup()
639
+ } catch (cleanupError) {
640
+ cleanupErrors.push(cleanupError)
641
+ settlementsUnreached = true
642
+ }
643
+ if (__isThenable(drainResult)) {
644
+ return Promise.resolve(drainResult).then(
645
+ () => __destroyContextForWasiRollback(cleanupErrors),
646
+ (cleanupError) => {
647
+ cleanupErrors.push(cleanupError)
648
+ return __retainFailedWasiRollback(cleanupErrors)
649
+ },
650
+ )
651
+ }
652
+ if (settlementsUnreached) {
653
+ return __retainFailedWasiRollback(cleanupErrors)
654
+ }
655
+ return __destroyContextForWasiRollback(cleanupErrors)
656
+ }
657
+
658
+ const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
659
+ const __wasiRollbackRegistryKey =
660
+ typeof __filename === 'string' ? __filename : __wasmFilePath
661
+
662
+ function __getWasiRollbackRegistry() {
663
+ const existing = process[__wasiRollbackRegistrySymbol]
664
+ if (existing !== undefined) {
665
+ if (!(existing instanceof Map)) {
666
+ throw new TypeError(
667
+ 'The process-wide NAPI-RS WASI rollback registry is invalid',
668
+ )
669
+ }
670
+ return existing
671
+ }
672
+ const registry = new Map()
673
+ Object.defineProperty(process, __wasiRollbackRegistrySymbol, {
674
+ configurable: false,
675
+ enumerable: false,
676
+ value: registry,
677
+ writable: false,
678
+ })
679
+ return registry
680
+ }
681
+
682
+ const __wasiRollbackRegistry = __getWasiRollbackRegistry()
683
+
684
+ function __completeWasiInitializationRollback(record, cleanupErrors) {
685
+ try {
686
+ if (cleanupErrors.length === 0) {
687
+ if (
688
+ __wasiRollbackRegistry.get(__wasiRollbackRegistryKey) === record
689
+ ) {
690
+ __wasiRollbackRegistry.delete(__wasiRollbackRegistryKey)
691
+ }
692
+ return
693
+ }
694
+ record.error = __attachCleanupErrors(record.error, cleanupErrors)
695
+ } catch (cleanupError) {
696
+ try {
697
+ record.error = __createCleanupError(
698
+ [record.error, cleanupError],
699
+ 'WASI binding initialization and cleanup failed',
700
+ )
701
+ } catch {}
702
+ } finally {
703
+ record.active = false
704
+ record.promise = undefined
705
+ }
706
+ }
707
+
708
+ function __runWasiInitializationRollback(record) {
709
+ if (record.active) {
710
+ return
711
+ }
712
+ record.active = true
713
+
714
+ let rollbackResult
715
+ try {
716
+ rollbackResult = record.rollback()
717
+ } catch (cleanupError) {
718
+ __completeWasiInitializationRollback(record, [cleanupError])
719
+ return
720
+ }
721
+
722
+ if (!__isThenable(rollbackResult)) {
723
+ __completeWasiInitializationRollback(record, rollbackResult)
724
+ return
725
+ }
726
+
727
+ record.promise = Promise.resolve(rollbackResult).then(
728
+ (cleanupErrors) => {
729
+ __completeWasiInitializationRollback(record, cleanupErrors)
730
+ },
731
+ (cleanupError) => {
732
+ __completeWasiInitializationRollback(record, [cleanupError])
733
+ },
734
+ )
735
+ }
736
+
737
+ const __pendingWasiRollback = __wasiRollbackRegistry.get(
738
+ __wasiRollbackRegistryKey,
739
+ )
740
+ if (__pendingWasiRollback !== undefined) {
741
+ __runWasiInitializationRollback(__pendingWasiRollback)
742
+ throw __pendingWasiRollback.error
743
+ }
744
+
745
+ let __wasiModule
746
+ let __napiModule
747
+ let __wasiExitListenerRegistered = false
748
+
749
+ function __removeWasiExitListener() {
750
+ if (
751
+ __wasiExitListenerRegistered &&
752
+ typeof process.removeListener === 'function'
753
+ ) {
754
+ process.removeListener('exit', __disposeWasiBindingAtExit)
755
+ }
756
+ __wasiExitListenerRegistered = false
757
+ }
758
+
759
+ function __disposeWasiBindingAtExit() {
760
+ __wasiExitListenerRegistered = false
761
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
762
+ // settlements the way __startWasiDisposal does — the process is leaving and
763
+ // those promises have no observer left anyway. Run the synchronous teardown
764
+ // directly. Every step is idempotent, which also makes this the synchronous
765
+ // finish for a disposal that is still waiting for its drain.
766
+ try {
767
+ __destroyEmnapiContext()
768
+ } catch {}
769
+ try {
770
+ const workerResult = __terminateWasiWorkers()
771
+ if (__isThenable(workerResult)) {
772
+ void Promise.resolve(workerResult).catch(() => {})
773
+ }
774
+ } catch {}
775
+ }
776
+
777
+ function __registerWasiExitListener() {
778
+ if (
779
+ !__wasiExitListenerRegistered &&
780
+ typeof process.once === 'function'
781
+ ) {
782
+ process.once('exit', __disposeWasiBindingAtExit)
783
+ __wasiExitListenerRegistered = true
784
+ }
785
+ }
786
+
787
+ __completeWasiDisposal = __removeWasiExitListener
788
+ // A rollback that could not reach the queued settlements keeps the context so
789
+ // the registry replay above can retry it. Nothing forces that replay to happen,
790
+ // so hand the context to the same synchronous teardown a successful load uses:
791
+ // a process that exits without ever retrying still runs the cleanup hooks. The
792
+ // handler cannot yield, so it does not settle anything — but by then the process
793
+ // is leaving and those promises have no observer left anyway.
794
+ __retainWasiRollbackForRetry = __registerWasiExitListener
795
+
796
+ function __captureEmnapiAutoDestroyListener() {
797
+ if (
798
+ typeof process.prependListener !== 'function' ||
799
+ typeof process.removeListener !== 'function'
800
+ ) {
801
+ return
802
+ }
803
+ let __autoDestroyListener
804
+ const __captureListener = (__event, __listener) => {
805
+ if (__event === 'beforeExit' && __autoDestroyListener === undefined) {
806
+ __autoDestroyListener = __listener
807
+ }
808
+ }
809
+ try {
810
+ // Run before existing newListener hooks so a hook that registers its own
811
+ // beforeExit listener cannot be mistaken for emnapi's registration.
812
+ process.prependListener('newListener', __captureListener)
813
+ } catch {
814
+ return
815
+ }
816
+ return () => {
817
+ try {
818
+ process.removeListener('newListener', __captureListener)
819
+ } catch {}
820
+ if (__autoDestroyListener !== undefined) {
821
+ try {
822
+ process.removeListener('beforeExit', __autoDestroyListener)
823
+ } catch {}
824
+ }
825
+ }
826
+ }
827
+
828
+ try {
829
+ const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
830
+ try {
831
+ __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
832
+ // emnapi 2.x still registers an unconditional once-listener for
833
+ // beforeExit that auto-destroys the context, and suppressDestroy() only
834
+ // neutralizes its callback without removing it. This loader owns cleanup
835
+ // through its 'exit' listener, so emnapi's listener is captured and
836
+ // removed; suppressDestroy() remains the safety net when removal fails.
837
+ __emnapiContext.suppressDestroy()
838
+ } finally {
839
+ // Remove only the exact emnapi callback captured above.
840
+ __finishAutoDestroyCapture?.()
841
+ }
842
+
843
+ ;({
844
+ instance: __napiInstance,
845
+ module: __wasiModule,
846
+ napiModule: __napiModule,
847
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
848
+ context: __emnapiContext,
849
+ asyncWorkPoolSize: (function() {
850
+ const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
851
+ // NaN > 0 is false
852
+ if (threadsSizeFromEnv > 0) {
853
+ return threadsSizeFromEnv
854
+ } else {
855
+ return 4
856
+ }
857
+ })(),
858
+ reuseWorker: true,
859
+ plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
860
+ wasi: __wasi,
861
+ onCreateWorker() {
862
+ const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
863
+ __wasiWorkers.add(worker)
864
+ worker.onmessage = ({ data }) => {
865
+ __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
866
+ }
867
+
868
+ // The main thread of Node.js waits for all the active handles before exiting.
869
+ // But Rust threads are never waited without `thread::join`.
870
+ // So here we hack the code of Node.js to prevent the workers from being referenced (active).
871
+ // According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415,
872
+ // a worker is consist of two handles: kPublicPort and kHandle.
873
+ {
874
+ const kPublicPort = Object.getOwnPropertySymbols(worker).find(s =>
875
+ s.toString().includes("kPublicPort")
876
+ );
877
+ if (kPublicPort) {
878
+ worker[kPublicPort].ref = () => {};
879
+ }
880
+
881
+ const kHandle = Object.getOwnPropertySymbols(worker).find(s =>
882
+ s.toString().includes("kHandle")
883
+ );
884
+ if (kHandle) {
885
+ worker[kHandle].ref = () => {};
886
+ }
887
+
888
+ worker.unref();
889
+ }
890
+ return worker
891
+ },
892
+ overwriteImports(importObject) {
893
+ importObject.env = {
894
+ ...importObject.env,
895
+ ...importObject.napi,
896
+ ...importObject.emnapi,
897
+ memory: __sharedMemory,
898
+ }
899
+ return importObject
900
+ },
901
+ beforeInit({ instance }) {
902
+ __napiInstance = instance
903
+ for (const name of Object.keys(instance.exports)) {
904
+ if (name.startsWith('__napi_register__')) {
905
+ instance.exports[name]()
906
+ }
907
+ }
908
+ },
909
+ }))
910
+ __publishWasiDispose(__napiModule.exports)
911
+ __registerWasiExitListener()
912
+ } catch (error) {
913
+ const rollback = {
914
+ active: false,
915
+ error,
916
+ promise: undefined,
917
+ rollback: __rollbackWasiInitialization,
918
+ }
919
+ __wasiRollbackRegistry.set(__wasiRollbackRegistryKey, rollback)
920
+ __runWasiInitializationRollback(rollback)
921
+ throw rollback.error
922
+ }
923
+ module.exports = __napiModule.exports
924
+ module.exports.Severity = __napiModule.exports.Severity
925
+ module.exports.transform = __napiModule.exports.transform
926
+ module.exports.transformSync = __napiModule.exports.transformSync