@solidjs/compiler-wasm32-wasi 2.0.0-rc.2 → 2.0.0-rc.4

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,620 @@
1
+ import {
2
+ emnapiAsyncWorkPlugin as __emnapiAsyncWorkPlugin,
3
+ emnapiTSFNPlugin as __emnapiTSFNPlugin,
4
+ createOnMessage as __wasmCreateOnMessageForFsProxy,
5
+ instantiateNapiModule as __emnapiInstantiateNapiModule,
6
+ WASI as __WASI,
7
+ } from '@napi-rs/wasm-runtime'
8
+ import { createContext as __emnapiCreateContext } from '@emnapi/runtime'
9
+
10
+
11
+
12
+ const __wasi = new __WASI({
13
+ version: 'preview1',
14
+ })
15
+
16
+ const __wasmUrl = new URL('./compiler.wasm32-wasi.wasm', import.meta.url).href
17
+ const __wasmResponse = await globalThis.fetch(__wasmUrl)
18
+ if (!__wasmResponse.ok) {
19
+ throw new Error(
20
+ 'Failed to fetch WASI module ' +
21
+ __wasmUrl +
22
+ ': ' +
23
+ __wasmResponse.status +
24
+ ' ' +
25
+ (__wasmResponse.statusText || 'Unknown Status'),
26
+ )
27
+ }
28
+ const __wasmFile = await __wasmResponse.arrayBuffer()
29
+
30
+ const __sharedMemory = new WebAssembly.Memory({
31
+ initial: 4000,
32
+ maximum: 65536,
33
+ shared: true,
34
+ })
35
+ const __asyncWorkPoolSize = 4
36
+ const __workerPoolSize = Math.max(
37
+ 2,
38
+ globalThis.navigator?.hardwareConcurrency ?? 4,
39
+ )
40
+
41
+ let __emnapiContext
42
+
43
+ const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
44
+ const __wasiWorkers = new Set()
45
+ let __napiInstance
46
+ let __emnapiContextDestroyed = false
47
+ let __emnapiContextDestroyPromise
48
+ let __emnapiWasmEnvCleanupPrepared = false
49
+ let __emnapiWasmEnvCleanupRan = false
50
+ let __emnapiWasmEnvCleanupDrained = false
51
+ let __emnapiWasmEnvCleanupDrainPromise
52
+ let __wasiDisposed = false
53
+ let __wasiDisposePromise
54
+ let __completeWasiDisposal = function() {}
55
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
56
+ // that stopped short of destroying the context. See
57
+ // `__rollbackWasiInitialization`.
58
+ let __retainWasiRollbackForRetry = function() {}
59
+
60
+ function __isThenable(value) {
61
+ return (
62
+ value !== null &&
63
+ (typeof value === 'object' || typeof value === 'function') &&
64
+ typeof value.then === 'function'
65
+ )
66
+ }
67
+
68
+ function __createCleanupError(errors, message) {
69
+ if (errors.length === 1) {
70
+ return errors[0]
71
+ }
72
+ const __AggregateError = globalThis.AggregateError
73
+ if (typeof __AggregateError === 'function') {
74
+ return new __AggregateError(errors, message)
75
+ }
76
+ const error = new Error(message)
77
+ error.errors = errors
78
+ return error
79
+ }
80
+
81
+ function __attachCleanupErrors(error, cleanupErrors) {
82
+ if (cleanupErrors.length === 0) {
83
+ return error
84
+ }
85
+ const cleanupError = __createCleanupError(
86
+ cleanupErrors,
87
+ 'WASI binding cleanup failed',
88
+ )
89
+ try {
90
+ if (
91
+ error &&
92
+ (typeof error === 'object' || typeof error === 'function')
93
+ ) {
94
+ if (error.cause === undefined) {
95
+ error.cause = cleanupError
96
+ if (error.cause === cleanupError) {
97
+ return error
98
+ }
99
+ }
100
+ if (Array.isArray(error.cleanupErrors)) {
101
+ error.cleanupErrors.push(cleanupError)
102
+ return error
103
+ } else {
104
+ const attachedCleanupErrors = [cleanupError]
105
+ error.cleanupErrors = attachedCleanupErrors
106
+ if (error.cleanupErrors === attachedCleanupErrors) {
107
+ return error
108
+ }
109
+ }
110
+ }
111
+ } catch {}
112
+ const aggregate = __createCleanupError(
113
+ [error, cleanupError],
114
+ 'WASI binding initialization and cleanup failed',
115
+ )
116
+ try {
117
+ aggregate.cause = error
118
+ } catch {}
119
+ return aggregate
120
+ }
121
+
122
+ function __prepareWasmEnvCleanup() {
123
+ if (__emnapiWasmEnvCleanupPrepared) {
124
+ return
125
+ }
126
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
127
+ if (typeof prepare === 'function') {
128
+ prepare()
129
+ __emnapiWasmEnvCleanupRan = true
130
+ }
131
+ __emnapiWasmEnvCleanupPrepared = true
132
+ }
133
+
134
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
135
+ // on, so the drain turns below interleave with that dispatch instead of racing
136
+ // ahead of it on a faster queue.
137
+ const __scheduleMacrotask = (function () {
138
+ if (typeof setImmediate === 'function') {
139
+ return function (callback) {
140
+ setImmediate(callback)
141
+ }
142
+ }
143
+ const __MessageChannel = globalThis.MessageChannel
144
+ if (typeof __MessageChannel === 'function') {
145
+ return function (callback) {
146
+ const channel = new __MessageChannel()
147
+ channel.port1.onmessage = function () {
148
+ channel.port1.onmessage = null
149
+ try {
150
+ channel.port1.close()
151
+ } catch {}
152
+ try {
153
+ channel.port2.close()
154
+ } catch {}
155
+ callback()
156
+ }
157
+ channel.port2.postMessage(null)
158
+ }
159
+ }
160
+ return function (callback) {
161
+ setTimeout(callback, 0)
162
+ }
163
+ })()
164
+
165
+ // Turns to wait for while the addon still reports queued settlements. Reaching
166
+ // zero is the only success. A counter still nonzero at this bound rejects the
167
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
168
+ // destroying the context over a still-queued settlement — the wait stays
169
+ // bounded either way.
170
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
171
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
172
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
173
+ // call made on this thread (two), plus a margin.
174
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
175
+
176
+ /**
177
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
178
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
179
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
180
+ * macrotask — two coalescing turns later, even for a call made on this very
181
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
182
+ * which drains the queue with a null env and *discards* whatever is still in it.
183
+ *
184
+ * So destroying without yielding first strands exactly the promises the barrier
185
+ * exists to settle. Yield real event-loop turns until the addon reports the
186
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
187
+ * macrotask run.
188
+ *
189
+ * Returns nothing when there is nothing to wait for, which keeps disposal
190
+ * synchronous in the common case.
191
+ *
192
+ * The "already drained" flag is set only once a wait has actually finished.
193
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
194
+ * that throws is enough — and a disposal that rejects stays retryable, so
195
+ * marking the drain complete up front would make the retry skip it and destroy
196
+ * the context with the barrier's settlements still queued.
197
+ *
198
+ * A wait that runs out of turns with the counter still nonzero rejects with
199
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
200
+ * "finished" is indistinguishable from the stranding above, and destroying
201
+ * would discard the very settlement the wait was for. The rejection leaves the
202
+ * flag unset and disposal retryable.
203
+ */
204
+ function __drainWasmEnvCleanup() {
205
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
206
+ return
207
+ }
208
+ if (__emnapiWasmEnvCleanupDrainPromise) {
209
+ return __emnapiWasmEnvCleanupDrainPromise
210
+ }
211
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
212
+ const observable = typeof pending === 'function'
213
+ if (observable) {
214
+ let queued
215
+ try {
216
+ queued = pending()
217
+ } catch {
218
+ __emnapiWasmEnvCleanupDrained = true
219
+ return
220
+ }
221
+ if (!queued) {
222
+ __emnapiWasmEnvCleanupDrained = true
223
+ return
224
+ }
225
+ }
226
+ const limit = observable
227
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
228
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
229
+ const drainPromise = (async () => {
230
+ let queued = 0
231
+ for (let turn = 0; turn < limit; turn++) {
232
+ await new Promise((resolve) => {
233
+ __scheduleMacrotask(resolve)
234
+ })
235
+ if (!observable) {
236
+ continue
237
+ }
238
+ try {
239
+ queued = pending()
240
+ } catch {
241
+ return
242
+ }
243
+ if (!queued) {
244
+ return
245
+ }
246
+ }
247
+ if (!observable) {
248
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
249
+ // contract — there is nothing to consult, so finishing the turns is
250
+ // finishing the drain.
251
+ return
252
+ }
253
+ // The counter is still nonzero after every turn the bound allows. The wait
254
+ // stays bounded — but claiming success here would be indistinguishable from
255
+ // the stranding this drain exists to prevent: disposal would go on to
256
+ // destroy the context, whose cleanup hook discards the still-queued
257
+ // settlement with a null env, and the promise it was for hangs forever.
258
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
259
+ // unset, dispose() (and the rollback) decline to destroy, and a later
260
+ // dispose() runs the drain again — by which time the queue has usually been
261
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
262
+ // attempt at most another bounded wait and a rejection, never a stranded
263
+ // promise; the process-exit teardown still reclaims the context.
264
+ const drainError = new Error(
265
+ 'the wasm environment still reports ' +
266
+ queued +
267
+ ' queued settlement(s) after ' +
268
+ limit +
269
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
270
+ )
271
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
272
+ throw drainError
273
+ })().then(
274
+ (value) => {
275
+ // Set only when the wait actually finished AND the queue was seen empty
276
+ // (or is unobservable): a drain that timed out with settlements still
277
+ // queued rejects above and must stay repeatable.
278
+ __emnapiWasmEnvCleanupDrained = true
279
+ __emnapiWasmEnvCleanupDrainPromise = undefined
280
+ return value
281
+ },
282
+ (error) => {
283
+ __emnapiWasmEnvCleanupDrainPromise = undefined
284
+ throw error
285
+ },
286
+ )
287
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
288
+ return drainPromise
289
+ }
290
+
291
+ function __destroyEmnapiContext() {
292
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
293
+ __emnapiContextDestroyed = true
294
+ return
295
+ }
296
+ if (__emnapiContextDestroyPromise) {
297
+ return __emnapiContextDestroyPromise
298
+ }
299
+
300
+ __prepareWasmEnvCleanup()
301
+ const result = __emnapiContext.destroy()
302
+ if (!__isThenable(result)) {
303
+ __emnapiContextDestroyed = true
304
+ return
305
+ }
306
+
307
+ const destroyPromise = Promise.resolve(result).then(
308
+ (value) => {
309
+ __emnapiContextDestroyed = true
310
+ return value
311
+ },
312
+ (error) => {
313
+ __emnapiContextDestroyPromise = undefined
314
+ throw error
315
+ },
316
+ )
317
+ __emnapiContextDestroyPromise = destroyPromise
318
+ return destroyPromise
319
+ }
320
+
321
+ function __terminateWasiWorkers() {
322
+ const cleanupErrors = []
323
+ const pending = []
324
+
325
+ for (const worker of __wasiWorkers) {
326
+ let result
327
+ try {
328
+ result = worker.terminate()
329
+ } catch (error) {
330
+ cleanupErrors.push(error)
331
+ continue
332
+ }
333
+ if (__isThenable(result)) {
334
+ pending.push(
335
+ Promise.resolve(result).then(
336
+ () => {
337
+ __wasiWorkers.delete(worker)
338
+ },
339
+ (error) => {
340
+ cleanupErrors.push(error)
341
+ },
342
+ ),
343
+ )
344
+ } else {
345
+ __wasiWorkers.delete(worker)
346
+ }
347
+ }
348
+
349
+ const finish = () => {
350
+ if (cleanupErrors.length > 0) {
351
+ throw __createCleanupError(
352
+ cleanupErrors,
353
+ 'Failed to terminate WASI workers',
354
+ )
355
+ }
356
+ }
357
+ return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
358
+ }
359
+
360
+ function __finishWasiDisposal() {
361
+ const workerResult = __terminateWasiWorkers()
362
+ if (__isThenable(workerResult)) {
363
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
364
+ }
365
+ return __completeWasiDisposal()
366
+ }
367
+
368
+ function __continueWasiDisposal() {
369
+ const destroyResult = __destroyEmnapiContext()
370
+ if (__isThenable(destroyResult)) {
371
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
372
+ }
373
+ return __finishWasiDisposal()
374
+ }
375
+
376
+ function __startWasiDisposal() {
377
+ // Run the pre-teardown barrier, then let the settlements it queued actually
378
+ // reach JavaScript, and only then destroy the environment. Doing these two
379
+ // back to back is what strands them.
380
+ __prepareWasmEnvCleanup()
381
+ const drainResult = __drainWasmEnvCleanup()
382
+ if (__isThenable(drainResult)) {
383
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
384
+ }
385
+ return __continueWasiDisposal()
386
+ }
387
+
388
+ /**
389
+ * Disposes this generated WASI binding.
390
+ *
391
+ * Access this function with:
392
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
393
+ */
394
+ function __disposeWasiBinding() {
395
+ if (__wasiDisposePromise) {
396
+ return __wasiDisposePromise
397
+ }
398
+ if (__wasiDisposed) {
399
+ return Promise.resolve()
400
+ }
401
+
402
+ let resolveDispose
403
+ let rejectDispose
404
+ const disposePromise = new Promise((resolve, reject) => {
405
+ resolveDispose = resolve
406
+ rejectDispose = reject
407
+ })
408
+ __wasiDisposePromise = disposePromise
409
+
410
+ let result
411
+ try {
412
+ result = __startWasiDisposal()
413
+ } catch (error) {
414
+ __wasiDisposePromise = undefined
415
+ rejectDispose(error)
416
+ return disposePromise
417
+ }
418
+
419
+ Promise.resolve(result).then(
420
+ (value) => {
421
+ __wasiDisposed = true
422
+ resolveDispose(value)
423
+ },
424
+ (error) => {
425
+ __wasiDisposePromise = undefined
426
+ rejectDispose(error)
427
+ },
428
+ )
429
+ return disposePromise
430
+ }
431
+
432
+ function __publishWasiDispose(exports) {
433
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
434
+ configurable: false,
435
+ enumerable: false,
436
+ value: __disposeWasiBinding,
437
+ writable: false,
438
+ })
439
+ }
440
+
441
+ function __finishWasiInitializationRollback(cleanupErrors) {
442
+ let workerResult
443
+ try {
444
+ workerResult = __terminateWasiWorkers()
445
+ } catch (cleanupError) {
446
+ cleanupErrors.push(cleanupError)
447
+ return cleanupErrors
448
+ }
449
+ if (__isThenable(workerResult)) {
450
+ return Promise.resolve(workerResult)
451
+ .catch((cleanupError) => {
452
+ cleanupErrors.push(cleanupError)
453
+ })
454
+ .then(() => cleanupErrors)
455
+ }
456
+ return cleanupErrors
457
+ }
458
+
459
+ function __destroyContextForWasiRollback(cleanupErrors) {
460
+ let destroyResult
461
+ try {
462
+ destroyResult = __destroyEmnapiContext()
463
+ } catch (cleanupError) {
464
+ cleanupErrors.push(cleanupError)
465
+ return __finishWasiInitializationRollback(cleanupErrors)
466
+ }
467
+ if (__isThenable(destroyResult)) {
468
+ return Promise.resolve(destroyResult)
469
+ .catch((cleanupError) => {
470
+ cleanupErrors.push(cleanupError)
471
+ })
472
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
473
+ }
474
+ return __finishWasiInitializationRollback(cleanupErrors)
475
+ }
476
+
477
+ /**
478
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
479
+ * hands it to whatever this flavor has that can still reclaim it.
480
+ */
481
+ function __retainFailedWasiRollback(cleanupErrors) {
482
+ try {
483
+ __retainWasiRollbackForRetry()
484
+ } catch (cleanupError) {
485
+ cleanupErrors.push(cleanupError)
486
+ }
487
+ return cleanupErrors
488
+ }
489
+
490
+ /**
491
+ * Initialization can fail *after* registration has already run, and registration
492
+ * runs with a live environment: a module-init hook can start async work and then
493
+ * return an error, and the promise it created may already have escaped into
494
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
495
+ * path needs the same drain the ordinary disposal does — destroying without
496
+ * yielding discards the queue with a null env and strands the promise.
497
+ *
498
+ * Stays synchronous when nothing is queued, which covers every failure before
499
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
500
+ *
501
+ * A barrier or drain that did *not* finish stops the rollback short of
502
+ * destroying, which is what `dispose()` already does — a rejected drain there
503
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
504
+ * two trades, and not because of what it saves:
505
+ *
506
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
507
+ * threadsafe function's cleanup hook, which drains the queue with a null env
508
+ * and discards it, so a promise that already escaped into JavaScript hangs
509
+ * forever with nothing left that could ever settle it.
510
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
511
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
512
+ * which this module's scope holds either way. What stopping short retains is
513
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
514
+ * - Retry is not theoretical. A rollback that records a cleanup error is
515
+ * already kept in the process-wide registry above, so re-`require()`ing this
516
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
517
+ * means the replay drains again rather than skipping it. Destroying first is
518
+ * what makes that retained record useless.
519
+ *
520
+ * The residual cost is honest: the CJS flavor hands the context to its
521
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
522
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
523
+ * throws while evaluating is permanently errored, so re-importing rethrows
524
+ * without re-running this file — and there the context stays until the realm
525
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
526
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
527
+ */
528
+ function __rollbackWasiInitialization() {
529
+ const cleanupErrors = []
530
+ let drainResult
531
+ let settlementsUnreached = false
532
+ try {
533
+ __prepareWasmEnvCleanup()
534
+ drainResult = __drainWasmEnvCleanup()
535
+ } catch (cleanupError) {
536
+ cleanupErrors.push(cleanupError)
537
+ settlementsUnreached = true
538
+ }
539
+ if (__isThenable(drainResult)) {
540
+ return Promise.resolve(drainResult).then(
541
+ () => __destroyContextForWasiRollback(cleanupErrors),
542
+ (cleanupError) => {
543
+ cleanupErrors.push(cleanupError)
544
+ return __retainFailedWasiRollback(cleanupErrors)
545
+ },
546
+ )
547
+ }
548
+ if (settlementsUnreached) {
549
+ return __retainFailedWasiRollback(cleanupErrors)
550
+ }
551
+ return __destroyContextForWasiRollback(cleanupErrors)
552
+ }
553
+
554
+ let __wasiModule
555
+ let __napiModule
556
+
557
+ try {
558
+ __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
559
+ __emnapiContext.suppressDestroy()
560
+
561
+ ;({
562
+ instance: __napiInstance,
563
+ module: __wasiModule,
564
+ napiModule: __napiModule,
565
+ } = await __emnapiInstantiateNapiModule(__wasmFile, {
566
+ context: __emnapiContext,
567
+ asyncWorkPoolSize: __asyncWorkPoolSize,
568
+ reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },
569
+ plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
570
+ wasi: __wasi,
571
+ onCreateWorker() {
572
+ const worker = new Worker(new URL('@solidjs/compiler-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url), {
573
+ type: 'module',
574
+ })
575
+ __wasiWorkers.add(worker)
576
+
577
+ worker.addEventListener('message', (event) => {
578
+ if (event.data && typeof event.data === 'object' && event.data.type === 'error') {
579
+ const __CustomEvent = globalThis.CustomEvent
580
+ if (
581
+ typeof globalThis.dispatchEvent === 'function' &&
582
+ typeof __CustomEvent === 'function'
583
+ ) {
584
+ globalThis.dispatchEvent(
585
+ new __CustomEvent('napi-rs-worker-error', { detail: event.data }),
586
+ )
587
+ }
588
+ }
589
+ })
590
+
591
+ return worker
592
+ },
593
+ overwriteImports(importObject) {
594
+ importObject.env = {
595
+ ...importObject.env,
596
+ ...importObject.napi,
597
+ ...importObject.emnapi,
598
+ memory: __sharedMemory,
599
+ }
600
+ return importObject
601
+ },
602
+ beforeInit({ instance }) {
603
+ __napiInstance = instance
604
+ for (const name of Object.keys(instance.exports)) {
605
+ if (name.startsWith('__napi_register__')) {
606
+ instance.exports[name]()
607
+ }
608
+ }
609
+ },
610
+ }))
611
+ __publishWasiDispose(__napiModule.exports)
612
+ } catch (error) {
613
+ const cleanupErrors = await __rollbackWasiInitialization()
614
+ throw __attachCleanupErrors(error, cleanupErrors)
615
+ }
616
+ export default __napiModule.exports
617
+ export const transform = __napiModule.exports.transform
618
+ export const transformDirectives = __napiModule.exports.transformDirectives
619
+ export const transformLazy = __napiModule.exports.transformLazy
620
+ export const transformRefresh = __napiModule.exports.transformRefresh