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