@seanhogg/builderforce-webcontainers-core 2026.10.9 → 2026.10.10

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,149 @@
1
+ /**
2
+ * `node:wasi`: Node's `WASI` class, preview1, over the process's file system and
3
+ * stdio. napi-rs `wasm32-wasip1` bindings (oxc-parser under Nuxt, and others) load
4
+ * through it — single-threaded builds that need no shared memory, so no
5
+ * cross-origin isolation.
6
+ *
7
+ * Imports this does not implement (sockets, `proc_raise`) answer ENOSYS instead of
8
+ * failing instantiation: `wasiImport` holds every preview1 name. `poll_oneoff` reports every subscription ready at once: a
9
+ * WASI call cannot block a process that runs on the event loop.
10
+ */
11
+ import { CLOCK, ERRNO, Memory, attempt, guest, u64 } from './abi.js';
12
+ import { createWasiFiles, type WasiFs } from './files.js';
13
+
14
+ /** Every `wasi_snapshot_preview1` function: a module imports by name, so each must exist (ENOSYS when not implemented). */
15
+ const WASI_FUNCTIONS = [
16
+ 'args_get', 'args_sizes_get', 'environ_get', 'environ_sizes_get', 'clock_res_get', 'clock_time_get', 'fd_advise', 'fd_allocate', 'fd_close', 'fd_datasync',
17
+ 'fd_fdstat_get', 'fd_fdstat_set_flags', 'fd_fdstat_set_rights', 'fd_filestat_get', 'fd_filestat_set_size', 'fd_filestat_set_times', 'fd_pread', 'fd_prestat_get',
18
+ 'fd_prestat_dir_name', 'fd_pwrite', 'fd_read', 'fd_readdir', 'fd_renumber', 'fd_seek', 'fd_sync', 'fd_tell', 'fd_write', 'path_create_directory', 'path_filestat_get',
19
+ 'path_filestat_set_times', 'path_link', 'path_open', 'path_readlink', 'path_remove_directory', 'path_rename', 'path_symlink', 'path_unlink_file', 'poll_oneoff',
20
+ 'proc_exit', 'proc_raise', 'sched_yield', 'random_get', 'sock_accept', 'sock_recv', 'sock_send', 'sock_shutdown',
21
+ ] as const;
22
+
23
+ export interface WasiOptions {
24
+ /** Only `preview1` exists here; `unstable` is rejected. */
25
+ version?: 'preview1';
26
+ args?: string[];
27
+ env?: Record<string, string | undefined>;
28
+ preopens?: Record<string, string>;
29
+ returnOnExit?: boolean;
30
+ }
31
+
32
+ export interface WasiDeps {
33
+ fs: WasiFs;
34
+ stdout(bytes: Uint8Array): void;
35
+ stderr(bytes: Uint8Array): void;
36
+ exit(code: number): void;
37
+ }
38
+
39
+ interface WasiInstance {
40
+ exports: Record<string, unknown> & { memory?: WebAssembly.Memory; _start?: () => void; _initialize?: () => void };
41
+ }
42
+
43
+ const knownClock = (id: number) => id === CLOCK.REALTIME || id === CLOCK.MONOTONIC || id === CLOCK.PROCESS_CPUTIME || id === CLOCK.THREAD_CPUTIME;
44
+
45
+ /** `proc_exit`: unwinds the module's stack back to `start()`. */
46
+ class WasiExit extends Error {
47
+ constructor(readonly code: number) {
48
+ super(`WASI exit ${code}`);
49
+ }
50
+ }
51
+
52
+ export function createWasiModule(deps: WasiDeps): Record<string, unknown> {
53
+ class WASI {
54
+ readonly wasiImport: Record<string, (...args: any[]) => number | void>;
55
+ private memory?: WebAssembly.Memory;
56
+ private readonly returnOnExit: boolean;
57
+ private started = false;
58
+ private readonly closeAll: () => void;
59
+
60
+ constructor(options: WasiOptions = {}) {
61
+ if (options.version !== undefined && options.version !== 'preview1') throw new TypeError(`WASI version "${options.version}" is not supported: only 'preview1' is`);
62
+ this.returnOnExit = options.returnOnExit ?? true;
63
+ const args = options.args ?? [];
64
+ const env = Object.entries(options.env ?? {}).flatMap(([key, value]) => (value === undefined ? [] : [`${key}=${value}`]));
65
+ const memory = new Memory(() => {
66
+ if (!this.memory) throw new Error('WASI: the instance has not been started or initialized');
67
+ return this.memory;
68
+ });
69
+ const { closeAll, ...files } = createWasiFiles(deps.fs, deps, memory, options.preopens ?? {});
70
+ this.closeAll = closeAll;
71
+ const calls: Record<string, (...args: any[]) => number | void> = {
72
+ ...files,
73
+ args_get: (pointers: number, buffer: number) => attempt(() => memory.strings(args, pointers, buffer)),
74
+ args_sizes_get: (count: number, size: number) => attempt(() => memory.sizes(args, count, size)),
75
+ environ_get: (pointers: number, buffer: number) => attempt(() => memory.strings(env, pointers, buffer)),
76
+ environ_sizes_get: (count: number, size: number) => attempt(() => memory.sizes(env, count, size)),
77
+ clock_res_get: (id: number, result: number) => (knownClock(id) ? attempt(() => memory.u64(result, 1000n)) : ERRNO.INVAL),
78
+ clock_time_get: (id: number, _precision: bigint, result: number) =>
79
+ knownClock(id) ? attempt(() => memory.u64(result, id === CLOCK.REALTIME ? u64(Date.now()) * 1_000_000n : u64(performance.now() * 1_000_000))) : ERRNO.INVAL,
80
+ random_get: (buffer: number, length: number) =>
81
+ attempt(() => {
82
+ // Filled outside the module's memory, which may be shared: getRandomValues rejects a view over it.
83
+ for (let at = 0; at < length; at += 65536) {
84
+ const chunk = new Uint8Array(Math.min(65536, length - at));
85
+ crypto.getRandomValues(chunk);
86
+ memory.bytes(buffer + at, chunk.length).set(chunk);
87
+ }
88
+ }),
89
+ poll_oneoff: (subscriptions: number, events: number, count: number, ready: number) =>
90
+ attempt(() =>
91
+ guest(() => {
92
+ const view = memory.view;
93
+ for (let i = 0; i < count; i++) {
94
+ const sub = subscriptions + i * 48;
95
+ const event = events + i * 32;
96
+ memory.bytes(event, 32).fill(0);
97
+ view.setBigUint64(event, view.getBigUint64(sub, true), true); // userdata
98
+ view.setUint8(event + 10, view.getUint8(sub + 8)); // the subscription's type
99
+ }
100
+ view.setUint32(ready, count, true);
101
+ }),
102
+ ),
103
+ proc_exit: (code: number) => {
104
+ throw new WasiExit(code);
105
+ },
106
+ sched_yield: () => ERRNO.SUCCESS,
107
+ };
108
+ this.wasiImport = Object.fromEntries(WASI_FUNCTIONS.map((name) => [name, calls[name] ?? (() => ERRNO.NOSYS)]));
109
+ }
110
+
111
+ getImportObject(): Record<string, unknown> {
112
+ return { wasi_snapshot_preview1: this.wasiImport };
113
+ }
114
+
115
+ /** Run a command module's `_start`; answers its exit code (or exits the process, without `returnOnExit`). */
116
+ start(instance: WasiInstance): number | undefined {
117
+ const { _start } = this.attach(instance);
118
+ if (typeof _start !== 'function') throw new TypeError('instance.exports._start is not a function');
119
+ try {
120
+ _start();
121
+ return 0;
122
+ } catch (error) {
123
+ if (!(error instanceof WasiExit)) throw error;
124
+ if (this.returnOnExit) return error.code;
125
+ deps.exit(error.code);
126
+ return undefined;
127
+ } finally {
128
+ this.closeAll();
129
+ }
130
+ }
131
+
132
+ /** Set up a reactor module (`_initialize`, no `_start`). */
133
+ initialize(instance: WasiInstance): void {
134
+ const { _start, _initialize } = this.attach(instance);
135
+ if (typeof _start === 'function') throw new TypeError('instance.exports._start must not be a function for initialize()');
136
+ if (typeof _initialize === 'function') _initialize();
137
+ }
138
+
139
+ private attach(instance: WasiInstance): WasiInstance['exports'] {
140
+ if (this.started) throw new Error('WASI instance has already started');
141
+ this.started = true;
142
+ const memory = instance.exports.memory;
143
+ if (!(memory instanceof WebAssembly.Memory)) throw new TypeError('instance.exports.memory must be a WebAssembly.Memory');
144
+ this.memory = memory;
145
+ return instance.exports;
146
+ }
147
+ }
148
+ return { WASI };
149
+ }