@petrea/wasm 0.0.0 → 0.5.1

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,990 @@
1
+ import {
2
+ emnapiAsyncWorkPlugin as __emnapiAsyncWorkPlugin,
3
+ emnapiTSFNPlugin as __emnapiTSFNPlugin,
4
+ instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync,
5
+ WASI as __WASI,
6
+ } from '@napi-rs/wasm-runtime'
7
+ import { createContext as __emnapiCreateContext } from '@emnapi/runtime'
8
+
9
+
10
+ export const __napiBindingTarget = 'wasm32-wasip1'
11
+ function __napiStampBindingTarget(exportsObject, target) {
12
+ if (
13
+ Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
14
+ ) {
15
+ if (exportsObject.__napiBindingTarget === target) {
16
+ // Already ours: the root entry aliases the object it loaded, so a WASI
17
+ // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
18
+ // is a generated loader — arrives already stamped with this same value.
19
+ return target
20
+ }
21
+ const error = new Error(
22
+ '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
23
+ )
24
+ error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
25
+ throw error
26
+ }
27
+ if (!Object.isExtensible(exportsObject)) {
28
+ // A `#[napi(module_exports)]` hook may seal or freeze this object
29
+ // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
30
+ // never a reason to fail an otherwise successful load, so the stamp is
31
+ // skipped. What a consumer still sees then follows the entry point: the
32
+ // browser and deferred loaders declare `__napiBindingTarget` at module
33
+ // level and go on reporting it, while the CommonJS entries hand back this
34
+ // very object as `module.exports`, so there the value is absent.
35
+ return target
36
+ }
37
+ try {
38
+ // [[Define]], not [[Set]]: an ordinary assignment walks the prototype
39
+ // chain, so an inherited accessor could swallow the value or throw and
40
+ // fail an otherwise successful load. The descriptor is what a successful
41
+ // assignment would have produced.
42
+ Object.defineProperty(exportsObject, '__napiBindingTarget', {
43
+ configurable: true,
44
+ enumerable: true,
45
+ value: target,
46
+ writable: true,
47
+ })
48
+ } catch {
49
+ // Same rule as the non-extensible skip above: reporting the artifact is
50
+ // metadata, never a reason to fail an otherwise successful load. An exotic
51
+ // object (a Proxy whose defineProperty trap refuses) is skipped, not
52
+ // thrown over.
53
+ }
54
+ // The CommonJS loaders assign this return value so `cjs-module-lexer` — and
55
+ // therefore Node's CJS -> ESM named export detection — can see
56
+ // `__napiBindingTarget` statically.
57
+ return target
58
+ }
59
+
60
+ const __wasi = new __WASI({
61
+ version: 'preview1',
62
+ })
63
+
64
+ const __wasmUrl = new URL('./binding.wasm32-wasip1.wasm', import.meta.url).href
65
+ const __wasmResponse = await globalThis.fetch(__wasmUrl)
66
+ if (!__wasmResponse.ok) {
67
+ throw new Error(
68
+ 'Failed to fetch WASI module ' +
69
+ __wasmUrl +
70
+ ': ' +
71
+ __wasmResponse.status +
72
+ ' ' +
73
+ (__wasmResponse.statusText || 'Unknown Status'),
74
+ )
75
+ }
76
+ const __wasmFile = await __wasmResponse.arrayBuffer()
77
+
78
+ const __wasmMemory = new WebAssembly.Memory({
79
+ initial: 4000,
80
+ maximum: 65536,
81
+ })
82
+ let __emnapiContext
83
+
84
+ const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
85
+ const __wasiWorkers = new Set()
86
+ // The thread manager has to be reachable *before* anything that can throw
87
+ // during load or registration. Initialization can fail after the pool has
88
+ // already spawned workers, and the rollback still has to mark their
89
+ // terminations as expected — but `__napiModule` is assigned only when
90
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
91
+ // plugin factory runs while the emnapi module is being created, before the
92
+ // wasm is loaded and before any registration function runs, and its context
93
+ // carries the very same manager instance.
94
+ let __wasiThreadManager
95
+
96
+ function __captureWasiThreadManager(context) {
97
+ if (context && context.PThread) {
98
+ __wasiThreadManager = context.PThread
99
+ }
100
+ return {}
101
+ }
102
+
103
+ function __getWasiThreadManager() {
104
+ const manager =
105
+ __wasiThreadManager !== undefined
106
+ ? __wasiThreadManager
107
+ : __napiModule
108
+ ? __napiModule.PThread
109
+ : undefined
110
+ if (manager && typeof manager.terminateWorker === 'function') {
111
+ return manager
112
+ }
113
+ return undefined
114
+ }
115
+ let __napiInstance
116
+ let __emnapiContextDestroyed = false
117
+ let __emnapiContextDestroyPromise
118
+ let __emnapiWasmEnvCleanupPrepared = false
119
+ let __emnapiWasmEnvCleanupPreparing = false
120
+ let __emnapiWasmEnvCleanupRan = false
121
+ let __emnapiWasmEnvCleanupDrained = false
122
+ let __emnapiWasmEnvCleanupDrainPromise
123
+ let __wasiDisposed = false
124
+ let __wasiAsyncWorkDrainPromise
125
+ let __wasiDisposePromise
126
+ let __completeWasiDisposal = function () {}
127
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
128
+ // that stopped short of destroying the context. See
129
+ // `__rollbackWasiInitialization`.
130
+ let __retainWasiRollbackForRetry = function () {}
131
+
132
+ function __isThenable(value) {
133
+ return (
134
+ value !== null &&
135
+ (typeof value === 'object' || typeof value === 'function') &&
136
+ typeof value.then === 'function'
137
+ )
138
+ }
139
+
140
+ function __createCleanupError(errors, message) {
141
+ if (errors.length === 1) {
142
+ return errors[0]
143
+ }
144
+ const __AggregateError = globalThis.AggregateError
145
+ if (typeof __AggregateError === 'function') {
146
+ return new __AggregateError(errors, message)
147
+ }
148
+ const error = new Error(message)
149
+ error.errors = errors
150
+ return error
151
+ }
152
+
153
+ function __attachCleanupErrors(error, cleanupErrors) {
154
+ if (cleanupErrors.length === 0) {
155
+ return error
156
+ }
157
+ const cleanupError = __createCleanupError(
158
+ cleanupErrors,
159
+ 'WASI binding cleanup failed',
160
+ )
161
+ try {
162
+ if (
163
+ error &&
164
+ (typeof error === 'object' || typeof error === 'function')
165
+ ) {
166
+ if (error.cause === undefined) {
167
+ error.cause = cleanupError
168
+ if (error.cause === cleanupError) {
169
+ return error
170
+ }
171
+ }
172
+ if (Array.isArray(error.cleanupErrors)) {
173
+ error.cleanupErrors.push(cleanupError)
174
+ return error
175
+ } else {
176
+ const attachedCleanupErrors = [cleanupError]
177
+ error.cleanupErrors = attachedCleanupErrors
178
+ if (error.cleanupErrors === attachedCleanupErrors) {
179
+ return error
180
+ }
181
+ }
182
+ }
183
+ } catch {}
184
+ const aggregate = __createCleanupError(
185
+ [error, cleanupError],
186
+ 'WASI binding initialization and cleanup failed',
187
+ )
188
+ try {
189
+ aggregate.cause = error
190
+ } catch {}
191
+ return aggregate
192
+ }
193
+
194
+ function __wrapEmnapiContextDestroyForSettlement(
195
+ context,
196
+ prepareEnvCleanup,
197
+ isPreparingEnvCleanup,
198
+ ) {
199
+ let destroy
200
+ try {
201
+ destroy = context.destroy
202
+ } catch {
203
+ return context
204
+ }
205
+ if (typeof destroy !== 'function') {
206
+ return context
207
+ }
208
+ try {
209
+ Object.defineProperty(context, 'destroy', {
210
+ configurable: true,
211
+ enumerable: false,
212
+ writable: true,
213
+ value: function () {
214
+ // Reentered from a promise hook that fired inside the barrier: the
215
+ // frame running it destroys as soon as it returns.
216
+ if (isPreparingEnvCleanup?.()) {
217
+ return
218
+ }
219
+ prepareEnvCleanup?.()
220
+ return Reflect.apply(destroy, this, arguments)
221
+ },
222
+ })
223
+ } catch {}
224
+ return context
225
+ }
226
+
227
+ function __isPreparingWasmEnvCleanup() {
228
+ return __emnapiWasmEnvCleanupPreparing
229
+ }
230
+
231
+ function __prepareWasmEnvCleanup() {
232
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
233
+ return
234
+ }
235
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
236
+ if (typeof prepare === 'function') {
237
+ // The addon settles the promises it cancels synchronously, under a
238
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
239
+ // here must not reach this export again.
240
+ __emnapiWasmEnvCleanupPreparing = true
241
+ try {
242
+ prepare()
243
+ } finally {
244
+ __emnapiWasmEnvCleanupPreparing = false
245
+ }
246
+ __emnapiWasmEnvCleanupRan = true
247
+ }
248
+ __emnapiWasmEnvCleanupPrepared = true
249
+ }
250
+
251
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
252
+ // on, so the drain turns below interleave with that dispatch instead of racing
253
+ // ahead of it on a faster queue.
254
+ const __scheduleMacrotask = (function () {
255
+ if (typeof setImmediate === 'function') {
256
+ return function (callback) {
257
+ setImmediate(callback)
258
+ }
259
+ }
260
+ const __MessageChannel = globalThis.MessageChannel
261
+ if (typeof __MessageChannel === 'function') {
262
+ return function (callback) {
263
+ const channel = new __MessageChannel()
264
+ channel.port1.onmessage = function () {
265
+ channel.port1.onmessage = null
266
+ try {
267
+ channel.port1.close()
268
+ } catch {}
269
+ try {
270
+ channel.port2.close()
271
+ } catch {}
272
+ callback()
273
+ }
274
+ channel.port2.postMessage(null)
275
+ }
276
+ }
277
+ return function (callback) {
278
+ setTimeout(callback, 0)
279
+ }
280
+ })()
281
+
282
+ // A real, *referenced* timer, for waits that must let the whole host make
283
+ // progress between looks — the async-work drain polls the addon rather than
284
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
285
+ // would spin the loop instead of yielding it. Falls back to the macrotask
286
+ // scheduler on a host without timers.
287
+ function __scheduleTimer(callback, delay) {
288
+ const setTimer = globalThis.setTimeout
289
+ if (typeof setTimer !== 'function') {
290
+ __scheduleMacrotask(callback)
291
+ return
292
+ }
293
+ try {
294
+ setTimer(callback, delay)
295
+ } catch {
296
+ __scheduleMacrotask(callback)
297
+ }
298
+ }
299
+
300
+ // Turns to wait for while the addon still reports queued settlements. Reaching
301
+ // zero is the only success. A counter still nonzero at this bound rejects the
302
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
303
+ // destroying the context over a still-queued settlement — the wait stays
304
+ // bounded either way.
305
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
306
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
307
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
308
+ // call made on this thread (two), plus a margin.
309
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
310
+
311
+ /**
312
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
313
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
314
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
315
+ * macrotask — two coalescing turns later, even for a call made on this very
316
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
317
+ * which drains the queue with a null env and *discards* whatever is still in it.
318
+ *
319
+ * So destroying without yielding first strands exactly the promises the barrier
320
+ * exists to settle. Yield real event-loop turns until the addon reports the
321
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
322
+ * macrotask run.
323
+ *
324
+ * Returns nothing when there is nothing to wait for, which keeps disposal
325
+ * synchronous in the common case.
326
+ *
327
+ * The "already drained" flag is set only once a wait has actually finished.
328
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
329
+ * that throws is enough — and a disposal that rejects stays retryable, so
330
+ * marking the drain complete up front would make the retry skip it and destroy
331
+ * the context with the barrier's settlements still queued.
332
+ *
333
+ * A wait that runs out of turns with the counter still nonzero rejects with
334
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
335
+ * "finished" is indistinguishable from the stranding above, and destroying
336
+ * would discard the very settlement the wait was for. The rejection leaves the
337
+ * flag unset and disposal retryable.
338
+ */
339
+ function __drainWasmEnvCleanup() {
340
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
341
+ return
342
+ }
343
+ if (__emnapiWasmEnvCleanupDrainPromise) {
344
+ return __emnapiWasmEnvCleanupDrainPromise
345
+ }
346
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
347
+ const observable = typeof pending === 'function'
348
+ if (observable) {
349
+ let queued
350
+ try {
351
+ queued = pending()
352
+ } catch {
353
+ __emnapiWasmEnvCleanupDrained = true
354
+ return
355
+ }
356
+ if (!queued) {
357
+ __emnapiWasmEnvCleanupDrained = true
358
+ return
359
+ }
360
+ }
361
+ const limit = observable
362
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
363
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
364
+ const drainPromise = (async () => {
365
+ let queued = 0
366
+ for (let turn = 0; turn < limit; turn++) {
367
+ await new Promise((resolve) => {
368
+ __scheduleMacrotask(resolve)
369
+ })
370
+ if (!observable) {
371
+ continue
372
+ }
373
+ try {
374
+ queued = pending()
375
+ } catch {
376
+ return
377
+ }
378
+ if (!queued) {
379
+ return
380
+ }
381
+ }
382
+ if (!observable) {
383
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
384
+ // contract — there is nothing to consult, so finishing the turns is
385
+ // finishing the drain.
386
+ return
387
+ }
388
+ // The counter is still nonzero after every turn the bound allows. The wait
389
+ // stays bounded — but claiming success here would be indistinguishable from
390
+ // the stranding this drain exists to prevent: disposal would go on to
391
+ // destroy the context, whose cleanup hook discards the still-queued
392
+ // settlement with a null env, and the promise it was for hangs forever.
393
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
394
+ // unset, dispose() (and the rollback) decline to destroy, and a later
395
+ // dispose() runs the drain again — by which time the queue has usually been
396
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
397
+ // attempt at most another bounded wait and a rejection, never a stranded
398
+ // promise; the process-exit teardown still reclaims the context.
399
+ const drainError = new Error(
400
+ 'the wasm environment still reports ' +
401
+ queued +
402
+ ' queued settlement(s) after ' +
403
+ limit +
404
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
405
+ )
406
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
407
+ throw drainError
408
+ })().then(
409
+ (value) => {
410
+ // Set only when the wait actually finished AND the queue was seen empty
411
+ // (or is unobservable): a drain that timed out with settlements still
412
+ // queued rejects above and must stay repeatable.
413
+ __emnapiWasmEnvCleanupDrained = true
414
+ __emnapiWasmEnvCleanupDrainPromise = undefined
415
+ return value
416
+ },
417
+ (error) => {
418
+ __emnapiWasmEnvCleanupDrainPromise = undefined
419
+ throw error
420
+ },
421
+ )
422
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
423
+ return drainPromise
424
+ }
425
+
426
+ function __destroyEmnapiContext() {
427
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
428
+ __emnapiContextDestroyed = true
429
+ return
430
+ }
431
+ if (__emnapiContextDestroyPromise) {
432
+ return __emnapiContextDestroyPromise
433
+ }
434
+
435
+ __prepareWasmEnvCleanup()
436
+ const result = __emnapiContext.destroy()
437
+ if (!__isThenable(result)) {
438
+ __emnapiContextDestroyed = true
439
+ return
440
+ }
441
+
442
+ const destroyPromise = Promise.resolve(result).then(
443
+ (value) => {
444
+ __emnapiContextDestroyed = true
445
+ return value
446
+ },
447
+ (error) => {
448
+ __emnapiContextDestroyPromise = undefined
449
+ throw error
450
+ },
451
+ )
452
+ __emnapiContextDestroyPromise = destroyPromise
453
+ return destroyPromise
454
+ }
455
+
456
+ /**
457
+ * Holds the event loop open until `work` settles.
458
+ *
459
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
460
+ * binding cannot keep a process alive, and referencing them again for the
461
+ * termination does not hold either — emnapi unreferences a worker the moment it
462
+ * reports `async-thread-ready`, which for a worker that was still starting
463
+ * lands *after* the termination began. Without a handle of its own, an
464
+ * `await dispose()` with nothing else pending exits the process with its
465
+ * promise unsettled, and everything after the `await` is skipped.
466
+ *
467
+ * The timer is cleared as soon as the work settles, so this never outlives the
468
+ * disposal that asked for it.
469
+ */
470
+ function __keepEventLoopAliveUntil(work) {
471
+ const setTimer = globalThis.setInterval
472
+ const clearTimer = globalThis.clearInterval
473
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
474
+ return work
475
+ }
476
+ let timer
477
+ try {
478
+ timer = setTimer(function () {}, 50)
479
+ } catch {
480
+ return work
481
+ }
482
+ const release = function () {
483
+ try {
484
+ clearTimer(timer)
485
+ } catch {}
486
+ }
487
+ return work.then(
488
+ (value) => {
489
+ release()
490
+ return value
491
+ },
492
+ (error) => {
493
+ release()
494
+ throw error
495
+ },
496
+ )
497
+ }
498
+
499
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
500
+ // ends when the addon reports zero, so this only decides how promptly disposal
501
+ // notices — not how long it waits.
502
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
503
+
504
+ /**
505
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
506
+ * would strand it.
507
+ *
508
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
509
+ * it is observable from JavaScript: the threadless archive resolves
510
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
511
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
512
+ * imports nor exports those symbols and the only brackets a loader could watch
513
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
514
+ * functions. The addon is the one place both flavors go through, so it answers
515
+ * for both, through the same kind of handshake the settlement drain uses:
516
+ *
517
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
518
+ * started. Those completion callbacks run with `napi_cancelled`, which
519
+ * napi-rs turns into a promise rejected with an `AbortError`.
520
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
521
+ * callback. Work already executing refuses cancellation and stays counted
522
+ * until it finishes normally — which it can, because this runs before the
523
+ * barrier, before `Context.destroy()` and before anything is terminated.
524
+ *
525
+ * Both exports are optional: an addon built against a napi crate that predates
526
+ * them drains nothing and keeps the previous behavior, exactly as the
527
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
528
+ *
529
+ * Returns nothing when there is nothing outstanding, which keeps disposal
530
+ * synchronous in the common case. The promise it returns otherwise never
531
+ * rejects.
532
+ *
533
+ * The wait has no deadline, and that is the point: giving up would destroy the
534
+ * environment with a completion callback still owed, which is the stranding
535
+ * this exists to prevent. A task whose `execute` never returns already keeps an
536
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
537
+ * rather than inventing a bound it cannot honor.
538
+ *
539
+ * Safe to call from inside a completion callback, which is reachable: settling
540
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
541
+ * being handed back, a threadsafe-function callback — and that JavaScript can
542
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
543
+ *
544
+ * - The addon keeps a work registered until its completion callback
545
+ * *finishes*, so the count read here is at least one and this takes the
546
+ * polling path instead of declaring the environment drained and tearing it
547
+ * down from inside the frame that is still settling a promise.
548
+ * - The poll is a timer, so it cannot run until the callback has returned to
549
+ * the host — by which time that work has left the registry. The count the
550
+ * next poll reads is the one taken after the callback finished.
551
+ *
552
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
553
+ * nested call joins this disposal rather than starting a second one.
554
+ */
555
+ function __drainWasiAsyncWork() {
556
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
557
+ return __wasiAsyncWorkDrainPromise
558
+ }
559
+ const exports = __napiInstance?.exports
560
+ const pending = exports?.napi_wasm_async_work_pending
561
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
562
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
563
+ return
564
+ }
565
+
566
+ const readPending = () => {
567
+ try {
568
+ return pending()
569
+ } catch (error) {
570
+ // A trap is the only way this call fails: it reads a counter and cannot
571
+ // allocate or call back into JavaScript. A trapped instance can no longer
572
+ // run anything, so its outstanding work is unreachable by definition —
573
+ // there is nothing left to wait for, and refusing to dispose would only
574
+ // keep a dead instance and its stuck counter alive. Best-effort here is
575
+ // the honest answer, and it is what disposal did before this drain
576
+ // existed.
577
+ //
578
+ // Only a trap. Anything else means the export is not what this loader
579
+ // thinks it is, which is a defect worth surfacing rather than disposing
580
+ // over.
581
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
582
+ return 0
583
+ }
584
+ throw error
585
+ }
586
+ }
587
+
588
+ if (!readPending()) {
589
+ return
590
+ }
591
+ try {
592
+ cancelPending()
593
+ } catch {
594
+ // Cancellation is an optimization: it bounds the wait by the work already
595
+ // executing. Failing it only means waiting for the whole queue instead.
596
+ }
597
+ if (!readPending()) {
598
+ return
599
+ }
600
+
601
+ const drainPromise = __keepEventLoopAliveUntil(
602
+ (async () => {
603
+ while (readPending()) {
604
+ await new Promise((resolve) => {
605
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
606
+ })
607
+ }
608
+ })(),
609
+ ).then(
610
+ () => {
611
+ __wasiAsyncWorkDrainPromise = undefined
612
+ },
613
+ (error) => {
614
+ // A wait that could not run is not a wait that finished. The only way
615
+ // here is a host whose timers and macrotask primitives all refuse, and
616
+ // the work is still outstanding — reporting success would destroy the
617
+ // environment over it, which is the stranding this exists to prevent.
618
+ // Reject instead: disposal stays retryable, and the context is not
619
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
620
+ __wasiAsyncWorkDrainPromise = undefined
621
+ throw error
622
+ },
623
+ )
624
+ __wasiAsyncWorkDrainPromise = drainPromise
625
+ return drainPromise
626
+ }
627
+
628
+ /**
629
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
630
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
631
+ * the manager's `exit` listener instead, which reports
632
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
633
+ * inside the emit — aborting the `once('exit')` that backs the terminate
634
+ * promise, so disposal never settles and the process dies with an uncaught
635
+ * exception. Mark the termination through the manager first.
636
+ *
637
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
638
+ * the initialization rollback runs on the one path where instantiation never
639
+ * returned, so `__napiModule` is still undefined there while the workers it
640
+ * spawned are already registered and loaded.
641
+ *
642
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
643
+ */
644
+ function __terminateWasiWorkers() {
645
+ const cleanupErrors = []
646
+ const pending = []
647
+ const threadManager = __getWasiThreadManager()
648
+
649
+ for (const worker of __wasiWorkers) {
650
+ let result
651
+ try {
652
+ if (threadManager) {
653
+ threadManager.terminateWorker(worker)
654
+ // `terminateWorker` leaves behind a reporter that logs every message
655
+ // still queued on the port, which Node flushes on exit. Nothing is
656
+ // listening for those any more.
657
+ worker.onmessage = undefined
658
+ }
659
+ result = worker.terminate()
660
+ } catch (error) {
661
+ cleanupErrors.push(error)
662
+ continue
663
+ }
664
+ if (__isThenable(result)) {
665
+ pending.push(
666
+ Promise.resolve(result).then(
667
+ () => {
668
+ __wasiWorkers.delete(worker)
669
+ },
670
+ (error) => {
671
+ cleanupErrors.push(error)
672
+ },
673
+ ),
674
+ )
675
+ } else {
676
+ __wasiWorkers.delete(worker)
677
+ }
678
+ }
679
+
680
+ const finish = () => {
681
+ if (cleanupErrors.length > 0) {
682
+ throw __createCleanupError(
683
+ cleanupErrors,
684
+ 'Failed to terminate WASI workers',
685
+ )
686
+ }
687
+ }
688
+ return pending.length > 0
689
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
690
+ : finish()
691
+ }
692
+
693
+ function __finishWasiDisposal() {
694
+ const workerResult = __terminateWasiWorkers()
695
+ if (__isThenable(workerResult)) {
696
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
697
+ }
698
+ return __completeWasiDisposal()
699
+ }
700
+
701
+ function __continueWasiDisposal() {
702
+ const destroyResult = __destroyEmnapiContext()
703
+ if (__isThenable(destroyResult)) {
704
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
705
+ }
706
+ return __finishWasiDisposal()
707
+ }
708
+
709
+ function __cleanUpWasmEnvForWasiDisposal() {
710
+ // Run the pre-teardown barrier, then let the settlements it queued actually
711
+ // reach JavaScript, and only then destroy the environment. Doing these two
712
+ // back to back is what strands them.
713
+ __prepareWasmEnvCleanup()
714
+ const drainResult = __drainWasmEnvCleanup()
715
+ if (__isThenable(drainResult)) {
716
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
717
+ }
718
+ return __continueWasiDisposal()
719
+ }
720
+
721
+ function __startWasiDisposal() {
722
+ // Outstanding `napi_async_work` goes first, while the environment is still
723
+ // completely live: the completion callbacks run addon code, and everything
724
+ // after this point takes that away from them — the barrier shuts the async
725
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
726
+ // the pool threads removes what would have reported the work finished.
727
+ const asyncWorkResult = __drainWasiAsyncWork()
728
+ if (__isThenable(asyncWorkResult)) {
729
+ return Promise.resolve(asyncWorkResult).then(
730
+ __cleanUpWasmEnvForWasiDisposal,
731
+ )
732
+ }
733
+ return __cleanUpWasmEnvForWasiDisposal()
734
+ }
735
+
736
+ /**
737
+ * Disposes this generated WASI binding.
738
+ *
739
+ * Access this function with:
740
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
741
+ */
742
+ function __disposeWasiBinding() {
743
+ if (__wasiDisposePromise) {
744
+ return __wasiDisposePromise
745
+ }
746
+ if (__wasiDisposed) {
747
+ return Promise.resolve()
748
+ }
749
+
750
+ let resolveDispose
751
+ let rejectDispose
752
+ const disposePromise = new Promise((resolve, reject) => {
753
+ resolveDispose = resolve
754
+ rejectDispose = reject
755
+ })
756
+ __wasiDisposePromise = disposePromise
757
+
758
+ let result
759
+ try {
760
+ result = __startWasiDisposal()
761
+ } catch (error) {
762
+ __wasiDisposePromise = undefined
763
+ rejectDispose(error)
764
+ return disposePromise
765
+ }
766
+
767
+ Promise.resolve(result).then(
768
+ (value) => {
769
+ __wasiDisposed = true
770
+ resolveDispose(value)
771
+ },
772
+ (error) => {
773
+ __wasiDisposePromise = undefined
774
+ rejectDispose(error)
775
+ },
776
+ )
777
+ return disposePromise
778
+ }
779
+
780
+ function __publishWasiDispose(exports) {
781
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
782
+ configurable: false,
783
+ enumerable: false,
784
+ value: __disposeWasiBinding,
785
+ writable: false,
786
+ })
787
+ }
788
+
789
+ function __finishWasiInitializationRollback(cleanupErrors) {
790
+ let workerResult
791
+ try {
792
+ workerResult = __terminateWasiWorkers()
793
+ } catch (cleanupError) {
794
+ cleanupErrors.push(cleanupError)
795
+ return cleanupErrors
796
+ }
797
+ if (__isThenable(workerResult)) {
798
+ return Promise.resolve(workerResult)
799
+ .catch((cleanupError) => {
800
+ cleanupErrors.push(cleanupError)
801
+ })
802
+ .then(() => cleanupErrors)
803
+ }
804
+ return cleanupErrors
805
+ }
806
+
807
+ function __destroyContextForWasiRollback(cleanupErrors) {
808
+ let destroyResult
809
+ try {
810
+ destroyResult = __destroyEmnapiContext()
811
+ } catch (cleanupError) {
812
+ cleanupErrors.push(cleanupError)
813
+ return __finishWasiInitializationRollback(cleanupErrors)
814
+ }
815
+ if (__isThenable(destroyResult)) {
816
+ return Promise.resolve(destroyResult)
817
+ .catch((cleanupError) => {
818
+ cleanupErrors.push(cleanupError)
819
+ })
820
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
821
+ }
822
+ return __finishWasiInitializationRollback(cleanupErrors)
823
+ }
824
+
825
+ /**
826
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
827
+ * hands it to whatever this flavor has that can still reclaim it.
828
+ */
829
+ function __retainFailedWasiRollback(cleanupErrors) {
830
+ try {
831
+ __retainWasiRollbackForRetry()
832
+ } catch (cleanupError) {
833
+ cleanupErrors.push(cleanupError)
834
+ }
835
+ return cleanupErrors
836
+ }
837
+
838
+ /**
839
+ * Initialization can fail *after* registration has already run, and registration
840
+ * runs with a live environment: a module-init hook can start async work and then
841
+ * return an error, and the promise it created may already have escaped into
842
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
843
+ * path needs the same drain the ordinary disposal does — destroying without
844
+ * yielding discards the queue with a null env and strands the promise.
845
+ *
846
+ * Stays synchronous when nothing is queued, which covers every failure before
847
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
848
+ *
849
+ * A barrier or drain that did *not* finish stops the rollback short of
850
+ * destroying, which is what `dispose()` already does — a rejected drain there
851
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
852
+ * two trades, and not because of what it saves:
853
+ *
854
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
855
+ * threadsafe function's cleanup hook, which drains the queue with a null env
856
+ * and discards it, so a promise that already escaped into JavaScript hangs
857
+ * forever with nothing left that could ever settle it.
858
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
859
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
860
+ * which this module's scope holds either way. What stopping short retains is
861
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
862
+ * - Retry is not theoretical. A rollback that records a cleanup error is
863
+ * already kept in the process-wide registry above, so re-`require()`ing this
864
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
865
+ * means the replay drains again rather than skipping it. Destroying first is
866
+ * what makes that retained record useless.
867
+ *
868
+ * The residual cost is honest: the CJS flavor hands the context to its
869
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
870
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
871
+ * throws while evaluating is permanently errored, so re-importing rethrows
872
+ * without re-running this file — and there the context stays until the realm
873
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
874
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
875
+ */
876
+ function __rollbackWasiInitialization() {
877
+ // The environment teardown this rollback performs, kept nested so it cannot
878
+ // be reached without the async-work drain below running first.
879
+ function __rollbackWasmEnvForWasiInitialization() {
880
+ const cleanupErrors = []
881
+ let drainResult
882
+ let settlementsUnreached = false
883
+ try {
884
+ __prepareWasmEnvCleanup()
885
+ drainResult = __drainWasmEnvCleanup()
886
+ } catch (cleanupError) {
887
+ cleanupErrors.push(cleanupError)
888
+ settlementsUnreached = true
889
+ }
890
+ if (__isThenable(drainResult)) {
891
+ return Promise.resolve(drainResult).then(
892
+ () => __destroyContextForWasiRollback(cleanupErrors),
893
+ (cleanupError) => {
894
+ cleanupErrors.push(cleanupError)
895
+ return __retainFailedWasiRollback(cleanupErrors)
896
+ },
897
+ )
898
+ }
899
+ if (settlementsUnreached) {
900
+ return __retainFailedWasiRollback(cleanupErrors)
901
+ }
902
+ return __destroyContextForWasiRollback(cleanupErrors)
903
+ }
904
+
905
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
906
+ // work before the load goes on to fail, and this rollback tears down exactly
907
+ // what those completions need. Settle them while everything is still live,
908
+ // before the barrier and the teardown above take that away.
909
+ //
910
+ // A drain that could not finish leaves async work possibly outstanding, and
911
+ // destroying the context over it would strand exactly what this rollback is
912
+ // there to settle. Stop short and retain instead — the same trade
913
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
914
+ // the context stays reclaimable by a retry or by this flavor's own
915
+ // last-resort teardown.
916
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
917
+ __retainFailedWasiRollback([cleanupError])
918
+ let asyncWorkResult
919
+ try {
920
+ asyncWorkResult = __drainWasiAsyncWork()
921
+ } catch (cleanupError) {
922
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
923
+ }
924
+ if (__isThenable(asyncWorkResult)) {
925
+ return Promise.resolve(asyncWorkResult).then(
926
+ __rollbackWasmEnvForWasiInitialization,
927
+ __retainAfterAsyncWorkDrainFailure,
928
+ )
929
+ }
930
+ return __rollbackWasmEnvForWasiInitialization()
931
+ }
932
+
933
+ let __wasiModule
934
+ let __napiModule
935
+
936
+ try {
937
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
938
+ __emnapiCreateContext({ autoDestroy: false }),
939
+ __prepareWasmEnvCleanup,
940
+ __isPreparingWasmEnvCleanup,
941
+ )
942
+ __emnapiContext.suppressDestroy()
943
+
944
+ ;({
945
+ instance: __napiInstance,
946
+ module: __wasiModule,
947
+ napiModule: __napiModule,
948
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
949
+ context: __emnapiContext,
950
+ asyncWorkPoolSize: 0,
951
+ plugins: [
952
+ __captureWasiThreadManager,
953
+ __emnapiAsyncWorkPlugin,
954
+ __emnapiTSFNPlugin,
955
+ ],
956
+ wasi: __wasi,
957
+ overwriteImports(importObject) {
958
+ importObject.env = {
959
+ ...importObject.env,
960
+ ...importObject.napi,
961
+ ...importObject.emnapi,
962
+ memory: __wasmMemory,
963
+ }
964
+ return importObject
965
+ },
966
+ beforeInit({ instance }) {
967
+ __napiInstance = instance
968
+ for (const name of Object.keys(instance.exports)) {
969
+ if (name.startsWith('__napi_register__')) {
970
+ instance.exports[name]()
971
+ }
972
+ }
973
+ },
974
+ }))
975
+ __publishWasiDispose(__napiModule.exports)
976
+ // The default export hands out this object; a named module export does not
977
+ // travel with it, so carry the marker on the binding itself too. After the
978
+ // host install, which hands the same object to addon-provided registration
979
+ // functions that may put anything on it, and inside this `try`, so a claimed
980
+ // name fails the load through the rollback below rather than past it.
981
+ __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
982
+ } catch (error) {
983
+ const cleanupErrors = await __rollbackWasiInitialization()
984
+ throw __attachCleanupErrors(error, cleanupErrors)
985
+ }
986
+ export default __napiModule.exports
987
+ export const transpileAsync = __napiModule.exports.transpileAsync
988
+ export const transpileNativeSync = __napiModule.exports.transpileNativeSync
989
+ export const transpileUtf16Async = __napiModule.exports.transpileUtf16Async
990
+ export const transpileUtf16Sync = __napiModule.exports.transpileUtf16Sync