@phron/image-wasm32-wasip1 0.0.0 → 0.1.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,1404 @@
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('./phron-image.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
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
121
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
122
+ // tell those two apart on its own: it is raised both for a purely synchronous
123
+ // frame — which must not be re-entered, and which nothing outside it can
124
+ // finish — and across this window, which spans real event-loop turns, so a
125
+ // caller that cannot yield can land in the middle of one. That caller can close
126
+ // this window, because `…_finish` is idempotent and joins, which is exactly
127
+ // what the single call does. See `__prepareWasmEnvCleanup`.
128
+ let __finishParkedWasmEnvCleanup
129
+ // Raised while a caller that can still yield is driving the barrier, so the
130
+ // queue it leaves behind is expected rather than lost. See
131
+ // `__reportUnreachedWasmEnvSettlements`.
132
+ let __emnapiWasmEnvCleanupYielding = false
133
+ let __emnapiWasmEnvSettlementLossReported = false
134
+ let __emnapiWasmEnvCleanupRan = false
135
+ let __emnapiWasmEnvCleanupDrained = false
136
+ let __emnapiWasmEnvCleanupDrainPromise
137
+ let __wasiDisposed = false
138
+ let __wasiAsyncWorkDrainPromise
139
+ let __wasiDisposePromise
140
+ let __completeWasiDisposal = function () {}
141
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
142
+ // that stopped short of destroying the context. See
143
+ // `__rollbackWasiInitialization`.
144
+ let __retainWasiRollbackForRetry = function () {}
145
+
146
+ function __isThenable(value) {
147
+ return (
148
+ value !== null &&
149
+ (typeof value === 'object' || typeof value === 'function') &&
150
+ typeof value.then === 'function'
151
+ )
152
+ }
153
+
154
+ function __createCleanupError(errors, message) {
155
+ if (errors.length === 1) {
156
+ return errors[0]
157
+ }
158
+ const __AggregateError = globalThis.AggregateError
159
+ if (typeof __AggregateError === 'function') {
160
+ return new __AggregateError(errors, message)
161
+ }
162
+ const error = new Error(message)
163
+ error.errors = errors
164
+ return error
165
+ }
166
+
167
+ function __attachCleanupErrors(error, cleanupErrors) {
168
+ if (cleanupErrors.length === 0) {
169
+ return error
170
+ }
171
+ const cleanupError = __createCleanupError(
172
+ cleanupErrors,
173
+ 'WASI binding cleanup failed',
174
+ )
175
+ try {
176
+ if (
177
+ error &&
178
+ (typeof error === 'object' || typeof error === 'function')
179
+ ) {
180
+ if (error.cause === undefined) {
181
+ error.cause = cleanupError
182
+ if (error.cause === cleanupError) {
183
+ return error
184
+ }
185
+ }
186
+ if (Array.isArray(error.cleanupErrors)) {
187
+ error.cleanupErrors.push(cleanupError)
188
+ return error
189
+ } else {
190
+ const attachedCleanupErrors = [cleanupError]
191
+ error.cleanupErrors = attachedCleanupErrors
192
+ if (error.cleanupErrors === attachedCleanupErrors) {
193
+ return error
194
+ }
195
+ }
196
+ }
197
+ } catch {}
198
+ const aggregate = __createCleanupError(
199
+ [error, cleanupError],
200
+ 'WASI binding initialization and cleanup failed',
201
+ )
202
+ try {
203
+ aggregate.cause = error
204
+ } catch {}
205
+ return aggregate
206
+ }
207
+
208
+ function __wrapEmnapiContextDestroyForSettlement(
209
+ context,
210
+ prepareEnvCleanup,
211
+ isPreparingEnvCleanup,
212
+ ) {
213
+ let destroy
214
+ try {
215
+ destroy = context.destroy
216
+ } catch {
217
+ return context
218
+ }
219
+ if (typeof destroy !== 'function') {
220
+ return context
221
+ }
222
+ try {
223
+ Object.defineProperty(context, 'destroy', {
224
+ configurable: true,
225
+ enumerable: false,
226
+ writable: true,
227
+ value: function () {
228
+ // Reentered from a promise hook that fired inside the barrier: the
229
+ // frame running it destroys as soon as it returns.
230
+ if (isPreparingEnvCleanup?.()) {
231
+ return
232
+ }
233
+ prepareEnvCleanup?.()
234
+ return Reflect.apply(destroy, this, arguments)
235
+ },
236
+ })
237
+ } catch {}
238
+ return context
239
+ }
240
+
241
+ function __isPreparingWasmEnvCleanup() {
242
+ return __emnapiWasmEnvCleanupPreparing
243
+ }
244
+
245
+ function __prepareWasmEnvCleanup() {
246
+ if (__emnapiWasmEnvCleanupPrepared) {
247
+ return
248
+ }
249
+ // A handshake parked between its two halves is one this frame can close, and
250
+ // must: every caller of this function is about to destroy the context, and
251
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
252
+ // the last thing the process runs, and `Context.destroy()` takes the
253
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
254
+ // this degrades to exactly the single call below. Leaving it open instead
255
+ // destroys the context with the barrier still raised, the runtime never
256
+ // joined and the workers never drained.
257
+ const finishParked = __finishParkedWasmEnvCleanup
258
+ if (finishParked !== undefined) {
259
+ finishParked()
260
+ __reportUnreachedWasmEnvSettlements()
261
+ return
262
+ }
263
+ if (__emnapiWasmEnvCleanupPreparing) {
264
+ return
265
+ }
266
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
267
+ if (typeof prepare === 'function') {
268
+ // The addon settles the promises it cancels synchronously, under a
269
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
270
+ // here must not reach this export again.
271
+ __emnapiWasmEnvCleanupPreparing = true
272
+ try {
273
+ prepare()
274
+ } finally {
275
+ __emnapiWasmEnvCleanupPreparing = false
276
+ }
277
+ __emnapiWasmEnvCleanupRan = true
278
+ __reportUnreachedWasmEnvSettlements()
279
+ }
280
+ __emnapiWasmEnvCleanupPrepared = true
281
+ }
282
+
283
+ /**
284
+ * Say so when the barrier leaves settlements queued and nothing is left that
285
+ * could deliver them.
286
+ *
287
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
288
+ * dispatch its queue. Every other caller of the barrier destroys in the same
289
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
290
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
291
+ * that queue with a null env and discards it. The promises those settlements
292
+ * were for then hang forever, silently.
293
+ *
294
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
295
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
296
+ * teardown down with it. Destroying anyway is still the right trade — the queue
297
+ * is already unreachable by then.
298
+ */
299
+ function __reportUnreachedWasmEnvSettlements() {
300
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
301
+ return
302
+ }
303
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
304
+ if (typeof pending !== 'function') {
305
+ return
306
+ }
307
+ let queued
308
+ try {
309
+ queued = pending()
310
+ } catch {
311
+ return
312
+ }
313
+ if (!queued) {
314
+ return
315
+ }
316
+ __emnapiWasmEnvSettlementLossReported = true
317
+ try {
318
+ const consoleHost = globalThis.console
319
+ if (consoleHost && typeof consoleHost.error === 'function') {
320
+ consoleHost.error(
321
+ "napi-rs: the wasm environment is being destroyed with " +
322
+ queued +
323
+ " queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.",
324
+ )
325
+ }
326
+ } catch {}
327
+ }
328
+
329
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
330
+ // on, so the drain turns below interleave with that dispatch instead of racing
331
+ // ahead of it on a faster queue.
332
+ const __scheduleMacrotask = (function () {
333
+ if (typeof setImmediate === 'function') {
334
+ return function (callback) {
335
+ setImmediate(callback)
336
+ }
337
+ }
338
+ const __MessageChannel = globalThis.MessageChannel
339
+ if (typeof __MessageChannel === 'function') {
340
+ return function (callback) {
341
+ const channel = new __MessageChannel()
342
+ channel.port1.onmessage = function () {
343
+ channel.port1.onmessage = null
344
+ try {
345
+ channel.port1.close()
346
+ } catch {}
347
+ try {
348
+ channel.port2.close()
349
+ } catch {}
350
+ callback()
351
+ }
352
+ channel.port2.postMessage(null)
353
+ }
354
+ }
355
+ return function (callback) {
356
+ setTimeout(callback, 0)
357
+ }
358
+ })()
359
+
360
+ // A real, *referenced* timer, for waits that must let the whole host make
361
+ // progress between looks — the async-work drain polls the addon rather than
362
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
363
+ // would spin the loop instead of yielding it. Falls back to the macrotask
364
+ // scheduler on a host without timers.
365
+ function __scheduleTimer(callback, delay) {
366
+ const setTimer = globalThis.setTimeout
367
+ if (typeof setTimer !== 'function') {
368
+ __scheduleMacrotask(callback)
369
+ return
370
+ }
371
+ try {
372
+ setTimer(callback, delay)
373
+ } catch {
374
+ __scheduleMacrotask(callback)
375
+ }
376
+ }
377
+
378
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
379
+ // reason the async-work drain uses one: this polls the addon instead of
380
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
381
+ // the loop instead of yielding it.
382
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
383
+ // Arrivals it takes before the poll paces on the host's timers alone. One
384
+ // proves nothing: a timer armed before the host's timers stopped still fires.
385
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
386
+ // How long a parked turn's own timer must already have been due before a
387
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
388
+ // against the event loop's clock, which is read once per iteration, while
389
+ // these are `Date.now()` readings taken part-way through one, so the two
390
+ // drift apart by however long the loop has been inside the current iteration.
391
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
392
+ // How long a backup itself waits. What is left of it after the slack and one
393
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
394
+ // parked turn from the last backup armed while the host's timers still
395
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
396
+ // `__armWasmRuntimePollStallBackup`.
397
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
398
+
399
+ /**
400
+ * Pacing state for one runtime-work poll.
401
+ *
402
+ * Per poll, never per module: whether the host's timers arrive is not a
403
+ * property of the module. A host can lose its timers between two disposals,
404
+ * and in the deferred shape every instance shares this module — one healthy
405
+ * instance must not disarm the fallback for the next one.
406
+ */
407
+ function __createWasmRuntimePollPace() {
408
+ return {
409
+ // Timers armed by *this* poll that have actually arrived.
410
+ arrivals: 0,
411
+ // The turn waiting on a timer alone *right now* — undefined whenever no
412
+ // turn is parked — and when that turn's own timer came due.
413
+ settleTurn: undefined,
414
+ turnTimerDueAt: 0,
415
+ }
416
+ }
417
+
418
+ /**
419
+ * The backup that ends a turn whose timer is never going to arrive.
420
+ *
421
+ * Once the poll paces on the timer alone it has nothing left to fall back on
422
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
423
+ * the turn that parks, and a parked poll schedules nothing that could notice.
424
+ * So every turn arms one of these before it yields, and each one compares due
425
+ * times instead of measuring how long the parked turn has been waiting.
426
+ *
427
+ * Invariant: a parked turn is ended by the newest backup that was armed while
428
+ * the host's timers still worked, and a backup ends a turn only when that
429
+ * turn's own timer was already due a whole window before the backup itself.
430
+ * Neither half turns on how far apart the arms happen to fall — what bounds
431
+ * the rescue is how far back that newest live backup is:
432
+ *
433
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
434
+ * turn due a whole window earlier is still parked proves that turn's timer
435
+ * was dropped rather than merely late. That same comparison is what leaves a
436
+ * healthy host alone: there the turn's timer has already run and cleared
437
+ * `settleTurn` before any backup due after it can look.
438
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
439
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
440
+ * primitives and the macrotask wins, so such a turn can end with its own
441
+ * timer — and the backup armed one line before it — already dead. The
442
+ * arrival that then flips the poll onto the timer alone can itself be a
443
+ * timer armed before the host's timers died. So the turn that parks can sit
444
+ * two turns past the last live arm, and the newest live backup is due
445
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
446
+ * Arming on every turn is what holds it to two, rather than however far back
447
+ * a throttle last let one through.
448
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
449
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
450
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
451
+ * Past that the turn stays parked and the disposal promise never settles.
452
+ * The bound is deliberate: reaching it takes a host that drops timers
453
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
454
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
455
+ * the second.
456
+ *
457
+ * The poll then goes back to arming both primitives until two fresh arrivals
458
+ * prove the timers again. A host that stops running the timers it has
459
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
460
+ * pending rather than wedging the thread — the same outcome as a blocking
461
+ * closure that never returns. Unreferenced wherever the host allows it: the
462
+ * poll's own turn timers are what keep the loop alive, never these.
463
+ */
464
+ function __armWasmRuntimePollStallBackup(pace) {
465
+ const setTimer = globalThis.setTimeout
466
+ if (typeof setTimer !== 'function') {
467
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
468
+ // already, and that one cannot park.
469
+ return
470
+ }
471
+ // Read before arming, so this never claims to be due earlier than the timer
472
+ // actually is: a backup ends a turn only when it is provably due after it.
473
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
474
+ let handle
475
+ try {
476
+ handle = setTimer(() => {
477
+ const settleTurn = pace.settleTurn
478
+ if (
479
+ !settleTurn ||
480
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
481
+ ) {
482
+ // No turn is parked, or the parked one's timer came due too close to
483
+ // this backup to call it dropped — it may still arrive, and the turn
484
+ // that armed it armed a backup due a whole window after *that*.
485
+ return
486
+ }
487
+ pace.arrivals = 0
488
+ pace.settleTurn = undefined
489
+ settleTurn()
490
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
491
+ } catch {
492
+ return
493
+ }
494
+ if (handle && typeof handle.unref === 'function') {
495
+ try {
496
+ handle.unref()
497
+ } catch {}
498
+ }
499
+ }
500
+
501
+ /**
502
+ * One turn of the runtime-work poll.
503
+ *
504
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
505
+ * missing or throws, but not when it is present, returns a handle and never
506
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
507
+ * host whose timers belong to an IO context that is already gone. That host
508
+ * would park this poll forever, and the poll is unbounded, so nothing would
509
+ * ever call `…_finish`.
510
+ *
511
+ * Arm both primitives until timers armed by this poll have arrived twice, and
512
+ * let whichever lands first end the turn; the loser resolves nothing. A host
513
+ * with working timers therefore pays the double arming for the first turn or
514
+ * two — the macrotask wins the race, but the timers behind it still arrive and
515
+ * are counted — and paces on the timer alone from then on, instead of spinning
516
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
517
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
518
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
519
+ * which ends the parked turn and puts this poll back on both.
520
+ */
521
+ function __yieldWasmRuntimePollTurn(pace) {
522
+ // Armed before the turn yields, and by every turn: what rescues a parked
523
+ // turn has to have been armed while the host's timers still worked, and the
524
+ // turn that parks is the one whose own timer is already dead.
525
+ __armWasmRuntimePollStallBackup(pace)
526
+ return new Promise((resolve) => {
527
+ let settled = false
528
+ const settle = () => {
529
+ if (settled) {
530
+ return
531
+ }
532
+ settled = true
533
+ if (pace.settleTurn === settle) {
534
+ // Nothing is parked any more: a backup running later must not read a
535
+ // due time this turn has already answered.
536
+ pace.settleTurn = undefined
537
+ }
538
+ resolve()
539
+ }
540
+ __scheduleTimer(() => {
541
+ pace.arrivals++
542
+ settle()
543
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
544
+ // Read next to the arming it describes; see
545
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
546
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
547
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
548
+ __scheduleMacrotask(settle)
549
+ return
550
+ }
551
+ // Paced by the timer alone from here; the backup is what ends this turn if
552
+ // the timer never arrives.
553
+ pace.settleTurn = settle
554
+ pace.turnTimerDueAt = turnTimerDueAt
555
+ })
556
+ }
557
+
558
+ /**
559
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
560
+ * event-loop turns in the middle.
561
+ *
562
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
563
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
564
+ * waits on is this one, the only thread that can give a running blocking
565
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
566
+ * for work that can never finish. The addon's two-phase form splits that:
567
+ * `…_begin` stops the runtime without joining and reports whether anything is
568
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
569
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
570
+ * entire point.
571
+ *
572
+ * The poll has no deadline, for the same reason the async-work drain below has
573
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
574
+ * work it would join is the work that is waiting for a turn from this thread —
575
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
576
+ * thread can no longer be reached. A blocking closure that never returns keeps
577
+ * the disposal promise pending instead, exactly as a task whose `execute` never
578
+ * returns already keeps an *undisposed* process alive. The host contract is in
579
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
580
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
581
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
582
+ *
583
+ * Feature-detected like every other export in this teardown, so an addon built
584
+ * against a napi crate that predates the split keeps the single blocking call.
585
+ * Returns nothing whenever the handshake finished without yielding, which keeps
586
+ * an idle disposal synchronous.
587
+ */
588
+ function __prepareWasmEnvCleanupWithTurns() {
589
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
590
+ return
591
+ }
592
+ const exports = __napiInstance?.exports
593
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
594
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
595
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
596
+ // No split to use. The settlement drain still follows this, so the queue
597
+ // the single call leaves behind is expected rather than lost.
598
+ __emnapiWasmEnvCleanupYielding = true
599
+ try {
600
+ __prepareWasmEnvCleanup()
601
+ } finally {
602
+ __emnapiWasmEnvCleanupYielding = false
603
+ }
604
+ return
605
+ }
606
+ const workPending = exports?.napi_wasm_runtime_work_pending
607
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
608
+ // from one of the JavaScript handlers they run is the same no-op it is inside
609
+ // the single call: the barrier is up and the runtime is mid-teardown, and
610
+ // destroying between the halves would strand exactly what this delivers.
611
+ __emnapiWasmEnvCleanupPreparing = true
612
+ let live
613
+ try {
614
+ live = begin()
615
+ } catch (error) {
616
+ __emnapiWasmEnvCleanupPreparing = false
617
+ throw error
618
+ }
619
+ __emnapiWasmEnvCleanupRan = true
620
+ const finishCleanup = () => {
621
+ if (__emnapiWasmEnvCleanupPrepared) {
622
+ // Already closed by a caller that could not yield — the 'exit' teardown
623
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
624
+ // is idempotent, but the flags it lowers are not: running it again here
625
+ // would clear a `preparing` some later barrier had raised.
626
+ return
627
+ }
628
+ __finishParkedWasmEnvCleanup = undefined
629
+ try {
630
+ finish()
631
+ } finally {
632
+ __emnapiWasmEnvCleanupPreparing = false
633
+ }
634
+ __emnapiWasmEnvCleanupPrepared = true
635
+ }
636
+ if (!live || typeof workPending !== 'function') {
637
+ finishCleanup()
638
+ return
639
+ }
640
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
641
+ // a caller that cannot yield is entitled to end this handshake itself.
642
+ __finishParkedWasmEnvCleanup = finishCleanup
643
+ return (async () => {
644
+ // Unbounded, exactly like the async-work drain below. The wait ends when
645
+ // the addon reports its runtime work finished; the turns spent here are
646
+ // what let that happen at all.
647
+ const pace = __createWasmRuntimePollPace()
648
+ for (;;) {
649
+ await __yieldWasmRuntimePollTurn(pace)
650
+ try {
651
+ if (!workPending()) {
652
+ return
653
+ }
654
+ } catch {
655
+ // A trap is the only way this fails, and a trapped instance has no
656
+ // reachable work left. Stop polling and finish.
657
+ return
658
+ }
659
+ }
660
+ })().then(finishCleanup, finishCleanup)
661
+ }
662
+
663
+ // Turns to wait for while the addon still reports queued settlements. Reaching
664
+ // zero is the only success. A counter still nonzero at this bound rejects the
665
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
666
+ // destroying the context over a still-queued settlement — the wait stays
667
+ // bounded either way.
668
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
669
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
670
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
671
+ // call made on this thread (two), plus a margin.
672
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
673
+
674
+ /**
675
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
676
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
677
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
678
+ * macrotask — two coalescing turns later, even for a call made on this very
679
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
680
+ * which drains the queue with a null env and *discards* whatever is still in it.
681
+ *
682
+ * So destroying without yielding first strands exactly the promises the barrier
683
+ * exists to settle. Yield real event-loop turns until the addon reports the
684
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
685
+ * macrotask run.
686
+ *
687
+ * Returns nothing when there is nothing to wait for, which keeps disposal
688
+ * synchronous in the common case.
689
+ *
690
+ * The "already drained" flag is set only once a wait has actually finished.
691
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
692
+ * that throws is enough — and a disposal that rejects stays retryable, so
693
+ * marking the drain complete up front would make the retry skip it and destroy
694
+ * the context with the barrier's settlements still queued.
695
+ *
696
+ * A wait that runs out of turns with the counter still nonzero rejects with
697
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
698
+ * "finished" is indistinguishable from the stranding above, and destroying
699
+ * would discard the very settlement the wait was for. The rejection leaves the
700
+ * flag unset and disposal retryable.
701
+ */
702
+ function __drainWasmEnvCleanup() {
703
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
704
+ return
705
+ }
706
+ if (__emnapiWasmEnvCleanupDrainPromise) {
707
+ return __emnapiWasmEnvCleanupDrainPromise
708
+ }
709
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
710
+ const observable = typeof pending === 'function'
711
+ if (observable) {
712
+ let queued
713
+ try {
714
+ queued = pending()
715
+ } catch {
716
+ __emnapiWasmEnvCleanupDrained = true
717
+ return
718
+ }
719
+ if (!queued) {
720
+ __emnapiWasmEnvCleanupDrained = true
721
+ return
722
+ }
723
+ }
724
+ const limit = observable
725
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
726
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
727
+ const drainPromise = (async () => {
728
+ let queued = 0
729
+ for (let turn = 0; turn < limit; turn++) {
730
+ await new Promise((resolve) => {
731
+ __scheduleMacrotask(resolve)
732
+ })
733
+ if (!observable) {
734
+ continue
735
+ }
736
+ try {
737
+ queued = pending()
738
+ } catch {
739
+ return
740
+ }
741
+ if (!queued) {
742
+ return
743
+ }
744
+ }
745
+ if (!observable) {
746
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
747
+ // contract — there is nothing to consult, so finishing the turns is
748
+ // finishing the drain.
749
+ return
750
+ }
751
+ // The counter is still nonzero after every turn the bound allows. The wait
752
+ // stays bounded — but claiming success here would be indistinguishable from
753
+ // the stranding this drain exists to prevent: disposal would go on to
754
+ // destroy the context, whose cleanup hook discards the still-queued
755
+ // settlement with a null env, and the promise it was for hangs forever.
756
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
757
+ // unset, dispose() (and the rollback) decline to destroy, and a later
758
+ // dispose() runs the drain again — by which time the queue has usually been
759
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
760
+ // attempt at most another bounded wait and a rejection, never a stranded
761
+ // promise; the process-exit teardown still reclaims the context.
762
+ const drainError = new Error(
763
+ 'the wasm environment still reports ' +
764
+ queued +
765
+ ' queued settlement(s) after ' +
766
+ limit +
767
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
768
+ )
769
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
770
+ throw drainError
771
+ })().then(
772
+ (value) => {
773
+ // Set only when the wait actually finished AND the queue was seen empty
774
+ // (or is unobservable): a drain that timed out with settlements still
775
+ // queued rejects above and must stay repeatable.
776
+ __emnapiWasmEnvCleanupDrained = true
777
+ __emnapiWasmEnvCleanupDrainPromise = undefined
778
+ return value
779
+ },
780
+ (error) => {
781
+ __emnapiWasmEnvCleanupDrainPromise = undefined
782
+ throw error
783
+ },
784
+ )
785
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
786
+ return drainPromise
787
+ }
788
+
789
+ function __destroyEmnapiContext() {
790
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
791
+ __emnapiContextDestroyed = true
792
+ return
793
+ }
794
+ if (__emnapiContextDestroyPromise) {
795
+ return __emnapiContextDestroyPromise
796
+ }
797
+
798
+ __prepareWasmEnvCleanup()
799
+ if (__isPreparingWasmEnvCleanup()) {
800
+ // Reached from inside the synchronous barrier — a promise hook one of the
801
+ // settlements above ran, which is the reentrancy the destroy wrapper
802
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
803
+ // no-op and answer `undefined`, and recording that as a completed destroy
804
+ // is what makes the frame that *did* start the barrier skip the real one
805
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
806
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
807
+ // moment it returns. The deferred loader carries the same backstop. A
808
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
809
+ // rather than skipping it.
810
+ return
811
+ }
812
+ const result = __emnapiContext.destroy()
813
+ if (!__isThenable(result)) {
814
+ __emnapiContextDestroyed = true
815
+ return
816
+ }
817
+
818
+ const destroyPromise = Promise.resolve(result).then(
819
+ (value) => {
820
+ __emnapiContextDestroyed = true
821
+ return value
822
+ },
823
+ (error) => {
824
+ __emnapiContextDestroyPromise = undefined
825
+ throw error
826
+ },
827
+ )
828
+ __emnapiContextDestroyPromise = destroyPromise
829
+ return destroyPromise
830
+ }
831
+
832
+ /**
833
+ * Holds the event loop open until `work` settles.
834
+ *
835
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
836
+ * binding cannot keep a process alive, and referencing them again for the
837
+ * termination does not hold either — emnapi unreferences a worker the moment it
838
+ * reports `async-thread-ready`, which for a worker that was still starting
839
+ * lands *after* the termination began. Without a handle of its own, an
840
+ * `await dispose()` with nothing else pending exits the process with its
841
+ * promise unsettled, and everything after the `await` is skipped.
842
+ *
843
+ * The timer is cleared as soon as the work settles, so this never outlives the
844
+ * disposal that asked for it.
845
+ */
846
+ function __keepEventLoopAliveUntil(work) {
847
+ const setTimer = globalThis.setInterval
848
+ const clearTimer = globalThis.clearInterval
849
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
850
+ return work
851
+ }
852
+ let timer
853
+ try {
854
+ timer = setTimer(function () {}, 50)
855
+ } catch {
856
+ return work
857
+ }
858
+ const release = function () {
859
+ try {
860
+ clearTimer(timer)
861
+ } catch {}
862
+ }
863
+ return work.then(
864
+ (value) => {
865
+ release()
866
+ return value
867
+ },
868
+ (error) => {
869
+ release()
870
+ throw error
871
+ },
872
+ )
873
+ }
874
+
875
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
876
+ // ends when the addon reports zero, so this only decides how promptly disposal
877
+ // notices — not how long it waits.
878
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
879
+
880
+ /**
881
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
882
+ * would strand it.
883
+ *
884
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
885
+ * it is observable from JavaScript: the threadless archive resolves
886
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
887
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
888
+ * imports nor exports those symbols and the only brackets a loader could watch
889
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
890
+ * functions. The addon is the one place both flavors go through, so it answers
891
+ * for both, through the same kind of handshake the settlement drain uses:
892
+ *
893
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
894
+ * started. Those completion callbacks run with `napi_cancelled`, which
895
+ * napi-rs turns into a promise rejected with an `AbortError`.
896
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
897
+ * callback. Work already executing refuses cancellation and stays counted
898
+ * until it finishes normally — which it can, because this runs before the
899
+ * barrier, before `Context.destroy()` and before anything is terminated.
900
+ *
901
+ * Both exports are optional: an addon built against a napi crate that predates
902
+ * them drains nothing and keeps the previous behavior, exactly as the
903
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
904
+ *
905
+ * Returns nothing when there is nothing outstanding, which keeps disposal
906
+ * synchronous in the common case. The promise it returns otherwise never
907
+ * rejects.
908
+ *
909
+ * The wait has no deadline, and that is the point: giving up would destroy the
910
+ * environment with a completion callback still owed, which is the stranding
911
+ * this exists to prevent. A task whose `execute` never returns already keeps an
912
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
913
+ * rather than inventing a bound it cannot honor.
914
+ *
915
+ * Safe to call from inside a completion callback, which is reachable: settling
916
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
917
+ * being handed back, a threadsafe-function callback — and that JavaScript can
918
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
919
+ *
920
+ * - The addon keeps a work registered until its completion callback
921
+ * *finishes*, so the count read here is at least one and this takes the
922
+ * polling path instead of declaring the environment drained and tearing it
923
+ * down from inside the frame that is still settling a promise.
924
+ * - The poll is a timer, so it cannot run until the callback has returned to
925
+ * the host — by which time that work has left the registry. The count the
926
+ * next poll reads is the one taken after the callback finished.
927
+ *
928
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
929
+ * nested call joins this disposal rather than starting a second one.
930
+ */
931
+ function __drainWasiAsyncWork() {
932
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
933
+ return __wasiAsyncWorkDrainPromise
934
+ }
935
+ const exports = __napiInstance?.exports
936
+ const pending = exports?.napi_wasm_async_work_pending
937
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
938
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
939
+ return
940
+ }
941
+
942
+ const readPending = () => {
943
+ try {
944
+ return pending()
945
+ } catch (error) {
946
+ // A trap is the only way this call fails: it reads a counter and cannot
947
+ // allocate or call back into JavaScript. A trapped instance can no longer
948
+ // run anything, so its outstanding work is unreachable by definition —
949
+ // there is nothing left to wait for, and refusing to dispose would only
950
+ // keep a dead instance and its stuck counter alive. Best-effort here is
951
+ // the honest answer, and it is what disposal did before this drain
952
+ // existed.
953
+ //
954
+ // Only a trap. Anything else means the export is not what this loader
955
+ // thinks it is, which is a defect worth surfacing rather than disposing
956
+ // over.
957
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
958
+ return 0
959
+ }
960
+ throw error
961
+ }
962
+ }
963
+
964
+ if (!readPending()) {
965
+ return
966
+ }
967
+ try {
968
+ cancelPending()
969
+ } catch {
970
+ // Cancellation is an optimization: it bounds the wait by the work already
971
+ // executing. Failing it only means waiting for the whole queue instead.
972
+ }
973
+ if (!readPending()) {
974
+ return
975
+ }
976
+
977
+ const drainPromise = __keepEventLoopAliveUntil(
978
+ (async () => {
979
+ while (readPending()) {
980
+ await new Promise((resolve) => {
981
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
982
+ })
983
+ }
984
+ })(),
985
+ ).then(
986
+ () => {
987
+ __wasiAsyncWorkDrainPromise = undefined
988
+ },
989
+ (error) => {
990
+ // A wait that could not run is not a wait that finished. The only way
991
+ // here is a host whose timers and macrotask primitives all refuse, and
992
+ // the work is still outstanding — reporting success would destroy the
993
+ // environment over it, which is the stranding this exists to prevent.
994
+ // Reject instead: disposal stays retryable, and the context is not
995
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
996
+ __wasiAsyncWorkDrainPromise = undefined
997
+ throw error
998
+ },
999
+ )
1000
+ __wasiAsyncWorkDrainPromise = drainPromise
1001
+ return drainPromise
1002
+ }
1003
+
1004
+ /**
1005
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1006
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1007
+ * the manager's `exit` listener instead, which reports
1008
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1009
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1010
+ * promise, so disposal never settles and the process dies with an uncaught
1011
+ * exception. Mark the termination through the manager first.
1012
+ *
1013
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1014
+ * the initialization rollback runs on the one path where instantiation never
1015
+ * returned, so `__napiModule` is still undefined there while the workers it
1016
+ * spawned are already registered and loaded.
1017
+ *
1018
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1019
+ */
1020
+ function __terminateWasiWorkers() {
1021
+ const cleanupErrors = []
1022
+ const pending = []
1023
+ const threadManager = __getWasiThreadManager()
1024
+
1025
+ for (const worker of __wasiWorkers) {
1026
+ let result
1027
+ try {
1028
+ if (threadManager) {
1029
+ threadManager.terminateWorker(worker)
1030
+ // `terminateWorker` leaves behind a reporter that logs every message
1031
+ // still queued on the port, which Node flushes on exit. Nothing is
1032
+ // listening for those any more.
1033
+ worker.onmessage = undefined
1034
+ }
1035
+ result = worker.terminate()
1036
+ } catch (error) {
1037
+ cleanupErrors.push(error)
1038
+ continue
1039
+ }
1040
+ if (__isThenable(result)) {
1041
+ pending.push(
1042
+ Promise.resolve(result).then(
1043
+ () => {
1044
+ __wasiWorkers.delete(worker)
1045
+ },
1046
+ (error) => {
1047
+ cleanupErrors.push(error)
1048
+ },
1049
+ ),
1050
+ )
1051
+ } else {
1052
+ __wasiWorkers.delete(worker)
1053
+ }
1054
+ }
1055
+
1056
+ const finish = () => {
1057
+ if (cleanupErrors.length > 0) {
1058
+ throw __createCleanupError(
1059
+ cleanupErrors,
1060
+ 'Failed to terminate WASI workers',
1061
+ )
1062
+ }
1063
+ }
1064
+ return pending.length > 0
1065
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1066
+ : finish()
1067
+ }
1068
+
1069
+ function __finishWasiDisposal() {
1070
+ const workerResult = __terminateWasiWorkers()
1071
+ if (__isThenable(workerResult)) {
1072
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
1073
+ }
1074
+ return __completeWasiDisposal()
1075
+ }
1076
+
1077
+ function __continueWasiDisposal() {
1078
+ const destroyResult = __destroyEmnapiContext()
1079
+ if (__isThenable(destroyResult)) {
1080
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
1081
+ }
1082
+ return __finishWasiDisposal()
1083
+ }
1084
+
1085
+ function __drainWasmEnvForWasiDisposal() {
1086
+ const drainResult = __drainWasmEnvCleanup()
1087
+ if (__isThenable(drainResult)) {
1088
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
1089
+ }
1090
+ return __continueWasiDisposal()
1091
+ }
1092
+
1093
+ function __cleanUpWasmEnvForWasiDisposal() {
1094
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1095
+ // for, when the addon has one — then let the settlements it queued actually
1096
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1097
+ // these back to back is what strands them.
1098
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1099
+ if (__isThenable(prepareResult)) {
1100
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1101
+ }
1102
+ return __drainWasmEnvForWasiDisposal()
1103
+ }
1104
+
1105
+ function __startWasiDisposal() {
1106
+ // Outstanding `napi_async_work` goes first, while the environment is still
1107
+ // completely live: the completion callbacks run addon code, and everything
1108
+ // after this point takes that away from them — the barrier shuts the async
1109
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1110
+ // the pool threads removes what would have reported the work finished.
1111
+ const asyncWorkResult = __drainWasiAsyncWork()
1112
+ if (__isThenable(asyncWorkResult)) {
1113
+ return Promise.resolve(asyncWorkResult).then(
1114
+ __cleanUpWasmEnvForWasiDisposal,
1115
+ )
1116
+ }
1117
+ return __cleanUpWasmEnvForWasiDisposal()
1118
+ }
1119
+
1120
+ /**
1121
+ * Disposes this generated WASI binding.
1122
+ *
1123
+ * Access this function with:
1124
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
1125
+ */
1126
+ function __disposeWasiBinding() {
1127
+ if (__wasiDisposePromise) {
1128
+ return __wasiDisposePromise
1129
+ }
1130
+ if (__wasiDisposed) {
1131
+ return Promise.resolve()
1132
+ }
1133
+
1134
+ let resolveDispose
1135
+ let rejectDispose
1136
+ const disposePromise = new Promise((resolve, reject) => {
1137
+ resolveDispose = resolve
1138
+ rejectDispose = reject
1139
+ })
1140
+ __wasiDisposePromise = disposePromise
1141
+
1142
+ let result
1143
+ try {
1144
+ result = __startWasiDisposal()
1145
+ } catch (error) {
1146
+ __wasiDisposePromise = undefined
1147
+ rejectDispose(error)
1148
+ return disposePromise
1149
+ }
1150
+
1151
+ Promise.resolve(result).then(
1152
+ (value) => {
1153
+ __wasiDisposed = true
1154
+ resolveDispose(value)
1155
+ },
1156
+ (error) => {
1157
+ __wasiDisposePromise = undefined
1158
+ rejectDispose(error)
1159
+ },
1160
+ )
1161
+ return disposePromise
1162
+ }
1163
+
1164
+ function __publishWasiDispose(exports) {
1165
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
1166
+ configurable: false,
1167
+ enumerable: false,
1168
+ value: __disposeWasiBinding,
1169
+ writable: false,
1170
+ })
1171
+ }
1172
+
1173
+ function __finishWasiInitializationRollback(cleanupErrors) {
1174
+ let workerResult
1175
+ try {
1176
+ workerResult = __terminateWasiWorkers()
1177
+ } catch (cleanupError) {
1178
+ cleanupErrors.push(cleanupError)
1179
+ return cleanupErrors
1180
+ }
1181
+ if (__isThenable(workerResult)) {
1182
+ return Promise.resolve(workerResult)
1183
+ .catch((cleanupError) => {
1184
+ cleanupErrors.push(cleanupError)
1185
+ })
1186
+ .then(() => cleanupErrors)
1187
+ }
1188
+ return cleanupErrors
1189
+ }
1190
+
1191
+ function __destroyContextForWasiRollback(cleanupErrors) {
1192
+ let destroyResult
1193
+ try {
1194
+ destroyResult = __destroyEmnapiContext()
1195
+ } catch (cleanupError) {
1196
+ cleanupErrors.push(cleanupError)
1197
+ return __finishWasiInitializationRollback(cleanupErrors)
1198
+ }
1199
+ if (__isThenable(destroyResult)) {
1200
+ return Promise.resolve(destroyResult)
1201
+ .catch((cleanupError) => {
1202
+ cleanupErrors.push(cleanupError)
1203
+ })
1204
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
1205
+ }
1206
+ return __finishWasiInitializationRollback(cleanupErrors)
1207
+ }
1208
+
1209
+ /**
1210
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
1211
+ * hands it to whatever this flavor has that can still reclaim it.
1212
+ */
1213
+ function __retainFailedWasiRollback(cleanupErrors) {
1214
+ try {
1215
+ __retainWasiRollbackForRetry()
1216
+ } catch (cleanupError) {
1217
+ cleanupErrors.push(cleanupError)
1218
+ }
1219
+ return cleanupErrors
1220
+ }
1221
+
1222
+ /**
1223
+ * Initialization can fail *after* registration has already run, and registration
1224
+ * runs with a live environment: a module-init hook can start async work and then
1225
+ * return an error, and the promise it created may already have escaped into
1226
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
1227
+ * path needs the same drain the ordinary disposal does — destroying without
1228
+ * yielding discards the queue with a null env and strands the promise.
1229
+ *
1230
+ * Stays synchronous when nothing is queued, which covers every failure before
1231
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
1232
+ *
1233
+ * A barrier or drain that did *not* finish stops the rollback short of
1234
+ * destroying, which is what `dispose()` already does — a rejected drain there
1235
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
1236
+ * two trades, and not because of what it saves:
1237
+ *
1238
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
1239
+ * threadsafe function's cleanup hook, which drains the queue with a null env
1240
+ * and discards it, so a promise that already escaped into JavaScript hangs
1241
+ * forever with nothing left that could ever settle it.
1242
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
1243
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
1244
+ * which this module's scope holds either way. What stopping short retains is
1245
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
1246
+ * - Retry is not theoretical. A rollback that records a cleanup error is
1247
+ * already kept in the process-wide registry above, so re-`require()`ing this
1248
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
1249
+ * means the replay drains again rather than skipping it. Destroying first is
1250
+ * what makes that retained record useless.
1251
+ *
1252
+ * The residual cost is honest: the CJS flavor hands the context to its
1253
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
1254
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
1255
+ * throws while evaluating is permanently errored, so re-importing rethrows
1256
+ * without re-running this file — and there the context stays until the realm
1257
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
1258
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
1259
+ */
1260
+ function __rollbackWasiInitialization() {
1261
+ // The environment teardown this rollback performs, kept nested so it cannot
1262
+ // be reached without the async-work drain below running first.
1263
+ function __rollbackWasmEnvForWasiInitialization() {
1264
+ const cleanupErrors = []
1265
+ let prepareResult
1266
+ try {
1267
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1268
+ } catch (cleanupError) {
1269
+ cleanupErrors.push(cleanupError)
1270
+ return __retainFailedWasiRollback(cleanupErrors)
1271
+ }
1272
+ if (__isThenable(prepareResult)) {
1273
+ return Promise.resolve(prepareResult).then(
1274
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1275
+ (cleanupError) => {
1276
+ cleanupErrors.push(cleanupError)
1277
+ return __retainFailedWasiRollback(cleanupErrors)
1278
+ },
1279
+ )
1280
+ }
1281
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1282
+ }
1283
+
1284
+ // The settlement drain of the rollback above, reached either straight away or
1285
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1286
+ // did not finish never gets here: it retains instead, exactly as a drain that
1287
+ // did not finish does.
1288
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1289
+ let drainResult
1290
+ try {
1291
+ drainResult = __drainWasmEnvCleanup()
1292
+ } catch (cleanupError) {
1293
+ cleanupErrors.push(cleanupError)
1294
+ return __retainFailedWasiRollback(cleanupErrors)
1295
+ }
1296
+ if (__isThenable(drainResult)) {
1297
+ return Promise.resolve(drainResult).then(
1298
+ () => __destroyContextForWasiRollback(cleanupErrors),
1299
+ (cleanupError) => {
1300
+ cleanupErrors.push(cleanupError)
1301
+ return __retainFailedWasiRollback(cleanupErrors)
1302
+ },
1303
+ )
1304
+ }
1305
+ return __destroyContextForWasiRollback(cleanupErrors)
1306
+ }
1307
+
1308
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1309
+ // work before the load goes on to fail, and this rollback tears down exactly
1310
+ // what those completions need. Settle them while everything is still live,
1311
+ // before the barrier and the teardown above take that away.
1312
+ //
1313
+ // A drain that could not finish leaves async work possibly outstanding, and
1314
+ // destroying the context over it would strand exactly what this rollback is
1315
+ // there to settle. Stop short and retain instead — the same trade
1316
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1317
+ // the context stays reclaimable by a retry or by this flavor's own
1318
+ // last-resort teardown.
1319
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1320
+ __retainFailedWasiRollback([cleanupError])
1321
+ let asyncWorkResult
1322
+ try {
1323
+ asyncWorkResult = __drainWasiAsyncWork()
1324
+ } catch (cleanupError) {
1325
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
1326
+ }
1327
+ if (__isThenable(asyncWorkResult)) {
1328
+ return Promise.resolve(asyncWorkResult).then(
1329
+ __rollbackWasmEnvForWasiInitialization,
1330
+ __retainAfterAsyncWorkDrainFailure,
1331
+ )
1332
+ }
1333
+ return __rollbackWasmEnvForWasiInitialization()
1334
+ }
1335
+
1336
+ let __wasiModule
1337
+ let __napiModule
1338
+
1339
+ try {
1340
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1341
+ __emnapiCreateContext({ autoDestroy: false }),
1342
+ __prepareWasmEnvCleanup,
1343
+ __isPreparingWasmEnvCleanup,
1344
+ )
1345
+ __emnapiContext.suppressDestroy()
1346
+
1347
+ ;({
1348
+ instance: __napiInstance,
1349
+ module: __wasiModule,
1350
+ napiModule: __napiModule,
1351
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
1352
+ context: __emnapiContext,
1353
+ asyncWorkPoolSize: 0,
1354
+ plugins: [
1355
+ __captureWasiThreadManager,
1356
+ __emnapiAsyncWorkPlugin,
1357
+ __emnapiTSFNPlugin,
1358
+ ],
1359
+ wasi: __wasi,
1360
+ overwriteImports(importObject) {
1361
+ importObject.env = {
1362
+ ...importObject.env,
1363
+ ...importObject.napi,
1364
+ ...importObject.emnapi,
1365
+ memory: __wasmMemory,
1366
+ }
1367
+ return importObject
1368
+ },
1369
+ beforeInit({ instance }) {
1370
+ __napiInstance = instance
1371
+ for (const name of Object.keys(instance.exports)) {
1372
+ if (name.startsWith('__napi_register__')) {
1373
+ instance.exports[name]()
1374
+ }
1375
+ }
1376
+ },
1377
+ }))
1378
+ __publishWasiDispose(__napiModule.exports)
1379
+ // The default export hands out this object; a named module export does not
1380
+ // travel with it, so carry the marker on the binding itself too. After the
1381
+ // host install, which hands the same object to addon-provided registration
1382
+ // functions that may put anything on it, and inside this `try`, so a claimed
1383
+ // name fails the load through the rollback below rather than past it.
1384
+ __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
1385
+ } catch (error) {
1386
+ const cleanupErrors = await __rollbackWasiInitialization()
1387
+ throw __attachCleanupErrors(error, cleanupErrors)
1388
+ }
1389
+ export default __napiModule.exports
1390
+ export const apiUrl = __napiModule.exports.apiUrl
1391
+ export const encodePath = __napiModule.exports.encodePath
1392
+ export const infoUrl = __napiModule.exports.infoUrl
1393
+ export const optionExpires = __napiModule.exports.optionExpires
1394
+ export const optionFormat = __napiModule.exports.optionFormat
1395
+ export const optionGravity = __napiModule.exports.optionGravity
1396
+ export const optionHeight = __napiModule.exports.optionHeight
1397
+ export const optionPreset = __napiModule.exports.optionPreset
1398
+ export const optionQuality = __napiModule.exports.optionQuality
1399
+ export const optionRaw = __napiModule.exports.optionRaw
1400
+ export const optionResize = __napiModule.exports.optionResize
1401
+ export const optionWidth = __napiModule.exports.optionWidth
1402
+ export const publicUrl = __napiModule.exports.publicUrl
1403
+ export const roundedExpiry = __napiModule.exports.roundedExpiry
1404
+ export const signUrl = __napiModule.exports.signUrl