@ai-ecoverse/slicc-kernel 1.193.0 → 1.193.2

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.
@@ -1,2 +1,2 @@
1
1
  export const HOST_SOURCE = "// src/cloudflare/process-host.ts\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport * as programImports from \"./imports.js\";\nimport { asyncProcessEntry } from \"./process.js\";\nimport program from \"./program.wasm\";\n\n// src/async/snapshots.ts\nvar SNAPSHOT_TTL_MS = 6e4;\nfunction forkSnapshots(ttlMs = SNAPSHOT_TTL_MS) {\n const held = /* @__PURE__ */ new Map();\n const release = (token) => {\n const entry = held.get(token);\n if (!entry) return;\n clearTimeout(entry.timer);\n held.delete(token);\n };\n return {\n keep(bytes) {\n const token = crypto.randomUUID();\n held.set(token, { bytes, timer: setTimeout(() => held.delete(token), ttlMs) });\n return { token, total: bytes.byteLength };\n },\n take(token) {\n const entry = held.get(token);\n release(token);\n return entry?.bytes;\n },\n read(token, offset, max) {\n const entry = held.get(token);\n if (!entry || !Number.isInteger(offset) || offset < 0) return void 0;\n const end = Math.min(entry.bytes.byteLength, offset + max);\n const bytes = entry.bytes.slice(offset, end);\n if (end >= entry.bytes.byteLength) release(token);\n return bytes;\n },\n release,\n get size() {\n return held.size;\n }\n };\n}\n\n// src/cloudflare/images.ts\nvar hex = (buffer) => Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\nasync function digest(data) {\n const bytes = typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n return hex(await crypto.subtle.digest(\"SHA-256\", bytes));\n}\n\n// src/cloudflare/process-end.ts\nimport { RpcTarget } from \"cloudflare:workers\";\n\n// src/cloudflare/rpc-pack.ts\nvar PIECE_BYTES = 16 * 2 ** 20;\nvar OUT_OF_BAND_BYTES = 4096;\nvar PART = \"\\0slicc-part\";\nvar TYPED = {\n Uint8Array,\n Int8Array,\n Uint8ClampedArray,\n Uint16Array,\n Int16Array,\n Uint32Array,\n Int32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array,\n DataView\n};\nfunction isPlain(value) {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\nfunction isBinary(value) {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n}\nfunction costOf(value, seen) {\n if (value === null || typeof value !== \"object\" || seen.has(value)) return 0;\n seen.add(value);\n if (value instanceof ArrayBuffer) return value.byteLength;\n if (ArrayBuffer.isView(value)) return value.buffer.byteLength;\n let cost = 0;\n if (Array.isArray(value)) for (const item of value) cost += costOf(item, seen);\n else if (isPlain(value)) for (const item of Object.values(value)) cost += costOf(item, seen);\n return cost;\n}\nfunction bytesOf(value) {\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n}\nfunction kindOf(value) {\n if (value instanceof ArrayBuffer) return \"ArrayBuffer\";\n const name = value.constructor.name;\n return name in TYPED ? name : \"Uint8Array\";\n}\nvar Stream = class {\n pieces = [];\n current = new Uint8Array(0);\n used = 0;\n offset = 0;\n write(bytes) {\n const at = this.offset;\n for (let done = 0; done < bytes.byteLength; ) {\n if (this.used === this.current.byteLength) {\n this.current = new Uint8Array(PIECE_BYTES);\n this.used = 0;\n this.pieces.push(this.current);\n }\n const n = Math.min(bytes.byteLength - done, this.current.byteLength - this.used);\n this.current.set(bytes.subarray(done, done + n), this.used);\n this.used += n;\n done += n;\n }\n this.offset += bytes.byteLength;\n return at;\n }\n finish() {\n const last = this.pieces.length - 1;\n if (last >= 0) this.pieces[last] = this.pieces[last].slice(0, this.used);\n return this.pieces;\n }\n};\nfunction rewrite(value, stream) {\n if (value === null || typeof value !== \"object\") return value;\n if (isBinary(value)) {\n const bytes = bytesOf(value);\n if (bytes.byteLength < OUT_OF_BAND_BYTES) {\n return bytes.buffer.byteLength === bytes.byteLength ? value : copyOf(value, bytes);\n }\n const placeholder = {\n [PART]: stream.write(bytes),\n length: bytes.byteLength,\n kind: kindOf(value)\n };\n return placeholder;\n }\n if (Array.isArray(value)) return value.map((item) => rewrite(item, stream));\n if (!isPlain(value)) return value;\n const out = {};\n for (const [key, item] of Object.entries(value)) out[key] = rewrite(item, stream);\n return out;\n}\nfunction copyOf(value, bytes) {\n return revive(kindOf(value), bytes.slice());\n}\nfunction revive(kind, bytes) {\n if (kind === \"ArrayBuffer\") return bytes.buffer;\n const make = TYPED[kind] ?? Uint8Array;\n return new make(bytes.buffer);\n}\nfunction pack(value) {\n if (costOf(value, /* @__PURE__ */ new Set()) <= PIECE_BYTES) return { value, pieces: [] };\n const stream = new Stream();\n const packed = rewrite(value, stream);\n return { value: packed, pieces: stream.finish() };\n}\nfunction joined(pieces) {\n if (pieces.length === 1) return pieces[0];\n const total = pieces.reduce((sum, piece) => sum + piece.byteLength, 0);\n const out = new Uint8Array(total);\n let at = 0;\n for (const piece of pieces) {\n out.set(piece, at);\n at += piece.byteLength;\n }\n return out;\n}\nfunction restore(value, stream) {\n if (value === null || typeof value !== \"object\" || isBinary(value)) return value;\n if (PART in value) {\n const { [PART]: at, length, kind } = value;\n return revive(kind, stream.slice(at, at + length));\n }\n if (Array.isArray(value)) return value.map((item) => restore(item, stream));\n if (!isPlain(value)) return value;\n const out = {};\n for (const [key, item] of Object.entries(value)) out[key] = restore(item, stream);\n return out;\n}\nfunction unpack(value, pieces) {\n if (pieces.length === 0) return value;\n return restore(value, joined(pieces));\n}\n\n// src/cloudflare/rpc-link.ts\nvar ignore = () => {\n};\nvar DISPOSE = Symbol.dispose;\nfunction dispose(stub) {\n const disposer = stub[DISPOSE];\n try {\n disposer?.call(stub);\n } catch {\n }\n}\nfunction quietly(result) {\n if (result && typeof result.then === \"function\") {\n result.then(ignore, ignore);\n }\n}\nfunction send(end, message) {\n const { value, pieces } = pack(message);\n for (const piece of pieces) quietly(end.part(piece));\n quietly(end.post(value, pieces.length));\n}\nvar Inbox = class {\n pieces = [];\n early = [];\n handlers = [];\n part(bytes) {\n this.pieces.push(bytes);\n }\n take(value, count) {\n return unpack(value, this.pieces.splice(0, count));\n }\n deliver(message) {\n if (this.handlers.length === 0) {\n this.early.push(message);\n return;\n }\n for (const handler of this.handlers) handler(message);\n }\n listen(handler) {\n this.handlers.push(handler);\n if (this.handlers.length > 1) return;\n for (const message of this.early.splice(0)) handler(message);\n }\n clear() {\n this.pieces.length = 0;\n this.early.length = 0;\n this.handlers = [];\n }\n};\nasync function answered(end, answer) {\n const { value, held, count } = answer;\n if (held === void 0 || !count) return value;\n const pieces = [];\n for (let index = 0; index < count; index++) pieces.push(await end.take(held, index));\n return unpack(value, pieces);\n}\nvar Closers = class {\n handlers = [];\n pending = /* @__PURE__ */ new Set();\n reason;\n listen(handler) {\n const reason = this.reason;\n if (reason === void 0) this.handlers.push(handler);\n else queueMicrotask(() => handler(reason));\n }\n guard(work) {\n if (this.reason !== void 0) return Promise.reject(new Error(`link closed: ${this.reason}`));\n let reject = () => {\n };\n const ended = new Promise((_, fail) => {\n reject = fail;\n });\n this.pending.add(reject);\n return Promise.race([work, ended]).finally(() => this.pending.delete(reject));\n }\n close(reason) {\n if (this.reason !== void 0) return false;\n this.reason = reason;\n const err = new Error(`link closed: ${reason}`);\n for (const reject of [...this.pending]) reject(err);\n this.pending.clear();\n for (const handler of this.handlers.splice(0)) handler(reason);\n return true;\n }\n};\n\n// src/cloudflare/process-end.ts\nvar CLOSED_BY_PROCESS = \"the process closed its link\";\nvar ProcessState = class {\n inbox = new Inbox();\n closers = new Closers();\n done = () => {\n };\n settled = new Promise((resolve) => {\n this.done = resolve;\n });\n kernel;\n constructor(kernel) {\n this.kernel = kernel;\n }\n get closed() {\n return this.closers.reason !== void 0;\n }\n close(reason) {\n if (!this.closers.close(reason)) return;\n this.inbox.clear();\n this.done(reason);\n dispose(this.kernel);\n }\n};\nvar ProcessEnd = class extends RpcTarget {\n #state;\n #snapshots;\n constructor(state, snapshots2) {\n super();\n this.#state = state;\n this.#snapshots = snapshots2;\n }\n part(bytes) {\n this.#state.inbox.part(bytes);\n }\n post(value, count) {\n const inbox = this.#state.inbox;\n const message = inbox.take(value, count);\n inbox.deliver(message);\n }\n close(reason) {\n this.#state.close(typeof reason === \"string\" ? reason : \"the kernel closed the process\");\n }\n snapshot(token, offset, max) {\n return this.#snapshots?.read(token, offset, max) ?? null;\n }\n settled() {\n return this.#state.settled;\n }\n};\nfunction processSide(kernel, snapshots2) {\n const state = new ProcessState(kernel);\n const link = {\n onClose: (handler) => state.closers.listen(handler),\n close: () => state.close(CLOSED_BY_PROCESS),\n post(message) {\n if (!state.closed) send(kernel, message);\n },\n call(message) {\n if (state.closed) return state.closers.guard(Promise.resolve());\n const { value, pieces } = pack(message);\n for (const piece of pieces) quietly(kernel.part(piece));\n return state.closers.guard(\n kernel.call(value, pieces.length, Date.now()).then((answer) => answered(kernel, answer))\n );\n },\n onMessage: (handler) => state.inbox.listen(handler)\n };\n return { end: new ProcessEnd(state, snapshots2), link };\n}\n\n// src/cloudflare/process-host.ts\nvar snapshots = forkSnapshots();\nvar kernelOnly = {\n keep: (bytes) => snapshots.keep(bytes),\n take: () => void 0,\n read: (token, offset, max) => snapshots.read(token, offset, max),\n release: (token) => snapshots.release(token),\n get size() {\n return snapshots.size;\n }\n};\nvar OTHER_IMPORTS = \"this Dynamic Worker was loaded with another imports module than the program names\";\nvar ProcessHost = class extends WorkerEntrypoint {\n open(kernel) {\n const store = this.env?.SLICC_LOCAL_FORKS === \"off\" ? kernelOnly : snapshots;\n const loaded = this.env?.SLICC_IMPORTS;\n const imports = async (source) => {\n if (loaded === void 0 || await digest(source) !== loaded) throw new Error(OTHER_IMPORTS);\n return programImports;\n };\n const { end, link } = processSide(kernel.dup(), store);\n void asyncProcessEntry(link, {\n module: () => program,\n imports,\n snapshots: store,\n deadlines: false\n });\n return end;\n }\n};\nexport {\n ProcessHost as default\n};\n";
2
- export const PROCESS_SOURCE = "// src/kernel/protocol.ts\nvar WASM_PROCESS_INIT = \"wasm-process-init\";\nvar WASM_PROCESS_EXIT = \"wasm-process-exit\";\nvar WASM_PROCESS_ERROR = \"wasm-process-error\";\nvar WASM_PROCESS_READY = \"wasm-process-ready\";\nvar WASM_THREAD_SPAWN = \"wasm-thread-spawn\";\nvar WASM_THREAD_INIT = \"wasm-thread-init\";\nvar WASM_THREAD_EXIT = \"wasm-thread-exit\";\nvar WASM_MAX_THREADS = 256;\nvar WASM_DEFAULT_THREADS = 64;\n\n// src/async/jspi.ts\nvar jspi = WebAssembly;\nfunction jspiAvailable() {\n return typeof jspi.Suspending === \"function\" && typeof jspi.promising === \"function\";\n}\nvar AsyncFunction = (async () => {\n}).constructor;\nvar waiters = /* @__PURE__ */ new WeakMap();\nvar sleepers = /* @__PURE__ */ new WeakMap();\nvar localWaiter = (typed2, index3, value2, timeout) => {\n if (Atomics.load(typed2, index3) !== value2) return Promise.resolve(\"not-equal\");\n if (timeout !== void 0 && Number.isFinite(timeout)) return Promise.resolve(\"timed-out\");\n let set = sleepers.get(typed2.buffer);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n sleepers.set(typed2.buffer, set);\n }\n const own = set;\n return new Promise((resolve) => {\n const sleeper = {\n index: index3,\n wake: () => {\n own.delete(sleeper);\n resolve(\"ok\");\n }\n };\n own.add(sleeper);\n });\n};\nfunction atomicsNotify(typed2, index3, count) {\n let woken = 0;\n for (const sleeper of [...sleepers.get(typed2.buffer) ?? []]) {\n if (count !== void 0 && woken >= count) break;\n if (sleeper.index !== index3) continue;\n sleeper.wake();\n woken++;\n }\n return woken + Atomics.notify(typed2, index3, count);\n}\nfunction registerWaiter(buffer, waiter) {\n waiters.set(buffer, waiter);\n}\nasync function atomicsWait(typed2, index3, value2, timeout) {\n const waiter = waiters.get(typed2.buffer);\n if (waiter) return waiter(typed2, index3, value2, timeout);\n if (Atomics.load(typed2, index3) !== value2) return \"not-equal\";\n if (timeout !== void 0 && timeout <= 0) return \"timed-out\";\n throw new Error(\n \"async process: a wait on memory no process owns: nothing can wake it, and no wait runs on a local timer\"\n );\n}\nfunction checked(name2, fn) {\n return (...args) => {\n const result = fn(...args);\n if (result instanceof Promise) {\n throw new Error(\n `async process: the import ${name2} returned a promise to wasm without suspending`\n );\n }\n return result;\n };\n}\nfunction suspendingImports(imports) {\n const Suspending = jspi.Suspending;\n if (!Suspending) throw new Error(\"async process: this engine has no WebAssembly.Suspending\");\n const out = {};\n for (const [ns, table] of Object.entries(imports)) {\n const wrapped = {};\n for (const [name2, value2] of Object.entries(table)) {\n wrapped[name2] = value2 instanceof AsyncFunction ? new Suspending(value2) : typeof value2 === \"function\" ? checked(`${ns}.${name2}`, value2) : value2;\n }\n out[ns] = wrapped;\n }\n return out;\n}\nvar entries = /* @__PURE__ */ new WeakMap();\nfunction reentered(fn) {\n const known = entries.get(fn);\n if (known) return known;\n const promising = jspi.promising;\n if (!promising) throw new Error(\"async process: this engine has no WebAssembly.promising\");\n let entry;\n try {\n entry = promising(fn);\n } catch {\n entry = async (...args) => fn(...args);\n }\n entries.set(fn, entry);\n return entry;\n}\nfunction refusedModule(_bytes) {\n throw new Error(\"compiling wasm at run time is not supported by the async process host\");\n}\nfunction refusedImport(_specifier) {\n return Promise.reject(\n new Error(\"loading JavaScript at run time is not supported by the async process host\")\n );\n}\n\n// src/kernel/signals.ts\nvar SIG = {\n HUP: 1,\n INT: 2,\n QUIT: 3,\n ILL: 4,\n TRAP: 5,\n ABRT: 6,\n BUS: 7,\n FPE: 8,\n KILL: 9,\n USR1: 10,\n SEGV: 11,\n USR2: 12,\n PIPE: 13,\n ALRM: 14,\n TERM: 15,\n STKFLT: 16,\n CHLD: 17,\n CONT: 18,\n STOP: 19,\n TSTP: 20,\n TTIN: 21,\n TTOU: 22,\n URG: 23,\n XCPU: 24,\n XFSZ: 25,\n VTALRM: 26,\n PROF: 27,\n WINCH: 28,\n POLL: 29,\n PWR: 30,\n SYS: 31\n};\nvar IGNORED_BY_DEFAULT = /* @__PURE__ */ new Set([SIG.CHLD, SIG.URG, SIG.WINCH]);\nvar STOPPING = /* @__PURE__ */ new Set([SIG.STOP, SIG.TSTP, SIG.TTIN, SIG.TTOU]);\nfunction defaultAction(sig) {\n if (sig === SIG.CONT) return \"continue\";\n if (STOPPING.has(sig)) return \"stop\";\n return IGNORED_BY_DEFAULT.has(sig) ? \"ignore\" : \"terminate\";\n}\nfunction sigbit(sig) {\n return 1 << sig;\n}\nfunction signalsIn(mask) {\n const out = [];\n for (let sig = 1; sig <= 31; sig++) if (mask & sigbit(sig)) out.push(sig);\n return out;\n}\nvar SIGNAL_BY_NAME = {\n SIGINT: SIG.INT,\n SIGTERM: SIG.TERM,\n SIGKILL: SIG.KILL,\n SIGSTOP: SIG.STOP,\n SIGCONT: SIG.CONT\n};\nvar SI = { USER: 0, QUEUE: -1, TIMER: -2, TKILL: -6, KERNEL: 128 };\nvar KERNEL_SIGINFO = Object.freeze({\n code: SI.KERNEL,\n pid: 0,\n uid: 0,\n status: 0\n});\n\n// src/fs/changes.ts\nvar GEN = 0;\nvar RING = 1;\nvar RING_SIZE = 4096;\nvar SLOT = 2;\nvar SHARED_TTL_MS = 100;\nvar RENAME_WAIT_MS = 100;\nvar RENAME_WAIT_SHARED_MS = 1e3;\nfunction renameWait(view) {\n return view.foreign() ? RENAME_WAIT_SHARED_MS : RENAME_WAIT_MS;\n}\nvar DIRTY = RING + RING_SIZE * SLOT;\nvar FOREIGN = DIRTY + 1;\nvar RENAMES = FOREIGN + 1;\nvar HELD = RENAMES + 1;\nvar HELD_SLOTS = 1024;\nvar CHANGES_BYTES = (HELD + HELD_SLOTS) * 4;\nfunction heldSlot(path) {\n return HELD + (changeHash(normal(path)) & HELD_SLOTS - 1);\n}\nfunction changeHash(path) {\n let h = 2166136261;\n for (let i = 0; i < path.length; i++) {\n h ^= path.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return h === 0 ? 1 : h;\n}\nfunction normal(path) {\n const parts = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\nvar ChangeView = class {\n view;\n constructor(sab) {\n this.view = new Int32Array(sab);\n }\n now() {\n return Atomics.load(this.view, GEN);\n }\n clean() {\n return this.view.length > DIRTY && Atomics.load(this.view, DIRTY) === 0;\n }\n foreign() {\n return this.view.length > FOREIGN && Atomics.load(this.view, FOREIGN) === 1;\n }\n peerHeld(path) {\n return this.view.length > HELD && Atomics.load(this.view, heldSlot(path)) === 1;\n }\n renames() {\n return this.view.length > RENAMES ? Atomics.load(this.view, RENAMES) : 0;\n }\n async awaitRename(seen, ms) {\n if (this.view.length > RENAMES) await atomicsWait(this.view, RENAMES, seen, ms);\n return this.renames();\n }\n changedSince(seen, path) {\n const now = Atomics.load(this.view, GEN);\n const distance = now - seen >>> 0;\n if (distance === 0) return { now, changed: false };\n if (distance > RING_SIZE) return { now, changed: true };\n const hash = changeHash(normal(path));\n for (let i = 1; i <= distance; i++) {\n const g = seen + i | 0;\n const at = RING + (g & RING_SIZE - 1) * SLOT;\n if (Atomics.load(this.view, at) !== g) return { now, changed: true };\n const hit = Atomics.load(this.view, at + 1) === hash;\n if (Atomics.load(this.view, at) !== g) return { now, changed: true };\n if (hit) return { now, changed: true };\n }\n return { now, changed: false };\n }\n};\n\n// src/realm/sync-sab-wire.ts\nvar atomicLoad = Atomics.load;\nvar atomicStore = Atomics.store;\nvar atomicWaitAsync = Atomics.waitAsync;\nvar setBytes = Uint8Array.prototype.set;\nvar bytesPart = Uint8Array.prototype.subarray;\nvar decodeText = TextDecoder.prototype.decode;\nvar sabLoad = (a, i) => atomicLoad(a, i);\nvar sabStore = (a, i, v) => atomicStore(a, i, v);\nfunction copyWindow(out, window, chunk, at) {\n setBytes.call(out, bytesPart.call(window, 0, chunk), at);\n}\nvar SAB_HEADER_I32 = 18;\nvar SAB_CLOCK_OFFSET = SAB_HEADER_I32 * 4;\nvar SAB_CLOCK_I64 = 3;\nvar SAB_HEADER_BYTES = SAB_CLOCK_OFFSET + SAB_CLOCK_I64 * 8;\nvar SAB_I_STATE = 0;\nvar SAB_I_SEQ = 1;\nvar SAB_I_STATUS = 2;\nvar SAB_I_TOTAL = 3;\nvar SAB_I_CHUNK = 4;\nvar SAB_I_OFFSET = 5;\nvar SAB_I_REQ = 6;\nvar SAB_I_PUB = 7;\nvar SAB_I_SIGNALS = 8;\nvar SAB_I_TIMERS = 9;\nvar SAB_I_MEMORY = 10;\nvar SAB_I_TOTAL_HI = 11;\nvar SAB_I_OFFSET_HI = 12;\nvar SAB_I_KILLED = 13;\nvar SAB_I_ASYNC = 14;\nvar SAB_I_STOP = 15;\nvar SAB_I_BLOCKED = 16;\nvar SAB_I_BLOCKED_HI = 17;\nfunction loadBlocked(header) {\n return [sabLoad(header, SAB_I_BLOCKED), sabLoad(header, SAB_I_BLOCKED_HI)];\n}\nfunction storeBlocked(header, [low, high]) {\n sabStore(header, SAB_I_BLOCKED_HI, high);\n sabStore(header, SAB_I_BLOCKED, low);\n}\nvar anyBlocked = (mask) => mask !== void 0 && (mask[0] !== 0 || mask[1] !== 0);\nvar U32 = 2 ** 32;\nfunction loadU53(header, lo, hi) {\n return (sabLoad(header, lo) >>> 0) + sabLoad(header, hi) * U32;\n}\nfunction publishMemory(sab, bytes) {\n if (bytes > 0)\n sabStore(new Int32Array(sab, 0, SAB_HEADER_I32), SAB_I_MEMORY, Math.ceil(bytes / 65536));\n}\nvar SAB_STATE_IDLE = 0;\nvar SAB_STATE_PENDING = 1;\nvar SAB_STATE_READY = 2;\nvar SAB_STATUS_BYTES = 1;\nvar SAB_STATUS_JSON = 2;\nvar SAB_STATUS_VOID = 3;\nvar SAB_STATUS_ERRNO = 4;\nvar SAB_DEFAULT_WINDOW_BYTES = 1024 * 1024;\nvar SAB_MIN_BYTES = SAB_HEADER_BYTES + 4096;\nvar SYNC_SAB_REQ_MSG = \"sync-sab-req\";\nvar SYNC_SAB_NEXT_MSG = \"sync-sab-next\";\nvar encoder = new TextEncoder();\nvar decoder = new TextDecoder();\nfunction decodeSabResult(status2, payload) {\n switch (status2) {\n case SAB_STATUS_BYTES:\n return { ok: true, kind: \"bytes\", bytes: payload };\n case SAB_STATUS_VOID:\n return { ok: true, kind: \"void\" };\n case SAB_STATUS_JSON: {\n try {\n return { ok: true, kind: \"json\", json: JSON.parse(decodeText.call(decoder, payload)) };\n } catch {\n return { ok: false, errno: \"EIO\", message: \"sync-sab: malformed json payload\" };\n }\n }\n case SAB_STATUS_ERRNO: {\n try {\n const parsed = JSON.parse(decodeText.call(decoder, payload));\n const errno = typeof parsed.errno === \"string\" && /^E[A-Z]+$|^EAI_[A-Z]+$/.test(parsed.errno) ? parsed.errno : \"EIO\";\n const message = String(parsed.message ?? errno);\n return {\n ok: false,\n errno,\n message,\n ...parsed.direct === true ? { direct: true } : {},\n ...typeof parsed.dev === \"string\" ? { dev: parsed.dev } : {},\n ...parsed.detail === \"transport\" || parsed.detail === \"placeholder\" || parsed.detail === \"forbidden-header\" ? { detail: parsed.detail } : {}\n };\n } catch {\n return { ok: false, errno: \"EIO\", message: \"sync-sab: malformed errno payload\" };\n }\n }\n default:\n return { ok: false, errno: \"EIO\", message: `sync-sab: unknown status ${status2}` };\n }\n}\nfunction sabViews(sab) {\n if (sab.byteLength < SAB_MIN_BYTES) {\n throw new Error(`sync-sab: buffer too small (${sab.byteLength} < ${SAB_MIN_BYTES})`);\n }\n return {\n header: new Int32Array(sab, 0, SAB_HEADER_I32),\n window: new Uint8Array(sab, SAB_HEADER_BYTES)\n };\n}\n\n// src/kernel/cpu-clock.ts\nvar LOCAL = SAB_CLOCK_OFFSET;\nvar BLOCKED = 0;\nvar IDLE = 1;\nfunction epochMicros() {\n return Math.floor((performance.timeOrigin + performance.now()) * 1e3);\n}\nfunction slots(sab) {\n return new BigInt64Array(sab, LOCAL, SAB_CLOCK_I64);\n}\nvar local;\nvar localSab;\nvar localStart = 0;\nvar rawWait = Atomics.wait.bind(Atomics);\nfunction localCpuNanos() {\n if (!local || !localSab) return void 0;\n const now = epochMicros();\n const blocked = Number(Atomics.load(local, BLOCKED)) + localIdle(localSab, now).idle;\n return BigInt(Math.max(0, now - localStart - blocked)) * 1000n;\n}\nfunction localIdle(sab, now) {\n const state = Number(Atomics.load(slots(sab), IDLE));\n if (state >= 0) return { idle: state, waiting: false };\n return { idle: Math.max(0, now + state), waiting: true };\n}\n\n// src/realm/sync-fs-wire.ts\nvar SYNC_FS_OPS = [\n \"read\",\n \"write\",\n \"exists\",\n \"stat\",\n \"lstat\",\n \"readdir\",\n \"readdir-stat\",\n \"mkdir\",\n \"rm\",\n \"rename\",\n \"link\",\n \"copy\",\n \"unlink\",\n \"rmdir\",\n \"symlink\",\n \"readlink\",\n \"chmod\",\n \"utimes\",\n \"lutimes\",\n \"statfs\",\n \"hold\",\n \"create\",\n \"mkfifo\",\n \"kept\",\n \"pread\",\n \"pwrite\",\n \"append\",\n \"truncate\",\n \"chown\",\n \"lchown\",\n \"access\",\n \"renames\"\n];\nvar HOLD_READ = 4;\nvar HOLD_WRITE = 8;\nvar HOLD_CREATED = 16;\nvar SYNC_FS_REQUEST_TIMEOUT_MS = 25e3;\nvar SYNC_FS_READ_ONLY = /* @__PURE__ */ new Set([\n \"read\",\n \"pread\",\n \"exists\",\n \"stat\",\n \"lstat\",\n \"readdir\",\n \"readdir-stat\",\n \"readlink\",\n \"statfs\",\n \"kept\",\n \"access\",\n \"renames\"\n]);\nfunction parseSyncFsUsage(json) {\n const u = json;\n if (!u || typeof u.quota !== \"number\" || typeof u.usage !== \"number\") return null;\n return { quota: u.quota, usage: u.usage };\n}\nfunction syncError(code2, label) {\n return Object.assign(new Error(`${code2}: ${label}`), { code: code2 });\n}\nfunction parseSyncFsStat(json) {\n const s = json;\n if (!s || typeof s.isFile !== \"boolean\" || typeof s.isDirectory !== \"boolean\" || typeof s.size !== \"number\") {\n return null;\n }\n return {\n isFile: s.isFile,\n isDirectory: s.isDirectory,\n isSymbolicLink: s.isSymbolicLink,\n ...s.isSocket === true ? { isSocket: true } : {},\n ...s.isFifo === true ? { isFifo: true } : {},\n size: s.size,\n ...typeof s.mode === \"number\" ? { mode: s.mode } : {},\n ...typeof s.mtimeMs === \"number\" ? { mtimeMs: s.mtimeMs } : {},\n ...typeof s.atimeMs === \"number\" ? { atimeMs: s.atimeMs } : {},\n ...typeof s.ctimeMs === \"number\" ? { ctimeMs: s.ctimeMs } : {},\n ...typeof s.ino === \"number\" ? { ino: s.ino } : {},\n ...typeof s.fid === \"string\" ? { fid: s.fid } : {},\n ...typeof s.nlink === \"number\" ? { nlink: s.nlink } : {},\n ...typeof s.dev === \"number\" ? { dev: s.dev } : {},\n ...s.readonly === true ? { readonly: true } : {},\n ...typeof s.maxFile === \"number\" ? { maxFile: s.maxFile } : {},\n ...s.ranged === true ? { ranged: true } : {},\n ...s.linkable === true ? { linkable: true } : {},\n ...typeof s.version === \"string\" ? { version: s.version } : {},\n ...typeof s.gen === \"number\" ? { gen: s.gen } : {},\n ...typeof s.uid === \"number\" ? { uid: s.uid } : {},\n ...typeof s.gid === \"number\" ? { gid: s.gid } : {}\n };\n}\n\n// src/realm/sync-sab-bridge.ts\nvar UNCOUNTED_OPS = /* @__PURE__ */ new Set([...SYNC_FS_OPS, \"cwd-check\", \"cwd-chdir\"]);\nvar calls = 0;\nfunction exactBody(req, transfer = []) {\n const body = req.body;\n if (!ArrayBuffer.isView(body)) return { req, transfer };\n if (Object.prototype.toString.call(body.buffer) === \"[object SharedArrayBuffer]\") {\n return { req, transfer };\n }\n const whole = body.constructor === Uint8Array && body.byteOffset === 0 && body.byteLength === body.buffer.byteLength;\n if (whole) return { req, transfer };\n const copy = new Uint8Array(body.byteLength);\n copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n return { req: { ...req, body: copy }, transfer: [...transfer, copy.buffer] };\n}\nvar looks = 0;\nfunction lookedOutside() {\n looks++;\n}\nvar SPIN_MS = 0.06;\nvar SPIN_STRIDE = 128;\nvar SPIN_STRIDES = 256;\nvar SPIN_CORES = 4;\nvar spinning = (globalThis.navigator?.hardwareConcurrency ?? 0) >= SPIN_CORES;\nvar SPIN_CAP_MS = 1;\nfunction createSyncSabTransport(sab, port, deps = {}) {\n const views = sabViews(sab);\n const { header, window } = views;\n const wait = deps.wait ?? (async (a, i, v, t) => await rawWait(a, i, v, t));\n const now = deps.now ?? (() => performance.now());\n let seq = 0;\n let typical = 0;\n const ready = (id) => sabLoad(header, SAB_I_STATE) === SAB_STATE_READY && sabLoad(header, SAB_I_SEQ) === id;\n function spinUntil(id, until) {\n for (let stride = 0; stride < SPIN_STRIDES; stride++) {\n for (let i = 0; i < SPIN_STRIDE; i++) if (ready(id)) return true;\n if (now() >= until) return false;\n }\n return false;\n }\n function settled(start2) {\n typical += (Math.min(now() - start2, SPIN_CAP_MS) - typical) / 8;\n }\n async function awaitReady(id, deadline, label) {\n const start2 = now();\n if (spinning && typical < SPIN_MS && spinUntil(id, start2 + SPIN_MS)) {\n settled(start2);\n return;\n }\n for (; ; ) {\n const published = sabLoad(header, SAB_I_PUB);\n if (ready(id)) {\n settled(start2);\n return;\n }\n const remaining = deadline - now();\n if (remaining <= 0) throw syncError(\"EIO\", label);\n await wait(header, SAB_I_PUB, published, remaining);\n }\n }\n return {\n async call(asked, timeoutMs2, label, given = [], sink) {\n if (deps.memory) publishMemory(sab, deps.memory());\n const { req, transfer } = exactBody(asked, given);\n const id = ++seq;\n calls += Number(!UNCOUNTED_OPS.has(req.op));\n let out = null;\n let status2 = 0;\n let offset = 0;\n sabStore(header, SAB_I_REQ, id);\n try {\n for (; ; ) {\n sabStore(header, SAB_I_STATE, SAB_STATE_PENDING);\n const msg = offset === 0 ? { type: SYNC_SAB_REQ_MSG, id, req } : { type: SYNC_SAB_NEXT_MSG, id, offset };\n try {\n if (offset === 0 && transfer.length > 0) port.postMessage(msg, transfer);\n else port.postMessage(msg);\n } catch {\n throw syncError(\"EIO\", label);\n }\n await awaitReady(id, now() + timeoutMs2, label);\n const total = loadU53(header, SAB_I_TOTAL, SAB_I_TOTAL_HI);\n const chunk = sabLoad(header, SAB_I_CHUNK);\n const at = loadU53(header, SAB_I_OFFSET, SAB_I_OFFSET_HI);\n if (at !== offset || chunk < 0 || total < 0 || offset + chunk > total) {\n throw syncError(\"EIO\", label);\n }\n if (out === null) {\n status2 = sabLoad(header, SAB_I_STATUS);\n out = await landing(status2, total, sink);\n }\n copyWindow(out, window, chunk, offset);\n offset += chunk;\n if (offset >= total) break;\n if (chunk === 0) throw syncError(\"EIO\", label);\n }\n } finally {\n sabStore(header, SAB_I_REQ, 0);\n sabStore(header, SAB_I_STATE, SAB_STATE_IDLE);\n }\n return decodeSabResult(status2, out);\n }\n };\n}\nvar typed = Object.getPrototypeOf(Uint8Array.prototype);\nvar getter = (name2) => Object.getOwnPropertyDescriptor(typed, name2)?.get;\nvar bufferOf = getter(\"buffer\");\nvar offsetOf = getter(\"byteOffset\");\nvar lengthOf = getter(\"length\");\nasync function landing(status2, total, sink) {\n if (!sink || status2 !== SAB_STATUS_BYTES || total > await lengthOf.call(sink)) {\n return new Uint8Array(total);\n }\n return new Uint8Array(await bufferOf.call(sink), await offsetOf.call(sink), total);\n}\nfunction errnoError(code2, path, direct) {\n const err = syncError(code2, `sync-sab bridge, '${path}'`);\n return direct ? Object.assign(err, { direct }) : err;\n}\nfunction holdSeen(seen) {\n return { gen: seen.gen, ino: seen.ino, ...seen.nofollow ? { nofollow: true } : {} };\n}\nfunction holds(json, run) {\n const reals = /* @__PURE__ */ new Map();\n return {\n hold: async (path, held, open, handle, want = 0, seen = {}) => {\n const mode = (held ? 1 : 0) | (open ? 2 : 0);\n if (mode === 3) {\n const reply = await json({ op: \"hold\", path, mode: mode | want, ...holdSeen(seen) }, path);\n if (typeof reply !== \"object\" || reply === null) return reply;\n reals.set(reply.handle, reply.real);\n return reply.handle;\n }\n if (handle !== void 0) reals.delete(handle);\n await run({ op: \"hold\", path, mode, ...handle !== void 0 ? { handle } : {} }, path);\n return void 0;\n },\n heldReal: (handle) => reals.get(handle)\n };\n}\nfunction createSyncFsSabBridge(transport, opts = {}) {\n const direct = opts.direct ? { direct: true } : {};\n const timeoutMs2 = opts.timeoutMs ?? SYNC_FS_REQUEST_TIMEOUT_MS;\n let identity = {};\n let once = false;\n let last = null;\n async function run(req, path, transfer) {\n last = null;\n const silence = SYNC_FS_READ_ONLY.has(req.op) ? timeoutMs2 : Number.POSITIVE_INFINITY;\n const result = await transport.call(req, silence, `sync-sab bridge, '${path}'`, transfer);\n if (!result.ok) throw errnoError(result.errno, path, result.direct);\n return result;\n }\n async function bytes(req, path) {\n const r = await run(req, path);\n if (r.ok && r.kind === \"bytes\") return r.bytes;\n throw errnoError(\"EIO\", path);\n }\n async function json(req, path) {\n const r = await run(req, path);\n if (r.ok && r.kind === \"json\") return r.json;\n throw errnoError(\"EIO\", path);\n }\n const changing = async (req, path, transfer) => {\n const ask = once ? { identity: true } : identity;\n once = false;\n const r = await run({ ...req, ...ask }, path, transfer);\n if (r.ok && r.kind === \"json\") last = parseSyncFsStat(r.json);\n };\n const io = (id) => ({\n readFile: async (path) => await bytes({ op: \"read\", path, ...id }, path),\n writeFile: async (path, data, open) => {\n await changing({ op: \"write\", path, body: data, ...open ? { mode: 1 } : {}, ...id }, path);\n },\n pread: async (path, offset, length, version) => await bytes({ op: \"pread\", path, offset, length, ...version ? { version } : {}, ...id }, path),\n pwrite: async (path, offset, body, transfer) => {\n const whole = body.byteOffset === 0 && body.byteLength === body.buffer.byteLength;\n const owned = transfer && whole && body.buffer instanceof ArrayBuffer;\n const transferred = owned ? [body.buffer] : [];\n await changing({ op: \"pwrite\", path, offset, body, ...id }, path, transferred);\n },\n truncate: async (path, length) => {\n await changing({ op: \"truncate\", path, length, ...id }, path);\n },\n append: async (path, body) => await json({ op: \"append\", path, body, ...id }, path)\n });\n return {\n ...io({}),\n pinned: (handle) => io({ handle }),\n kept: async (handle) => await json({ op: \"kept\", path: \"/\", handle }, \"/\") === true,\n keptStat: async (handle) => {\n const s = parseSyncFsStat(await json({ op: \"stat\", path: \"/\", handle }, \"/\"));\n if (!s) throw errnoError(\"EIO\", \"/\");\n return s;\n },\n stat: async (path) => {\n const s = parseSyncFsStat(await json({ op: \"stat\", path, ...direct }, path));\n if (!s) throw errnoError(\"EIO\", path);\n return s;\n },\n lstat: async (path) => {\n const s = parseSyncFsStat(await json({ op: \"lstat\", path, ...direct }, path));\n if (!s) throw errnoError(\"EIO\", path);\n return s;\n },\n readdir: async (path) => {\n const list = await json({ op: \"readdir\", path }, path);\n if (!Array.isArray(list) || !list.every((s) => typeof s === \"string\")) {\n throw errnoError(\"EIO\", path);\n }\n return list;\n },\n readdirStat: async (path) => {\n const list = await json({ op: \"readdir-stat\", path }, path);\n if (!Array.isArray(list)) throw errnoError(\"EIO\", path);\n return list.map((entry) => {\n if (!Array.isArray(entry) || typeof entry[0] !== \"string\") throw errnoError(\"EIO\", path);\n if (entry[1] === null) return [entry[0], null];\n const stat = parseSyncFsStat(entry[1]);\n if (!stat) throw errnoError(\"EIO\", path);\n return [entry[0], stat];\n });\n },\n exists: async (path) => {\n const v = await json({ op: \"exists\", path }, path);\n if (typeof v !== \"boolean\") throw errnoError(\"EIO\", path);\n return v;\n },\n mkdir: async (path, mode) => {\n await run({ op: \"mkdir\", path, exclusive: true, ...mode !== void 0 ? { mode } : {} }, path);\n },\n rm: async (path) => {\n await run({ op: \"rm\", path }, path);\n },\n rename: async (from, to) => {\n const r = await run({ op: \"rename\", path: from, arg2: to }, from);\n const seq = r.ok && r.kind === \"json\" ? r.json.seq : void 0;\n return typeof seq === \"number\" ? seq : void 0;\n },\n link: async (from, to, follow2) => {\n await run({ op: \"link\", path: from, arg2: to, ...follow2 ? { mode: 1 } : {} }, from);\n },\n unlink: async (path) => {\n await run({ op: \"unlink\", path }, path);\n },\n rmdir: async (path) => {\n await run({ op: \"rmdir\", path }, path);\n },\n symlink: async (target, linkPath2) => {\n await run({ op: \"symlink\", path: linkPath2, arg2: target }, linkPath2);\n },\n readlink: async (path) => {\n const target = await json({ op: \"readlink\", path }, path);\n if (typeof target !== \"string\") throw errnoError(\"EIO\", path);\n return target;\n },\n chmod: async (path, mode) => {\n await changing({ op: \"chmod\", path, mode }, path);\n },\n utimes: async (path, atimeMs, mtimeMs, now) => {\n await changing({ op: \"utimes\", path, atimeMs, mtimeMs, ...now ? { now } : {} }, path);\n },\n identify: () => {\n identity = { identity: true };\n },\n identifyNext: () => {\n once = true;\n last = null;\n },\n identified: () => {\n once = false;\n return last;\n },\n lutimes: async (path, atimeMs, mtimeMs, now) => {\n await run({ op: \"lutimes\", path, atimeMs, mtimeMs, ...now ? { now } : {} }, path);\n },\n mkfifo: async (path, mode) => {\n await run({ op: \"mkfifo\", path, mode }, path);\n },\n copy: async (from, to, mode, exclusive) => {\n await run({ op: \"copy\", path: from, arg2: to, mode, ...exclusive ? { exclusive } : {} }, to);\n },\n create: async (path, mode, opening) => {\n const flags = { ...mode !== void 0 ? { mode } : {}, ...opening ? { opening } : {} };\n const r = await run({ op: \"create\", path, ...flags, identity: true }, path);\n if (!r.ok || r.kind !== \"json\") return void 0;\n const st = parseSyncFsStat(r.json);\n if (!st) return void 0;\n const { seen } = r.json;\n return typeof seen === \"number\" ? { ...st, seen } : st;\n },\n chown: async (path, uid, gid, follow2, handle) => {\n const ids = { ...uid !== void 0 ? { uid } : {}, ...gid !== void 0 ? { gid } : {} };\n await changing(\n {\n op: follow2 ? \"chown\" : \"lchown\",\n path,\n ...ids,\n ...handle !== void 0 ? { handle } : {}\n },\n path\n );\n },\n ...opts.owners ? { owners: true } : {},\n ...opts.links ? { links: true } : {},\n ...opts.changes ? { changes: new ChangeView(opts.changes) } : {},\n access: async (path, mode, kind = \"access\", nofollow) => {\n await run({ op: \"access\", path, mode, arg2: kind, ...nofollow ? { nofollow } : {} }, path);\n },\n ...holds(json, run),\n statfs: async (path = \"/\") => parseSyncFsUsage(await json({ op: \"statfs\", path }, path)),\n renames: async (since, held) => await json(\n { op: \"renames\", path: \"/\", offset: since, arg2: JSON.stringify(held) },\n \"/\"\n )\n };\n}\n\n// src/fs/dev-removal.ts\nvar SHM = \"/dev/shm\";\nfunction inShm(path) {\n return path === SHM || path.startsWith(`${SHM}/`);\n}\nfunction inDevTree(path) {\n if (path.startsWith(`${SHM}/`)) return false;\n return path === \"/dev\" || path.startsWith(\"/dev/\");\n}\nfunction inSys(path) {\n return path === \"/sys\" || path.startsWith(\"/sys/\");\n}\nfunction devRemoval(path, cred) {\n if (inSys(path)) return \"EROFS\";\n if (!inDevTree(path)) return void 0;\n if (cred && cred.euid !== 0) return \"EACCES\";\n return path === \"/dev\" ? \"EBUSY\" : \"EPERM\";\n}\nfunction devCreation(path, cred) {\n if (path === \"/proc\" || path.startsWith(\"/proc/\") || inSys(path)) return \"EROFS\";\n if (path === \"/dev\" || !inDevTree(path)) return void 0;\n return cred && cred.euid !== 0 ? \"EACCES\" : \"EPERM\";\n}\n\n// src/kernel/net/loopback-names.ts\nvar HOST_LOOPBACK = \"host.slicc.internal\";\nvar HOST_LOOPBACK_ADDRESS = [10, 0, 2, 2];\nvar PAGE_LOOPBACK = \"kernel.localhost\";\nvar PAGE_LOOPBACK_URL = `http://{port}.${PAGE_LOOPBACK}`;\nvar DEFAULT_HOSTNAME = \"slicc\";\nvar HOSTNAME_ADDRESS = \"127.0.1.1\";\nvar LIBC_HOSTNAMES = [\"emscripten\", \"wasmer.sh\"];\nvar LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;\nfunction reserved(name2) {\n const lower = name2.toLowerCase();\n return lower === \"localhost\" || lower.endsWith(\".localhost\") || lower === HOST_LOOPBACK || lower === \"wasmer.sh\" || /^\\d+(\\.\\d+){3}$/.test(lower);\n}\nfunction isHostname(name2) {\n if (typeof name2 !== \"string\" || name2.length > 253 || reserved(name2)) return false;\n return name2.split(\".\").every((l) => LABEL.test(l));\n}\nfunction hostnameOf(env) {\n return isHostname(env.HOSTNAME) ? env.HOSTNAME : DEFAULT_HOSTNAME;\n}\nfunction initHostname(init) {\n return isHostname(init.hostname) ? init.hostname : hostnameOf(init.env);\n}\nfunction ownNames(hostname) {\n return [.../* @__PURE__ */ new Set([hostname.toLowerCase(), ...LIBC_HOSTNAMES])];\n}\nfunction hostsFile(hostname = DEFAULT_HOSTNAME) {\n return [\n \"127.0.0.1 localhost localhost.localdomain\",\n \"::1 localhost ip6-localhost\",\n `${HOSTNAME_ADDRESS} ${ownNames(hostname).join(\" \")}`,\n `${HOST_LOOPBACK_ADDRESS.join(\".\")} ${HOST_LOOPBACK}`,\n \"\"\n ].join(\"\\n\");\n}\n\n// src/fs/types.ts\nfunction normalizePath(path) {\n const parts = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\nfunction inodeOf(path) {\n let h1 = 3735928559;\n let h2 = 1103547991;\n for (let i = 0; i < path.length; i++) {\n const c = path.charCodeAt(i);\n h1 = Math.imul(h1 ^ c, 2654435761);\n h2 = Math.imul(h2 ^ c, 1597334677);\n }\n h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);\n h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);\n return 4294967296 * (2097151 & h2) + (h1 >>> 0) || 1;\n}\n\n// src/fs/owners.ts\nvar ROOT_OWNER = Object.freeze({ uid: 0, gid: 0 });\n\n// src/fs/pages.ts\nvar PAGE = 64 * 1024;\nvar READAHEAD = 1024 * 1024;\nvar CLEAN_LIMIT = 4 * 1024 * 1024;\nvar WRITEBACK = 8 * 1024 * 1024;\nvar RUN = 1024 * 1024;\nvar Pages = class {\n length;\n stored;\n shrink;\n pages = /* @__PURE__ */ new Map();\n dirty = /* @__PURE__ */ new Set();\n free = [];\n pinned = false;\n constructor(size) {\n this.length = size;\n this.stored = size;\n }\n get dirtyBytes() {\n return this.dirty.size * PAGE;\n }\n get changed() {\n return this.dirty.size > 0 || this.shrink !== void 0 || this.length !== this.stored;\n }\n missing(at, length) {\n this.evict();\n const end = Math.min(this.stored, at + length, this.length);\n const runs = [];\n for (let page = Math.floor(at / PAGE); page * PAGE < end; page++) {\n if (this.pages.has(page)) continue;\n const last2 = runs[runs.length - 1];\n if (last2 && last2[0] + last2[1] === page * PAGE) last2[1] += PAGE;\n else runs.push([page * PAGE, PAGE]);\n }\n const last = runs[runs.length - 1];\n if (last) last[1] = Math.max(last[1], Math.min(READAHEAD, this.stored - last[0]));\n return runs.map(([start2, n]) => [start2, Math.min(n, this.stored - start2)]);\n }\n partial(at, length) {\n if (length === 0) return [];\n this.evict();\n const edges = /* @__PURE__ */ new Set([Math.floor(at / PAGE), Math.floor((at + length - 1) / PAGE)]);\n const runs = [];\n for (const page of edges) {\n const start2 = page * PAGE;\n const covered = at <= start2 && at + length >= start2 + PAGE;\n if (covered || this.pages.has(page) || start2 >= this.stored) continue;\n runs.push([start2, Math.min(PAGE, this.stored - start2)]);\n }\n return runs;\n }\n fill(start2, bytes) {\n for (let at = 0; at < bytes.length; at += PAGE) {\n const page = (start2 + at) / PAGE;\n if (this.pages.has(page)) continue;\n const part = bytes.subarray(at, Math.min(at + PAGE, bytes.length));\n const fresh = this.take(part.length);\n fresh.set(part);\n this.pages.set(page, fresh);\n }\n }\n read(at, length) {\n const out = new Uint8Array(Math.max(0, Math.min(this.length, at + length) - at));\n this.readInto(at, out);\n return out;\n }\n readInto(at, out) {\n const end = Math.min(this.length, at + out.length);\n for (let pos = at; pos < end; ) {\n const page = Math.floor(pos / PAGE);\n const from = pos - page * PAGE;\n const n = Math.min(PAGE - from, end - pos);\n const bytes = this.pages.get(page);\n if (bytes) out.set(bytes.subarray(from, from + n), pos - at);\n else out.fill(0, pos - at, pos - at + n);\n pos += n;\n }\n return Math.max(0, end - at);\n }\n write(at, bytes) {\n for (let done = 0; done < bytes.length; ) {\n const pos = at + done;\n const page = Math.floor(pos / PAGE);\n const from = pos - page * PAGE;\n const n = Math.min(PAGE - from, bytes.length - done);\n let target = this.pages.get(page);\n if (!target) {\n target = this.take(0);\n this.pages.set(page, target);\n }\n target.set(bytes.subarray(done, done + n), from);\n this.dirty.add(page);\n done += n;\n }\n this.length = Math.max(this.length, at + bytes.length);\n }\n truncate(size) {\n if (size < this.stored) {\n this.stored = size;\n this.shrink = Math.min(this.shrink ?? size, size);\n }\n if (size < this.length) {\n const edge = Math.floor(size / PAGE);\n for (const page of [...this.pages.keys()]) {\n if (page > edge || page === edge && size === edge * PAGE) this.drop(page);\n }\n this.pages.get(edge)?.fill(0, size - edge * PAGE);\n }\n this.length = size;\n }\n plan() {\n const runs = [];\n const sorted = [...this.dirty].sort((a, b) => a - b);\n for (let i = 0; i < sorted.length; ) {\n let j = i + 1;\n const first = sorted[i];\n while (j < sorted.length && sorted[j] === first + (j - i) && sorted[j] * PAGE % RUN !== 0) {\n j++;\n }\n const start2 = first * PAGE;\n const end = Math.min(this.length, (first + (j - i)) * PAGE);\n const bytes = new Uint8Array(end - start2);\n for (let k = i; k < j; k++) {\n const page = this.pages.get(sorted[k]);\n bytes.set(page.subarray(0, Math.min(PAGE, end - (k - i) * PAGE - start2)), (k - i) * PAGE);\n }\n runs.push({ offset: start2, bytes });\n i = j;\n }\n const written = Math.max(this.stored, ...runs.map((r) => r.offset + r.bytes.length));\n return {\n ...this.shrink !== void 0 ? { shrink: this.shrink } : {},\n runs,\n ...this.length > written ? { extend: this.length } : {}\n };\n }\n flushed() {\n this.dirty.clear();\n this.shrink = void 0;\n this.stored = this.length;\n this.evict();\n }\n pin() {\n this.pinned = true;\n }\n landed(at, length) {\n const end = at + length;\n for (let page = Math.floor(at / PAGE); page * PAGE < end; page++) {\n if (this.pages.has(page) && !this.dirty.has(page)) this.drop(page);\n }\n this.length = Math.max(this.length, end);\n this.stored = Math.max(this.stored, end);\n }\n reset(size) {\n if (this.pinned) return;\n for (const page of [...this.pages.keys()]) if (!this.dirty.has(page)) this.drop(page);\n if (this.changed) return;\n this.length = size;\n this.stored = size;\n }\n refresh(size) {\n if (this.pinned) return;\n for (const page of [...this.pages.keys()]) if (!this.dirty.has(page)) this.drop(page);\n const resized = this.length !== this.stored || this.shrink !== void 0;\n if (this.shrink === void 0) this.stored = size;\n this.length = resized ? Math.max(this.length, this.stored) : size;\n }\n evict() {\n if (this.pinned) return;\n let clean = (this.pages.size - this.dirty.size) * PAGE;\n for (const page of this.pages.keys()) {\n if (clean <= CLEAN_LIMIT) return;\n if (this.dirty.has(page)) continue;\n this.drop(page);\n clean -= PAGE;\n }\n }\n take(used) {\n const page = this.free.pop();\n if (!page) return new Uint8Array(PAGE);\n page.fill(0, used);\n return page;\n }\n drop(page) {\n const bytes = this.pages.get(page);\n this.pages.delete(page);\n this.dirty.delete(page);\n if (this.free.length < CLEAN_LIMIT / PAGE) this.free.push(bytes);\n }\n};\n\n// src/fs/ranged.ts\nvar signatureOf = (st) => `${st.version ?? \"\"}:${st.size}:${st.mtimeMs ?? \"\"}`;\nfunction linkedWatch(watch, st) {\n if ((st.nlink ?? 1) < 2) return watch;\n watch.linked = true;\n watch.sig = signatureOf(st);\n return watch;\n}\nasync function viaAlias(watch, seen, path) {\n if (watch.resolved === void 0) {\n let real;\n try {\n real = await watch.real?.();\n } catch {\n }\n watch.resolved = real && real !== path ? real : null;\n }\n return watch.resolved !== null && watch.view.changedSince(seen, watch.resolved).changed;\n}\nasync function viaLink(watch, path) {\n if (!watch.linked) return false;\n let sig;\n try {\n sig = signatureOf(await watch.stat(path));\n } catch {\n return false;\n }\n if (sig === watch.sig) return false;\n watch.sig = sig;\n return true;\n}\nasync function watchedChange(watch, seen, path) {\n const said = watch.view.changedSince(seen, path);\n if (said.changed || said.now === seen) return said;\n return { now: said.now, changed: await viaAlias(watch, seen, path) || await viaLink(watch, path) };\n}\nvar RangedFile = class {\n pages;\n io;\n pinned = false;\n version;\n watch;\n seen = 0;\n path;\n constructor(io, path, size, version, watch) {\n this.io = io;\n this.path = path;\n this.version = version;\n this.pages = new Pages(size);\n this.watch = watch;\n if (watch) this.seen = watch.seen ?? watch.view.now();\n }\n async fresh() {\n const watch = this.watch;\n if (!watch || this.pinned) return;\n const { now, changed: changed2 } = await watchedChange(watch, this.seen, this.path);\n this.seen = now;\n if (changed2) await this.reread();\n }\n async reread() {\n const watch = this.watch;\n if (!watch || this.pinned || this.pages.changed) return;\n let st;\n try {\n st = await watch.stat(this.path);\n } catch {\n return;\n }\n if (watch.ino !== void 0 && st.ino !== watch.ino) return;\n this.version = st.version;\n this.pages.refresh(st.size);\n }\n get changed() {\n return this.pages.changed;\n }\n async wrote(at, length) {\n this.pages.landed(at, length);\n this.version = void 0;\n await this.fresh();\n }\n get pinnedVersion() {\n return this.version;\n }\n forget() {\n this.pages.reset(this.pages.length);\n }\n async size() {\n await this.fresh();\n return this.pages.length;\n }\n async fetch(runs) {\n for (const [start2, n] of runs) {\n this.pages.fill(start2, await this.io.pread(this.path, start2, n, this.version));\n }\n }\n async read(at, length) {\n await this.fresh();\n await this.fetch(this.pages.missing(at, length));\n return this.pages.read(at, length);\n }\n async readInto(at, out) {\n await this.fresh();\n await this.fetch(this.pages.missing(at, out.length));\n return this.pages.readInto(at, out);\n }\n async write(at, bytes) {\n await this.fresh();\n await this.fetch(this.pages.partial(at, bytes.length));\n this.pages.write(at, bytes);\n if (!this.pinned && this.pages.dirtyBytes >= WRITEBACK) await this.flush();\n }\n truncate(size) {\n this.pages.truncate(size);\n }\n async flush() {\n if (this.pinned || !this.pages.changed) return;\n const plan = this.pages.plan();\n if (plan.shrink !== void 0) await this.io.truncate(this.path, plan.shrink);\n for (const run of plan.runs) await this.io.pwrite(this.path, run.offset, run.bytes, true);\n if (plan.extend !== void 0) await this.io.truncate(this.path, plan.extend);\n this.version = void 0;\n this.pages.flushed();\n }\n async pin() {\n this.pinned = true;\n this.pages.pin();\n await this.prefetch();\n }\n async prefetch() {\n await this.fresh();\n await this.fetch(this.pages.missing(0, this.pages.length));\n }\n reset(size) {\n this.pages.reset(size);\n }\n};\n\n// src/process/wasi/wasi-abi.ts\nvar E = {\n SUCCESS: 0,\n \"2BIG\": 1,\n ACCES: 2,\n ADDRINUSE: 3,\n ADDRNOTAVAIL: 4,\n AFNOSUPPORT: 5,\n AGAIN: 6,\n ALREADY: 7,\n BADF: 8,\n BADMSG: 9,\n BUSY: 10,\n CANCELED: 11,\n CHILD: 12,\n CONNABORTED: 13,\n CONNREFUSED: 14,\n CONNRESET: 15,\n DEADLK: 16,\n DESTADDRREQ: 17,\n DOM: 18,\n DQUOT: 19,\n EXIST: 20,\n FAULT: 21,\n FBIG: 22,\n HOSTUNREACH: 23,\n IDRM: 24,\n ILSEQ: 25,\n INPROGRESS: 26,\n INTR: 27,\n INVAL: 28,\n IO: 29,\n ISCONN: 30,\n ISDIR: 31,\n LOOP: 32,\n MFILE: 33,\n MLINK: 34,\n MSGSIZE: 35,\n MULTIHOP: 36,\n NAMETOOLONG: 37,\n NETDOWN: 38,\n NETRESET: 39,\n NETUNREACH: 40,\n NFILE: 41,\n NOBUFS: 42,\n NODEV: 43,\n NOENT: 44,\n NOEXEC: 45,\n NOLCK: 46,\n NOLINK: 47,\n NOMEM: 48,\n NOMSG: 49,\n NOPROTOOPT: 50,\n NOSPC: 51,\n NOSYS: 52,\n NOTCONN: 53,\n NOTDIR: 54,\n NOTEMPTY: 55,\n NOTRECOVERABLE: 56,\n NOTSOCK: 57,\n NOTSUP: 58,\n NOTTY: 59,\n NXIO: 60,\n OVERFLOW: 61,\n OWNERDEAD: 62,\n PERM: 63,\n PIPE: 64,\n PROTO: 65,\n PROTONOSUPPORT: 66,\n PROTOTYPE: 67,\n RANGE: 68,\n ROFS: 69,\n SPIPE: 70,\n SRCH: 71,\n STALE: 72,\n TIMEDOUT: 73,\n TXTBSY: 74,\n XDEV: 75,\n NOTCAPABLE: 76\n};\nfunction wasiErrnoOf(code2) {\n if (!code2) return E.IO;\n const name2 = code2.startsWith(\"E\") ? code2.slice(1) : code2;\n if (name2 === \"OPNOTSUPP\") return E.NOTSUP;\n if (name2 === \"WOULDBLOCK\") return E.AGAIN;\n if (name2 === \"NOMEDIUM\") return E.NODEV;\n return E[name2] ?? E.IO;\n}\nvar FILETYPE = {\n UNKNOWN: 0,\n BLOCK_DEVICE: 1,\n CHARACTER_DEVICE: 2,\n DIRECTORY: 3,\n REGULAR_FILE: 4,\n SOCKET_DGRAM: 5,\n SOCKET_STREAM: 6,\n SYMBOLIC_LINK: 7\n};\nvar RIGHTS = {\n FD_DATASYNC: 1n << 0n,\n FD_READ: 1n << 1n,\n FD_SEEK: 1n << 2n,\n FD_FDSTAT_SET_FLAGS: 1n << 3n,\n FD_SYNC: 1n << 4n,\n FD_TELL: 1n << 5n,\n FD_WRITE: 1n << 6n,\n ALL: (1n << 30n) - 1n\n};\nvar OFLAGS = { CREAT: 1, DIRECTORY: 2, EXCL: 4, TRUNC: 8 };\nvar FDFLAGS = { APPEND: 1, DSYNC: 2, NONBLOCK: 4, RSYNC: 8, SYNC: 16 };\nvar LOOKUP_SYMLINK_FOLLOW = 1;\nvar WHENCE = { SET: 0, CUR: 1, END: 2 };\nvar CLOCK = { REALTIME: 0, MONOTONIC: 1, PROCESS_CPUTIME: 2, THREAD_CPUTIME: 3 };\nvar FSTFLAGS = { ATIM: 1, ATIM_NOW: 2, MTIM: 4, MTIM_NOW: 8 };\nvar EVENTTYPE = { CLOCK: 0, FD_READ: 1, FD_WRITE: 2 };\nvar SUBCLOCK_ABSTIME = 1;\nvar EVENT_FD_READWRITE_HANGUP = 1;\nvar RIFLAGS = { PEEK: 1, WAITALL: 2 };\nvar SDFLAGS = { RD: 1, WR: 2 };\nvar PREOPENTYPE_DIR = 0;\nvar SIZE = {\n FILESTAT: 64,\n FDSTAT: 24,\n DIRENT: 24,\n SUBSCRIPTION: 48,\n EVENT: 32\n};\nvar WASI_SIGNAL_TO_POSIX = Object.fromEntries(\n Array.from({ length: 30 }, (_, i) => [i + 1, i + 1 < 16 ? i + 1 : i + 2])\n);\nfunction wasixSignal(sig) {\n return Number.isInteger(sig) && sig >= 1 && sig <= 31 ? sig : void 0;\n}\n\n// src/process/wasi-errno.ts\nvar WASI_ERRNO = {\n ...Object.fromEntries(Object.entries(E).map(([name2, errno]) => [`E${name2}`, errno])),\n EWOULDBLOCK: E.AGAIN,\n ENOTSUP: 138,\n EOPNOTSUPP: 138,\n ENOMEDIUM: 148\n};\nfunction wasiErrno(code2) {\n return WASI_ERRNO[code2] ?? E.IO;\n}\n\n// src/realm/live-vfs-fs.ts\nvar EARLY_WHOLE_FILE = 64 * 1024;\nvar createParentRefresh = 0;\nfunction createParentRefreshCount() {\n return createParentRefresh;\n}\n\n// src/version.ts\nvar KERNEL_VERSION = true ? \"1.193.0\" : \"0.0.0-dev\";\nvar OS_RELEASE = \"6.0.0-slicc\";\nfunction procVersion() {\n return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC\n`;\n}\n\n// src/kernel/serial-ioctl.ts\nvar IOCTL = {\n TCGETS: 21505,\n TCSETS: 21506,\n TCSETSW: 21507,\n TCSETSF: 21508,\n TCSBRK: 21513,\n TCFLSH: 21515,\n TIOCEXCL: 21516,\n TIOCNXCL: 21517,\n TIOCSCTTY: 21518,\n TIOCGPGRP: 21519,\n TIOCSPGRP: 21520,\n TIOCOUTQ: 21521,\n TIOCGWINSZ: 21523,\n TIOCSWINSZ: 21524,\n TIOCMGET: 21525,\n TIOCMBIS: 21526,\n TIOCMBIC: 21527,\n TIOCMSET: 21528,\n FIONREAD: 21531,\n TIOCNOTTY: 21538,\n TCSBRKP: 21541,\n TIOCSBRK: 21543,\n TIOCCBRK: 21544,\n TCGETS2: 2150388778,\n TCSETS2: 1076646955,\n TCSETSW2: 1076646956,\n TCSETSF2: 1076646957\n};\nvar TERMIOS_GETS = /* @__PURE__ */ new Set([IOCTL.TCGETS, IOCTL.TCGETS2]);\nvar TERMIOS_SETS = /* @__PURE__ */ new Set([\n IOCTL.TCSETS,\n IOCTL.TCSETSW,\n IOCTL.TCSETSF,\n IOCTL.TCSETS2,\n IOCTL.TCSETSW2,\n IOCTL.TCSETSF2\n]);\nvar INT_OUT = /* @__PURE__ */ new Set([\n IOCTL.TIOCMGET,\n IOCTL.FIONREAD,\n IOCTL.TIOCOUTQ\n]);\nvar INT_IN = /* @__PURE__ */ new Set([\n IOCTL.TIOCMBIS,\n IOCTL.TIOCMBIC,\n IOCTL.TIOCMSET\n]);\nvar INT_ARG = /* @__PURE__ */ new Set([IOCTL.TCSBRK, IOCTL.TCSBRKP, IOCTL.TCFLSH]);\nvar CBAUD = 4111;\nvar CSIZE = 48;\nvar CSTOPB = 64;\nvar PARENB = 256;\nvar PARODD = 512;\nvar CRTSCTS = 2147483648;\nfunction settingsOf(cflag, baudRate) {\n return {\n baudRate,\n dataBits: 5 + ((cflag & CSIZE) >> 4),\n parity: cflag & PARENB ? cflag & PARODD ? \"odd\" : \"even\" : \"none\",\n stopBits: cflag & CSTOPB ? 2 : 1,\n flowControl: cflag & CRTSCTS ? \"hardware\" : \"none\"\n };\n}\nvar SERIAL_CFLAG = 13 | 48 | 128 | 1024 | 2048;\nvar SERIAL_LFLAG = 16 | 32 | 512 | 2048;\nvar NCCS = 32;\nvar NCCS2 = 19;\nvar C_LINE = 16;\nvar C_CC = 17;\nfunction readFlags(view, at, ncc) {\n const cCc = new Array(NCCS).fill(0);\n for (let i = 0; i < ncc; i++) cCc[i] = view.getUint8(at + C_CC + i);\n return {\n c_iflag: view.getUint32(at, true),\n c_oflag: view.getUint32(at + 4, true),\n c_cflag: view.getUint32(at + 8, true),\n c_lflag: view.getUint32(at + 12, true),\n c_cc: cCc\n };\n}\nfunction writeFlags(view, at, t, ncc) {\n view.setUint32(at, t.c_iflag >>> 0, true);\n view.setUint32(at + 4, t.c_oflag >>> 0, true);\n view.setUint32(at + 8, t.c_cflag >>> 0, true);\n view.setUint32(at + 12, t.c_lflag >>> 0, true);\n view.setUint8(at + C_LINE, 0);\n for (let i = 0; i < ncc; i++) view.setUint8(at + C_CC + i, t.c_cc[i] ?? 0);\n}\nfunction ioctlArg(view, request, arg) {\n if (TERMIOS_SETS.has(request)) {\n if (request > 65535) {\n const t = readFlags(view, arg, NCCS2);\n return {\n ...t,\n c_ispeed: view.getUint32(arg + 36, true),\n c_ospeed: view.getUint32(arg + 40, true)\n };\n }\n return readFlags(view, arg, NCCS);\n }\n if (INT_IN.has(request)) return view.getInt32(arg, true);\n if (INT_ARG.has(request)) return arg | 0;\n if (request === IOCTL.TIOCSWINSZ)\n return { rows: view.getUint16(arg, true), cols: view.getUint16(arg + 2, true) };\n return void 0;\n}\nfunction ioctlResult(view, request, arg, result) {\n if (TERMIOS_GETS.has(request)) {\n const t = result;\n if (request === IOCTL.TCGETS2) {\n writeFlags(view, arg, t, NCCS2);\n view.setUint32(arg + 36, (t.c_ispeed ?? 0) >>> 0, true);\n view.setUint32(arg + 40, (t.c_ospeed ?? 0) >>> 0, true);\n } else {\n writeFlags(view, arg, t, NCCS);\n view.setUint32(arg + 52, t.c_cflag & CBAUD, true);\n view.setUint32(arg + 56, t.c_cflag & CBAUD, true);\n }\n } else if (INT_OUT.has(request)) view.setInt32(arg, Number(result) | 0, true);\n else if (request === IOCTL.TIOCGWINSZ) {\n const size = result;\n view.setUint16(arg, size.rows, true);\n view.setUint16(arg + 2, size.cols, true);\n view.setUint32(arg + 4, 0, true);\n }\n}\n\n// src/process/process-pty.ts\nvar TIOCGPTN = 2147767344;\nvar TIOCSPTLCK = 1074025521;\nvar TIOCSCTTY = 21518;\nvar TIOCSWINSZ = 21524;\nvar TIOCPKT = 21536;\n\n// src/process/process-fds.ts\nvar REFUSED = /* @__PURE__ */ new Set([wasiErrno(\"EACCES\"), wasiErrno(\"EPERM\")]);\nvar OWN_ERRORS = 128 | 131072;\nvar field = (text) => (text || \"none\").replace(/[\\s\\\\]/g, (c) => `\\\\${c.charCodeAt(0).toString(8).padStart(3, \"0\")}`);\nvar pinnedRoot;\nvar rootKind = () => globalThis.navigator?.storage ? \"opfs\" : \"memory\";\nfunction mountTable(mounts = []) {\n const root = pinnedRoot ?? rootKind();\n const lines = [`${root} / ${root} rw 0 0`, \"devfs /dev devfs rw 0 0\", \"proc /proc proc rw 0 0\"];\n for (const m of mounts) {\n const options = Object.entries(m.options).map(([k, v]) => v === \"\" ? k : `${k}=${v}`);\n if (m.state !== \"ok\") options.push(m.state);\n const access3 = options.includes(\"ro\") ? [] : [\"rw\"];\n lines.push(\n `${field(m.source)} ${field(m.target)} ${m.type} ${[...access3, ...options].join(\",\")} 0 0`\n );\n }\n return `${lines.join(\"\\n\")}\n`;\n}\nvar NAME = /^[a-z_][a-z0-9_-]*$/i;\nfunction accounts(env = {}) {\n const user = env.USER ?? \"web_user\";\n const name2 = NAME.test(user) && user !== \"root\" ? user : \"user\";\n const home = env.HOME || \"/home\";\n return {\n passwd: `root:x:0:0:root:/root:/bin/sh\n${name2}:x:1000:1000:${name2}:${home}:/bin/bash\n`,\n group: `root:x:0:\n${name2}:x:1000:\n`\n };\n}\n\n// src/process/kernel-streams.ts\nvar KILLED_BY_SIGPIPE = 128 + 13;\nvar SyscallError = class extends Error {\n code;\n constructor(code2) {\n super(code2);\n this.code = code2;\n }\n};\n\n// src/kernel/held-cwd.ts\nvar CWD_SLOTS = 1024;\nvar UNTRACKED = CWD_SLOTS - 1;\nvar HeldCwd = class {\n view;\n seen;\n dead = false;\n slot;\n at;\n ask;\n constructor(sab, slot2, ask, state) {\n this.view = new Int32Array(sab);\n this.slot = slot2;\n this.ask = ask;\n this.seen = state.seen;\n this.dead = state.dead;\n this.at = state.path;\n }\n moved(reply, path) {\n if (reply.slot === void 0) return false;\n this.slot = reply.slot;\n this.seen = reply.seen ?? Atomics.load(this.view, reply.slot);\n this.dead = reply.dead === true;\n this.at = path;\n return true;\n }\n async follow() {\n const answer = await this.ask();\n if (answer.slot !== void 0) this.slot = answer.slot;\n this.seen = answer.gen;\n this.dead = !answer.alive;\n return answer.alive;\n }\n async alive(path) {\n if (path !== void 0 && this.at !== void 0 && path !== this.at) {\n this.at = path;\n return await this.follow();\n }\n if (this.dead) return false;\n if (Atomics.load(this.view, this.slot) === this.seen) return true;\n return await this.follow();\n }\n get current() {\n return this.slot;\n }\n};\n\n// src/process/process-children.ts\nvar UNSEEDED = sigbit(SIG.KILL) | sigbit(SIG.STOP) | 1;\nfunction inheritedOf(r) {\n return r.ok && r.kind === \"json\" ? r.json & ~UNSEEDED : 0;\n}\nasync function inheritedSignals(transport) {\n return inheritedOf(\n await transport.call({ op: \"sig-inherited\" }, Number.POSITIVE_INFINITY, \"sig-inherited\")\n );\n}\n\n// src/process/process-signals.ts\nvar SignalGate = class {\n reported = { caught: 0, ignored: 0, nocldwait: false };\n restart = 0;\n lastDelivered = 0;\n depth = 0;\n reporting = false;\n unwinding = false;\n quieted = 0;\n delivered = 0;\n raised = 0;\n entering = 0;\n raw;\n header;\n hooks;\n constructor(raw, header, hooks) {\n this.raw = raw;\n this.header = header;\n this.hooks = hooks;\n }\n transport() {\n return {\n call: async (req, timeoutMs2, label) => {\n await this.report();\n this.depth++;\n try {\n const result = await this.raw.call(req, timeoutMs2, label);\n await this.deliver();\n return result;\n } finally {\n this.depth--;\n }\n }\n };\n }\n deliveries() {\n return this.delivered;\n }\n restartable() {\n return this.lastDelivered !== 0 && (this.lastDelivered & ~this.restart) === 0;\n }\n async report() {\n if (this.reporting) return;\n this.reporting = true;\n let masks;\n try {\n masks = this.hooks.masks();\n } catch {\n masks = null;\n } finally {\n this.reporting = false;\n }\n if (!masks) return;\n this.restart = masks.restart;\n const { caught, ignored, defaults = 0 } = masks;\n const nocldwait = masks.nocldwait === true;\n const was = this.reported;\n const same2 = caught === was.caught && ignored === was.ignored && nocldwait === was.nocldwait;\n if (same2 && defaults === 0) return;\n this.reported = { caught, ignored, nocldwait };\n const req = {\n op: \"sig-mask\",\n caught,\n ignored,\n ...defaults ? { defaults } : {},\n ...nocldwait ? { nocldwait } : {}\n };\n await this.raw.call(req, Number.POSITIVE_INFINITY, \"sig-mask\");\n }\n async quiet(fn) {\n this.quieted++;\n try {\n return await fn();\n } finally {\n this.quieted--;\n }\n }\n async interrupt() {\n await this.report();\n const header = this.header;\n const pending = Atomics.load(header, SAB_I_SIGNALS) & ~Atomics.load(header, SAB_I_BLOCKED) | Atomics.load(header, SAB_I_TIMERS) | Atomics.load(header, SAB_I_KILLED);\n if (pending === 0) return false;\n if (this.entering === 0) this.raised = this.quieted > 0 ? -1 : 0;\n this.entering++;\n try {\n await this.deliver();\n } finally {\n this.entering--;\n }\n return true;\n }\n raisedOnEntry() {\n return this.raised;\n }\n async deliver() {\n if (this.quieted > 0) return;\n const killed = Atomics.load(this.header, SAB_I_KILLED);\n if (killed !== 0 && !this.unwinding && this.hooks.killed) {\n this.unwinding = true;\n this.hooks.killed(killed);\n }\n const timers = Atomics.exchange(this.header, SAB_I_TIMERS, 0);\n const blocked = Atomics.load(this.header, SAB_I_BLOCKED);\n const pending = blocked === 0 ? Atomics.exchange(this.header, SAB_I_SIGNALS, 0) : Atomics.and(this.header, SAB_I_SIGNALS, blocked) & ~blocked;\n if (this.depth <= 1) this.lastDelivered = pending | (timers & 1 ? sigbit(SIG.ALRM) : 0);\n if (pending !== 0 || timers !== 0) this.delivered++;\n this.raised |= pending | (timers & 1 ? sigbit(SIG.ALRM) : 0) | (timers & ~1 ? -1 : 0);\n for (let which = 0; which < 3; which++) {\n if (timers & 1 << which) await this.hooks.timer?.(which);\n }\n for (const sig of signalsIn(pending)) await this.hooks.raise(sig);\n }\n};\n\n// src/process/process-sockets.ts\nvar KILLED_BY_SIGPIPE2 = 128 + 13;\n\n// src/kernel/cred.ts\nvar ROOT = Object.freeze({\n ruid: 0,\n euid: 0,\n suid: 0,\n rgid: 0,\n egid: 0,\n sgid: 0,\n groups: [0]\n});\nvar MAX_GROUPS = 65536;\n\n// src/kernel/proc-info.ts\nfunction mayTrace(viewer, target) {\n const by = viewer?.cred;\n const of = target.cred;\n if (!by || !of || by.euid === 0) return true;\n const uid = of.ruid === by.euid && of.euid === by.euid && of.suid === by.euid;\n return uid && of.rgid === by.egid && of.egid === by.egid && of.sgid === by.egid;\n}\nfunction fileIdentity(ino, mtimeMs) {\n if (ino === void 0 || mtimeMs === void 0 || !Number.isFinite(mtimeMs)) return void 0;\n return `${ino}:${Math.trunc(mtimeMs)}`;\n}\n\n// src/process/procfs.ts\nvar HZ = 100;\nvar KIB = 1024;\nvar FALLBACK_MEMORY = 4 * KIB * KIB * KIB;\nvar PID_FILES = [\"cmdline\", \"comm\", \"stat\", \"statm\", \"status\"];\nvar SYSTEM_FILES = [\"loadavg\", \"meminfo\", \"stat\", \"uptime\", \"version\"];\nvar SYS_TREE = {\n kernel: {\n osrelease: `${OS_RELEASE}\n`,\n ostype: \"Linux\\n\",\n slicc_wasm_memories: (listing2) => `${listing2.wasm?.live ?? 0} ${listing2.wasm?.ceiling ?? 0} ${listing2.wasm?.source ?? \"none\"}\n`,\n slicc_shared_root: (listing2) => `${listing2.peers ?? 0}\n`,\n slicc_fs_calls: (listing2) => `${listing2.fsCalls ?? 0}\n`,\n slicc_opfs_calls: (listing2) => `${listing2.opfsCalls ?? 0}\n`,\n slicc_opfs_ops: (listing2) => `${listing2.opfsOps ?? 0}\n`,\n slicc_create_parent_refresh: (_listing) => `${createParentRefreshCount()}\n`,\n slicc_meta_transactions: ({ meta }) => `${meta?.reads ?? 0} ${meta?.writes ?? 0}\n`,\n slicc_cwd_checks: (listing2) => `${listing2.cwdChecks ?? 0}\n`,\n slicc_package_swaps: ({ swaps }) => `${swaps?.swaps ?? 0} ${(swaps?.longestMs ?? 0).toFixed(1)} ${swaps?.waits ?? 0} ${(swaps?.waitedMs ?? 0).toFixed(1)}\n`,\n slicc_rename_ack_busy: (listing2) => `${listing2.renameAcks?.busy ?? 0}\n`,\n slicc_stale_fds: (listing2) => `${listing2.staleFds ?? 0}\n`,\n slicc_file_ids: (listing2) => `${listing2.fileIds ?? 0}\n`,\n slicc_peer_holds: ({ holds: holds2 }) => `${holds2?.mine ?? 0} ${holds2?.peers ?? 0} ${holds2?.sent ?? 0}\n`,\n slicc_peer_held: ({ holds: holds2 }) => (holds2?.held ?? []).map((path) => `${path}\n`).join(\"\"),\n slicc_rename_acks: (listing2) => {\n const samples = [...listing2.renameAcks?.ackMs ?? []].sort((a, b) => a - b);\n const median = samples[Math.floor(samples.length / 2)] ?? 0;\n const most = samples.at(-1) ?? 0;\n const waits = listing2.renameAcks?.waits ?? 0;\n const queries = listing2.renameAcks?.queries ?? 0;\n return `${listing2.renameAcks?.acks ?? 0} ${median.toFixed(1)} ${most.toFixed(1)} ${waits} ${queries}\n`;\n }\n }\n};\nfunction isSysFile(at) {\n return typeof at === \"string\" || typeof at === \"function\";\n}\nfunction sysEntry(parts) {\n let at = SYS_TREE;\n for (const part of parts) {\n if (isSysFile(at) || !Object.hasOwn(at, part)) return void 0;\n at = at[part];\n }\n return at;\n}\nasync function sysText(file, listing2) {\n return typeof file === \"string\" ? file : file(await listing2());\n}\nfunction commOf(info) {\n const name2 = info.argv[0] ?? \"\";\n return name2.slice(name2.lastIndexOf(\"/\") + 1).slice(0, 15);\n}\nfunction ttyNumber(tty) {\n const pts = tty && /^\\/dev\\/pts\\/(\\d+)$/.exec(tty);\n if (pts) return 136 << 8 | Number(pts[1]);\n const vt = tty && /^\\/dev\\/tty(\\d+)$/.exec(tty);\n return vt ? 4 << 8 | Number(vt[1]) : 0;\n}\nfunction pages(bytes) {\n return Math.ceil(bytes / 4096);\n}\nfunction ticks(ms) {\n return Math.max(0, Math.floor(ms * HZ / 1e3));\n}\nfunction pidStat(info, boot, state = info.state) {\n const fields = [\n info.pid,\n `(${commOf(info)})`,\n state,\n info.ppid,\n info.pgid,\n info.sid,\n ttyNumber(info.tty),\n info.tty ? info.pgid : -1,\n 4194304,\n 0,\n 0,\n 0,\n 0,\n ticks(info.utime ?? 0),\n ticks(info.stime ?? 0),\n ticks(info.cutime ?? 0),\n ticks(info.cstime ?? 0),\n 20,\n 0,\n 1,\n 0,\n ticks(info.started - boot),\n info.memory,\n pages(info.memory),\n \"18446744073709551615\",\n ...Array(12).fill(0),\n 17,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n ...Array(7).fill(0),\n 0\n ];\n return `${fields.join(\" \")}\n`;\n}\nvar sigMask = (mask = 0) => (mask >>> 1).toString(16).padStart(16, \"0\");\nvar STATES = {\n S: \"S (sleeping)\",\n T: \"T (stopped)\",\n Z: \"Z (zombie)\"\n};\nvar tagLine = (tag) => `Tag:\t${tag.replaceAll(\"\\n\", \"\\\\n\").replaceAll(\"\t\", \"\\\\t\").replaceAll(\"\\r\", \"\\\\r\")}`;\nfunction taskStat(info, tid, boot) {\n const thread = (info.threads ?? [{ tid: 1, state: info.state }]).find((t) => t.tid === tid);\n return thread && pidStat({ ...info, pid: tid }, boot, thread.state);\n}\nfunction taskIds(info) {\n return (info.threads ?? [{ tid: 1 }]).map((t) => t.tid);\n}\nfunction pidStatus(info) {\n const state = STATES[info.state];\n const c = info.cred ?? ROOT;\n const ids = (r, e, s) => `${r}\t${e}\t${s}\t${e}`;\n return [\n `Name:\t${commOf(info)}`,\n `Umask:\t${(info.umask ?? 18).toString(8).padStart(4, \"0\")}`,\n `State:\t${state}`,\n `Tgid:\t${info.pid}`,\n \"Ngid:\t0\",\n `Pid:\t${info.pid}`,\n `PPid:\t${info.ppid}`,\n \"TracerPid:\t0\",\n `Uid:\t${ids(c.ruid, c.euid, c.suid)}`,\n `Gid:\t${ids(c.rgid, c.egid, c.sgid)}`,\n ...(info.tags ?? (info.tag !== void 0 ? [info.tag] : [])).map(tagLine),\n \"FDSize:\t64\",\n `VmSize:\t${Math.ceil(info.memory / KIB)} kB`,\n `VmRSS:\t${Math.ceil(info.memory / KIB)} kB`,\n `Groups:\t${c.groups.join(\" \")}`,\n `NSpid:\t${info.pid}`,\n `NSpgid:\t${info.pgid}`,\n `NSsid:\t${info.sid}`,\n \"Threads:\t1\",\n \"SigQ:\t0/0\",\n \"SigPnd:\t0000000000000000\",\n \"ShdPnd:\t0000000000000000\",\n `SigBlk:\t${sigMask(info.sigBlk)}`,\n `SigIgn:\t${sigMask(info.sigIgn)}`,\n `SigCgt:\t${sigMask(info.sigCgt)}`,\n \"\"\n ].join(\"\\n\");\n}\nfunction pidFile(name2, info, boot) {\n if (name2 === \"cmdline\") return info.state === \"Z\" ? \"\" : `${info.argv.join(\"\\0\")}\\0`;\n if (name2 === \"comm\") return `${commOf(info)}\n`;\n if (name2 === \"stat\") return pidStat(info, boot);\n if (name2 === \"statm\") {\n const p = pages(info.memory);\n return `${p} ${p} 0 0 0 ${p} 0\n`;\n }\n return pidStatus(info);\n}\nfunction memoryInfo(source, used = 0) {\n const total = source.deviceMemory ? source.deviceMemory * KIB * KIB * KIB : FALLBACK_MEMORY;\n const free = Math.max(0, total - used - (source.usedHeap ?? 0));\n const kb = (bytes) => `${Math.floor(bytes / KIB)} kB`;\n return [\n [\"MemTotal\", kb(total)],\n [\"MemFree\", kb(free)],\n [\"MemAvailable\", kb(free)],\n [\"Buffers\", kb(0)],\n [\"Cached\", kb(0)],\n [\"SwapCached\", kb(0)],\n [\"Shmem\", kb(0)],\n [\"SReclaimable\", kb(0)],\n [\"SwapTotal\", kb(0)],\n [\"SwapFree\", kb(0)]\n ].map(([key, value2]) => `${`${key}:`.padEnd(16)}${value2.padStart(12)}`).concat(\"\").join(\"\\n\");\n}\nfunction systemFile(name2, listing2, now, memory) {\n if (name2 === \"version\") return procVersion();\n const up = Math.max(0, now - listing2.boot) / 1e3;\n if (name2 === \"uptime\") return `${up.toFixed(2)} ${up.toFixed(2)}\n`;\n if (name2 === \"meminfo\") {\n return memoryInfo(\n memory,\n listing2.processes.reduce((sum2, p) => sum2 + p.memory, 0)\n );\n }\n const live = listing2.processes.filter((p) => p.state !== \"Z\");\n if (name2 === \"loadavg\") {\n const last = Math.max(0, ...listing2.processes.map((p) => p.pid));\n const [one, five, fifteen] = (listing2.load ?? [0, 0, 0]).map((n) => n.toFixed(2));\n return `${one} ${five} ${fifteen} 1/${live.length} ${last}\n`;\n }\n const sum = (key) => listing2.cpu?.[key] ?? listing2.processes.reduce((n, p) => n + (p[key] ?? 0), 0);\n const user = ticks(sum(\"utime\"));\n const system = ticks(sum(\"stime\"));\n const idle = listing2.cpu ? ticks(listing2.cpu.idle) : Math.max(0, ticks(now - listing2.boot) - user - system);\n return [\n `cpu ${user} 0 ${system} ${idle} 0 0 0 0 0 0`,\n `cpu0 ${user} 0 ${system} ${idle} 0 0 0 0 0 0`,\n \"intr 0\",\n \"ctxt 0\",\n `btime ${Math.floor(listing2.boot / 1e3)}`,\n `processes ${listing2.processes.length}`,\n \"procs_running 1\",\n \"procs_blocked 0\",\n \"\"\n ].join(\"\\n\");\n}\nfunction memorySource(scope = globalThis) {\n const nav = scope.navigator;\n const perf = scope.performance;\n const deviceMemory = nav?.deviceMemory;\n const used = perf?.memory?.usedJSHeapSize;\n return {\n ...typeof deviceMemory === \"number\" && deviceMemory > 0 ? { deviceMemory } : {},\n ...typeof used === \"number\" ? { usedHeap: used } : {}\n };\n}\n\n// src/process/realm-user.ts\nvar LEGACY_OWNER = Object.freeze({ uid: 1e3, gid: 1e3 });\n\n// src/kernel/pipe.ts\nvar PIPE_CAPACITY = 64 * 1024;\n\n// src/kernel/fd-table.ts\nvar DEVICE_PATHS = /* @__PURE__ */ new Map([\n [\"/dev/null\", \"null\"],\n [\"/dev/zero\", \"zero\"],\n [\"/dev/full\", \"full\"],\n [\"/dev/urandom\", \"urandom\"],\n [\"/dev/random\", \"urandom\"]\n]);\nfunction deviceAt(path) {\n return DEVICE_PATHS.get(path);\n}\n\n// src/kernel/embedder.ts\nvar EMBEDDER_HEADER_MAX = 64 * 1024;\nvar EMBEDDER_WINDOW = 1024 * 1024;\nvar EMBEDDER_BUDGET = 256 * 1024 * 1024;\n\n// src/kernel/tty.ts\nvar encoder2 = new TextEncoder();\n\n// src/kernel/devices.ts\nvar DEVICE_NAME = /^tty(USB|ACM)(\\d{1,3})$/;\nvar BY_ID = \"/dev/serial/by-id\";\nvar HIGH_WATER = 64 * 1024;\nvar DEFAULT_SETTINGS = settingsOf(SERIAL_CFLAG, 9600);\n\n// src/kernel/sysfs.ts\nvar HCD = \"/sys/devices/platform/slicc_hcd.0\";\nvar VIRTUAL = \"/sys/devices/virtual/tty\";\nvar CLASS = \"/sys/class/tty\";\nvar USB_BUS = \"/sys/bus/usb\";\nvar SERIAL_BUS = \"/sys/bus/usb-serial\";\nvar ALWAYS = [\"/sys/class/tty\", \"/sys/bus/usb\", \"/sys/bus/usb-serial\", \"/sys/devices\"];\nvar DIR_MODE = 16877;\nvar FILE_MODE = 33060;\nvar LINK_MODE = 41471;\nvar MAX_HOPS = 40;\nfunction sysError(code2, path) {\n return Object.assign(new Error(`${code2}: ${path}`), { code: code2 });\n}\nfunction relative(fromDir, to) {\n const from = fromDir.split(\"/\").filter(Boolean);\n const dest = to.split(\"/\").filter(Boolean);\n let same2 = 0;\n while (same2 < from.length && from[same2] === dest[same2]) same2++;\n if (same2 === dest.length) same2--;\n return [...from.slice(same2).map(() => \"..\"), ...dest.slice(same2)].join(\"/\");\n}\nfunction parentOf2(path) {\n return path.slice(0, path.lastIndexOf(\"/\")) || \"/\";\n}\nfunction baseOf(path) {\n return path.slice(path.lastIndexOf(\"/\") + 1);\n}\nfunction inodeOf2(path) {\n let hash = 2166136261;\n for (let i = 0; i < path.length; i++) hash = Math.imul(hash ^ path.charCodeAt(i), 16777619);\n return hash >>> 0 || 1;\n}\nfunction product(vid, pid) {\n return `${Number.parseInt(vid, 16).toString(16)}/${Number.parseInt(pid, 16).toString(16)}/0`;\n}\nvar Layout = class {\n entries = /* @__PURE__ */ new Map([[\"/\", { kind: \"dir\", names: /* @__PURE__ */ new Set() }]]);\n dir(path) {\n if (this.entries.has(path)) return;\n const parent = parentOf2(path);\n this.dir(parent);\n this.entries.get(parent).names.add(baseOf(path));\n this.entries.set(path, { kind: \"dir\", names: /* @__PURE__ */ new Set() });\n }\n put(path, entry) {\n const parent = parentOf2(path);\n this.dir(parent);\n this.entries.get(parent).names.add(baseOf(path));\n this.entries.set(path, entry);\n }\n file(path, text) {\n this.put(path, { kind: \"file\", text });\n }\n link(path, to) {\n this.put(path, { kind: \"link\", target: relative(parentOf2(path), to) });\n }\n};\nfunction addNode(layout, node) {\n const name2 = node.path.slice(\"/dev/\".length);\n const family = DEVICE_NAME.exec(name2)?.[1];\n const { sys } = node;\n const bus = family === \"USB\" ? 1 : 2;\n const usb = `${HCD}/usb${bus}/${bus}-${node.minor + 1}`;\n const intf = `${usb}/${bus}-${node.minor + 1}:1.0`;\n const port = family === \"USB\" ? `${intf}/${name2}` : intf;\n const tty = sys ? `${port}/tty/${name2}` : `${VIRTUAL}/${name2}`;\n layout.link(`${CLASS}/${name2}`, tty);\n layout.file(`${tty}/dev`, `${node.major}:${node.minor}\n`);\n layout.file(`${tty}/uevent`, `MAJOR=${node.major}\nMINOR=${node.minor}\nDEVNAME=${name2}\n`);\n layout.link(`${tty}/subsystem`, CLASS);\n if (!sys) return;\n layout.link(`${tty}/device`, port);\n if (port !== intf) layout.link(`${port}/subsystem`, SERIAL_BUS);\n const id = product(sys.idVendor, sys.idProduct);\n layout.file(`${intf}/bInterfaceNumber`, \"00\\n\");\n layout.file(`${intf}/uevent`, `DEVTYPE=usb_interface\nPRODUCT=${id}\n`);\n layout.link(`${intf}/subsystem`, USB_BUS);\n layout.file(`${usb}/idVendor`, `${sys.idVendor}\n`);\n layout.file(`${usb}/idProduct`, `${sys.idProduct}\n`);\n layout.file(`${usb}/bNumInterfaces`, \" 1\\n\");\n for (const key of [\"manufacturer\", \"product\", \"serial\"]) {\n const text = sys[key];\n if (text !== void 0) layout.file(`${usb}/${key}`, `${text}\n`);\n }\n layout.file(`${usb}/uevent`, `DEVTYPE=usb_device\nPRODUCT=${id}\n`);\n layout.link(`${usb}/subsystem`, USB_BUS);\n}\nfunction sysLayout(nodes) {\n const layout = new Layout();\n for (const dir of ALWAYS) layout.dir(dir);\n for (const node of nodes) addNode(layout, node);\n return layout.entries;\n}\nvar SKELETON = sysLayout([]);\nvar FIXED = /* @__PURE__ */ new Set([\n \"/\",\n \"/sys\",\n \"/sys/class\",\n \"/sys/bus\",\n \"/sys/bus/usb\",\n \"/sys/bus/usb-serial\"\n]);\nvar BORN = Date.now();\nfunction walk(entries2, path, follow2) {\n const done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n let hops = 0;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \"..\") {\n done.pop();\n continue;\n }\n const here = entries2.get(`/${done.join(\"/\")}`);\n if (here?.kind !== \"dir\") throw sysError(\"ENOTDIR\", path);\n const entry = entries2.get(`/${[...done, part].join(\"/\")}`);\n if (!entry) throw sysError(\"ENOENT\", path);\n if (entry.kind === \"link\" && (follow2 || todo.length > 0)) {\n if (++hops > MAX_HOPS) throw sysError(\"ELOOP\", path);\n todo = [...entry.target.split(\"/\").filter((p) => p !== \"\" && p !== \".\"), ...todo];\n continue;\n }\n done.push(part);\n }\n return `/${done.join(\"/\")}`;\n}\nfunction walked(path, follow2) {\n try {\n return walk(SKELETON, path, follow2);\n } catch {\n return void 0;\n }\n}\nvar SysTree = class {\n source;\n built;\n constructor(source) {\n this.source = source;\n }\n async layout() {\n this.built ??= sysLayout(await this.source());\n return this.built;\n }\n async find(path, follow2, listing2 = false) {\n const known = walked(path, follow2);\n if (known !== void 0 && (!listing2 || FIXED.has(known)))\n return { at: known, entry: SKELETON.get(known) };\n const entries2 = await this.layout();\n const at = walk(entries2, path, follow2);\n return { at, entry: entries2.get(at) };\n }\n async resolve(path, follow2 = true) {\n return (await this.find(path, follow2)).at;\n }\n async stat(path, follow2 = true) {\n const { at, entry } = await this.find(path, follow2);\n const size = entry.kind === \"file\" ? new TextEncoder().encode(entry.text).length : entry.kind === \"link\" ? entry.target.length : 0;\n return {\n isFile: entry.kind === \"file\",\n isDirectory: entry.kind === \"dir\",\n isSymbolicLink: entry.kind === \"link\",\n size,\n mode: entry.kind === \"dir\" ? DIR_MODE : entry.kind === \"file\" ? FILE_MODE : LINK_MODE,\n mtimeMs: BORN,\n atimeMs: BORN,\n ctimeMs: BORN,\n ino: inodeOf2(at),\n nlink: entry.kind === \"dir\" ? 2 : 1,\n uid: 0,\n gid: 0,\n readonly: true\n };\n }\n async read(path) {\n const { entry } = await this.find(path, true);\n if (entry.kind !== \"file\") throw sysError(\"EISDIR\", path);\n return new TextEncoder().encode(entry.text);\n }\n async readdir(path) {\n const { entry } = await this.find(path, true, true);\n if (entry.kind !== \"dir\") throw sysError(\"ENOTDIR\", path);\n return [...entry.names].sort();\n }\n async readlink(path) {\n const { entry } = await this.find(path, false);\n if (entry.kind !== \"link\") throw sysError(\"EINVAL\", path);\n return entry.target;\n }\n async exists(path, follow2 = true) {\n try {\n await this.resolve(path, follow2);\n return true;\n } catch (err) {\n if (err.code === void 0) throw err;\n return false;\n }\n }\n async access(path, mode) {\n const { entry } = await this.find(path, true);\n if (mode & 2) throw sysError(\"EROFS\", path);\n if (mode & 1 && entry.kind !== \"dir\") throw sysError(\"EACCES\", path);\n }\n};\n\n// src/process/process-runtime.ts\nfunction ownBytes(bytes) {\n if (bytes.constructor === Uint8Array) return bytes;\n return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength).slice();\n}\nfunction ownedBuffer(body, given) {\n return body === given ? void 0 : [body.buffer];\n}\nvar FS_OPS = new Set(SYNC_FS_OPS);\nfunction deviceSys(call2) {\n const json = (r) => r.ok && r.kind === \"json\" ? r.json : void 0;\n return {\n async devNodes() {\n return json(await call2({ op: \"fd-dev-nodes\" }, \"fd-dev-nodes\"));\n },\n async openDev(path, flags) {\n return json(await call2({ op: \"fd-open-dev\", path, flags }, `fd-open-dev ${path}`));\n },\n async devIoctl(fd, request, arg) {\n const req = {\n op: \"fd-dev-ioctl\",\n fd,\n request,\n ...arg !== void 0 ? { arg } : {}\n };\n return json(await call2(req, `fd-dev-ioctl ${fd}`));\n },\n async devMeta(path, change) {\n await call2({ op: \"fd-dev-meta\", path, ...change }, `fd-dev-meta ${path}`);\n }\n };\n}\nfunction kernelSys(transport) {\n const call2 = async (req, label, transfer) => {\n const r = await transport.call(req, Number.POSITIVE_INFINITY, label, transfer);\n if (!r.ok) throw new SyscallError(r.errno);\n return r;\n };\n const json = (r) => r.ok && r.kind === \"json\" ? r.json : void 0;\n return {\n ...deviceSys(call2),\n async read(fd, max, opts) {\n const flags = {\n ...opts?.nonblock ? { nonblock: true } : {},\n ...opts?.peek ? { peek: true } : {}\n };\n const r = await call2({ op: \"fd-read\", fd, max, ...flags }, `fd-read ${fd}`);\n return r.ok && r.kind === \"bytes\" ? r.bytes : new Uint8Array(0);\n },\n async write(fd, bytes, opts) {\n const body = ownBytes(bytes);\n const req = {\n op: \"fd-write\",\n fd,\n body,\n ...opts?.nonblock ? { nonblock: true } : {}\n };\n const n = json(await call2(req, `fd-write ${fd}`, ownedBuffer(body, bytes)));\n return typeof n === \"number\" ? n : bytes.length;\n },\n async close(fd) {\n await call2({ op: \"fd-close\", fd }, `fd-close ${fd}`);\n },\n async pipe() {\n return json(await call2({ op: \"fd-pipe\" }, \"fd-pipe\"));\n },\n async poll(fd) {\n return json(await call2({ op: \"fd-poll\", fd }, `fd-poll ${fd}`));\n },\n async openVfs(path, flags, position, opts) {\n return json(\n await call2(\n {\n op: \"fd-open-vfs\",\n path,\n flags,\n position,\n ...opts?.contents !== void 0 ? { contents: opts.contents } : {},\n ...opts?.orphan ? { orphan: true } : {},\n ...opts?.truncate ? { truncate: true } : {},\n ...opts?.create ? { create: true } : {},\n ...opts?.created ? { created: true } : {},\n ...opts?.pin ? { pin: opts.pin } : {},\n ...opts?.handle !== void 0 ? { handle: opts.handle } : {},\n ...opts?.ino !== void 0 ? { ino: opts.ino } : {},\n ...opts?.nofollow ? { nofollow: true } : {},\n ...opts?.fifo ? { fifo: true } : {}\n },\n `fd-open-vfs ${path}`\n )\n );\n },\n async seek(fd, offset, whence) {\n return json(await call2({ op: \"fd-seek\", fd, offset, whence }, `fd-seek ${fd}`));\n },\n async flush(fd) {\n await call2({ op: \"fd-flush\", fd }, `fd-flush ${fd}`);\n },\n async pread(fd, max, at) {\n const r = await call2({ op: \"fd-pread\", fd, max, offset: at }, `fd-pread ${fd}`);\n return r.ok && r.kind === \"bytes\" ? r.bytes : new Uint8Array(0);\n },\n async pwrite(fd, bytes, at) {\n const body = ownBytes(bytes);\n return json(\n await call2({ op: \"fd-pwrite\", fd, offset: at, body }, `fd-pwrite ${fd}`, ownedBuffer(body, bytes))\n );\n },\n async isatty(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`))?.tty === true;\n },\n async ttyName(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`))?.name;\n },\n async kind(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`))?.kind;\n },\n async heldMeta(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`)).meta;\n },\n async access(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`)).access;\n },\n async size(fd) {\n return json(await call2({ op: \"fd-vfs-stat\", fd }, `fd-vfs-stat ${fd}`)).size;\n },\n async fdStat(fd) {\n const r = json(await call2({ op: \"fd-vfs-stat\", fd, full: true }, `fd-vfs-stat ${fd}`));\n return r?.stat;\n },\n async fdChmod(fd, mode) {\n await call2({ op: \"fd-chmod\", fd, mode }, `fd-chmod ${fd}`);\n },\n async fdChown(fd, uid, gid) {\n const ids = { ...uid !== void 0 ? { uid } : {}, ...gid !== void 0 ? { gid } : {} };\n await call2({ op: \"fd-chown\", fd, ...ids }, `fd-chown ${fd}`);\n },\n async fdUtimes(fd, atimeMs, mtimeMs, now) {\n await call2({ op: \"fd-utimes\", fd, atimeMs, mtimeMs, now }, `fd-utimes ${fd}`);\n },\n async ttyNames() {\n return json(await call2({ op: \"fd-tty-names\" }, \"fd-tty-names\"));\n },\n async ttyOwner(name2) {\n return json(await call2({ op: \"fd-tty-owner\", name: name2 }, `fd-tty-owner ${name2}`));\n },\n async openTty(name2) {\n const req = name2 === void 0 ? { op: \"fd-open-tty\" } : { op: \"fd-open-tty\", name: name2 };\n return json(await call2(req, `fd-open-tty ${name2 ?? \"\"}`));\n },\n async tcgets(fd) {\n return json(await call2({ op: \"tty-get\", fd }, `tty-get ${fd}`));\n },\n async tcsets(fd, termios, flush, drain) {\n const how = { ...flush ? { flush } : {}, ...drain ? { drain } : {} };\n await call2({ op: \"tty-set\", fd, termios, ...how }, `tty-set ${fd}`);\n },\n async winsize(fd) {\n return json(await call2({ op: \"tty-winsz\", fd }, `tty-winsz ${fd}`));\n },\n async openPty() {\n return json(await call2({ op: \"pty-open\" }, \"pty-open\"));\n },\n async openPts(n, noctty) {\n return json(await call2({ op: \"pty-slave-open\", n, noctty }, `pty-slave-open ${n}`));\n },\n async openSealed(flags) {\n return json(await call2({ op: \"fd-open-sealed\", flags }, \"fd-open-sealed\"));\n },\n async openClipboard(flags) {\n return json(await call2({ op: \"fd-open-clipboard\", flags }, \"fd-open-clipboard\"));\n },\n async clipboardAbort(fd) {\n await call2({ op: \"fd-clipboard-abort\", fd }, \"fd-clipboard-abort\");\n },\n async openEmbedder(flags) {\n return json(await call2({ op: \"fd-open-embedder\", flags }, \"fd-open-embedder\"));\n },\n async ptyNumbers() {\n return json(await call2({ op: \"pty-list\" }, \"pty-list\"));\n },\n async procList() {\n return json(await call2({ op: \"proc-list\" }, \"proc-list\"));\n },\n async mountList() {\n return json(await call2({ op: \"mount-list\" }, \"mount-list\"));\n },\n async setLock(target, kind, start2, len, wait) {\n const req = { op: \"lk-set\", ...target, kind, start: start2, len, ...wait ? { wait } : {} };\n await call2(req, \"lk-set\");\n },\n async getLock(target, kind, start2, len) {\n return json(await call2({ op: \"lk-get\", ...target, kind, start: start2, len }, \"lk-get\"));\n },\n async closeLocks(target) {\n await call2({ op: \"lk-close\", ...target }, \"lk-close\");\n },\n async flock(fd, kind, wait) {\n await call2({ op: \"flock\", fd, kind, ...wait ? { wait } : {} }, `flock ${fd}`);\n },\n async ptyNumber(fd) {\n return json(await call2({ op: \"pty-number\", fd }, `pty-number ${fd}`));\n },\n async ptyLock(fd, lock) {\n await call2({ op: \"pty-lock\", fd, lock }, `pty-lock ${fd}`);\n },\n async setControllingTerminal(fd) {\n await call2({ op: \"pty-ctty\", fd }, `pty-ctty ${fd}`);\n },\n async setPacketMode(fd, on) {\n await call2({ op: \"pty-packet\", fd, on }, `pty-packet ${fd}`);\n },\n async setWinsize(fd, rows, cols) {\n await call2({ op: \"pty-winsz-set\", fd, rows, cols }, `pty-winsz-set ${fd}`);\n }\n };\n}\nvar GLUE_TRAILER = [\n \"if (typeof ENV !== 'undefined') Object.assign(ENV, Module.sliccEnv);\",\n \"if (typeof thisProgram !== 'undefined' && Module.thisProgram === '') thisProgram = '';\",\n \"const __sliccTake = (name, value) => {\",\n \" const own = Object.getOwnPropertyDescriptor(Module, name);\",\n \" if (own && 'value' in own && own.value != null) return;\",\n \" Object.defineProperty(Module, name, { value, writable: true, configurable: true, enumerable: true });\",\n \"};\",\n \"if (typeof FS !== 'undefined') __sliccTake('FS', FS);\",\n \"if (typeof callMain === 'function') __sliccTake('callMain', callMain);\",\n \"if (typeof sliccRunMain === 'function') __sliccTake('sliccRunMain', sliccRunMain);\",\n \"if (typeof sliccForkChild === 'function') __sliccTake('sliccForkChild', sliccForkChild);\",\n \"if (typeof PIPEFS !== 'undefined') __sliccTake('PIPEFS', PIPEFS);\",\n \"Module.sliccSyscalls ??= {\",\n \" fcntl: typeof ___syscall_fcntl64 === 'function' ? ___syscall_fcntl64 : undefined,\",\n \" pipe2: typeof ___syscall_pipe2 === 'function' ? ___syscall_pipe2 : undefined,\",\n \" dup3: typeof ___syscall_dup3 === 'function' ? ___syscall_dup3 : undefined,\",\n \" socket: typeof ___syscall_socket === 'function' ? ___syscall_socket : undefined,\",\n \" accept4: typeof ___syscall_accept4 === 'function' ? ___syscall_accept4 : undefined,\",\n \" ioctl: typeof ___syscall_ioctl === 'function' ? ___syscall_ioctl : undefined,\",\n \" setitimer: typeof __setitimer_js === 'function' ? __setitimer_js : undefined,\",\n \"};\",\n \"Module.sliccKernelImports ??= {\",\n \" openat: typeof ___syscall_openat === 'function' ? ___syscall_openat : undefined,\",\n \" mkdirat: typeof ___syscall_mkdirat === 'function' ? ___syscall_mkdirat : undefined,\",\n \" mknodat: typeof ___syscall_mknodat === 'function' ? ___syscall_mknodat : undefined,\",\n \" umask: typeof ___syscall_umask === 'function' ? ___syscall_umask : undefined,\",\n \" faccessat: typeof ___syscall_faccessat === 'function' ? ___syscall_faccessat : undefined,\",\n \" linkat: typeof ___syscall_linkat === 'function' ? ___syscall_linkat : undefined,\",\n \" symlinkat: typeof ___syscall_symlinkat === 'function' ? ___syscall_symlinkat : undefined,\",\n \" uname: typeof ___syscall_uname === 'function' ? ___syscall_uname : undefined,\",\n \" utimensat: typeof ___syscall_utimensat === 'function' ? ___syscall_utimensat : undefined,\",\n \" getppid: typeof _slicc_getppid_js === 'function' ? _slicc_getppid_js : undefined,\",\n \" resizeHeap: typeof _emscripten_resize_heap === 'function' ? _emscripten_resize_heap : undefined,\",\n \" fdWrite: typeof _fd_write === 'function' ? _fd_write : undefined,\",\n \" fdRead: typeof _fd_read === 'function' ? _fd_read : undefined,\",\n \" sleepMs: typeof slicc_sleep_ms === 'function' ? slicc_sleep_ms : undefined,\",\n \" flock: typeof __syscall_flock === 'function' ? __syscall_flock : undefined,\",\n \"};\",\n \"Module.sliccFdImports ??= {\",\n \" fd_sync: typeof _fd_sync === 'function' ? _fd_sync : undefined,\",\n \" fd_pread: typeof _fd_pread === 'function' ? _fd_pread : undefined,\",\n \" fd_pwrite: typeof _fd_pwrite === 'function' ? _fd_pwrite : undefined,\",\n \"};\",\n \"const __sliccUp = () =>\",\n \" (typeof runtimeInitialized === 'undefined' || runtimeInitialized) &&\",\n \" !(typeof runtimeExited !== 'undefined' && runtimeExited) &&\",\n \" !(typeof ABORT !== 'undefined' && ABORT);\",\n \"Module.sliccSigpipe ??= () => (__sliccUp() && typeof _slicc_sigpipe === 'function' ? _slicc_sigpipe() : -1);\",\n \"Module.sliccSigMask ??= (w) => (__sliccUp() && typeof _slicc_sig_mask === 'function' ? _slicc_sig_mask(w) : -1);\",\n \"Module.sliccRaise ??= (sig) => { if (__sliccUp() && typeof _slicc_raise === 'function') _slicc_raise(sig); };\",\n \"Module.sliccTimerFire ??= (which) => {\",\n \" if (!__sliccUp() || typeof __emscripten_timeout !== 'function') return false;\",\n \" __emscripten_timeout(which, typeof _emscripten_get_now === 'function' ? _emscripten_get_now() : performance.now());\",\n \" return true;\",\n \"};\",\n \"if (typeof SliccFork !== 'undefined' && !SliccFork.balancesKeepalive && typeof runtimeKeepalivePop === 'function') {\",\n \" let __sliccForking = SliccFork.forking === true;\",\n \" Object.defineProperty(SliccFork, 'forking', {\",\n \" get: () => __sliccForking,\",\n \" set: (on) => { if (__sliccForking && !on) runtimeKeepalivePop(); __sliccForking = on; },\",\n \" configurable: true,\",\n \" });\",\n \"}\"\n].join(\"\\n\");\nasync function identify(transport, init) {\n const r = await transport.call({ op: \"proc-identity\" }, Number.POSITIVE_INFINITY, \"proc-identity\");\n const id = r.ok && r.kind === \"json\" ? r.json : null;\n return id ?? { pid: init.pid, ppid: init.ppid ?? 1 };\n}\nfunction signalMasks(m, seeded = { bits: 0 }) {\n const mask = m.sliccSigMask;\n const caught = mask?.(0) ?? -1;\n if (!mask || caught === -1) return null;\n const ignored = mask(1);\n const defaults = seeded.bits & ~ignored & ~caught;\n seeded.bits &= ~defaults;\n return { caught, ignored, restart: mask(2), ...defaults ? { defaults } : {} };\n}\n\n// src/process/wasi/wasi-files.ts\nvar FOLLOW_MS = 2e3;\nvar WasiError = class extends Error {\n code;\n constructor(code2) {\n super(code2);\n this.code = code2;\n }\n};\nvar FileBuffer = class {\n data;\n length = 0;\n dirty = false;\n whole = false;\n from = Infinity;\n to = 0;\n orphaned = false;\n opens = 0;\n fs;\n where;\n ranged;\n watch;\n seen = 0;\n maxFile;\n handle;\n moved;\n bound;\n real;\n constructor(fs, path, empty, maxFile, size, version, watch) {\n this.fs = fs;\n this.where = path;\n this.maxFile = maxFile;\n const { pread, pwrite, truncate } = fs;\n this.watch = watch;\n this.seen = watch?.seen ?? watch?.view.now() ?? 0;\n if (size !== void 0 && pread && pwrite && truncate) {\n const io = {\n pread: async (_, ...rest2) => await this.retried(async () => await pread.call(fs, this.where, ...rest2)),\n pwrite: async (_, ...rest2) => await this.retried(async () => await pwrite.call(fs, this.where, ...rest2)),\n truncate: async (_, size2) => await this.retried(async () => await truncate.call(fs, this.where, size2))\n };\n this.ranged = new RangedFile(io, path, size, version, watch);\n } else if (empty) {\n this.data = new Uint8Array(0);\n this.dirty = true;\n this.whole = true;\n }\n }\n get path() {\n return this.where;\n }\n async emptied(empty) {\n if (empty && this.ranged) await this.truncate(0);\n return this;\n }\n async retried(op) {\n const end = performance.now() + FOLLOW_MS;\n for (; ; ) {\n try {\n return await op();\n } catch (err) {\n const code2 = err.code;\n const followable = code2 === \"ENOENT\" || code2 === \"EIO\";\n if (!followable || performance.now() > end || !await this.moved?.(true)) throw err;\n }\n }\n }\n set path(path) {\n this.where = path;\n if (this.ranged) this.ranged.path = path;\n }\n get isRanged() {\n return this.ranged !== void 0;\n }\n get pin() {\n return this.ranged?.pinnedVersion;\n }\n async keep() {\n if (this.ranged) await this.ranged.pin();\n else await this.load();\n }\n async prefetch() {\n if (this.ranged) await this.ranged.prefetch();\n else await this.load();\n }\n async load() {\n const view = this.watch?.view;\n if (this.data && view && this.watch && !this.dirty) {\n const { now, changed: changed2 } = await watchedChange(this.watch, this.seen, this.path);\n this.seen = now;\n if (changed2) this.data = void 0;\n }\n if (!this.data) {\n this.seen = view?.now() ?? 0;\n this.data = await this.retried(async () => await this.fs.readFile(this.path));\n this.length = this.data.length;\n }\n return this.data;\n }\n spoiled = false;\n spoil() {\n this.spoiled = true;\n this.dirty = false;\n }\n live() {\n if (this.spoiled) throw new WasiError(\"ESTALE\");\n }\n peered = false;\n held() {\n const view = this.watch?.view;\n if (!view) return false;\n return view.peerHeld(this.where) || this.real !== void 0 && view.peerHeld(this.real);\n }\n crowded() {\n if (this.held()) this.peered = true;\n return this.peered;\n }\n async exact() {\n await this.flush();\n const watch = this.watch;\n const size = (await this.retried(async () => await watch.stat(this.where))).size;\n this.peered = this.held();\n if (this.ranged) {\n if (size !== await this.ranged.size()) await this.ranged.reread();\n return void 0;\n }\n if (this.data && size !== this.length) this.data = void 0;\n return this.data ? void 0 : size;\n }\n async wrote(at, bytes) {\n if (this.ranged) {\n await this.ranged.wrote(at, bytes.length);\n return;\n }\n const view = this.watch.view;\n const { now, changed: changed2 } = view.changedSince(this.seen, this.where);\n this.seen = now;\n if (changed2) this.data = void 0;\n if (!this.data) return;\n const end = at + bytes.length;\n this.ensure(end);\n const buf = this.data;\n if (at > this.length) buf.fill(0, this.length, at);\n buf.set(bytes, at);\n this.length = Math.max(this.length, end);\n }\n async size() {\n this.live();\n if (this.crowded()) {\n const known = await this.exact();\n if (known !== void 0) return known;\n }\n if (this.ranged) return await this.ranged.size();\n await this.load();\n return this.length;\n }\n async pread(max, at) {\n this.live();\n if (this.ranged) return await this.ranged.read(at, max);\n const bytes = await this.load();\n const n = Math.max(0, Math.min(max, this.length - at));\n return bytes.subarray(at, at + n);\n }\n fits(end) {\n if (this.maxFile !== void 0 && end > this.maxFile) throw new WasiError(\"EFBIG\");\n }\n async pwrite(bytes, at) {\n this.live();\n if (bytes.length === 0) return 0;\n const end = at + bytes.length;\n this.fits(end);\n const { pwrite } = this.fs;\n if (pwrite && this.crowded() && end > await this.size()) {\n const copy = bytes.slice();\n await this.retried(async () => await pwrite.call(this.fs, this.where, at, copy, true));\n await this.wrote(at, bytes);\n return bytes.length;\n }\n this.dirty = true;\n if (this.ranged) {\n await this.ranged.write(at, bytes);\n return bytes.length;\n }\n await this.load();\n this.ensure(end);\n const buf = this.data;\n this.from = Math.min(this.from, at, this.length);\n this.to = Math.max(this.to, end);\n if (at > this.length) buf.fill(0, this.length, at);\n buf.set(bytes, at);\n this.length = Math.max(this.length, end);\n return bytes.length;\n }\n async append(bytes) {\n this.live();\n const { append } = this.fs;\n if (!append || this.orphaned) return void 0;\n await this.moved?.(false);\n await this.flush();\n const end = await this.retried(async () => await append.call(this.fs, this.path, bytes));\n if (!this.ranged) {\n this.data = void 0;\n this.length = 0;\n }\n return end;\n }\n async truncate(size) {\n this.live();\n this.fits(size);\n this.dirty = true;\n if (this.ranged) {\n this.ranged.truncate(size);\n return;\n }\n await this.load();\n this.ensure(size);\n this.whole = true;\n if (size > this.length) this.data.fill(0, this.length, size);\n this.length = size;\n }\n ensure(need) {\n const cur = this.data;\n if (cur.length >= need) return;\n const grown = new Uint8Array(Math.max(need, cur.length * 2, 4096));\n grown.set(cur.subarray(0, this.length));\n this.data = grown;\n }\n async orphan() {\n this.orphaned = true;\n await this.ranged?.pin();\n }\n async reread() {\n if (this.dirty || this.orphaned) return;\n if (this.ranged) await this.ranged.reread();\n else this.data = void 0;\n }\n isOrphan() {\n return this.orphaned;\n }\n isDirty() {\n return this.dirty;\n }\n async contents() {\n this.live();\n if (this.ranged) return await this.ranged.read(0, await this.ranged.size());\n return (await this.load()).slice(0, this.length);\n }\n async flush() {\n if (this.orphaned || !this.dirty) return;\n await this.moved?.(false);\n if (this.ranged) await this.ranged.flush();\n else if (!this.data) return;\n else if (this.whole || !this.fs.pwrite) {\n const whole = this.data.slice(0, this.length);\n await this.retried(async () => await this.fs.writeFile(this.path, whole, true));\n } else {\n const { pwrite } = this.fs;\n const run = this.data.slice(this.from, this.to);\n await this.retried(async () => await pwrite.call(this.fs, this.path, this.from, run, true));\n }\n this.dirty = false;\n this.whole = false;\n this.from = Infinity;\n this.to = 0;\n }\n};\nvar LocalFile = class {\n offset = 0;\n refs = 1;\n ino;\n buffer;\n readable;\n writable;\n append;\n constructor(buffer, readable, writable, append) {\n this.buffer = buffer;\n this.readable = readable;\n this.writable = writable;\n this.append = append;\n }\n get path() {\n return this.buffer.path;\n }\n async size() {\n return await this.buffer.size();\n }\n async pread(max, at) {\n return await this.buffer.pread(max, at);\n }\n async read(max) {\n const out = await this.buffer.pread(max, this.offset);\n this.offset += out.length;\n return out;\n }\n async pwrite(bytes, at) {\n return await this.buffer.pwrite(bytes, at);\n }\n async write(bytes) {\n if (this.append && bytes.length > 0) {\n this.buffer.fits(await this.buffer.size() + bytes.length);\n const end = await this.buffer.append(bytes);\n if (end !== void 0) {\n this.offset = end;\n return bytes.length;\n }\n }\n if (this.append) this.offset = await this.buffer.size();\n const n = await this.buffer.pwrite(bytes, this.offset);\n this.offset += n;\n return n;\n }\n async truncate(size) {\n await this.buffer.truncate(size);\n }\n async flush() {\n await this.buffer.flush();\n }\n};\nfunction normalize(path) {\n const out = [];\n for (const seg of path.split(\"/\")) {\n if (seg === \"\" || seg === \".\") continue;\n if (seg === \"..\") out.pop();\n else out.push(seg);\n }\n return `/${out.join(\"/\")}`;\n}\nvar MAX_LINKS = 40;\nasync function physical(fs, path) {\n let done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n let hops = 0;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \"..\") {\n done.pop();\n continue;\n }\n if (!todo.includes(\"..\")) {\n done.push(part);\n continue;\n }\n const at = `/${[...done, part].join(\"/\")}`;\n const st = await fs.lstat(at);\n if (st.isSymbolicLink) {\n if (++hops > MAX_LINKS) throw new WasiError(\"ELOOP\");\n if (fs.links) await fs.access?.(at, 0, \"follow\", true);\n const target = await fs.readlink(at);\n if (target.startsWith(\"/\")) done = [];\n todo = [...target.split(\"/\").filter((p) => p !== \"\" && p !== \".\"), ...todo];\n } else if (!st.isDirectory) {\n throw new WasiError(\"ENOTDIR\");\n } else {\n done.push(part);\n }\n }\n return `/${done.join(\"/\")}`;\n}\nasync function realOf(fs, path) {\n let done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n let hops = 0;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \"..\") {\n done.pop();\n continue;\n }\n const at = `/${[...done, part].join(\"/\")}`;\n if (!(await fs.lstat(at)).isSymbolicLink) {\n done.push(part);\n continue;\n }\n if (++hops > MAX_LINKS) throw new WasiError(\"ELOOP\");\n const target = await fs.readlink(at);\n if (target.startsWith(\"/\")) done = [];\n todo = [...target.split(\"/\").filter((p) => p !== \"\" && p !== \".\"), ...todo];\n }\n return `/${done.join(\"/\")}`;\n}\nfunction resolveUnder(dir, path) {\n return normalize(path.startsWith(\"/\") ? path : `${dir}/${path}`);\n}\nfunction pathInode(path) {\n let h = 0xcbf29ce484222325n;\n for (let i = 0; i < path.length; i++) {\n h ^= BigInt(path.charCodeAt(i));\n h = h * 0x100000001b3n & 0xffffffffffffffffn;\n }\n return h;\n}\nvar MISS_TTL_MS = 20;\nvar CACHE_CAP = 8192;\nvar FS_GEN = 4;\nvar CRED_GEN = 5;\nvar UMASK = 6;\nvar RING2 = 8;\nvar RING_SIZE2 = 64;\nvar SLOT2 = 3;\nvar FD_RING = RING2 + RING_SIZE2 * SLOT2;\nvar FD_RING_SIZE = 64;\nvar SHARED_IDS_BYTES = (FD_RING + FD_RING_SIZE * 2) * 4;\nfunction inoKey(st) {\n return \"ino\" in st && typeof st.ino === \"number\" ? st.ino % 4294967296 | 0 : 0;\n}\nfunction pathHash(path) {\n let h = 2166136261;\n for (let i = 0; i < path.length; i++) h = Math.imul(h ^ path.charCodeAt(i), 16777619);\n return h === 0 ? 1 : h;\n}\nvar StatCache = class {\n stats = /* @__PURE__ */ new Map();\n lstats = /* @__PURE__ */ new Map();\n byHash = /* @__PURE__ */ new Map();\n byIno = /* @__PURE__ */ new Map();\n missed = /* @__PURE__ */ new Map();\n shared;\n seen;\n constructor(shared) {\n this.shared = shared;\n this.seen = shared ? Atomics.load(shared, FS_GEN) : 0;\n }\n put(map, path, entry) {\n if (this.stats.size + this.lstats.size + this.byHash.size + this.byIno.size >= CACHE_CAP)\n this.clear();\n map.set(path, entry);\n if (\"until\" in entry) {\n const paths = this.missed.get(map) ?? /* @__PURE__ */ new Set();\n paths.add(path);\n this.missed.set(map, paths);\n }\n if (!this.shared) return;\n index(this.byHash, pathHash(path), path);\n const ino = inoKey(entry);\n if (ino !== 0) index(this.byIno, ino, path);\n }\n fresh() {\n if (!this.shared) return;\n const now = Atomics.load(this.shared, FS_GEN);\n if (now === this.seen) return;\n this.replay(now);\n this.seen = now;\n }\n changed(path, ino = 0) {\n const key = ino % 4294967296 | 0;\n if (this.shared) {\n const g = this.publish(this.shared, path === void 0 ? 0 : pathHash(path), key);\n this.replay(g - 1);\n this.seen = g;\n if (path === void 0) this.clear();\n else this.drop(pathHash(path), key);\n }\n if (path === void 0) return;\n this.stats.delete(path);\n this.lstats.delete(path);\n }\n mutated(paths, ino = 0) {\n const key = ino % 4294967296 | 0;\n if (paths.length === 0 || !this.shared) this.clear();\n if (!this.shared) return;\n for (const [i, hash] of (paths.length > 0 ? paths.map(pathHash) : [0]).entries()) {\n const g = this.publish(this.shared, hash, i === 0 ? key : 0);\n if (paths.length > 0) this.replay(g - 1);\n this.seen = g;\n }\n if (paths.length === 0) return;\n for (const [i, path] of paths.entries()) {\n this.stats.delete(path);\n this.lstats.delete(path);\n this.drop(pathHash(path), i === 0 ? key : 0);\n }\n this.forgetMisses();\n }\n async inoOf(path, look) {\n if (!this.shared) return 0;\n this.fresh();\n const hit = this.stats.get(path);\n if (hit && \"ino\" in hit && typeof hit.ino === \"number\") return hit.ino;\n try {\n return (await look()).ino ?? 0;\n } catch {\n return 0;\n }\n }\n publish(shared, hash, ino) {\n const g = Atomics.add(shared, FS_GEN, 1) + 1;\n const at = RING2 + g % RING_SIZE2 * SLOT2;\n Atomics.store(shared, at, 0);\n Atomics.store(shared, at + 1, hash);\n Atomics.store(shared, at + 2, ino);\n Atomics.store(shared, at, g);\n return g;\n }\n replay(upTo) {\n const shared = this.shared;\n const missed = [];\n for (let g = this.seen + 1; g <= upTo && upTo - this.seen <= RING_SIZE2; g++) {\n const at = RING2 + g % RING_SIZE2 * SLOT2;\n const tag = Atomics.load(shared, at);\n const hash = Atomics.load(shared, at + 1);\n const ino = Atomics.load(shared, at + 2);\n if (tag !== g || hash === 0 || Atomics.load(shared, at) !== g) break;\n missed.push([hash, ino]);\n }\n if (missed.length < upTo - this.seen) this.clear();\n else for (const [hash, ino] of missed) this.drop(hash, ino);\n }\n drop(hash, ino) {\n const paths = [\n ...this.byHash.get(hash) ?? [],\n ...ino === 0 ? [] : this.byIno.get(ino) ?? []\n ];\n for (const path of paths) {\n this.stats.delete(path);\n this.lstats.delete(path);\n }\n this.byHash.delete(hash);\n if (ino !== 0) this.byIno.delete(ino);\n }\n forgetMisses() {\n for (const [map, paths] of this.missed) {\n for (const path of paths) if (\"until\" in (map.get(path) ?? {})) map.delete(path);\n }\n this.missed.clear();\n }\n clear() {\n this.missed.clear();\n this.stats.clear();\n this.lstats.clear();\n this.byHash.clear();\n this.byIno.clear();\n }\n};\nfunction index(map, key, path) {\n const paths = map.get(key) ?? /* @__PURE__ */ new Set();\n paths.add(path);\n map.set(key, paths);\n}\nvar SEEN_CAP = 4096;\nvar SeenAt = class {\n view;\n lstats;\n links = /* @__PURE__ */ new Map();\n stats = /* @__PURE__ */ new Map();\n constructor(view, lstats) {\n this.view = view;\n this.lstats = lstats;\n }\n of(map) {\n return map === this.lstats ? this.links : this.stats;\n }\n lstat(path) {\n return this.links.get(path);\n }\n saw(map, path, gen) {\n const seen = this.of(map);\n if (seen.size >= SEEN_CAP) seen.clear();\n seen.set(path, gen);\n }\n changed(map, path) {\n if (this.view === void 0) return false;\n const seen = this.of(map);\n const gen = seen.get(path);\n if (gen === void 0) return true;\n const since = this.view.changedSince(gen, path);\n if (!since.changed) seen.set(path, since.now);\n return since.changed;\n }\n};\nfunction goneAbove(maps, live, path) {\n for (let at = path.lastIndexOf(\"/\"); at > 0; at = path.lastIndexOf(\"/\", at - 1)) {\n const up = path.slice(0, at);\n for (const map of maps) {\n const hit = map.get(up);\n const code2 = hit && \"until\" in hit ? hit.error.code : void 0;\n if (hit && \"until\" in hit && code2 === \"ENOENT\" && live(hit, up)) return hit;\n }\n }\n return void 0;\n}\nvar remember = (cache, seen, blind, fill) => (path, made) => {\n if (!made || blind) return made;\n const { seen: at, ...st } = made;\n fill(st);\n cache.put(cache.stats, path, st);\n if (at !== void 0) seen.saw(cache.stats, path, at);\n return made;\n};\nfunction copying(bridge, mutating, entry) {\n const { copy } = bridge;\n if (!copy) return {};\n return {\n copy: async (from, to, mode, exclusive) => await mutating(async () => await copy.call(bridge, from, to, mode, exclusive), ...entry(to))\n };\n}\nvar Fills = class {\n at = /* @__PURE__ */ new WeakMap();\n view;\n now;\n constructor(view, now) {\n this.view = view;\n this.now = now;\n }\n set(entry, at = this.now()) {\n this.at.set(entry, at);\n }\n young(entry) {\n if (!this.view?.foreign()) return true;\n return this.now() - (this.at.get(entry) ?? Number.NEGATIVE_INFINITY) < SHARED_TTL_MS;\n }\n};\nfunction listed({ cache, seen, filled }, p, list, gen, asked) {\n const base = p === \"/\" ? \"\" : p;\n for (const [name2, st] of list) {\n if (!st) continue;\n filled.set(st, asked);\n const at = `${base}/${name2}`;\n cache.put(cache.lstats, at, st);\n if (gen !== void 0) seen.saw(cache.lstats, at, gen);\n if (st.isSymbolicLink) continue;\n cache.put(cache.stats, at, st);\n if (gen !== void 0) seen.saw(cache.stats, at, gen);\n }\n}\nasync function fetched({\n view,\n now,\n seen,\n filled,\n cache\n}, map, path, get) {\n const gen = view?.now();\n const asked = now();\n let hit;\n try {\n hit = await get();\n if (gen !== void 0) seen.saw(map, path, gen);\n } catch (e) {\n hit = { error: e, until: asked + MISS_TTL_MS, ...gen !== void 0 ? { gen } : {} };\n }\n filled.set(hit, asked);\n cache.put(map, path, hit);\n return hit;\n}\nfunction cachingBridge(bridge, now = () => performance.now(), shared) {\n const blind = shared !== void 0 && shared.length * 4 < SHARED_IDS_BYTES;\n const cache = new StatCache(blind ? void 0 : shared);\n const { stats, lstats } = cache;\n const view = bridge.changes;\n const filled = new Fills(view, now);\n const young = (entry2) => filled.young(entry2);\n const live = (miss, path) => miss.until > now() && young(miss) && (view === void 0 || miss.gen === void 0 || !view.changedSince(miss.gen, path).changed);\n const seen = new SeenAt(view, lstats);\n const kept = remember(cache, seen, blind, (entry2) => filled.set(entry2));\n const gone = (path) => goneAbove([lstats, stats], live, path);\n const usable = (map, path) => {\n const hit = map.get(path);\n if (hit === void 0) return void 0;\n if (\"until\" in hit) return live(hit, path) ? hit : void 0;\n return young(hit) && !seen.changed(map, path) ? hit : void 0;\n };\n const cached = async (map, path, get) => {\n if (blind) return await get();\n cache.fresh();\n let hit = usable(map, path);\n if (hit === void 0) {\n const missing3 = gone(path);\n if (missing3) throw missing3.error;\n hit = await fetched({ view, now, seen, filled, cache }, map, path, get);\n }\n if (\"until\" in hit) throw hit.error;\n return hit;\n };\n const invalidate = () => cache.mutated([]);\n const touched = (path, ino) => cache.changed(path, ino);\n const { chown: chown2 } = bridge;\n const mutating = async (op, ...paths) => {\n try {\n return await op();\n } finally {\n cache.mutated(paths);\n }\n };\n let exact = false;\n const threaded = async () => {\n if (blind || shared === void 0 || !bridge.identify) return;\n exact = true;\n await bridge.identify();\n };\n const identified = async (p, op, also) => {\n try {\n return await op();\n } finally {\n const st = await bridge.identified?.() ?? null;\n if (st) cache.mutated([p, ...also], st.ino);\n else cache.mutated([]);\n }\n };\n const relabeling = async (p, op) => {\n if (exact || !bridge.identifyNext) return await rewriting(p, op);\n await bridge.identifyNext();\n try {\n return await op();\n } finally {\n const st = await bridge.identified?.() ?? null;\n if (st) cache.mutated([p], st.ino);\n else cache.mutated([]);\n }\n };\n const rewriting = async (p, op, ...also) => {\n if (exact) return await identified(p, op, also);\n const ino = await cache.inoOf(p, async () => await bridge.stat(p));\n try {\n return await op();\n } finally {\n cache.mutated([p, ...also], ino);\n }\n };\n const entry = (p) => [p, p.slice(0, p.lastIndexOf(\"/\")) || \"/\"];\n return {\n ...bridge.changes ? { changes: bridge.changes } : {},\n ...bridge.renames ? { renames: bridge.renames.bind(bridge) } : {},\n readFile: async (p) => await bridge.readFile(p),\n readdir: async (p) => await bridge.readdir(p),\n readdirStat: async (p) => {\n const gen = view?.now();\n const asked = now();\n const list = await bridge.readdirStat(p);\n if (!blind) listed({ cache, seen, filled }, p, list, gen, asked);\n return list;\n },\n readlink: async (p) => {\n if (!blind) cache.fresh();\n const known = blind ? void 0 : lstats.get(p);\n const gen = seen.lstat(p);\n const current2 = view !== void 0 && gen !== void 0 && !view.changedSince(gen, p).changed;\n if (known && current2 && !(\"until\" in known) && young(known) && !known.isSymbolicLink) {\n throw syncError(\"EINVAL\", `'${p}' is not a symbolic link`);\n }\n return await bridge.readlink(p);\n },\n stat: async (p) => await cached(stats, p, async () => await bridge.stat(p)),\n lstat: async (p) => await cached(lstats, p, async () => await bridge.lstat(p)),\n exists: async (p) => {\n try {\n await cached(stats, p, async () => await bridge.stat(p));\n return true;\n } catch {\n return false;\n }\n },\n writeFile: async (p, bytes, open) => await rewriting(p, async () => await bridge.writeFile(p, bytes, open), ...entry(p).slice(1)),\n mkdir: async (p) => await mutating(async () => await bridge.mkdir(p), ...entry(p)),\n rm: async (p) => await mutating(async () => await bridge.rm(p)),\n rename: async (from, to) => await mutating(async () => await bridge.rename(from, to)),\n link: async (from, to, follow2) => await mutating(async () => await bridge.link(from, to, follow2)),\n unlink: async (p) => await mutating(async () => await bridge.unlink(p)),\n rmdir: async (p) => await mutating(async () => await bridge.rmdir(p)),\n symlink: async (target, link) => await mutating(async () => await bridge.symlink(target, link), ...entry(link)),\n chmod: async (p, mode) => await relabeling(p, async () => await bridge.chmod(p, mode)),\n utimes: async (p, a, m, now2) => await relabeling(p, async () => await bridge.utimes(p, a, m, now2)),\n lutimes: async (p, a, m, now2) => await mutating(async () => await bridge.lutimes(p, a, m, now2)),\n ...bridge.hold ? { hold: bridge.hold.bind(bridge) } : {},\n ...bridge.heldReal ? { heldReal: bridge.heldReal.bind(bridge) } : {},\n ...bridge.access ? { access: bridge.access.bind(bridge) } : {},\n ...bridge.kept ? { kept: bridge.kept.bind(bridge) } : {},\n ...bridge.keptStat ? { keptStat: bridge.keptStat.bind(bridge) } : {},\n ...bridge.pinned ? { pinned: async (handle) => await pinnedIo(bridge, handle, rewriting) } : {},\n ...bridge.create ? {\n create: async (p, mode, opening) => kept(\n p,\n await mutating(async () => await bridge.create?.(p, mode, opening), ...entry(p))\n )\n } : {},\n ...bridge.mkfifo ? {\n mkfifo: async (p, mode) => await mutating(async () => await bridge.mkfifo?.(p, mode), ...entry(p))\n } : {},\n ...copying(bridge, mutating, entry),\n ...chown2 ? {\n chown: async (p, ...rest2) => await relabeling(p, async () => await chown2.call(bridge, p, ...rest2))\n } : {},\n ...bridge.pread && bridge.pwrite && bridge.truncate ? {\n pread: bridge.pread.bind(bridge),\n pwrite: async (p, at, bytes, transfer) => await rewriting(p, async () => await bridge.pwrite?.(p, at, bytes, transfer)),\n truncate: async (p, size) => await rewriting(p, async () => await bridge.truncate?.(p, size))\n } : {},\n ...bridge.append ? {\n append: async (p, bytes) => await rewriting(p, async () => await bridge.append(p, bytes))\n } : {},\n ...bridge.owners ? { owners: true } : {},\n ...bridge.links ? { links: true } : {},\n invalidate,\n touched,\n threaded\n };\n}\nasync function pinnedIo(bridge, handle, rewriting) {\n const io = await bridge.pinned(handle);\n const { pread, pwrite, truncate } = io;\n return {\n readFile: async (p) => await io.readFile(p),\n writeFile: async (p, bytes, open) => await rewriting(p, async () => await io.writeFile(p, bytes, open)),\n pread: async (p, at, n, version) => await pread(p, at, n, version),\n pwrite: async (p, at, bytes, transfer) => await rewriting(p, async () => await pwrite(p, at, bytes, transfer)),\n truncate: async (p, size) => await rewriting(p, async () => await truncate(p, size)),\n ...io.append ? {\n append: async (p, bytes) => await rewriting(p, async () => await io.append(p, bytes))\n } : {}\n };\n}\n\n// src/fs/physical-path.ts\nvar MAX_HOPS2 = 40;\nfunction start(path) {\n return { done: [], todo: path.split(\"/\").filter((p) => p !== \"\"), hops: 0 };\n}\nfunction next(walk2) {\n while (walk2.todo.length > 0) {\n const part = walk2.todo.shift();\n if (part === \".\") continue;\n if (part === \"..\") {\n walk2.done.pop();\n continue;\n }\n return part;\n }\n return void 0;\n}\nfunction lexical(path) {\n const walk2 = start(path);\n for (let part = next(walk2); part !== void 0; part = next(walk2)) walk2.done.push(part);\n return `/${walk2.done.join(\"/\")}`;\n}\nfunction rest(walk2, part) {\n return lexical(`/${[...walk2.done, part, ...walk2.todo].join(\"/\")}`);\n}\nfunction follow(walk2, target) {\n if (++walk2.hops > MAX_HOPS2) return false;\n if (target.startsWith(\"/\")) walk2.done.length = 0;\n walk2.todo = [...target.split(\"/\").filter((p) => p !== \"\"), ...walk2.todo];\n return true;\n}\nasync function physicalPath(fs, path) {\n const walk2 = start(path);\n for (let part = next(walk2); part !== void 0; part = next(walk2)) {\n const at = `/${[...walk2.done, part].join(\"/\")}`;\n let target;\n try {\n target = (await fs.lstat(at)).isSymbolicLink ? await fs.readlink(at) : void 0;\n } catch {\n return rest(walk2, part);\n }\n if (target === void 0) walk2.done.push(part);\n else if (!follow(walk2, target)) {\n throw Object.assign(new Error(\"too many levels of symbolic links\"), { code: \"ELOOP\" });\n }\n }\n return `/${walk2.done.join(\"/\")}`;\n}\nasync function physicalLeaf(fs, path) {\n const walk2 = start(path);\n for (let part = next(walk2); part !== void 0; part = next(walk2)) {\n const at = `/${[...walk2.done, part].join(\"/\")}`;\n let target;\n try {\n target = (await fs.lstat(at)).isSymbolicLink ? await fs.readlink(at) : void 0;\n } catch {\n const tail = walk2.todo;\n return tail.some((p) => p === \".\" || p === \"..\") ? void 0 : [at, ...tail].join(\"/\");\n }\n if (target === void 0) walk2.done.push(part);\n else if (!follow(walk2, target)) return void 0;\n }\n return `/${walk2.done.join(\"/\")}`;\n}\n\n// src/process/js/js-kernel.ts\nvar JsCallError = class extends Error {\n code;\n detail;\n dev;\n constructor(code2, what, detail) {\n super(`${what}: ${code2}`);\n this.name = \"JsCallError\";\n this.code = code2;\n this.detail = detail;\n }\n};\n\n// src/process/js/js-io.ts\nvar CHUNK = 64 * 1024;\nvar MAX_IO = 1024 * 1024;\nvar MAX_PREAD = 16 * 1024 * 1024;\n\n// src/process/js/js-dev.ts\nvar DEV_READ_MAX = 64 * 1024 * 1024;\nvar DEVICES = [\"null\", \"zero\", \"full\", \"random\", \"urandom\"];\nvar STDIO = [\"stdin\", \"stdout\", \"stderr\"];\nvar SELF_FD = \"/proc/self/fd\";\nvar S_IFMT = 61440;\nvar DIR = 16384;\nvar LINK = 40960;\nvar CHAR = 8192;\nvar BORN2 = Date.now();\nvar CHAR_KINDS = /* @__PURE__ */ new Set([\n \"device\",\n \"tty\",\n \"clipboard\",\n \"embedder\",\n \"sealed\"\n]);\nfunction inDev(abs) {\n return abs.startsWith(\"/dev\") && (abs.length === 4 || abs[4] === \"/\") && !inShm(abs);\n}\nfunction missing(path) {\n throw new JsCallError(\"ENOENT\", path);\n}\nfunction nodeStat(mode, size = 0, owner) {\n return {\n isFile: false,\n isDirectory: (mode & S_IFMT) === DIR,\n isSymbolicLink: (mode & S_IFMT) === LINK,\n size,\n mode,\n mtimeMs: BORN2,\n atimeMs: BORN2,\n ctimeMs: BORN2,\n nlink: 1,\n uid: owner?.uid ?? 0,\n gid: owner?.gid ?? 0\n };\n}\nvar SERIAL = \"/dev/serial\";\nfunction serialNamed(name2) {\n return DEVICE_NAME.test(name2) || name2 === \"serial\" || name2.startsWith(\"serial/\");\n}\nfunction serialNode(abs, nodes) {\n const node = nodes.find((n) => n.path === abs);\n if (node) return { kind: \"serial\", node };\n const links = nodes.some((n) => n.links.length > 0);\n if (links && (abs === SERIAL || abs === BY_ID)) return { kind: \"dir\", mode: DIR | 493 };\n const owner = nodes.find((n) => n.links.includes(abs));\n if (owner) return { kind: \"devlink\", target: `../..${owner.path.slice(4)}`, node: owner };\n return void 0;\n}\nfunction* deviceNodes() {\n return yield { op: \"fd-dev-nodes\" };\n}\nfunction* lookup(abs) {\n if (abs === \"/dev\") return { kind: \"dir\", mode: DIR | 493 };\n const name2 = abs.slice(\"/dev/\".length);\n if (serialNamed(name2)) {\n const found = serialNode(abs, yield* deviceNodes());\n if (found) return found;\n }\n if (DEVICES.includes(name2)) return { kind: \"device\" };\n if (name2 === \"tty\") return { kind: \"tty\" };\n if (name2 === \"clipboard\") return { kind: \"clipboard\" };\n if (name2 === \"embedder\") return { kind: \"embedder\" };\n if (name2 === \"sealed\") return { kind: \"sealed\" };\n const std = STDIO.indexOf(name2);\n if (std >= 0) return { kind: \"link\", target: `${SELF_FD}/${std}`, fd: std };\n if (name2 === \"fd\") return { kind: \"link\", target: SELF_FD };\n const fd = /^fd\\/(\\d+)$/.exec(name2)?.[1];\n if (fd !== void 0) return { kind: \"fd\", fd: Number(fd) };\n if (/^tty\\d+$/.test(name2)) {\n const names2 = yield { op: \"fd-tty-names\" };\n if (names2.includes(abs)) return { kind: \"terminal\", name: abs };\n }\n if (name2 === \"pts\") return { kind: \"dir\", mode: DIR | 365 };\n const pts = /^pts\\/(\\d+)$/.exec(name2)?.[1];\n if (pts !== void 0) {\n const open = yield { op: \"pty-list\" };\n if (open.includes(Number(pts))) return { kind: \"terminal\", name: abs, pts: Number(pts) };\n }\n return missing(abs);\n}\nfunction* fdInfo(fd, path) {\n try {\n return yield { op: \"fd-info\", fd };\n } catch (err) {\n if (err instanceof JsCallError && err.code === \"EBADF\") return missing(path);\n throw err;\n }\n}\nfunction* pathStat(path) {\n const s = parseSyncFsStat(yield { op: \"stat\", path });\n if (!s) throw new JsCallError(\"EIO\", \"stat\");\n return s;\n}\nfunction* terminalStat(name2) {\n const owner = yield { op: \"fd-tty-owner\", name: name2 };\n if (owner) return nodeStat(CHAR | (owner.mode ?? 400), 0, owner);\n return nodeStat(CHAR | (name2.startsWith(\"/dev/pts/\") ? 400 : 438));\n}\nfunction* fdStat(fd, path) {\n const info = yield* fdInfo(fd, path);\n if (info.meta && \"dir\" in info.meta) return yield* pathStat(info.meta.dir);\n if (info.kind === \"file\") {\n const file = yield { op: \"fd-vfs-stat\", fd };\n if (file.orphan) return { ...nodeStat(33152, file.size), isFile: true };\n const st = yield* pathStat(file.path);\n return { ...st, size: file.size };\n }\n if (info.terminal) return yield* terminalStat(info.terminal);\n if (CHAR_KINDS.has(info.kind)) return nodeStat(CHAR | 438);\n if (info.kind === \"socket\") return nodeStat(49663);\n return nodeStat(4480);\n}\nfunction* fdTarget(fd, path) {\n const info = yield* fdInfo(fd, path);\n if (info.meta && \"dir\" in info.meta) return info.meta.dir;\n if (info.kind === \"file\") return (yield { op: \"fd-vfs-stat\", fd }).path;\n if (info.terminal) return info.terminal;\n if (info.meta && \"device\" in info.meta) return `/dev/${info.meta.device}`;\n if (info.kind === \"clipboard\" || info.kind === \"sealed\" || info.kind === \"embedder\")\n return `/dev/${info.kind}`;\n return `${info.kind === \"socket\" ? \"socket\" : \"pipe\"}:[${fd}]`;\n}\nfunction devFdStat(fd) {\n return fdStat(fd, `/dev/fd/${fd}`);\n}\nfunction serialStat(node) {\n return {\n ...nodeStat(CHAR | node.mode, 0, node),\n atimeMs: node.atimeMs,\n mtimeMs: node.mtimeMs,\n ctimeMs: node.ctimeMs\n };\n}\nfunction linkStat(target) {\n return nodeStat(LINK | 511, target.length);\n}\nfunction* devStat(abs, follow2) {\n const node = yield* lookup(abs);\n switch (node.kind) {\n case \"dir\":\n return nodeStat(node.mode);\n case \"device\":\n case \"tty\":\n case \"clipboard\":\n case \"embedder\":\n case \"sealed\":\n return nodeStat(CHAR | 438);\n case \"terminal\":\n return yield* terminalStat(node.name);\n case \"serial\":\n return serialStat(node.node);\n case \"devlink\":\n return follow2 ? serialStat(node.node) : linkStat(node.target);\n case \"link\":\n if (!follow2) return linkStat(node.target);\n return node.fd === void 0 ? nodeStat(DIR | 365) : yield* fdStat(node.fd, abs);\n case \"fd\":\n return follow2 ? yield* fdStat(node.fd, abs) : linkStat(yield* fdTarget(node.fd, abs));\n }\n}\nfunction* devMeta(abs, follow2, change) {\n if (!abs.startsWith(\"/dev/\") || !serialNamed(abs.slice(5))) return false;\n const found = serialNode(abs, yield* deviceNodes());\n if (found?.kind !== \"serial\" && !(found?.kind === \"devlink\" && follow2)) return false;\n yield { op: \"fd-dev-meta\", path: found.node.path, ...change };\n return true;\n}\nfunction* devReadlink(abs) {\n const node = yield* lookup(abs);\n if (node.kind === \"link\" || node.kind === \"devlink\") return node.target;\n if (node.kind === \"fd\") return yield* fdTarget(node.fd, abs);\n throw new JsCallError(\"EINVAL\", abs);\n}\nfunction* devResolveTarget(abs) {\n const node = yield* lookup(abs);\n if (node.kind === \"fd\") return yield* fdTarget(node.fd, abs);\n if (node.kind === \"link\" && node.fd !== void 0) return yield* fdTarget(node.fd, abs);\n return void 0;\n}\nfunction* devReaddir(abs) {\n if (abs === \"/dev/fd\") {\n const fds = yield { op: \"fd-list\" };\n return fds.map(({ fd }) => String(fd));\n }\n if (abs === \"/dev/pts\") {\n const open = yield { op: \"pty-list\" };\n return open.map(String).sort();\n }\n const node = yield* lookup(abs);\n if (node.kind !== \"dir\") throw new JsCallError(\"ENOTDIR\", abs);\n if (abs === SERIAL || abs === BY_ID) {\n const nodes2 = yield* deviceNodes();\n if (abs === SERIAL) return [\"by-id\"];\n return nodes2.flatMap((n) => n.links.map((l) => l.slice(BY_ID.length + 1))).sort();\n }\n const names2 = yield { op: \"fd-tty-names\" };\n const ttys = names2.filter((n) => /^\\/dev\\/tty\\d+$/.test(n)).map((n) => n.slice(5));\n const nodes = yield* deviceNodes();\n const serial = nodes.map((n) => n.path.slice(5));\n if (nodes.some((n) => n.links.length > 0)) serial.push(\"serial\");\n return [\n ...serial,\n ...DEVICES,\n \"clipboard\",\n \"embedder\",\n \"sealed\",\n \"tty\",\n \"fd\",\n \"pts\",\n \"shm\",\n ...STDIO,\n ...ttys\n ].sort();\n}\nasync function devSync(kernel, step) {\n let next2 = step.next();\n while (!next2.done) {\n let answer;\n try {\n answer = { value: await kernel.json(next2.value) };\n } catch (error) {\n answer = { error };\n }\n next2 = \"value\" in answer ? step.next(answer.value) : step.throw(answer.error);\n }\n return next2.value;\n}\nvar WHEN = {\n now: IOCTL.TCSETS2,\n drain: IOCTL.TCSETSW2,\n flush: IOCTL.TCSETSF2\n};\n\n// src/process/wasi/slicc-lock.ts\nvar F_GETLK = 12;\nvar F_SETLK = 13;\nvar F_SETLKW = 14;\nvar F_RDLCK = 0;\nvar F_WRLCK = 1;\nvar F_UNLCK = 2;\nvar SEEK_SET = 0;\nvar SEEK_CUR = 1;\nvar SEEK_END = 2;\nvar LOCK_NB = 4;\nvar FLOCK_OPS = { 1: \"shared\", 2: \"exclusive\", 8: \"unlock\" };\nfunction kindOf(type) {\n if (type === F_RDLCK) return \"read\";\n if (type === F_WRLCK) return \"write\";\n if (type === F_UNLCK) return \"unlock\";\n throw new WasiError(\"EINVAL\");\n}\nasync function baseOf2(file, whence) {\n if (whence === SEEK_SET) return 0;\n if (whence === SEEK_CUR) return await file.offset();\n if (whence === SEEK_END) return await file.size();\n throw new WasiError(\"EINVAL\");\n}\nfunction writeHolder(view, at, found) {\n if (!found) {\n view.setInt16(at, F_UNLCK, true);\n return;\n }\n view.setInt16(at, found.kind === \"read\" ? F_RDLCK : F_WRLCK, true);\n view.setInt16(at + 2, SEEK_SET, true);\n view.setBigInt64(at + 8, BigInt(found.start), true);\n view.setBigInt64(at + 16, BigInt(found.len), true);\n view.setInt32(at + 24, found.pid, true);\n}\nfunction lockImports(host) {\n return {\n flock: async (fd, op) => {\n await host.promote(fd);\n const kind = FLOCK_OPS[op & ~LOCK_NB];\n if (!kind) throw new WasiError(\"EINVAL\");\n const shared = await host.calls.flock(fd, kind, kind !== \"unlock\" && (op & LOCK_NB) === 0);\n if (kind !== \"unlock\" && shared === true) await host.reread(fd);\n },\n fcntl_lock: async (fd, cmd, at) => {\n if (cmd !== F_GETLK && cmd !== F_SETLK && cmd !== F_SETLKW) throw new WasiError(\"EINVAL\");\n await host.promote(fd, true);\n const file = await host.file(fd);\n const view = host.mem.view();\n const kind = kindOf(view.getInt16(at, true));\n const start2 = await baseOf2(file, view.getInt16(at + 2, true)) + Number(view.getBigInt64(at + 8, true));\n const len = Number(view.getBigInt64(at + 16, true));\n if (cmd === F_GETLK) {\n if (kind === \"unlock\") throw new WasiError(\"EINVAL\");\n writeHolder(view, at, await host.calls.get(file.target, kind, start2, len));\n return;\n }\n if (kind === \"read\" && file.readable === false || kind === \"write\" && file.writable === false)\n throw new WasiError(\"EBADF\");\n if (kind !== \"write\") await host.flush(file);\n const shared = await host.calls.set(file.target, kind, start2, len, cmd === F_SETLKW);\n if (kind === \"unlock\") return;\n host.locked();\n if (shared === true) await host.reread(fd);\n }\n };\n}\n\n// src/process/wasi/slicc-sem.ts\nvar SEM_CREAT = 1;\nvar SEM_EXCL = 2;\nvar HOW = [\"block\", \"try\", \"timed\"];\nvar NS_PER_MS = 1000000n;\nfunction remainingMs(deadline, now) {\n if (deadline <= now) return 0;\n return Number((deadline - now + NS_PER_MS - 1n) / NS_PER_MS);\n}\nfunction semImports(host) {\n const { mem } = host;\n const call2 = async (req) => await host.o.kernel.call(req);\n const name2 = (ptr, len) => mem.string(ptr, len);\n return {\n sem_open: async (np, nl, oflag, mode, value2, out) => {\n const handle = await call2({\n op: \"sem-open\",\n name: name2(np, nl),\n create: (oflag & SEM_CREAT) !== 0,\n exclusive: (oflag & SEM_EXCL) !== 0,\n mode,\n value: value2\n });\n mem.view().setUint32(out, handle, true);\n },\n sem_close: async (handle) => void await call2({ op: \"sem-close\", handle }),\n sem_unlink: async (np, nl) => void await call2({ op: \"sem-unlink\", name: name2(np, nl) }),\n sem_post: async (handle) => void await call2({ op: \"sem-post\", handle }),\n sem_wait: async (handle, how, clock, deadline) => {\n const kind = HOW[how];\n if (!kind) throw new WasiError(\"EINVAL\");\n let timeoutMs2 = -1;\n if (kind === \"timed\") {\n if (deadline < 0n) throw new WasiError(\"EINVAL\");\n if (clock !== CLOCK.REALTIME && clock !== CLOCK.MONOTONIC) throw new WasiError(\"EINVAL\");\n timeoutMs2 = remainingMs(deadline, host.now(clock));\n }\n await call2({ op: \"sem-wait\", handle, how: kind, timeoutMs: timeoutMs2 });\n },\n sem_getvalue: async (handle, out) => void mem.view().setInt32(out, await call2({ op: \"sem-getvalue\", handle }), true)\n };\n}\n\n// src/process/wasi/wasi-cred.ts\nvar CredCache = class {\n cred;\n stamp = 0;\n fetch;\n shared;\n constructor(fetch, shared) {\n this.fetch = fetch;\n this.shared = shared;\n }\n gen() {\n return this.shared ? Atomics.load(this.shared, CRED_GEN) : 0;\n }\n async get() {\n const gen = this.gen();\n if (this.cred === void 0 || this.stamp !== gen) {\n this.cred = await this.fetch();\n this.stamp = gen;\n }\n return this.cred;\n }\n async change(apply2) {\n const seen = this.gen();\n const cred = await apply2();\n if (!this.shared) {\n this.cred = cred;\n return cred;\n }\n const was = Atomics.add(this.shared, CRED_GEN, 1);\n this.cred = was === seen ? cred : void 0;\n this.stamp = was + 1;\n return cred;\n }\n};\nvar KNOWN = 65536;\nvar LOCKED = 131072;\nvar UNGATED = { quiet: async (fn) => await fn(), deliver: () => {\n} };\nvar UmaskCache = class {\n mask;\n call;\n shared;\n signals;\n constructor(call2, shared, signals = UNGATED) {\n this.call = call2;\n this.shared = shared;\n this.signals = signals;\n }\n async get() {\n const { shared } = this;\n if (!shared) {\n this.mask ??= await this.call();\n return this.mask;\n }\n for (; ; ) {\n const seen = Atomics.load(shared, UMASK);\n if (seen & LOCKED) await atomicsWait(shared, UMASK, seen);\n else if (seen & KNOWN) return seen & 511;\n else {\n const mask = await this.call();\n if (Atomics.compareExchange(shared, UMASK, 0, mask | KNOWN) === 0) return mask;\n }\n }\n }\n async set(mask) {\n try {\n return await this.signals.quiet(async () => await this.change(mask));\n } finally {\n await this.signals.deliver();\n }\n }\n async change(mask) {\n const { shared } = this;\n if (!shared) {\n const old = await this.call(mask);\n this.mask = mask & 511;\n return old;\n }\n const seen = await this.lock(shared);\n let next2 = seen;\n try {\n const old = await this.call(mask);\n next2 = mask & 511 | KNOWN;\n return old;\n } finally {\n Atomics.store(shared, UMASK, next2);\n atomicsNotify(shared, UMASK);\n }\n }\n async lock(shared) {\n for (; ; ) {\n const seen = Atomics.load(shared, UMASK);\n if (seen & LOCKED) await atomicsWait(shared, UMASK, seen);\n else if (Atomics.compareExchange(shared, UMASK, seen, seen | LOCKED) === seen) return seen;\n }\n }\n};\n\n// src/process/wasi/wasi-fds.ts\nvar SYNTHETIC_DIRS = [\"usr\", \"bin\"];\nvar O_NONBLOCK2 = 2048;\nvar O_WRONLY = 1;\nvar O_RDWR = 2;\nvar O_APPEND = 1024;\nfunction stdioAlias(path) {\n const m = /^\\/dev\\/(?:(stdin)|(stdout)|(stderr)|fd\\/(\\d+))$/.exec(path);\n if (!m) return void 0;\n return m[1] ? 0 : m[2] ? 1 : m[3] ? 2 : Number(m[4]);\n}\nvar DEVICE_PATH = /^\\/dev\\/tty(?:USB|ACM)\\d+$/;\nvar SEALED_PATH = \"/dev/sealed\";\nvar CLIPBOARD_PATH = \"/dev/clipboard\";\nvar EMBEDDER_PATH = \"/dev/embedder\";\nfunction deviceOf(path) {\n return deviceAt(path);\n}\nvar NAMED_PATHS = /* @__PURE__ */ new Set([\n SEALED_PATH,\n CLIPBOARD_PATH,\n EMBEDDER_PATH,\n \"/dev/tty\"\n]);\nfunction namedDevice(path) {\n if (deviceOf(path) || stdioAlias(path) !== void 0) return true;\n return NAMED_PATHS.has(path);\n}\nfunction within(path, root) {\n return path === root || path.startsWith(root === \"/\" ? \"/\" : `${root}/`);\n}\nvar WasiFds = class {\n table = /* @__PURE__ */ new Map();\n buffers = /* @__PURE__ */ new Map();\n reported = /* @__PURE__ */ new WeakSet();\n byId = /* @__PURE__ */ new Map();\n ids = /* @__PURE__ */ new Map();\n kernel;\n fs;\n renamesSeen;\n constructor(kernel, fs) {\n this.kernel = kernel;\n this.fs = fs;\n this.renamesSeen = fs.changes?.renames() ?? 0;\n }\n ownRename(seq) {\n if (seq !== void 0 && seq === (this.renamesSeen + 1 | 0)) this.renamesSeen = seq;\n }\n async followRenames(missing3 = false) {\n const view = this.fs.changes;\n const end = missing3 && view ? performance.now() + renameWait(view) : 0;\n const start2 = this.renamesSeen;\n for (; ; ) {\n const now = view?.renames() ?? 0;\n if (now !== this.renamesSeen && this.fs.renames && await this.followTo(now)) return true;\n if (missing3 && this.renamesSeen !== start2) return true;\n const left = end - performance.now();\n if (!view || left <= 0) return false;\n await view.awaitRename(now, left);\n }\n }\n async followTo(now) {\n const held = [...this.buffers].filter(([, b]) => !b.isOrphan()).map(([p]) => p);\n if (held.length === 0) {\n this.renamesSeen = now;\n return false;\n }\n const { now: seen, renames } = await this.fs.renames(\n this.renamesSeen,\n held\n );\n this.renamesSeen = seen;\n for (const [from, to] of renames) await this.renamed(from, to, void 0, true);\n return renames.length > 0;\n }\n async setup(cwd, inherited2, root = false) {\n for (const fd of [0, 1, 2]) this.table.set(fd, await this.stdioEntry(fd));\n const preopens = await this.preopens(cwd, root);\n const top = 3 + preopens.length;\n for (const { fd, kind, flags, device } of inherited2) {\n let at = fd;\n if (fd < top) {\n at = await this.kernel.call({ op: \"fd-dup\", fd, min: top });\n await this.kernel.sys.close(fd);\n }\n if (device) {\n this.table.set(at, deviceEntry(device));\n continue;\n }\n const nonblock = ((flags ?? 0) & O_NONBLOCK2) !== 0;\n this.table.set(at, { ...kernelEntry(), nonblock, ...kind ? { kind } : {} });\n }\n for (const [i, entry] of preopens.entries()) {\n await this.kernel.call({ op: \"fd-reserve\", fd: 3 + i, meta: metaOf(entry) });\n this.table.set(3 + i, entry);\n }\n }\n async adoptCopy(fd) {\n const at = await this.kernel.call({ op: \"fd-dup\", fd, min: 3 });\n this.table.set(at, await this.stdioEntry(at));\n return at;\n }\n async preopenAt(path, name2) {\n return await this.install({ type: \"dir\", path: normalize(path), preopen: name2 });\n }\n async preopens(cwd, root) {\n const here = normalize(cwd);\n const dot = { type: \"dir\", path: here, preopen: \".\" };\n const out = [dot];\n let names2 = [];\n try {\n names2 = await this.fs.readdir(\"/\");\n } catch {\n return out;\n }\n for (const name2 of [.../* @__PURE__ */ new Set([...names2, \"dev\", ...SYNTHETIC_DIRS])].sort()) {\n const path = `/${name2}`;\n if (path === \"/dev\") {\n out.push({ type: \"dir\", path, preopen: path });\n continue;\n }\n try {\n if ((await this.fs.stat(path)).isDirectory) out.push({ type: \"dir\", path, preopen: path });\n } catch {\n }\n }\n if (root) {\n out.push(\n { type: \"dir\", path: \"/\", preopen: \"/\" },\n { type: \"dir\", path: here, preopen: \"./\" }\n );\n dot.twin = 3 + out.length - 1;\n }\n return out;\n }\n async find(fd) {\n if (!this.shared) return this.table.get(fd);\n this.sync();\n return this.table.get(fd) ?? await this.fetch(fd);\n }\n shared;\n seen = 0;\n get isShared() {\n return this.shared !== void 0;\n }\n async share(ids, fresh) {\n if (!fresh) {\n await this.promoteFiles();\n for (const fd of this.cloexec) await this.kernel.call({ op: \"fd-cloexec\", fd, on: true });\n for (const [fd, e] of this.table) {\n if (e.type === \"kernel\" && (e.nonblock || e.append)) await this.publishFlags(fd, e);\n }\n } else {\n this.table.clear();\n this.cloexec.clear();\n }\n this.shared = ids;\n this.fs.threaded?.();\n this.seen = Atomics.load(ids, GEN2);\n }\n sync() {\n const shared = this.shared;\n const gen = Atomics.load(shared, GEN2);\n if (gen === this.seen) return;\n if (!this.replay(shared, gen)) {\n this.table.clear();\n this.cloexec.clear();\n }\n this.seen = gen;\n }\n replay(shared, upTo) {\n if (upTo - this.seen > FD_RING_SIZE || !ringed(shared)) return false;\n const changed2 = [];\n for (let g = this.seen + 1; g <= upTo; g++) {\n const at = FD_RING + g % FD_RING_SIZE * 2;\n if (Atomics.load(shared, at) !== g) return false;\n const fd = Atomics.load(shared, at + 1);\n if (fd < 0 || Atomics.load(shared, at) !== g) return false;\n changed2.push(fd);\n }\n for (const fd of changed2) {\n this.table.delete(fd);\n this.cloexec.delete(fd);\n }\n return true;\n }\n bump(...fds) {\n if (!this.shared) return;\n const shared = this.shared;\n for (const fd of fds.length > 0 ? fds : [-1]) {\n const gen = Atomics.add(shared, GEN2, 1) + 1;\n if (ringed(shared)) {\n const at = FD_RING + gen % FD_RING_SIZE * 2;\n Atomics.store(shared, at, 0);\n Atomics.store(shared, at + 1, fd);\n Atomics.store(shared, at, gen);\n }\n if (gen - 1 === this.seen) this.seen = gen;\n }\n }\n async stdioEntry(fd) {\n let info;\n try {\n info = await this.kernel.call({ op: \"fd-info\", fd });\n } catch {\n return kernelEntry();\n }\n return info?.meta && \"dir\" in info.meta ? { type: \"dir\", path: info.meta.dir } : kernelEntry();\n }\n async fetch(fd) {\n let info;\n try {\n info = await this.kernel.call({ op: \"fd-info\", fd });\n } catch {\n return void 0;\n }\n const e = entryOf(info);\n if (!e) return void 0;\n this.table.set(fd, e);\n if (info.cloexec) this.cloexec.add(fd);\n return e;\n }\n async listed() {\n const out = [];\n for (const info of await this.kernel.call({ op: \"fd-list\" })) {\n const e = entryOf(info);\n if (e) out.push([info.fd, e, info.cloexec === true]);\n }\n return out;\n }\n async publishFlags(fd, e) {\n const flags = (e.nonblock ? O_NONBLOCK2 : 0) | (e.append ? O_APPEND : 0);\n await this.kernel.call({ op: \"fd-setfl\", fd, flags });\n }\n async setFlags(fd, nonblock, append) {\n const e = await this.get(fd);\n if (e.type === \"kernel\") {\n e.nonblock = nonblock;\n e.append = append;\n if (this.shared) {\n await this.publishFlags(fd, e);\n this.bump(fd);\n }\n } else if (e.type === \"file\") e.file.append = append;\n }\n async setCloexec(fd, on) {\n await this.get(fd);\n if (on) this.cloexec.add(fd);\n else this.cloexec.delete(fd);\n if (this.shared) {\n await this.kernel.call({ op: \"fd-cloexec\", fd, on });\n this.bump(fd);\n }\n }\n async cwd() {\n const dot = await this.find(3);\n return dot?.type === \"dir\" && dot.preopen === \".\" ? dot.path : void 0;\n }\n async terminals() {\n const fds = this.shared ? (await this.kernel.call({ op: \"fd-list\" })).filter((info) => info.tty).map((info) => info.fd) : [...this.table].filter(([, e]) => e.type === \"kernel\" && e.kind === \"tty\").map(([fd]) => fd);\n return fds.sort((a, b) => a - b);\n }\n sockets() {\n return [...this.table].filter(([, e]) => e.type === \"kernel\" && e.kind === \"socket\").map(([fd]) => fd).sort((a, b) => a - b);\n }\n async adopt(fd, kind, nonblock, dgram = false) {\n this.table.set(fd, { type: \"kernel\", kind, dgram, nonblock, append: false });\n if (this.shared && nonblock) await this.publishFlags(fd, { nonblock, append: false });\n this.bump(fd);\n }\n async get(fd) {\n const e = await this.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type === \"file\") await this.followRenames();\n return e;\n }\n async preopen(fd) {\n const e = await this.find(fd);\n if (e?.type !== \"dir\" || e.preopen === void 0) throw new WasiError(\"EBADF\");\n return e;\n }\n async dir(fd) {\n const e = await this.get(fd);\n if (e.type !== \"dir\") throw new WasiError(\"ENOTDIR\");\n return e;\n }\n async install(e, min = 3) {\n const meta = metaOf(e);\n const fd = await this.kernel.call({\n op: \"fd-reserve\",\n ...min > 3 ? { min } : {},\n ...meta ? { meta } : {}\n });\n this.table.set(fd, e);\n this.bump(fd);\n return fd;\n }\n cloexec = /* @__PURE__ */ new Set();\n implicitCloexec = false;\n async dup(fd, min, cloexec) {\n const e = await this.get(fd);\n let at;\n if (e.type !== \"file\") {\n at = await this.kernel.call({ op: \"fd-dup\", fd, min: Math.max(3, min) });\n this.table.set(at, { ...e });\n } else {\n e.file.refs++;\n at = await this.install(e, min);\n }\n if (cloexec) await this.setCloexec(at, true);\n this.bump(at);\n return at;\n }\n async pipe() {\n const [r, w] = await this.kernel.sys.pipe();\n this.table.set(r, { type: \"kernel\", kind: \"stream\", nonblock: false, append: false });\n this.table.set(w, { type: \"kernel\", kind: \"stream\", nonblock: false, append: false });\n this.bump(r, w);\n return [r, w];\n }\n async chdir(path) {\n const dot = await this.find(3);\n if (dot?.type !== \"dir\" || dot.preopen !== \".\") return;\n const moved = [[3, dot]];\n const twin = dot.twin === void 0 ? void 0 : await this.find(dot.twin);\n if (twin?.type === \"dir\" && twin.preopen === \"./\") moved.push([dot.twin, twin]);\n for (const [fd, e] of moved) {\n e.path = path;\n await this.kernel.call({ op: \"fd-meta\", fd, meta: metaOf(e) });\n }\n this.held?.moved(await this.kernel.call({ op: \"cwd-chdir\", path }), path);\n this.bump();\n }\n async promote(fd, moved = false) {\n const e = await this.get(fd);\n if (e.type === \"file\" && (!moved || await this.moved(fd))) await this.promoteFiles(e.file.buffer);\n }\n async promoteFiles(only) {\n const promoted = /* @__PURE__ */ new Map();\n const handed = /* @__PURE__ */ new Set();\n for (const [fd, e] of [...this.table]) {\n if (e.type !== \"file\" || only && e.file.buffer !== only) continue;\n const first = promoted.get(e.file);\n if (first !== void 0) {\n await this.kernel.call({ op: \"fd-promote\", fd, share: first });\n } else {\n await this.kernel.call(await promoteRequest(fd, e.file, handed));\n handed.add(e.file.buffer);\n promoted.set(e.file, fd);\n }\n this.table.set(fd, {\n type: \"kernel\",\n kind: \"file\",\n nonblock: false,\n append: e.file.append,\n path: e.file.path,\n ino: await this.inoOf(e.file.path)\n });\n }\n for (const file of promoted.keys()) {\n if (--file.buffer.opens <= 0) {\n this.forget(file.buffer);\n await this.letGo(file.buffer);\n }\n }\n }\n snapshot() {\n const out = [];\n if (this.shared) return out;\n for (const [fd, e] of this.table) {\n if (e.type === \"kernel\")\n out.push({ fd, type: \"kernel\", nonblock: e.nonblock, append: e.append });\n else if (e.type === \"dir\") out.push({ fd, type: \"dir\", path: e.path, ...preopenOf(e) });\n else if (e.type === \"device\") out.push({ fd, ...deviceEntry(e) });\n }\n return out;\n }\n restore(fds, cloexec) {\n this.table.clear();\n for (const f of fds) {\n if (f.type === \"kernel\")\n this.table.set(f.fd, { type: \"kernel\", nonblock: f.nonblock, append: f.append });\n else if (f.type === \"dir\")\n this.table.set(f.fd, { type: \"dir\", path: f.path, ...preopenOf(f) });\n else this.table.set(f.fd, deviceEntry(f));\n }\n for (const fd of cloexec) this.cloexec.add(fd);\n }\n async inheritable() {\n const out = /* @__PURE__ */ new Map();\n const all = this.shared ? await this.listed() : [...this.table].map(([fd, e]) => [\n fd,\n e,\n this.cloexec.has(fd)\n ]);\n for (const [fd, e, cloexec] of all) {\n if (e.type !== \"kernel\" || cloexec) continue;\n if (this.implicitCloexec && fd > 2) continue;\n out.set(fd, fd);\n }\n return out;\n }\n locking = false;\n holdLocks() {\n this.locking = true;\n }\n async dropLocks(e) {\n if (!this.locking || e?.type !== \"file\") return;\n try {\n await this.kernel.call({ op: \"lk-close\", path: e.file.path });\n } catch {\n }\n }\n async close(fd) {\n const e = await this.get(fd);\n this.table.delete(fd);\n this.cloexec.delete(fd);\n try {\n await this.kernel.sys.close(fd);\n } finally {\n await this.release(e);\n await this.dropLocks(e);\n this.bump(fd);\n }\n }\n async renumber(from, to, keep = false) {\n const e = await this.get(from);\n const old = keep ? await this.find(to) : await this.get(to);\n if (from === to) return;\n await this.kernel.call({ op: \"fd-renumber\", from, to, ...keep ? { keep } : {} });\n this.cloexec.delete(to);\n if (keep) {\n if (e.type === \"file\") e.file.refs++;\n this.table.set(to, e.type === \"file\" ? e : { ...e });\n } else {\n this.table.delete(from);\n this.table.set(to, e);\n if (this.cloexec.delete(from)) this.cloexec.add(to);\n }\n if (old) await this.release(old);\n await this.dropLocks(old);\n this.bump(from, to);\n }\n async release(e) {\n if (e.type !== \"file\" || --e.file.refs > 0) return;\n const { buffer } = e.file;\n try {\n await buffer.flush();\n this.reported.delete(buffer);\n } catch (err) {\n this.reported.add(buffer);\n await this.drop(buffer);\n throw err;\n }\n await this.drop(buffer);\n }\n async drop(buffer) {\n if (--buffer.opens > 0) return;\n this.forget(buffer);\n await this.letGo(buffer);\n }\n forget(buffer) {\n for (const [p, b] of [...this.buffers]) if (b === buffer) this.buffers.delete(p);\n const id = this.ids.get(buffer);\n if (id !== void 0 && this.byId.get(id) === buffer) this.byId.delete(id);\n this.ids.delete(buffer);\n }\n know(buffer, id) {\n if (this.ids.has(buffer)) return;\n this.ids.set(buffer, id);\n if (!this.byId.has(id)) this.byId.set(id, buffer);\n }\n identity(st) {\n if (!st || st.ino === void 0 || (st.nlink ?? 1) < 2) return void 0;\n return `${st.dev ?? 0}:${st.ino}`;\n }\n async sharing(path, st) {\n if (st?.ino === void 0) return void 0;\n const id = `${st.dev ?? 0}:${st.ino}`;\n if (!this.byId.has(id) && this.identity(st) !== void 0) await this.learn();\n const buffer = this.byId.get(id);\n if (!buffer) return void 0;\n this.buffers.set(path, buffer);\n return buffer;\n }\n async learn() {\n for (const [p, buffer] of this.buffers) {\n if (this.ids.has(buffer) || buffer.isOrphan()) continue;\n const known = this.identity(await this.statOrMissing(p));\n if (known !== void 0) this.know(buffer, known);\n }\n }\n async linked(from, to) {\n const buffer = this.buffers.get(from);\n if (!buffer || buffer.isOrphan()) return;\n const id = this.identity(await this.statOrMissing(to));\n if (id === void 0) return;\n this.know(buffer, id);\n if (!this.buffers.has(to)) this.buffers.set(to, buffer);\n }\n async letGo(buffer) {\n await this.fs.hold?.(buffer.path, false, true, buffer.handle);\n }\n async kind(fd, e) {\n if (!e.kind) {\n const info = await this.kernel.call({ op: \"fd-info\", fd });\n e.kind = info.kind ?? (info.tty ? \"tty\" : \"stream\");\n e.dgram = info.dgram === true;\n }\n return e.kind;\n }\n async datagram(fd, e) {\n if (await this.kind(fd, e) !== \"socket\") return false;\n if (e.dgram === void 0) {\n e.dgram = (await this.kernel.call({ op: \"fd-info\", fd })).dgram === true;\n }\n return e.dgram;\n }\n async flushAll() {\n for (const buffer of this.buffers.values()) {\n try {\n await buffer.flush();\n this.reported.delete(buffer);\n } catch (err) {\n if (!this.reported.has(buffer)) throw err;\n }\n }\n }\n async synced(file) {\n try {\n await file.flush();\n await this.kernel.call({ op: \"fd-path-flush\", path: file.buffer.path, durable: true });\n this.reported.delete(file.buffer);\n } catch (err) {\n this.reported.add(file.buffer);\n throw err;\n }\n }\n async flushEarly() {\n for (const buffer of this.buffers.values()) {\n try {\n await buffer.flush();\n } catch {\n }\n }\n }\n async reread(fd) {\n const e = await this.get(fd);\n if (e.type === \"file\") await e.file.buffer.reread();\n }\n async flushPath(path) {\n for (const [p, buffer] of this.buffers) if (within(p, path)) await buffer.flush();\n if (this.shared && !this.fs.changes?.clean()) await this.kernel.call({ op: \"fd-path-flush\", path });\n }\n holdsUnder(path) {\n for (const p of this.buffers.keys()) if (within(p, path)) return true;\n return false;\n }\n async replacing(path) {\n for (const [p, buffer] of this.buffers) {\n if (!within(p, path)) continue;\n try {\n await buffer.prefetch();\n } catch {\n buffer.spoil();\n }\n }\n }\n async unlinking(path, linked) {\n const buffer = this.buffers.get(path);\n if (buffer && this.survives(buffer, linked)) await buffer.flush();\n else await buffer?.keep();\n if (this.shared) await this.kernel.call({ op: \"fd-path-unlinking\", path });\n }\n async unlinked(path, linked) {\n if (this.shared) await this.kernel.call({ op: \"fd-path-unlinked\", path });\n const buffer = this.buffers.get(path);\n if (!buffer) return;\n await this.detach(buffer, linked);\n this.buffers.delete(path);\n }\n async openedIno(fd) {\n try {\n return (await this.kernel.call({ op: \"fd-vfs-stat\", fd, identity: true })).ino;\n } catch (err) {\n await this.kernel.sys.close(fd);\n throw err;\n }\n }\n async moved(fd) {\n const e = await this.get(fd);\n if (e.type !== \"file\") return false;\n if (e.file.buffer.isOrphan()) return true;\n return e.file.ino !== void 0 && await this.inoOf(e.file.path) !== e.file.ino;\n }\n async inoOf(path) {\n try {\n return (await this.fs.stat(path)).ino;\n } catch {\n return void 0;\n }\n }\n survives(buffer, linked) {\n return linked !== void 0 && buffer.handle !== void 0;\n }\n async detach(buffer, linked) {\n if (this.survives(buffer, linked)) {\n const id = this.identity(linked);\n if (id !== void 0) this.know(buffer, id);\n return;\n }\n await buffer.orphan();\n this.forget(buffer);\n }\n async renamed(from, to, replacedLinked, foreign = false) {\n if (from === to) return;\n if (this.shared && !foreign) await this.kernel.call({ op: \"fd-path-renamed\", from, to });\n for (const e of this.table.values()) {\n if (e.type === \"kernel\" && e.path !== void 0 && within(e.path, from)) {\n e.path = to + e.path.slice(from.length);\n }\n }\n const moved = [];\n for (const [p, buffer] of this.buffers) {\n if (foreign && buffer.isOrphan()) continue;\n if (within(p, from)) moved.push([p, buffer]);\n else if (within(p, to)) {\n await this.detach(buffer, replacedLinked);\n this.buffers.delete(p);\n }\n }\n for (const [p] of moved) this.buffers.delete(p);\n for (const [p, buffer] of moved) {\n const next2 = to + p.slice(from.length);\n if (buffer.path === p) buffer.path = next2;\n this.buffers.set(next2, buffer);\n }\n }\n held;\n cwdEntry(dir) {\n return dir.preopen === \".\" || dir.preopen === \"./\";\n }\n async goneCwd(dir) {\n return this.held !== void 0 && this.cwdEntry(dir) && !await this.held.alive(dir.path);\n }\n async resolve(dirfd, path) {\n if (path === \"\") throw new WasiError(\"ENOENT\");\n if (path.startsWith(\"/\")) return await this.joined(path);\n const dir = await this.dir(dirfd);\n if (path.split(\"/\")[0] !== \"..\" && await this.goneCwd(dir)) throw new WasiError(\"ENOENT\");\n return await this.joined(`${dir.path}/${path}`);\n }\n async joined(joined2) {\n return joined2.split(\"/\").includes(\"..\") ? await physical(this.fs, joined2) : normalize(joined2);\n }\n async openKernelDevice(path, oflags, fdflags, rights) {\n const { openSealed, openClipboard, openEmbedder, openTty } = this.kernel.sys;\n const nonblock = (fdflags & FDFLAGS.NONBLOCK) !== 0;\n let fd;\n let kind;\n if (path === SEALED_PATH && openSealed) {\n fd = await this.openCharDevice(openSealed, oflags, rights);\n kind = \"sealed\";\n } else if (path === CLIPBOARD_PATH && openClipboard) {\n fd = await this.openCharDevice(openClipboard, oflags, rights);\n kind = \"clipboard\";\n } else if (path === EMBEDDER_PATH && openEmbedder) {\n fd = await this.openCharDevice(openEmbedder, oflags, rights);\n kind = \"embedder\";\n } else if (path === \"/dev/tty\" || /^\\/dev\\/tty\\d+$/.test(path)) {\n const exclusive = (oflags & OFLAGS.CREAT) !== 0 && (oflags & OFLAGS.EXCL) !== 0;\n try {\n fd = await openTty?.call(this.kernel.sys, path === \"/dev/tty\" ? void 0 : path);\n } catch (err) {\n if (exclusive && err.code === \"EACCES\")\n throw new WasiError(\"EEXIST\");\n throw err;\n }\n if (fd === void 0) throw new WasiError(\"ENXIO\");\n if (exclusive) {\n await this.kernel.sys.close(fd);\n throw new WasiError(\"EEXIST\");\n }\n kind = \"tty\";\n } else return void 0;\n await this.adopt(fd, kind, nonblock);\n return fd;\n }\n async openSerial(path, oflags, fdflags, rights) {\n const { openDev } = this.kernel.sys;\n const linked = path.startsWith(`${BY_ID}/`);\n if (!openDev || !(linked || DEVICE_PATH.test(path))) return void 0;\n if (this.nofollow && linked) throw new WasiError(\"ELOOP\");\n const fd = await this.openCharDevice(\n async (flags) => await openDev.call(this.kernel.sys, path, flags),\n oflags,\n rights\n );\n await this.adopt(fd, \"tty\", (fdflags & FDFLAGS.NONBLOCK) !== 0);\n return fd;\n }\n async openCharDevice(openDevice, oflags, rights) {\n if (oflags & OFLAGS.DIRECTORY) throw new WasiError(\"ENOTDIR\");\n if (oflags & OFLAGS.CREAT && oflags & OFLAGS.EXCL) throw new WasiError(\"EEXIST\");\n const want = wantOf(oflags, rights);\n const flags = want === 6 ? O_RDWR : want === 2 ? O_WRONLY : 0;\n return await openDevice.call(this.kernel.sys, flags);\n }\n async open(path, oflags, rights, fdflags, mode, nofollow = false) {\n this.made = void 0;\n this.created = false;\n this.nofollow = nofollow;\n const exclusive = (oflags & OFLAGS.CREAT) !== 0 && (oflags & OFLAGS.EXCL) !== 0;\n const special = await this.openSpecial(path, oflags, rights, fdflags, exclusive);\n if (special !== void 0) return special;\n const outside = await this.escaped(path, oflags, rights);\n if (outside !== void 0) return await this.open(outside, oflags, rights, fdflags, mode);\n if (exclusive && !(oflags & OFLAGS.DIRECTORY) && await this.madeAtOnce(path, mode)) {\n return await this.regular(path, void 0, oflags, rights, fdflags, mode, true);\n }\n if (exclusive && !nofollow && await this.isLink(path)) throw new WasiError(\"EEXIST\");\n const s = nofollow ? await this.lstatOrMissing(path) : await this.statOrMissing(path);\n if (s?.isSymbolicLink) throw new WasiError(exclusive ? \"EEXIST\" : \"ELOOP\");\n if (exclusive && s) throw new WasiError(\"EEXIST\");\n if (s?.escape !== void 0) {\n refuseWrite({ readonly: true }, oflags, rights);\n return await this.open(s.escape, oflags, rights, fdflags, mode);\n }\n if (oflags & OFLAGS.DIRECTORY && !s?.isDirectory) {\n throw new WasiError(s ? \"ENOTDIR\" : \"ENOENT\");\n }\n if (s?.isDirectory) {\n const asked = (oflags & OFLAGS.DIRECTORY) === 0 && (rights & RIGHTS.FD_WRITE) !== 0n;\n if (asked || (oflags & (OFLAGS.CREAT | OFLAGS.TRUNC)) !== 0) throw new WasiError(\"EISDIR\");\n return await this.install({ type: \"dir\", path });\n }\n if (!s && !(oflags & OFLAGS.CREAT)) throw new WasiError(\"ENOENT\");\n refuseWrite(s, oflags, rights);\n return await this.regular(path, s, oflags, rights, fdflags, mode);\n }\n nofollow = false;\n inos = /* @__PURE__ */ new WeakMap();\n otherFile(buffer, st) {\n const ino = this.inos.get(buffer);\n return ino !== void 0 && st?.ino !== void 0 && ino !== st.ino;\n }\n async openSpecial(path, oflags, rights, fdflags, exclusive) {\n if (exclusive && namedDevice(path)) throw new WasiError(\"EEXIST\");\n const device = deviceOf(path);\n if (device) return await this.install({ type: \"device\", device });\n const serial = await this.openSerial(path, oflags, fdflags, rights);\n if (serial !== void 0) return serial;\n const kernelDevice = await this.openKernelDevice(path, oflags, fdflags, rights);\n if (kernelDevice !== void 0) return kernelDevice;\n const alias = stdioAlias(path);\n if (alias === void 0) return void 0;\n if (this.nofollow) throw new WasiError(\"ELOOP\");\n return await this.reopen(alias);\n }\n async escaped(path, oflags, rights) {\n const outside = await this.fs.escape?.(path);\n if (outside === void 0) return void 0;\n refuseWrite({ readonly: true }, oflags | (oflags & OFLAGS.CREAT ? OFLAGS.TRUNC : 0), rights);\n return outside;\n }\n async regular(path, s, oflags, rights, fdflags, mode, created = false) {\n if (s?.isFifo) return await this.kernelFifo(path, s, oflags, rights, fdflags);\n if (s?.isSocket) throw new WasiError(\"ENXIO\");\n if (this.shared || await this.kernelHolds(path, s)) {\n return await this.kernelFile(path, s, oflags, rights, fdflags, mode, created);\n }\n return await this.install({\n type: \"file\",\n file: await this.file(path, s, oflags, rights, fdflags, mode, created)\n });\n }\n async kernelHolds(path, st) {\n for (const [fd, e] of this.table) {\n if (e.type !== \"kernel\" || await this.kind(fd, e) !== \"file\") continue;\n await this.named(fd, e);\n if (e.path === path || st?.ino !== void 0 && e.ino === st.ino) return true;\n }\n return false;\n }\n learned = /* @__PURE__ */ new WeakSet();\n async named(fd, e) {\n if (e.path !== void 0 || this.learned.has(e)) return;\n this.learned.add(e);\n try {\n const vfs = await this.kernel.call({ op: \"fd-vfs-stat\", fd, identity: true });\n if (vfs.orphan || vfs.path === void 0) return;\n e.path = vfs.path;\n e.ino = vfs.ino ?? await this.inoOf(vfs.path);\n } catch {\n }\n }\n async file(path, existing, oflags, rights, fdflags, mode, created = false) {\n const { readable, writable } = openAccess(existing, oflags, rights);\n await this.followRenames();\n let buffer = created ? void 0 : this.buffers.get(path);\n if (buffer?.handle !== void 0 && await this.fs.kept?.(buffer.handle)) {\n this.buffers.delete(path);\n buffer = void 0;\n }\n buffer ??= await this.sharing(path, existing);\n if (buffer && this.nofollow && this.otherFile(buffer, existing)) buffer = void 0;\n const want = wantOf(oflags, rights);\n if (buffer) {\n if (this.fs.owners) await this.fs.access?.(path, want, \"open\");\n if (oflags & OFLAGS.TRUNC) await buffer.truncate(0);\n } else {\n buffer = await this.freshBuffer(path, existing, oflags, want, mode, created);\n }\n buffer.opens++;\n const file = new LocalFile(buffer, readable, writable, (fdflags & FDFLAGS.APPEND) !== 0);\n file.ino = existing?.ino;\n return file;\n }\n async freshBuffer(path, existing, oflags, want, mode, created = false) {\n const made = created || !existing && await this.createNew(path, oflags, mode);\n const reply = made ? this.made : void 0;\n this.made = void 0;\n const empty = made || (oflags & OFLAGS.TRUNC) !== 0;\n if (existing?.ranged) this.fs.invalidate?.();\n const seen = reply ? reply.seen : this.fs.changes?.now();\n const st = reply?.st ?? (existing?.ranged || !existing ? await this.fs.stat(path) : existing);\n const ranged = st.ranged ? st.size : void 0;\n const asked = (want & 4 ? HOLD_READ : 0) | (want & 2 ? HOLD_WRITE : 0) | (made ? HOLD_CREATED : 0);\n const asking = this.fs.owners ? asked : asked & HOLD_WRITE;\n const handle = await this.fs.hold?.(path, true, true, void 0, asking, {\n gen: st.gen,\n ...this.nofollow ? { nofollow: true } : {},\n ...st.ino !== void 0 ? { ino: st.ino } : {}\n });\n const io = handle !== void 0 && this.fs.pinned ? await this.fs.pinned(handle) : this.fs;\n const view = this.fs.changes;\n const watch = view && linkedWatch(\n {\n view,\n ino: st.ino,\n seen,\n stat: async (at) => {\n this.fs.invalidate?.();\n return await this.fs.stat(at);\n },\n real: async () => await realOf(this.fs, path)\n },\n st\n );\n const buffer = await new FileBuffer(io, path, empty, st.maxFile, ranged, st.version, watch).emptied(\n empty\n );\n buffer.moved = async (missing3) => await this.followRenames(missing3);\n buffer.bound = st;\n buffer.handle = handle;\n if (handle !== void 0) buffer.real = await this.fs.heldReal?.(handle);\n if (st.ino !== void 0) this.inos.set(buffer, st.ino);\n this.buffers.set(path, buffer);\n const id = this.identity(st);\n if (id !== void 0) this.know(buffer, id);\n return buffer;\n }\n async kernelFile(path, existing, oflags, rights, fdflags, mode, created = false) {\n const { readable, writable } = openAccess(existing, oflags, rights);\n const append = (fdflags & FDFLAGS.APPEND) !== 0;\n const flags = (writable ? readable ? O_RDWR : O_WRONLY : 0) | (append ? O_APPEND : 0);\n const made = created || !existing && await this.createNew(path, oflags, mode);\n const truncate = made || (oflags & OFLAGS.TRUNC) !== 0;\n const fd = await this.kernel.sys.openVfs(path, flags, 0, {\n ...truncate ? { truncate } : {},\n ...made ? { created: true } : {},\n ...this.nofollow && !made ? { nofollow: true } : {}\n });\n const ino = writable ? await this.openedIno(fd) ?? await this.inoOf(path) : void 0;\n if (truncate) this.fs.touched?.(path, ino);\n this.table.set(fd, { type: \"kernel\", kind: \"file\", nonblock: false, append, path, ino });\n if (append) await this.publishFlags(fd, { nonblock: false, append });\n this.bump(fd);\n return fd;\n }\n async kernelFifo(path, existing, oflags, rights, fdflags) {\n const { readable, writable } = openAccess(existing, oflags, rights);\n const nonblock = (fdflags & FDFLAGS.NONBLOCK) !== 0;\n const access3 = writable ? readable ? O_RDWR : O_WRONLY : 0;\n const fd = await this.restarting(\n async () => await this.kernel.sys.openVfs(path, access3 | (nonblock ? O_NONBLOCK2 : 0), 0, { fifo: true })\n );\n this.table.set(fd, { type: \"kernel\", kind: \"stream\", nonblock, append: false });\n if (nonblock) await this.publishFlags(fd, { nonblock, append: false });\n this.bump(fd);\n return fd;\n }\n restartable;\n async restarting(call2) {\n for (; ; ) {\n try {\n return await call2();\n } catch (err) {\n if (err.code !== \"EINTR\" || !this.restartable?.()) throw err;\n }\n }\n }\n created = false;\n made;\n async creating(path, mode) {\n const st = await this.fs.create?.(path, mode, true);\n this.made = st ? { st, seen: st.seen } : void 0;\n this.created = true;\n }\n async madeAtOnce(path, mode) {\n if (!this.fs.create) return false;\n try {\n await this.creating(path, mode);\n return true;\n } catch (err) {\n if (err.code === \"EEXIST\") throw err;\n return false;\n }\n }\n async createNew(path, oflags, mode) {\n if (!this.fs.create) {\n await this.fs.writeFile(path, new Uint8Array(0));\n this.created = true;\n return true;\n }\n try {\n await this.creating(path, mode);\n return true;\n } catch (err) {\n if (oflags & OFLAGS.EXCL || err.code !== \"EEXIST\") throw err;\n return false;\n }\n }\n async isLink(path) {\n try {\n return (await this.fs.lstat(path)).isSymbolicLink === true;\n } catch {\n return false;\n }\n }\n async lstatOrMissing(path) {\n try {\n return await this.fs.lstat(path);\n } catch (e) {\n if (e.code === \"ENOENT\") return void 0;\n throw e;\n }\n }\n async statOrMissing(path) {\n try {\n return await this.fs.stat(path);\n } catch (e) {\n if (e.code === \"ENOENT\") return void 0;\n throw e;\n }\n }\n async reopen(fd) {\n const e = await this.get(fd);\n if (e.type === \"kernel\") {\n const at = await this.kernel.call({ op: \"fd-dup\", fd });\n this.table.set(at, { ...e });\n this.bump(at);\n return at;\n }\n if (e.type === \"file\") e.file.refs++;\n return await this.install(e.type === \"file\" ? e : { ...e });\n }\n};\nfunction kernelEntry() {\n return { type: \"kernel\", nonblock: false, append: false };\n}\nvar GEN2 = 2;\nfunction ringed(shared) {\n return shared.length >= FD_RING + FD_RING_SIZE * 2;\n}\nfunction deviceEntry(meta) {\n return { type: \"device\", device: meta.device, ...meta.access ? { access: meta.access } : {} };\n}\nfunction refuseWrite(s, oflags, rights) {\n const writes = (rights & RIGHTS.FD_WRITE) !== 0n || (oflags & OFLAGS.TRUNC) !== 0;\n if (s?.readonly && writes) throw new WasiError(\"EROFS\");\n}\nfunction preopenOf(e) {\n return {\n ...e.preopen ? { preopen: e.preopen } : {},\n ...e.twin !== void 0 ? { twin: e.twin } : {}\n };\n}\nfunction metaOf(e) {\n if (e.type === \"dir\") return { dir: e.path, ...preopenOf(e) };\n if (e.type === \"device\") return { device: e.device, ...e.access ? { access: e.access } : {} };\n return void 0;\n}\nfunction entryOf(info) {\n if (info.meta && \"dir\" in info.meta) {\n return { type: \"dir\", path: info.meta.dir, ...preopenOf(info.meta) };\n }\n if (info.meta && \"device\" in info.meta) return deviceEntry(info.meta);\n if (info.kind === \"held\") return void 0;\n return {\n type: \"kernel\",\n kind: info.kind,\n dgram: info.dgram === true,\n nonblock: ((info.flags ?? 0) & O_NONBLOCK2) !== 0,\n append: ((info.flags ?? 0) & O_APPEND) !== 0\n };\n}\nfunction wantOf(oflags, rights) {\n const write2 = (rights & RIGHTS.FD_WRITE) !== 0n || (oflags & OFLAGS.TRUNC) !== 0;\n const read2 = (rights & RIGHTS.FD_READ) !== 0n || !write2;\n return (read2 ? 4 : 0) | (write2 ? 2 : 0);\n}\nfunction openAccess(existing, oflags, rights) {\n const readonly = existing?.readonly === true;\n const mutating = readonly ? OFLAGS.TRUNC : OFLAGS.CREAT | OFLAGS.TRUNC;\n const writable = (rights & RIGHTS.FD_WRITE) !== 0n || (oflags & mutating) !== 0;\n if (writable && readonly) throw new WasiError(\"EROFS\");\n return { readable: (rights & RIGHTS.FD_READ) !== 0n || !writable, writable };\n}\nasync function promoteRequest(fd, f, handed) {\n const orphan = f.buffer.isOrphan() || (f.buffer.handle ?? 0) < 0;\n if (!orphan && f.buffer.isRanged) await f.buffer.flush();\n const joins = !orphan && (handed.has(f.buffer) || f.buffer.isRanged);\n return {\n op: \"fd-promote\",\n fd,\n path: f.path,\n flags: (f.writable ? f.readable ? O_RDWR : O_WRONLY : 0) | (f.append ? O_APPEND : 0),\n position: f.offset,\n ...joins ? {} : { contents: await f.buffer.contents() },\n ...orphan ? { orphan: true } : {},\n ...!orphan && f.buffer.pin !== void 0 ? { pin: { version: f.buffer.pin, size: await f.buffer.size() } } : {},\n ...!joins && f.buffer.isDirty() ? { dirty: true } : {},\n ...f.buffer.handle !== void 0 ? { handle: f.buffer.handle } : {},\n ...f.buffer.handle !== void 0 && f.ino !== void 0 ? { ino: f.ino } : {}\n };\n}\n\n// src/process/wasi/wasi-futex.ts\nvar FUTEX_SLICE_MS = 50;\nasync function futexWait(view, index3, expected, ms, interrupted) {\n const deadline = performance.now() + ms;\n for (; ; ) {\n const slice = interrupted ? Math.min(FUTEX_SLICE_MS, ms) : ms;\n if (await atomicsWait(view, index3, expected, slice) !== \"timed-out\") return true;\n if (interrupted?.()) return true;\n ms = deadline - performance.now();\n if (ms <= 0) return false;\n }\n}\nvar atomicFutexes = {\n wait: futexWait,\n notify: (view, index3, count) => atomicsNotify(view, index3, count),\n pause: () => {\n }\n};\n\n// src/process/wasi/wasi-memory.ts\nvar decoder2 = new TextDecoder();\nvar WasiMemory = class {\n memory;\n bind(memory) {\n this.memory = memory;\n }\n buffer() {\n if (!this.memory) throw new Error(\"WASI: no memory bound\");\n return this.memory.buffer;\n }\n view() {\n return new DataView(this.buffer());\n }\n bytes(ptr, len) {\n return new Uint8Array(this.buffer(), ptr, len);\n }\n string(ptr, len) {\n return decoder2.decode(this.bytes(ptr, len).slice());\n }\n cString(ptr) {\n const bytes = new Uint8Array(this.buffer());\n let end = ptr;\n while (end < bytes.length && bytes[end] !== 0) end++;\n return decoder2.decode(bytes.slice(ptr, end));\n }\n size() {\n return this.buffer().byteLength;\n }\n iovecs(ptr, count) {\n const v = this.view();\n const out = [];\n for (let i = 0; i < count; i++) {\n out.push([v.getUint32(ptr + i * 8, true), v.getUint32(ptr + i * 8 + 4, true)]);\n }\n return out;\n }\n capacity(ptr, count) {\n return this.iovecs(ptr, count).reduce((n, [, len]) => n + len, 0);\n }\n gather(ptr, count) {\n const vecs = this.iovecs(ptr, count);\n if (vecs.length === 1) return this.bytes(vecs[0][0], vecs[0][1]).slice();\n const out = new Uint8Array(vecs.reduce((n, [, len]) => n + len, 0));\n let at = 0;\n for (const [base, len] of vecs) {\n out.set(this.bytes(base, len), at);\n at += len;\n }\n return out;\n }\n scatter(ptr, count, data) {\n let at = 0;\n for (const [base, len] of this.iovecs(ptr, count)) {\n if (at >= data.length) break;\n const n = Math.min(len, data.length - at);\n this.bytes(base, n).set(data.subarray(at, at + n));\n at += n;\n }\n return at;\n }\n putStrings(list, ptrs, buf) {\n const encoder6 = new TextEncoder();\n const v = this.view();\n let at = buf;\n list.forEach((s, i) => {\n const b = encoder6.encode(s);\n v.setUint32(ptrs + i * 4, at, true);\n this.bytes(at, b.length).set(b);\n v.setUint8(at + b.length, 0);\n at += b.length + 1;\n });\n }\n putSizes(list, countPtr, sizePtr) {\n const encoder6 = new TextEncoder();\n const v = this.view();\n v.setUint32(countPtr, list.length, true);\n v.setUint32(\n sizePtr,\n list.reduce((n, s) => n + encoder6.encode(s).length + 1, 0),\n true\n );\n }\n};\n\n// src/process/wasi/wasi-poll.ts\nfunction readSubscriptions(mem, ptr, n, now) {\n const v = mem.view();\n const at = performance.now();\n const subs = [];\n for (let i = 0; i < n; i++) {\n const p = ptr + i * SIZE.SUBSCRIPTION;\n const type = v.getUint8(p + 8);\n const sub = { userdata: v.getBigUint64(p, true), type, fd: -1, deadline: Infinity };\n if (type === EVENTTYPE.CLOCK) {\n const id = v.getUint32(p + 16, true);\n let ms = Number(v.getBigUint64(p + 24, true)) / 1e6;\n if (v.getUint16(p + 40, true) & SUBCLOCK_ABSTIME) ms -= Number(now(id)) / 1e6;\n sub.deadline = at + Math.max(0, ms);\n } else {\n sub.fd = v.getUint32(p + 16, true);\n }\n subs.push(sub);\n }\n return subs;\n}\nfunction writeEvents(mem, ptr, events) {\n const v = mem.view();\n events.forEach((ev, i) => {\n const p = ptr + i * SIZE.EVENT;\n mem.bytes(p, SIZE.EVENT).fill(0);\n v.setBigUint64(p, ev.userdata, true);\n v.setUint16(p + 8, ev.error, true);\n v.setUint8(p + 10, ev.type);\n if (ev.type !== EVENTTYPE.CLOCK) {\n v.setBigUint64(p + 16, BigInt(ev.nbytes ?? 1), true);\n if (ev.hangup) v.setUint16(p + 24, EVENT_FD_READWRITE_HANGUP, true);\n }\n });\n}\nasync function classify(fds, subs) {\n const events = [];\n const read2 = [];\n const write2 = [];\n for (const s of subs) {\n if (s.type === EVENTTYPE.CLOCK) continue;\n const e = await fds.find(s.fd);\n if (!e) events.push({ userdata: s.userdata, error: E.BADF, type: s.type });\n else if (e.type !== \"kernel\")\n events.push({ userdata: s.userdata, error: E.SUCCESS, type: s.type });\n else (s.type === EVENTTYPE.FD_READ ? read2 : write2).push(s.fd);\n }\n return { events, read: read2, write: write2 };\n}\nfunction nbytesOf(s, ready) {\n const n = s.type === EVENTTYPE.FD_READ ? ready.nread?.[s.fd] : void 0;\n return n === void 0 ? {} : { nbytes: n };\n}\nfunction readyEvents(subs, ready) {\n return subs.filter(\n (s) => s.type === EVENTTYPE.FD_READ && ready.read.includes(s.fd) || s.type === EVENTTYPE.FD_WRITE && ready.write.includes(s.fd)\n ).map((s) => ({\n userdata: s.userdata,\n error: E.SUCCESS,\n type: s.type,\n hangup: ready.hangup?.includes(s.fd) === true,\n ...nbytesOf(s, ready)\n }));\n}\nvar RESUMES = 64;\nasync function selectOnce(deps, read2, write2, timeoutMs2, mayResume) {\n try {\n const ready = await deps.kernel.call({ op: \"fd-select\", read: read2, write: write2, timeoutMs: timeoutMs2 });\n return { ready, interrupted: false };\n } catch (e) {\n if (e.code !== \"EINTR\") throw e;\n if (!deps.interruptWakes && mayResume && await deps.resumes?.()) {\n return { ready: { read: [], write: [] }, interrupted: false, resumed: true };\n }\n if (!deps.interruptWakes) throw e;\n return { ready: { read: [], write: [] }, interrupted: true };\n }\n}\nasync function waitEvents(deps, subs, { events, read: read2, write: write2 }, entered) {\n const earliest = subs.reduce((min, s) => Math.min(min, s.deadline), Infinity);\n const timeout = () => {\n if (events.length > 0 || entered) return 0;\n return earliest === Infinity ? -1 : Math.max(0, Math.ceil(earliest - performance.now()));\n };\n for (let resumes = 0; ; ) {\n const { ready, interrupted, resumed } = await selectOnce(\n deps,\n read2,\n write2,\n timeout(),\n resumes++ < RESUMES\n );\n if (resumed) continue;\n events.push(...readyEvents(subs, ready));\n if (interrupted) return true;\n if (events.length > 0 || entered || earliest === Infinity) return false;\n if (performance.now() >= earliest) return false;\n }\n}\nasync function pollOneoff(deps, inPtr, outPtr, nsubs, neventsPtr) {\n if (nsubs === 0) return E.INVAL;\n const { mem } = deps;\n const subs = readSubscriptions(mem, inPtr, nsubs, deps.now);\n const found = await classify(deps.fds, subs);\n const { events, read: read2, write: write2 } = found;\n const entered = deps.entered === true && deps.interruptWakes !== true;\n const waits = read2.length > 0 || write2.length > 0 || events.length === 0;\n const interrupted = waits && await waitEvents(deps, subs, found, entered);\n const after = performance.now();\n if (entered && events.length === 0 && !subs.some((s) => s.deadline <= after)) return E.INTR;\n for (const s of subs) {\n if (s.type === EVENTTYPE.CLOCK && (interrupted || s.deadline <= after)) {\n events.push({ userdata: s.userdata, error: E.SUCCESS, type: s.type });\n }\n }\n writeEvents(mem, outPtr, events);\n mem.view().setUint32(neventsPtr, events.length, true);\n return E.SUCCESS;\n}\n\n// src/process/wasi/wasi-sigmask.ts\nvar UNBLOCKABLE = sigbit(SIG.KILL) | sigbit(SIG.STOP);\nvar LIBC_UNBLOCKABLE = 1 << SIG.KILL - 1 | 1 << SIG.STOP - 1;\nvar FOREVER = 0xffffffffffffffffn;\nvar NS_PER_MS2 = 1000000n;\nvar POLL_MS = 50;\nvar SIG_BLOCK = 0;\nvar SIG_UNBLOCK = 1;\nvar SIG_SETMASK = 2;\nvar kernelBits = (lo) => lo << 1 & ~UNBLOCKABLE;\nvar libcBits = (bits) => bits >>> 1 & ~LIBC_UNBLOCKABLE;\nvar apply = (how, mask, set) => {\n if (how === SIG_BLOCK) return mask | set;\n if (how === SIG_UNBLOCK) return mask & ~set;\n return set;\n};\nvar WasiSigmask = class {\n lo;\n hi;\n header;\n deliver;\n process;\n tid;\n published;\n constructor(header, deliver, process, tid = 1, published) {\n this.header = header;\n this.deliver = deliver;\n this.process = process;\n this.tid = tid;\n this.published = published;\n this.lo = libcBits(Atomics.load(header, SAB_I_BLOCKED));\n this.hi = Atomics.load(header, SAB_I_BLOCKED_HI);\n }\n static unsupported(header) {\n storeBlocked(header, [0, 0]);\n }\n async set(how, setLo, setHi, old) {\n if (how !== SIG_BLOCK && how !== SIG_UNBLOCK && how !== SIG_SETMASK) return E.INVAL;\n old(this.lo >>> 0, this.hi >>> 0);\n this.lo = apply(how, this.lo, setLo | 0) & ~LIBC_UNBLOCKABLE;\n this.hi = apply(how, this.hi, setHi | 0);\n const now = kernelBits(this.lo);\n storeBlocked(this.header, [now, this.hi]);\n this.published?.();\n if ((Atomics.load(this.header, SAB_I_SIGNALS) & ~now) !== 0) await this.deliver();\n return E.SUCCESS;\n }\n swap(setLo, setHi) {\n const old = [this.lo, this.hi];\n this.lo = setLo & ~LIBC_UNBLOCKABLE;\n this.hi = setHi | 0;\n storeBlocked(this.header, [kernelBits(this.lo), this.hi]);\n this.published?.();\n return old;\n }\n async deliverUnblocked() {\n const now = Atomics.load(this.header, SAB_I_BLOCKED);\n if ((Atomics.load(this.header, SAB_I_SIGNALS) & ~now) === 0) return false;\n await this.deliver();\n return true;\n }\n async restore([lo, hi]) {\n await this.set(SIG_SETMASK, lo, hi, () => {\n });\n }\n blockedBits() {\n return Atomics.load(this.header, SAB_I_BLOCKED);\n }\n blocks(sig) {\n return (Atomics.load(this.header, SAB_I_BLOCKED) & sigbit(sig)) !== 0;\n }\n inherited() {\n return [kernelBits(this.lo), this.hi];\n }\n discard(sig) {\n Atomics.and(this.header, SAB_I_SIGNALS, ~sigbit(sig));\n if (this.process) Atomics.and(this.process, SAB_I_SIGNALS, ~sigbit(sig));\n }\n async sigwait(setLo, timeoutNs, publish, took, entered = false) {\n const set = kernelBits(setLo | 0);\n const value2 = BigInt.asUintN(64, timeoutNs);\n const deadline = value2 === FOREVER ? Number.POSITIVE_INFINITY : performance.now() + Number((value2 + NS_PER_MS2 - 1n) / NS_PER_MS2);\n await publish(set);\n try {\n for (; ; ) {\n const seen = Atomics.load(this.header, SAB_I_SIGNALS);\n const sig = this.take(set);\n if (sig !== 0) {\n took(sig);\n return E.SUCCESS;\n }\n if (entered || await this.deliverUnblocked() || await this.interrupted()) return E.INTR;\n const left = deadline - performance.now();\n if (left <= 0) return E.AGAIN;\n await atomicsWait(this.header, SAB_I_SIGNALS, seen, Math.min(left, POLL_MS));\n }\n } finally {\n await publish(0);\n }\n }\n take(set) {\n for (const header of this.process ? [this.header, this.process] : [this.header]) {\n const ready = Atomics.load(header, SAB_I_SIGNALS) & set;\n if (ready === 0) continue;\n const bit = ready & -ready;\n if ((Atomics.and(header, SAB_I_SIGNALS, ~bit) & bit) !== 0) return 31 - Math.clz32(bit);\n }\n return 0;\n }\n async interrupted() {\n const killed = this.process ?? this.header;\n if (Atomics.load(killed, SAB_I_KILLED) !== 0) {\n await this.deliver();\n return true;\n }\n if (Atomics.load(killed, SAB_I_STOP) !== 1) return false;\n while (Atomics.load(killed, SAB_I_STOP) === 1) await atomicsWait(killed, SAB_I_STOP, 1);\n return true;\n }\n pending() {\n const own = Atomics.load(this.header, SAB_I_SIGNALS);\n return libcBits(own | (this.process ? Atomics.load(this.process, SAB_I_SIGNALS) : 0));\n }\n};\n\n// src/process/wasi/wasi-termios.ts\nvar NCCS3 = 32;\nvar C_LINE2 = 16;\nvar C_CC2 = 17;\nvar ISPEED = 52;\nvar OSPEED = 56;\nvar CBAUD2 = 4111;\nvar TCSAFLUSH = 2;\nfunction writeTermios(mem, ptr, termios) {\n mem.bytes(ptr, OSPEED + 4).fill(0);\n const v = mem.view();\n v.setUint32(ptr, termios.c_iflag, true);\n v.setUint32(ptr + 4, termios.c_oflag, true);\n v.setUint32(ptr + 8, termios.c_cflag, true);\n v.setUint32(ptr + 12, termios.c_lflag, true);\n for (let i = 0; i < NCCS3; i++) v.setUint8(ptr + C_CC2 + i, termios.c_cc[i] ?? 0);\n v.setUint8(ptr + C_LINE2, 0);\n v.setUint32(ptr + ISPEED, termios.c_cflag & CBAUD2, true);\n v.setUint32(ptr + OSPEED, termios.c_cflag & CBAUD2, true);\n}\nfunction readTermios(mem, ptr) {\n const v = mem.view();\n return {\n c_iflag: v.getUint32(ptr, true),\n c_oflag: v.getUint32(ptr + 4, true),\n c_cflag: v.getUint32(ptr + 8, true),\n c_lflag: v.getUint32(ptr + 12, true),\n c_cc: Array.from({ length: NCCS3 }, (_, i) => v.getUint8(ptr + C_CC2 + i))\n };\n}\nfunction sliccTty(mem, fds, kernel, interrupted = () => void 0) {\n const { sys } = kernel;\n const terminal2 = async (fd) => {\n const e = await fds.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type !== \"kernel\" || await fds.kind(fd, e) !== \"tty\") throw new WasiError(\"ENOTTY\");\n return fd;\n };\n const needs = (value2) => {\n if (value2 === void 0) throw new WasiError(\"ENOTTY\");\n return value2;\n };\n const getAttr = async (fd, ptr) => {\n await interrupted();\n writeTermios(mem, ptr, needs(await sys.tcgets?.(await terminal2(fd))));\n };\n const setAttr = async (fd, actions, ptr) => {\n await interrupted();\n if (actions < 0 || actions > TCSAFLUSH) throw new WasiError(\"EINVAL\");\n const at = await terminal2(fd);\n needs(sys.tcsets);\n await sys.tcsets?.(at, readTermios(mem, ptr), actions === TCSAFLUSH, actions !== 0);\n };\n const control = async (fd, request, arg) => {\n await interrupted();\n const e = await fds.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type !== \"kernel\") throw new WasiError(\"ENOTTY\");\n const asked = request >>> 0;\n const value2 = ioctlArg(mem.view(), asked, arg >>> 0);\n const result = await needs(sys.devIoctl).call(sys, fd, asked, value2);\n ioctlResult(mem.view(), asked, arg >>> 0, result);\n };\n const size = async (fd, ptr) => {\n await interrupted();\n const [rows, cols] = needs(await sys.winsize?.(await terminal2(fd)));\n mem.bytes(ptr, 8).fill(0);\n const v = mem.view();\n v.setUint16(ptr, rows, true);\n v.setUint16(ptr + 2, cols, true);\n };\n return {\n tcgetattr: async (fd, ptr) => void await getAttr(fd, ptr),\n tcsetattr: async (fd, actions, ptr) => void await setAttr(fd, actions, ptr),\n winsize: async (fd, ptr) => void await size(fd, ptr),\n ioctl: async (fd, request, arg) => void await control(fd, request, arg)\n };\n}\n\n// src/process/wasi/wasix-epoll.ts\nvar EVENT_SIZE = 32;\nvar DATA_OFFSET = 8;\nvar DATA_SIZE = 24;\nvar MAX_EVENTS = 4096;\nvar FOREVER2 = 0xffffffffffffffffn;\nvar MAX_TIMEOUT_MS = 2147483647;\nvar NS_PER_MS3 = 1000000n;\nvar EVENTFD_SEMAPHORE = 1;\nvar EVENTFD_NONBLOCK = 4;\nvar EVENTFD_MAX = 0xfffffffffffffffen;\nvar WASIX_OPS = [\"add\", \"mod\", \"del\"];\nvar DUAL_OPS = [\"add\", \"set\", \"del\", \"mod\"];\nfunction timeoutMs(ns) {\n const value2 = BigInt.asUintN(64, ns);\n if (value2 === FOREVER2) return -1;\n const ms = (value2 + NS_PER_MS3 - 1n) / NS_PER_MS3;\n return ms > BigInt(MAX_TIMEOUT_MS) ? -1 : Number(ms);\n}\nfunction wasixEpollImports(host) {\n const { mem, fds, o } = host;\n const call2 = async (req) => await o.kernel.call(req);\n const kernelFd = async (fd, refusal2) => {\n const e = await fds.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type !== \"kernel\") throw new WasiError(refusal2);\n };\n const writeEvents2 = (ptr, events) => {\n const view = mem.view();\n events.forEach((ev, i) => {\n const at = ptr + i * EVENT_SIZE;\n mem.bytes(at, EVENT_SIZE).fill(0);\n view.setUint32(at, ev.events, true);\n mem.bytes(at + DATA_OFFSET, DATA_SIZE).set(ev.data);\n });\n };\n return {\n epoll_create: async (out) => {\n const fd = await call2({ op: \"epoll-create\" });\n await fds.adopt(fd, \"stream\", false);\n mem.view().setUint32(out, fd, true);\n },\n epoll_ctl: async (epfd, op, fd, event) => {\n const how = (host.strictEpoll ? WASIX_OPS : DUAL_OPS)[op];\n if (!how) throw new WasiError(\"EINVAL\");\n await kernelFd(epfd, \"EINVAL\");\n await kernelFd(fd, \"EPERM\");\n if (how !== \"del\" && event === 0) throw new WasiError(\"EINVAL\");\n const events = event === 0 ? 0 : mem.view().getUint32(event, true);\n const data = event === 0 ? [] : [...mem.bytes(event + DATA_OFFSET, DATA_SIZE)];\n await call2({ op: \"epoll-ctl\", epfd, how, fd, events, data });\n },\n epoll_wait: async (epfd, ptr, maxevents, timeout, out) => {\n mem.view().setUint32(out, 0, true);\n if ((maxevents | 0) <= 0) throw new WasiError(\"EINVAL\");\n await kernelFd(epfd, \"EINVAL\");\n const max = Math.min(maxevents | 0, MAX_EVENTS);\n const ms = host.entered ? 0 : timeoutMs(timeout);\n const events = await call2({ op: \"epoll-wait\", epfd, max, timeoutMs: ms });\n if (host.entered && events.length === 0 && timeoutMs(timeout) !== 0) return E.INTR;\n writeEvents2(ptr, events);\n mem.view().setUint32(out, events.length, true);\n return E.SUCCESS;\n },\n fd_event: async (initial, flags, out) => {\n const value2 = BigInt.asUintN(64, initial);\n if (value2 > EVENTFD_MAX) throw new WasiError(\"EINVAL\");\n const fd = await call2({\n op: \"eventfd-open\",\n initial: value2.toString(),\n semaphore: (flags & EVENTFD_SEMAPHORE) !== 0\n });\n await fds.adopt(fd, \"stream\", (flags & EVENTFD_NONBLOCK) !== 0);\n mem.view().setUint32(out, fd, true);\n }\n };\n}\n\n// src/kernel/net/datagram-wire.ts\nfunction decodeReceived(raw) {\n const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);\n const length = view.getUint8(3);\n return {\n truncated: (view.getUint8(0) & 1) !== 0,\n unix: (view.getUint8(0) & 2) !== 0,\n port: view.getUint16(1),\n host: new TextDecoder().decode(raw.subarray(4, 4 + length)),\n bytes: raw.subarray(4 + length)\n };\n}\n\n// src/kernel/net/routes.ts\nvar HOST_ADDRESS = HOST_LOOPBACK_ADDRESS.join(\".\");\nfunction ipv4Bytes(text) {\n const parts = text.split(\".\");\n if (parts.length !== 4 || !parts.every((p) => /^\\d{1,3}$/.test(p))) return void 0;\n const bytes = parts.map(Number);\n return bytes.every((b) => b <= 255) ? bytes : void 0;\n}\nfunction ipv6Groups(text) {\n if (!text.includes(\":\")) return void 0;\n let canonical;\n try {\n canonical = new URL(`http://[${text}]/`).hostname.slice(1, -1);\n } catch {\n return void 0;\n }\n const [head, tail] = canonical.split(\"::\");\n const part = (s) => s ? s.split(\":\").map((h) => Number.parseInt(h, 16)) : [];\n const front = part(head);\n const back = part(tail);\n return tail === void 0 ? front : [...front, ...new Array(8 - front.length - back.length).fill(0), ...back];\n}\nfunction toBits(values, width) {\n return values.reduce((acc, v) => acc << BigInt(width) | BigInt(v), 0n);\n}\nfunction addressBits(host) {\n const v4 = ipv4Bytes(host);\n if (v4) return { v6: false, bits: toBits(v4, 8) };\n const v6 = ipv6Groups(host);\n return v6 ? { v6: true, bits: toBits(v6, 16) } : void 0;\n}\nfunction parsePrefix(text) {\n const parts = text.trim().split(\"/\");\n if (parts.length > 2) return void 0;\n const [address = \"\", size] = parts;\n const parsed = addressBits(address);\n if (!parsed) return void 0;\n const max = parsed.v6 ? 128 : 32;\n const length = size === void 0 ? max : /^\\d{1,3}$/.test(size) ? Number(size) : -1;\n if (length < 0 || length > max) return void 0;\n return { ...parsed, length };\n}\nvar RESERVED = [\n \"0.0.0.0/8\",\n \"127.0.0.0/8\",\n \"169.254.0.0/16\",\n \"224.0.0.0/4\",\n \"240.0.0.0/4\",\n \"::/96\",\n \"::ffff:0:0/96\",\n \"fe80::/10\",\n \"ff00::/8\"\n].map((p) => parsePrefix(p));\n\n// src/process/wasi/wasix-sockets.ts\nvar INET4 = 1;\nvar INET6 = 2;\nvar UNIX = 3;\nvar STREAM = 1;\nvar DGRAM = 2;\nvar RECV_DATA_TRUNCATED = 1;\nvar RIFLAG_PEEK = 1;\nvar MAX_DATAGRAM = 65536;\nvar ADDR_IP_SIZE = 18;\nvar LOOPBACK = \"127.0.0.1\";\nvar OPTIONS = {\n 1: [1, 15],\n 2: [1, 2],\n 3: [6, 1],\n 4: [1, 5],\n 6: [1, 6],\n 10: [1, 30],\n 11: [1, 4],\n 12: [1, 9],\n 14: [1, 10],\n 15: [1, 8],\n 16: [1, 7],\n 25: [1, 3]\n};\nfunction readAddr(view, ptr) {\n const tag = view.getUint8(ptr);\n if (tag === UNIX) {\n let end = ptr + 2;\n while (end < ptr + 110 && view.getUint8(end) !== 0) end++;\n const path = new TextDecoder().decode(\n new Uint8Array(view.buffer, ptr + 2, end - ptr - 2).slice()\n );\n return { family: \"unix\", path };\n }\n const port = view.getUint16(ptr + 2, true);\n if (tag === INET4) {\n const host = [0, 1, 2, 3].map((i) => view.getUint8(ptr + 4 + i)).join(\".\");\n return { family: \"inet\", host, port };\n }\n if (tag === INET6) {\n return { family: \"inet\", host: ipv6Host(new Uint8Array(view.buffer, ptr + 4, 16)), port };\n }\n throw new WasiError(\"EAFNOSUPPORT\");\n}\nfunction ipv6Host(bytes) {\n const zeros = (n) => bytes.subarray(0, n).every((b) => b === 0);\n if (zeros(16)) return \"0.0.0.0\";\n if (zeros(15) && bytes[15] === 1) return LOOPBACK;\n if (zeros(10) && bytes[10] === 255 && bytes[11] === 255) return bytes.subarray(12).join(\".\");\n const groups = [0, 2, 4, 6, 8, 10, 12, 14].map(\n (i) => (bytes[i] << 8 | bytes[i + 1]).toString(16)\n );\n return new URL(`http://[${groups.join(\":\")}]/`).hostname.slice(1, -1);\n}\nfunction writeAddr(view, ptr, addr) {\n new Uint8Array(view.buffer, ptr, 110).fill(0);\n if (!addr) return;\n if (addr.family === \"unix\") {\n view.setUint8(ptr, UNIX);\n new Uint8Array(view.buffer, ptr + 2, 107).set(\n new TextEncoder().encode(addr.path).subarray(0, 107)\n );\n return;\n }\n view.setUint16(ptr + 2, addr.port, true);\n const groups = ipv4(addr.host) ? void 0 : ipv6Groups(addr.host);\n if (groups) {\n view.setUint8(ptr, INET6);\n groups.forEach((g, i) => void view.setUint16(ptr + 4 + i * 2, g));\n return;\n }\n view.setUint8(ptr, INET4);\n const octets = ipv4(addr.host) ?? [127, 0, 0, 1];\n octets.forEach((b, i) => void view.setUint8(ptr + 4 + i, b));\n}\nfunction ipBytes(host) {\n const groups = ipv4(host) ? void 0 : ipv6Groups(host);\n return groups ? groups.flatMap((g) => [g >> 8, g & 255]) : ipv4(host);\n}\nfunction ipv4(host) {\n const parts = host.split(\".\");\n if (parts.length !== 4) return void 0;\n const bytes = parts.map((p) => /^\\d{1,3}$/.test(p) ? Number(p) : Number.NaN);\n return bytes.every((b) => b >= 0 && b <= 255) ? bytes : void 0;\n}\nfunction openRequest2(af, type) {\n if (af !== INET4 && af !== INET6 && af !== UNIX) throw new WasiError(\"EAFNOSUPPORT\");\n if (type !== STREAM && type !== DGRAM) throw new WasiError(\"EPROTONOSUPPORT\");\n const domain = af === UNIX ? \"unix\" : \"inet\";\n return {\n op: \"sock-open\",\n domain,\n ...type === DGRAM ? { type: \"dgram\" } : {}\n };\n}\nfunction pairRequest(af, type) {\n if (af !== UNIX)\n throw new WasiError(af === INET4 || af === INET6 ? \"EOPNOTSUPP\" : \"EAFNOSUPPORT\");\n if (type !== STREAM && type !== DGRAM) throw new WasiError(\"EPROTONOSUPPORT\");\n return {\n op: \"sock-pair\",\n domain: \"unix\",\n ...type === DGRAM ? { type: \"dgram\" } : {}\n };\n}\nfunction absolute(cwd, addr) {\n if (addr.family !== \"unix\" || addr.path === \"\" || addr.path.startsWith(\"\\0\")) return addr;\n return addr.path.startsWith(\"/\") ? addr : { family: \"unix\", path: `${cwd}/${addr.path}` };\n}\nfunction optionalAddr(view, ptr) {\n if (ptr === 0 || view.getUint8(ptr) === 0) return void 0;\n return readAddr(view, ptr);\n}\nfunction datagramCalls(host) {\n const { mem, o } = host;\n const call2 = async (req) => await o.kernel.call(req);\n return {\n async recvFrom(fd, nonblock, iovs, n, riflags, outLen, outFlags, outAddr) {\n const max = Math.min(mem.capacity(iovs, n), MAX_DATAGRAM);\n const peek = (riflags & RIFLAG_PEEK) !== 0;\n const raw = await call2({ op: \"sock-recvfrom\", fd, max, peek, nonblock });\n const got = decodeReceived(raw);\n const view = mem.view();\n view.setUint32(outLen, mem.scatter(iovs, n, got.bytes), true);\n view.setUint16(outFlags, got.truncated ? RECV_DATA_TRUNCATED : 0, true);\n const from = got.unix ? { family: \"unix\", path: got.host } : { family: \"inet\", host: got.host, port: got.port };\n if (outAddr) writeAddr(mem.view(), outAddr, from);\n return E.SUCCESS;\n },\n async sendTo(fd, nonblock, iovs, n, addr, out) {\n const named = optionalAddr(mem.view(), addr);\n const to = named && absolute(await host.workingDir(), named);\n const body = mem.gather(iovs, n);\n const sent = await call2({ op: \"sock-sendto\", fd, body, ...to ? { addr: to } : {}, nonblock });\n mem.view().setUint32(out, sent, true);\n return E.SUCCESS;\n }\n };\n}\nfunction wasixSocketImports(host, preview1) {\n const { mem, fds, o } = host;\n const call2 = async (req) => await o.kernel.call(req);\n const socket = async (fd) => {\n const e = await fds.get(fd);\n if (e.type !== \"kernel\" || await fds.kind(fd, e) !== \"socket\") throw new WasiError(\"ENOTSOCK\");\n return e;\n };\n const option = (opt) => OPTIONS[opt];\n const datagrams = async (fd) => {\n try {\n const e = await fds.get(fd);\n return e.type === \"kernel\" && await fds.datagram(fd, e);\n } catch {\n return false;\n }\n };\n const dgram = datagramCalls(host);\n return {\n sock_open: async (af, type, _proto, out) => {\n const req = openRequest2(af, type);\n const fd = await call2(req);\n await fds.adopt(fd, \"socket\", false, \"type\" in req);\n mem.view().setUint32(out, fd, true);\n },\n sock_pair: async (af, type, _proto, out1, out2) => {\n const req = pairRequest(af, type);\n mem.view().setUint32(out1, 0, true);\n mem.view().setUint32(out2, 0, true);\n const [a, b] = await call2(req);\n await fds.adopt(a, \"socket\", false, \"type\" in req);\n await fds.adopt(b, \"socket\", false, \"type\" in req);\n mem.view().setUint32(out1, a, true);\n mem.view().setUint32(out2, b, true);\n },\n sock_bind: async (fd, addr) => {\n await socket(fd);\n await call2({ op: \"sock-bind\", fd, addr: absolute(await host.workingDir(), readAddr(mem.view(), addr)) });\n },\n sock_listen: async (fd, backlog) => {\n await socket(fd);\n await call2({ op: \"sock-listen\", fd, backlog });\n },\n sock_connect: async (fd, addr) => {\n const e = await socket(fd);\n const to = absolute(await host.workingDir(), readAddr(mem.view(), addr));\n await call2({ op: \"sock-connect\", fd, addr: to, nonblock: e.nonblock });\n },\n sock_accept_v2: async (fd, flags, outFd, outAddr) => {\n const e = await socket(fd);\n const r = await call2({ op: \"sock-accept\", fd, nonblock: e.nonblock });\n await fds.adopt(r.fd, \"socket\", (flags & FDFLAGS.NONBLOCK) !== 0);\n mem.view().setUint32(outFd, r.fd, true);\n writeAddr(mem.view(), outAddr, r.peer);\n },\n sock_addr_local: async (fd, out) => {\n await socket(fd);\n writeAddr(mem.view(), out, await call2({ op: \"sock-name\", fd, peer: false }));\n },\n sock_addr_peer: async (fd, out) => {\n await socket(fd);\n writeAddr(mem.view(), out, await call2({ op: \"sock-name\", fd, peer: true }));\n },\n sock_recv_from: async (fd, iovs, n, riflags, outLen, outFlags, outAddr) => {\n if (await datagrams(fd)) {\n const e = await socket(fd);\n return await dgram.recvFrom(fd, e.nonblock, iovs, n, riflags, outLen, outFlags, outAddr);\n }\n const r = await preview1.sock_recv(\n fd,\n iovs,\n n,\n riflags,\n outLen,\n outFlags\n );\n if (r !== E.SUCCESS) return r;\n writeAddr(mem.view(), outAddr, await call2({ op: \"sock-name\", fd, peer: true }));\n return E.SUCCESS;\n },\n sock_send_to: async (fd, iovs, n, flags, addr, out) => {\n if (await datagrams(fd)) return await dgram.sendTo(fd, (await socket(fd)).nonblock, iovs, n, addr, out);\n return await preview1.sock_send(\n fd,\n iovs,\n n,\n flags,\n out\n );\n },\n sock_status: async (fd, out) => {\n await socket(fd);\n mem.view().setUint8(out, 1);\n },\n sock_get_opt_flag: async (fd, opt, out) => {\n await socket(fd);\n const pair = option(opt);\n const v = pair ? await call2({ op: \"sock-getopt\", fd, level: pair[0], name: pair[1] }) : 0;\n mem.view().setUint8(out, v ? 1 : 0);\n },\n sock_set_opt_flag: async (fd, opt, flag) => {\n await socket(fd);\n const pair = option(opt);\n if (pair) await call2({ op: \"sock-setopt\", fd, level: pair[0], name: pair[1], value: flag ? 1 : 0 });\n },\n sock_get_opt_size: async (fd, opt, out) => {\n await socket(fd);\n const pair = option(opt);\n const v = pair ? await call2({ op: \"sock-getopt\", fd, level: pair[0], name: pair[1] }) : 0;\n mem.view().setBigUint64(out, BigInt(v), true);\n },\n sock_set_opt_size: async (fd, opt, size) => {\n await socket(fd);\n const pair = option(opt);\n if (pair) await call2({ op: \"sock-setopt\", fd, level: pair[0], name: pair[1], value: Number(size) });\n },\n sock_get_opt_time: async (fd, _opt, out) => {\n await socket(fd);\n new Uint8Array(mem.view().buffer, out, 16).fill(0);\n },\n sock_set_opt_time: async (fd) => void await socket(fd),\n sock_send_file: () => E.NOSYS,\n resolve: async (name2, len, _port, addrs, naddrs, out) => {\n const found = await call2({ op: \"sock-resolve\", name: mem.string(name2, len), family: 0 });\n const ips = found.map(ipBytes).filter((ip) => ip !== void 0);\n if (ips.length === 0) throw new WasiError(\"ENOENT\");\n if (naddrs < 1) throw new WasiError(\"EINVAL\");\n const view = mem.view();\n const count = Math.min(ips.length, naddrs);\n new Uint8Array(view.buffer, addrs, ADDR_IP_SIZE * count).fill(0);\n for (let i = 0; i < count; i++) {\n const at = addrs + i * ADDR_IP_SIZE;\n view.setUint8(at, ips[i].length === 4 ? INET4 : INET6);\n new Uint8Array(view.buffer, at + 2, ips[i].length).set(ips[i]);\n }\n view.setUint32(out, count, true);\n }\n };\n}\n\n// src/process/wasi/wasi-host.ts\nvar WasiExit = class extends Error {\n code;\n constructor(code2) {\n super(`exit ${code2}`);\n this.code = code2;\n }\n};\nvar IDS = [\"ruid\", \"euid\", \"suid\", \"rgid\", \"egid\", \"sgid\"];\nvar NS_PER_MS4 = 1000000n;\nvar AT_SYMLINK_NOFOLLOW = 1;\nvar AT_FDCWD = -2;\nvar COPY_EXCL = 1;\nvar COPY_MODE = 2;\nvar AT_EACCESS = 2;\nvar ROOT_IDS = Object.freeze({ uid: 0, gid: 0 });\nvar GONE = /* @__PURE__ */ new Set([\"ENOENT\", \"ENOTDIR\"]);\nfunction timesChange(atim, mtim, flags) {\n const now = Date.now();\n const pick = (set, setNow, value2) => flags & setNow ? now : flags & set ? Number(value2 / NS_PER_MS4) : null;\n return {\n atimeMs: pick(FSTFLAGS.ATIM, FSTFLAGS.ATIM_NOW, atim),\n mtimeMs: pick(FSTFLAGS.MTIM, FSTFLAGS.MTIM_NOW, mtim),\n now: (flags & (FSTFLAGS.ATIM | FSTFLAGS.MTIM)) === 0\n };\n}\nfunction idOf(value2) {\n return value2 >>> 0 === 4294967295 ? void 0 : value2 >>> 0;\n}\nvar S_IFIFO = 4096;\nvar S_IFLNK = 40960;\nvar DEFAULT_UMASK = 18;\nvar MONOTONIC_BASE = BigInt(Math.round(performance.timeOrigin)) * NS_PER_MS4;\nvar MAX_READ = 1024 * 1024;\nvar SIGINFO_BYTES = 24;\nvar FD_ALIAS = /^\\/(?:dev\\/(stdin|stdout|stderr)|dev\\/fd\\/(\\d+)|proc\\/(self|[1-9]\\d*)\\/fd\\/(\\d+))$/;\nvar STDIO_FDS = { stdin: 0, stdout: 1, stderr: 2 };\nvar SIGPIPE_EXIT = 128 + SIG.PIPE;\nvar SIG_IGN = 1;\nfunction linkedOf(st) {\n return (st.nlink ?? 1) > 1 ? st : void 0;\n}\nasync function linkedElsewhere(fs, path) {\n try {\n return linkedOf(await fs.lstat(path));\n } catch {\n return void 0;\n }\n}\nfunction filetypeOf(s) {\n if (!s) return FILETYPE.UNKNOWN;\n if (s.isSymbolicLink) return FILETYPE.SYMBOLIC_LINK;\n if (s.isDirectory) return FILETYPE.DIRECTORY;\n if (s.isSocket) return FILETYPE.SOCKET_STREAM;\n if (((s.mode ?? 0) & 61440) === 8192) return FILETYPE.CHARACTER_DEVICE;\n return s.isFile ? FILETYPE.REGULAR_FILE : FILETYPE.UNKNOWN;\n}\nfunction filestatOf(path, s) {\n return {\n filetype: filetypeOf(s),\n size: BigInt(s.size),\n ino: s.ino !== void 0 ? BigInt(s.ino) : pathInode(path),\n ...s.nlink !== void 0 ? { nlink: BigInt(s.nlink) } : {},\n mtimeNs: BigInt(Math.round(s.mtimeMs ?? 0)) * NS_PER_MS4\n };\n}\nvar SEALED_MODE = 8630;\nvar DEVICE_MODE = 8630;\nfunction kernelDev(path) {\n return inDev(path) && path !== SEALED_PATH && path !== CLIPBOARD_PATH;\n}\nfunction kernelFiletype(kind) {\n switch (kind) {\n case \"tty\":\n case \"sealed\":\n case \"clipboard\":\n case \"embedder\":\n return { filetype: FILETYPE.CHARACTER_DEVICE, seeks: false };\n case \"device\":\n return { filetype: FILETYPE.CHARACTER_DEVICE, seeks: true };\n case \"socket\":\n return { filetype: FILETYPE.SOCKET_STREAM, seeks: false };\n case \"dgram\":\n return { filetype: FILETYPE.SOCKET_DGRAM, seeks: false };\n case \"file\":\n return { filetype: FILETYPE.REGULAR_FILE, seeks: true };\n default:\n return { filetype: FILETYPE.UNKNOWN, seeks: false };\n }\n}\nvar WasiHost = class {\n mem = new WasiMemory();\n fds;\n creds;\n umasks;\n started = performance.now();\n cache;\n startCwd;\n interruptWakes = false;\n strictEpoll = false;\n cwdFd = false;\n entered = false;\n enteredSignals = 0;\n raisedOnEntry;\n onRaise;\n muted;\n signals;\n sigmask;\n tid = 1;\n linkedTls;\n threadEntry;\n linkedModules;\n interrupted;\n quietly = UNGATED.quiet;\n deliverDue = UNGATED.deliver;\n futexes = atomicFutexes;\n listening = [];\n o;\n constructor(o) {\n const { kernel } = o;\n const call2 = async (req) => {\n if (req.op !== \"fd-promote\") await this.fds.flushEarly();\n return await kernel.call(req);\n };\n const sys = new Proxy(kernel.sys, {\n get: (target, name2) => {\n const member = Reflect.get(target, name2);\n if (typeof member !== \"function\") return member;\n return async (...args) => {\n await this.fds.flushEarly();\n return member.apply(target, args);\n };\n }\n });\n this.o = { ...o, kernel: { sys, call: call2 } };\n this.startCwd = o.cwd;\n this.fds = new WasiFds(this.o.kernel, o.fs);\n if (o.held) this.fds.held = o.held;\n this.creds = new CredCache(\n async () => await this.o.kernel.call({ op: \"proc-cred\" }),\n o.credGen ?? o.shared\n );\n this.umasks = new UmaskCache(\n async (mask) => await this.o.kernel.call(\n mask === void 0 ? { op: \"proc-umask\" } : { op: \"proc-umask\", mask }\n ),\n o.credGen ?? o.shared,\n { quiet: async (fn) => await this.quietly(fn), deliver: async () => await this.deliverDue() }\n );\n }\n async attach() {\n const o = this.o;\n if (o.shared) await this.fds.share(o.shared, true);\n else if (o.forked) this.fds.restore(o.forked.fds, o.forked.cloexec);\n else if (!o.bare) await this.fds.setup(o.cwd, o.inherited ?? [], o.preopenRoot === true);\n this.listening = o.shared ? [] : this.fds.sockets();\n return this;\n }\n async fromCwd(raw) {\n return await this.fds.cwd() === void 0 ? await this.fds.resolve(3, `${await this.workingDir()}/${raw}`) : await this.fds.resolve(3, raw);\n }\n async workingDir() {\n return await this.fds.cwd() ?? this.startCwd;\n }\n async umask(mask) {\n return mask === void 0 ? await this.umasks.get() : await this.umasks.set(mask);\n }\n copyImport() {\n const { mem, fds } = this;\n const named = async (dirfd, p, l) => {\n const raw = mem.string(p, l);\n if (raw === \"\") throw new WasiError(\"ENOENT\");\n if (raw.startsWith(\"/\")) return await fds.resolve(3, raw);\n return dirfd === AT_FDCWD ? await this.fromCwd(raw) : await fds.resolve(dirfd, raw);\n };\n return async (...args) => {\n const [srcDirfd, sp, sl, dstDirfd, dp, dl, mode, flags] = args;\n if (!this.o.fs.copy) return E.NOSYS;\n if ((flags & ~(COPY_EXCL | COPY_MODE)) !== 0) throw new WasiError(\"EINVAL\");\n const from = await named(srcDirfd, sp, sl);\n const to = await named(dstDirfd, dp, dl);\n const bits = flags & COPY_MODE ? (await this.o.fs.stat(from)).mode ?? 0 : mode;\n await this.copyFile(from, to, bits, (flags & COPY_EXCL) !== 0);\n return E.SUCCESS;\n };\n }\n async copyFile(from, to, mode, exclusive) {\n const { copy } = this.o.fs;\n if (!copy) throw new WasiError(\"ENOSYS\");\n await this.fds.flushPath(from);\n await copy.call(this.o.fs, from, to, mode & 4095 & ~await this.umasks.get(), exclusive);\n }\n async created(path, mode) {\n const umask = await this.umasks.get();\n if (umask !== DEFAULT_UMASK) await this.o.fs.chmod(path, mode & ~umask);\n }\n sliccTtyImports() {\n return wrap(sliccTty(this.mem, this.fds, this.o.kernel, async () => await this.interrupted?.()));\n }\n sliccFsImports() {\n const { mem, fds } = this;\n const at = async (dirfd, p, l) => await fds.resolve(dirfd, mem.string(p, l));\n const pathOf = async (fd) => {\n const e = await fds.get(fd);\n if (e.type === \"dir\") return e.path;\n if (e.type === \"file\") return e.file.path;\n const path = e.type === \"kernel\" && await fds.kind(fd, e) === \"file\" ? (await this.kernelStat(fd)).path : void 0;\n if (path === void 0) throw new WasiError(\"EBADF\");\n return path;\n };\n const target = async (path, flags) => {\n if (flags & AT_SYMLINK_NOFOLLOW && (await this.o.fs.lstat(path)).isSymbolicLink) {\n throw new WasiError(\"ENOTSUP\");\n }\n return path;\n };\n const modeOf2 = (st) => (st.mode ?? 0) & 4095;\n const caller = async () => {\n const cred = await this.creds.get();\n return [cred.euid, cred.egid];\n };\n const owner = async (st, out) => {\n const [uid, gid] = st?.uid === void 0 ? await caller() : [st.uid, st.gid];\n const view = mem.view();\n view.getUint32(out + 4, true);\n view.setUint32(out, uid, true);\n view.setUint32(out + 4, gid, true);\n };\n const dev = {\n json: async (req) => await this.o.kernel.call(req)\n };\n const fdOwned = async (fd) => {\n const e = await fds.get(fd);\n if (e.type === \"device\") return ROOT_IDS;\n const kind = e.type === \"kernel\" ? await fds.kind(fd, e) : \"file\";\n if (kind === \"sealed\" || kind === \"clipboard\") return ROOT_IDS;\n if (kind === \"tty\") return await devSync(dev, devFdStat(fd));\n if (kind !== \"file\") return void 0;\n try {\n return await this.o.fs.stat(await pathOf(fd));\n } catch (err) {\n if (!GONE.has(err?.code)) throw err;\n return void 0;\n }\n };\n const fdMode = async (fd) => {\n const e = await fds.get(fd);\n if (e.type === \"device\") return DEVICE_MODE;\n const kind = e.type === \"kernel\" ? await fds.kind(fd, e) : void 0;\n if (kind === \"stream\") return S_IFIFO | 384;\n if (kind === \"sealed\" || kind === \"clipboard\") return SEALED_MODE;\n if (kind !== void 0 && kind !== \"file\")\n return (await devSync(dev, devFdStat(fd))).mode ?? DEVICE_MODE;\n return modeOf2(await this.o.fs.stat(await pathOf(fd)));\n };\n const pathOwned = async (path, follow2) => {\n const alias = this.fdAlias(path);\n if (alias && !follow2) return alias.stdio ? ROOT_IDS : void 0;\n if (alias) {\n await this.openFd(alias.fd);\n return await fdOwned(alias.fd);\n }\n if (this.synthetic(path)) return ROOT_IDS;\n if (kernelDev(path)) return await devSync(dev, devStat(path, follow2));\n return await this.viaDev(path, follow2, async () => await this.statOf(path, follow2), pathOwned);\n };\n const pathMode = async (path, follow2) => {\n const alias = this.fdAlias(path);\n if (alias && !follow2) {\n await this.fdTarget(alias);\n return S_IFLNK | 511;\n }\n if (alias) {\n await this.openFd(alias.fd);\n return await fdMode(alias.fd);\n }\n if (this.synthetic(path) && deviceOf(path) === void 0) return SEALED_MODE;\n if (kernelDev(path)) return (await devSync(dev, devStat(path, follow2))).mode ?? DEVICE_MODE;\n const fileMode = (st) => (st.isFifo ? S_IFIFO : 0) | modeOf2(st);\n return await this.viaDev(path, follow2, async () => fileMode(await this.statOf(path, follow2)), pathMode);\n };\n return wrap({\n fd_chown: async (fd, uid, gid) => {\n if (await this.serialFd(fd)) return void await this.o.kernel.sys.fdChown?.(fd, idOf(uid), idOf(gid));\n const e = await fds.get(fd);\n const handle = e.type === \"file\" ? e.file.buffer.handle : void 0;\n void await this.chownPath(await pathOf(fd), uid, gid, true, handle);\n },\n path_chown: async (dirfd, p, l, uid, gid, flags) => void await this.pathChown(await at(dirfd, p, l), uid, gid, (flags & AT_SYMLINK_NOFOLLOW) === 0),\n fd_owner: async (fd, out) => {\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n await owner(await fdOwned(fd), out);\n },\n fd_filestat_owner: async (fd, statOut, out) => {\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n this.writeFilestat(statOut, await this.fdFilestat(fd));\n await owner(await fdOwned(fd), out);\n },\n path_filestat_owner: async (dirfd, lookup2, p, l, statOut, out) => {\n const path = await at(dirfd, p, l);\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n this.writeFilestat(statOut, await this.pathFilestat(path, lookup2));\n await owner(await pathOwned(path, (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0), out);\n },\n path_owner: async (dirfd, p, l, flags, out) => {\n const path = await at(dirfd, p, l);\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n await owner(await pathOwned(path, (flags & AT_SYMLINK_NOFOLLOW) === 0), out);\n },\n path_access: async (dirfd, p, l, amode, flags) => {\n const path = await at(dirfd, p, l);\n const nofollow = (flags & AT_SYMLINK_NOFOLLOW) !== 0;\n if (this.synthetic(path)) {\n if (this.o.fs.owners && amode & 1) throw new WasiError(\"EACCES\");\n return;\n }\n const st = await pathOwned(path, !nofollow);\n if (amode & 2 && st.readonly) throw new WasiError(\"EROFS\");\n if (!this.o.fs.owners) return;\n const kind = flags & AT_EACCESS ? \"eaccess\" : \"access\";\n await this.o.fs.access?.(path, amode & 7, kind, nofollow);\n },\n fd_chmod: async (fd, mode) => {\n if (await this.serialFd(fd)) return void await this.o.kernel.sys.fdChmod?.(fd, mode & 4095);\n await this.o.fs.chmod(await pathOf(fd), mode & 4095);\n },\n path_chmod: async (dirfd, p, l, mode, flags) => {\n const path = await target(await at(dirfd, p, l), flags);\n const bits = mode & 4095;\n await this.devChange(path, true, { mode: bits }, async () => await this.o.fs.chmod(path, bits));\n },\n path_mkfifo: async (dirfd, p, l, mode) => {\n const { mkfifo } = this.o.fs;\n if (!mkfifo) return E.NOSYS;\n const raw = mem.string(p, l);\n if (raw === \"\") throw new WasiError(\"ENOENT\");\n const path = dirfd === AT_FDCWD && !raw.startsWith(\"/\") ? await this.fromCwd(raw) : await at(dirfd, p, l);\n const umask = await this.umasks.get();\n const want = mode & 4095 & ~umask;\n await mkfifo.call(this.o.fs, path, want);\n const made = ((await this.o.fs.lstat(path)).mode ?? 0) & 4095;\n if ((made & ~want) !== 0) await this.o.fs.chmod(path, made & want);\n return E.SUCCESS;\n },\n path_copy_file: this.copyImport(),\n umask: async (mask, out) => {\n const old = await this.umasks.set(mask);\n mem.view().setUint32(out, old, true);\n },\n fd_mode: async (fd, out) => void mem.view().setUint32(out, await fdMode(fd), true),\n path_mode: async (dirfd, p, l, flags, out) => {\n const path = await at(dirfd, p, l);\n const mode = await pathMode(path, (flags & AT_SYMLINK_NOFOLLOW) === 0);\n mem.view().setUint32(out, mode, true);\n }\n });\n }\n async pathChown(path, uid, gid, follow2) {\n const ids = { uid: idOf(uid), gid: idOf(gid) };\n await this.devChange(path, follow2, ids, async () => await this.chownPath(path, uid, gid, follow2));\n }\n async chownPath(path, uid, gid, follow2, handle) {\n const { chown: own } = this.o.fs;\n if (!own) throw new WasiError(\"ENOSYS\");\n await own.call(this.o.fs, path, idOf(uid), idOf(gid), follow2, handle);\n }\n lockHost(mem) {\n return {\n mem,\n file: async (fd) => await this.lockedFile(fd),\n flush: async (file) => {\n if (file.path !== void 0) await this.fds.flushPath(file.path);\n else if (file.target.fd !== void 0) await this.o.kernel.sys.flush(file.target.fd);\n },\n locked: () => this.fds.holdLocks(),\n promote: async (fd, moved) => await this.fds.promote(fd, moved),\n reread: async (fd) => await this.fds.reread(fd),\n calls: {\n flock: async (fd, kind, wait) => await this.fds.restarting(\n async () => await this.o.kernel.call({ op: \"flock\", fd, kind, ...wait ? { wait } : {} })\n ),\n set: async (target, kind, start2, len, wait) => await this.fds.restarting(\n async () => await this.o.kernel.call({\n op: \"lk-set\",\n ...target,\n kind,\n start: start2,\n len,\n ...wait ? { wait } : {}\n })\n ),\n get: async (target, kind, start2, len) => await this.o.kernel.call({ op: \"lk-get\", ...target, kind, start: start2, len })\n }\n };\n }\n sliccImports() {\n const { mem } = this;\n const path = async (p, l) => {\n const text = mem.string(p, l);\n return text === \"\" || text.startsWith(\"/\") ? text : normalize(`${await this.workingDir()}/${text}`);\n };\n return wrap({\n mount: async (sp, sl, tp, tl, fp, fl, flags, dp, dl) => void await this.o.kernel.call({\n op: \"mount\",\n source: mem.string(sp, sl),\n target: await path(tp, tl),\n type: mem.string(fp, fl),\n flags,\n data: mem.string(dp, dl)\n }),\n umount2: async (tp, tl, flags) => void await this.o.kernel.call({ op: \"umount\", target: await path(tp, tl), flags }),\n cred_get: async (out) => {\n const cred = await this.creds.get();\n const view = mem.view();\n view.getUint32(out + 20, true);\n IDS.forEach((key, i) => void view.setUint32(out + i * 4, cred[key], true));\n },\n cred_set: async (...ids) => {\n const change = {};\n IDS.forEach((key, i) => {\n if (ids[i] !== -1) change[key] = ids[i] >>> 0;\n });\n void await this.creds.change(async () => await this.o.kernel.call({ op: \"proc-setcred\", change }));\n },\n ...semImports(this),\n ...lockImports(this.lockHost(mem)),\n groups_get: async (buf, cap, count) => {\n const { groups } = await this.creds.get();\n if (cap !== 0 && cap < groups.length) throw new WasiError(\"EINVAL\");\n const shown = cap === 0 ? [] : groups;\n const view = mem.view();\n view.getUint32(count, true);\n if (shown.length > 0) view.getUint32(buf + (shown.length - 1) * 4, true);\n shown.forEach((g, i) => void view.setUint32(buf + i * 4, g, true));\n view.setUint32(count, groups.length, true);\n },\n groups_set: async (buf, n) => {\n if (n < 0 || n > MAX_GROUPS) throw new WasiError(\"EINVAL\");\n const view = mem.view();\n const groups = Array.from({ length: n }, (_, i) => view.getUint32(buf + i * 4, true));\n void await this.creds.change(\n async () => await this.o.kernel.call({ op: \"proc-setcred\", change: { groups } })\n );\n },\n sigaction_set: (sig, disposition, flags) => {\n if (!this.signals) return E.NOSYS;\n const errno = this.signals.disposition(sig, disposition, flags);\n if (errno === E.SUCCESS && disposition === SIG_IGN) this.sigmask?.discard(sig);\n return errno;\n },\n sigmask_set: async (how, lo, hi, old) => {\n if (!this.sigmask) return E.NOSYS;\n if (how === SIG_UNBLOCK || how === SIG_SETMASK) {\n this.signals?.unblocking(how === SIG_UNBLOCK ? lo << 1 : ~(lo << 1));\n }\n return await this.sigmask.set(how, lo, hi, (oldLo, oldHi) => {\n if (old === 0) return;\n const view = mem.view();\n view.setUint32(old, oldLo, true);\n view.setUint32(old + 4, oldHi, true);\n });\n },\n sigmask_poll: async (lo, hi, inPtr, outPtr, n, nevents) => this.sigmask ? await this.maskedPoll(this.sigmask, [lo, hi], [inPtr, outPtr, n, nevents]) : E.NOSYS,\n sigmask_epoll_wait: async (lo, hi, epfd, events, max, timeout, nevents) => this.sigmask ? await this.maskedEpoll(\n this.sigmask,\n [lo, hi],\n nevents,\n async (epoll) => await epoll(epfd, events, max, timeout, nevents)\n ) : E.NOSYS,\n sigwait: async (lo, _hi, timeout, out) => {\n const mask = this.sigmask;\n if (!mask) return E.NOSYS;\n mem.view().setUint32(out, 0, true);\n return await mask.sigwait(\n lo,\n timeout,\n async (set) => void await this.o.kernel.call({ op: \"sig-waiting\", tid: mask.tid, set }),\n (sig) => void mem.view().setUint32(out, sig, true),\n this.entered\n );\n },\n sigwait_info: async (lo, _hi, timeout, info) => {\n const mask = this.sigmask;\n if (!mask) return E.NOSYS;\n let took = 0;\n const r = await mask.sigwait(\n lo,\n timeout,\n async (set) => void await this.o.kernel.call({ op: \"sig-waiting\", tid: mask.tid, set }),\n (sig) => {\n took = sig;\n },\n this.entered\n );\n if (r === E.SUCCESS) await this.writeSiginfo(info, took, mask.tid);\n return r;\n },\n siginfo_take: async (sig, info) => await this.writeSiginfo(info, sig, this.sigmask?.tid ?? this.tid, false) ? E.SUCCESS : E.NOENT,\n sigaction_inherited: async (out) => {\n const bits = await this.o.kernel.call({ op: \"sig-inherited\" });\n mem.view().setBigUint64(out, BigInt(libcBits(bits) >>> 0), true);\n return E.SUCCESS;\n },\n sigpending_get: (out) => {\n if (!this.sigmask) return E.NOSYS;\n mem.view().setBigUint64(out, BigInt(this.sigmask.pending()), true);\n return E.SUCCESS;\n }\n });\n }\n async poll(inPtr, outPtr, n, nevents, resume = true) {\n const ran = this.signals?.ran ?? 0;\n try {\n return await pollOneoff(\n {\n mem: this.mem,\n fds: this.fds,\n kernel: this.o.kernel,\n now: (id) => this.now(id),\n interruptWakes: this.interruptWakes,\n entered: this.entered,\n ...resume ? { resumes: async () => await this.resumesPoll(ran) } : {}\n },\n inPtr,\n outPtr,\n n,\n nevents\n );\n } finally {\n this.o.fs.invalidate?.();\n }\n }\n async resumesPoll(ran) {\n await this.interrupted?.();\n return (this.signals?.ran ?? 0) === ran;\n }\n async maskedPoll(mask, set, [inPtr, outPtr, n, nevents]) {\n const old = mask.swap(set[0], set[1]);\n try {\n this.mem.view().setUint32(nevents, 0, true);\n if (await mask.deliverUnblocked()) return E.INTR;\n this.settleEntry(mask);\n if (n > 0) return await this.poll(inPtr, outPtr, n, nevents, false);\n return this.entered ? E.INTR : await this.suspend();\n } finally {\n await mask.deliverUnblocked();\n await mask.restore(old);\n }\n }\n epollWait;\n settleEntry(mask) {\n if (this.entered && (this.enteredSignals & ~mask.blockedBits()) === 0) this.entered = false;\n }\n async maskedEpoll(mask, set, nevents, wait) {\n const old = mask.swap(set[0], set[1]);\n try {\n this.mem.view().setUint32(nevents, 0, true);\n if (await mask.deliverUnblocked()) return E.INTR;\n this.settleEntry(mask);\n this.epollWait ??= wasixEpollImports(this).epoll_wait;\n return await wait(this.epollWait) ?? E.SUCCESS;\n } finally {\n await mask.deliverUnblocked();\n await mask.restore(old);\n }\n }\n async suspend() {\n for (; ; ) {\n try {\n await this.o.kernel.call({ op: \"fd-select\", read: [], write: [], timeoutMs: -1 });\n } catch (e) {\n if (e.code === \"EINTR\") return E.INTR;\n throw e;\n }\n }\n }\n imports() {\n this.cache ??= wrap({\n ...this.processImports(),\n ...this.ioImports(),\n ...this.statImports(),\n ...this.pathImports(),\n ...this.socketImports(),\n poll_oneoff: async (inPtr, outPtr, n, nevents) => await this.poll(inPtr, outPtr, n, nevents)\n });\n return this.cache;\n }\n now(id) {\n if (id === CLOCK.REALTIME) return BigInt(Date.now()) * NS_PER_MS4;\n if (id === CLOCK.MONOTONIC) {\n return MONOTONIC_BASE + BigInt(Math.round(performance.now() * 1e6));\n }\n return (localCpuNanos() ?? BigInt(Math.round((performance.now() - this.started) * 1e6))) + 1n;\n }\n async environ() {\n if (this.o.bare) return Object.entries(this.o.env).map(([k, v]) => `${k}=${v}`);\n const listen = this.listening.length > 0 ? { SLICC_LISTEN_FDS: this.listening.join(\" \") } : {};\n const env = { PWD: await this.workingDir(), ...this.o.env, ...listen };\n return Object.entries(env).map(([k, v]) => `${k}=${v}`);\n }\n processImports() {\n const { mem } = this;\n return {\n args_get: (argv, buf) => void mem.putStrings(this.o.args, argv, buf),\n args_sizes_get: (n, size) => void mem.putSizes(this.o.args, n, size),\n environ_get: async (envp, buf) => void mem.putStrings(await this.environ(), envp, buf),\n environ_sizes_get: async (n, size) => void mem.putSizes(await this.environ(), n, size),\n clock_res_get: (_id, out) => void mem.view().setBigUint64(out, 1000n, true),\n clock_time_get: (id, _precision, out) => void mem.view().setBigUint64(out, this.now(id), true),\n random_get: (buf, len) => {\n for (let at = 0; at < len; at += 65536) {\n const chunk = new Uint8Array(Math.min(65536, len - at));\n crypto.getRandomValues(chunk);\n mem.bytes(buf + at, chunk.length).set(chunk);\n }\n },\n sched_yield: async () => {\n await this.futexes.pause();\n return E.SUCCESS;\n },\n proc_exit: (code2) => {\n throw new WasiExit(code2);\n },\n proc_raise: async (sig) => {\n const posix = WASI_SIGNAL_TO_POSIX[sig];\n if (posix === void 0) throw new WasiError(\"EINVAL\");\n if (await this.onRaise?.(posix)) return;\n await this.o.kernel.call({ op: \"proc-kill\", pid: this.o.pid, sig: posix });\n }\n };\n }\n ioImports() {\n const { mem, fds } = this;\n return {\n fd_write: async (fd, iovs, n, out) => void mem.view().setUint32(out, await this.write(fd, mem.gather(iovs, n)), true),\n fd_read: async (fd, iovs, n, out) => {\n const data = await this.read(fd, mem.capacity(iovs, n));\n mem.view().setUint32(out, mem.scatter(iovs, n, data), true);\n },\n fd_pread: async (fd, iovs, n, at, out) => {\n const data = await (await this.positional(fd, \"read\")).pread(mem.capacity(iovs, n), Number(at));\n mem.view().setUint32(out, mem.scatter(iovs, n, data), true);\n },\n fd_pwrite: async (fd, iovs, n, at, out) => void mem.view().setUint32(\n out,\n await (await this.positional(fd, \"write\")).pwrite(mem.gather(iovs, n), Number(at)),\n true\n ),\n fd_seek: async (fd, offset, whence, out) => void mem.view().setBigUint64(out, BigInt(await this.seek(fd, Number(offset), whence)), true),\n fd_tell: async (fd, out) => void mem.view().setBigUint64(out, BigInt(await this.seek(fd, 0, WHENCE.CUR)), true),\n fd_close: async (fd) => void await fds.close(fd),\n fd_renumber: async (from, to) => void await fds.renumber(from, to),\n fd_sync: async (fd) => void await this.sync(fd),\n fd_datasync: async (fd) => void await this.sync(fd),\n fd_advise: async (fd) => void await fds.get(fd),\n fd_allocate: async (fd, offset, len) => {\n const file = await this.positional(fd, \"write\");\n const end = Number(offset + len);\n if (end > await file.size()) await file.truncate(end);\n }\n };\n }\n statImports() {\n const { mem, fds } = this;\n return {\n fd_fdstat_get: async (fd, out) => void await this.fdstat(fd, out),\n fd_fdstat_set_flags: async (fd, flags) => void await fds.setFlags(fd, (flags & FDFLAGS.NONBLOCK) !== 0, (flags & FDFLAGS.APPEND) !== 0),\n fd_fdstat_set_rights: async (fd) => void await fds.get(fd),\n fd_filestat_get: async (fd, out) => void this.writeFilestat(out, await this.fdFilestat(fd)),\n fd_filestat_set_size: async (fd, size) => void await (await this.positional(fd, \"write\")).truncate(Number(size)),\n fd_filestat_set_times: async (fd, atim, mtim, flags) => {\n const e = await fds.get(fd);\n if (e.type === \"file\") {\n await e.file.flush();\n await this.setTimes(e.file.path, atim, mtim, flags);\n } else if (e.type === \"dir\") await this.setTimes(e.path, atim, mtim, flags);\n else if (await this.serialFd(fd)) {\n const { atimeMs, mtimeMs, now } = timesChange(atim, mtim, flags);\n await this.o.kernel.sys.fdUtimes?.(fd, atimeMs, mtimeMs, now);\n }\n },\n fd_prestat_get: async (fd, out) => {\n const name2 = new TextEncoder().encode((await fds.preopen(fd)).preopen);\n mem.view().setUint8(out, PREOPENTYPE_DIR);\n mem.view().setUint32(out + 4, name2.length, true);\n },\n fd_prestat_dir_name: async (fd, buf, len) => {\n const name2 = new TextEncoder().encode((await fds.preopen(fd)).preopen);\n mem.bytes(buf, Math.min(len, name2.length)).set(name2.subarray(0, len));\n },\n fd_readdir: async (fd, buf, len, cookie, used) => void await this.readdir(fd, buf, len, Number(cookie), used)\n };\n }\n pathImports() {\n const { mem, fds, o } = this;\n const at = async (dirfd, p, l) => await fds.resolve(dirfd, mem.string(p, l));\n return {\n path_open: async (dirfd, lookup2, p, l, oflags, rights, _inheriting, fdflags, out) => {\n const follow2 = (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0;\n try {\n const asked = await at(dirfd, p, l);\n const alias = this.fdAlias(asked);\n if (alias && !alias.stdio) await this.openFd(alias.fd);\n const path = alias && !alias.stdio ? `/dev/fd/${alias.fd}` : asked;\n if (deviceOf(path)) await this.interrupted?.();\n mem.view().setUint32(out, await fds.open(path, oflags, rights, fdflags, void 0, !follow2), true);\n if (fds.created) await this.created(path, 438);\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n const raw = mem.string(p, l);\n const joined2 = raw.startsWith(\"/\") ? raw : `${(await fds.dir(dirfd)).path}/${raw}`;\n const resolved2 = await this.resolveForDev(joined2, follow2);\n if (!resolved2) throw err;\n mem.view().setUint32(out, await fds.open(resolved2, oflags, rights, fdflags, void 0, !follow2), true);\n }\n },\n path_filestat_get: async (dirfd, lookup2, p, l, out) => {\n try {\n this.writeFilestat(out, await this.pathFilestat(await at(dirfd, p, l), lookup2));\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n const raw = mem.string(p, l);\n const joined2 = raw.startsWith(\"/\") ? raw : `${(await fds.dir(dirfd)).path}/${raw}`;\n const resolved2 = await this.resolveForDev(joined2, (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0);\n if (!resolved2) throw err;\n this.writeFilestat(out, await this.pathFilestat(resolved2, lookup2));\n }\n },\n path_filestat_set_times: async (dirfd, lookup2, p, l, atim, mtim, flags) => {\n const path = await at(dirfd, p, l);\n await fds.flushPath(path);\n await this.setTimes(path, atim, mtim, flags, (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0);\n },\n path_create_directory: async (dirfd, p, l) => {\n const path = await at(dirfd, p, l);\n if (await o.fs.exists(path)) throw new WasiError(\"EEXIST\");\n await o.fs.mkdir(path);\n await this.created(path, 511);\n },\n path_remove_directory: async (dirfd, p, l) => void await o.fs.rmdir(await at(dirfd, p, l)),\n path_unlink_file: async (dirfd, p, l) => {\n const path = await at(dirfd, p, l);\n if (inDevTree(path)) return void await o.fs.unlink(path);\n const st = await o.fs.lstat(path);\n if (st.isDirectory) throw new WasiError(\"EISDIR\");\n const linked = linkedOf(st);\n await fds.unlinking(path, linked);\n await o.fs.unlink(path);\n await fds.unlinked(path, linked);\n },\n path_rename: async (fd, p, l, fd2, p2, l2) => {\n const from = await at(fd, p, l);\n const to = await at(fd2, p2, l2);\n await fds.flushPath(from);\n const replaced = fds.holdsUnder(to) ? await linkedElsewhere(o.fs, to) : void 0;\n if (replaced === void 0) await fds.replacing(to);\n const seq = await o.fs.rename(from, to);\n await fds.renamed(from, to, replaced);\n fds.ownRename(typeof seq === \"number\" ? seq : void 0);\n },\n path_symlink: async (tp, tl, dirfd, p, l) => {\n const path = await at(dirfd, p, l);\n if (tl === 0) throw new WasiError(\"ENOENT\");\n await o.fs.symlink(mem.string(tp, tl), path);\n },\n path_readlink: async (dirfd, p, l, buf, len, used) => {\n const path = await at(dirfd, p, l);\n const alias = this.fdAlias(path);\n const target = new TextEncoder().encode(alias ? await this.fdTarget(alias) : await o.fs.readlink(path));\n const n = Math.min(len, target.length);\n mem.bytes(buf, n).set(target.subarray(0, n));\n mem.view().setUint32(used, n, true);\n },\n path_link: async (fd, lookup2, p, l, fd2, p2, l2) => {\n const from = await at(fd, p, l);\n const to = await at(fd2, p2, l2);\n const follow2 = (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0;\n const source = follow2 ? await physicalPath(o.fs, from) : from;\n await fds.flushPath(from);\n if (source !== from) await fds.flushPath(source);\n await o.fs.link(from, to, follow2);\n await fds.linked(from, to);\n if (source !== from) await fds.linked(source, to);\n }\n };\n }\n async socket(fd) {\n const e = await this.fds.get(fd);\n if (e.type !== \"kernel\" || await this.fds.kind(fd, e) !== \"socket\") throw new WasiError(\"ENOTSOCK\");\n return e;\n }\n socketImports() {\n const { mem, fds, o } = this;\n return {\n sock_accept: async (fd, flags, out) => {\n const listener = await this.socket(fd);\n const r = await o.kernel.call({ op: \"sock-accept\", fd, nonblock: listener.nonblock });\n await fds.adopt(r.fd, \"socket\", (flags & FDFLAGS.NONBLOCK) !== 0);\n mem.view().setUint32(out, r.fd, true);\n },\n sock_recv: async (fd, iovs, n, riflags, outLen, outFlags) => {\n const e = await this.socket(fd);\n if (await this.fds.datagram(fd, e)) {\n return await datagramCalls(this).recvFrom(\n fd,\n e.nonblock,\n iovs,\n n,\n riflags,\n outLen,\n outFlags,\n 0\n );\n }\n const peek = (riflags & RIFLAGS.PEEK) !== 0;\n const want = mem.capacity(iovs, n);\n const data = (riflags & RIFLAGS.WAITALL) !== 0 && !peek ? await this.recvAll(fd, want, e.nonblock) : await o.kernel.sys.read(fd, Math.min(want, MAX_READ), { nonblock: e.nonblock, peek });\n mem.view().setUint32(outLen, mem.scatter(iovs, n, data), true);\n mem.view().setUint16(outFlags, 0, true);\n },\n sock_send: async (fd, iovs, n, _flags, out) => {\n const e = await this.socket(fd);\n const sent = await o.kernel.sys.write(fd, mem.gather(iovs, n), { nonblock: e.nonblock });\n mem.view().setUint32(out, sent, true);\n },\n sock_shutdown: async (fd, how) => {\n await this.socket(fd);\n const both = SDFLAGS.RD | SDFLAGS.WR;\n if (how === 0 || (how & ~both) !== 0) throw new WasiError(\"EINVAL\");\n await o.kernel.call({\n op: \"sock-shutdown\",\n fd,\n how: how === both ? 2 : how === SDFLAGS.WR ? 1 : 0\n });\n }\n };\n }\n async recvAll(fd, want, nonblock) {\n const chunks = [];\n let got = 0;\n while (got < want) {\n let chunk;\n try {\n chunk = await this.o.kernel.sys.read(fd, Math.min(want - got, MAX_READ), { nonblock });\n } catch (err) {\n if (got === 0) throw err;\n break;\n }\n if (chunk.length === 0) break;\n chunks.push(chunk);\n got += chunk.length;\n }\n const out = new Uint8Array(got);\n let at = 0;\n for (const chunk of chunks) {\n out.set(chunk, at);\n at += chunk.length;\n }\n return out;\n }\n async file(fd, access3) {\n const e = await this.fds.get(fd);\n if (e.type !== \"file\") {\n throw new WasiError(e.type === \"dir\" ? \"EISDIR\" : e.type === \"kernel\" ? \"ESPIPE\" : \"EINVAL\");\n }\n if (access3 === \"read\" && !e.file.readable || access3 === \"write\" && !e.file.writable) {\n throw new WasiError(\"EBADF\");\n }\n return e.file;\n }\n async positional(fd, access3) {\n const e = await this.fds.get(fd);\n const kind = e.type === \"kernel\" ? await this.fds.kind(fd, e) : e.type;\n if (kind === \"device\") await this.interrupted?.();\n if (kind !== \"file\" || e.type !== \"kernel\") return await this.file(fd, access3);\n const kernel = this.o.kernel;\n return {\n pread: async (max, at) => {\n if (!kernel.sys.pread) throw new WasiError(\"ESPIPE\");\n return await kernel.sys.pread(fd, Math.min(max, MAX_READ), at);\n },\n pwrite: async (body, at) => await this.changed(fd, e, await kernel.call({ op: \"fd-pwrite\", fd, offset: at, body })),\n size: async () => (await this.kernelStat(fd)).size,\n truncate: async (size) => await this.changed(fd, e, void await kernel.call({ op: \"fd-resize\", fd, size }))\n };\n }\n unnamed = /* @__PURE__ */ new WeakSet();\n async changed(fd, e, result) {\n if (e.path === void 0 && !this.unnamed.has(e)) await this.learnPath(fd, e);\n this.o.fs.touched?.(e.path, e.ino);\n return result;\n }\n async learnPath(fd, e) {\n this.unnamed.add(e);\n let path;\n try {\n const st = await this.o.kernel.call({ op: \"fd-vfs-stat\", fd, identity: true });\n path = st.orphan ? void 0 : st.path;\n if (path !== void 0) e.ino = st.ino ?? (await this.o.fs.stat(path)).ino;\n } catch {\n return;\n }\n e.path = path;\n }\n async lockedFile(fd) {\n const e = await this.fds.get(fd);\n if (e.type === \"file\") {\n const { file } = e;\n return {\n target: { path: file.path },\n path: file.path,\n readable: file.readable,\n writable: file.writable,\n offset: () => file.offset,\n size: async () => await file.size()\n };\n }\n if (e.type !== \"kernel\") throw new WasiError(\"EBADF\");\n if (await this.fds.kind(fd, e) !== \"file\") return { target: { fd }, offset: () => 0, size: () => 0 };\n return {\n target: { fd },\n offset: async () => await this.o.kernel.sys.seek(fd, 0, WHENCE.CUR),\n size: async () => (await this.kernelStat(fd)).size\n };\n }\n async kernelStat(fd) {\n return await this.o.kernel.call({ op: \"fd-vfs-stat\", fd });\n }\n async write(fd, data) {\n if (this.muted?.(fd, data)) return data.length;\n const e = await this.fds.get(fd);\n if (e.type === \"kernel\") {\n try {\n const n = await this.o.kernel.sys.write(fd, data, { nonblock: e.nonblock });\n return await this.fds.kind(fd, e) === \"file\" ? await this.changed(fd, e, n) : n;\n } catch (err) {\n const broken = err.code === \"EPIPE\";\n if (broken && await this.fds.kind(fd, e) !== \"socket\") await this.brokenPipe();\n throw err;\n }\n }\n if (e.type === \"device\") {\n await this.interrupted?.();\n if (e.access === \"read\") throw new WasiError(\"EBADF\");\n if (e.device === \"full\" && data.length > 0) throw new WasiError(\"ENOSPC\");\n return data.length;\n }\n return await (await this.file(fd, \"write\")).write(data);\n }\n async brokenPipe() {\n let action;\n try {\n action = await this.o.kernel.call({ op: \"proc-kill-self\", sig: SIG.PIPE, dry: true });\n } catch {\n action = \"terminate\";\n }\n if (action === \"ignore\") return;\n if (action === \"terminate\" && !this.sigmask?.blocks(SIG.PIPE)) throw new WasiExit(SIGPIPE_EXIT);\n await this.o.kernel.call({ op: \"thread-kill\", tid: this.tid, sig: SIG.PIPE });\n }\n async read(fd, max) {\n const e = await this.fds.get(fd);\n if (e.type === \"kernel\") {\n return await this.o.kernel.sys.read(fd, Math.min(max, MAX_READ), { nonblock: e.nonblock });\n }\n if (e.type === \"device\") {\n await this.interrupted?.();\n if (e.access === \"write\") throw new WasiError(\"EBADF\");\n if (e.device === \"null\") return new Uint8Array(0);\n const out = new Uint8Array(Math.min(max, 65536));\n return e.device === \"urandom\" ? crypto.getRandomValues(out) : out;\n }\n return await (await this.file(fd, \"read\")).read(max);\n }\n async local(answer) {\n await this.interrupted?.();\n return answer;\n }\n async seek(fd, offset, whence) {\n const e = await this.fds.get(fd);\n if (e.type === \"kernel\") {\n const kind = await this.fds.kind(fd, e);\n if (kind === \"device\") return await this.local(0);\n if (kind !== \"file\") throw new WasiError(\"ESPIPE\");\n return await this.o.kernel.sys.seek(fd, offset, whence);\n }\n if (e.type === \"device\") return await this.local(0);\n const file = await this.file(fd);\n const base = whence === WHENCE.SET ? 0 : whence === WHENCE.CUR ? file.offset : await file.size();\n if (whence > WHENCE.END || base + offset < 0) throw new WasiError(\"EINVAL\");\n file.offset = base + offset;\n return file.offset;\n }\n async sync(fd) {\n const e = await this.fds.get(fd);\n if (e.type === \"file\") await this.fds.synced(e.file);\n else if (e.type === \"device\") await this.interrupted?.();\n else if (e.type === \"kernel\") {\n const kind = await this.fds.kind(fd, e);\n if (kind === \"file\") await this.o.kernel.sys.flush(fd);\n else if (kind === \"device\") await this.interrupted?.();\n }\n }\n async fdstat(fd, out) {\n const e = await this.fds.get(fd);\n if (e.type === \"device\") await this.interrupted?.();\n let filetype = FILETYPE.CHARACTER_DEVICE;\n let seeks = true;\n let flags = 0;\n if (e.type === \"kernel\") {\n const kind = await this.fds.kind(fd, e);\n if (kind === \"device\") await this.interrupted?.();\n ({ filetype, seeks } = kernelFiletype(await this.fds.datagram(fd, e) ? \"dgram\" : kind));\n if (e.nonblock) flags |= FDFLAGS.NONBLOCK;\n if (e.append) flags |= FDFLAGS.APPEND;\n } else if (e.type === \"file\") {\n filetype = FILETYPE.REGULAR_FILE;\n if (e.file.append) flags |= FDFLAGS.APPEND;\n } else if (e.type === \"dir\") filetype = FILETYPE.DIRECTORY;\n const v = this.mem.view();\n v.setUint8(out, filetype);\n v.setUint16(out + 2, flags, true);\n let rights = seeks ? RIGHTS.ALL : RIGHTS.ALL & ~(RIGHTS.FD_SEEK | RIGHTS.FD_TELL);\n if (e.type === \"kernel\") {\n const access3 = await this.o.kernel.sys.access?.(fd);\n if (access3 === \"read\") rights &= ~RIGHTS.FD_WRITE;\n else if (access3 === \"write\") rights &= ~RIGHTS.FD_READ;\n }\n v.setBigUint64(out + 8, rights, true);\n v.setBigUint64(out + 16, RIGHTS.ALL, true);\n }\n writeFilestat(ptr, f) {\n const v = this.mem.view();\n v.setBigUint64(ptr, 1n, true);\n v.setBigUint64(ptr + 8, f.ino, true);\n v.setUint8(ptr + 16, f.filetype);\n v.setBigUint64(ptr + 24, f.nlink ?? 1n, true);\n v.setBigUint64(ptr + 32, f.size, true);\n v.setBigUint64(ptr + 40, f.mtimeNs, true);\n v.setBigUint64(ptr + 48, f.mtimeNs, true);\n v.setBigUint64(ptr + 56, f.mtimeNs, true);\n }\n async fdFilestat(fd) {\n const e = await this.fds.get(fd);\n if (e.type === \"dir\") return filestatOf(e.path, await this.o.fs.stat(e.path));\n if (e.type === \"file\") return await this.localFilestat(e.file);\n const kind = e.type === \"kernel\" ? await this.fds.kind(fd, e) : void 0;\n if (kind === \"file\") {\n const vfs = await this.kernelStat(fd);\n if (vfs.path) return await this.statOrphanable(vfs.path, vfs.size, vfs.orphan, vfs.orphan);\n }\n const filetype = kind ? kernelFiletype(kind).filetype : FILETYPE.CHARACTER_DEVICE;\n return await this.local({ filetype, size: 0n, ino: BigInt(fd + 1), mtimeNs: 0n });\n }\n async localFilestat(file) {\n const { buffer } = file;\n if (buffer.isOrphan()) {\n const bound2 = buffer.bound;\n if (!bound2) return await this.statOrphanable(file.path, await file.size(), false, true);\n return { ...this.sized(file.path, bound2, await file.size()), nlink: 0n };\n }\n let s;\n try {\n s = await this.o.fs.stat(file.path);\n } catch {\n s = await this.keptStat(buffer.handle);\n }\n const bound = buffer.bound;\n if (s && bound?.ino !== void 0 && s.ino !== bound.ino) {\n s = await this.keptStat(buffer.handle) ?? bound;\n }\n return this.sized(file.path, s, await file.size());\n }\n async keptStat(handle) {\n if (handle === void 0) return void 0;\n try {\n return await this.o.fs.keptStat?.(handle);\n } catch {\n return void 0;\n }\n }\n sized(path, s, size) {\n return {\n ...filestatOf(path, s ?? { isFile: true, isDirectory: false, size: 0 }),\n size: BigInt(size)\n };\n }\n async statOrphanable(path, size, orphan = false, gone = false) {\n let s;\n if (!orphan) {\n try {\n s = await this.o.fs.stat(path);\n } catch {\n }\n }\n const out = this.sized(path, s, size);\n return gone ? { ...out, nlink: 0n } : out;\n }\n synthetic(path) {\n return deviceOf(path) !== void 0 || path === SEALED_PATH && !!this.o.kernel.sys.openSealed || path === CLIPBOARD_PATH && !!this.o.kernel.sys.openClipboard || path === EMBEDDER_PATH && !!this.o.kernel.sys.openEmbedder;\n }\n async serialFd(fd) {\n const e = await this.fds.get(fd);\n if (e.type !== \"kernel\" || await this.fds.kind(fd, e) !== \"tty\") return false;\n const { terminal: terminal2 } = await this.o.kernel.call({ op: \"fd-info\", fd });\n return terminal2?.startsWith(\"/dev/\") === true && DEVICE_NAME.test(terminal2.slice(5));\n }\n async devChange(path, follow2, change, plain) {\n const dev = {\n json: async (req) => await this.o.kernel.call(req)\n };\n if (await devSync(dev, devMeta(path, follow2, change))) return;\n try {\n await plain();\n } catch (err) {\n const gone = err.code === \"ENOENT\";\n const linked = gone ? await this.linkedDev(path, follow2) : void 0;\n if (linked === void 0 || !await devSync(dev, devMeta(linked, true, change))) throw err;\n }\n }\n async linkedDev(path, follow2) {\n if (!follow2) return void 0;\n const real = await physicalLeaf(this.o.fs, path);\n return real !== void 0 && real !== path && kernelDev(real) ? real : void 0;\n }\n async statOf(path, follow2) {\n return follow2 ? await this.o.fs.stat(path) : await this.o.fs.lstat(path);\n }\n async viaDev(path, follow2, stat, device) {\n try {\n return await stat();\n } catch (err) {\n const linked = err.code === \"ENOENT\" && await this.linkedDev(path, follow2);\n if (!linked) throw err;\n return await device(linked, true);\n }\n }\n async devChar(path, follow2) {\n try {\n const json = async (req) => await this.o.kernel.call(req);\n const st = await devSync({ json }, devStat(path, follow2));\n return ((st.mode ?? 0) & 61440) === 8192;\n } catch {\n return false;\n }\n }\n async resolveForDev(path, follow2 = true) {\n try {\n if (!follow2) {\n const slash = path.lastIndexOf(\"/\");\n if (slash <= 0) return void 0;\n const parent = await physicalLeaf(this.o.fs, path.slice(0, slash));\n const resolved3 = parent === void 0 ? void 0 : `${parent}/${path.slice(slash + 1)}`;\n return resolved3 !== void 0 && resolved3 !== path && this.synthetic(resolved3) ? resolved3 : void 0;\n }\n const resolved2 = await physicalLeaf(this.o.fs, path);\n return resolved2 !== void 0 && resolved2 !== path && this.synthetic(resolved2) ? resolved2 : void 0;\n } catch {\n return void 0;\n }\n }\n async writeSiginfo(at, sig, tid, waited = true) {\n const taken = await this.o.kernel.call({ op: \"sig-info\", sig, tid });\n if (!taken && !waited) return false;\n const info = taken ?? KERNEL_SIGINFO;\n const view = this.mem.view();\n const size = Math.min(view.getUint32(at, true), SIGINFO_BYTES);\n const fields = [sig, info.code, info.pid, info.uid, info.status];\n let filled = 4;\n for (const [i, value2] of fields.entries()) {\n if (4 + (i + 1) * 4 > size) break;\n view.setInt32(4 + at + i * 4, value2, true);\n filled = 4 + (i + 1) * 4;\n }\n view.setUint32(at, filled, true);\n return true;\n }\n fdAlias(path) {\n const m = FD_ALIAS.exec(path);\n if (!m) return void 0;\n if (m[1]) return { fd: STDIO_FDS[m[1]], stdio: true };\n if (m[3] !== void 0 && m[3] !== \"self\" && Number(m[3]) !== this.o.pid) return void 0;\n return { fd: Number(m[2] ?? m[4]), stdio: false };\n }\n async openFd(fd) {\n try {\n await this.fds.get(fd);\n } catch {\n throw new WasiError(\"ENOENT\");\n }\n }\n async fdTarget(alias) {\n if (alias.stdio) return `/proc/self/fd/${alias.fd}`;\n await this.openFd(alias.fd);\n const e = await this.fds.get(alias.fd);\n if (e.type === \"file\") return e.file.path;\n if (e.type === \"dir\") return e.path;\n if (e.type === \"device\") return `/dev/${e.device}`;\n const kind = e.type === \"kernel\" ? await this.fds.kind(alias.fd, e) : void 0;\n if (kind === \"file\") {\n const vfs = await this.kernelStat(alias.fd);\n if (vfs.path) return vfs.path;\n }\n if (kind === \"tty\") return \"/dev/tty\";\n if (kind === \"device\") return \"/dev/null\";\n if (kind === \"stream\") {\n const { fifo } = await this.o.kernel.call({ op: \"fd-info\", fd: alias.fd });\n if (fifo !== void 0) return fifo;\n }\n const ino = (await this.fdFilestat(alias.fd)).ino;\n if (kind === \"stream\") return `pipe:[${ino}]`;\n if (kind === \"socket\") return `socket:[${ino}]`;\n return `anon_inode:[${kind ?? \"fd\"}]`;\n }\n async aliasFilestat(path, alias, lookup2) {\n if ((lookup2 & LOOKUP_SYMLINK_FOLLOW) === 0) {\n const target = await this.fdTarget(alias);\n return await this.local({\n filetype: FILETYPE.SYMBOLIC_LINK,\n size: BigInt(new TextEncoder().encode(target).length),\n ino: pathInode(path),\n mtimeNs: 0n\n });\n }\n await this.openFd(alias.fd);\n return await this.fdFilestat(alias.fd);\n }\n async pathFilestat(path, lookup2) {\n const alias = this.fdAlias(path);\n if (alias) return await this.aliasFilestat(path, alias, lookup2);\n if (this.synthetic(path)) {\n return await this.local({\n filetype: FILETYPE.CHARACTER_DEVICE,\n size: 0n,\n ino: pathInode(path),\n mtimeNs: 0n\n });\n }\n await this.fds.flushPath(path);\n const follow2 = (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0;\n try {\n return filestatOf(path, follow2 ? await this.o.fs.stat(path) : await this.o.fs.lstat(path));\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n const device = kernelDev(path) ? path : await this.linkedDev(path, follow2);\n const alias2 = device && device !== path ? this.fdAlias(device) : void 0;\n if (device && alias2) return await this.aliasFilestat(device, alias2, lookup2);\n if (device && await this.devChar(device, true)) {\n return await this.local({\n filetype: FILETYPE.CHARACTER_DEVICE,\n size: 0n,\n ino: pathInode(device),\n mtimeNs: 0n\n });\n }\n const resolved2 = await this.resolveForDev(path, follow2);\n if (!resolved2) throw err;\n return await this.local({\n filetype: FILETYPE.CHARACTER_DEVICE,\n size: 0n,\n ino: pathInode(resolved2),\n mtimeNs: 0n\n });\n }\n }\n async setTimes(path, atim, mtim, flags, follow2 = true) {\n const asked = FSTFLAGS.ATIM | FSTFLAGS.ATIM_NOW | FSTFLAGS.MTIM | FSTFLAGS.MTIM_NOW;\n if (this.o.fs.owners && (flags & asked) === 0) return;\n await this.devChange(\n path,\n follow2,\n timesChange(atim, mtim, flags),\n async () => await this.fileTimes(path, atim, mtim, flags, follow2)\n );\n }\n async fileTimes(path, atim, mtim, flags, follow2) {\n const now = Date.now();\n let current2;\n const statOf = follow2 ? this.o.fs.stat.bind(this.o.fs) : this.o.fs.lstat.bind(this.o.fs);\n const kept = async (field2) => {\n current2 ??= await statOf(path);\n return current2[field2] ?? current2.mtimeMs ?? now;\n };\n const pick = async (set, setNow, value2, field2) => flags & setNow ? now : flags & set ? Number(value2 / NS_PER_MS4) : await kept(field2);\n await (follow2 ? this.o.fs.utimes : this.o.fs.lutimes).call(\n this.o.fs,\n path,\n await pick(FSTFLAGS.ATIM, FSTFLAGS.ATIM_NOW, atim, \"atimeMs\"),\n await pick(FSTFLAGS.MTIM, FSTFLAGS.MTIM_NOW, mtim, \"mtimeMs\"),\n (flags & (FSTFLAGS.ATIM | FSTFLAGS.MTIM)) === 0\n );\n }\n async readdir(fd, buf, len, cookie, usedPtr) {\n const dir = await this.fds.dir(fd);\n if (cookie === 0 || !dir.listing) {\n dir.listing = await this.fds.goneCwd(dir) ? { names: [], stats: /* @__PURE__ */ new Map() } : await this.list(dir.path);\n }\n const { names: names2, stats } = dir.listing;\n let at = 0;\n for (let i = cookie; i < names2.length && at < len; i++) {\n const name2 = names2[i];\n const full = name2 === \".\" ? dir.path : name2 === \"..\" ? normalize(`${dir.path}/..`) : resolveUnder(dir.path, name2);\n if (!stats.has(name2)) stats.set(name2, await this.lstatOrNull(full));\n const st = stats.get(name2) ?? null;\n const record = direntRecord(\n i + 1,\n st?.ino !== void 0 ? BigInt(st.ino) : pathInode(full),\n name2,\n filetypeOf(st)\n );\n const n = Math.min(record.length, len - at);\n this.mem.bytes(buf + at, n).set(record.subarray(0, n));\n at += n;\n }\n this.mem.view().setUint32(usedPtr, at, true);\n }\n async list(path) {\n const { fs } = this.o;\n const listed3 = await fs.readdirStat(path);\n return { names: [\".\", \"..\", ...listed3.map(([name2]) => name2)], stats: new Map(listed3) };\n }\n async lstatOrNull(path) {\n try {\n return await this.o.fs.lstat(path);\n } catch {\n return null;\n }\n }\n async flushAll() {\n await this.fds.flushAll();\n }\n};\nfunction direntRecord(next2, ino, name2, filetype) {\n const nameBytes = new TextEncoder().encode(name2);\n const record = new Uint8Array(SIZE.DIRENT + nameBytes.length);\n const v = new DataView(record.buffer);\n v.setBigUint64(0, BigInt(next2), true);\n v.setBigUint64(8, ino, true);\n v.setUint32(16, nameBytes.length, true);\n v.setUint8(20, filetype);\n record.set(nameBytes, SIZE.DIRENT);\n return record;\n}\nfunction wrap(table) {\n const out = {};\n for (const [name2, fn] of Object.entries(table)) {\n out[name2] = async (...args) => {\n try {\n return await fn(...args) ?? E.SUCCESS;\n } catch (e) {\n if (e instanceof WasiExit) throw e;\n if (e instanceof WasiError) return wasiErrnoOf(e.code);\n const code2 = e?.code;\n if (typeof code2 === \"string\") return wasiErrnoOf(code2);\n if (e instanceof RangeError) return E.FAULT;\n throw e;\n }\n };\n }\n return out;\n}\n\n// src/process/wasi/wasi-procfs.ts\nvar DIR_MODE2 = 16749;\nvar FILE_MODE2 = 33060;\nvar LINK_MODE2 = 41471;\nvar PID_NAMES = PID_FILES;\nvar SYSTEM_NAMES = SYSTEM_FILES;\nfunction inProc(path) {\n return path === \"/proc\" || path.startsWith(\"/proc/\");\n}\nvar ProcTree = class {\n source;\n pid;\n memory;\n constructor(source, pid, memory = memorySource()) {\n this.source = source;\n this.pid = pid;\n this.memory = memory;\n }\n async listing() {\n return await this.source.procList();\n }\n async alive(pid) {\n return (await this.listing()).processes.some((p) => p.pid === pid);\n }\n async node(parts) {\n const [top, leaf, ...rest2] = parts;\n if (top === void 0) {\n return {\n kind: \"dir\",\n names: async () => [\n ...SYSTEM_NAMES,\n \"mounts\",\n \"sys\",\n \"self\",\n ...(await this.listing()).processes.map((p) => String(p.pid))\n ]\n };\n }\n if (top === \"sys\") {\n const entry = sysEntry(parts.slice(1));\n if (typeof entry === \"string\" || typeof entry === \"function\") {\n return { kind: \"file\", content: async () => await sysText(entry, async () => await this.listing()) };\n }\n return entry && { kind: \"dir\", names: () => Object.keys(entry) };\n }\n if (top === \"self\") {\n return leaf === void 0 ? { kind: \"link\", target: String(this.pid) } : void 0;\n }\n if (leaf === void 0 && top === \"mounts\") {\n return { kind: \"file\", content: async () => mountTable(await this.source.mountList()) };\n }\n if (leaf === void 0 && SYSTEM_NAMES.includes(top)) {\n return {\n kind: \"file\",\n content: async () => systemFile(top, await this.listing(), Date.now(), this.memory)\n };\n }\n if (!/^[1-9]\\d*$/.test(top) || !await this.alive(Number(top))) return void 0;\n if (leaf === \"task\") return await this.task(Number(top), rest2);\n if (rest2.length > 0) return void 0;\n if (leaf === void 0) {\n const exe = async () => (await this.info(Number(top)))?.exe === void 0 ? [] : [\"exe\"];\n return { kind: \"dir\", names: async () => [...PID_NAMES, ...await exe(), \"task\"] };\n }\n if (leaf === \"exe\") return await this.exe(Number(top));\n if (!PID_NAMES.includes(leaf)) return void 0;\n return {\n kind: \"file\",\n content: async () => {\n const listing2 = await this.listing();\n const info = listing2.processes.find((p) => p.pid === Number(top));\n if (!info) throw syncError(\"ENOENT\", `/proc/${top}/${leaf}`);\n return pidFile(leaf, info, listing2.boot);\n }\n };\n }\n async exe(pid) {\n const info = await this.info(pid);\n if (info?.exe === void 0) return void 0;\n const denied = !mayTrace(await this.ownInfo(), info);\n const id = info.exeId === void 0 ? {} : { id: info.exeId };\n return { kind: \"link\", target: info.exe, ...denied ? { denied } : {}, ...id };\n }\n async ownInfo() {\n const processes2 = (await this.listing()).processes;\n return processes2.find((p) => p.tid === this.pid) ?? processes2.find((p) => p.pid === this.pid);\n }\n async info(pid) {\n return (await this.listing()).processes.find((p) => p.pid === pid);\n }\n async task(pid, rest2) {\n const [tid, leaf, ...more] = rest2;\n const tids = async () => taskIds(await this.info(pid));\n if (tid === void 0) return { kind: \"dir\", names: async () => (await tids()).map(String) };\n if (!/^[1-9]\\d*$/.test(tid) || more.length > 0 || !(await tids()).includes(Number(tid)))\n return void 0;\n if (leaf === void 0) return { kind: \"dir\", names: () => [\"stat\"] };\n if (leaf !== \"stat\") return void 0;\n return {\n kind: \"file\",\n content: async () => {\n const listing2 = await this.listing();\n const info = listing2.processes.find((p) => p.pid === pid);\n const line = info && taskStat(info, Number(tid), listing2.boot);\n if (line === void 0) throw syncError(\"ENOENT\", `/proc/${pid}/task/${tid}/stat`);\n return line;\n }\n };\n }\n parts(path, follow2) {\n const parts = path.split(\"/\").filter((p) => p !== \"\").slice(1);\n if (parts[0] === \"self\" && (follow2 || parts.length > 1)) parts[0] = String(this.pid);\n return parts;\n }\n async find(path, follow2) {\n const node = await this.node(this.parts(path, follow2));\n if (!node) throw syncError(\"ENOENT\", path);\n return node;\n }\n async stat(path, follow2 = true) {\n const node = await this.find(path, follow2);\n const base = {\n isFile: false,\n isDirectory: false,\n size: 0,\n mtimeMs: Date.now(),\n readonly: true\n };\n if (node.kind === \"dir\") return { ...base, isDirectory: true, mode: DIR_MODE2 };\n if (node.kind === \"link\") {\n return { ...base, isSymbolicLink: true, mode: LINK_MODE2, size: node.target.length };\n }\n return { ...base, isFile: true, mode: FILE_MODE2, size: (await this.bytes(node)).length };\n }\n async bytes(node) {\n return new TextEncoder().encode(node.kind === \"file\" ? await node.content() : \"\");\n }\n async read(path) {\n const node = await this.find(path, true);\n if (node.kind !== \"file\") throw syncError(\"EISDIR\", path);\n return await this.bytes(node);\n }\n async readdir(path) {\n const node = await this.find(path, true);\n if (node.kind !== \"dir\") throw syncError(\"ENOTDIR\", path);\n return await node.names();\n }\n async escape(path) {\n return (await this.escapeTo(path))?.target;\n }\n async escapeTo(path) {\n const node = await this.node(this.parts(path, true));\n if (node?.kind !== \"link\" || !node.target.startsWith(\"/\")) return void 0;\n if (node.denied) throw syncError(\"EACCES\", path);\n return node.id === void 0 ? { target: node.target } : { target: node.target, id: node.id };\n }\n async linkTo(path) {\n const node = await this.node(this.parts(path, false));\n if (node?.kind !== \"link\" || node.id === void 0 || node.denied) return void 0;\n return { target: node.target, id: node.id };\n }\n async readlink(path) {\n const node = await this.find(path, false);\n if (node.kind !== \"link\") throw syncError(\"EINVAL\", path);\n if (node.denied) throw syncError(\"EACCES\", path);\n return node.target;\n }\n async exists(path) {\n try {\n await this.find(path, true);\n return true;\n } catch {\n return false;\n }\n }\n};\nvar FOLLOWING = [\"writeFile\", \"chmod\", \"utimes\", \"pwrite\", \"truncate\"];\nvar NOT_FOLLOWING = [\"mkdir\", \"rm\", \"unlink\", \"rmdir\", \"lutimes\", \"create\", \"mkfifo\"];\nvar MAX_HOPS3 = 40;\nfunction* procWalk(path, follow2) {\n let done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\");\n let hops = 0;\n let broken;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \".\") continue;\n if (part === \"..\") {\n done.pop();\n continue;\n }\n const at = `/${[...done, part].join(\"/\")}`;\n const whole = normalize(`/${[...done, part, ...todo].join(\"/\")}`);\n if (inProc(at) && inProc(whole)) return broken ?? whole;\n if (!follow2 && todo.length === 0) return void 0;\n const target = yield { at, check: todo.find((next2) => next2 !== \".\") === \"..\" };\n if (typeof target === \"string\") {\n if (++hops > MAX_HOPS3) return void 0;\n [done, todo] = throughLink(target, done, todo);\n } else {\n broken ??= refusalOf(target);\n done.push(part);\n }\n }\n return void 0;\n}\nfunction failed(err) {\n const code2 = err?.code;\n return { refused: typeof code2 === \"string\" ? code2 : \"ENOENT\" };\n}\nfunction refusalOf(found) {\n if (found === true) return void 0;\n return found === false ? { refused: \"ENOTDIR\" } : found;\n}\nfunction throughLink(target, done, todo) {\n const parts = target.split(\"/\").filter((part) => part !== \"\");\n return [target.startsWith(\"/\") ? [] : done, [...parts, ...todo]];\n}\nasync function procPath(fs, path, follow2) {\n const walk2 = procWalk(path, follow2);\n let step = walk2.next();\n while (!step.done) {\n const { at, check } = step.value;\n let target;\n try {\n const st = await fs.lstat(at);\n target = st.isSymbolicLink ? await fs.readlink(at) : !check || st.isDirectory;\n } catch (err) {\n target = failed(err);\n }\n step = walk2.next(target);\n }\n const result = step.value;\n if (typeof result === \"object\") throw syncError(result.refused, path);\n return result;\n}\nfunction frozen(bytes) {\n const refuse2 = () => {\n throw syncError(\"EROFS\", \"/proc\");\n };\n return {\n readFile: () => bytes,\n pread: (_p, at, n) => bytes.subarray(at, at + n),\n writeFile: refuse2,\n pwrite: refuse2,\n truncate: refuse2\n };\n}\nfunction physicalProc(fs, now = () => performance.now()) {\n const view = fs.changes;\n let seen;\n return async () => {\n if (seen && view && (!view.foreign() || now() - seen.at < SHARED_TTL_MS)) {\n const proc = view.changedSince(seen.gen, \"/proc\");\n if (!proc.changed && !view.changedSince(seen.gen, \"/\").changed) {\n seen.gen = proc.now;\n return seen.physical;\n }\n }\n const gen = view?.now();\n const at = now();\n let physical2;\n try {\n await fs.stat(\"/proc\");\n physical2 = true;\n } catch (err) {\n const code2 = err.code;\n if (code2 !== \"ENOENT\" && code2 !== \"ENOTDIR\") {\n seen = void 0;\n return false;\n }\n physical2 = false;\n }\n seen = gen === void 0 ? void 0 : { gen, physical: physical2, at };\n return physical2;\n };\n}\nfunction directMiss(err, path) {\n if (err?.direct !== true) return false;\n return !path.split(\"/\").some((part) => part === \".\" || part === \"..\");\n}\nvar GONE2 = /* @__PURE__ */ new Set([\"ENOENT\", \"ENOTDIR\"]);\nasync function same(fs, path, id) {\n let st;\n try {\n st = await fs.stat(path);\n } catch (err) {\n if (GONE2.has(err?.code ?? \"\")) return false;\n throw err;\n }\n if (id.startsWith(\"fid:\")) return st.fid !== void 0 && id.startsWith(`fid:${st.fid}:`);\n const now = fileIdentity(st.ino, st.mtimeMs);\n return now === void 0 || now === id;\n}\nasync function current(fs, tree, q) {\n const to = await tree.escapeTo(q);\n if (!to || to.id === void 0) return to?.target;\n if (!await same(fs, to.target, to.id)) throw syncError(\"ENOENT\", q);\n return to.target;\n}\nfunction guard(toProc, shadowing) {\n return async (paths, run) => {\n const physical2 = await shadowing();\n for (const [p, follow2] of paths) {\n if (inProc(p) || physical2 && await toProc(p, follow2) !== void 0) throw syncError(\"EROFS\", p);\n }\n return await run();\n };\n}\nasync function shownLink(fs, tree, q) {\n const target = await tree.readlink(q);\n const to = await tree.linkTo(q);\n if (!to) return target;\n try {\n return await same(fs, to.target, to.id) ? target : `${target} (deleted)`;\n } catch {\n return target;\n }\n}\nfunction routing(fs, tree, toProc, shadowing) {\n return async (p, inner, own, follow2 = true, outside) => {\n const proc = async (q) => {\n const target = outside ? await current(fs, tree, q) : void 0;\n return target === void 0 ? await inner(q) : await outside(target);\n };\n if (inProc(p)) return await proc(p);\n if (await shadowing()) {\n const real = await toProc(p, follow2);\n if (real !== void 0) return await proc(real);\n }\n try {\n return await own();\n } catch (err) {\n if (directMiss(err, p)) throw err;\n const real = await toProc(p, follow2);\n if (real === void 0) throw err;\n return await proc(real);\n }\n };\n}\nfunction procfsBridge(fs, tree) {\n const toProc = async (path, follow2) => await procPath(fs, path, follow2);\n const shadowing = physicalProc(fs);\n const via = routing(fs, tree, toProc, shadowing);\n const readOnly = guard(toProc, shadowing);\n const snapshots = /* @__PURE__ */ new Map();\n let lastSnapshot = 0;\n const snapshot = async (q) => {\n lastSnapshot--;\n snapshots.set(lastSnapshot, await tree.read(q));\n return lastSnapshot;\n };\n const late = async (p) => {\n const q = await toProc(p, true);\n return q === void 0 ? void 0 : await snapshot(q);\n };\n const over = {\n readFile: async (p) => await via(\n p,\n async (q) => await tree.read(q),\n async () => await fs.readFile(p),\n true,\n async (t) => await fs.readFile(t)\n ),\n stat: async (p) => await via(\n p,\n async (q) => await tree.stat(q),\n async () => await fs.stat(p),\n true,\n async (t) => ({ ...await fs.stat(t), escape: t })\n ),\n lstat: async (p) => await via(\n p,\n async (q) => await tree.stat(q, false),\n async () => await fs.lstat(p),\n false\n ),\n readdir: async (p) => await via(\n p,\n async (q) => await tree.readdir(q),\n async () => {\n const names2 = await fs.readdir(p);\n return p === \"/\" && !names2.includes(\"proc\") ? [...names2, \"proc\"] : names2;\n }\n ),\n exists: async (p) => {\n if (inProc(p)) return await tree.exists(p);\n const probe = async () => {\n try {\n return await toProc(p, true);\n } catch {\n return null;\n }\n };\n const real = await shadowing() ? await probe() : void 0;\n if (real === null) return false;\n if (real !== void 0) return await tree.exists(real);\n try {\n await fs.stat(p);\n return true;\n } catch (err) {\n if (directMiss(err, p)) return false;\n }\n const late2 = await probe();\n return typeof late2 === \"string\" && await tree.exists(late2);\n },\n readlink: async (p) => await via(\n p,\n async (q) => await shownLink(fs, tree, q),\n async () => await fs.readlink(p),\n false\n ),\n readdirStat: async (p) => await via(\n p,\n async (q) => {\n const listed3 = [];\n for (const name2 of await tree.readdir(q)) {\n try {\n listed3.push([name2, await tree.stat(`${q}/${name2}`, false)]);\n } catch {\n listed3.push([name2, null]);\n }\n }\n return listed3;\n },\n async () => {\n const listed3 = await fs.readdirStat(p);\n if (p !== \"/\" || listed3.some(([name2]) => name2 === \"proc\")) return listed3;\n return [...listed3, [\"proc\", await tree.stat(\"/proc\")]];\n }\n ),\n rename: async (from, to) => await readOnly(\n [\n [from, false],\n [to, false]\n ],\n async () => await fs.rename(from, to)\n ),\n symlink: async (target, link) => await readOnly([[link, false]], async () => await fs.symlink(target, link)),\n link: async (from, to, follow2) => await readOnly(\n [\n [from, follow2 === true],\n [to, false]\n ],\n async () => await fs.link(from, to, follow2)\n ),\n hold: async (p, held, open, handle, want, seen) => {\n if (handle !== void 0 && snapshots.delete(handle)) return void 0;\n if (!held) return await fs.hold?.(p, held, open, handle);\n return await via(p, snapshot, async () => await fs.hold?.(p, held, open, void 0, want, seen) ?? await late(p));\n },\n kept: async (handle) => snapshots.has(handle) || await fs.kept?.(handle) === true,\n escape: async (p) => inProc(p) ? await current(fs, tree, p) : void 0,\n pinned: async (handle) => {\n const bytes = snapshots.get(handle);\n return bytes ? frozen(bytes) : await fs.pinned?.(handle) ?? fs;\n },\n ...fs.pread ? {\n pread: async (p, at, n, version) => await via(\n p,\n async (q) => (await tree.read(q)).subarray(at, at + n),\n async () => await fs.pread(p, at, n, version)\n )\n } : {}\n };\n for (const [names2, follow2] of [\n [FOLLOWING, true],\n [NOT_FOLLOWING, false]\n ]) {\n for (const name2 of names2) {\n const fn = fs[name2];\n if (!fn) continue;\n over[name2] = (async (p, ...rest2) => await readOnly([[p, follow2]], async () => await fn.call(fs, p, ...rest2)));\n }\n }\n const { chown: chown2 } = fs;\n if (chown2) {\n over.chown = async (p, ...rest2) => await readOnly([[p, rest2[2] === true]], async () => await chown2.call(fs, p, ...rest2));\n }\n return new Proxy(fs, {\n get: (target, key, receiver) => key in over ? over[key] : Reflect.get(target, key, receiver)\n });\n}\n\n// src/process/wasi/wasi-ptsfs.ts\nvar PTS = \"/dev/pts\";\nvar PTS_ENTRY = /^\\/dev\\/pts\\/(\\d+)$/;\nvar SERIAL_AREA = /^\\/dev\\/(?:tty(?:USB|ACM)\\d+|serial(?:\\/.*)?)$/;\nfunction ptsBridge(fs, call2) {\n const open = async () => await call2({ op: \"pty-list\" });\n const kernel = { json: async (req) => await call2(req) };\n const entry = async (p, given) => {\n const known = given === void 0 ? await open() : given;\n const n = PTS_ENTRY.exec(p)?.[1];\n if (n === void 0 || !known.includes(Number(n))) throw syncError(\"ENOENT\", p);\n return await devSync(kernel, devStat(p, true));\n };\n const listedEntry = async (name2, known) => {\n try {\n return [name2, await entry(`${PTS}/${name2}`, known)];\n } catch {\n return [name2, null];\n }\n };\n const dir = async () => await devSync(kernel, devStat(PTS, true));\n const statOf = async (p, real, follow2 = true) => {\n if (p === PTS) return await dir();\n if (SERIAL_AREA.test(p)) return await devSync(kernel, devStat(p, follow2));\n return PTS_ENTRY.test(p) ? await entry(p) : await real();\n };\n const serialNames = async () => (await devSync(kernel, devReaddir(\"/dev\"))).filter((n) => SERIAL_AREA.test(`/dev/${n}`));\n const withSerial = async (listed3) => [\n ...listed3,\n ...(await serialNames()).filter((n) => !listed3.includes(n))\n ];\n const names2 = async (given) => (given === void 0 ? await open() : given).map(String).sort();\n const serialEntry = async (p, name2) => {\n try {\n return [name2, await devSync(kernel, devStat(p, false))];\n } catch {\n return [name2, null];\n }\n };\n const over = {\n stat: async (p) => await statOf(p, async () => await fs.stat(p)),\n lstat: async (p) => await statOf(p, async () => await fs.lstat(p), false),\n readlink: async (p) => SERIAL_AREA.test(p) ? await devSync(kernel, devReadlink(p)) : await fs.readlink(p),\n exists: async (p) => {\n if (p === PTS) return true;\n if (SERIAL_AREA.test(p)) {\n try {\n await devSync(kernel, devStat(p, true));\n return true;\n } catch {\n return false;\n }\n }\n if (!PTS_ENTRY.test(p)) return await fs.exists(p);\n return (await open()).includes(Number(PTS_ENTRY.exec(p)?.[1]));\n },\n readdir: async (p) => {\n if (p === PTS) return await names2();\n if (SERIAL_AREA.test(p)) return await devSync(kernel, devReaddir(p));\n const listed3 = await fs.readdir(p);\n if (p !== \"/dev\") return listed3;\n return await withSerial(listed3.includes(\"pts\") ? listed3 : [...listed3, \"pts\"]);\n },\n readdirStat: async (p) => {\n if (p === PTS) {\n const known = await open();\n const listed4 = [];\n for (const name2 of await names2(known)) listed4.push(await listedEntry(name2, known));\n return listed4;\n }\n if (SERIAL_AREA.test(p)) {\n const serial = [];\n for (const name2 of await devSync(kernel, devReaddir(p))) {\n serial.push(await serialEntry(`${p}/${name2}`, name2));\n }\n return serial;\n }\n const listed3 = await fs.readdirStat(p);\n if (p !== \"/dev\") return listed3;\n const all = listed3.some(([name2]) => name2 === \"pts\") ? [...listed3] : [...listed3, [\"pts\", await dir()]];\n const have = all.map(([name2]) => name2);\n for (const name2 of await serialNames()) {\n if (!have.includes(name2)) all.push(await serialEntry(`/dev/${name2}`, name2));\n }\n return all;\n }\n };\n return new Proxy(fs, {\n get(target, key, receiver) {\n if (Object.hasOwn(over, key)) return over[key];\n const value2 = Reflect.get(target, key, receiver);\n return typeof value2 === \"function\" ? value2.bind(target) : value2;\n }\n });\n}\n\n// src/process/raw-stack.ts\nvar reader = (error) => error.stack;\nfunction rawStack(error) {\n const stack = reader(error);\n return typeof stack === \"string\" ? stack : void 0;\n}\n\n// src/process/wasi/dylink.ts\nvar MEM_INFO = 1;\nvar NEEDED = 2;\nvar RUNTIME_PATH = 5;\nfunction dylinkInfo(module) {\n const [section2] = WebAssembly.Module.customSections(module, \"dylink.0\");\n if (!section2) return void 0;\n const bytes = new Uint8Array(section2);\n let at = 0;\n const uleb = () => {\n let value2 = 0;\n let shift = 0;\n for (; ; ) {\n const b = bytes[at++];\n value2 += (b & 127) * 2 ** shift;\n if (!(b & 128)) return value2;\n shift += 7;\n }\n };\n const string = () => {\n const len = uleb();\n const s = new TextDecoder().decode(bytes.subarray(at, at + len));\n at += len;\n return s;\n };\n const info = {\n memorySize: 0,\n memoryAlign: 0,\n tableSize: 0,\n tableAlign: 0,\n needed: [],\n runtimePath: []\n };\n while (at < bytes.length) {\n const kind = bytes[at++];\n const len = uleb();\n const end = at + len;\n if (kind === MEM_INFO) {\n info.memorySize = uleb();\n info.memoryAlign = uleb();\n info.tableSize = uleb();\n info.tableAlign = uleb();\n } else if (kind === NEEDED) {\n for (let n = uleb(); n > 0; n--) info.needed.push(string());\n } else if (kind === RUNTIME_PATH) {\n for (let n = uleb(); n > 0; n--) info.runtimePath.push(string());\n }\n at = end;\n }\n return info;\n}\n\n// src/process/wasi/wasi-threads.ts\nvar LAST_TID = 0;\nvar RUNNING = 1;\nvar MAIN_TID = 1;\nvar ThreadExit = class extends Error {\n constructor() {\n super(\"thread exit\");\n }\n};\nfunction threadCap(env) {\n const asked = Number.parseInt(env.SLICC_WASM_THREADS ?? \"\", 10);\n return asked >= 1 ? Math.min(asked, WASM_MAX_THREADS) : WASM_DEFAULT_THREADS;\n}\nvar WasiThreads = class {\n ids;\n beforeSpawn;\n modules;\n received;\n blocked;\n port;\n memory;\n cap;\n tid;\n constructor(port, memory, cap, tid, ids) {\n this.port = port;\n this.memory = memory;\n this.cap = cap;\n this.tid = tid;\n this.ids = new Int32Array(ids ?? new SharedArrayBuffer(SHARED_IDS_BYTES));\n if (!ids) Atomics.store(this.ids, LAST_TID, MAIN_TID);\n }\n async spawn(arg) {\n if (Atomics.add(this.ids, RUNNING, 1) + 1 >= this.cap) {\n Atomics.sub(this.ids, RUNNING, 1);\n return -1;\n }\n await this.beforeSpawn?.();\n const tid = Atomics.add(this.ids, LAST_TID, 1) + 1;\n const modules = this.modules?.();\n const blocked = this.blocked?.();\n this.port.postMessage({\n type: WASM_THREAD_SPAWN,\n thread: {\n tid,\n arg,\n memory: this.memory,\n ids: this.ids.buffer,\n ...modules ? { modules } : {},\n ...anyBlocked(blocked) ? { blocked } : {}\n }\n });\n return tid;\n }\n exited() {\n Atomics.sub(this.ids, RUNNING, 1);\n this.port.postMessage({ type: WASM_THREAD_EXIT });\n }\n known(tid) {\n return tid >= MAIN_TID && tid <= Atomics.load(this.ids, LAST_TID);\n }\n parallelism() {\n const cores = globalThis.navigator?.hardwareConcurrency;\n return Math.max(1, Math.min(this.cap, cores ?? this.cap));\n }\n};\n\n// src/process/wasi/wasix-process.ts\nasync function restarted(issue) {\n for (; ; ) {\n try {\n return await issue();\n } catch (e) {\n if (e?.code !== \"EINTR\") throw e;\n }\n }\n}\nfunction resolveFrom(cwd, path) {\n return normalize(path.startsWith(\"/\") ? path : `${cwd}/${path}`);\n}\nvar O_WRONLY2 = 1;\nvar O_RDWR2 = 2;\nvar O_APPEND2 = 1024;\nvar OFLAG_CREAT = 1;\nvar OFLAG_TRUNC = 8;\nvar JOIN_NON_BLOCKING = 1;\nvar JOIN_WAKE_STOPPED = 2;\nvar JOIN_STOPPED = 3;\nvar WasixProcess = class {\n host;\n driver;\n inThread;\n constructor(host, driver, inThread = () => false) {\n this.host = host;\n this.driver = driver;\n this.inThread = inThread;\n }\n restart() {\n return this.inThread() ? {} : { restart: true };\n }\n async call(req) {\n return await this.host.o.kernel.call(req);\n }\n async environment() {\n return { ...this.host.o.env, PWD: await this.host.workingDir() };\n }\n async locate(name2, search, path) {\n if (name2.includes(\"/\"))\n return name2.startsWith(\"/\") ? name2 : normalize(`${await this.host.workingDir()}/${name2}`);\n if (!search) return name2;\n for (const dir of path.split(\":\")) {\n if (!dir) continue;\n const candidate = normalize(\n `${dir.startsWith(\"/\") ? \"\" : `${await this.host.workingDir()}/`}${dir}/${name2}`\n );\n if (await this.host.o.fs.exists(candidate)) return candidate;\n }\n return name2;\n }\n async childFds(ops) {\n const { fds } = this.host;\n await fds.promoteFiles();\n const map = await fds.inheritable();\n const nulls = /* @__PURE__ */ new Set();\n const opened = [];\n let cwd = await this.host.workingDir();\n try {\n for (const op of ops) cwd = await this.applyFdOp(op, { map, nulls, opened }, cwd);\n } catch (e) {\n for (const kfd of opened) await this.host.o.kernel.sys.close(kfd);\n throw e;\n }\n const stdio = [0, 1, 2].map((fd) => {\n const k = map.get(fd);\n return k === void 0 ? { none: true } : { fd: k };\n });\n const inherit = [\n ...[...map].filter(([fd]) => fd > 2).map(([fd, kernel]) => ({ fd, kernel })),\n ...[...nulls].filter((fd) => fd > 2).map((fd) => ({ fd, device: \"null\" }))\n ];\n return { stdio, inherit, cwd, opened };\n }\n async applyFdOp(op, slots2, cwd) {\n const { map, nulls, opened } = slots2;\n const { fds } = this.host;\n const point = (fd, kfd) => {\n if (kfd === void 0) {\n map.delete(fd);\n nulls.add(fd);\n } else {\n map.set(fd, kfd);\n nulls.delete(fd);\n }\n };\n if (op.cmd === \"close\") {\n map.delete(op.fd);\n nulls.delete(op.fd);\n } else if (op.cmd === \"dup2\" && nulls.has(op.srcFd)) point(op.fd, void 0);\n else if (op.cmd === \"dup2\") {\n const src = map.get(op.srcFd) ?? ((await fds.find(op.srcFd))?.type === \"kernel\" ? op.srcFd : void 0);\n if (src === void 0) throw Object.assign(new Error(\"EBADF\"), { code: \"EBADF\" });\n point(op.fd, src);\n } else if (op.cmd === \"open\" && resolveFrom(cwd, op.path) === \"/dev/null\") {\n point(op.fd, void 0);\n } else if (op.cmd === \"open\") {\n const kfd = await this.openFor(op, cwd);\n opened.push(kfd);\n point(op.fd, kfd);\n } else if (op.cmd === \"chdir\") return await this.physicalFrom(cwd, op.path);\n else return await physicalPath(this.host.o.fs, (await fds.dir(op.fd)).path);\n return cwd;\n }\n async physicalFrom(cwd, path) {\n return await physicalPath(this.host.o.fs, path.startsWith(\"/\") ? path : `${cwd}/${path}`);\n }\n async openFor(op, cwd) {\n const path = resolveFrom(cwd, op.path);\n const create = (op.oflags & OFLAG_CREAT) !== 0;\n if (!create && !await this.host.o.fs.exists(path)) {\n throw Object.assign(new Error(\"ENOENT\"), { code: \"ENOENT\" });\n }\n const flags = (op.rightsWrite ? O_RDWR2 : 0) | (op.append ? O_APPEND2 : 0);\n return await this.host.o.kernel.sys.openVfs(path, op.rightsWrite ? flags || O_WRONLY2 : 0, 0, {\n ...create ? { create } : {},\n ...op.oflags & OFLAG_TRUNC ? { truncate: true } : {}\n });\n }\n async spawn(req, exec = false) {\n const ops = req.ops ?? [];\n const { stdio, inherit, cwd, opened } = await this.childFds(ops);\n const moved = ops.some((op) => op.cmd === \"chdir\" || op.cmd === \"fchdir\");\n try {\n const spawn = {\n op: \"proc-spawn\",\n file: await this.locate(req.name, req.search, req.path),\n ...req.search ? {} : { search: false },\n argv: req.argv.length > 0 ? req.argv : [req.name],\n env: req.env ?? await this.environment(),\n cwd,\n ...moved ? { chdir: true } : {},\n stdio,\n inherit,\n ...exec ? { exec } : {},\n ...this.restart()\n };\n return await restarted(async () => await this.call(spawn));\n } finally {\n for (const kfd of opened) await this.host.o.kernel.sys.close(kfd);\n this.host.o.fs.invalidate?.();\n }\n }\n async exec(req) {\n const pid = await this.spawn(req, true);\n const [, status2] = await this.call({ op: \"proc-exec\", pid });\n const sig = status2 & 127;\n throw new WasiExit(sig ? 128 + sig : status2 >> 8 & 255);\n }\n async join(pidPtr, flags, statusPtr) {\n const v = this.host.mem.view();\n const pid = v.getUint8(pidPtr) === 1 ? v.getUint32(pidPtr + 4, true) : -1;\n this.host.mem.bytes(statusPtr, 6).fill(0);\n const [child, status2] = await this.call({\n op: \"proc-wait\",\n pid,\n nohang: (flags & JOIN_NON_BLOCKING) !== 0,\n ...flags & JOIN_WAKE_STOPPED ? { untraced: true } : {}\n });\n if (child === 0) return;\n this.host.o.fs.invalidate?.();\n v.setUint8(pidPtr, 1);\n v.setUint32(pidPtr + 4, child, true);\n const sig = status2 & 127;\n if (sig === 127) {\n v.setUint8(statusPtr, JOIN_STOPPED);\n v.setUint8(statusPtr + 2, status2 >> 8 & 255);\n } else if (sig) {\n v.setUint8(statusPtr, 2);\n v.setUint8(statusPtr + 4, sig);\n } else {\n v.setUint8(statusPtr, 1);\n v.setUint16(statusPtr + 2, status2 >> 8 & 255, true);\n }\n }\n fork(pidPtr) {\n const back = this.driver.rewound();\n if (back !== void 0) {\n this.host.mem.view().setUint32(pidPtr, back, true);\n return void 0;\n }\n return this.driver.fork(\n async (asyncifyData, globals, forkSp) => await restarted(async () => await this.forkCall(asyncifyData, globals, forkSp))\n );\n }\n async forkCall(asyncifyData, globals, forkSp) {\n const { fds } = this.host;\n await fds.promoteFiles();\n const memory = this.host.mem.bytes(0, this.host.mem.size()).slice();\n const wasi = {\n asyncifyData,\n globals,\n fds: fds.snapshot(),\n cloexec: [...fds.cloexec],\n cwd: await this.host.workingDir(),\n ...fds.isShared ? { shared: true } : {},\n setjmps: this.driver.setjmps(),\n ...this.host.signals ? { signals: this.host.signals.snapshot() } : {},\n ...this.host.sigmask ? { blocked: this.host.sigmask.inherited() } : {},\n ...this.host.linkedTls ? { tls: this.host.linkedTls() } : {},\n ...this.host.linkedModules ? { modules: this.host.linkedModules() } : {}\n };\n if (this.host.threadEntry) wasi.entry = this.host.threadEntry;\n return await this.call({\n op: \"proc-fork\",\n state: { memory, currData: 0, forkSp, callStackNames: [], ppid: this.host.o.pid, wasi },\n ...this.restart()\n });\n }\n};\n\n// src/process/wasi/wasi-imports.ts\nvar UID = 1e3;\nfunction base64(text) {\n const bytes = new TextEncoder().encode(text);\n let binary = \"\";\n for (let at = 0; at < bytes.length; at += 32768) {\n binary += String.fromCharCode(...bytes.subarray(at, at + 32768));\n }\n return btoa(binary);\n}\nfunction importSource(source) {\n return refusedImport(`data:text/javascript;base64,${base64(source)}`);\n}\nasync function loadImports(source) {\n const loaded = await importSource(source);\n if (typeof loaded.createImports !== \"function\") {\n throw new Error(\"the imports module exports no createImports function\");\n }\n return loaded.createImports;\n}\nfunction value(result) {\n if (!result.ok) throw new WasiError(result.errno);\n if (result.kind === \"json\") return result.json;\n return result.kind === \"bytes\" ? result.bytes : void 0;\n}\nfunction code(err) {\n const c = err?.code;\n return typeof c === \"string\" ? c : void 0;\n}\nfunction importsContext({\n host,\n raw,\n tid,\n memory,\n instance\n}) {\n const { fs } = host.o;\n const call2 = async (req) => value(await raw(req));\n const pathOf = async (fd) => {\n const e = await host.fds.get(fd);\n if (e.type === \"file\") return e.file.path;\n if (e.type === \"dir\") return e.path;\n if (e.type === \"kernel\" && await host.fds.kind(fd, e) === \"file\") {\n return (await call2({ op: \"fd-vfs-stat\", fd })).path;\n }\n return void 0;\n };\n const sizedOf = async (fd) => {\n const e = await host.fds.get(fd);\n if (e.type === \"file\") return { path: e.file.path, size: await e.file.size() };\n if (e.type === \"kernel\" && await host.fds.kind(fd, e) === \"file\") {\n return await call2({ op: \"fd-vfs-stat\", fd });\n }\n return { path: await pathOf(fd) };\n };\n const requirePath = async (fd) => {\n const path = await pathOf(fd);\n if (path === void 0) throw new WasiError(\"EBADF\");\n return path;\n };\n const owners = fs.owners === true;\n const live = async () => {\n if (!owners) return { uid: UID, gid: UID };\n const cred = await call2({ op: \"proc-cred\" });\n return { uid: cred.euid, gid: cred.egid };\n };\n const fds = {\n async open(path, o = {}) {\n const abs = await host.fds.resolve(3, path);\n const fresh = o.create === true && o.exclusive === true && owners && fs.create !== void 0;\n const existed = !fresh && await fs.exists(abs);\n const oflags = (o.create ? OFLAGS.CREAT : 0) | (o.exclusive ? OFLAGS.EXCL : 0) | (o.truncate ? OFLAGS.TRUNC : 0) | (o.directory ? OFLAGS.DIRECTORY : 0);\n const rights = (o.write ? RIGHTS.FD_WRITE : 0n) | (o.read || !o.write ? RIGHTS.FD_READ : 0n);\n const flags = o.append ? FDFLAGS.APPEND : 0;\n const fd = await host.fds.open(\n abs,\n oflags,\n rights,\n flags,\n fresh ? o.mode : void 0,\n o.nofollow === true\n );\n if (o.mode !== void 0 && !existed && !fresh) await fs.chmod(abs, o.mode);\n return fd;\n },\n async close(fd) {\n await host.fds.close(fd);\n },\n async fstat(fd) {\n const e = await host.fds.get(fd);\n const { path, size } = await sizedOf(fd);\n if (path === void 0) {\n const kind = e.type === \"device\" ? \"device\" : \"stream\";\n return { kind, mode: kind === \"device\" ? 8630 : 4480, ...await live(), size: 0 };\n }\n if (size === void 0) await host.fds.flushPath(path);\n const s = await fs.stat(path);\n return {\n kind: s.isDirectory ? \"dir\" : \"file\",\n path,\n mode: s.mode ?? (s.isDirectory ? 16877 : 33188),\n ...s.uid !== void 0 && s.gid !== void 0 ? { uid: s.uid, gid: s.gid } : await live(),\n size: size ?? s.size,\n ...s.ino !== void 0 ? { ino: s.ino } : {},\n ...s.mtimeMs !== void 0 ? { mtimeMs: s.mtimeMs } : {}\n };\n },\n async fchmod(fd, mode) {\n await fs.chmod(await requirePath(fd), mode);\n },\n async tryLock(fd, exclusive) {\n const path = await requirePath(fd);\n await host.fds.promote(fd);\n try {\n await call2({ op: \"lock\", path, exclusive, fd });\n } catch (err) {\n if (code(err) === \"EAGAIN\") return E.AGAIN;\n throw err;\n }\n return E.SUCCESS;\n },\n async unlock(fd) {\n await call2({ op: \"unlock\", path: await requirePath(fd), fd });\n }\n };\n const ctx = {\n memory,\n instance,\n tid,\n argv: host.o.args,\n env: host.o.env,\n cwd: async () => await host.workingDir(),\n fs: Object.assign(Object.create(fs), {\n async copyFile(from, to, options = {}) {\n const at = async (p) => await host.fds.resolve(3, p.startsWith(\"/\") ? p : `${await host.workingDir()}/${p}`);\n await host.copyFile(await at(from), await at(to), options.mode ?? 438, options.excl === true);\n }\n }),\n fds,\n syscall: async (req) => req.op === \"proc-umask\" ? await host.umask(req.mask) : await call2(req),\n net: network(raw, call2),\n ...processes(host, call2, tid !== MAIN_TID),\n async: {\n submit: async (req) => await call2({ op: \"async-submit\", req }),\n async wait(timeoutMs2) {\n for (; ; ) {\n try {\n return await call2({\n op: \"async-wait\",\n ...timeoutMs2 !== void 0 ? { timeoutMs: timeoutMs2 } : {}\n });\n } catch (err) {\n if (code(err) !== \"EINTR\") throw err;\n if (timeoutMs2 !== void 0) return 0;\n }\n }\n },\n async take(id) {\n const result = await raw({ op: \"async-take\", id });\n if (!result.ok && result.errno === \"EAGAIN\") return void 0;\n if (!result.ok) return { error: result.errno };\n return { value: value(result) };\n },\n resolve: async (v) => await call2({ op: \"async-resolve\", value: v }),\n hold: async () => await call2({ op: \"async-hold\" }),\n cancel: async (id) => void await raw({ op: \"async-cancel\", id }),\n close: async () => void await call2({ op: \"async-close\" })\n },\n errno: (err) => wasiErrnoOf(code(err))\n };\n if (!owners) return ctx;\n return Object.defineProperties(ctx, {\n uid: { get: async () => (await live()).uid, enumerable: true },\n gid: { get: async () => (await live()).gid, enumerable: true }\n });\n}\nvar LOOPBACK2 = /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nvar SOL_SOCKET = 1;\nvar SO_ERROR = 4;\nfunction loopbackHost(host) {\n if (host === \"localhost\") return \"127.0.0.1\";\n if (typeof host === \"string\" && LOOPBACK2.test(host)) return host;\n throw new WasiError(\"EINVAL\");\n}\nfunction network(raw, call2) {\n return {\n async connect({ host, port, nonblock = false }) {\n const to = loopbackHost(host);\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new WasiError(\"EINVAL\");\n const fd = await call2({ op: \"sock-open\", domain: \"inet\" });\n const addr = { family: \"inet\", host: to, port };\n const r = await raw({ op: \"sock-connect\", fd, addr, ...nonblock ? { nonblock: true } : {} });\n if (r.ok || nonblock && r.errno === \"EINPROGRESS\") return fd;\n await raw({ op: \"fd-close\", fd });\n throw new WasiError(r.errno);\n },\n async ready(fd) {\n const sel = await call2({ op: \"fd-select\", read: [], write: [fd], timeoutMs: 0 });\n if (!sel.write.includes(fd)) return E.INPROGRESS;\n return await call2({ op: \"sock-getopt\", fd, level: SOL_SOCKET, name: SO_ERROR });\n }\n };\n}\nvar STDIO2 = [\"stdin\", \"stdout\", \"stderr\"];\nfunction processes(host, call2, inThread) {\n const close = async (fd) => void await call2({ op: \"fd-close\", fd });\n const slot2 = async (n, how, mine, theirs) => {\n if (how === \"inherit\") return { fd: n };\n if (how === \"null\") return { none: true };\n const [read2, write2] = await call2({ op: \"fd-pipe\" });\n mine[n] = n === 0 ? write2 : read2;\n theirs.push(n === 0 ? read2 : write2);\n return { fd: n === 0 ? read2 : write2 };\n };\n return {\n async spawn(o) {\n const mine = [];\n const theirs = [];\n await host.fds.promoteFiles();\n try {\n const stdio = [];\n for (const [n, name2] of STDIO2.entries())\n stdio.push(await slot2(n, o[name2] ?? \"inherit\", mine, theirs));\n const req = {\n op: \"proc-spawn\",\n file: o.argv[0],\n argv: o.argv,\n env: o.env ?? { ...host.o.env },\n cwd: o.cwd ?? await host.workingDir(),\n ...o.cwd !== void 0 ? { chdir: true } : {},\n stdio,\n ...inThread ? {} : { restart: true }\n };\n const pid = await restarted(async () => await call2(req));\n const out = { pid };\n STDIO2.forEach((name2, n) => {\n if (mine[n] !== void 0) out[name2] = mine[n];\n });\n return out;\n } catch (err) {\n for (const fd of mine) if (fd !== void 0) await close(fd);\n throw err;\n } finally {\n for (const fd of theirs) await close(fd);\n host.o.fs.invalidate?.();\n }\n },\n async wait(pid) {\n for (; ; ) {\n try {\n const [, status2] = await call2({ op: \"proc-wait\", pid, nohang: false });\n host.o.fs.invalidate?.();\n const signal = status2 & 127;\n return signal ? { status: 128 + signal, signal } : { status: status2 >> 8 & 255 };\n } catch (err) {\n if (code(err) !== \"EINTR\") throw err;\n }\n }\n },\n async kill(pid, sig) {\n await call2({ op: \"proc-kill\", pid, sig });\n }\n };\n}\n\n// src/process/wasi/wasi-module.ts\nvar RESERVED_NAMESPACES = /* @__PURE__ */ new Set([\n \"wasi_snapshot_preview1\",\n \"wasix_32v1\",\n \"wasi\",\n \"env\"\n]);\nvar LIBC_MARK = /^wasix-sysroot \\d{4}\\.\\d+\\.\\d+-(\\d+)/;\nfunction libcOf(sections) {\n for (const section2 of sections) {\n const found = LIBC_MARK.exec(new TextDecoder().decode(section2));\n if (found) return Number(found[1]);\n }\n return void 0;\n}\nfunction libcVersion(module) {\n return libcOf(WebAssembly.Module.customSections(module, \"slicc.libc\"));\n}\n\n// src/process/wasi/wasi-signals.ts\nvar DELIVERED_MASK = Object.values(SIG).filter((sig) => sig !== SIG.KILL && sig !== SIG.STOP).reduce((m, sig) => m | sigbit(sig), 0);\nvar KERNEL_DEFAULTS = [SIG.TSTP, SIG.TTIN, SIG.TTOU, SIG.CHLD, SIG.CONT, SIG.URG, SIG.WINCH].map(sigbit).reduce((m, bit) => m | bit, 0);\nvar LIBC_DEFAULT_EXIT = 127;\nvar SA_RESTART = 268435456;\nvar SA_NODEFER = 1073741824;\nvar SA_NOCLDWAIT = 2;\nvar DISPOSITION_IGNORE = 1;\nvar DISPOSITION_HANDLER = 2;\nvar withBit = (mask, bit, on) => on ? mask | bit : mask & ~bit;\nvar WASIX_LIBC_DEFAULT_LINE = /^Program recieved (?:stop|termination|fatal) signal: [^\\n]+\\n$/;\nvar WasiSignals = class {\n exports;\n callback;\n uncaught = 0;\n delivering;\n defaulted = false;\n libcDefault = false;\n hooked = false;\n handlers = 0;\n ignoring = 0;\n restarting = 0;\n nodefer = 0;\n running = 0;\n deferred = 0;\n lifted = 0;\n unblocking(bits) {\n this.lifted |= bits & this.running;\n }\n defaults = 0;\n nocldwait = false;\n fallBack;\n onKilled;\n constructor(fallBack, onKilled) {\n this.fallBack = fallBack;\n this.onKilled = onKilled;\n }\n killed(code2) {\n this.onKilled?.(code2);\n }\n bind(exports) {\n this.exports = exports;\n }\n register(name2) {\n if (typeof this.exports?.[name2] === \"function\") this.callback = name2;\n }\n useHook() {\n this.hooked = true;\n }\n disposition(sig, disposition, flags) {\n if (sig < 1 || sig > 31 || (DELIVERED_MASK & sigbit(sig)) === 0) return E.INVAL;\n const bit = sigbit(sig);\n this.handlers = withBit(this.handlers, bit, disposition === DISPOSITION_HANDLER);\n this.ignoring = withBit(this.ignoring, bit, disposition === DISPOSITION_IGNORE);\n this.restarting = withBit(this.restarting, bit, (flags & SA_RESTART) !== 0);\n this.nodefer = withBit(this.nodefer, bit, (flags & SA_NODEFER) !== 0);\n this.defaults = withBit(this.defaults, bit, disposition === 0);\n if (sig === SIG.CHLD) this.nocldwait = (flags & SA_NOCLDWAIT) !== 0;\n return E.SUCCESS;\n }\n snapshot() {\n return {\n ...this.callback ? { callback: this.callback } : {},\n ...this.hooked ? { hooked: true } : {},\n handlers: this.handlers,\n ignoring: this.ignoring,\n restarting: this.restarting,\n uncaught: this.uncaught,\n ...this.nocldwait ? { nocldwait: true } : {}\n };\n }\n restore(state) {\n if (state.callback) this.register(state.callback);\n if (state.hooked) this.hooked = true;\n this.handlers = state.handlers;\n this.ignoring = state.ignoring;\n this.restarting = state.restarting;\n this.uncaught = state.uncaught;\n this.nocldwait = state.nocldwait === true;\n }\n masks() {\n if (this.hooked) {\n const caught = this.handler() ? this.handlers : 0;\n const defaults = this.defaults;\n this.defaults = 0;\n const nocldwait = this.nocldwait ? { nocldwait: true } : {};\n return { caught, ignored: this.ignoring, restart: this.restarting, defaults, ...nocldwait };\n }\n if (!this.handler()) return null;\n return { caught: DELIVERED_MASK & ~this.uncaught & ~KERNEL_DEFAULTS, ignored: 0, restart: 0 };\n }\n async raise(sig) {\n const handler = this.handler();\n if (!handler && !this.hooked) return;\n if (!handler || this.hooked && (this.handlers & sigbit(sig)) === 0) {\n if ((this.ignoring & sigbit(sig)) === 0) await this.defaultAction(sig);\n return;\n }\n const bit = sigbit(sig);\n if ((this.running & bit) !== 0 && ((this.nodefer | this.lifted) & bit) === 0) {\n this.deferred |= bit;\n return;\n }\n const outer = { running: this.running & bit, lifted: this.lifted & bit };\n this.running |= bit;\n this.lifted &= ~bit;\n try {\n await this.run(handler, sig);\n } finally {\n this.running = this.running & ~bit | outer.running;\n this.lifted = this.lifted & ~bit | outer.lifted;\n }\n if ((this.deferred & bit) === 0) return;\n this.deferred &= ~bit;\n await this.raise(sig);\n }\n ran = 0;\n async run(handler, sig) {\n this.ran++;\n const outer = { sig: this.delivering, defaulted: this.defaulted, libc: this.libcDefault };\n this.delivering = sig;\n this.defaulted = false;\n this.libcDefault = false;\n try {\n await handler(sig);\n } catch (e) {\n const libcExit = e instanceof WasiExit && e.code === LIBC_DEFAULT_EXIT && this.libcDefault;\n if (!(libcExit && !this.defaulted) && !(e instanceof WebAssembly.RuntimeError)) throw e;\n if (!this.defaulted) await this.defaultAction(sig);\n } finally {\n this.delivering = outer.sig;\n this.defaulted = outer.defaulted;\n this.libcDefault = outer.libc;\n }\n }\n muted(fd, data) {\n if (fd !== 2 || this.delivering === void 0) return false;\n if (!WASIX_LIBC_DEFAULT_LINE.test(new TextDecoder().decode(data))) return false;\n this.libcDefault = true;\n return true;\n }\n async raised(sig) {\n if (sig !== SIG.ABRT || this.delivering === void 0) return false;\n if (!this.defaulted) await this.defaultAction(this.delivering);\n return true;\n }\n async defaultAction(sig) {\n this.defaulted = true;\n this.uncaught |= sigbit(sig);\n await this.fallBack(sig);\n if (defaultAction(sig) !== \"terminate\") this.uncaught &= ~sigbit(sig);\n }\n handler() {\n const fn = this.callback ? this.exports?.[this.callback] : void 0;\n return typeof fn === \"function\" ? reentered(fn) : void 0;\n }\n};\n\n// src/process/wasi/wasi-stats.ts\nvar WasiStats = class {\n rows = /* @__PURE__ */ new Map();\n phases = [];\n mark = performance.now();\n wrap(tag, table) {\n return Object.fromEntries(\n Object.entries(table).map(([name2, value2]) => {\n if (typeof value2 !== \"function\") return [name2, value2];\n const fn = value2;\n const key = `${tag}.${name2}`;\n return [name2, async (...args) => await this.time(key, async () => await fn.apply(table, args))];\n })\n );\n }\n async time(key, fn) {\n const t = performance.now();\n try {\n return await fn();\n } finally {\n this.count(key, performance.now() - t);\n }\n }\n phase(name2) {\n const now = performance.now();\n this.phases.push([name2, now - this.mark]);\n this.mark = now;\n }\n count(key, ms) {\n const row = this.rows.get(key) ?? { n: 0, ms: 0, max: 0 };\n row.n++;\n row.ms += ms;\n row.max = Math.max(row.max, ms);\n this.rows.set(key, row);\n }\n report() {\n const ms = (v) => v.toFixed(1).padStart(9);\n const lines = this.phases.map(([name2, t]) => `${ms(t)} ms ${name2}`);\n lines.push(`${\"total ms\".padStart(12)} ${\"calls\".padStart(7)} ${\"max ms\".padStart(9)} call`);\n const sorted = [...this.rows].sort((a, b) => b[1].ms - a[1].ms);\n for (const [key, row] of sorted) {\n lines.push(`${ms(row.ms)} ${String(row.n).padStart(7)} ${ms(row.max)} ${key}`);\n }\n return `${lines.join(\"\\n\")}\n`;\n }\n};\n\n// src/process/wasi/wasi-sysfs.ts\nvar ONE = [\n \"writeFile\",\n \"mkdir\",\n \"rm\",\n \"unlink\",\n \"rmdir\",\n \"chmod\",\n \"utimes\",\n \"lutimes\",\n \"create\",\n \"mkfifo\",\n \"chown\",\n \"pwrite\",\n \"truncate\",\n \"append\"\n];\nvar TWO = [\"rename\", \"link\", \"copy\"];\nfunction refuse(p) {\n throw syncError(\"EROFS\", p);\n}\nasync function listed2(tree, p) {\n const out = [];\n for (const name2 of await tree.readdir(p)) out.push([name2, await tree.stat(`${p}/${name2}`, false)]);\n return out;\n}\nfunction sysfsBridge(fs, nodes) {\n const tree = () => new SysTree(nodes);\n const over = {\n readFile: async (p) => inSys(p) ? await tree().read(p) : await fs.readFile(p),\n stat: async (p) => inSys(p) ? await tree().stat(p) : await fs.stat(p),\n lstat: async (p) => inSys(p) ? await tree().stat(p, false) : await fs.lstat(p),\n readlink: async (p) => inSys(p) ? await tree().readlink(p) : await fs.readlink(p),\n exists: async (p) => inSys(p) ? await tree().exists(p) : await fs.exists(p),\n readdir: async (p) => {\n if (inSys(p)) return await tree().readdir(p);\n const names2 = await fs.readdir(p);\n return p !== \"/\" || names2.includes(\"sys\") ? names2 : [...names2, \"sys\"];\n },\n readdirStat: async (p) => {\n if (inSys(p)) return await listed2(tree(), p);\n const entries2 = await fs.readdirStat(p);\n if (p !== \"/\" || entries2.some(([name2]) => name2 === \"sys\")) return entries2;\n return [...entries2, [\"sys\", await new SysTree(() => []).stat(\"/sys\")]];\n },\n symlink: async (target, link) => inSys(link) ? refuse(link) : await fs.symlink(target, link)\n };\n const { access: access3, hold, pread } = fs;\n if (access3)\n over.access = async (p, mode, ...rest2) => inSys(p) ? await tree().access(p, mode) : await access3.call(fs, p, mode, ...rest2);\n if (hold) over.hold = async (p, ...rest2) => inSys(p) ? void 0 : await hold.call(fs, p, ...rest2);\n if (pread)\n over.pread = async (p, at, n, version) => inSys(p) ? (await tree().read(p)).subarray(at, at + n) : await pread.call(fs, p, at, n, version);\n for (const name2 of ONE) {\n const fn = fs[name2];\n if (!fn) continue;\n over[name2] = (async (p, ...rest2) => inSys(p) ? refuse(p) : await fn.call(fs, p, ...rest2));\n }\n for (const name2 of TWO) {\n const fn = fs[name2];\n if (!fn) continue;\n over[name2] = (async (from, to, ...rest2) => inSys(to) || name2 !== \"copy\" && inSys(from) ? refuse(inSys(to) ? to : from) : await fn.call(fs, from, to, ...rest2));\n }\n return new Proxy(fs, {\n get: (target, key, receiver) => key in over ? over[key] : Reflect.get(target, key, receiver)\n });\n}\n\n// src/process/wasi/wasix-fork.ts\nvar STACK_POINTER = \"__stack_pointer\";\nvar UNWINDING = 1;\nvar REWINDING = 2;\nfunction mutableGlobals(exports) {\n const out = [];\n for (const [name2, value2] of Object.entries(exports)) {\n if (!(value2 instanceof WebAssembly.Global) || typeof value2.value !== \"number\") continue;\n try {\n const v = value2.value;\n value2.value = v;\n out.push([name2, v]);\n } catch {\n }\n }\n return out;\n}\nfunction reseatTls(exports, bytes) {\n const init = exports.__wasm_init_tls;\n const base = exports.__tls_base;\n const size = exports.__tls_size;\n if (typeof init !== \"function\" || !(base instanceof WebAssembly.Global) || !(size instanceof WebAssembly.Global)) {\n return;\n }\n const at = base.value;\n const block = bytes(at, size.value).slice();\n init(at);\n bytes(at, block.length).set(block);\n}\nvar AsyncifyDriver = class {\n exports = {};\n stackUpper = 0;\n linked;\n pending;\n answer = 0;\n snapshots = /* @__PURE__ */ new Map();\n nextSnapshot = 1;\n mem;\n constructor(mem) {\n this.mem = mem;\n }\n useStack(pointer, low) {\n this.linked = { pointer, low };\n }\n threadStack = false;\n useThreadStack(pointer, low) {\n this.useStack(pointer, low);\n this.threadStack = true;\n }\n bind(exports) {\n this.exports = exports;\n this.stackUpper = this.stackPointer();\n }\n get supported() {\n return typeof this.exports.asyncify_start_unwind === \"function\";\n }\n get idle() {\n const state = this.exports.asyncify_get_state;\n return !this.supported || typeof state !== \"function\" || state() === 0;\n }\n async resume() {\n if (this.exports.asyncify_get_state?.() !== UNWINDING) return false;\n this.exports.asyncify_stop_unwind?.();\n const op = this.pending;\n this.pending = void 0;\n if (!op) throw new Error(\"WASIX: unwound with nothing to do\");\n this.exports.asyncify_start_rewind?.(await op());\n return true;\n }\n setjmps() {\n return { next: this.nextSnapshot, snapshots: [...this.snapshots] };\n }\n startChild(state) {\n for (const [id, snap] of state.setjmps?.snapshots ?? []) this.snapshots.set(id, snap);\n this.nextSnapshot = Math.max(this.nextSnapshot, state.setjmps?.next ?? 1);\n this.restoreGlobals(state.globals);\n reseatTls(this.exports, (at, length) => this.mem.bytes(at, length));\n this.answer = 0;\n this.exports.asyncify_start_rewind?.(state.asyncifyData);\n }\n rewound() {\n if (this.exports.asyncify_get_state?.() !== REWINDING) return void 0;\n this.exports.asyncify_stop_rewind?.();\n return this.answer;\n }\n fork(fork) {\n const sp = this.stackPointer();\n const globals = this.globals();\n return this.unwind(async (data) => {\n this.answer = await fork(data, globals, sp);\n });\n }\n checkpoint(snapPtr, retPtr) {\n const id = this.nextSnapshot++;\n const v = this.mem.view();\n v.setBigUint64(snapPtr, BigInt(retPtr), true);\n v.setBigUint64(snapPtr + 8, BigInt(id), true);\n v.setBigUint64(snapPtr + 16, 0x51cc5117n, true);\n const globals = this.globals();\n return this.unwind((data) => {\n const end = this.mem.view().getUint32(data, true);\n this.snapshots.set(id, { frames: this.mem.bytes(data + 8, end - data - 8).slice(), globals });\n this.answer = 0;\n });\n }\n restore(snapPtr, val) {\n const id = Number(this.mem.view().getBigUint64(snapPtr + 8, true));\n const snap = this.snapshots.get(id);\n if (!snap) throw new Error(`WASIX: longjmp to an unknown setjmp (${id})`);\n return this.unwind((data) => {\n this.mem.bytes(data + 8, snap.frames.length).set(snap.frames);\n this.mem.view().setUint32(data, data + 8 + snap.frames.length, true);\n this.restoreGlobals(snap.globals);\n this.answer = Number(val) || 1;\n });\n }\n stackGlobal() {\n const g = this.exports[STACK_POINTER];\n return g instanceof WebAssembly.Global ? g : this.linked?.pointer;\n }\n stackPointer() {\n return this.stackGlobal()?.value ?? 0;\n }\n globals() {\n const out = mutableGlobals(this.exports);\n if (this.linked && !out.some(([name2]) => name2 === STACK_POINTER)) {\n out.push([STACK_POINTER, this.linked.pointer.value]);\n }\n return out;\n }\n dataPointer() {\n const own = this.exports[STACK_POINTER] instanceof WebAssembly.Global;\n if (this.linked && (this.threadStack || !own)) return this.linked.low + 15 & ~15;\n const g = this.exports.__data_end;\n const dataEnd = g instanceof WebAssembly.Global ? g.value : 0;\n return dataEnd < this.stackUpper ? dataEnd + 15 & ~15 : 16;\n }\n unwind(then) {\n if (!this.supported) return E.NOSYS;\n const data = this.dataPointer();\n const v = this.mem.view();\n v.setUint32(data, data + 8, true);\n v.setUint32(data + 4, this.stackPointer() - 16, true);\n this.pending = async () => {\n await then(data);\n return data;\n };\n this.exports.asyncify_start_unwind?.(data);\n return E.SUCCESS;\n }\n restoreGlobals(globals) {\n for (const [name2, value2] of globals) {\n const g = name2 === STACK_POINTER ? this.stackGlobal() : this.exports[name2];\n if (g instanceof WebAssembly.Global) g.value = value2;\n }\n }\n};\n\n// src/process/wasi/wasix-ffi.ts\nvar SIZE2 = { i32: 4, i64: 8, f32: 4, f64: 8 };\nfunction read(view, at, type) {\n if (type === \"i32\") return view.getInt32(at, true);\n if (type === \"i64\") return view.getBigInt64(at, true);\n if (type === \"f32\") return view.getFloat32(at, true);\n return view.getFloat64(at, true);\n}\nfunction readSome(view, at, end, type) {\n if (at + SIZE2[type] <= end) return read(view, at, type);\n const some = new DataView(new ArrayBuffer(8));\n for (let i = 0; at + i < end; i++) some.setUint8(i, view.getUint8(at + i));\n return read(some, 0, type);\n}\nfunction write(view, at, type, value2) {\n if (type === \"i32\") view.setInt32(at, Number(value2), true);\n else if (type === \"i64\") view.setBigInt64(at, BigInt(value2), true);\n else if (type === \"f32\") view.setFloat32(at, Number(value2), true);\n else view.setFloat64(at, Number(value2), true);\n}\nfunction scalars(types) {\n if (types.includes(\"other\")) throw new WasiError(\"EINVAL\");\n return types;\n}\nasync function callDynamic(ctx, ...operands) {\n const [id, values, valuesLen, results, resultsLen, strict] = operands.map((n) => n >>> 0);\n const table = ctx.table();\n if (!table) throw new WasiError(\"ENOTSUP\");\n const fn = id < table.length ? table.get(id) : null;\n const sig = fn ? await ctx.types.of(fn) : void 0;\n if (!fn || !sig) throw new WasiError(\"EINVAL\");\n const params = scalars(sig.params);\n const outs = scalars(sig.results);\n const size = (types) => types.reduce((n, type) => n + SIZE2[type], 0);\n if (strict && (size(params) !== valuesLen || size(outs) !== resultsLen)) {\n throw new WasiError(\"EINVAL\");\n }\n const view = ctx.mem.view();\n if (values + valuesLen > view.byteLength || results + resultsLen > view.byteLength) {\n throw new WasiError(\"EFAULT\");\n }\n const end = values + valuesLen;\n let at = values;\n const args = params.map((type) => {\n const v = readSome(view, at, end, type);\n at += SIZE2[type];\n return v;\n });\n const returned = await reentered(fn)(...args);\n const got = outs.length === 1 ? [returned] : returned ?? [];\n const after = ctx.mem.view();\n const stop = results + resultsLen;\n let out = results;\n outs.forEach((type, i) => {\n if (out + SIZE2[type] > stop) return;\n write(after, out, type, got[i]);\n out += SIZE2[type];\n });\n}\n\n// src/process/wasi/wasix-trampoline.ts\nvar CODES = [\"i32\", \"i64\", \"f32\", \"f64\", \"v128\"];\nvar VALTYPE = {\n i32: 127,\n i64: 126,\n f32: 125,\n f64: 124,\n v128: 123\n};\nvar SIZE3 = { i32: 4, i64: 8, f32: 4, f64: 8, v128: 16 };\nvar STORE = {\n i32: [54],\n i64: [55],\n f32: [56],\n f64: [57],\n v128: [253, 11]\n};\nvar LOAD = {\n i32: [40],\n i64: [41],\n f32: [42],\n f64: [43],\n v128: [253, 0]\n};\nfunction valueTypes(codes) {\n const out = [];\n for (const code2 of codes) {\n const type = CODES[code2];\n if (!type) return void 0;\n out.push(type);\n }\n return out;\n}\nfunction u32(n) {\n const out = [];\n let v = n >>> 0;\n do {\n let b = v & 127;\n v >>>= 7;\n if (v) b |= 128;\n out.push(b);\n } while (v);\n return out;\n}\nfunction s32(n) {\n const out = [];\n let v = n | 0;\n for (; ; ) {\n const b = v & 127;\n v >>= 7;\n if (v === 0 && !(b & 64) || v === -1 && b & 64) {\n out.push(b);\n return out;\n }\n out.push(b | 128);\n }\n}\nfunction name(s) {\n const bytes = [...new TextEncoder().encode(s)];\n return [...u32(bytes.length), ...bytes];\n}\nfunction section(id, body) {\n return [id, ...u32(body.length), ...body];\n}\nfunction vec(items) {\n return [...u32(items.length), ...items.flat()];\n}\nfunction align16(n) {\n return Math.ceil(n / 16) * 16;\n}\nfunction trampolineBytes(params, results, shared) {\n const sig = [\n 96,\n ...vec(params.map((t) => [VALTYPE[t]])),\n ...vec(results.map((t) => [VALTYPE[t]]))\n ];\n const backing = [96, ...vec([[127], [127], [127]]), ...vec([])];\n const memory = shared ? [3, 0, ...u32(65536)] : [0, 0];\n const imports = vec([\n [...name(\"env\"), ...name(\"memory\"), 2, ...memory],\n [...name(\"env\"), ...name(\"__indirect_function_table\"), 1, 112, 0, 0],\n [...name(\"env\"), ...name(\"__stack_pointer\"), 3, 127, 1],\n [...name(\"env\"), ...name(\"backing\"), 3, 127, 0],\n [...name(\"env\"), ...name(\"user_data\"), 3, 127, 0]\n ]);\n const n = params.length;\n const [orig, args, res] = [n, n + 1, n + 2];\n const valuesSize = align16(params.reduce((sum, t) => sum + SIZE3[t], 0));\n const resultsSize = align16(results.reduce((sum, t) => sum + SIZE3[t], 0));\n const body = [\n 35,\n 0,\n 34,\n ...u32(orig),\n 65,\n ...s32(resultsSize),\n 107,\n 34,\n ...u32(res)\n ];\n body.push(65, ...s32(valuesSize), 107, 34, ...u32(args), 36, 0);\n let at = 0;\n params.forEach((t, i) => {\n body.push(32, ...u32(args), 32, ...u32(i), ...STORE[t], 0, ...u32(at));\n at += SIZE3[t];\n });\n body.push(32, ...u32(args), 32, ...u32(res), 35, 2, 35, 1, 17, 1, 0);\n at = 0;\n for (const t of results) {\n body.push(32, ...u32(res), ...LOAD[t], 0, ...u32(at));\n at += SIZE3[t];\n }\n body.push(32, ...u32(orig), 36, 0, 11);\n const func = [...vec([[...u32(3), 127]]), ...body];\n return Uint8Array.from([\n 0,\n 97,\n 115,\n 109,\n 1,\n 0,\n 0,\n 0,\n ...section(1, vec([sig, backing])),\n ...section(2, imports),\n ...section(3, vec([[0]])),\n ...section(7, vec([[...name(\"t\"), 0, 0]])),\n ...section(10, vec([[...u32(func.length), ...func]]))\n ]);\n}\nvar Trampolines = class {\n modules = /* @__PURE__ */ new Map();\n get compiled() {\n return this.modules.size;\n }\n make(params, results, env) {\n const shared = env.memory.buffer instanceof SharedArrayBuffer;\n const key = `${params.join(\",\")}>${results.join(\",\")}${shared ? \"s\" : \"\"}`;\n let module = this.modules.get(key);\n if (!module) {\n module = refusedModule(trampolineBytes(params, results, shared));\n this.modules.set(key, module);\n }\n const i32 = (v) => new WebAssembly.Global({ value: \"i32\", mutable: false }, v);\n const instance = new WebAssembly.Instance(module, suspendingImports({\n env: {\n memory: env.memory,\n __indirect_function_table: env.table,\n __stack_pointer: env.stackPointer,\n backing: i32(env.backing),\n user_data: i32(env.userData)\n }\n }));\n const sig = {\n params: params.map((t) => t === \"v128\" ? \"other\" : t),\n results: results.map((t) => t === \"v128\" ? \"other\" : t)\n };\n return { fn: instance.exports.t, sig };\n }\n};\n\n// src/process/wasi/wasm-functypes.ts\nvar VALTYPES = {\n 127: \"i32\",\n 126: \"i64\",\n 125: \"f32\",\n 124: \"f64\"\n};\nvar TABLE_BASE = \"__table_base\";\nvar Reader = class {\n at = 8;\n bytes;\n constructor(bytes) {\n this.bytes = bytes;\n }\n byte() {\n return this.bytes[this.at++] ?? 0;\n }\n u32() {\n let result = 0;\n let shift = 0;\n for (; ; ) {\n const b = this.byte();\n result |= (b & 127) << shift;\n if (!(b & 128)) return result >>> 0;\n shift += 7;\n }\n }\n s32() {\n let result = 0;\n let shift = 0;\n let b;\n do {\n b = this.byte();\n result |= (b & 127) << shift;\n shift += 7;\n } while (b & 128);\n return shift < 32 && b & 64 ? result | -1 << shift : result;\n }\n name() {\n const len = this.u32();\n const s = new TextDecoder().decode(this.bytes.subarray(this.at, this.at + len));\n this.at += len;\n return s;\n }\n valtype() {\n const code2 = this.byte();\n if (code2 === 99 || code2 === 100) this.s32();\n return VALTYPES[code2] ?? \"other\";\n }\n limits() {\n const flags = this.byte();\n this.u32();\n if (flags & 1) this.u32();\n }\n};\nfunction readTypes(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n r.byte();\n const params = [];\n for (let n = r.u32(); n > 0; n--) params.push(r.valtype());\n const results = [];\n for (let n = r.u32(); n > 0; n--) results.push(r.valtype());\n s.info.sigs.push({ params, results });\n }\n}\nfunction readImports(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n r.name();\n const field2 = r.name();\n const kind = r.byte();\n if (kind === 0) s.info.funcs.push(r.u32());\n else if (kind === 1) {\n r.valtype();\n r.limits();\n } else if (kind === 2) r.limits();\n else if (kind === 3) {\n r.valtype();\n r.byte();\n s.globals.push(field2);\n } else {\n r.byte();\n r.u32();\n }\n }\n}\nfunction readFunctions(r, s) {\n for (let i = r.u32(); i > 0; i--) s.info.funcs.push(r.u32());\n}\nvar SKIP = {\n 66: (r) => r.s32(),\n 67: (r) => {\n r.at += 4;\n },\n 68: (r) => {\n r.at += 8;\n },\n 208: (r) => r.valtype()\n};\nfunction constExpr(r, s) {\n let value2 = 0;\n let tableBase = false;\n let known = true;\n for (; ; ) {\n const op = r.byte();\n if (op === 11) return known ? { value: value2, tableBase } : void 0;\n if (op === 65) value2 += r.s32();\n else if (op === 35) {\n const g = s.globals[r.u32()];\n if (g === TABLE_BASE) tableBase = true;\n else if (typeof g === \"number\") value2 += g;\n else known = false;\n } else if (op === 210) {\n value2 = r.u32();\n } else if (op in SKIP) {\n SKIP[op]?.(r);\n known = false;\n } else if (op !== 106) {\n r.at = r.bytes.length;\n return void 0;\n }\n }\n}\nfunction readGlobals(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n r.valtype();\n r.byte();\n const init = constExpr(r, s);\n s.globals.push(init && !init.tableBase ? init.value : void 0);\n }\n}\nfunction readExports(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n const name2 = r.name();\n const kind = r.byte();\n const index3 = r.u32();\n if (kind === 0) s.info.exports[name2] = index3;\n }\n}\nfunction readElems(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n const flags = r.u32();\n const active = (flags & 1) === 0;\n const table = flags & 2 ? active ? r.u32() : 0 : 0;\n const offset = active ? constExpr(r, s) : void 0;\n if (flags & 3) r.valtype();\n const funcs = [];\n for (let n = r.u32(); n > 0; n--) {\n if (flags & 4) {\n const ref = constExpr(r, s);\n funcs.push(ref ? ref.value : -1);\n } else funcs.push(r.u32());\n }\n if (offset && table === 0) {\n s.info.elems.push({ offset: offset.value, tableBase: offset.tableBase, funcs });\n }\n }\n}\nvar SECTIONS = {\n 1: readTypes,\n 2: readImports,\n 3: readFunctions,\n 6: readGlobals,\n 7: readExports,\n 9: readElems\n};\nfunction funcTypeInfo(bytes) {\n const r = new Reader(bytes);\n const s = { info: { sigs: [], funcs: [], exports: {}, elems: [] }, globals: [] };\n while (r.at < bytes.length) {\n const id = r.byte();\n const end = r.u32() + r.at;\n SECTIONS[id]?.(r, s);\n r.at = end;\n }\n return s.info;\n}\nvar FuncTypes = class {\n known = /* @__PURE__ */ new WeakMap();\n pending = [];\n register(read2, instance, table, tableBase) {\n this.pending.push(async () => {\n const bytes = await read2();\n if (bytes) this.add(funcTypeInfo(bytes), instance, table, tableBase);\n });\n }\n add(info, instance, table, tableBase) {\n const sig = (func) => info.sigs[info.funcs[func] ?? -1];\n for (const [name2, func] of Object.entries(info.exports)) {\n const fn = instance.exports[name2];\n const type = sig(func);\n if (typeof fn === \"function\" && type) this.known.set(fn, type);\n }\n if (!table) return;\n for (const seg of info.elems) {\n const start2 = seg.offset + (seg.tableBase ? tableBase : 0);\n seg.funcs.forEach((func, i) => {\n const type = sig(func);\n const fn = start2 + i < table.length ? table.get(start2 + i) : null;\n if (fn && type) this.known.set(fn, type);\n });\n }\n }\n set(fn, sig) {\n this.known.set(fn, sig);\n }\n async of(fn) {\n const known = this.known.get(fn);\n if (known || this.pending.length === 0) return known;\n const pending = this.pending;\n this.pending = [];\n for (const run of pending) await run();\n return this.known.get(fn);\n }\n};\n\n// src/process/wasi/wasix-linker.ts\nvar TABLE_BASE2 = 1;\nvar PAGE2 = 65536;\nvar STACK_SIZE = 8 * 1024 * 1024;\nvar LIBRARY_DIRS = [\"/lib\", \"/usr/lib\", \"/usr/local/lib\"];\nfunction expandOrigin(entry, dir) {\n return entry.replace(/\\$(?:ORIGIN\\b|\\{ORIGIN\\})/g, dir);\n}\nvar DlError = class extends Error {\n};\nvar WasixLinker = class {\n table;\n stackPointer;\n memoryBase;\n stackLow;\n stackHigh;\n cLongjmp;\n cppException;\n main;\n modules = /* @__PURE__ */ new Map();\n forkedTls;\n byPath = /* @__PURE__ */ new Map();\n mainGot = [];\n slots = /* @__PURE__ */ new Map();\n nextHandle = 1;\n publisher;\n indices;\n types = new FuncTypes();\n trampolines = new Trampolines();\n memory;\n host;\n constructor(memory, mainInfo, host, thread = false) {\n this.memory = memory;\n this.host = host;\n this.memoryBase = Math.max(1, 2 ** mainInfo.memoryAlign);\n this.stackLow = align(this.memoryBase + mainInfo.memorySize, 1024);\n this.stackHigh = this.stackLow + STACK_SIZE;\n if (!thread) growTo(memory, this.stackHigh);\n this.table = new WebAssembly.Table({\n element: \"anyfunc\",\n initial: TABLE_BASE2 + mainInfo.tableSize\n });\n this.stackPointer = new WebAssembly.Global(\n { value: \"i32\", mutable: true },\n thread ? 0 : this.stackHigh\n );\n const tag = () => new WebAssembly.Tag({\n parameters: [\"i32\"]\n });\n this.cLongjmp = tag();\n this.cppException = tag();\n }\n mainImports(module) {\n const i32 = (v) => new WebAssembly.Global({ value: \"i32\", mutable: false }, v);\n const got = (v) => new WebAssembly.Global({ value: \"i32\", mutable: true }, v);\n const env = {\n memory: this.memory,\n __indirect_function_table: this.table,\n __stack_pointer: this.stackPointer,\n __memory_base: i32(this.memoryBase),\n __table_base: i32(TABLE_BASE2),\n __c_longjmp: this.cLongjmp,\n __cpp_exception: this.cppException\n };\n const gotMem = {\n __stack_high: got(this.stackHigh),\n __stack_low: got(this.stackLow),\n __heap_base: got(this.stackHigh)\n };\n const gotFunc = {};\n this.mainGot = [];\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module === \"env\" && imp.kind === \"function\" && !(imp.name in env)) {\n env[imp.name] = this.functionImport(imp.name);\n } else if (imp.module === \"GOT.func\" || imp.module === \"GOT.mem\" && !(imp.name in gotMem)) {\n const g = got(0);\n (imp.module === \"GOT.func\" ? gotFunc : gotMem)[imp.name] = g;\n const kind = imp.module;\n this.mainGot.push(async () => {\n g.value = kind === \"GOT.func\" ? await this.slotOrNull(imp.name) : this.addressOrNull(imp.name);\n });\n }\n }\n return { env, \"GOT.mem\": gotMem, \"GOT.func\": gotFunc };\n }\n async bindMainGot() {\n for (const resolve of this.mainGot) await resolve();\n }\n async bindMain(instance, relocate) {\n this.main = instance;\n if (relocate) await call(instance, \"__wasm_apply_data_relocs\");\n }\n mainPath;\n async isMain(path) {\n if (this.mainPath === void 0) return false;\n if (path === this.mainPath) return true;\n const real = this.host.real;\n if (real === void 0) return false;\n try {\n return await real(path) === await real(this.mainPath);\n } catch {\n return false;\n }\n }\n async open(name2, cwd, ldPath) {\n const path = await this.locate(name2, cwd, ldPath);\n if (await this.isMain(path)) return 0;\n await this.indices?.lock();\n try {\n return (await this.load(path, cwd, ldPath)).handle;\n } finally {\n await this.indices?.unlock();\n }\n }\n async symbol(handle, name2) {\n const found = handle === 0 ? this.find(name2) : this.findIn(this.module(handle), name2, /* @__PURE__ */ new Set());\n if (!found) throw new DlError(`undefined symbol: ${name2}`);\n const [owner, value2] = found;\n if (typeof value2 === \"function\") return await this.slot(value2, owner, name2);\n if (value2 instanceof WebAssembly.Global) return this.baseOf(owner) + value2.value;\n throw new DlError(`${name2} is neither a function nor data`);\n }\n invalid(handle) {\n return !this.modules.has(handle);\n }\n cache;\n compiled() {\n const out = {};\n for (const [path, linked] of this.byPath) out[path] = linked.module;\n return out;\n }\n async allocateClosure() {\n const index3 = await this.indices.allocate(this.table.length);\n growTable(this.table, index3 + 1);\n this.live.add(index3);\n return index3;\n }\n async freeClosure(index3) {\n await this.indices?.free(index3);\n this.live.delete(index3);\n this.table.set(index3, null);\n }\n live = /* @__PURE__ */ new Set();\n async prepareClosure(record) {\n if (!this.live.has(record.index)) throw new DlError(`closure ${record.index}: not allocated`);\n const full = { kind: \"closure-prepare\", ...record };\n this.install(full);\n await this.publisher?.(full);\n }\n install(record) {\n growTable(this.table, record.index + 1);\n const { fn, sig } = this.trampolines.make(record.params, record.results, {\n memory: this.memory,\n table: this.table,\n stackPointer: this.stackPointer,\n backing: record.backing,\n userData: record.userData\n });\n this.table.set(record.index, fn);\n this.types.set(fn, sig);\n }\n async reserveLoad(size) {\n return await this.indices?.load(this.table.length, size) ?? {\n base: this.table.length,\n handle: this.nextHandle++\n };\n }\n async reserve(size) {\n return await this.indices?.reserve(this.table.length, size) ?? this.table.length;\n }\n tlsBases() {\n const bases = [];\n for (const [handle, linked] of this.modules) {\n const base = linked.instance.exports.__tls_base;\n if (base instanceof WebAssembly.Global) bases.push([handle, base.value]);\n }\n return bases;\n }\n carryTls(linked) {\n const base = this.forkedTls?.get(linked.handle);\n const global = linked.instance.exports.__tls_base;\n if (base === void 0 || !(global instanceof WebAssembly.Global)) return false;\n global.value = base;\n reseatTls(\n linked.instance.exports,\n (at, length) => new Uint8Array(this.memory.buffer, at, length)\n );\n return true;\n }\n async replay(record) {\n if (record.kind === \"closure\") {\n growTable(this.table, record.index + 1);\n this.live.add(record.index);\n return;\n }\n if (record.kind === \"closure-free\") {\n this.live.delete(record.index);\n if (record.index < this.table.length) this.table.set(record.index, null);\n return;\n }\n if (record.kind === \"closure-prepare\") {\n this.install(record);\n return;\n }\n if (record.kind === \"load\") {\n if (this.modules.has(record.handle)) return;\n const linked = await this.instantiate(record.path, await this.moduleAt(record.path), record, false);\n linked.needed.push(...record.needed ?? []);\n this.nextHandle = Math.max(this.nextHandle, record.handle + 1);\n return;\n }\n const value2 = record.handle === 0 ? this.main?.exports[record.name] : this.module(record.handle).instance.exports[record.name];\n if (typeof value2 !== \"function\") throw new DlError(`${record.name}: not a function`);\n growTable(this.table, record.index + 1);\n this.table.set(record.index, value2);\n this.slots.set(value2, record.index);\n }\n async moduleAt(path) {\n const cached = this.cache?.[path];\n if (cached) return cached;\n const bytes = await this.host.read(path);\n if (!bytes) throw new DlError(`${path}: gone`);\n return refusedModule(bytes);\n }\n module(handle) {\n const m = this.modules.get(handle);\n if (!m) throw new DlError(`invalid handle ${handle}`);\n return m;\n }\n async locate(name2, cwd, ldPath) {\n if (name2.includes(\"/\"))\n return name2.startsWith(\"/\") ? normalize(name2) : normalize(`${cwd}/${name2}`);\n for (const dir of [...ldPath.filter(Boolean), ...LIBRARY_DIRS]) {\n const path = normalize(`${dir.startsWith(\"/\") ? \"\" : `${cwd}/`}${dir}/${name2}`);\n if (this.byPath.has(path) || await this.host.read(path)) return path;\n }\n throw new DlError(`${name2}: not found`);\n }\n async load(path, cwd, ldPath) {\n const loaded = this.byPath.get(path);\n if (loaded) return loaded;\n const bytes = await this.host.read(path);\n if (!bytes) throw new DlError(`${path}: no such file`);\n let module;\n try {\n module = refusedModule(bytes);\n } catch (e) {\n throw new DlError(`${path}: not a wasm module (${e.message})`);\n }\n const info = dylinkInfo(module);\n if (!info) throw new DlError(`${path}: not a side module (no dylink.0)`);\n const dir = path.slice(0, path.lastIndexOf(\"/\")) || \"/\";\n const search = [dir, ...ldPath, ...info.runtimePath.map((p) => expandOrigin(p, dir))];\n const needed = [];\n for (const n of info.needed)\n needed.push((await this.load(await this.locate(n, cwd, search), cwd, ldPath)).handle);\n const memoryBase = await this.allocate(info.memorySize, 2 ** info.memoryAlign);\n const { base: tableBase, handle } = await this.reserveLoad(info.tableSize);\n const record = {\n kind: \"load\",\n handle,\n path,\n memoryBase,\n tableBase,\n ...needed.length > 0 ? { needed } : {}\n };\n const linked = await this.instantiate(path, module, record, true);\n linked.needed.push(...needed);\n await this.publisher?.(record);\n return linked;\n }\n async instantiate(path, module, at, init) {\n const info = dylinkInfo(module);\n growTable(this.table, at.tableBase + info.tableSize);\n const pending = [];\n const env = {\n memory: this.memory,\n __indirect_function_table: this.table,\n __stack_pointer: this.stackPointer,\n __memory_base: new WebAssembly.Global({ value: \"i32\", mutable: false }, at.memoryBase),\n __table_base: new WebAssembly.Global({ value: \"i32\", mutable: false }, at.tableBase),\n __c_longjmp: this.cLongjmp,\n __cpp_exception: this.cppException\n };\n const gotMem = {};\n const gotFunc = {};\n const linked = {\n handle: at.handle,\n path,\n module,\n info,\n instance: void 0,\n memoryBase: at.memoryBase,\n tableBase: at.tableBase,\n needed: []\n };\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module === \"env\" && imp.kind === \"function\" && !(imp.name in env)) {\n env[imp.name] = this.functionImport(imp.name);\n } else if (imp.module === \"GOT.mem\") {\n const g = new WebAssembly.Global({ value: \"i32\", mutable: true }, 0);\n gotMem[imp.name] = g;\n pending.push(() => {\n g.value = this.addressOrNull(imp.name);\n });\n } else if (imp.module === \"GOT.func\") {\n const g = new WebAssembly.Global({ value: \"i32\", mutable: true }, 0);\n gotFunc[imp.name] = g;\n pending.push(async () => {\n g.value = await this.slotOrNull(imp.name);\n });\n }\n }\n const imports = {\n ...this.host.hostImports(module),\n env,\n \"GOT.mem\": gotMem,\n \"GOT.func\": gotFunc\n };\n linked.instance = new WebAssembly.Instance(module, suspendingImports(imports));\n this.types.register(async () => await this.host.read(path), linked.instance, this.table, at.tableBase);\n this.modules.set(at.handle, linked);\n const first = this.byPath.get(path);\n if (!first || at.handle < first.handle) this.byPath.set(path, linked);\n for (const resolve of pending) await resolve();\n if (init) {\n await call(linked.instance, \"__wasm_apply_data_relocs\");\n await call(linked.instance, \"__wasm_call_ctors\");\n } else if (!this.carryTls(linked)) {\n await call(linked.instance, \"__wasix_init_tls\");\n }\n return linked;\n }\n functionImport(name2) {\n const now = this.find(name2);\n if (now && typeof now[1] === \"function\") return now[1];\n let resolved2;\n return async (...args) => {\n if (!resolved2) {\n const later2 = this.find(name2);\n if (!later2 || typeof later2[1] !== \"function\")\n throw new WebAssembly.RuntimeError(`unresolved symbol ${name2}`);\n resolved2 = later2[1];\n }\n return await resolved2(...args);\n };\n }\n addressOrNull(name2) {\n const found = this.find(name2);\n if (!found || !(found[1] instanceof WebAssembly.Global)) return 0;\n return this.baseOf(found[0]) + found[1].value;\n }\n async slotOrNull(name2) {\n const found = this.find(name2);\n if (!found || typeof found[1] !== \"function\") return 0;\n return await this.slot(found[1], found[0], name2);\n }\n find(name2) {\n const inMain = this.main?.exports[name2];\n if (inMain !== void 0) return [0, inMain];\n for (const m of this.modules.values()) {\n const v = m.instance?.exports[name2];\n if (v !== void 0) return [m.handle, v];\n }\n return void 0;\n }\n findIn(m, name2, seen) {\n if (seen.has(m.handle)) return void 0;\n seen.add(m.handle);\n const v = m.instance.exports[name2];\n if (v !== void 0) return [m.handle, v];\n for (const h of m.needed) {\n const found = this.findIn(this.module(h), name2, seen);\n if (found) return found;\n }\n return void 0;\n }\n baseOf(handle) {\n return handle === 0 ? this.memoryBase : this.module(handle).memoryBase;\n }\n indexed = 0;\n indexTable() {\n for (let i = this.indexed; i < this.table.length; i++) {\n const fn = this.table.get(i);\n if (fn && !this.slots.has(fn)) this.slots.set(fn, i);\n }\n this.indexed = this.table.length;\n }\n async slot(fn, handle, name2) {\n this.indexTable();\n const known = this.slots.get(fn);\n if (known !== void 0) return known;\n const index3 = await this.reserve(1);\n growTable(this.table, index3 + 1);\n this.table.set(index3, fn);\n this.slots.set(fn, index3);\n await this.publisher?.({ kind: \"slot\", index: index3, handle, name: name2 });\n return index3;\n }\n async heapAlloc(bytes) {\n const exports = this.main?.exports;\n const calloc = exports?.calloc;\n if (typeof calloc !== \"function\") return void 0;\n const state = exports?.asyncify_get_state;\n if (typeof state === \"function\" && await state() !== 0) return void 0;\n const at = await calloc(1, bytes) >>> 0;\n return at === 0 ? void 0 : at;\n }\n async allocate(size, alignment) {\n if (size === 0) return 0;\n const to = Math.max(alignment, 16);\n const heap = await this.heapAlloc(size + to - 16);\n if (heap !== void 0) return align(heap, to);\n const pages2 = Math.ceil((size + (to > PAGE2 ? to : 0)) / PAGE2);\n return align(this.memory.grow(pages2) * PAGE2, to);\n }\n};\nfunction align(n, to) {\n return Math.ceil(n / to) * to;\n}\nfunction growTo(memory, bytes) {\n const pages2 = Math.ceil(bytes / PAGE2) - memory.buffer.byteLength / PAGE2;\n if (pages2 > 0) memory.grow(pages2);\n}\nfunction growTable(table, length) {\n if (table.length < length) table.grow(length - table.length);\n}\nasync function call(instance, name2) {\n const fn = instance.exports[name2];\n if (typeof fn === \"function\") await fn();\n}\n\n// src/process/wasi/wasix-host.ts\nvar FDFLAGSEXT_CLOEXEC = 1;\nvar SPAWN_OP_SIZE = 56;\nvar SPAWN_OPS = [\"close\", \"dup2\", \"open\", \"chdir\", \"fchdir\"];\nvar RIGHTS_FD_WRITE = 1n << 6n;\nvar ICANON = 2;\nvar ECHO = 8;\nvar EINTR_LIBC = 22;\nvar STRICT_EPOLL_LIBC = 29;\nvar CWD_FD_LIBC = 41;\nvar MAIN_HANDLE = 2147483647;\nvar WasixHost = class _WasixHost {\n process;\n threads;\n linker;\n types = new FuncTypes();\n table;\n signals;\n host;\n driver;\n constructor(host, driver, module) {\n this.host = host;\n this.driver = driver;\n this.process = new WasixProcess(\n host,\n driver,\n () => (this.threads?.tid ?? MAIN_TID) !== MAIN_TID\n );\n const libc = module ? libcVersion(module) ?? 0 : void 0;\n if (libc !== void 0) host.strictEpoll = libc >= STRICT_EPOLL_LIBC;\n if (libc !== void 0) host.cwdFd = libc >= CWD_FD_LIBC;\n if (module && !WebAssembly.Module.imports(module).some((i) => i.name === \"fd_fdflags_set\")) {\n host.fds.implicitCloexec = true;\n host.interruptWakes = (libcVersion(module) ?? 0) < EINTR_LIBC;\n }\n }\n get mem() {\n return this.host.mem;\n }\n str(ptr, len) {\n const s = this.mem.string(ptr, len);\n return s.endsWith(\"\\0\") ? s.slice(0, -1) : s;\n }\n cStrings(ptr, count) {\n const v = this.mem.view();\n return Array.from(\n { length: count },\n (_, i) => this.mem.cString(v.getUint32(ptr + i * 4, true))\n );\n }\n async execOrExit(n, nl, a, al, e, el) {\n try {\n return await this.process.exec({\n name: this.str(n, nl),\n argv: _WasixHost.lines(this.str(a, al)),\n env: _WasixHost.env(e === 0 ? void 0 : _WasixHost.lines(this.str(e, el))),\n search: false,\n path: \"\"\n });\n } catch (err) {\n if (err instanceof WasiExit) throw err;\n const code2 = err instanceof WasiError ? err.code : err?.code;\n throw new WasiExit(wasiErrnoOf(typeof code2 === \"string\" ? code2 : \"ENOEXEC\"));\n }\n }\n static env(entries2) {\n if (!entries2) return void 0;\n const env = {};\n for (const line of entries2) {\n const eq = line.indexOf(\"=\");\n if (eq > 0) env[line.slice(0, eq)] = line.slice(eq + 1);\n }\n return env;\n }\n static lines(text) {\n return text.split(\"\\n\").filter((line, i, all) => line !== \"\" || i < all.length - 1);\n }\n spawnOps(ptr, count) {\n const v = this.mem.view();\n return Array.from({ length: count }, (_, i) => {\n const p = ptr + i * SPAWN_OP_SIZE;\n const cmd = SPAWN_OPS[v.getUint8(p)];\n if (!cmd) throw new WasiError(\"EINVAL\");\n return {\n cmd,\n fd: v.getUint32(p + 4, true),\n srcFd: v.getUint32(p + 8, true),\n path: this.str(v.getUint32(p + 12, true), v.getUint32(p + 16, true)),\n oflags: v.getUint16(p + 24, true),\n rightsWrite: (v.getBigUint64(p + 32, true) & RIGHTS_FD_WRITE) !== 0n,\n append: (v.getUint16(p + 48, true) & FDFLAGS.APPEND) !== 0\n };\n });\n }\n imports() {\n return wrap({\n ...this.startupImports(),\n ...this.fdImports(),\n ...this.processImports(),\n ...this.threadImports(),\n ...this.dlImports(),\n closure_allocate: async (out) => {\n if (!this.linker) throw new WasiError(\"ENOTSUP\");\n this.mem.view().setUint32(out, await this.linker.allocateClosure(), true);\n },\n closure_prepare: async (backing, index3, argTypes, argCount, resultTypes, resultCount, userData) => {\n if (!this.linker) throw new WasiError(\"ENOTSUP\");\n const params = valueTypes(this.mem.bytes(argTypes, argCount));\n const results = valueTypes(this.mem.bytes(resultTypes, resultCount));\n if (!params || !results) throw new WasiError(\"EINVAL\");\n try {\n await this.linker.prepareClosure({ index: index3, backing, userData, params, results });\n } catch (e) {\n if (e instanceof DlError) throw new WasiError(\"EINVAL\");\n throw e;\n }\n },\n closure_free: async (index3) => {\n if (!this.linker) throw new WasiError(\"ENOTSUP\");\n await this.linker.freeClosure(index3);\n },\n call_dynamic: async (...a) => void await callDynamic(\n { mem: this.mem, table: () => this.table, types: this.types },\n ...a\n ),\n ...wasixSocketImports(this.host, this.host.imports()),\n ...wasixEpollImports(this.host)\n });\n }\n preview1() {\n const { fds } = this.host;\n return wrap({\n fd_renumber: async (from, to) => void await fds.renumber(from, to, true),\n fd_close: async (fd) => {\n const e = await fds.get(fd);\n if (e.type !== \"dir\" || !e.preopen) await fds.close(fd);\n }\n });\n }\n startupImports() {\n const { host, mem } = this;\n return {\n proc_exit2: (code2) => {\n throw new WasiExit(code2);\n },\n proc_signals_sizes_get: (out) => void mem.view().setUint32(out, 0, true),\n proc_signals_get: () => E.SUCCESS,\n callback_signal: (name2, len) => void this.signals?.register(this.str(name2, len)),\n proc_raise_interval: async (sig, interval, repeat) => void await host.o.kernel.call({\n op: \"proc-alarm\",\n sig: posixSignal(sig),\n ms: nsToMs(interval),\n repeat: repeat !== 0\n }),\n proc_raise_interval2: async (sig, initial, interval, repeat) => {\n const ms = nsToMs(interval);\n await host.o.kernel.call({\n op: \"proc-alarm\",\n sig: posixSignal(sig),\n ms,\n firstMs: nsToMs(initial),\n repeat: repeat !== 0 && ms > 0\n });\n },\n proc_id: (out) => void mem.view().setUint32(out, host.o.pid, true),\n proc_parent: async (pid, out) => {\n if (pid !== 0 && pid !== host.o.pid) throw new WasiError(\"ESRCH\");\n mem.view().setUint32(out, await host.o.parent?.() ?? host.o.ppid ?? 1, true);\n },\n getcwd: async (buf, lenPtr) => {\n if (host.cwdFd && host.fds.held && !await host.fds.held.alive()) return E.NOENT;\n const bytes = new TextEncoder().encode(await host.workingDir());\n const max = mem.view().getUint32(lenPtr, true);\n mem.view().setUint32(lenPtr, bytes.length, true);\n if (bytes.length > max) return E.RANGE;\n mem.bytes(buf, bytes.length).set(bytes);\n if (bytes.length < max) mem.view().setUint8(buf + bytes.length, 0);\n return E.SUCCESS;\n },\n chdir: async (ptr, len) => {\n const path = await host.fds.resolve(3, this.str(ptr, len));\n if (!(await host.o.fs.stat(path)).isDirectory) throw new WasiError(\"ENOTDIR\");\n await host.fds.chdir(path);\n }\n };\n }\n fdImports() {\n const { host, mem } = this;\n const preview1 = host.imports();\n return {\n fd_dup: async (fd, out) => void mem.view().setUint32(out, await host.fds.dup(fd, 0, false), true),\n fd_dup2: async (fd, min, cloexec, out) => void mem.view().setUint32(out, await host.fds.dup(fd, min, cloexec !== 0), true),\n fd_pipe: async (rPtr, wPtr) => {\n const [r, w] = await host.fds.pipe();\n mem.view().setUint32(rPtr, r, true);\n mem.view().setUint32(wPtr, w, true);\n },\n fd_fdflags_get: async (fd, out) => {\n await host.fds.get(fd);\n mem.view().setUint16(out, host.fds.cloexec.has(fd) ? FDFLAGSEXT_CLOEXEC : 0, true);\n },\n fd_fdflags_set: async (fd, flags) => void await host.fds.setCloexec(fd, (flags & FDFLAGSEXT_CLOEXEC) !== 0),\n path_open2: async (dirfd, lookup2, p, l, oflags, rights, inheriting, fdflags, fdflagsext, out) => {\n const r = preview1.path_open(dirfd, lookup2, p, l, oflags, rights, inheriting, fdflags, out);\n if (r === E.SUCCESS && fdflagsext & FDFLAGSEXT_CLOEXEC)\n await host.fds.setCloexec(mem.view().getUint32(out, true), true);\n return r;\n },\n tty_get: async (ptr) => void await this.ttyGet(ptr),\n tty_set: async (ptr) => void await this.ttySet(ptr)\n };\n }\n processImports() {\n const { mem, process } = this;\n return {\n proc_fork: (_copy, pidPtr) => process.fork(pidPtr),\n stack_checkpoint: (snapPtr, retPtr) => {\n const back = this.driver.rewound();\n if (back === void 0) return this.driver.checkpoint(snapPtr, retPtr);\n mem.view().setBigUint64(retPtr, BigInt(back), true);\n return E.SUCCESS;\n },\n stack_restore: (snapPtr, val) => void this.driver.restore(snapPtr, val),\n proc_join: async (pidPtr, flags, statusPtr) => void await process.join(pidPtr, flags, statusPtr),\n proc_signal: async (pid, sig) => {\n const posix = sig === 0 ? 0 : wasixSignal(sig);\n if (posix === void 0) throw new WasiError(\"EINVAL\");\n if (pid === this.host.o.pid && posix !== 0 && await this.host.onRaise?.(posix)) return;\n await this.host.o.kernel.call({ op: \"proc-kill\", pid, sig: posix });\n },\n proc_exec: async (n, nl, a, al) => await this.execOrExit(n, nl, a, al, 0, 0),\n proc_exec2: async (n, nl, a, al, e, el) => await this.execOrExit(n, nl, a, al, e, el),\n proc_exec3: async (n, nl, a, al, e, el, search, p, pl) => await process.exec({\n name: this.str(n, nl),\n argv: _WasixHost.lines(this.str(a, al)),\n env: _WasixHost.env(_WasixHost.lines(this.str(e, el))),\n search: search !== 0,\n path: this.str(p, pl)\n }),\n proc_exec4: async (n, nl, a, ac, e, ec, search, p, pl) => await process.exec({\n name: this.str(n, nl),\n argv: this.cStrings(a, ac),\n env: _WasixHost.env(e === 0 ? void 0 : this.cStrings(e, ec)),\n search: search !== 0,\n path: this.str(p, pl)\n }),\n proc_spawn2: async (...args) => {\n const [n, nl, a, al, e, el, ops, opc, , , search, p, pl, out] = args;\n const pid = await process.spawn({\n name: this.str(n, nl),\n argv: _WasixHost.lines(this.str(a, al)),\n env: _WasixHost.env(_WasixHost.lines(this.str(e, el))),\n search: search !== 0,\n path: this.str(p, pl),\n ops: this.spawnOps(ops, opc)\n });\n mem.view().setUint32(out, pid, true);\n },\n proc_spawn3: async (...args) => {\n const [n, nl, a, ac, e, ec, ops, opc, , , search, p, pl, out] = args;\n const pid = await process.spawn({\n name: this.str(n, nl),\n argv: this.cStrings(a, ac),\n env: _WasixHost.env(e === 0 ? void 0 : this.cStrings(e, ec)),\n search: search !== 0,\n path: this.str(p, pl),\n ops: this.spawnOps(ops, opc)\n });\n mem.view().setUint32(out, pid, true);\n }\n };\n }\n dlImports() {\n const { mem, host } = this;\n const failed2 = (message, buf, len) => {\n if (len > 0) {\n const bytes = new TextEncoder().encode(message).subarray(0, len - 1);\n mem.bytes(buf, bytes.length).set(bytes);\n mem.view().setUint8(buf + bytes.length, 0);\n }\n return E.NOEXEC;\n };\n const linked = async (buf, len, op, out) => {\n if (!this.linker) return failed2(\"not a dynamically-linked program\", buf, len);\n try {\n out(await op(this.linker));\n return E.SUCCESS;\n } catch (e) {\n if (e instanceof DlError) return failed2(e.message, buf, len);\n throw e;\n }\n };\n return {\n dlopen: async (p, pl, _flags, buf, len, lp, ll, out) => {\n if (p === 0) {\n if (!this.linker) return failed2(\"not a dynamically-linked program\", buf, len);\n mem.view().setUint32(out, MAIN_HANDLE, true);\n return E.SUCCESS;\n }\n return await linked(\n buf,\n len,\n async (l) => await l.open(this.str(p, pl), await host.workingDir(), lp === 0 ? [] : this.str(lp, ll).split(\":\")),\n (h) => void mem.view().setUint32(out, h === 0 ? MAIN_HANDLE : h, true)\n );\n },\n dlsym: async (handle, s, sl, buf, len, out) => await linked(\n buf,\n len,\n async (l) => await l.symbol(handle === MAIN_HANDLE ? 0 : handle, this.str(s, sl)),\n (v) => void mem.view().setUint32(out, v, true)\n ),\n dl_invalid_handle: (handle) => this.linker && (handle === MAIN_HANDLE || handle !== 0 && !this.linker.invalid(handle)) ? E.SUCCESS : E.NOEXEC\n };\n }\n threadImports() {\n const { mem, host } = this;\n const i32 = () => new Int32Array(mem.view().buffer);\n return {\n thread_id: (out) => void mem.view().setUint32(out, this.threads?.tid ?? MAIN_TID, true),\n thread_parallelism: (out) => void mem.view().setUint32(out, this.threads?.parallelism() ?? 1, true),\n thread_exit: (code2) => {\n if (this.threads && this.threads.tid !== MAIN_TID) throw new ThreadExit();\n throw new WasiExit(code2);\n },\n thread_signal: async (tid, sig) => {\n if (!(this.threads?.known(tid) ?? tid === MAIN_TID)) throw new WasiError(\"ESRCH\");\n const posix = posixSignal(sig);\n if (await host.onRaise?.(posix)) return;\n await host.o.kernel.call({ op: \"thread-kill\", tid, sig: posix });\n },\n thread_spawn_v2: async (startPtr, tidPtr) => {\n if (!this.threads) return E.NOTSUP;\n const tid = await this.threads.spawn(startPtr);\n if (tid < 0) return E.AGAIN;\n mem.view().setUint32(tidPtr, tid, true);\n return E.SUCCESS;\n },\n futex_wait: async (ptr, expected, timeoutPtr, wokenPtr) => {\n const v = mem.view();\n const timed = timeoutPtr !== 0 && v.getUint8(timeoutPtr) === 1;\n const ms = timed ? Number(v.getBigUint64(timeoutPtr + 8, true)) / 1e6 : Number.POSITIVE_INFINITY;\n const woken = host.entered || await host.futexes.wait(i32(), ptr >> 2, expected | 0, ms, host.interrupted);\n v.setUint8(wokenPtr, woken ? 1 : 0);\n },\n futex_wake: (ptr, wokenPtr) => {\n host.futexes.notify(i32(), ptr >> 2, 1);\n mem.view().setUint8(wokenPtr, 1);\n },\n futex_wake_all: (ptr, wokenPtr) => {\n host.futexes.notify(i32(), ptr >> 2);\n mem.view().setUint8(wokenPtr, 1);\n }\n };\n }\n async ttyFd() {\n for (const fd of [0, 1, 2]) {\n const e = await this.host.fds.find(fd);\n if (e?.type === \"kernel\" && await this.host.fds.kind(fd, e) === \"tty\") return fd;\n }\n return (await this.host.fds.terminals()).find((fd) => fd > 2);\n }\n async ttyGet(ptr) {\n const { host, mem } = this;\n await host.interrupted?.();\n const v = mem.view();\n mem.bytes(ptr, 24).fill(0);\n const fd = await this.ttyFd();\n const isTty2 = async (n) => {\n const e = await host.fds.find(n);\n return e?.type === \"kernel\" && await host.fds.kind(n, e) === \"tty\" ? 1 : 0;\n };\n v.setUint8(ptr + 16, await isTty2(0));\n v.setUint8(ptr + 17, await isTty2(1));\n v.setUint8(ptr + 18, await isTty2(2));\n if (fd === void 0) throw new WasiError(\"ENOTTY\");\n const [rows, cols] = await host.o.kernel.sys.winsize?.(fd) ?? [24, 80];\n const termios = await host.o.kernel.sys.tcgets?.(fd);\n v.setUint32(ptr, cols, true);\n v.setUint32(ptr + 4, rows, true);\n v.setUint8(ptr + 19, termios && termios.c_lflag & ECHO ? 1 : 0);\n v.setUint8(ptr + 20, termios && termios.c_lflag & ICANON ? 1 : 0);\n }\n async ttySet(ptr) {\n await this.host.interrupted?.();\n const fd = await this.ttyFd();\n if (fd === void 0) throw new WasiError(\"ENOTTY\");\n const { sys } = this.host.o.kernel;\n const termios = await sys.tcgets?.(fd);\n if (!termios) throw new WasiError(\"ENOTTY\");\n const v = this.mem.view();\n let lflag = termios.c_lflag & ~(ECHO | ICANON);\n if (v.getUint8(ptr + 19)) lflag |= ECHO;\n if (v.getUint8(ptr + 20)) lflag |= ICANON;\n await sys.tcsets?.(fd, { ...termios, c_lflag: lflag });\n }\n};\nfunction posixSignal(sig) {\n const posix = wasixSignal(sig);\n if (posix === void 0) throw new WasiError(\"EINVAL\");\n return posix;\n}\nfunction nsToMs(ns) {\n return Math.ceil(Number(ns) / 1e6);\n}\n\n// src/process/wasi/wasm-names.ts\nfunction parseFunctionNames(payload) {\n const names2 = /* @__PURE__ */ new Map();\n const decoder3 = new TextDecoder();\n let at = 0;\n const leb = () => {\n let value2 = 0;\n let shift = 0;\n let byte;\n do {\n if (at >= payload.length) throw new RangeError(\"truncated name section\");\n byte = payload[at++];\n value2 += (byte & 127) * 2 ** shift;\n shift += 7;\n } while (byte & 128);\n return value2;\n };\n while (at < payload.length) {\n const id = payload[at++];\n const size = leb();\n const end = at + size;\n if (end > payload.length) throw new RangeError(\"truncated name section\");\n if (id === 1) {\n for (let count = leb(); count > 0; count--) {\n const index3 = leb();\n const length = leb();\n if (at + length > end) throw new RangeError(\"truncated name section\");\n names2.set(index3, decoder3.decode(payload.subarray(at, at + length)));\n at += length;\n }\n }\n at = end;\n }\n return names2;\n}\nvar UNNAMED_FRAME = /^(\\s+at )(wasm:\\/\\/wasm\\/([^\\s()]+?):wasm-function\\[(\\d+)\\]:0x[0-9a-f]+)$/;\nvar WASM_MODULE = /wasm:\\/\\/wasm\\/([^\\s()]+?):wasm-function\\[/;\nfunction mainModule(lines) {\n for (let i = lines.length - 1; i >= 0; i--) {\n const m = WASM_MODULE.exec(lines[i]);\n if (!m) continue;\n return lines.slice(i + 1).some((line) => /^\\s+at /.test(line)) ? m[1] : void 0;\n }\n return void 0;\n}\nasync function nameFrame(line, module, name2) {\n const m = UNNAMED_FRAME.exec(line);\n if (!m || m[3] !== module) return line;\n const found = await name2(Number(m[4]));\n return found === void 0 ? line : `${m[1]}${found} (${m[2]})`;\n}\nfunction definedFunctions(bytes) {\n let at = 8;\n const leb = () => {\n let value2 = 0;\n let shift = 0;\n let byte;\n do {\n if (at >= bytes.length) throw new RangeError(\"truncated module\");\n byte = bytes[at++];\n value2 += (byte & 127) * 2 ** shift;\n shift += 7;\n } while (byte & 128);\n return value2;\n };\n while (at < bytes.length) {\n const id = bytes[at++];\n const size = leb();\n if (id === 3) return leb();\n at += size;\n }\n return 0;\n}\nfunction sidecarNames(read2, path, fit) {\n let names2;\n return async (index3) => {\n if (!names2) {\n try {\n names2 = parseFunctionNames(await read2(path));\n } catch {\n names2 = /* @__PURE__ */ new Map();\n }\n let want = names2.size;\n try {\n if (fit) want = await fit.functions();\n } catch {\n fit?.warn(`${path} can't be checked against the module, so the frames show raw indices`);\n names2 = /* @__PURE__ */ new Map();\n return void 0;\n }\n if (fit && names2.size !== want) {\n fit.warn(\n `${path} names ${names2.size} functions, but the module has ${want}: it doesn't fit, so the frames show raw indices`\n );\n names2 = /* @__PURE__ */ new Map();\n }\n }\n return names2.get(index3);\n };\n}\n\n// src/process/wasi/wasi-runtime.ts\nvar TRAPPED = 134;\nvar PREVIEW1 = \"wasi_snapshot_preview1\";\nvar WASIX = \"wasix_32v1\";\nvar SLICC = \"slicc\";\nvar SIGNAL_CALLBACK = \"__wasm_signal\";\nvar takeDefault = (call2, pid) => async (sig) => {\n await call2({ op: \"proc-kill\", pid, sig });\n if (defaultAction(sig) === \"terminate\") throw new WasiExit(128 + sig);\n};\nvar takeThreadDefault = (call2, pid) => async (sig) => {\n if (defaultAction(sig) !== \"terminate\") {\n await call2({ op: \"proc-kill\", pid, sig });\n return;\n }\n try {\n await call2({ op: \"proc-kill-self\", sig });\n } catch {\n }\n throw new WasiExit(128 + sig);\n};\nvar SLICC_FS = \"slicc_fs\";\nvar SLICC_TTY = \"slicc_tty\";\nvar RESERVED2 = RESERVED_NAMESPACES;\nvar UNDELIVERED = {\n [PREVIEW1]: [\"proc_exit\", \"clock_time_get\"],\n [WASIX]: [\"proc_exit2\", \"thread_exit\", \"thread_spawn_v2\", \"callback_signal\"],\n [SLICC]: [\"sigaction_set\", \"siginfo_take\"],\n wasi: [\"thread-spawn\"]\n};\nvar DELIVERED = [PREVIEW1, WASIX, SLICC, SLICC_FS, SLICC_TTY];\nfunction wireSignals(host, gate) {\n host.interrupted = async () => await gate.interrupt();\n host.raisedOnEntry = () => gate.raisedOnEntry();\n host.quietly = async (fn) => await gate.quiet(fn);\n host.deliverDue = async () => void await gate.interrupt();\n host.fds.restartable = () => gate.restartable();\n}\nfunction catchUpFirst(host, sync) {\n return sync && (async () => await host.quietly(() => sync.current()));\n}\nfunction deliverAll(imports, host, driver, before) {\n for (const ns of DELIVERED) {\n const table = imports[ns];\n if (table) imports[ns] = delivering(ns, table, host, driver, before);\n }\n}\nfunction delivering(ns, table, host, driver, before) {\n const exempt = new Set(UNDELIVERED[ns]);\n const out = {};\n for (const [name2, value2] of Object.entries(table)) {\n if (exempt.has(name2) || typeof value2 !== \"function\") {\n out[name2] = value2;\n continue;\n }\n const fn = value2;\n out[name2] = async (...args) => {\n host.entered = false;\n if (driver.idle) {\n await before?.();\n host.entered = await host.interrupted?.() === true;\n host.enteredSignals = host.entered ? host.raisedOnEntry?.() ?? -1 : 0;\n }\n return await fn(...args);\n };\n }\n return out;\n}\nvar importsSlicc = (module, name2) => WebAssembly.Module.imports(module).some((i) => i.module === SLICC && i.name === name2);\nvar importsSigactionHook = (module) => importsSlicc(module, \"sigaction_set\");\nfunction sigmaskOf(module, sab, gate, threads, process, published) {\n const header = new Int32Array(sab, 0, SAB_HEADER_I32);\n if (!importsSlicc(module, \"sigmask_set\")) {\n WasiSigmask.unsupported(header);\n return void 0;\n }\n if (threads) threads.blocked = () => loadBlocked(header);\n const shared = process && new Int32Array(process, 0, SAB_HEADER_I32);\n return new WasiSigmask(header, async () => await gate.deliver(), shared, threads?.tid ?? MAIN_TID, published);\n}\nvar noErrno = (key) => `imports ${key}: its result cannot carry ENOSYS, and this host does not provide it`;\nfunction enosys(module, name2, foreign) {\n const type = foreign?.[module]?.[name2];\n if (type === \"other\") throw new Error(noErrno(`${module}.${name2}`));\n if (type === \"none\") return () => void 0;\n if (type === \"i64\") return () => 52n;\n return () => 52;\n}\nfunction firstOther(foreign) {\n for (const [module, fields] of Object.entries(foreign)) {\n const name2 = Object.keys(fields).find((field2) => fields[field2] === \"other\");\n if (name2 !== void 0) return `${module}.${name2}`;\n }\n return void 0;\n}\nfunction accepted(imp, scope) {\n const { module, name: name2, kind } = imp;\n if (module === PREVIEW1 || module === WASIX) return true;\n if (!RESERVED2.has(module) && (scope.extended || scope.wasi && kind === \"function\")) return true;\n if (scope.pie && (module === \"GOT.mem\" || module === \"GOT.func\")) return true;\n if (scope.pie && module === \"env\" && kind !== \"memory\") return true;\n if (kind === \"memory\" && scope.memory?.module === module && scope.memory.name === name2)\n return true;\n return module === \"wasi\" && name2 === \"thread-spawn\" && (scope.wasix || !!scope.memory?.shared);\n}\nfunction unsupportedImport(module, memory, extended = false, foreign = {}) {\n const imports = WebAssembly.Module.imports(module);\n const wasix = imports.some((i) => i.module === WASIX);\n const wasi = wasix || imports.some((i) => i.module === PREVIEW1);\n const scope = { extended, wasi, wasix, pie: dylinkInfo(module) !== void 0, memory };\n const refused3 = imports.find((imp) => !accepted(imp, scope));\n if (refused3) {\n if (refused3.kind === \"memory\" || refused3.module === \"wasi\") {\n return `imports ${refused3.module}.${refused3.name}: no WASI program this host runs`;\n }\n return `imports ${refused3.module}.${refused3.name}: no WASI preview1 program (an Emscripten one runs with its glue)`;\n }\n const unanswerable = extended ? void 0 : firstOther(foreign);\n if (unanswerable) return noErrno(unanswerable);\n if (!WebAssembly.Module.exports(module).some((e) => e.name === \"_start\")) {\n return \"no WASI command (it exports no _start)\";\n }\n return void 0;\n}\nfunction linkImports(module, preview1, wasix, memory, threads, program = {}, foreign, slicc = {}, sliccFs = {}, sliccTty2 = {}) {\n for (const ns of Object.keys(program)) {\n if (RESERVED2.has(ns) || ns === SLICC || ns === SLICC_FS || ns === SLICC_TTY)\n throw new Error(`the imports module may not define ${ns}`);\n }\n const imports = {\n ...program,\n [SLICC]: { ...slicc },\n [SLICC_FS]: { ...sliccFs },\n [SLICC_TTY]: { ...sliccTty2 },\n [PREVIEW1]: preview1,\n ...wasix ? { [WASIX]: { ...wasix } } : {},\n ...threads ? { wasi: { \"thread-spawn\": async (arg) => await threads.spawn(arg) } } : {}\n };\n for (const imp of WebAssembly.Module.imports(module)) {\n const ns = imports[imp.module] ??= {};\n if (imp.name in ns) continue;\n if (imp.kind === \"memory\" && memory) ns[imp.name] = memory;\n else if (imp.module === \"wasi\" && imp.name === \"thread-spawn\") ns[imp.name] = () => -1;\n else if (imp.kind === \"function\") ns[imp.name] = enosys(imp.module, imp.name, foreign);\n }\n return imports;\n}\nvar FALLBACK_MAXIMUM_PAGES = 32768;\nfunction newImportedMemory(spec) {\n const maximum = spec.maximum ?? 65536;\n try {\n return new WebAssembly.Memory({ initial: spec.initial, maximum, shared: spec.shared });\n } catch (err) {\n if (!(err instanceof RangeError) || maximum <= FALLBACK_MAXIMUM_PAGES) throw err;\n if (spec.initial > FALLBACK_MAXIMUM_PAGES) throw err;\n return new WebAssembly.Memory({\n initial: spec.initial,\n maximum: FALLBACK_MAXIMUM_PAGES,\n shared: spec.shared\n });\n }\n}\nfunction createImportedMemory(spec, copy) {\n if (!spec) return void 0;\n const memory = newImportedMemory(spec);\n if (copy) fillMemory(memory, copy);\n return memory;\n}\nfunction restoreExportedMemory(instance, imported, init) {\n if (imported || !init.fork?.wasi) return;\n fillMemory(instance.exports.memory, init.fork.memory);\n init.fork.memory = new Uint8Array(0);\n}\nfunction fillMemory(memory, copy) {\n const pages2 = copy.byteLength / 65536 - memory.buffer.byteLength / 65536;\n if (pages2 > 0) memory.grow(pages2);\n new Uint8Array(memory.buffer).set(copy);\n}\nfunction sizeOf(main) {\n return () => main.memory?.buffer.byteLength ?? 0;\n}\nfunction memoryOf(instance, imported) {\n return imported ?? instance.exports.memory;\n}\nvar sabTransport = (sab, port, memory) => createSyncSabTransport(sab, port, memory ? { memory } : {});\nfunction kernelOf(init, port, hooks = { masks: () => null, raise: () => {\n} }, memory, transports = sabTransport) {\n const raw = transports(init.sab, port, memory);\n const gate = new SignalGate(raw, new Int32Array(init.sab, 0, SAB_HEADER_I32), hooks);\n const transport = gate.transport();\n const sys = kernelSys(transport);\n const call2 = async (req) => {\n const r = await transport.call(req, Number.POSITIVE_INFINITY, req.op);\n if (!r.ok) throw new SyscallError(r.errno);\n return r.kind === \"json\" ? r.json : r.kind === \"bytes\" ? r.bytes : void 0;\n };\n const say = async (text) => await sys.write(2, new TextEncoder().encode(`${init.argv0}: ${text}\n`));\n const published = raw.publish && (() => raw.publish?.());\n return { transport, sys, call: call2, say, gate, published };\n}\nfunction traced(stats, tag, table) {\n return stats ? stats.wrap(tag, table) : table;\n}\nfunction timedCalls(stats, call2) {\n return async (req) => await stats.time(`kernel.${req.op}`, async () => await call2(req));\n}\nasync function report(stats, sys) {\n stats.phase(\"run\");\n try {\n await sys.write(2, new TextEncoder().encode(stats.report()));\n } catch {\n }\n}\nvar START_STACK = 0;\nvar START_STACK_SIZE = 56;\nfunction isWasix(module) {\n return WebAssembly.Module.imports(module).some((i) => i.module === WASIX);\n}\nvar MIN_THREAD_STACK = 4096;\nvar START_ARGS_SLACK = 64;\nfunction threadStackLow(memory, start2) {\n if (start2 < 0 || start2 + START_ARGS_SLACK > memory.byteLength) return void 0;\n const stack = memory.getUint32(start2 + START_STACK, true);\n const size = memory.getUint32(start2 + START_STACK_SIZE, true);\n if (size < MIN_THREAD_STACK || size > memory.byteLength || size > stack) return void 0;\n if (stack % 16 !== 0 || stack > start2 + START_ARGS_SLACK || stack + START_ARGS_SLACK < start2) {\n return void 0;\n }\n return stack - size;\n}\nfunction ownStack(driver, instance, linked, low) {\n const own = instance.exports.__stack_pointer;\n const pointer = own instanceof WebAssembly.Global ? own : linked;\n if (!pointer) return false;\n driver.useThreadStack(pointer, low);\n return true;\n}\nasync function untilDone(run, driver) {\n do\n await run();\n while (await driver.resume());\n}\nfunction threadStart(instance) {\n return reentered(instance.exports.wasi_thread_start);\n}\nfunction spawnsThreads(module) {\n return WebAssembly.Module.imports(module).some(\n (i) => i.module === \"wasi\" && i.name === \"thread-spawn\" || i.module === WASIX && i.name === \"thread_spawn_v2\"\n );\n}\nasync function instantiate(host, module, memory, threads, {\n thread = false,\n forked,\n stats,\n signals,\n program,\n foreign,\n path\n} = {}) {\n const driver = new AsyncifyDriver(host.mem);\n const wasixHost = WebAssembly.Module.imports(module).some((i) => i.module === WASIX) ? new WasixHost(host, driver, module) : void 0;\n if (wasixHost) {\n wasixHost.threads = threads;\n wasixHost.signals = signals;\n }\n let preview1 = traced(stats, \"wasi\", {\n ...host.imports(),\n ...wasixHost?.preview1()\n });\n let wasix = wasixHost && traced(stats, \"wasix\", wasixHost.imports());\n const info = dylinkInfo(module);\n const sync = info && memory ? new LinkSync(\n new WasixLinker(\n memory,\n info,\n linkerHost(host, () => imports),\n thread\n ),\n async (req) => await host.o.kernel.call(req),\n threads\n ) : void 0;\n if (sync) {\n ({ preview1, wasix } = sync.guard(preview1, wasix));\n if (wasixHost) {\n wasixHost.linker = sync.linker;\n wasixHost.types = sync.linker.types;\n }\n if (threads) {\n sync.linker.cache = threads.received;\n threads.modules = () => sync.linker.compiled();\n }\n }\n let instance;\n const extra = await program?.(\n () => memory ?? instance?.exports.memory,\n () => instance\n );\n const slicc = traced(stats, \"slicc\", host.sliccImports());\n const sliccFs = traced(stats, \"slicc_fs\", host.sliccFsImports());\n const sliccTty2 = traced(stats, \"slicc_tty\", host.sliccTtyImports());\n const hostImports = linkImports(\n module,\n preview1,\n wasix,\n memory,\n threads,\n extra,\n foreign,\n slicc,\n sliccFs,\n sliccTty2\n );\n deliverAll(hostImports, host, driver, catchUpFirst(host, sync));\n const imports = sync ? merge(hostImports, sync.linker.mainImports(module)) : hostImports;\n instance = await WebAssembly.instantiate(module, suspendingImports(imports));\n stats?.phase(\"instantiate\");\n const exports = instance.exports;\n host.mem.bind(memory ?? exports.memory);\n if (wasixHost) {\n const table = sync?.linker.table ?? exportedTable(instance);\n wasixHost.table = table;\n if (path !== void 0) {\n const read2 = linkerHost(host, () => ({})).read;\n wasixHost.types.register(async () => await read2(path), instance, table, sync ? TABLE_BASE2 : 0);\n }\n }\n if (sync) await bindLinker(host, sync, instance, { thread, forked, path });\n if (sync && !thread) driver.useStack(sync.linker.stackPointer, sync.linker.stackLow);\n return { instance, driver, linkedStack: sync?.linker.stackPointer };\n}\nasync function bindLinker(host, sync, instance, at) {\n await sync.linker.bindMain(instance, !at.thread && !at.forked);\n if (at.path !== void 0) sync.linker.mainPath = at.path;\n host.linkedTls = () => sync.linker.tlsBases();\n host.linkedModules = () => sync.linker.compiled();\n if (at.forked) {\n sync.linker.forkedTls = new Map(at.forked.tls ?? []);\n sync.linker.cache = at.forked.modules;\n }\n if (at.thread || at.forked) await sync.catchUp();\n await sync.linker.bindMainGot();\n}\nfunction procTree(call2, pid) {\n return new ProcTree(\n {\n procList: async () => await call2({ op: \"proc-list\" }),\n mountList: async () => await call2({ op: \"mount-list\" })\n },\n pid\n );\n}\nfunction devNodes(call2) {\n return async () => await call2({ op: \"fd-dev-nodes\" });\n}\nfunction exportedTable(instance) {\n const table = instance.exports.__indirect_function_table;\n return table instanceof WebAssembly.Table ? table : void 0;\n}\nfunction linkerHost(host, imports) {\n return {\n read: async (path) => {\n try {\n return await host.o.fs.readFile(path);\n } catch {\n return void 0;\n }\n },\n hostImports: () => {\n const { env: _env, \"GOT.mem\": _mem, \"GOT.func\": _func, ...rest2 } = imports();\n return rest2;\n },\n real: async (path) => await physicalPath(host.o.fs, path)\n };\n}\nfunction merge(base, extra) {\n const out = { ...base };\n for (const [ns, values] of Object.entries(extra)) out[ns] = { ...base[ns], ...values };\n return out;\n}\nvar LinkSync = class {\n count = 0;\n gen = 0;\n linker;\n call;\n ids;\n owner;\n constructor(linker, call2, threads) {\n this.linker = linker;\n this.call = call2;\n this.ids = threads?.ids;\n this.owner = threads?.tid ?? 0;\n linker.publisher = async (record) => await this.publish(record);\n linker.indices = {\n reserve: async (floor, size) => await this.call({ op: \"dl-reserve\", floor, size }),\n load: async (floor, size) => await this.call({ op: \"dl-load-reserve\", floor, size }),\n lock: async () => {\n await this.call({ op: \"dl-lock\", owner: this.owner });\n try {\n await this.catchUp();\n } catch (e) {\n await this.call({ op: \"dl-unlock\", owner: this.owner });\n throw e;\n }\n },\n unlock: async () => await this.call({ op: \"dl-unlock\", owner: this.owner }),\n allocate: async (floor) => {\n const index3 = await this.call({ op: \"dl-closure\", floor });\n await this.catchUp();\n this.bump();\n return index3;\n },\n free: async (index3) => {\n await this.call({ op: \"dl-closure-free\", index: index3 });\n this.bump();\n }\n };\n }\n bump() {\n if (this.ids) Atomics.add(this.ids, DL_GEN, 1);\n }\n async publish(record) {\n const since = await this.call({ op: \"dl-log\", append: record, from: this.count });\n for (const r of since.slice(0, -1)) await this.linker.replay(r);\n this.count += since.length;\n this.bump();\n await this.catchUp();\n }\n async current() {\n if (this.ids && Atomics.load(this.ids, DL_GEN) !== this.gen) await this.catchUp();\n }\n async catchUp() {\n for (; ; ) {\n const gen = this.ids ? Atomics.load(this.ids, DL_GEN) : 0;\n const since = await this.call({ op: \"dl-log\", from: this.count });\n for (const r of since) await this.linker.replay(r);\n this.count += since.length;\n if (!this.ids || Atomics.load(this.ids, DL_GEN) === gen) {\n this.gen = gen;\n return;\n }\n }\n }\n guard(preview1, wasix) {\n const ids = this.ids;\n if (!ids) return { preview1, wasix };\n const wrap2 = (table) => Object.fromEntries(\n Object.entries(table).map(([name2, fn]) => [\n name2,\n (async (...args) => {\n await this.current();\n const result = await fn(...args);\n await this.current();\n return result;\n })\n ])\n );\n return { preview1: wrap2(preview1), wasix: wasix && wrap2(wasix) };\n }\n};\nvar DL_GEN = 3;\nfunction descriptors(init, fork, threads) {\n if (fork?.shared && threads) return { shared: threads.ids };\n if (fork) return { forked: { fds: fork.fds, cloexec: fork.cloexec } };\n return { inherited: init.fds ?? [], ...init.program.preopenRoot ? { preopenRoot: true } : {} };\n}\nfunction ownersOf(init) {\n return {\n ...init.owners ? { owners: true } : {},\n ...init.links ? { links: true } : {},\n ...init.changes ? { changes: init.changes } : {}\n };\n}\nfunction heldOf(init, call2) {\n const { held } = init;\n if (!held) return {};\n const ask = async () => await call2({ op: \"cwd-check\" });\n return { held: new HeldCwd(held.sab, held.slot, ask, { ...held, path: init.cwd }) };\n}\nfunction mainThreads(port, module, memory, cap) {\n return memory?.buffer instanceof SharedArrayBuffer && spawnsThreads(module) ? new WasiThreads(port, memory, cap, MAIN_TID) : void 0;\n}\nasync function runWasiProcess(init, port, given = {}) {\n captureBacktraces(init.env);\n const signals = new WasiSignals(\n takeDefault(async (req) => await call2(req), init.pid),\n (code2) => {\n throw new WasiExit(code2);\n }\n );\n const main = {};\n const {\n transport,\n sys,\n call: kernelCall,\n say,\n gate,\n published\n } = kernelOf(init, port, signals, sizeOf(main), given.transport);\n const id = await identify(transport, init);\n const stats = init.env.SLICC_WASI_STATS === \"1\" ? new WasiStats() : void 0;\n const call2 = stats ? timedCalls(stats, kernelCall) : kernelCall;\n const { module } = init.program;\n const refused3 = unsupportedImport(\n module,\n init.program.memory,\n init.program.imports !== void 0,\n init.program.foreign\n );\n if (refused3) {\n await say(refused3);\n return 126;\n }\n const fork = init.fork?.wasi;\n const memory = createImportedMemory(init.program.memory, fork ? init.fork?.memory : void 0);\n const threads = mainThreads(port, module, memory, given.threadCap ?? threadCap(init.env));\n const host = await new WasiHost({\n args: [init.argv0, ...init.args],\n env: init.env,\n cwd: fork?.cwd ?? init.cwd,\n pid: id.pid,\n ppid: id.ppid,\n parent: async () => (await identify(transport, init)).ppid,\n kernel: { sys: traced(stats, \"kernel\", sys), call: call2 },\n fs: ptsBridge(\n sysfsBridge(\n procfsBridge(\n cachingBridge(\n traced(\n stats,\n \"fs\",\n createSyncFsSabBridge(transport, { ...ownersOf(init), direct: true })\n ),\n void 0,\n threads?.ids\n ),\n procTree(call2, id.pid)\n ),\n devNodes(call2)\n ),\n call2\n ),\n ...descriptors(init, fork, threads),\n ...heldOf(init, call2),\n ...threads ? { credGen: threads.ids } : {}\n }).attach();\n if (given.futexes) host.futexes = given.futexes;\n host.sigmask = sigmaskOf(module, init.sab, gate, threads, void 0, published);\n if (threads) {\n threads.beforeSpawn = async () => {\n if (!host.fds.isShared) await host.fds.share(threads.ids, false);\n };\n }\n const program = await programImports(init.program, host, transport, MAIN_TID, given.imports);\n const { instance, driver, linkedStack } = await instantiate(host, module, memory, threads, {\n ...fork ? { forked: fork } : {},\n stats,\n signals,\n foreign: init.program.foreign,\n path: init.program.path,\n ...program ? { program } : {}\n });\n restoreExportedMemory(instance, memory, init);\n main.memory = memoryOf(instance, memory);\n publishMemory(init.sab, sizeOf(main)());\n port.postMessage({ type: WASM_PROCESS_READY });\n signals.bind(instance.exports);\n if (importsSigactionHook(module)) signals.useHook();\n if (fork?.signals) signals.restore(fork.signals);\n host.signals = signals;\n wireSignals(host, gate);\n host.onRaise = async (sig) => await signals.raised(sig);\n host.muted = (fd, data) => signals.muted(fd, data);\n const exports = instance.exports;\n driver.bind(instance.exports);\n const entry = fork?.entry;\n if (entry) {\n ownStack(driver, instance, linkedStack, entry.low);\n host.threadEntry = entry;\n }\n const run = entry ? async () => await threadStart(instance)(entry.tid, entry.arg) : async () => await reentered(exports._start)();\n try {\n if (fork) driver.startChild(fork);\n await untilDone(run, driver);\n return 0;\n } catch (e) {\n if (e instanceof WasiExit) return e.code;\n if (!(e instanceof WebAssembly.RuntimeError)) throw e;\n try {\n await say(await trapReport(e, init, host, \"\"));\n } catch {\n throw new Error(`${init.argv0}: wasm trap: ${e.message}`);\n }\n return TRAPPED;\n } finally {\n await host.flushAll();\n if (stats) await report(stats, sys);\n }\n}\nvar BACKTRACE_FRAMES = 40;\nasync function trapMessage(e, env, where = \"\", name2) {\n const head = `wasm trap${where}: ${e.message}`;\n if (env.SLICC_WASM_BACKTRACE !== \"1\") return head;\n const lines = (rawStack(e) ?? \"\").split(\"\\n\");\n const main = name2 && mainModule(lines);\n const frames = [];\n const shown = lines.filter((line) => /^\\s+at .*wasm:\\/\\/wasm\\//.test(line)).slice(0, BACKTRACE_FRAMES);\n for (const line of shown) frames.push(name2 && main ? await nameFrame(line, main, name2) : line);\n return frames.length ? `${head}\n${frames.join(\"\\n\")}` : head;\n}\nasync function trapReport(e, init, host, where) {\n const warned = [];\n const message = await trapMessage(e, init.env, where, programNames(host, init.program, warned));\n return [...warned, message].join(`\n${init.argv0}: `);\n}\nfunction programNames(host, program, warned) {\n const path = program.names;\n if (path === void 0) return void 0;\n const read2 = async (p) => await host.o.fs.readFile(p);\n const imported = WebAssembly.Module.imports(program.module).filter((i) => i.kind === \"function\");\n return sidecarNames(read2, path, {\n functions: async () => imported.length + definedFunctions(await read2(program.path)),\n warn: (line) => warned.push(line)\n });\n}\nasync function programImports(program, host, transport, tid, given) {\n if (program.imports === void 0) return void 0;\n const create = given ?? await loadImports(program.imports);\n const raw = async (req) => await transport.call(req, Number.POSITIVE_INFINITY, req.op);\n return async (memory, instance) => await create(importsContext({ host, raw, tid, memory, instance }));\n}\nfunction captureBacktraces(env) {\n if (env.SLICC_WASM_BACKTRACE !== \"1\") return;\n const v8 = Error;\n v8.stackTraceLimit = Math.max(v8.stackTraceLimit ?? 0, BACKTRACE_FRAMES + 20);\n}\nasync function runWasiThread(init, port, given = {}) {\n captureBacktraces(init.env);\n const { thread } = init;\n const kernelFor = (hooks) => kernelOf(init, port, hooks, void 0, given.transport);\n const { transport, sys, call: call2, say, gate } = kernelFor({\n masks: () => null,\n raise: async (sig) => await signals.raise(sig)\n });\n const signals = new WasiSignals(takeThreadDefault(call2, init.pid));\n const cap = given.threadCap ?? threadCap(init.env);\n const threads = new WasiThreads(port, thread.memory, cap, thread.tid, thread.ids);\n threads.received = thread.modules;\n const id = await identify(transport, init);\n const host = await new WasiHost({\n args: [init.argv0, ...init.args],\n env: init.env,\n cwd: init.cwd,\n pid: id.pid,\n ppid: id.ppid,\n parent: async () => (await identify(transport, init)).ppid,\n kernel: { sys, call: call2 },\n fs: ptsBridge(\n sysfsBridge(\n procfsBridge(\n cachingBridge(\n createSyncFsSabBridge(transport, { ...ownersOf(init), direct: true }),\n void 0,\n threads.ids\n ),\n procTree(call2, id.pid)\n ),\n devNodes(call2)\n ),\n call2\n ),\n shared: threads.ids,\n ...heldOf(init, call2)\n }).attach();\n host.tid = thread.tid;\n if (given.futexes) host.futexes = given.futexes;\n host.sigmask = sigmaskOf(init.program.module, init.sab, gate, threads, init.signals);\n const program = await programImports(init.program, host, transport, thread.tid, given.imports);\n const { module } = init.program;\n const { memory } = thread;\n const { instance, driver, linkedStack } = await instantiate(host, module, memory, threads, {\n thread: true,\n foreign: init.program.foreign,\n path: init.program.path,\n ...program ? { program } : {}\n });\n signals.bind(instance.exports);\n signals.register(SIGNAL_CALLBACK);\n wireSignals(host, gate);\n host.onRaise = async (sig) => await signals.raised(sig);\n const low = isWasix(module) ? threadStackLow(host.mem.view(), thread.arg) : void 0;\n if (low !== void 0 && ownStack(driver, instance, linkedStack, low)) {\n driver.bind(instance.exports);\n host.threadEntry = { tid: thread.tid, arg: thread.arg, low };\n }\n const start2 = threadStart(instance);\n try {\n await untilDone(async () => await start2(thread.tid, thread.arg), driver);\n threads.exited();\n } catch (e) {\n if (e instanceof ThreadExit) {\n threads.exited();\n return;\n }\n if (e instanceof WasiExit) {\n port.postMessage({ type: WASM_PROCESS_EXIT, code: e.code });\n return;\n }\n if (e instanceof WebAssembly.RuntimeError) {\n try {\n await say(await trapReport(e, init, host, ` in thread ${thread.tid}`));\n } catch {\n }\n port.postMessage({ type: WASM_PROCESS_EXIT, code: TRAPPED });\n return;\n }\n throw e;\n }\n}\n\n// src/process/emscripten/errno.ts\nvar EM = {\n AGAIN: 6,\n BADF: 8,\n BUSY: 10,\n CHILD: 12,\n EXIST: 20,\n FAULT: 21,\n INTR: 27,\n INVAL: 28,\n IO: 29,\n ISDIR: 31,\n LOOP: 32,\n MLINK: 34,\n NAMETOOLONG: 37,\n NOENT: 44,\n NOMEM: 48,\n NOSYS: 52,\n NOTDIR: 54,\n NOTEMPTY: 55,\n NOTSOCK: 57,\n NOTTY: 59,\n NXIO: 60,\n OVERFLOW: 61,\n PERM: 63,\n PIPE: 64,\n RANGE: 68,\n SPIPE: 70,\n XDEV: 75,\n NOTSUP: 138\n};\nvar EmError = class extends Error {\n errno;\n constructor(errno) {\n super(`errno ${errno}`);\n this.errno = errno;\n }\n};\nfunction errnoOf(e) {\n if (e instanceof EmError) return e.errno;\n const code2 = e?.code;\n if (typeof code2 === \"string\") return wasiErrno(code2);\n if (e instanceof RangeError) return EM.FAULT;\n return void 0;\n}\nfunction negated(fn) {\n return async (...args) => {\n try {\n return Number(await fn(...args) ?? 0);\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n };\n}\nfunction positive(fn) {\n return async (...args) => {\n try {\n return Number(await fn(...args) ?? 0);\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return errno;\n }\n };\n}\n\n// src/process/emscripten/cwd.ts\nvar AT_FDCWD2 = -100;\nvar X_OK2 = 1;\nvar EmCwd = class {\n path;\n held;\n host;\n call;\n constructor(host, path, call2, held) {\n this.host = host;\n this.path = path;\n this.call = call2;\n if (held) {\n const ask = async () => await call2({ op: \"cwd-check\" });\n this.held = new HeldCwd(held.sab, held.slot, ask, { ...held, path });\n }\n }\n async gone() {\n return this.held !== void 0 && !await this.held.alive(this.path);\n }\n async base(dirfd) {\n if (dirfd === AT_FDCWD2) return this.path;\n const e = await this.host.fds.get(dirfd);\n if (e.type === \"dir\") return e.path;\n if (e.type === \"file\") return e.file.path;\n throw new EmError(EM.NOTDIR);\n }\n async resolve(dirfd, raw, allowEmpty = false) {\n if (raw === \"\") {\n if (!allowEmpty) throw new EmError(EM.NOENT);\n return await this.base(dirfd);\n }\n if (raw.startsWith(\"/\")) return await this.host.fds.resolve(0, raw);\n const relativeHere = raw.split(\"/\")[0] !== \"..\";\n if (dirfd === AT_FDCWD2 && relativeHere && await this.gone()) throw new EmError(EM.NOENT);\n const base = await this.base(dirfd);\n return await this.host.fds.resolve(0, `${base === \"/\" ? \"\" : base}/${raw}`);\n }\n async chdir(abs) {\n const fs = this.host.o.fs;\n const real = await physicalPath(fs, abs);\n const st = await fs.stat(real);\n if (!st.isDirectory) throw new EmError(EM.NOTDIR);\n if (fs.owners) await fs.access?.(real, X_OK2, \"eaccess\", false);\n this.path = real;\n if (this.held) {\n const reply = await this.call({ op: \"cwd-chdir\", path: real });\n this.held.moved(reply, real);\n }\n }\n};\n\n// src/process/emscripten/dns.ts\nvar htons = (v) => (v & 255) << 8 | v >> 8 & 255;\nvar htonl = (v) => ((v & 255) << 24 | (v & 65280) << 8 | v >>> 8 & 65280 | v >>> 24 & 255) >>> 0;\nfunction pton4(str) {\n const b = str.split(\".\");\n const n = [];\n for (let i = 0; i < 4; i++) {\n const tmp = Number(b[i]);\n if (Number.isNaN(tmp)) return null;\n n.push(tmp);\n }\n return (n[0] | n[1] << 8 | n[2] << 16 | n[3] << 24) >>> 0;\n}\nvar VALID6 = /^((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|$))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})$/i;\nfunction pton6(input) {\n if (!VALID6.test(input)) return null;\n if (input === \"::\") return [0, 0, 0, 0, 0, 0, 0, 0];\n let str = input.startsWith(\"::\") ? input.replace(\"::\", \"Z:\") : input.replace(\"::\", \":Z:\");\n let words;\n if (str.indexOf(\".\") > 0) {\n str = str.replace(/[.]/g, \":\");\n words = str.split(\":\");\n const n = words.length;\n words[n - 4] = Number(words[n - 4]) + Number(words[n - 3]) * 256;\n words[n - 3] = Number(words[n - 2]) + Number(words[n - 1]) * 256;\n words = words.slice(0, n - 2);\n } else {\n words = str.split(\":\");\n }\n const parts = [];\n let offset = 0;\n for (let w = 0; w < words.length; w++) {\n const word = words[w];\n if (typeof word === \"string\") {\n if (word === \"Z\") {\n let z = 0;\n for (z = 0; z < 8 - words.length + 1; z++) parts[w + z] = 0;\n offset = z - 1;\n } else {\n parts[w + offset] = htons(Number.parseInt(word, 16));\n }\n } else {\n parts[w + offset] = word;\n }\n }\n const p = (i) => parts[i] ?? 0;\n return [p(1) << 16 | p(0), p(3) << 16 | p(2), p(5) << 16 | p(4), p(7) << 16 | p(6)];\n}\nvar names = /* @__PURE__ */ new Map();\nvar nextId = 1;\nfunction lookupName(name2) {\n if (pton4(name2) !== null || pton6(name2) !== null) return name2;\n const known = names.get(name2);\n if (known) return known;\n const id = nextId++;\n const addr = `172.29.${id & 255}.${id & 65280}`;\n names.set(name2, addr);\n return addr;\n}\nfunction writeSockaddr(ctx, sa, family, addr, port) {\n const v = ctx.mem.view();\n if (family === 2) {\n ctx.mem.bytes(sa, 16).fill(0);\n v.setInt16(sa, family, true);\n v.setInt32(sa + 4, addr, true);\n v.setInt16(sa + 2, htons(port), true);\n return;\n }\n const a = addr;\n ctx.mem.bytes(sa, 28).fill(0);\n v.setInt32(sa, family, true);\n for (let i = 0; i < 4; i++) v.setInt32(sa + 8 + i * 4, a[i] ?? 0, true);\n v.setInt16(sa + 2, htons(port), true);\n}\nfunction allocInfo(ctx, ai) {\n const malloc = ctx.exports().malloc;\n const salen = ai.family === 10 ? 28 : 16;\n const sa = malloc(salen);\n writeSockaddr(ctx, sa, ai.family, ai.addr, ai.port);\n const out = malloc(32);\n const v = ctx.mem.view();\n v.setInt32(out + 4, ai.family, true);\n v.setInt32(out + 8, ai.type, true);\n v.setInt32(out + 12, ai.proto, true);\n v.setUint32(out + 24, ai.canon >>> 0, true);\n v.setUint32(out + 20, sa, true);\n v.setInt32(out + 16, salen, true);\n v.setInt32(out + 28, 0, true);\n return out;\n}\nfunction hintsOf(ctx, hint) {\n const v = ctx.mem.view();\n const h = hint ? {\n flags: v.getInt32(hint, true),\n family: v.getInt32(hint + 4, true),\n type: v.getInt32(hint + 8, true),\n proto: v.getInt32(hint + 12, true)\n } : { flags: 0, family: 0, type: 0, proto: 0 };\n if (h.type && !h.proto) h.proto = h.type === 2 ? 17 : 6;\n if (!h.type && h.proto) h.type = h.proto === 17 ? 2 : 1;\n if (h.proto === 0) h.proto = 6;\n if (h.type === 0) h.type = 1;\n return h;\n}\nfunction refused2(h, node, service) {\n if (!node && !service) return -2;\n if (h.flags & ~(1 | 2 | 4 | 1024 | 8 | 16 | 32)) return -1;\n if (h.flags & 2 && !node) return -1;\n if (h.flags & 32) return -2;\n if (h.type !== 0 && h.type !== 1 && h.type !== 2) return -7;\n if (h.family !== 0 && h.family !== 2 && h.family !== 10) return -6;\n return 0;\n}\nfunction numeric(h, node) {\n const four = pton4(node);\n if (four !== null) {\n if (h.family === 0 || h.family === 2) {\n h.family = 2;\n return four;\n }\n if (h.family === 10 && h.flags & 8) return [0, 0, htonl(65535), four];\n return void 0;\n }\n const six = pton6(node);\n if (six === null) return null;\n if (h.family !== 0 && h.family !== 10) return void 0;\n h.family = 10;\n return six;\n}\nfunction getaddrinfo(ctx, nodePtr, servicePtr, hint, out) {\n const h = hintsOf(ctx, hint);\n const bad = refused2(h, nodePtr, servicePtr);\n if (bad !== 0) return bad;\n let port = 0;\n if (servicePtr) {\n port = Number.parseInt(ctx.mem.cString(servicePtr), 10);\n if (Number.isNaN(port)) return h.flags & 1024 ? -2 : -8;\n }\n const put = (canon, addr2) => {\n const ai = allocInfo(ctx, {\n family: h.family,\n type: h.type,\n proto: h.proto,\n canon,\n addr: addr2,\n port\n });\n ctx.mem.view().setUint32(out, ai, true);\n return 0;\n };\n if (!nodePtr) {\n if (h.family === 0) h.family = 2;\n if (h.flags & 1) return put(0, 0);\n return put(0, h.family === 2 ? htonl(2130706433) : [0, 0, 0, htonl(1)]);\n }\n const node = ctx.mem.cString(nodePtr);\n const addr = numeric(h, node);\n if (addr === void 0) return -2;\n if (addr !== null) return put(Number(node) >>> 0, addr);\n if (h.flags & 4) return -2;\n const fake = pton4(lookupName(node));\n if (h.family === 0) h.family = 2;\n return put(0, h.family === 10 ? [0, 0, htonl(65535), fake] : fake);\n}\nfunction dnsImports(ctx) {\n return {\n getaddrinfo: (node, service, hint, out) => getaddrinfo(ctx, node, service, hint, out),\n _emscripten_lookup_name: (name2) => pton4(lookupName(ctx.mem.cString(name2)))\n };\n}\n\n// src/process/emscripten/layout.ts\nvar S_IFMT2 = 61440;\nvar S_IFSOCK = 49152;\nvar S_IFLNK2 = 40960;\nvar S_IFREG = 32768;\nvar S_IFDIR = 16384;\nvar S_IFCHR = 8192;\nvar S_IFIFO2 = 4096;\nfunction putTime(v, at, ms) {\n v.setBigInt64(at, BigInt(Math.floor(ms / 1e3)), true);\n v.setUint32(at + 8, Math.round(ms % 1e3 * 1e3 * 1e3) >>> 0, true);\n}\nfunction writeStat(mem, buf, st) {\n const v = mem.view();\n v.setUint32(buf, st.dev >>> 0, true);\n v.setUint32(buf + 4, st.mode >>> 0, true);\n v.setUint32(buf + 8, st.nlink >>> 0, true);\n v.setUint32(buf + 12, st.uid >>> 0, true);\n v.setUint32(buf + 16, st.gid >>> 0, true);\n v.setUint32(buf + 20, st.rdev >>> 0, true);\n v.setBigInt64(buf + 24, BigInt(st.size), true);\n v.setInt32(buf + 32, 4096, true);\n v.setInt32(buf + 36, st.blocks, true);\n putTime(v, buf + 40, st.atimeMs);\n putTime(v, buf + 56, st.mtimeMs);\n putTime(v, buf + 72, st.ctimeMs);\n v.setBigInt64(buf + 88, BigInt(st.ino), true);\n}\nfunction writeStatfs(mem, buf, s) {\n const v = mem.view();\n v.setUint32(buf + 4, s.bsize, true);\n v.setUint32(buf + 60, s.bsize, true);\n v.setBigInt64(buf + 8, BigInt(s.blocks), true);\n v.setBigInt64(buf + 16, BigInt(s.bfree), true);\n v.setBigInt64(buf + 24, BigInt(s.bavail), true);\n v.setBigInt64(buf + 32, BigInt(s.files), true);\n v.setBigInt64(buf + 40, BigInt(s.ffree), true);\n v.setUint32(buf + 48, s.fsid, true);\n v.setUint32(buf + 64, s.flags, true);\n v.setUint32(buf + 56, s.namelen, true);\n}\nvar DIRENT_SIZE = 280;\nvar encoder3 = new TextEncoder();\nfunction writeDirent(mem, at, ino, next2, type, name2) {\n const v = mem.view();\n v.setBigInt64(at, BigInt(ino), true);\n v.setBigInt64(at + 8, BigInt(next2), true);\n v.setUint16(at + 16, DIRENT_SIZE, true);\n v.setUint8(at + 18, type);\n putString(mem, at + 19, name2, 256);\n}\nfunction putString(mem, at, text, max) {\n if (max <= 0) return 0;\n const bytes = encoder3.encode(text);\n let n = Math.min(bytes.length, max - 1);\n while (n > 0 && n < bytes.length && (bytes[n] & 192) === 128) n--;\n const out = mem.bytes(at, n + 1);\n out.set(bytes.subarray(0, n));\n out[n] = 0;\n return n;\n}\n\n// src/process/emscripten/files.ts\nvar O_ACCMODE = 3;\nvar O_WRONLY3 = 1;\nvar O_RDWR3 = 2;\nvar O_CREAT = 64;\nvar O_EXCL = 128;\nvar O_TRUNC = 512;\nvar O_APPEND3 = 1024;\nvar O_NONBLOCK3 = 2048;\nvar O_DIRECTORY = 65536;\nvar O_NOFOLLOW = 131072;\nvar O_CLOEXEC2 = 524288;\nvar O_PATH = 2097152;\nvar AT_SYMLINK_NOFOLLOW2 = 256;\nvar AT_REMOVEDIR = 512;\nvar AT_SYMLINK_FOLLOW = 1024;\nvar AT_EACCESS2 = 512;\nvar AT_EMPTY_PATH = 4096;\nvar UTIME_NOW = 1073741823;\nvar UTIME_OMIT = 1073741822;\nvar FD_ALIAS2 = /^\\/(?:dev\\/(stdin|stdout|stderr)|dev\\/fd\\/(\\d+)|proc\\/(self|[1-9]\\d*)\\/fd\\/(\\d+))$/;\nvar STDIO3 = { stdin: 0, stdout: 1, stderr: 2 };\nvar DT_CHR = 2;\nvar DT_DIR = 4;\nvar DT_REG = 8;\nvar DT_LNK = 10;\nvar encoder4 = new TextEncoder();\nfunction fdAlias(ctx, path) {\n const m = FD_ALIAS2.exec(path);\n if (!m) return void 0;\n if (m[1]) return STDIO3[m[1]];\n if (m[3] !== void 0 && m[3] !== \"self\" && Number(m[3]) !== ctx.pid) return void 0;\n return Number(m[2] ?? m[4]);\n}\nasync function credOf(ctx) {\n return await ctx.call({ op: \"proc-cred\" });\n}\nfunction typeOf(st) {\n if (st.isSymbolicLink) return S_IFLNK2;\n if (st.isDirectory) return S_IFDIR;\n if (st.isSocket) return S_IFSOCK;\n if (st.isFifo) return S_IFIFO2;\n if (st.isFile) return S_IFREG;\n const own = (st.mode ?? 0) & S_IFMT2;\n return own || S_IFREG;\n}\nvar RDEV = {\n \"/dev/null\": 259,\n \"/dev/zero\": 261,\n \"/dev/full\": 263,\n \"/dev/random\": 16384,\n \"/dev/urandom\": 16640,\n \"/dev/tty\": 1280,\n \"/dev/ptmx\": 1282,\n \"/dev/sealed\": 2810,\n \"/dev/clipboard\": 2811,\n \"/dev/embedder\": 2812\n};\nvar PTS2 = /^\\/dev\\/pts\\/(\\d+)$/;\nfunction rdevOf(path) {\n const n = PTS2.exec(path)?.[1];\n if (n === void 0) return RDEV[path] ?? 0;\n const minor = Number(n);\n return (minor & 1048320) << 12 | 136 << 8 | minor & 255;\n}\nasync function emStat(ctx, path, st, size) {\n const owners = ctx.host.o.fs.owners === true;\n const type = typeOf(st);\n const fallback = type === S_IFDIR || type === S_IFLNK2 ? 511 : 438;\n const perm = (st.mode ?? fallback) & 4095;\n const mode = type | (owners ? perm : perm || fallback);\n const bytes = type === S_IFDIR ? 4096 : size ?? st.size;\n const mtimeMs = st.mtimeMs ?? 0;\n let uid = owners ? st.uid ?? 0 : 0;\n let gid = owners ? st.gid ?? 0 : 0;\n if (!ctx.init.owners && !ctx.credAbi) {\n uid = 1e3;\n gid = 1e3;\n } else if (!ctx.init.owners) {\n const cred = await credOf(ctx);\n uid = cred.euid;\n gid = cred.egid;\n }\n return {\n dev: st.dev ?? 1,\n ino: st.ino ?? inodeOf(path),\n mode,\n nlink: st.nlink ?? 1,\n uid,\n gid,\n rdev: type === S_IFCHR ? rdevOf(path) : 0,\n size: bytes,\n atimeMs: st.atimeMs ?? mtimeMs,\n mtimeMs,\n ctimeMs: st.ctimeMs ?? mtimeMs,\n blocks: Math.ceil(bytes / 4096) * 8\n };\n}\nfunction devKernel(ctx) {\n return { json: async (req) => await ctx.call(req) };\n}\nvar PTMX = \"/dev/ptmx\";\nfunction ptmxStat() {\n return {\n isFile: false,\n isDirectory: false,\n size: 0,\n mode: S_IFCHR | 438,\n mtimeMs: Date.now(),\n uid: 0,\n gid: 0\n };\n}\nasync function bridgeStat(ctx, path, follow2) {\n const fs = ctx.host.o.fs;\n if (path === PTMX && ctx.sys.openPty) return ptmxStat();\n if (inDev(path)) {\n try {\n return await devSync(devKernel(ctx), devStat(path, follow2));\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n }\n }\n await ctx.host.fds.flushPath(path);\n try {\n return follow2 ? await fs.stat(path) : await fs.lstat(path);\n } catch (err) {\n const real = follow2 && missing2(err) ? await devTarget(ctx, path) : void 0;\n if (real === void 0) throw err;\n return await bridgeStat(ctx, real, true);\n }\n}\nasync function devTarget(ctx, path) {\n let real;\n try {\n real = await physicalPath(ctx.host.o.fs, path);\n } catch {\n return void 0;\n }\n return real !== path && inDev(real) ? real : void 0;\n}\nfunction linkStat2(target) {\n return {\n isFile: false,\n isDirectory: false,\n isSymbolicLink: true,\n size: encoder4.encode(target).length,\n mode: S_IFLNK2 | 511,\n mtimeMs: Date.now()\n };\n}\nasync function fdTarget2(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") return e.file.path;\n if (e.type === \"dir\") return e.path;\n if (e.type === \"device\") return `/dev/${e.device}`;\n if (await ctx.host.fds.kind(fd, e) === \"stream\") {\n const info = await ctx.call({ op: \"fd-info\", fd });\n if (info.fifo !== void 0) return info.fifo;\n }\n const target = await devSync(devKernel(ctx), devResolveTarget(`/dev/fd/${fd}`));\n return target ?? `pipe:[${fd}]`;\n}\nasync function pathStat2(ctx, path, follow2) {\n const alias = fdAlias(ctx, path);\n if (alias !== void 0) {\n if (follow2) return await fdStat2(ctx, alias);\n const target = /^\\/dev\\/std/.test(path) ? \"\" : await fdTarget2(ctx, alias);\n if (/^\\/dev\\/std/.test(path)) return await emStat(ctx, path, linkStat2(`/proc/self/fd/${alias}`));\n return await emStat(ctx, path, { ...linkStat2(target), size: 0, mode: S_IFLNK2 | 448 });\n }\n if (procFdDir(ctx, path)) {\n return await emStat(ctx, path, {\n isFile: false,\n isDirectory: true,\n size: 0,\n mode: S_IFDIR | 365,\n mtimeMs: Date.now()\n });\n }\n return await emStat(ctx, path, await bridgeStat(ctx, path, follow2));\n}\nasync function kernelFdStat(ctx, fd, kind) {\n if (kind === \"file\") {\n const st = await ctx.call({ op: \"fd-vfs-stat\", fd, full: true });\n const path = st.path ?? `/proc/self/fd/${fd}`;\n const base = st.stat ?? { isFile: true, isDirectory: false, size: st.size };\n return await emStat(ctx, path, base, st.size);\n }\n if (kind === \"tty\" || kind === \"device\") {\n return await emStat(ctx, await fdTarget2(ctx, fd), await devSync(devKernel(ctx), devFdStat(fd)));\n }\n const type = kind === \"socket\" ? S_IFSOCK : kind === \"stream\" ? S_IFIFO2 : S_IFCHR;\n const now = Date.now();\n return await emStat(ctx, `pipe:${fd}`, {\n isFile: false,\n isDirectory: false,\n ...type === S_IFSOCK ? { isSocket: true } : {},\n ...type === S_IFIFO2 ? { isFifo: true } : {},\n size: 0,\n mode: type | 384,\n mtimeMs: now\n });\n}\nasync function fdStat2(ctx, fd) {\n const { fds } = ctx.host;\n const e = await fds.get(fd);\n if (e.type === \"dir\") return await emStat(ctx, e.path, await bridgeStat(ctx, e.path, true));\n if (e.type === \"device\") {\n return await emStat(ctx, `/dev/${e.device}`, await bridgeStat(ctx, `/dev/${e.device}`, true));\n }\n if (e.type === \"file\") {\n const file = e.file;\n let st;\n const kept = async () => {\n const handle = file.buffer.handle;\n try {\n return handle === void 0 ? void 0 : await ctx.host.o.fs.keptStat?.(handle);\n } catch {\n return void 0;\n }\n };\n try {\n await file.buffer.flush();\n st = await ctx.host.o.fs.stat(file.path);\n } catch {\n st = await kept();\n }\n const bound = file.buffer.bound;\n if (st && bound?.ino !== void 0 && st.ino !== bound.ino) st = await kept() ?? bound;\n const base = st ?? { isFile: true, isDirectory: false, size: 0, nlink: 0 };\n const orphan = file.buffer.isOrphan();\n return await emStat(ctx, file.path, orphan ? { ...base, nlink: 0 } : base, await file.size());\n }\n return await kernelFdStat(ctx, fd, await fds.kind(fd, e));\n}\nasync function accessFlags(ctx, fd, e) {\n if (e.type === \"dir\") return O_DIRECTORY;\n if (e.type === \"file\") {\n const acc2 = e.file.writable ? e.file.readable ? O_RDWR3 : O_WRONLY3 : 0;\n return acc2 | (e.file.append ? O_APPEND3 : 0);\n }\n if (e.type === \"device\")\n return e.access === \"read\" ? 0 : e.access === \"write\" ? O_WRONLY3 : O_RDWR3;\n const access3 = await ctx.sys.access?.(fd);\n const acc = access3 === \"read\" ? 0 : access3 === \"write\" ? O_WRONLY3 : O_RDWR3;\n return acc | (e.append ? O_APPEND3 : 0) | (e.nonblock ? O_NONBLOCK3 : 0);\n}\nfunction rightsOf(flags) {\n const acc = flags & O_ACCMODE;\n if (acc === O_WRONLY3) return RIGHTS.ALL & ~RIGHTS.FD_READ;\n if (acc === O_RDWR3) return RIGHTS.ALL;\n return RIGHTS.ALL & ~RIGHTS.FD_WRITE;\n}\nfunction oflagsOf(flags) {\n return (flags & O_CREAT ? OFLAGS.CREAT : 0) | (flags & O_DIRECTORY ? OFLAGS.DIRECTORY : 0) | (flags & O_EXCL ? OFLAGS.EXCL : 0) | (flags & O_TRUNC ? OFLAGS.TRUNC : 0);\n}\nfunction fdflagsOf(flags) {\n return (flags & O_APPEND3 ? FDFLAGS.APPEND : 0) | (flags & O_NONBLOCK3 ? FDFLAGS.NONBLOCK : 0);\n}\nasync function refusedCreation(ctx, path) {\n const cred = ctx.host.o.fs.owners ? await credOf(ctx) : void 0;\n const refused3 = devCreation(path, cred);\n if (!refused3) return;\n try {\n await bridgeStat(ctx, path, false);\n } catch {\n throw new EmError(wasiErrno(refused3));\n }\n}\nfunction etcDefaults(ctx) {\n const env = { ...ctx.init.env, HOSTNAME: initHostname(ctx.init) };\n const { passwd, group } = accounts(env);\n return {\n \"/etc/passwd\": passwd,\n \"/etc/group\": group,\n \"/etc/hosts\": hostsFile(hostnameOf(env)),\n \"/etc/hostname\": `${hostnameOf(env)}\n`\n };\n}\nasync function seed(ctx, path, text) {\n const fs = ctx.host.o.fs;\n if (await fs.exists(path)) return;\n try {\n await fs.create?.(path, fs.owners ? 420 : void 0, false);\n await fs.writeFile(path, encoder4.encode(text));\n if ((((await fs.stat(path)).mode ?? 420) & 4095) !== 420) await fs.chmod(path, 420);\n } catch {\n }\n}\nfunction missing2(err) {\n return err.code === \"ENOENT\";\n}\nasync function openPath(ctx, path, flags, mode) {\n const writes = (flags & (O_ACCMODE | O_CREAT)) !== 0;\n const text = path.startsWith(\"/etc/\") ? etcDefaults(ctx)[path] : void 0;\n if (text !== void 0 && writes) await seed(ctx, path, text);\n if (text === void 0 && path !== \"/etc/mtab\" || writes) return await openAt(ctx, path, flags, mode);\n try {\n return await openAt(ctx, path, flags, mode);\n } catch (err) {\n if (!missing2(err)) throw err;\n if (text === void 0) return await openAt(ctx, \"/proc/mounts\", flags, mode);\n const fd = await ctx.sys.openVfs(path, 0, 0, { contents: encoder4.encode(text), orphan: true });\n await ctx.host.fds.adopt(fd, \"file\", false);\n if (flags & O_CLOEXEC2) await ctx.host.fds.setCloexec(fd, true);\n return fd;\n }\n}\nvar O_NOCTTY = 256;\nasync function openPty(ctx, path, flags) {\n const pts = PTS2.exec(path)?.[1];\n if (path !== PTMX && pts === void 0) return void 0;\n const { openPty: master, openPts } = ctx.sys;\n if (!master || !openPts) return void 0;\n const fd = pts === void 0 ? await master.call(ctx.sys) : await openPts.call(ctx.sys, Number(pts), (flags & O_NOCTTY) !== 0);\n await ctx.host.fds.adopt(fd, \"tty\", (flags & O_NONBLOCK3) !== 0);\n if (flags & O_CLOEXEC2) await ctx.host.fds.setCloexec(fd, true);\n return fd;\n}\nasync function openAt(ctx, path, flags, mode) {\n const pty = await openPty(ctx, path, flags);\n if (pty !== void 0) return pty;\n try {\n return await openFile(ctx, path, flags, mode);\n } catch (err) {\n const real = missing2(err) && !(flags & O_NOFOLLOW) ? await devTarget(ctx, path) : void 0;\n if (real === void 0) throw err;\n return await openAt(ctx, real, flags, mode);\n }\n}\nasync function openFile(ctx, path, flags, mode) {\n const { fds } = ctx.host;\n if (flags & O_CREAT) await refusedCreation(ctx, path);\n const alias = fdAlias(ctx, path);\n const target = alias !== void 0 && alias > 2 ? `/dev/fd/${alias}` : path;\n if (alias !== void 0 && alias > 2) await fds.get(alias);\n if (procFdDir(ctx, path) || path === \"/dev/fd\") {\n if ((flags & O_ACCMODE) !== 0 || flags & (O_CREAT | O_TRUNC)) throw new EmError(EM.ISDIR);\n const fd2 = await fds.preopenAt(path, \"\");\n if (flags & O_CLOEXEC2) await fds.setCloexec(fd2, true);\n return fd2;\n }\n const umask = await ctx.host.umask();\n const created = flags & O_CREAT ? mode & 4095 & ~umask : void 0;\n const nofollow = (flags & O_NOFOLLOW) !== 0;\n if (deviceOf(target)) await ctx.host.interrupted?.();\n if (target === path && !deviceOf(path) && !inDev(path)) await refusedLookup(ctx, path);\n const opened = await readOnlyCreate(ctx, target, flags, created);\n const fd = await fds.open(\n target,\n oflagsOf(opened),\n rightsOf(flags),\n fdflagsOf(flags),\n created,\n nofollow\n );\n await dirAccess(ctx, fd, flags);\n if (flags & O_CLOEXEC2) await fds.setCloexec(fd, true);\n return fd;\n}\nasync function refusedLookup(ctx, path) {\n try {\n await ctx.host.o.fs.lstat(path);\n } catch (err) {\n const code2 = err.code;\n if (code2 === \"EACCES\" || code2 === \"EPERM\") throw err;\n }\n}\nasync function readOnlyCreate(ctx, path, flags, mode) {\n if (!(flags & O_CREAT) || (flags & O_ACCMODE) !== 0 || flags & O_DIRECTORY) return flags;\n if (deviceOf(path) || fdAlias(ctx, path) !== void 0 || inDev(path)) return flags;\n const fs = ctx.host.o.fs;\n let exists = true;\n try {\n await fs.lstat(path);\n } catch (err) {\n if (!missing2(err)) throw err;\n exists = false;\n }\n if (exists && flags & O_EXCL) throw new EmError(EM.EXIST);\n if (!exists) {\n try {\n if (fs.create) await fs.create(path, fs.owners ? mode : void 0, false);\n else await fs.writeFile(path, new Uint8Array(0));\n } catch (err) {\n if (err.code !== \"EEXIST\" || flags & O_EXCL) throw err;\n }\n }\n return flags & ~(O_CREAT | O_EXCL);\n}\nasync function dirAccess(ctx, fd, flags) {\n const fs = ctx.host.o.fs;\n if (!fs.owners || !fs.access || flags & O_PATH) return;\n const e = await ctx.host.fds.find(fd);\n if (e?.type !== \"dir\") return;\n const acc = flags & O_ACCMODE;\n const want = (acc === O_WRONLY3 ? 0 : 4) | (acc !== 0 || flags & O_TRUNC ? 2 : 0);\n try {\n await fs.access(e.path, want, \"open\");\n } catch (err) {\n await ctx.host.fds.close(fd);\n throw err;\n }\n}\nfunction times(ctx, ptr) {\n const now = Date.now();\n if (!ptr) return [now, now];\n const v = ctx.mem.view();\n const one = (at) => {\n const nsec = v.getInt32(at + 8, true);\n if (nsec === UTIME_NOW) return now;\n if (nsec === UTIME_OMIT) return null;\n const sec = v.getUint32(at, true) + v.getInt32(at + 4, true) * 4294967296;\n return sec * 1e3 + nsec / 1e6;\n };\n return [one(ptr), one(ptr + 16)];\n}\nfunction touching(ctx, ptr) {\n if (!ptr) return true;\n const v = ctx.mem.view();\n const a = v.getInt32(ptr + 8, true);\n const m = v.getInt32(ptr + 24, true);\n return (a === UTIME_NOW || a === UTIME_OMIT) && (m === UTIME_NOW || m === UTIME_OMIT);\n}\nasync function setTimes(ctx, path, atime, mtime, follow2, now) {\n const fs = ctx.host.o.fs;\n await ctx.host.fds.flushPath(path);\n let a = atime;\n let m = mtime;\n if (a === null || m === null) {\n const st = follow2 ? await fs.stat(path) : await fs.lstat(path);\n a ??= st.atimeMs ?? st.mtimeMs ?? Date.now();\n m ??= st.mtimeMs ?? Date.now();\n }\n await (follow2 ? fs.utimes : fs.lutimes).call(fs, path, a, m, now);\n}\nvar PROC_FD = /^\\/proc\\/(self|[1-9]\\d*)\\/fd$/;\nfunction procFdDir(ctx, path) {\n const m = PROC_FD.exec(path);\n return m !== null && (m[1] === \"self\" || Number(m[1]) === ctx.pid);\n}\nasync function fdNames(ctx) {\n const listed3 = await ctx.call({ op: \"fd-list\" });\n const fds = [];\n for (const entry of listed3) fds.push(entry.fd);\n fds.sort((a, b) => a - b);\n const names2 = [];\n for (const fd of fds) names2.push(String(fd));\n return names2;\n}\nvar PROC_PID = /^\\/proc\\/(self|[1-9]\\d*)$/;\nfunction procListing(ctx, path, listed3) {\n const stats = /* @__PURE__ */ new Map();\n for (const [name2, st] of listed3) if (name2 !== \"task\") stats.set(name2, st);\n stats.set(\"fd\", { isFile: false, isDirectory: true, size: 0, mode: S_IFDIR | 365 });\n const sorted = [...stats.keys()].sort();\n return { names: [\".\", \"..\", ...sorted], stats, path };\n}\nasync function listing(ctx, path) {\n if (procFdDir(ctx, path) || path === \"/dev/fd\") {\n const names3 = [\".\", \"..\"];\n const stats2 = /* @__PURE__ */ new Map();\n for (const name2 of await fdNames(ctx)) {\n names3.push(name2);\n stats2.set(name2, { ...linkStat2(\"\"), mode: S_IFLNK2 | 448 });\n }\n return { names: names3, stats: stats2, path };\n }\n if (inDev(path) && path !== \"/dev/shm\" && !path.startsWith(\"/dev/shm/\")) {\n const names3 = [\".\", \"..\"];\n const stats2 = /* @__PURE__ */ new Map();\n const listed4 = await devSync(devKernel(ctx), devReaddir(path));\n if (path === \"/dev\" && !listed4.includes(\"fd\")) listed4.push(\"fd\");\n if (path === \"/dev\" && ctx.sys.openPty && !listed4.includes(\"ptmx\")) listed4.push(\"ptmx\");\n listed4.sort();\n for (const name2 of listed4) {\n names3.push(name2);\n const child = childPath(path, name2);\n try {\n stats2.set(name2, await bridgeStat(ctx, child, false));\n } catch {\n stats2.set(name2, null);\n }\n }\n return { names: names3, stats: stats2, path };\n }\n const listed3 = await ctx.host.o.fs.readdirStat(path);\n if (PROC_PID.test(path)) return procListing(ctx, path, listed3);\n const names2 = [\".\", \"..\"];\n const stats = /* @__PURE__ */ new Map();\n for (const [name2, st] of listed3) {\n names2.push(name2);\n stats.set(name2, st);\n }\n return { names: names2, stats, path };\n}\nfunction direntType(st) {\n if (!st) return DT_REG;\n if (st.isDirectory) return DT_DIR;\n if (st.isSymbolicLink) return DT_LNK;\n if (!st.isFile && ((st.mode ?? 0) & S_IFMT2) === S_IFCHR) return DT_CHR;\n return DT_REG;\n}\nfunction childPath(dir, name2) {\n return dir === \"/\" ? `/${name2}` : `${dir}/${name2}`;\n}\nasync function dirOf(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type !== \"dir\") throw new EmError(EM.NOTDIR);\n return e;\n}\nasync function getdents(ctx, state, fd, dirp, count) {\n const dir = await dirOf(ctx, fd);\n let held = state.listings.get(dir);\n if (!held) {\n held = { listing: await listing(ctx, dir.path), pos: 0 };\n state.listings.set(dir, held);\n }\n const { names: names2, stats, path } = held.listing;\n const start2 = Math.floor(held.pos / DIRENT_SIZE);\n const end = Math.min(names2.length, start2 + Math.floor(count / DIRENT_SIZE));\n let pos = 0;\n let idx = start2;\n for (; idx < end; idx++) {\n const name2 = names2[idx];\n let ino;\n let type;\n if (name2 === \".\" || name2 === \"..\") {\n const at = name2 === \".\" ? path : parentOf3(path);\n ino = inodeOf(at);\n type = DT_DIR;\n try {\n ino = (await ctx.host.o.fs.stat(at)).ino ?? ino;\n } catch {\n }\n } else {\n const full = childPath(path, name2);\n let st = stats.get(name2) ?? null;\n if (st === null) {\n try {\n st = await ctx.host.o.fs.lstat(full);\n } catch {\n st = null;\n }\n }\n ino = st?.ino ?? inodeOf(full);\n type = direntType(st);\n }\n writeDirent(ctx.mem, dirp + pos, ino, (idx + 1) * DIRENT_SIZE, type, name2);\n pos += DIRENT_SIZE;\n }\n held.pos = idx * DIRENT_SIZE;\n return pos;\n}\nfunction seekDir(state, entry, offset, whence) {\n const held = state.listings.get(entry);\n const base = whence === 1 ? held?.pos ?? 0 : 0;\n const pos = base + offset;\n if (pos < 0) throw new EmError(EM.INVAL);\n if (pos === 0 && whence === 0) {\n state.listings.delete(entry);\n return 0;\n }\n if (held) held.pos = pos;\n return pos;\n}\nvar UTS_FIELD = 65;\nfunction unameHost(ctx) {\n return initHostname(ctx.init);\n}\nasync function chown(ctx, path, uid, gid, follow2) {\n const fs = ctx.host.o.fs;\n if (!fs.chown) throw new EmError(EM.NOSYS);\n const id = (v) => v >>> 0 === 4294967295 ? void 0 : v >>> 0;\n await fs.chown.call(fs, path, id(uid), id(gid), follow2);\n}\nasync function chmodPath(ctx, path, mode, follow2) {\n const fs = ctx.host.o.fs;\n const alias = fdAlias(ctx, path);\n if (alias !== void 0 && follow2) {\n await chmodFd(ctx, alias, mode);\n return;\n }\n if (!follow2 && (await fs.lstat(path)).isSymbolicLink) throw new EmError(EM.NOTSUP);\n await fs.chmod(follow2 ? await physicalPath(fs, path) : path, mode & 4095);\n}\nasync function chmodFd(ctx, fd, mode) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") {\n await ctx.sys.fdChmod?.(fd, mode & 4095);\n return;\n }\n if (e.type === \"dir\") return void await ctx.host.o.fs.chmod(e.path, mode & 4095);\n if (e.type === \"file\") return void await ctx.host.o.fs.chmod(e.file.path, mode & 4095);\n throw new EmError(EM.PERM);\n}\nasync function access2(ctx, path, amode, flags) {\n if (amode & ~7) throw new EmError(EM.INVAL);\n const fs = ctx.host.o.fs;\n const follow2 = (flags & AT_SYMLINK_NOFOLLOW2) === 0;\n const alias = fdAlias(ctx, path);\n if (alias !== void 0) {\n await ctx.host.fds.get(alias);\n return;\n }\n const st = await bridgeStat(ctx, path, follow2);\n if (amode & 2 && st.readonly) throw new EmError(69);\n if (!fs.owners || !fs.access || inDev(path)) return;\n const kind = flags & AT_EACCESS2 ? \"eaccess\" : \"access\";\n await fs.access(path, amode & 7, kind, !follow2);\n}\nasync function devRemove(ctx, path) {\n const cred = ctx.host.o.fs.owners ? await credOf(ctx) : void 0;\n const refused3 = devRemoval(path, cred);\n if (refused3) throw new EmError(wasiErrno(refused3));\n}\nasync function unlinkPath(ctx, path) {\n await devRemove(ctx, path);\n const fs = ctx.host.o.fs;\n const { fds } = ctx.host;\n const st = await fs.lstat(path);\n if (st.isDirectory) throw new EmError(EM.ISDIR);\n const linked = (st.nlink ?? 1) > 1 ? st : void 0;\n await fds.unlinking(path, linked);\n await fs.unlink(path);\n await fds.unlinked(path, linked);\n}\nfunction parentOf3(path) {\n const slash = path.lastIndexOf(\"/\");\n return slash <= 0 ? \"/\" : path.slice(0, slash);\n}\nasync function mountOf(ctx, state, dir) {\n if (dir === \"/dev/shm\" || dir.startsWith(\"/dev/shm/\")) return \"/dev/shm\";\n if (dir === \"/\") return \"/\";\n const top = `/${dir.split(\"/\")[1]}`;\n return (await mountPoints(ctx, state)).has(top) ? top : \"/\";\n}\nvar OWN_MOUNTS = /* @__PURE__ */ new Set([\"dev\", \"proc\", \"sys\"]);\nasync function mountPoints(ctx, state) {\n if (state.mounts) return state.mounts;\n const fs = ctx.host.o.fs;\n const out = /* @__PURE__ */ new Set([\"/dev\", \"/proc\", \"/sys\"]);\n let names2 = [];\n try {\n names2 = await fs.readdir(\"/\");\n } catch {\n }\n for (const name2 of [...names2, \"usr\", \"bin\"]) {\n if (!name2 || name2.includes(\"/\") || OWN_MOUNTS.has(name2)) continue;\n try {\n if ((await fs.stat(`/${name2}`)).isDirectory) out.add(`/${name2}`);\n } catch {\n }\n }\n try {\n if ((await fs.stat(\"/dev/shm\")).isDirectory) out.add(\"/dev/shm\");\n } catch {\n }\n state.mounts = out;\n return out;\n}\nasync function removeDir(ctx, state, path) {\n await devRemove(ctx, path);\n if (path === \"/\" || (await mountPoints(ctx, state)).has(path)) {\n await ctx.host.o.fs.lstat(path);\n throw new EmError(EM.BUSY);\n }\n await ctx.host.o.fs.rmdir(path);\n}\nasync function renamePath(ctx, state, from, to) {\n const fs = ctx.host.o.fs;\n const { fds } = ctx.host;\n const points = await mountPoints(ctx, state);\n if (points.has(from)) {\n await fs.lstat(from);\n throw new EmError(EM.XDEV);\n }\n if (points.has(to)) {\n await fs.lstat(from);\n throw new EmError(EM.BUSY);\n }\n if (await mountOf(ctx, state, parentOf3(from)) !== await mountOf(ctx, state, parentOf3(to))) {\n await fs.lstat(from);\n throw new EmError(EM.XDEV);\n }\n await fds.flushPath(from);\n let replaced;\n if (fds.holdsUnder(to)) {\n try {\n const st = await fs.lstat(to);\n replaced = (st.nlink ?? 1) > 1 ? st : void 0;\n } catch {\n }\n }\n if (replaced === void 0) await fds.replacing(to);\n const seq = await fs.rename(from, to);\n await fds.renamed(from, to, replaced);\n fds.ownRename(typeof seq === \"number\" ? seq : void 0);\n}\nasync function linkPath(ctx, from, to, follow2) {\n const fs = ctx.host.o.fs;\n const { fds } = ctx.host;\n const source = follow2 ? await physicalPath(fs, from) : from;\n await fds.flushPath(from);\n if (source !== from) await fds.flushPath(source);\n try {\n await fs.link(from, to, follow2);\n } catch (err) {\n if (err.code !== \"EPERM\" || await linkable(ctx, source)) throw err;\n throw new EmError(EM.MLINK);\n }\n await fds.linked(from, to);\n if (source !== from) await fds.linked(source, to);\n}\nasync function linkable(ctx, path) {\n try {\n return (await ctx.host.o.fs.lstat(path)).linkable === true;\n } catch {\n return false;\n }\n}\nasync function truncateFd(ctx, fd, size) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") {\n if (!e.file.writable) throw new EmError(EM.INVAL);\n await e.file.buffer.truncate(size);\n return;\n }\n if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") {\n await ctx.call({ op: \"fd-resize\", fd, size });\n ctx.host.o.fs.touched?.(e.path, e.ino);\n return;\n }\n throw new EmError(EM.INVAL);\n}\nasync function syncFd(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") await ctx.host.fds.synced(e.file);\n else if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") await ctx.sys.flush(fd);\n}\nasync function readlink(ctx, path) {\n const alias = fdAlias(ctx, path);\n if (alias !== void 0) {\n if (/^\\/dev\\/(stdin|stdout|stderr)$/.test(path)) return `/proc/self/fd/${alias}`;\n return await fdTarget2(ctx, alias);\n }\n return await ctx.host.o.fs.readlink(path);\n}\nfunction fileImports(ctx, state) {\n const { mem } = ctx;\n const str = (ptr) => mem.cString(ptr);\n const at = async (dirfd, ptr, empty = false) => await ctx.cwd.resolve(dirfd, str(ptr), empty);\n const fds = () => ctx.host.fds;\n return {\n __syscall_chdir: negated(async (p) => await ctx.cwd.chdir(await at(AT_FDCWD2, p))),\n __syscall_fchdir: negated(async (fd) => await ctx.cwd.chdir((await dirOf(ctx, fd)).path)),\n __syscall_getcwd: negated(async (buf, size) => {\n if (size === 0) return -EM.INVAL;\n if (await ctx.cwd.gone()) return -EM.NOENT;\n const cwd = ctx.cwd.path;\n const n = encoder4.encode(cwd).length + 1;\n if (size < n) return -EM.RANGE;\n putString(mem, buf, cwd, size);\n return n;\n }),\n __syscall_chmod: negated(\n async (p, mode) => await chmodPath(ctx, await at(AT_FDCWD2, p), mode, true)\n ),\n __syscall_fchmod: negated(async (fd, mode) => await chmodFd(ctx, fd, mode)),\n __syscall_fchmodat2: negated(\n async (dirfd, p, mode, flags) => await chmodPath(ctx, await at(dirfd, p), mode, (flags & AT_SYMLINK_NOFOLLOW2) === 0)\n ),\n __syscall_fchown32: negated(async (fd, uid, gid) => {\n const e = await fds().get(fd);\n if (e.type === \"kernel\" && await fds().kind(fd, e) === \"file\") {\n const id = (v) => v >>> 0 === 4294967295 ? void 0 : v >>> 0;\n await ctx.sys.fdChown?.(fd, id(uid), id(gid));\n return;\n }\n await chown(ctx, await fdTarget2(ctx, fd), uid, gid, true);\n }),\n __syscall_fchownat: negated(\n async (dirfd, p, uid, gid, flags) => await chown(\n ctx,\n await at(dirfd, p, (flags & AT_EMPTY_PATH) !== 0),\n uid,\n gid,\n !(flags & AT_SYMLINK_NOFOLLOW2)\n )\n ),\n __syscall_faccessat: negated(\n async (dirfd, p, amode, flags) => await access2(ctx, await at(dirfd, p), amode, flags)\n ),\n __syscall_fadvise64: () => 0,\n __syscall_fdatasync: negated(async (fd) => await syncFd(ctx, fd)),\n __syscall_fstat64: negated(async (fd, buf) => writeStat(mem, buf, await fdStat2(ctx, fd))),\n __syscall_stat64: negated(\n async (p, buf) => writeStat(mem, buf, await pathStat2(ctx, await at(AT_FDCWD2, p), true))\n ),\n __syscall_lstat64: negated(\n async (p, buf) => writeStat(mem, buf, await pathStat2(ctx, await at(AT_FDCWD2, p), false))\n ),\n __syscall_newfstatat: negated(async (dirfd, p, buf, flags) => {\n const raw = str(p);\n if (raw === \"\" && flags & AT_EMPTY_PATH && dirfd !== AT_FDCWD2) {\n return writeStat(mem, buf, await fdStat2(ctx, dirfd));\n }\n const path = await ctx.cwd.resolve(dirfd, raw, (flags & AT_EMPTY_PATH) !== 0);\n writeStat(mem, buf, await pathStat2(ctx, path, (flags & AT_SYMLINK_NOFOLLOW2) === 0));\n }),\n __syscall_statfs64: negated(async (p, _size, buf) => {\n const path = await at(AT_FDCWD2, p);\n await bridgeStat(ctx, path, true);\n const usage = await ctx.statfs(path);\n const blocks = usage ? Math.ceil(usage.quota / 4096) : 1e6;\n const free = usage ? Math.max(0, Math.floor((usage.quota - usage.usage) / 4096)) : 5e5;\n writeStatfs(mem, buf, {\n bsize: 4096,\n blocks,\n bfree: free,\n bavail: free,\n files: 1e6,\n ffree: 5e5,\n fsid: 42,\n flags: 2,\n namelen: 255\n });\n }),\n __syscall_ftruncate64: negated(async (fd, length) => {\n const size = Number(length);\n if (!Number.isSafeInteger(size)) return -EM.OVERFLOW;\n if (size < 0) return -EM.INVAL;\n await truncateFd(ctx, fd, size);\n }),\n ...moreFileImports(ctx, state)\n };\n}\nfunction moreFileImports(ctx, state) {\n const { mem } = ctx;\n const str = (ptr) => mem.cString(ptr);\n const at = async (dirfd, ptr, empty = false) => await ctx.cwd.resolve(dirfd, str(ptr), empty);\n return {\n __syscall_getdents64: negated(\n async (fd, dirp, count) => await getdents(ctx, state, fd, dirp, count)\n ),\n __syscall_mkdirat: negated(async (dirfd, p, mode) => {\n const path = await at(dirfd, p);\n await refusedCreation(ctx, path);\n const fs = ctx.host.o.fs;\n if (await fs.exists(path)) throw new EmError(EM.EXIST);\n const perm = mode & 4095 & ~await ctx.host.umask();\n await fs.mkdir(path, fs.owners ? perm : void 0);\n if (!fs.owners && perm !== 493) await fs.chmod(path, perm);\n }),\n __syscall_mknodat: negated(async (dirfd, p, mode) => {\n const path = await at(dirfd, p);\n const type = mode & S_IFMT2;\n if (type !== S_IFREG && type !== S_IFCHR && type !== 24576 && type !== S_IFIFO2 && type !== S_IFSOCK) {\n return -EM.INVAL;\n }\n await refusedCreation(ctx, path);\n const fs = ctx.host.o.fs;\n const perm = mode & 4095 & ~await ctx.host.umask();\n if (type === S_IFIFO2 && fs.mkfifo) return void await fs.mkfifo(path, perm);\n if (type === S_IFREG) {\n if (await fs.exists(path)) throw new EmError(EM.EXIST);\n if (fs.create) await fs.create(path, fs.owners ? perm : void 0);\n else await fs.writeFile(path, new Uint8Array(0));\n return;\n }\n throw new EmError(EM.PERM);\n }),\n __syscall_openat: negated(async (dirfd, p, flags, varargs) => {\n const mode = varargs ? mem.view().getInt32(varargs, true) : 0;\n return await openPath(ctx, await at(dirfd, p), flags, mode);\n }),\n __syscall_readlinkat: negated(async (dirfd, p, buf, bufsize) => {\n const path = await at(dirfd, p);\n if (bufsize <= 0) return -EM.INVAL;\n const target = encoder4.encode(await readlink(ctx, path));\n const n = Math.min(bufsize, target.length);\n mem.bytes(buf, n).set(target.subarray(0, n));\n return n;\n }),\n __syscall_renameat: negated(\n async (od, op, nd, np) => await renamePath(ctx, state, await at(od, op), await at(nd, np))\n ),\n __syscall_rmdir: negated(async (p) => await removeDir(ctx, state, await at(AT_FDCWD2, p))),\n __syscall_symlinkat: negated(async (target, dirfd, p) => {\n const path = await at(dirfd, p);\n await refusedCreation(ctx, path);\n await ctx.host.o.fs.symlink(str(target), path);\n }),\n __syscall_linkat: negated(\n async (od, op, nd, np, flags) => await linkPath(ctx, await at(od, op), await at(nd, np), (flags & AT_SYMLINK_FOLLOW) !== 0)\n ),\n __syscall_unlinkat: negated(async (dirfd, p, flags) => {\n const path = await at(dirfd, p);\n if (flags === 0) return void await unlinkPath(ctx, path);\n if (flags === AT_REMOVEDIR) return void await removeDir(ctx, state, path);\n return -EM.INVAL;\n }),\n __syscall_utimensat: negated(async (dirfd, p, ptr, flags) => {\n const path = await at(dirfd, p, true);\n const [atime, mtime] = times(ctx, ptr);\n if ((mtime ?? atime) === null) return;\n await setTimes(ctx, path, atime, mtime, (flags & AT_SYMLINK_NOFOLLOW2) === 0, touching(ctx, ptr));\n }),\n __syscall_umask: async (mask) => await ctx.host.umask(mask & 511),\n __syscall_uname: negated((buf) => {\n if (!buf) return -EM.FAULT;\n const fields = [\n \"Linux\",\n unameHost(ctx),\n OS_RELEASE,\n \"#1 SMP PREEMPT_DYNAMIC\",\n \"wasm32\",\n \"(none)\"\n ];\n mem.bytes(buf, UTS_FIELD * fields.length).fill(0);\n for (let i = 0; i < fields.length; i++) {\n putString(mem, buf + i * UTS_FIELD, fields[i], UTS_FIELD);\n }\n })\n };\n}\nasync function fdFlags(ctx, fd) {\n return await accessFlags(ctx, fd, await ctx.host.fds.get(fd));\n}\n\n// src/process/emscripten/net.ts\nvar KILLED_BY_SIGPIPE3 = 128 + SIG.PIPE;\nasync function guard2(ctx, op) {\n for (; ; ) {\n try {\n return await op();\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n if (errno === 27 && ctx.gate.restartable()) continue;\n return -errno;\n }\n }\n}\nasync function socketFd(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type !== \"kernel\" || await ctx.host.fds.kind(fd, e) !== \"socket\") throw new EmError(EM.NOTSOCK);\n return e;\n}\nfunction resolved(ctx, addr) {\n if (addr.family !== \"unix\" || !addr.path || addr.path.startsWith(\"\\0\")) return addr;\n const path = addr.path.startsWith(\"/\") ? addr.path : `${ctx.cwd.path}/${addr.path}`;\n return { family: \"unix\", path: normalizePath(path) };\n}\nasync function install(ctx, fd, nonblock, cloexec) {\n await ctx.host.fds.adopt(fd, \"socket\", nonblock);\n if (nonblock) await ctx.host.fds.setFlags(fd, true, false);\n if (cloexec) await ctx.host.fds.setCloexec(fd, true);\n return fd;\n}\nfunction writeAddr2(ctx, out, a) {\n if (!a) return;\n const v = ctx.mem.view();\n if (a.family === \"unix\") {\n v.setInt32(out, 1, true);\n const bytes = new TextEncoder().encode(a.path).subarray(0, 107);\n ctx.mem.bytes(out + 12, bytes.length + 1).set(bytes);\n ctx.mem.bytes(out + 12 + bytes.length, 1)[0] = 0;\n return;\n }\n const q = a.host.split(\".\");\n const ip = (Number(q[0]) << 24 | Number(q[1]) << 16 | Number(q[2]) << 8 | Number(q[3])) >>> 0;\n v.setInt32(out, 2, true);\n v.setUint32(out + 4, ip, true);\n v.setInt32(out + 8, a.port, true);\n}\nfunction netImports(ctx) {\n const { mem } = ctx;\n const json = async (req) => await ctx.call(req);\n return {\n slicc_net_ready: () => 1,\n slicc_socket_js: async (unix, nonblock, cloexec) => await guard2(ctx, async () => {\n const fd = await json({ op: \"sock-open\", domain: unix ? \"unix\" : \"inet\" });\n return await install(ctx, fd, !!nonblock, !!cloexec);\n }),\n slicc_bind_js: async (fd, family, ip, port, path, connect) => await guard2(ctx, async () => {\n const host = [ip >>> 24, ip >>> 16 & 255, ip >>> 8 & 255, ip & 255].join(\".\");\n const given = family === 1 ? { family: \"unix\", path: mem.cString(path) } : { family: \"inet\", host, port };\n const e = await socketFd(ctx, fd);\n const addr = resolved(ctx, given);\n if (connect) await json({ op: \"sock-connect\", fd, addr, nonblock: e.nonblock });\n else await json({ op: \"sock-bind\", fd, addr });\n return 0;\n }),\n slicc_socketpair_js: async (unix, nonblock, cloexec, out) => await guard2(ctx, async () => {\n const pair = await json({ op: \"sock-pair\", domain: unix ? \"unix\" : \"inet\" });\n await install(ctx, pair[0], !!nonblock, !!cloexec);\n await install(ctx, pair[1], !!nonblock, !!cloexec);\n mem.view().setInt32(out, pair[0], true);\n mem.view().setInt32(out + 4, pair[1], true);\n return 0;\n }),\n slicc_listen_js: async (fd, backlog) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n await json({ op: \"sock-listen\", fd, backlog });\n return 0;\n }),\n slicc_addr_call_js: async (op, fd, arg, out) => await guard2(ctx, async () => {\n const e = await socketFd(ctx, fd);\n if (op === 0) {\n const got = await json({ op: \"sock-accept\", fd, nonblock: e.nonblock });\n const at = await install(ctx, got.fd, (arg & 1) !== 0, (arg & 2) !== 0);\n writeAddr2(ctx, out, got.peer);\n return at;\n }\n writeAddr2(ctx, out, await json({ op: \"sock-name\", fd, peer: op === 2 }));\n return 0;\n }),\n slicc_shutdown_js: async (fd, how) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n await json({ op: \"sock-shutdown\", fd, how });\n return 0;\n }),\n slicc_getopt_js: async (fd, level, name2, value2) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n const got = await json({ op: \"sock-getopt\", fd, level, name: name2 });\n mem.view().setInt32(value2, got, true);\n return 0;\n }),\n slicc_setopt_js: async (fd, level, name2, value2) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n await json({ op: \"sock-setopt\", fd, level, name: name2, value: value2 });\n return 0;\n }),\n slicc_send_js: async (fd, buf, len, dontwait, nosignal) => await guard2(ctx, async () => {\n const e = await socketFd(ctx, fd);\n const bytes = mem.bytes(buf, len).slice();\n try {\n return await ctx.sys.write(fd, bytes, { nonblock: !!dontwait || e.nonblock });\n } catch (err) {\n const broken = err.code === \"EPIPE\";\n if (broken && !nosignal && !await sigpipeSpared(ctx)) throw new WasiExit(KILLED_BY_SIGPIPE3);\n throw err;\n }\n }),\n slicc_recv_js: async (fd, buf, len, dontwait, peek) => await guard2(ctx, async () => {\n const e = await socketFd(ctx, fd);\n const got = await ctx.sys.read(fd, len, { nonblock: !!dontwait || e.nonblock, peek: !!peek });\n mem.bytes(buf, got.length).set(got);\n return got.length;\n }),\n slicc_resolve_js: async (name2, out, max) => {\n let r;\n try {\n r = await json({ op: \"sock-resolve\", name: mem.cString(name2), family: 4 });\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n if (!Array.isArray(r)) return -EM.NOSYS;\n let n = 0;\n for (const a of r) {\n const parts = String(a).split(\".\");\n if (parts.length !== 4 || n >= max) continue;\n let ok = true;\n let ip = 0;\n for (let i = 0; i < 4; i++) {\n const x = Number(parts[i]);\n if (String(x) !== parts[i] || x > 255) ok = false;\n ip = ip << 8 | x & 255;\n }\n if (!ok) continue;\n mem.view().setUint32(out + 4 * n++, ip >>> 0, true);\n }\n return n;\n }\n };\n}\nasync function sigpipeSpared(ctx) {\n const spare = ctx.exports().slicc_sigpipe;\n if (typeof spare === \"function\" && await ctx.enter(\"slicc_sigpipe\", spare, []) === 1) {\n return true;\n }\n try {\n const r = await ctx.call({ op: \"proc-kill-self\", sig: SIG.PIPE, probe: true });\n return r !== \"terminate\";\n } catch {\n return false;\n }\n}\n\n// src/process/emscripten/wasi.ts\nvar EINTR = 27;\nvar KILLED_BY_SIGPIPE4 = 141;\nvar encoder5 = new TextEncoder();\nasync function holdStopped(ctx) {\n const header = new Int32Array(ctx.init.sab, 0, SAB_HEADER_I32);\n while (Atomics.load(header, SAB_I_STOP) === 1) await atomicsWait(header, SAB_I_STOP, 1);\n}\nasync function sleepFor(ms) {\n await atomicsWait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\nasync function sleepIn(ctx, ms) {\n if (ctx.init.sab instanceof SharedArrayBuffer || !(ms > 0)) {\n await sleepFor(ms);\n return;\n }\n try {\n await ctx.call({ op: \"fd-select\", read: [], write: [], timeoutMs: ms });\n } catch (e) {\n if (errnoOf(e) === void 0) throw e;\n }\n}\nasync function afterStopped(ctx) {\n const header = new Int32Array(ctx.init.sab, 0, SAB_HEADER_I32);\n await holdStopped(ctx);\n const due = Atomics.load(header, SAB_I_SIGNALS) | Atomics.load(header, SAB_I_TIMERS) | Atomics.load(header, SAB_I_KILLED);\n if (due !== 0) await ctx.gate.interrupt();\n}\nfunction envStrings(ctx) {\n const out = [];\n for (const [key, value2] of Object.entries(ctx.init.env)) {\n if (value2 !== void 0) out.push(`${key}=${value2}`);\n }\n return out;\n}\nvar NODE_CLOCK = Boolean(\n globalThis.process?.versions?.node\n);\nasync function restarting(ctx, fn, args) {\n for (; ; ) {\n const r = await fn(...args) ?? 0;\n if (r !== EINTR || !ctx.gate.restartable()) return r;\n }\n}\nvar STRERROR = {\n EACCES: \"Permission denied\",\n EIO: \"I/O error\",\n ENOTSUP: \"Not supported\",\n EOPNOTSUPP: \"Not supported\",\n EFBIG: \"File too large\",\n EILSEQ: \"Illegal byte sequence\",\n EINTR: \"Interrupted system call\"\n};\nvar REPORTING = /* @__PURE__ */ new Set([\"clipboard\", \"embedder\"]);\nasync function commitStdout(ctx) {\n const e = await ctx.host.fds.find(1);\n if (e?.type !== \"kernel\" || !REPORTING.has(await ctx.host.fds.kind(1, e))) return;\n try {\n await ctx.host.fds.close(1);\n } catch (err) {\n const code2 = err.code;\n if (typeof code2 !== \"string\") throw err;\n ctx.quit.failed = true;\n try {\n await ctx.sys.write(\n 2,\n encoder5.encode(`${ctx.init.argv0}: write error: ${STRERROR[code2] ?? code2}\n`)\n );\n } catch {\n }\n }\n}\nvar WASI_NOTSUP = 58;\nfunction emscriptenErrno(errno) {\n return errno === WASI_NOTSUP ? EM.NOTSUP : errno;\n}\nfunction emscriptenErrnos(fn) {\n return (async (...args) => emscriptenErrno(await fn(...args) ?? 0));\n}\nasync function streamed(ctx, fd) {\n const e = await ctx.host.fds.find(fd);\n if (e?.type !== \"kernel\") return false;\n const kind = await ctx.host.fds.kind(fd, e);\n return kind !== \"file\" && kind !== \"socket\";\n}\nfunction streamWrite(ctx) {\n return positive(async (fd, iov, n, out) => {\n const e = await ctx.host.fds.get(fd);\n const nonblock = e.type === \"kernel\" && e.nonblock;\n let written;\n try {\n written = await ctx.sys.write(fd, ctx.mem.gather(iov, n), { nonblock });\n } catch (err) {\n if (err.code === \"EPIPE\" && !await sigpipeSpared(ctx)) {\n throw new WasiExit(KILLED_BY_SIGPIPE4);\n }\n throw err;\n }\n ctx.mem.view().setUint32(out, written, true);\n });\n}\nfunction wasiImports(ctx, state) {\n const host = ctx.host.imports();\n const { mem } = ctx;\n const call2 = (name2) => emscriptenErrnos(host[name2]);\n return {\n fd_write: async (fd, iov, n, out) => {\n await holdStopped(ctx);\n const r = await streamed(ctx, fd) ? await restarting(ctx, streamWrite(ctx), [fd, iov, n, out]) : await restarting(ctx, call2(\"fd_write\"), [fd, iov, n, out]);\n await afterStopped(ctx);\n return r;\n },\n fd_read: async (fd, iov, n, out) => {\n await holdStopped(ctx);\n const r = await restarting(ctx, call2(\"fd_read\"), [fd, iov, n, out]);\n await afterStopped(ctx);\n return r;\n },\n fd_pread: async (fd, iov, n, at, out) => {\n if (at < 0n || at > BigInt(Number.MAX_SAFE_INTEGER)) return EM.OVERFLOW;\n return await call2(\"fd_pread\")(...[fd, iov, n, at, out]) ?? 0;\n },\n fd_pwrite: async (fd, iov, n, at, out) => {\n if (at < 0n || at > BigInt(Number.MAX_SAFE_INTEGER)) return EM.OVERFLOW;\n return await call2(\"fd_pwrite\")(...[fd, iov, n, at, out]) ?? 0;\n },\n fd_close: async (fd) => {\n const e = await ctx.host.fds.find(fd);\n if (e) state.listings.delete(e);\n if (fd === 2 && ctx.quit.atExit) await commitStdout(ctx);\n return await call2(\"fd_close\")(...[fd]) ?? 0;\n },\n fd_seek: positive(async (fd, offset, whence, out) => {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"dir\") {\n const pos = seekDir(state, e, Number(offset), whence);\n mem.view().setBigInt64(out, BigInt(pos), true);\n return 0;\n }\n return await call2(\"fd_seek\")(...[fd, offset, whence, out]) ?? 0;\n }),\n fd_sync: positive(async (fd) => {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") await ctx.host.fds.synced(e.file);\n else if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") await ctx.sys.flush(fd);\n }),\n fd_fdstat_get: positive(async (fd, out) => {\n const e = await ctx.host.fds.get(fd);\n let type = 4;\n if (e.type === \"dir\") type = 3;\n else if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"tty\") type = 2;\n const v = mem.view();\n v.setInt8(out, type);\n v.setInt16(out + 2, 0, true);\n v.setBigInt64(out + 8, 0n, true);\n v.setBigInt64(out + 16, 0n, true);\n }),\n environ_sizes_get: (count, size) => {\n const list = envStrings(ctx);\n let bytes = 0;\n for (const s of list) bytes += encoder5.encode(s).length + 1;\n const v = mem.view();\n v.setUint32(count, list.length, true);\n v.setUint32(size, bytes, true);\n return 0;\n },\n environ_get: (envp, buf) => {\n const list = envStrings(ctx);\n let at = buf;\n for (let i = 0; i < list.length; i++) {\n const bytes = encoder5.encode(list[i]);\n mem.view().setUint32(envp + i * 4, at, true);\n mem.bytes(at, bytes.length + 1).set(bytes);\n mem.bytes(at + bytes.length, 1)[0] = 0;\n at += bytes.length + 1;\n }\n return 0;\n },\n clock_time_get: (id, _precision, out) => {\n lookedOutside();\n if (id < 0 || id > 3) return EM.INVAL;\n const now = id === 0 ? Date.now() : performance.now();\n mem.view().setBigInt64(out, BigInt(Math.round(now * 1e3 * 1e3)), true);\n return 0;\n },\n clock_res_get: (id, out) => {\n if (id < 0 || id > 3) return EM.INVAL;\n const nsec = id === 0 ? 1e3 * 1e3 : NODE_CLOCK ? 1 : 1e3;\n mem.view().setBigInt64(out, BigInt(nsec), true);\n return 0;\n },\n random_get: (buf, len) => {\n lookedOutside();\n for (let at = 0; at < len; at += 65536) {\n const chunk = new Uint8Array(Math.min(65536, len - at));\n crypto.getRandomValues(chunk);\n mem.bytes(buf + at, chunk.length).set(chunk);\n }\n return 0;\n },\n proc_exit: (code2) => {\n throw new WasiExit(code2);\n }\n };\n}\n\n// src/process/emscripten/fds.ts\nvar F_DUPFD = 0;\nvar F_GETFD = 1;\nvar F_SETFD = 2;\nvar F_GETFL = 3;\nvar F_SETFL = 4;\nvar F_GETLK2 = 12;\nvar F_SETLK2 = 13;\nvar F_SETLKW2 = 14;\nvar F_DUPFD_CLOEXEC = 1030;\nvar FD_CLOEXEC = 1;\nvar TCGETS = 21505;\nvar TCSETS = 21506;\nvar TCSETSW = 21507;\nvar TCSETSF = 21508;\nvar TCSBRK = 21509;\nvar TCXONC = 21510;\nvar TCFLSH = 21515;\nvar TIOCGPGRP = 21519;\nvar TIOCSPGRP = 21520;\nvar TIOCGWINSZ = 21523;\nvar FIONREAD = 21531;\nvar FIONBIO = 21537;\nvar POLLIN = 1;\nvar POLLOUT = 4;\nvar POLLERR = 8;\nvar POLLHUP = 16;\nvar POLLNVAL = 32;\nvar POLLRDNORM = 64;\nvar POLLWRNORM = 256;\nasync function isTty(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n return e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"tty\";\n}\nasync function isKernel(ctx, fd) {\n return (await ctx.host.fds.find(fd))?.type === \"kernel\";\n}\nfunction readTermios2(ctx, ptr) {\n const v = ctx.mem.view();\n const cCc = [];\n for (let i = 0; i < 32; i++) cCc.push(v.getInt8(ptr + 17 + i));\n return {\n c_iflag: v.getInt32(ptr, true),\n c_oflag: v.getInt32(ptr + 4, true),\n c_cflag: v.getInt32(ptr + 8, true),\n c_lflag: v.getInt32(ptr + 12, true),\n c_cc: cCc\n };\n}\nfunction writeTermios2(ctx, ptr, t) {\n const v = ctx.mem.view();\n v.setInt32(ptr, t.c_iflag || 0, true);\n v.setInt32(ptr + 4, t.c_oflag || 0, true);\n v.setInt32(ptr + 8, t.c_cflag || 0, true);\n v.setInt32(ptr + 12, t.c_lflag || 0, true);\n for (let i = 0; i < 32; i++) v.setInt8(ptr + 17 + i, t.c_cc[i] || 0);\n}\nasync function ptyIoctl2(ctx, fd, request, argp) {\n const v = ctx.mem.view();\n switch (request) {\n case TIOCGPTN:\n v.setInt32(argp, await ctx.sys.ptyNumber(fd), true);\n return 0;\n case TIOCSPTLCK:\n await ctx.sys.ptyLock(fd, v.getInt32(argp, true) !== 0);\n return 0;\n case TIOCSCTTY:\n await ctx.sys.setControllingTerminal(fd);\n return 0;\n case TIOCPKT:\n await ctx.sys.setPacketMode(fd, v.getInt32(argp, true) !== 0);\n return 0;\n default: {\n const word = v.getInt32(argp, true);\n await ctx.sys.setWinsize(fd, word & 65535, word >>> 16 & 65535);\n return 0;\n }\n }\n}\nvar PTY_REQUESTS = /* @__PURE__ */ new Set([\n TIOCGPTN,\n TIOCSPTLCK,\n TIOCSCTTY,\n TIOCSWINSZ,\n TIOCPKT\n]);\nvar TTY_NOOPS = /* @__PURE__ */ new Set([TCSBRK, TCXONC, TCXONC + 1, TCXONC + 2, TCFLSH]);\nasync function ptyRequest(ctx, fd, request, argp) {\n await ctx.host.fds.get(fd);\n if (await isKernel(ctx, fd)) return await ptyIoctl2(ctx, fd, request, argp());\n if (request === TIOCSWINSZ) return await isTty(ctx, fd) ? 0 : -EM.NOTTY;\n return -EM.INVAL;\n}\nasync function termiosRequest(ctx, fd, request, argp) {\n if (!await isTty(ctx, fd)) return -EM.NOTTY;\n if (request === TCGETS) {\n const t = await ctx.sys.tcgets?.(fd);\n if (t) writeTermios2(ctx, argp(), t);\n return 0;\n }\n if (!ctx.sys.tcsets) return 0;\n await ctx.sys.tcsets(fd, readTermios2(ctx, argp()), request === TCSETSF);\n return 0;\n}\nasync function winsize(ctx, fd, argp) {\n if (!await isTty(ctx, fd)) return -EM.NOTTY;\n const [rows, cols] = await ctx.sys.winsize?.(fd) ?? [24, 80];\n const at = argp();\n const v = ctx.mem.view();\n v.setInt16(at, rows, true);\n v.setInt16(at + 2, cols, true);\n return 0;\n}\nasync function ioctl(ctx, fd, op, varargs) {\n const request = op >>> 0;\n const argp = () => ctx.mem.view().getUint32(varargs, true);\n if (PTY_REQUESTS.has(request)) return await ptyRequest(ctx, fd, request, argp);\n if (TTY_NOOPS.has(request)) return await isTty(ctx, fd) ? 0 : -EM.NOTTY;\n if (request === TCGETS || request === TCSETS || request === TCSETSW || request === TCSETSF) {\n return await termiosRequest(ctx, fd, request, argp);\n }\n if (request === TIOCGWINSZ) return await winsize(ctx, fd, argp);\n if (request === TIOCGPGRP) {\n if (!await isTty(ctx, fd)) return -EM.NOTTY;\n ctx.mem.view().setInt32(argp(), 0, true);\n return 0;\n }\n if (request === TIOCSPGRP) return await isTty(ctx, fd) ? -EM.INVAL : -EM.NOTTY;\n await ctx.host.fds.get(fd);\n return request === FIONREAD || request === FIONBIO ? -EM.NOTTY : -EM.INVAL;\n}\nasync function lockAllowed(ctx, fd, varargs) {\n const at = ctx.mem.view().getUint32(varargs, true);\n const type = ctx.mem.view().getInt16(at, true);\n const acc = await fdFlags(ctx, fd) & 3;\n if (type === 0) return acc !== 1;\n if (type === 1) return acc !== 0;\n return true;\n}\nasync function fcntl(ctx, fd, cmd, varargs) {\n const { fds } = ctx.host;\n const arg = () => ctx.mem.view().getInt32(varargs, true);\n await fds.get(fd);\n switch (cmd) {\n case F_DUPFD:\n case F_DUPFD_CLOEXEC: {\n const min = arg();\n if (min < 0) return -EM.INVAL;\n return await fds.dup(fd, min, cmd === F_DUPFD_CLOEXEC);\n }\n case F_GETFD:\n return fds.cloexec.has(fd) ? FD_CLOEXEC : 0;\n case F_SETFD:\n await fds.setCloexec(fd, (arg() & FD_CLOEXEC) !== 0);\n return 0;\n case F_GETFL:\n return await fdFlags(ctx, fd);\n case F_SETFL: {\n const flags = arg();\n await fds.setFlags(fd, (flags & O_NONBLOCK3) !== 0, (flags & O_APPEND3) !== 0);\n return 0;\n }\n case F_GETLK2:\n case F_SETLK2:\n case F_SETLKW2: {\n if (cmd !== F_GETLK2 && !await lockAllowed(ctx, fd, varargs)) return -EM.BADF;\n const lock = ctx.host.sliccImports().fcntl_lock;\n const r = await lock(fd, cmd, ctx.mem.view().getUint32(varargs, true));\n return r === 0 ? 0 : -emscriptenErrno(r);\n }\n default:\n return -EM.INVAL;\n }\n}\nasync function pollMask(ctx, fd) {\n const e = await ctx.host.fds.find(fd);\n if (!e) return POLLNVAL;\n if (e.type !== \"kernel\") return POLLIN | POLLOUT;\n const state = await ctx.sys.poll(fd);\n let mask = 0;\n if (state.readable) mask |= POLLIN | POLLRDNORM;\n if (state.writable) mask |= POLLOUT | POLLWRNORM;\n if (state.hangup) mask |= state.readable ? POLLHUP : POLLERR;\n return mask;\n}\nasync function select(ctx, read2, write2, timeoutMs2) {\n const { fds } = ctx.host;\n const localRead = [];\n const localWrite = [];\n const kernelRead = [];\n const kernelWrite = [];\n for (const fd of read2) {\n const e = await fds.find(fd);\n if (e?.type === \"kernel\") kernelRead.push(fd);\n else localRead.push(fd);\n }\n for (const fd of write2) {\n const e = await fds.find(fd);\n if (e?.type === \"kernel\") kernelWrite.push(fd);\n else localWrite.push(fd);\n }\n const local2 = localRead.length + localWrite.length > 0;\n if (kernelRead.length + kernelWrite.length === 0 && local2) {\n return { read: localRead, write: localWrite };\n }\n const got = await ctx.call({\n op: \"fd-select\",\n read: kernelRead,\n write: kernelWrite,\n timeoutMs: local2 ? 0 : timeoutMs2\n });\n const out = { read: [], write: [] };\n for (const fd of read2) {\n if (localRead.includes(fd) || got.read.includes(fd)) out.read.push(fd);\n }\n for (const fd of write2) {\n if (localWrite.includes(fd) || got.write.includes(fd)) out.write.push(fd);\n }\n return out;\n}\nfunction bitsOf(ctx, set, n) {\n const out = [];\n if (!set) return out;\n const v = ctx.mem.view();\n for (let fd = 0; fd < n; fd++) {\n if (v.getUint32(set + (fd >> 5) * 4, true) & 1 << (fd & 31)) out.push(fd);\n }\n return out;\n}\nfunction storeBits(ctx, set, n, ready) {\n if (!set) return;\n const v = ctx.mem.view();\n for (let w = 0; w < n + 31 >> 5; w++) v.setUint32(set + w * 4, 0, true);\n for (const fd of ready) {\n const at = set + (fd >> 5) * 4;\n v.setUint32(at, (v.getUint32(at, true) | 1 << (fd & 31)) >>> 0, true);\n }\n}\nasync function blockingPoll(ctx, ptr, n, timeoutMs2) {\n const IN = POLLIN | POLLRDNORM;\n const OUT = POLLOUT | POLLWRNORM;\n const v = () => ctx.mem.view();\n const read2 = [];\n const write2 = [];\n for (let i = 0; i < n; i++) {\n const fd = v().getInt32(ptr + i * 8, true);\n const events = v().getInt16(ptr + i * 8 + 4, true);\n if (fd < 0) continue;\n if (events & IN) read2.push(fd);\n if (events & OUT) write2.push(fd);\n }\n const ready = await select(ctx, read2, write2, timeoutMs2);\n let count = 0;\n for (let i = 0; i < n; i++) {\n const fd = v().getInt32(ptr + i * 8, true);\n const events = v().getInt16(ptr + i * 8 + 4, true);\n let revents = 0;\n if (fd >= 0 && ready.read.includes(fd)) revents |= events & IN;\n if (fd >= 0 && ready.write.includes(fd)) revents |= events & OUT;\n v().setInt16(ptr + i * 8 + 6, revents, true);\n if (revents) count++;\n }\n return count;\n}\nfunction fdImports(ctx) {\n const { fds } = ctx.host;\n return {\n __syscall_dup: negated(async (fd) => await fds.dup(fd, 0, false)),\n __syscall_dup3: negated(async (fd, newfd, flags) => {\n await fds.get(fd);\n if (fd === newfd) return -EM.INVAL;\n if (newfd < 0 || newfd >= 4096) return -EM.BADF;\n if (flags === 0 && await fds.find(newfd)) {\n try {\n await fds.close(newfd);\n } catch {\n }\n }\n await fds.renumber(fd, newfd, true);\n if (flags & O_CLOEXEC2) await fds.setCloexec(newfd, true);\n return newfd;\n }),\n __syscall_fcntl64: negated(\n async (fd, cmd, varargs) => await fcntl(ctx, fd, cmd, varargs)\n ),\n __syscall_ioctl: negated(\n async (fd, op, varargs) => await ioctl(ctx, fd, op, varargs)\n ),\n __syscall_pipe: negated(async (ptr) => {\n if (ptr === 0) return -EM.FAULT;\n const [r, w] = await fds.pipe();\n const v = ctx.mem.view();\n v.setInt32(ptr, r, true);\n v.setInt32(ptr + 4, w, true);\n }),\n __syscall_flock: negated(async (fd, op) => {\n const flock = ctx.host.sliccImports().flock;\n const r = await flock(fd, op);\n return r === 0 ? 0 : -emscriptenErrno(r);\n }),\n _poll_js: negated(async (ptr, nfds) => {\n let count = 0;\n const v = () => ctx.mem.view();\n for (let i = 0; i < nfds; i++) {\n const at = ptr + 8 * i;\n const fd = v().getInt32(at, true);\n const events = v().getInt16(at + 4, true);\n const flags = await pollMask(ctx, fd) & (events | POLLERR | POLLHUP);\n if (flags) count++;\n v().setInt16(at + 6, flags, true);\n }\n return count;\n }),\n slicc_select_js: negated(async (n, rfds, wfds, timeoutMs2) => {\n const r = await select(ctx, bitsOf(ctx, rfds, n), bitsOf(ctx, wfds, n), timeoutMs2);\n storeBits(ctx, rfds, n, r.read);\n storeBits(ctx, wfds, n, r.write);\n return r.read.length + r.write.length;\n }),\n slicc_poll_js: negated(\n async (ptr, n, timeoutMs2) => await blockingPoll(ctx, ptr, n, timeoutMs2)\n )\n };\n}\n\n// src/process/emscripten/errno-cell.ts\nvar ENOMEM = 48;\nvar IMPOSSIBLE = 3221225472;\nvar ErrnoCell = class {\n at;\n ctx;\n constructor(ctx) {\n this.ctx = ctx;\n }\n find() {\n const malloc = this.ctx.exports().malloc;\n if (typeof malloc !== \"function\") return void 0;\n const before = new Int32Array(this.ctx.mem.bytes(0, this.ctx.mem.size()).slice().buffer);\n const got = malloc(IMPOSSIBLE);\n if (got !== 0) {\n this.ctx.exports().free?.(got);\n return void 0;\n }\n const after = new Int32Array(this.ctx.exports().memory.buffer, 0, before.length);\n let found;\n for (let i = 0; i < before.length; i++) {\n if (after[i] !== ENOMEM || before[i] === ENOMEM) continue;\n if (found !== void 0) return void 0;\n found = i * 4;\n }\n return found;\n }\n set(errno) {\n this.at ??= this.find();\n if (this.at === void 0) return false;\n this.ctx.mem.view().setInt32(this.at, errno, true);\n return true;\n }\n};\n\n// src/process/emscripten/fork.ts\nvar REWINDING2 = 2;\nvar ASYNCIFY_STACK = 1048576;\nvar EmFork = class {\n forking = false;\n forkSp = 0;\n data = 0;\n value = 0;\n ctx;\n errno;\n constructor(ctx) {\n this.ctx = ctx;\n this.errno = new ErrnoCell(ctx);\n }\n supported() {\n return typeof this.ctx.exports().asyncify_start_unwind === \"function\";\n }\n forkImport() {\n const ex = this.ctx.exports();\n if (ex.asyncify_get_state?.() === REWINDING2) {\n ex.asyncify_stop_rewind?.();\n ex.free?.(this.data);\n this.data = 0;\n return this.value;\n }\n this.forking = true;\n this.forkSp = ex.emscripten_stack_get_current();\n const ptr = ex.malloc(12 + ASYNCIFY_STACK);\n const v = this.ctx.mem.view();\n v.setUint32(ptr, ptr + 12, true);\n v.setUint32(ptr + 4, ptr + 12 + ASYNCIFY_STACK, true);\n v.setInt32(ptr + 8, 0, true);\n this.data = ptr;\n ex.asyncify_start_unwind?.(ptr);\n return 0;\n }\n async settle(ret) {\n let result = ret;\n for (; ; ) {\n const name2 = this.ctx.reentry.unwound;\n if (name2 === void 0) return result;\n this.ctx.reentry.unwound = void 0;\n if (!this.forking) {\n throw new Error(`${this.ctx.init.argv0}: unexpected Asyncify suspension (not a fork)`);\n }\n this.forking = false;\n result = await this.resume(name2, this.failed(await this.kernelFork(name2)));\n }\n }\n failed(pid) {\n if (pid >= 0) return pid;\n this.errno.set(-pid);\n return -1;\n }\n async resume(name2, value2) {\n const ex = this.ctx.exports();\n ex._emscripten_stack_restore(this.forkSp);\n this.value = value2;\n ex.asyncify_start_rewind?.(this.data);\n return await this.ctx.enter(name2, ex[name2], []);\n }\n async child(state) {\n const memory = this.ctx.exports().memory;\n if (state.memory.length > memory.buffer.byteLength) {\n memory.grow(Math.ceil((state.memory.length - memory.buffer.byteLength) / 65536));\n }\n new Uint8Array(memory.buffer).set(state.memory);\n state.memory = new Uint8Array(0);\n this.data = state.currData;\n this.forkSp = state.forkSp;\n const name2 = state.callStackNames[0]?.[1] ?? \"main\";\n return await this.settle(await this.resume(name2, 0));\n }\n snapshot(name2) {\n const { host, cwd } = this.ctx;\n const memory = this.ctx.mem.bytes(0, this.ctx.mem.size()).slice();\n const wasi = {\n asyncifyData: this.data,\n globals: [],\n fds: host.fds.snapshot(),\n cloexec: [...host.fds.cloexec],\n cwd: cwd.path\n };\n return {\n memory,\n currData: this.data,\n forkSp: this.forkSp,\n callStackNames: [[0, name2]],\n ppid: this.ctx.pid,\n wasi\n };\n }\n async kernelFork(name2) {\n const { host, gate } = this.ctx;\n try {\n await host.fds.flushAll();\n await host.fds.promoteFiles();\n } catch (e) {\n const code2 = e.code;\n if (typeof code2 !== \"string\") throw e;\n return -wasiErrno(code2);\n }\n let seen = gate.deliveries();\n let state = this.snapshot(name2);\n for (; ; ) {\n try {\n return await this.ctx.call({ op: \"proc-fork\", state, restart: true });\n } catch (e) {\n const code2 = e.code;\n if (code2 !== \"EINTR\") {\n if (typeof code2 !== \"string\") throw e;\n return -wasiErrno(code2);\n }\n if (gate.deliveries() !== seen) {\n seen = gate.deliveries();\n state = this.snapshot(name2);\n }\n }\n }\n }\n};\n\n// src/process/emscripten/longjmp.ts\nvar LONGJMP = Number.POSITIVE_INFINITY;\nfunction dynCallOf(ctx, sig, index3) {\n const ex = ctx.exports();\n const named = ex[`dynCall_${sig}`];\n if (typeof named === \"function\")\n return [`dynCall_${sig}`, named];\n const table = ex.__indirect_function_table;\n const fn = table?.get(index3);\n if (typeof fn !== \"function\")\n throw new WebAssembly.RuntimeError(\"null function or function signature mismatch\");\n return [`table:${index3}`, fn];\n}\nfunction invoke(ctx, sig) {\n const returnsI64 = sig.startsWith(\"j\");\n return async (index3, ...rest2) => {\n const ex = ctx.exports();\n const save = ex.emscripten_stack_get_current;\n const restore = ex._emscripten_stack_restore;\n const sp = save();\n try {\n const [name2, fn] = dynCallOf(ctx, sig, index3);\n const args = name2.startsWith(\"dynCall_\") ? [index3, ...rest2] : rest2;\n return await ctx.enter(name2, fn, args);\n } catch (e) {\n restore(sp);\n if (e !== e + 0) throw e;\n ex.setThrew(1, 0);\n return returnsI64 ? 0n : void 0;\n }\n };\n}\nfunction invokeImports(ctx, module) {\n const out = {};\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module !== \"env\" || !imp.name.startsWith(\"invoke_\")) continue;\n out[imp.name] = invoke(ctx, imp.name.slice(\"invoke_\".length));\n }\n return out;\n}\n\n// src/process/emscripten/mmap.ts\nvar PROT_WRITE = 2;\nvar MAP_PRIVATE = 2;\nvar MAP_TYPE = 15;\nvar MAP_ALIGN = 65536;\nvar MAX_READ2 = 1024 * 1024;\nasync function readAt(ctx, fd, target, position) {\n const e = await ctx.host.fds.get(fd);\n let done = 0;\n while (done < target.length) {\n const want = Math.min(MAX_READ2, target.length - done);\n let got;\n if (e.type === \"file\") got = await e.file.pread(want, position + done);\n else got = await ctx.sys.pread?.(fd, want, position + done) ?? new Uint8Array(0);\n if (got.length === 0) break;\n target.set(got, done);\n done += got.length;\n }\n return done;\n}\nfunction mmapImport(ctx) {\n return {\n _mmap_js: negated(\n async (len, prot, flags, fd, offset, allocated, addr) => {\n const position = Number(offset);\n if (!Number.isSafeInteger(position)) return -EM.OVERFLOW;\n const e = await ctx.host.fds.get(fd);\n const kernelFile = e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\";\n if (e.type !== \"file\" && !kernelFile) throw new EmError(43);\n const shared = (flags & MAP_TYPE) !== MAP_PRIVATE && (prot & PROT_WRITE) !== 0;\n if (shared) throw new EmError(43);\n if (e.type === \"file\" && !e.file.readable) throw new EmError(2);\n if (len <= 0) return -EM.INVAL;\n const memalign = ctx.exports().emscripten_builtin_memalign;\n if (!memalign) return -EM.NOMEM;\n const data = new Uint8Array(len);\n const done = await readAt(ctx, fd, data, position);\n const size = Math.ceil(len / MAP_ALIGN) * MAP_ALIGN;\n const ptr = memalign(MAP_ALIGN, size);\n if (!ptr) return -EM.NOMEM;\n const target = ctx.mem.bytes(ptr, size);\n target.fill(0);\n target.set(data.subarray(0, done));\n const v = ctx.mem.view();\n v.setInt32(allocated, 1, true);\n v.setUint32(addr, ptr, true);\n return 0;\n }\n )\n };\n}\n\n// src/process/emscripten/proc.ts\nvar WNOHANG = 1;\nvar WUNTRACED = 2;\nvar WCONTINUED = 8;\nvar IDS2 = [\"ruid\", \"euid\", \"suid\", \"rgid\", \"egid\", \"sgid\"];\nfunction strings(ctx, ptr) {\n const out = [];\n if (!ptr) return out;\n const v = ctx.mem.view();\n for (let i = 0; ; i++) {\n const s = v.getUint32(ptr + i * 4, true);\n if (!s) break;\n out.push(ctx.mem.cString(s));\n }\n return out;\n}\nfunction envOf(ctx, ptr) {\n if (!ptr) return null;\n const env = {};\n for (const kv of strings(ctx, ptr)) {\n const eq = kv.indexOf(\"=\");\n if (eq > 0) env[kv.slice(0, eq)] = kv.slice(eq + 1);\n }\n return env;\n}\nasync function restartedCall(ctx, req) {\n for (; ; ) {\n try {\n return await ctx.call(req);\n } catch (e) {\n if (e.code !== \"EINTR\") throw e;\n }\n }\n}\nasync function slot(ctx, fd) {\n const e = fd >= 0 ? await ctx.host.fds.find(fd) : void 0;\n if (!e) return { none: true };\n if (e.type === \"kernel\") return { fd };\n if (e.type === \"dir\") return { dir: e.path };\n if (e.type === \"device\") return { device: e.device, ...e.access ? { access: e.access } : {} };\n return { none: true };\n}\nfunction inherited(ctx, actions) {\n const { fds } = ctx.host;\n const table = /* @__PURE__ */ new Map();\n for (const entry of fds.snapshot()) {\n const cloexec = fds.cloexec.has(entry.fd);\n if (entry.type === \"kernel\")\n table.set(entry.fd, { slot: { fd: entry.fd, kernel: entry.fd }, cloexec });\n else if (entry.type === \"device\") {\n const access3 = entry.access ? { access: entry.access } : {};\n table.set(entry.fd, { slot: { fd: entry.fd, device: entry.device, ...access3 }, cloexec });\n } else table.set(entry.fd, { slot: void 0, cloexec });\n }\n for (const [target, source] of actions) {\n if (target <= 2) continue;\n const from = source >= 0 ? table.get(source) : void 0;\n if (from?.slot) {\n const moved = \"kernel\" in from.slot ? { fd: target, kernel: from.slot.kernel } : { ...from.slot, fd: target };\n table.set(target, { slot: moved, cloexec: false });\n } else table.delete(target);\n }\n const out = [];\n for (const [fd, { slot: s, cloexec }] of table) {\n if (fd > 2 && !cloexec && s) out.push(s);\n }\n return out;\n}\nasync function kernelWait(ctx, pid, nohang, options = 0) {\n const req = {\n op: \"proc-wait\",\n pid,\n nohang,\n ...options & WUNTRACED ? { untraced: true } : {},\n ...options & WCONTINUED ? { continued: true } : {}\n };\n for (; ; ) {\n try {\n const waited = await ctx.call(req) ?? [0, 0];\n if (waited[0] > 0) ctx.host.o.fs.invalidate?.();\n return [waited[0], waited[1]];\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n if (errno === 27 && ctx.gate.restartable()) continue;\n return -errno;\n }\n }\n}\nasync function execWait(ctx, pid) {\n try {\n const r = await ctx.call({ op: \"proc-exec\", pid });\n ctx.host.o.fs.invalidate?.();\n return r ? r[1] : 0;\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n}\nasync function spawnChild(ctx, req) {\n const { fds } = ctx.host;\n try {\n await fds.flushAll();\n await fds.promoteFiles();\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n const stdio = [];\n for (let n = 0; n < 3; n++) stdio.push(await slot(ctx, req.stdio[n] ?? -1));\n const inherit = inherited(ctx, req.actions);\n const spawn = {\n op: \"proc-spawn\",\n file: req.file,\n argv: req.argv,\n env: req.env ?? ctx.init.env,\n cwd: req.cwd ?? ctx.cwd.path,\n ...req.cwd !== null ? { chdir: true } : {},\n stdio,\n ...inherit.length > 0 ? { inherit } : {},\n ...req.exec ? { exec: true } : {},\n restart: true\n };\n try {\n return await restartedCall(ctx, spawn);\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n } finally {\n ctx.host.o.fs.invalidate?.();\n }\n}\nfunction throughKernel(sig) {\n if (sig === 0) return false;\n const action = defaultAction(sig);\n return action === \"terminate\" || action === \"stop\";\n}\nasync function status(ctx, req) {\n try {\n await ctx.call(req);\n return 0;\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n}\nasync function numberOf(ctx, req) {\n try {\n const r = await ctx.call(req);\n return typeof r === \"number\" ? r : -EM.IO;\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n}\nasync function terminal(ctx, fd) {\n return (await ctx.host.fds.find(fd))?.type === \"kernel\";\n}\nasync function jobs(ctx, op, a, b) {\n switch (op) {\n case 0:\n return await status(ctx, { op: \"proc-setpgid\", pid: a, pgid: b });\n case 1:\n return await numberOf(ctx, { op: \"proc-getpgid\", pid: a });\n case 2:\n return await numberOf(ctx, { op: \"proc-getsid\", pid: a });\n case 3:\n return await numberOf(ctx, { op: \"proc-setsid\" });\n case 4:\n return await terminal(ctx, a) ? await numberOf(ctx, { op: \"tty-pgrp-get\", fd: a }) : -EM.NOTTY;\n case 5:\n return await terminal(ctx, a) ? await status(ctx, { op: \"tty-pgrp-set\", fd: a, pgrp: b }) : -EM.NOTTY;\n }\n return -EM.NOSYS;\n}\nasync function credOf2(ctx) {\n return await ctx.call({ op: \"proc-cred\" });\n}\nfunction procImports(ctx, state) {\n const { mem } = ctx;\n const cred = ctx.host.sliccImports();\n return {\n slicc_spawn_capture_js: async (path, argv, envp, cwd, inFd, outFd, errFd, actions, nactions) => {\n const file = mem.cString(path);\n if (!file) return -EM.NOENT;\n const pairs = [];\n const v = mem.view();\n for (let i = 0; i < nactions; i++) {\n pairs.push([v.getInt32(actions + 8 * i, true), v.getInt32(actions + 8 * i + 4, true)]);\n }\n return await spawnChild(ctx, {\n file,\n argv: strings(ctx, argv),\n env: envOf(ctx, envp),\n cwd: cwd ? mem.cString(cwd) : null,\n stdio: [inFd === -2 ? 0 : inFd, outFd, errFd],\n actions: pairs,\n exec: false\n });\n },\n slicc_wait_js: async (pid, statusPtr, options) => {\n const r = await kernelWait(ctx, pid, (options & WNOHANG) !== 0, options);\n if (typeof r === \"number\") return r;\n if (statusPtr && r[0] > 0) mem.view().setInt32(statusPtr, r[1], true);\n return r[0];\n },\n slicc_exec_detach: () => 0,\n slicc_exec_wait_js: async (pid) => await execWait(ctx, pid),\n slicc_execve_js: async (path, argv, envp) => {\n const file = mem.cString(path);\n if (!file) return -EM.NOENT;\n const pid = await spawnChild(ctx, {\n file,\n argv: strings(ctx, argv),\n env: envOf(ctx, envp),\n cwd: null,\n stdio: [0, 1, 2],\n actions: [],\n exec: true\n });\n if (pid < 0) return pid;\n return await execWait(ctx, pid);\n },\n slicc_in_emulated_fork: () => 0,\n slicc_getpid_js: () => ctx.pid,\n slicc_getppid_js: async () => (await identify(ctx.transport, ctx.init)).ppid,\n slicc_default_getpid_js: () => ctx.pid | 0 || 42,\n slicc_default_getppid_js: () => ctx.ppid | 0 || 1,\n slicc_kill_js: async (pid, sig) => {\n if (pid === ctx.init.pid && !throughKernel(sig)) {\n if (sig !== 0) await state.raise(sig);\n return 0;\n }\n return await status(ctx, { op: \"proc-kill\", pid, sig });\n },\n slicc_pause_js: async () => await status(ctx, { op: \"sig-pause\" }),\n slicc_sig_inherited_js: async () => {\n try {\n const bits = await inheritedSignals(ctx.transport);\n state.seeded.bits |= bits;\n return bits | 0;\n } catch {\n return 0;\n }\n },\n slicc_jobs_js: async (op, a, b) => await jobs(ctx, op, a, b),\n slicc_cred_js: negated(async (out) => {\n const c = await credOf2(ctx);\n const v = mem.view();\n for (let i = 0; i < IDS2.length; i++) v.setUint32(out + i * 4, c[IDS2[i]] >>> 0, true);\n }),\n slicc_groups_js: negated(async (list, cap) => {\n const { groups } = await credOf2(ctx);\n if (cap === 0) return groups.length;\n if (cap < groups.length) return -EM.INVAL;\n const v = mem.view();\n for (let i = 0; i < groups.length; i++)\n v.setUint32(list + i * 4, groups[i] >>> 0, true);\n return groups.length;\n }),\n slicc_setcred_js: async (...ids) => {\n const set = cred.cred_set;\n const r = await set(...ids);\n return r === 0 ? 0 : -r;\n },\n slicc_setgroups_js: async (list, n) => {\n const set = cred.groups_set;\n const r = await set(list, n);\n return r === 0 ? 0 : -r;\n },\n slicc_sleep_ms: async (ms) => {\n await holdStopped(ctx);\n await sleepIn(ctx, ms);\n await afterStopped(ctx);\n }\n };\n}\n\n// src/process/emscripten/pthread.ts\nvar DEFAULT_STACK = 65536;\nasync function canBlock() {\n try {\n await atomicsWait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n return true;\n } catch {\n return false;\n }\n}\nasync function initMainThread(ctx, self) {\n const ex = ctx.exports();\n const blocks = await canBlock();\n const init = ex._emscripten_thread_init;\n if (typeof init === \"function\") {\n const args = [self, blocks ? 0 : 1, 1, blocks ? 1 : 0, DEFAULT_STACK, 0];\n await ctx.enter(\"_emscripten_thread_init\", init, args);\n }\n const tls = ex._emscripten_tls_init;\n if (typeof tls === \"function\") await ctx.enter(\"_emscripten_tls_init\", tls, []);\n}\nfunction pthreadImports(ctx) {\n const nothing = () => {\n };\n return {\n _emscripten_init_main_thread_js: async (self) => await initMainThread(ctx, self),\n __pthread_create_js: () => EM.AGAIN,\n _emscripten_thread_set_strongref: nothing,\n _emscripten_thread_mailbox_await: nothing,\n _emscripten_thread_cleanup: nothing,\n _emscripten_notify_mailbox_postmessage: nothing,\n _emscripten_receive_on_main_thread_js: () => 0,\n emscripten_check_blocking_allowed: nothing,\n emscripten_exit_with_live_runtime: async () => await ctx.exit(0)\n };\n}\n\n// src/process/emscripten/reentry.ts\nvar UNWINDING2 = 1;\nvar Reentry = class {\n stack = [];\n state = () => 0;\n stopUnwind = () => {\n };\n unwound;\n bind(exports) {\n const state = exports.asyncify_get_state;\n const stop = exports.asyncify_stop_unwind;\n if (typeof state === \"function\") this.state = state;\n if (typeof stop === \"function\") this.stopUnwind = stop;\n }\n async enter(name2, fn, args) {\n this.stack.push(name2);\n try {\n return await reentered(fn)(...args);\n } finally {\n this.stack.pop();\n if (this.stack.length === 0 && await this.state() === UNWINDING2) {\n await this.stopUnwind();\n this.unwound = name2;\n }\n }\n }\n};\n\n// src/process/emscripten/time.ts\nvar TZ_GROUPS = [\n [\n \"Europe/London Europe/Belfast Europe/Guernsey Europe/Isle_of_Man Europe/Jersey GB GB-Eire\",\n { \"0\": \"GMT\", d3600: \"BST\" }\n ],\n [\"Europe/Dublin Eire\", { \"0\": \"GMT\", d3600: \"IST\" }],\n [\n \"Europe/Lisbon Portugal Atlantic/Madeira Atlantic/Canary Atlantic/Faroe Atlantic/Faeroe WET\",\n { \"0\": \"WET\", d3600: \"WEST\" }\n ],\n [\n \"Europe/Amsterdam Europe/Andorra Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Budapest Europe/Busingen Europe/Copenhagen Europe/Gibraltar Europe/Ljubljana Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Monaco Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Rome Europe/San_Marino Europe/Sarajevo Europe/Skopje Europe/Stockholm Europe/Tirane Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Warsaw Europe/Zagreb Europe/Zurich Africa/Ceuta Africa/Algiers Africa/Tunis Arctic/Longyearbyen Atlantic/Jan_Mayen Poland CET MET\",\n { \"3600\": \"CET\", d7200: \"CEST\" }\n ],\n [\n \"Europe/Athens Europe/Bucharest Europe/Chisinau Europe/Helsinki Europe/Kiev Europe/Kyiv Europe/Mariehamn Europe/Riga Europe/Sofia Europe/Tallinn Europe/Tiraspol Europe/Uzhgorod Europe/Vilnius Europe/Zaporozhye Europe/Nicosia Europe/Kaliningrad Asia/Beirut Asia/Nicosia Africa/Cairo Egypt EET\",\n { \"7200\": \"EET\", d10800: \"EEST\" }\n ],\n [\"Europe/Moscow Europe/Simferopol Europe/Kirov Europe/Volgograd W-SU\", { \"10800\": \"MSK\" }],\n [\"Asia/Jerusalem Asia/Tel_Aviv Israel\", { \"7200\": \"IST\", d10800: \"IDT\" }],\n [\"Asia/Kolkata Asia/Calcutta\", { \"19800\": \"IST\" }],\n [\"Asia/Karachi\", { \"18000\": \"PKT\", d21600: \"PKST\", since: 31536e3 }],\n [\"Asia/Tokyo Japan\", { \"32400\": \"JST\", d36000: \"JDT\" }],\n [\"Asia/Seoul Asia/Pyongyang ROK\", { \"32400\": \"KST\", d36000: \"KDT\" }],\n [\n \"Asia/Shanghai Asia/Chongqing Asia/Chungking Asia/Harbin Asia/Taipei Asia/Macau Asia/Macao PRC ROC\",\n { \"28800\": \"CST\", d32400: \"CDT\" }\n ],\n [\"Asia/Manila\", { \"28800\": \"PST\", d32400: \"PDT\" }],\n [\"Asia/Hong_Kong Hongkong\", { \"28800\": \"HKT\", d32400: \"HKST\" }],\n [\"Asia/Jakarta Asia/Pontianak\", { \"25200\": \"WIB\" }],\n [\"Asia/Makassar Asia/Ujung_Pandang\", { \"28800\": \"WITA\" }],\n [\"Asia/Jayapura\", { \"32400\": \"WIT\" }],\n [\n \"Australia/Sydney Australia/Melbourne Australia/Hobart Australia/Canberra Australia/ACT Australia/NSW Australia/Victoria Australia/Tasmania Australia/Currie Australia/Brisbane Australia/Lindeman Australia/Queensland Antarctica/Macquarie\",\n { \"36000\": \"AEST\", d39600: \"AEDT\" }\n ],\n [\n \"Australia/Adelaide Australia/Broken_Hill Australia/South Australia/Yancowinna Australia/Darwin Australia/North\",\n { \"34200\": \"ACST\", d37800: \"ACDT\" }\n ],\n [\"Australia/Perth Australia/West\", { \"28800\": \"AWST\", d32400: \"AWDT\" }],\n [\n \"Pacific/Auckland Antarctica/McMurdo Antarctica/South_Pole NZ\",\n { \"43200\": \"NZST\", d46800: \"NZDT\" }\n ],\n [\"Pacific/Guam Pacific/Saipan\", { \"36000\": \"ChST\", since: 977493600 }],\n [\"Africa/Windhoek\", { \"7200\": \"CAT\", since: 637365600 }],\n [\"Asia/Gaza Asia/Hebron\", { \"7200\": \"EET\", d10800: \"EEST\", since: 820454400 }],\n [\"Pacific/Pago_Pago Pacific/Midway Pacific/Samoa US/Samoa\", { \"-39600\": \"SST\" }],\n [\"America/Adak America/Atka US/Aleutian\", { \"-36000\": \"HST\", \"d-32400\": \"HDT\" }],\n [\n \"America/Hermosillo America/Mazatlan America/Chihuahua America/Ciudad_Juarez America/Ojinaga America/Dawson America/Whitehorse Mexico/BajaSur Canada/Yukon\",\n { \"-25200\": \"MST\", \"d-21600\": \"MDT\", intl: 1 }\n ],\n [\"America/Havana Cuba\", { \"-18000\": \"CST\", \"d-14400\": \"CDT\" }],\n [\n \"Etc/GMT Etc/GMT0 Etc/GMT+0 Etc/GMT-0 Etc/Greenwich GMT GMT0 GMT+0 GMT-0 Greenwich\",\n { \"0\": \"GMT\" }\n ],\n [\"Antarctica/Troll\", { \"0\": \"+00\", d7200: \"+02\" }],\n [\"America/St_Johns Canada/Newfoundland\", { \"-12600\": \"NST\", \"d-9000\": \"NDT\" }],\n [\"Africa/Johannesburg Africa/Maseru Africa/Mbabane\", { \"7200\": \"SAST\" }],\n [\n \"Africa/Maputo Africa/Blantyre Africa/Bujumbura Africa/Gaborone Africa/Harare Africa/Kigali Africa/Lubumbashi Africa/Lusaka\",\n { \"7200\": \"CAT\" }\n ],\n [\"Africa/Juba Africa/Khartoum\", { \"7200\": \"CAT\", \"10800\": \"EAT\" }],\n [\n \"Africa/Nairobi Africa/Addis_Ababa Africa/Asmara Africa/Asmera Africa/Dar_es_Salaam Africa/Djibouti Africa/Kampala Africa/Mogadishu Indian/Antananarivo Indian/Comoro Indian/Mayotte\",\n { \"10800\": \"EAT\" }\n ],\n [\n \"Africa/Lagos Africa/Bangui Africa/Brazzaville Africa/Douala Africa/Kinshasa Africa/Libreville Africa/Luanda Africa/Malabo Africa/Niamey Africa/Porto-Novo Africa/Ndjamena\",\n { \"3600\": \"WAT\" }\n ]\n];\nvar tzTable;\nfunction zones() {\n if (tzTable) return tzTable;\n const table = /* @__PURE__ */ new Map();\n for (const [names2, labels] of TZ_GROUPS) {\n for (const zone of names2.split(\" \")) table.set(zone, labels);\n }\n tzTable = table;\n return table;\n}\nvar lows = /* @__PURE__ */ new Map();\nvar MONTH = 2629800;\nfunction tzIntl(zone, t) {\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n timeZoneName: \"short\"\n });\n const at = (s) => {\n const parts = {};\n for (const p of fmt.formatToParts(new Date(s * 1e3))) parts[p.type] = p.value;\n const wall = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n ) / 1e3;\n return { off: Math.round(wall - s), name: parts.timeZoneName ?? \"\" };\n };\n const now = at(t);\n const canon = fmt.resolvedOptions().timeZone;\n const names2 = zones().get(zone) ?? zones().get(canon);\n const key = `${zone}|${Math.floor(t / 86400)}`;\n let low = lows.get(key);\n if (!low) {\n low = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];\n for (let m = 1; m <= 12; m++) {\n low[0] = Math.min(low[0], at(t - m * MONTH).off);\n low[1] = Math.min(low[1], at(t + m * MONTH).off);\n }\n if (lows.size > 4096) lows.clear();\n lows.set(key, low);\n }\n const dst = now.off > low[0] && now.off > low[1] ? 1 : 0;\n const since = names2?.since;\n const fixed = names2 && !(typeof since === \"number\" && t < since) ? names2[`${dst ? \"d\" : \"\"}${now.off}`] : void 0;\n const fixedLabel = typeof fixed === \"string\" ? fixed : void 0;\n let label = fixedLabel && !names2?.intl ? fixedLabel : /^[A-Za-z]{3,5}$/.test(now.name) ? now.name : fixedLabel;\n if (!label) {\n const a = Math.abs(now.off);\n const hh = String(Math.floor(a / 3600)).padStart(2, \"0\");\n const mm = Math.floor(a / 60) % 60;\n label = `${now.off < 0 ? \"-\" : \"+\"}${hh}${mm ? String(mm).padStart(2, \"0\") : \"\"}`;\n }\n return { value: now.off * 2 + dst, label };\n}\nvar LEAP = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\nvar REGULAR = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];\nfunction leap(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nfunction yday(date) {\n const table = leap(date.getFullYear()) ? LEAP : REGULAR;\n return table[date.getMonth()] + date.getDate() - 1;\n}\nfunction i53(value2) {\n return value2 < -9007199254740992n || value2 > 9007199254740992n ? Number.NaN : Number(value2);\n}\nfunction zoneName(offset) {\n const sign = offset >= 0 ? \"-\" : \"+\";\n const abs = Math.abs(offset);\n return `UTC${sign}${String(Math.floor(abs / 60)).padStart(2, \"0\")}${String(abs % 60).padStart(2, \"0\")}`;\n}\nvar ALIASES = {\n A: \"%a\",\n B: \"%b\",\n c: \"%a %b %d %H:%M:%S %Y\",\n D: \"%m\\\\/%d\\\\/%y\",\n e: \"%d\",\n F: \"%Y-%m-%d\",\n h: \"%b\",\n R: \"%H\\\\:%M\",\n r: \"%I\\\\:%M\\\\:%S\\\\s%p\",\n T: \"%H\\\\:%M\\\\:%S\",\n x: \"%m\\\\/%d\\\\/(?:%y|%Y)\",\n X: \"%H\\\\:%M\\\\:%S\"\n};\nvar FIELDS = {\n a: \"(?:Sun(?:day)?)|(?:Mon(?:day)?)|(?:Tue(?:sday)?)|(?:Wed(?:nesday)?)|(?:Thu(?:rsday)?)|(?:Fri(?:day)?)|(?:Sat(?:urday)?)\",\n b: \"(?:Jan(?:uary)?)|(?:Feb(?:ruary)?)|(?:Mar(?:ch)?)|(?:Apr(?:il)?)|May|(?:Jun(?:e)?)|(?:Jul(?:y)?)|(?:Aug(?:ust)?)|(?:Sep(?:tember)?)|(?:Oct(?:ober)?)|(?:Nov(?:ember)?)|(?:Dec(?:ember)?)\",\n C: \"\\\\d\\\\d\",\n d: \"0[1-9]|[1-9](?!\\\\d)|1\\\\d|2\\\\d|30|31\",\n H: \"\\\\d(?!\\\\d)|[0,1]\\\\d|20|21|22|23\",\n I: \"\\\\d(?!\\\\d)|0\\\\d|10|11|12\",\n j: \"00[1-9]|0?[1-9](?!\\\\d)|0?[1-9]\\\\d(?!\\\\d)|[1,2]\\\\d\\\\d|3[0-6]\\\\d\",\n m: \"0[1-9]|[1-9](?!\\\\d)|10|11|12\",\n M: \"0\\\\d|\\\\d(?!\\\\d)|[1-5]\\\\d\",\n n: \" \",\n p: \"AM|am|PM|pm|A\\\\.M\\\\.|a\\\\.m\\\\.|P\\\\.M\\\\.|p\\\\.m\\\\.\",\n S: \"0\\\\d|\\\\d(?!\\\\d)|[1-5]\\\\d|60\",\n U: \"0\\\\d|\\\\d(?!\\\\d)|[1-4]\\\\d|50|51|52|53\",\n W: \"0\\\\d|\\\\d(?!\\\\d)|[1-4]\\\\d|50|51|52|53\",\n w: \"[0-6]\",\n y: \"\\\\d\\\\d\",\n Y: \"\\\\d\\\\d\\\\d\\\\d\",\n t: \" \",\n z: \"Z|(?:[\\\\+\\\\-]\\\\d\\\\d:?(?:\\\\d\\\\d)?)\"\n};\nvar ESCAPED = /[\\\\!@#$^&*()+=\\-[\\]/{}|:<>?,.]/g;\nvar MONTHS = [\"JAN\", \"FEB\", \"MAR\", \"APR\", \"MAY\", \"JUN\", \"JUL\", \"AUG\", \"SEP\", \"OCT\", \"NOV\", \"DEC\"];\nvar DAYS = [\"SUN\", \"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\"];\nfunction parsePattern(format) {\n const fields = [];\n const source = format.replace(ESCAPED, \"\\\\$&\").replace(/%(.)/g, (whole, c) => ALIASES[c] || whole).replace(/%(.)/g, (_, c) => {\n const field2 = FIELDS[c];\n if (!field2) return c;\n fields.push(c);\n return `(${field2})`;\n }).replace(/\\s+/g, \"\\\\s*\");\n return { pattern: new RegExp(`^${source}`, \"i\"), fields };\n}\nfunction within2(value2, min, max) {\n return Number.isNaN(value2) || value2 < min ? min : Math.min(value2, max);\n}\nfunction weekDate(year, week, day, first) {\n const lead = new Date(year, 0, 1).getDay();\n const before = lead === first ? 0 : 7 - lead + first;\n return new Date(year, 0, 1 + Math.max(0, before + day + 7 * (week - 1)));\n}\nfunction offsetOf2(zone) {\n if (zone.toLowerCase() === \"z\") return 0;\n const [, hours, minutes] = /^([-+]\\d\\d):?(\\d\\d)?/.exec(zone);\n const base = Number(hours) * 3600;\n return minutes ? base + (base > 0 ? 60 : -60) * Number(minutes) : base;\n}\nfunction yearOf(num, fallback) {\n const short = num(\"y\");\n if (num(\"Y\") !== void 0 || short === void 0) return num(\"Y\") ?? fallback;\n const century = num(\"C\");\n return short + (century !== void 0 ? century * 100 : short < 69 ? 2e3 : 1900);\n}\nfunction monthOf(num, name2, fallback) {\n const month = num(\"m\");\n if (month !== void 0) return month - 1;\n return name2 ? Math.max(0, MONTHS.indexOf(name2.slice(0, 3).toUpperCase())) : fallback;\n}\nfunction weekDay(num, name2, year) {\n const at = DAYS.indexOf(name2.slice(0, 3).toUpperCase());\n const sunday = num(\"U\");\n if (sunday !== void 0) return weekDate(year, sunday, at, 0);\n const monday = num(\"W\");\n return monday === void 0 ? void 0 : weekDate(year, monday, (at + 6) % 7, 1);\n}\nfunction dayOf(num, name2, at) {\n const day = num(\"d\");\n if (day !== void 0) return { month: at.month, day };\n const ofYear = num(\"j\");\n if (ofYear !== void 0) {\n const fits = ofYear <= (leap(at.year) ? 366 : 365);\n const december = (leap(at.year) ? LEAP : REGULAR)[11];\n return { month: at.month, day: fits ? ofYear - december : at.day };\n }\n const date = name2 ? weekDay(num, name2, at.year) : void 0;\n return date ? { month: date.getMonth(), day: date.getDate() } : at;\n}\nfunction hourOf(num, half, fallback) {\n const hour = num(\"I\");\n if (num(\"H\") !== void 0 || hour === void 0) return num(\"H\") ?? fallback;\n return hour + (half.toUpperCase().startsWith(\"P\") ? 12 : 0);\n}\nfunction strptime(ctx, buf, format, tm) {\n const { mem } = ctx;\n const i32 = (at) => mem.view().getInt32(at, true);\n const put = (at, value2) => mem.view().setInt32(at, value2, true);\n const { pattern, fields } = parsePattern(mem.cString(format));\n const found = pattern.exec(mem.cString(buf));\n if (!found) return 0;\n const got = (field2) => fields.includes(field2) && found[fields.indexOf(field2) + 1] || \"\";\n const num = (field2) => got(field2) ? Number(got(field2)) : void 0;\n const year = yearOf(num, within2(i32(tm + 20) + 1900, 1970, 9999));\n const month = monthOf(num, got(\"b\"), within2(i32(tm + 16), 0, 11));\n const on = dayOf(num, got(\"a\"), { year, month, day: within2(i32(tm + 12), 1, 31) });\n const hour = hourOf(num, got(\"p\"), within2(i32(tm + 8), 0, 23));\n const minute = num(\"M\") ?? within2(i32(tm + 4), 0, 59);\n const second = num(\"S\") ?? within2(i32(tm), 0, 59);\n const date = new Date(year, on.month, on.day, hour, minute, second, 0);\n put(tm, date.getSeconds());\n put(tm + 4, date.getMinutes());\n put(tm + 8, date.getHours());\n put(tm + 12, date.getDate());\n put(tm + 16, date.getMonth());\n put(tm + 20, date.getFullYear() - 1900);\n put(tm + 24, date.getDay());\n put(tm + 28, yday(date));\n put(tm + 32, 0);\n put(tm + 36, got(\"z\") ? offsetOf2(got(\"z\")) : 0);\n return buf + new TextEncoder().encode(found[0]).length;\n}\nfunction timeImports(ctx) {\n const { mem } = ctx;\n const i32 = (at) => mem.view().getInt32(at, true);\n const put = (at, value2) => mem.view().setInt32(at, value2, true);\n return {\n emscripten_date_now: () => {\n lookedOutside();\n return Date.now();\n },\n emscripten_get_now: () => {\n lookedOutside();\n return performance.now();\n },\n _tzset_js: (timezone, daylight, std, dst) => {\n const year = (/* @__PURE__ */ new Date()).getFullYear();\n const winter = new Date(year, 0, 1).getTimezoneOffset();\n const summer = new Date(year, 6, 1).getTimezoneOffset();\n mem.view().setUint32(timezone, Math.max(winter, summer) * 60, true);\n put(daylight, Number(winter !== summer));\n const winterName = zoneName(winter);\n const summerName = zoneName(summer);\n if (summer < winter) {\n putString(mem, std, winterName, 17);\n putString(mem, dst, summerName, 17);\n } else {\n putString(mem, dst, winterName, 17);\n putString(mem, std, summerName, 17);\n }\n },\n _localtime_js: (time, tm) => {\n const date = new Date(i53(time) * 1e3);\n put(tm, date.getSeconds());\n put(tm + 4, date.getMinutes());\n put(tm + 8, date.getHours());\n put(tm + 12, date.getDate());\n put(tm + 16, date.getMonth());\n put(tm + 20, date.getFullYear() - 1900);\n put(tm + 24, date.getDay());\n put(tm + 28, yday(date) | 0);\n put(tm + 36, -(date.getTimezoneOffset() * 60));\n const summer = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n const winter = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();\n const isDst = summer !== winter && date.getTimezoneOffset() === Math.min(winter, summer) ? 1 : 0;\n put(tm + 32, isDst);\n },\n _gmtime_js: (time, tm) => {\n const date = new Date(i53(time) * 1e3);\n put(tm, date.getUTCSeconds());\n put(tm + 4, date.getUTCMinutes());\n put(tm + 8, date.getUTCHours());\n put(tm + 12, date.getUTCDate());\n put(tm + 16, date.getUTCMonth());\n put(tm + 20, date.getUTCFullYear() - 1900);\n put(tm + 24, date.getUTCDay());\n const start2 = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);\n put(tm + 28, (date.getTime() - start2) / 864e5 | 0);\n },\n _mktime_js: (tm) => {\n const date = new Date(\n i32(tm + 20) + 1900,\n i32(tm + 16),\n i32(tm + 12),\n i32(tm + 8),\n i32(tm + 4),\n i32(tm),\n 0\n );\n const dst = i32(tm + 32);\n const guessed = date.getTimezoneOffset();\n const start2 = new Date(date.getFullYear(), 0, 1);\n const summer = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n const winter = start2.getTimezoneOffset();\n const dstOffset = Math.min(winter, summer);\n if (dst < 0) {\n put(tm + 32, Number(summer !== winter && dstOffset === guessed));\n } else if (dst > 0 !== (dstOffset === guessed)) {\n const nonDst = Math.max(winter, summer);\n const trueOffset = dst > 0 ? dstOffset : nonDst;\n date.setTime(date.getTime() + (trueOffset - guessed) * 6e4);\n }\n put(tm + 24, date.getDay());\n put(tm + 28, yday(date) | 0);\n put(tm, date.getSeconds());\n put(tm + 4, date.getMinutes());\n put(tm + 8, date.getHours());\n put(tm + 12, date.getDate());\n put(tm + 16, date.getMonth());\n put(tm + 20, date.getFullYear() - 1900);\n const ms = date.getTime();\n return BigInt(Number.isNaN(ms) ? -1 : Math.trunc(ms / 1e3));\n },\n _timegm_js: (tm) => {\n const time = Date.UTC(\n i32(tm + 20) + 1900,\n i32(tm + 16),\n i32(tm + 12),\n i32(tm + 8),\n i32(tm + 4),\n i32(tm),\n 0\n );\n const date = new Date(time);\n put(tm + 24, date.getUTCDay());\n const start2 = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);\n put(tm + 28, (date.getTime() - start2) / 864e5 | 0);\n return BigInt(Math.trunc(date.getTime() / 1e3));\n },\n strptime: (buf, format, tm) => strptime(ctx, buf, format, tm),\n slicc_tz_intl: (name2, t, abbr, abbrlen) => {\n try {\n const { value: value2, label } = tzIntl(mem.cString(name2), t);\n if (abbr) putString(mem, abbr, label, abbrlen);\n return value2;\n } catch {\n return 2147483647;\n }\n }\n };\n}\n\n// src/process/emscripten/runtime.ts\nvar NOT_RUNNABLE = 126;\nvar HEAP_MAX = 2147483648;\nfunction procTree2(call2, pid) {\n return new ProcTree(\n {\n procList: async () => await call2({ op: \"proc-list\" }),\n mountList: async () => await call2({ op: \"mount-list\" })\n },\n pid\n );\n}\nfunction ownersOf2(init) {\n return {\n ...init.owners ? { owners: true } : {},\n ...init.links ? { links: true } : {},\n ...init.changes ? { changes: init.changes } : {}\n };\n}\nvar O_NONBLOCK4 = 2048;\nvar O_APPEND4 = 1024;\nasync function stdioEntries(init, call2) {\n const fds = [];\n const cloexec = [];\n for (let fd = 0; fd < 3; fd++) {\n let info;\n try {\n info = await call2({ op: \"fd-info\", fd });\n } catch {\n info = void 0;\n }\n const dir = info?.meta?.dir;\n if (dir !== void 0) fds.push({ fd, type: \"dir\", path: dir });\n else fds.push({ fd, type: \"kernel\", nonblock: false, append: false });\n }\n for (const entry of init.fds ?? []) {\n if (entry.fd <= 2) continue;\n if (entry.device) {\n const access3 = entry.device.access ? { access: entry.device.access } : {};\n fds.push({ fd: entry.fd, type: \"device\", device: entry.device.device, ...access3 });\n } else {\n const flags = entry.flags ?? 0;\n fds.push({\n fd: entry.fd,\n type: \"kernel\",\n nonblock: (flags & O_NONBLOCK4) !== 0,\n append: (flags & O_APPEND4) !== 0\n });\n }\n if (entry.cloexec) cloexec.push(entry.fd);\n }\n return { fds, cloexec };\n}\nvar PROVIDED_ELSEWHERE = /* @__PURE__ */ new Set([\"memory\"]);\nfunction missingImports(module, imports) {\n const missing3 = [];\n for (const imp of WebAssembly.Module.imports(module)) {\n const ns = imports[imp.module];\n if (imp.kind === \"function\" && typeof ns?.[imp.name] === \"function\") continue;\n if (imp.kind !== \"function\" && PROVIDED_ELSEWHERE.has(imp.kind) && ns?.[imp.name]) continue;\n missing3.push(`${imp.module}.${imp.name}`);\n }\n return missing3;\n}\nfunction importsCred(module) {\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module === \"env\" && imp.name === \"slicc_cred_js\") return true;\n }\n return false;\n}\nvar EmRuntime = class {\n reentry = new Reentry();\n ex;\n up = false;\n exiting = false;\n seeded = { bits: 0 };\n fork;\n ctx;\n exports() {\n if (!this.ex) throw new Error(\"emscripten: no instance yet\");\n return this.ex;\n }\n bind(exports, imported) {\n const own = exports;\n this.ex = imported && !own.memory ? { ...own, memory: imported } : own;\n this.reentry.bind(exports);\n }\n async enter(name2, fn, args) {\n return await this.reentry.enter(name2, fn, args);\n }\n masks() {\n const mask = this.ex?.slicc_sig_mask;\n const sliccSigMask = (w) => this.up && mask ? mask(w) : -1;\n return signalMasks({ sliccSigMask }, this.seeded);\n }\n async raise(sig) {\n const fn = this.ex?.slicc_raise;\n if (this.up && typeof fn === \"function\") await this.enter(\"slicc_raise\", fn, [sig]);\n }\n async timer(which) {\n const fn = this.ex?._emscripten_timeout;\n if (!this.up || typeof fn !== \"function\") {\n await this.raise(SIG.ALRM);\n return;\n }\n await this.enter(\"_emscripten_timeout\", fn, [which, performance.now()]);\n }\n async exit(status2) {\n if (!this.exiting) {\n this.exiting = true;\n const atexit = this.ex?.__funcs_on_exit;\n const quit = this.ctx?.quit;\n if (quit) quit.atExit = true;\n if (typeof atexit === \"function\") await this.enter(\"__funcs_on_exit\", atexit, []);\n const flush = this.ex?.fflush;\n if (typeof flush === \"function\") await this.enter(\"fflush\", flush, [0]);\n if (this.ctx) await commitStdout(this.ctx);\n if (quit) quit.atExit = false;\n this.up = false;\n }\n throw new WasiExit(this.ctx?.quit.failed && status2 === 0 ? 1 : status2);\n }\n};\nasync function abort(ctx, what) {\n await ctx.say(`Aborted(${what})`);\n throw new WebAssembly.RuntimeError(`Aborted(${what}). Build with -sASSERTIONS for more info.`);\n}\nfunction resizeHeap(ctx, requested) {\n const memory = ctx.exports().memory;\n const old = memory.buffer.byteLength;\n const size = requested >>> 0;\n if (size > HEAP_MAX) return 0;\n for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {\n let over = old * (1 + 0.2 / cutDown);\n over = Math.min(over, size + 100663296);\n const next2 = Math.min(HEAP_MAX, Math.ceil(Math.max(size, over) / 65536) * 65536);\n const pages2 = (next2 - memory.buffer.byteLength + 65535) / 65536 | 0;\n try {\n memory.grow(pages2);\n publishMemory(ctx.init.sab, memory.buffer.byteLength);\n return 1;\n } catch {\n }\n }\n return 0;\n}\nfunction runtimeImports(ctx, rt) {\n const { mem } = ctx;\n const sighandler = invoke(ctx, \"vi\");\n return {\n exit: async (status2) => await rt.exit(status2),\n _abort_js: async () => await abort(ctx, \"\"),\n __assert_fail: async (cond, file, line, func) => await abort(\n ctx,\n `Assertion failed: ${mem.cString(cond)}, at: ${[\n file ? mem.cString(file) : \"unknown filename\",\n line,\n func ? mem.cString(func) : \"unknown function\"\n ].join(\",\")}`\n ),\n emscripten_resize_heap: (size) => resizeHeap(ctx, size),\n emscripten_get_heap_max: () => HEAP_MAX,\n _emscripten_runtime_keepalive_clear: () => {\n },\n _emscripten_get_progname: (str, len) => putString(mem, str, ctx.init.argv0 || \"./this.program\", len),\n _emscripten_throw_longjmp: () => {\n throw Number.POSITIVE_INFINITY;\n },\n __call_sighandler: async (fp, sig) => {\n const ex = ctx.exports();\n if (typeof ex.dynCall_vi === \"function\") return await sighandler(fp, sig);\n const fn = ex.__indirect_function_table?.get(fp);\n if (typeof fn !== \"function\") throw new WebAssembly.RuntimeError(\"null function\");\n await ctx.enter(`table:${fp}`, fn, [sig]);\n },\n _setitimer_js: async (which, ms) => {\n if (which !== 0) return 0;\n await ctx.call({ op: \"proc-alarm\", sig: SIG.ALRM, ms: ms ?? 0, repeat: false, timer: 0 });\n return 0;\n },\n slicc_webcrypto_random: (out, len) => {\n for (let at = 0; at < len; at += 65536) {\n crypto.getRandomValues(\n mem.bytes(out + at, Math.min(65536, len - at))\n );\n }\n return 0;\n },\n slicc_fork_js: () => {\n if (!rt.fork) return -1;\n if (!rt.fork.supported()) return rt.fork.failed(-EM.NOSYS);\n return rt.fork.forkImport();\n }\n };\n}\nfunction buildImports(ctx, rt, module) {\n const state = { listings: /* @__PURE__ */ new WeakMap() };\n const env = {\n ...fileImports(ctx, state),\n ...fdImports(ctx),\n ...procImports(ctx, { seeded: rt.seeded, raise: async (sig) => await rt.raise(sig) }),\n ...timeImports(ctx),\n ...netImports(ctx),\n ...mmapImport(ctx),\n ...dnsImports(ctx),\n ...pthreadImports(ctx),\n ...runtimeImports(ctx, rt),\n ...invokeImports(ctx, module)\n };\n const preview1 = wasiImports(ctx, state);\n if (ctx.init.env.SLICC_EMSCRIPTEN_TRACE === \"1\") {\n for (const table of [env, preview1]) {\n for (const [name2, fn] of Object.entries(table)) {\n if (typeof fn !== \"function\" || name2.startsWith(\"invoke_\")) continue;\n table[name2] = async (...args) => {\n const r = await fn(...args);\n await ctx.say(`[em] ${name2}(${args.map(String).join(\",\")}) = ${String(r)}`);\n return r;\n };\n }\n }\n }\n return {\n env,\n wasi_snapshot_preview1: preview1\n };\n}\nfunction argvOnStack(ctx, args) {\n const ex = ctx.exports();\n const alloc = ex._emscripten_stack_alloc;\n const argv = alloc((args.length + 1) * 4);\n const encoder6 = new TextEncoder();\n for (let i = 0; i < args.length; i++) {\n const bytes = encoder6.encode(args[i]);\n const at = alloc(bytes.length + 1);\n ctx.mem.bytes(at, bytes.length + 1).set(bytes);\n ctx.mem.bytes(at + bytes.length, 1)[0] = 0;\n ctx.mem.view().setUint32(argv + i * 4, at, true);\n }\n ctx.mem.view().setUint32(argv + args.length * 4, 0, true);\n return argv;\n}\nasync function runMain(ctx, rt) {\n const ex = ctx.exports();\n const args = [ctx.init.argv0, ...ctx.init.args];\n const name2 = typeof ex.main === \"function\" ? \"main\" : \"__main_argc_argv\";\n const main = ex[name2];\n if (typeof main !== \"function\") throw new Error(`${ctx.init.argv0}: exports no main`);\n const argv = argvOnStack(ctx, args);\n const ret = await ctx.enter(name2, main, [args.length, argv]);\n const settled = rt.fork ? await rt.fork.settle(ret) : ret;\n return await rt.exit(Number(settled ?? 0));\n}\nvar sabTransport2 = (sab, port, memory) => createSyncSabTransport(sab, port, memory ? { memory } : {});\nasync function runEmscriptenProcess(init, port, given = {}) {\n const rt = new EmRuntime();\n let memory;\n const transports = given.transport ?? sabTransport2;\n const gate = new SignalGate(\n transports(init.sab, port, () => memory?.buffer.byteLength ?? 0),\n new Int32Array(init.sab, 0, SAB_HEADER_I32),\n {\n masks: () => rt.masks(),\n raise: async (sig) => await rt.raise(sig),\n timer: async (which) => await rt.timer(which)\n }\n );\n const transport = gate.transport();\n const sys = kernelSys(transport);\n const call2 = async (req) => {\n const r = await transport.call(req, Number.POSITIVE_INFINITY, req.op);\n if (!r.ok) throw new SyscallError(r.errno);\n return r.kind === \"json\" ? r.json : r.kind === \"bytes\" ? r.bytes : void 0;\n };\n const encoder6 = new TextEncoder();\n const say = async (text) => void await sys.write(2, encoder6.encode(`${text}\n`));\n const id = await identify(transport, init);\n const fork = init.fork?.wasi;\n const raw = createSyncFsSabBridge(transport, { ...ownersOf2(init), direct: true });\n const host = await new WasiHost({\n args: [init.argv0, ...init.args],\n env: init.env,\n cwd: fork?.cwd ?? init.cwd,\n pid: id.pid,\n ppid: id.ppid,\n parent: async () => (await identify(transport, init)).ppid,\n kernel: { sys, call: call2 },\n fs: ptsBridge(\n sysfsBridge(\n procfsBridge(cachingBridge(raw), procTree2(call2, id.pid)),\n async () => await call2({ op: \"fd-dev-nodes\" })\n ),\n call2\n ),\n bare: true\n }).attach();\n if (fork) host.fds.restore(fork.fds, fork.cloexec);\n else {\n const { fds, cloexec } = await stdioEntries(init, call2);\n host.fds.restore(fds, cloexec);\n }\n wireSignals(host, gate);\n const cwd = new EmCwd(host, fork?.cwd ?? init.cwd, call2, init.held);\n const ctx = {\n init,\n host,\n mem: host.mem,\n sys,\n transport,\n gate,\n cwd,\n reentry: rt.reentry,\n pid: init.pid,\n ppid: id.ppid,\n credAbi: importsCred(init.program.module),\n statfs: async (path) => await raw.statfs?.(path) ?? null,\n quit: { atExit: false, failed: false },\n call: call2,\n exports: () => rt.exports(),\n enter: async (name2, fn, args) => await rt.enter(name2, fn, args),\n exit: async (status2) => await rt.exit(status2),\n say\n };\n rt.ctx = ctx;\n const { module } = init.program;\n const imports = buildImports(ctx, rt, module);\n const spec = init.program.memory;\n const imported = createImportedMemory(spec);\n if (spec && imported) (imports[spec.module] ??= {})[spec.name] = imported;\n const missing3 = missingImports(module, imports);\n if (missing3.length > 0) {\n await say(\n `${init.argv0}: cannot start: the kernel's Emscripten runtime does not provide ${missing3.join(\", \")}`\n );\n return NOT_RUNNABLE;\n }\n const instance = await WebAssembly.instantiate(module, suspendingImports(imports));\n rt.bind(instance.exports, imported);\n memory = rt.exports().memory;\n host.mem.bind(memory);\n publishMemory(init.sab, memory.buffer.byteLength);\n port.postMessage({ type: WASM_PROCESS_READY });\n rt.fork = new EmFork(ctx);\n try {\n rt.up = true;\n const ctors = instance.exports.__wasm_call_ctors;\n if (typeof ctors === \"function\") await rt.enter(\"__wasm_call_ctors\", ctors, []);\n if (init.fork) {\n if (!rt.fork.supported()) throw new EmError(EM.NOSYS);\n const ret = await rt.fork.child(init.fork);\n return await rt.exit(Number(ret ?? 0));\n }\n return await runMain(ctx, rt);\n } catch (e) {\n if (e instanceof WasiExit) return e.code;\n throw e;\n } finally {\n rt.up = false;\n try {\n await host.flushAll();\n } catch {\n }\n }\n}\n\n// src/async/futexes.ts\nvar FUTEX_WAIT = \"futex-wait\";\nfunction later(fn) {\n const immediate = globalThis.setImmediate;\n if (immediate) immediate(fn);\n else setTimeout(fn, 0);\n}\nvar FutexHub = class {\n sleepers = /* @__PURE__ */ new Map();\n threads = 1;\n sleep(index3) {\n let set = this.sleepers.get(index3);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this.sleepers.set(index3, set);\n }\n const own = set;\n let wake = () => {\n };\n const woken = new Promise((resolve) => {\n wake = resolve;\n });\n own.add(wake);\n const cancel = () => {\n own.delete(wake);\n if (own.size === 0 && this.sleepers.get(index3) === own) this.sleepers.delete(index3);\n };\n return { woken, cancel };\n }\n wake(index3, count = Number.POSITIVE_INFINITY) {\n const set = this.sleepers.get(index3);\n if (!set) return 0;\n let woken = 0;\n for (const wake of [...set]) {\n if (woken >= count) break;\n set.delete(wake);\n wake();\n woken++;\n }\n if (set.size === 0) this.sleepers.delete(index3);\n return woken;\n }\n};\nfunction asyncFutexes(hub, transport) {\n const timed = async (ms, woken) => {\n const timeoutMs2 = Math.max(1, Math.ceil(ms));\n const waited = transport.call(\n { op: \"fd-select\", read: [], write: [], timeoutMs: timeoutMs2 },\n Number.POSITIVE_INFINITY,\n FUTEX_WAIT\n );\n const first = await Promise.race([woken.then(() => void 0), waited]);\n if (first !== void 0) return !first.ok;\n transport.cancel();\n waited.catch(() => void 0);\n return true;\n };\n const futexes = {\n async wait(view, index3, expected, ms) {\n if (Atomics.load(view, index3) !== expected) return true;\n if (!(ms > 0)) return false;\n const sleep = hub.sleep(index3);\n try {\n if (Number.isFinite(ms)) {\n return await timed(ms, sleep.woken) || Atomics.load(view, index3) !== expected;\n }\n const watch = transport.watch();\n try {\n await Promise.race([sleep.woken, watch.changed]);\n } finally {\n watch.forget();\n }\n return true;\n } finally {\n sleep.cancel();\n }\n },\n notify: (view, index3, count) => hub.wake(index3, count) + atomicsNotify(view, index3, count),\n async pause() {\n if (hub.threads > 1) await new Promise((resolve) => later(resolve));\n }\n };\n return futexes;\n}\n\n// src/async/wire.ts\nvar ASYNC_SYSCALL = \"async-syscall\";\nvar ASYNC_MORE = \"async-more\";\nvar ASYNC_STAGE = \"async-stage\";\nvar ASYNC_WORDS = \"async-words\";\nvar ASYNC_MIRROR = \"async-mirror\";\nvar ASYNC_SNAPSHOT = \"async-snapshot\";\nvar ASYNC_SNAPSHOT_TAKEN = \"async-snapshot-taken\";\nvar ASYNC_CANCEL = \"async-cancel\";\nvar ASYNC_THREAD = \"async-thread\";\nfunction isThreadMsg(message) {\n const data = message;\n return data?.type === ASYNC_THREAD && typeof data.channel === \"number\";\n}\nfunction applyRuns(view, runs) {\n if (!runs) return;\n let at = 0;\n while (at + 1 < runs.length) {\n const start2 = runs[at];\n const count = runs[at + 1];\n at += 2;\n for (let k = 0; k < count && start2 + k < view.length; k++) {\n Atomics.store(view, start2 + k, runs[at + k]);\n }\n at += count;\n }\n}\n\n// src/async/transport.ts\nfunction snapshotted(asked, snapshots) {\n const fork = asked;\n const memory = fork.state?.memory;\n if (!snapshots || fork.op !== \"proc-fork\" || !(memory instanceof Uint8Array)) {\n return { req: asked };\n }\n if (memory.byteLength === 0) return { req: asked };\n const owned = memory.buffer instanceof ArrayBuffer ? memory : memory.slice();\n const snapshot = snapshots.keep(owned);\n const state = { ...fork.state, memory: new Uint8Array(0), snapshot };\n const req = { ...asked, state };\n return { req, token: snapshot.token };\n}\nvar CLOCK_BLOCKED = 0;\nvar CLOCK_IDLE = 1;\nfunction isAnswer(reply) {\n return typeof reply.status === \"number\";\n}\nfunction bodyOf(req) {\n const body = req.body;\n return body instanceof Uint8Array ? body : void 0;\n}\nfunction exactCopy(body) {\n const whole = body.byteOffset === 0 && body.byteLength === body.buffer.byteLength;\n if (whole && body.buffer instanceof ArrayBuffer) return { body, transfer: [] };\n const copy = body.slice();\n return { body: copy, transfer: [copy.buffer] };\n}\nfunction landing2(status2, total, sink) {\n if (!sink || status2 !== SAB_STATUS_BYTES || total > sink.length) return new Uint8Array(total);\n return new Uint8Array(sink.buffer, sink.byteOffset, total);\n}\nfunction mirrored(spec) {\n if (!spec) return void 0;\n const buffer = new ArrayBuffer(spec.bytes);\n applyRuns(new Int32Array(buffer), spec.runs);\n return buffer;\n}\nfunction withTimeout(work, ms, label) {\n if (!Number.isFinite(ms)) return work;\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(syncError(\"EIO\", label)), Math.max(0, ms));\n work.then(\n (value2) => {\n clearTimeout(timer);\n resolve(value2);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n }\n );\n });\n}\nvar Mirrors = class {\n buffer = new ArrayBuffer(SAB_HEADER_BYTES);\n header = new Int32Array(this.buffer, 0, SAB_HEADER_I32);\n clock = new BigInt64Array(this.buffer, SAB_CLOCK_OFFSET, SAB_CLOCK_I64);\n changes;\n cwds;\n changesView;\n cwdsView;\n applied = 0;\n early = /* @__PURE__ */ new Map();\n settled = /* @__PURE__ */ new Map();\n waiters = /* @__PURE__ */ new Set();\n watchers = /* @__PURE__ */ new Set();\n start(mirror) {\n this.header.set(mirror.header.subarray(0, SAB_HEADER_I32));\n Atomics.store(this.clock, CLOCK_BLOCKED, BigInt(mirror.clock[0]));\n Atomics.store(this.clock, CLOCK_IDLE, BigInt(mirror.clock[1]));\n this.changes = mirrored(mirror.changes);\n this.cwds = mirrored(mirror.cwds);\n this.changesView = this.changes ? new Int32Array(this.changes) : void 0;\n this.cwdsView = this.cwds ? new Int32Array(this.cwds) : void 0;\n }\n apply(m) {\n const { header } = this;\n if (m.signals) Atomics.or(header, SAB_I_SIGNALS, m.signals);\n if (m.timers) Atomics.or(header, SAB_I_TIMERS, m.timers);\n Atomics.store(header, SAB_I_KILLED, m.killed);\n Atomics.store(header, SAB_I_ASYNC, m.async);\n Atomics.store(header, SAB_I_STOP, m.stop);\n Atomics.store(this.clock, CLOCK_BLOCKED, BigInt(m.clock));\n if (this.changesView) applyRuns(this.changesView, m.changes);\n if (this.cwdsView) applyRuns(this.cwdsView, m.cwds);\n this.applied = m.seq;\n }\n accept(m) {\n if (m.seq <= this.applied) return Promise.resolve();\n this.early.set(m.seq, m);\n const done = new Promise((resolve) => {\n const list = this.settled.get(m.seq) ?? [];\n list.push(resolve);\n this.settled.set(m.seq, list);\n });\n let progressed = false;\n for (let next2 = this.early.get(this.applied + 1); next2; next2 = this.early.get(this.applied + 1)) {\n this.early.delete(next2.seq);\n this.apply(next2);\n progressed = true;\n for (const resolve of this.settled.get(next2.seq) ?? []) resolve();\n this.settled.delete(next2.seq);\n }\n if (progressed) this.wake();\n return done;\n }\n watch() {\n let watcher;\n const changed2 = new Promise((resolve, reject) => {\n watcher = { view: this.header, index: 0, value: 0, settle: () => resolve(), fail: reject };\n this.watchers.add(watcher);\n });\n return { changed: changed2, forget: () => void (watcher && this.watchers.delete(watcher)) };\n }\n wake() {\n for (const watcher of [...this.watchers]) watcher.settle(\"ok\");\n this.watchers.clear();\n for (const waiter of [...this.waiters]) {\n if (Atomics.load(waiter.view, waiter.index) === waiter.value) continue;\n this.waiters.delete(waiter);\n waiter.settle(\"ok\");\n }\n }\n notify(view, index3) {\n for (const waiter of [...this.waiters]) {\n if (waiter.view !== view || waiter.index !== index3) continue;\n this.waiters.delete(waiter);\n waiter.settle(\"ok\");\n }\n }\n failAll(err) {\n for (const watcher of [...this.watchers]) watcher.fail(err);\n this.watchers.clear();\n for (const waiter of [...this.waiters]) {\n this.waiters.delete(waiter);\n waiter.fail(err);\n }\n }\n words(n, memory) {\n const { header } = this;\n if (memory !== void 0 && memory > 0) {\n Atomics.store(header, SAB_I_MEMORY, Math.ceil(memory / 65536));\n }\n return {\n n,\n seen: this.applied,\n signals: Atomics.load(header, SAB_I_SIGNALS),\n timers: Atomics.load(header, SAB_I_TIMERS),\n blocked: [Atomics.load(header, SAB_I_BLOCKED), Atomics.load(header, SAB_I_BLOCKED_HI)],\n memory: Atomics.load(header, SAB_I_MEMORY),\n idle: Number(Atomics.load(this.clock, CLOCK_IDLE))\n };\n }\n wait(view, index3, value2, timeoutMs2) {\n return new Promise((resolve, reject) => {\n let timer;\n const waiter = {\n view,\n index: index3,\n value: value2,\n settle: (result) => {\n clearTimeout(timer);\n resolve(result);\n },\n fail: (err) => {\n clearTimeout(timer);\n reject(err);\n }\n };\n this.waiters.add(waiter);\n if (!Number.isFinite(timeoutMs2)) return;\n timer = setTimeout(\n () => {\n this.waiters.delete(waiter);\n resolve(\"timed-out\");\n },\n Math.max(0, timeoutMs2)\n );\n });\n }\n};\nvar Caller = class {\n link;\n max;\n stages = 0;\n constructor(link, max) {\n this.link = link;\n this.max = max;\n }\n async pull(part, out, from, label) {\n for (let offset = from; offset < out.length; ) {\n const reply = await this.link.call({ type: ASYNC_MORE, part, offset });\n const bytes = reply?.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.length === 0) throw syncError(\"EIO\", label);\n if (offset + bytes.length > out.length) throw syncError(\"EIO\", label);\n out.set(bytes, offset);\n offset += bytes.length;\n }\n }\n async snapshot(token, out) {\n for (let offset = 0; offset < out.length; ) {\n const reply = await this.link.call({\n type: ASYNC_SNAPSHOT,\n token,\n offset\n });\n const bytes = reply?.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.length === 0)\n throw syncError(\"EIO\", \"fork memory\");\n if (offset + bytes.length > out.length) throw syncError(\"EIO\", \"fork memory\");\n out.set(bytes, offset);\n offset += bytes.length;\n }\n }\n async stage(body) {\n const id = ++this.stages;\n for (let offset = 0; offset < body.length; offset += this.max) {\n const bytes = body.slice(offset, Math.min(body.length, offset + this.max));\n await this.link.call({ type: ASYNC_STAGE, stage: id, offset, total: body.length, bytes }, [\n bytes.buffer\n ]);\n }\n return id;\n }\n staging(asked) {\n const body = bodyOf(asked);\n return body && body.byteLength > this.max ? body : void 0;\n }\n async staged(asked, body, timeoutMs2, label) {\n const staged = await withTimeout(this.stage(body), timeoutMs2, label).catch(() => {\n throw syncError(\"EIO\", label);\n });\n const { body: _dropped, ...rest2 } = asked;\n return { req: rest2, transfer: [], staged };\n }\n exact(asked, given) {\n const body = bodyOf(asked);\n if (!body) return { req: asked, transfer: given };\n const exact = exactCopy(body);\n if (exact.body === body) return { req: asked, transfer: given };\n return {\n req: { ...asked, body: exact.body },\n transfer: [...given, ...exact.transfer]\n };\n }\n async answer(reply, timeoutMs2, label, sink) {\n const { status: status2, total, bytes } = reply;\n if (reply.part === void 0) {\n if (!sink || status2 !== SAB_STATUS_BYTES || bytes.length > sink.length) {\n return decodeSabResult(status2, bytes);\n }\n const out2 = landing2(status2, bytes.length, sink);\n out2.set(bytes);\n return decodeSabResult(status2, out2);\n }\n const out = landing2(status2, total, sink);\n out.set(bytes);\n await withTimeout(this.pull(reply.part, out, bytes.length, label), timeoutMs2, label).catch(\n (err) => {\n throw err.code === \"EIO\" ? err : syncError(\"EIO\", label);\n }\n );\n return decodeSabResult(status2, out);\n }\n};\nfunction createAsyncTransport(link, options = {}) {\n const mirrors = new Mirrors();\n const caller = new Caller(link, options.maxMessageBytes ?? Number.POSITIVE_INFINITY);\n const started2 = Promise.withResolvers();\n let words = 0;\n let lastCall = 0;\n let initialised = false;\n let closedBy;\n const current2 = () => mirrors.words(++words, options.memory?.());\n const begin = async (init) => {\n mirrors.start(init.mirror);\n if (options.maxMessageBytes === void 0 && init.maxMessageBytes !== void 0) {\n caller.max = init.maxMessageBytes;\n }\n if (init.type === WASM_THREAD_INIT) {\n started2.resolve(init);\n return;\n }\n const fork = init.fork;\n const ref = fork?.snapshot;\n if (fork && ref) {\n delete fork.snapshot;\n const local2 = options.snapshots?.take(ref.token);\n if (local2 && local2.byteLength === ref.total) {\n fork.memory = local2;\n link.post({ type: ASYNC_SNAPSHOT_TAKEN, token: ref.token });\n } else {\n const whole = new Uint8Array(ref.total);\n await caller.snapshot(ref.token, whole);\n fork.memory = whole;\n }\n }\n const memory = init.fork?.memory;\n if (memory && !(memory instanceof Uint8Array) && init.fork) {\n const whole = new Uint8Array(memory.total);\n await caller.pull(memory.part, whole, 0, \"fork memory\");\n init.fork.memory = whole;\n }\n started2.resolve(init);\n };\n link.onMessage((message) => {\n const data = message;\n if (!initialised && (data?.type === WASM_PROCESS_INIT || data?.type === WASM_THREAD_INIT)) {\n initialised = true;\n begin(data).catch((err) => started2.reject(err));\n } else if (initialised && data?.type === ASYNC_MIRROR && data.mirror) {\n void mirrors.accept(data.mirror);\n }\n });\n link.onClose((reason) => {\n closedBy = reason;\n if (!initialised) started2.reject(new Error(`the kernel link closed: ${reason}`));\n mirrors.failAll(syncError(\"EIO\", `kernel link closed: ${reason}`));\n });\n const send = (msg, transfer, ms, label) => {\n const answered = link.call(msg, transfer).then(async (value2) => {\n const reply = value2;\n if (!reply || !isAnswer(reply)) throw syncError(\"EIO\", label);\n await mirrors.accept(reply.mirror);\n return reply;\n });\n answered.catch(() => void 0);\n return withTimeout(answered, ms, label).catch((err) => {\n throw err.code === \"EIO\" ? err : syncError(\"EIO\", label);\n });\n };\n const issue = async (asked, given, ms, label) => {\n const words2 = current2();\n lastCall = words2.n;\n const body = caller.staging(asked);\n if (!body) {\n const { req: req2, transfer } = caller.exact(asked, given);\n return send({ type: ASYNC_SYSCALL, req: req2, words: words2 }, transfer, ms, label);\n }\n const { req, staged } = await caller.staged(asked, body, ms, label);\n return send({ type: ASYNC_SYSCALL, req, words: words2, staged }, [], ms, label);\n };\n return {\n init: started2.promise,\n buffer: mirrors.buffer,\n header: mirrors.header,\n clock: mirrors.clock,\n get changes() {\n return mirrors.changes;\n },\n get cwds() {\n return mirrors.cwds;\n },\n get closed() {\n return closedBy !== void 0;\n },\n async call(asked, askedMs, label, given = [], sink) {\n const timeoutMs2 = options.deadlines === false ? Number.POSITIVE_INFINITY : askedMs;\n if (closedBy !== void 0) throw syncError(\"EIO\", label);\n const { req, token } = snapshotted(asked, options.snapshots);\n const forget = () => {\n if (token !== void 0) options.snapshots?.release(token);\n };\n try {\n const reply = await issue(req, given, timeoutMs2, label);\n const result = await caller.answer(reply, timeoutMs2, label, sink);\n if (!result.ok) forget();\n return result;\n } catch (err) {\n forget();\n throw err;\n }\n },\n wait(view, index3, value2, timeoutMs2 = Number.POSITIVE_INFINITY) {\n if (Atomics.load(view, index3) !== value2) return Promise.resolve(\"not-equal\");\n if (closedBy !== void 0) {\n return Promise.reject(syncError(\"EIO\", `kernel link closed: ${closedBy}`));\n }\n return mirrors.wait(view, index3, value2, timeoutMs2);\n },\n notify: (view, index3) => mirrors.notify(view, index3),\n watch() {\n if (closedBy === void 0) return mirrors.watch();\n const changed2 = Promise.reject(syncError(\"EIO\", `kernel link closed: ${closedBy}`));\n return { changed: changed2, forget: () => {\n } };\n },\n cancel() {\n if (closedBy === void 0 && initialised && lastCall > 0) {\n link.post({ type: ASYNC_CANCEL, n: lastCall });\n }\n },\n publish() {\n if (closedBy === void 0 && initialised) {\n link.post({ type: ASYNC_WORDS, words: current2() });\n }\n },\n post(message, transfer) {\n if (closedBy === void 0) link.post(message, transfer);\n },\n onClose: (handler) => link.onClose(handler)\n };\n}\n\n// src/async/process-entry.ts\nvar NOT_RUNNABLE2 = 126;\nvar ASYNC_NO_JSPI = \"the async process host needs WebAssembly JSPI (Suspending, promising)\";\nvar ASYNC_NO_JS = \"the async process host runs no JavaScript programs\";\nvar ASYNC_NO_EMSCRIPTEN = \"the async process host runs Emscripten programs only on the kernel's personality (emscripten: 'kernel')\";\nvar ASYNC_NO_IMPORTS = \"the async process host loads no JavaScript imports modules\";\nvar ASYNC_LOST_THREAD = \"the async process host has no memory for this thread\";\nvar ASYNC_NO_CREATE = \"the imports module exports no createAsyncImports function, which the async process host calls\";\nfunction refusal(init, deps) {\n const program = init.program;\n if (program.abi === \"js\") return ASYNC_NO_JS;\n if (program.abi !== \"wasi\" && program.emscripten !== \"kernel\") return ASYNC_NO_EMSCRIPTEN;\n if (program.imports !== void 0 && !deps.imports) return ASYNC_NO_IMPORTS;\n if (!jspiAvailable()) return ASYNC_NO_JSPI;\n return void 0;\n}\nvar NotRunnable = class extends Error {\n};\nasync function importsOf(init, deps) {\n const source = init.program.imports;\n if (source === void 0 || !deps.imports) return void 0;\n const create = (await deps.imports(source)).createAsyncImports;\n if (typeof create !== \"function\") throw new NotRunnable(ASYNC_NO_CREATE);\n return create;\n}\nvar KernelGone = class extends Error {\n constructor() {\n super(\"the kernel link closed\");\n }\n};\nfunction guarded(transport) {\n const call2 = async (...args) => {\n if (transport.closed) throw new KernelGone();\n try {\n return await transport.call(...args);\n } catch (err) {\n if (transport.closed) throw new KernelGone();\n throw err;\n }\n };\n return { call: call2, publish: () => transport.publish() };\n}\nvar KERNEL_WAIT = \"kernel-wait\";\nfunction kernelWaiter(transport, kernel, mirrored2) {\n return async (view, index3, value2, timeout = Number.POSITIVE_INFINITY) => {\n if (Atomics.load(view, index3) !== value2) return \"not-equal\";\n if (timeout <= 0) return \"timed-out\";\n const forever = !Number.isFinite(timeout);\n if (forever && mirrored2) return transport.wait(view, index3, value2);\n const timeoutMs2 = forever ? -1 : Math.max(1, Math.ceil(timeout));\n await kernel.call({ op: \"fd-select\", read: [], write: [], timeoutMs: timeoutMs2 }, Infinity, KERNEL_WAIT);\n return forever || Atomics.load(view, index3) !== value2 ? \"ok\" : \"timed-out\";\n };\n}\nfunction waitsOn(waiter, buffer) {\n if (buffer) registerWaiter(buffer, waiter);\n}\nvar ProcessThreads = class {\n hub = new FutexHub();\n main;\n spawned = /* @__PURE__ */ new Map();\n outgoing(message) {\n const data = message;\n if (data?.type !== WASM_THREAD_SPAWN || !data.thread) return message;\n const { memory, ids, modules, ...shown } = data.thread;\n this.spawned.set(shown.tid, { memory, ids, ...modules ? { modules } : {} });\n registerWaiter(ids, localWaiter);\n return { ...data, thread: shown };\n }\n take(tid) {\n const local2 = this.spawned.get(tid);\n this.spawned.delete(tid);\n return local2;\n }\n};\nfunction channelEnd(root, channel, gone) {\n const posts = [];\n const early = [];\n const closes = [];\n let ended;\n const close = (reason) => {\n if (ended !== void 0) return;\n ended = reason;\n gone();\n for (const handler of closes.splice(0)) handler(reason);\n };\n const link = {\n post(message, transfer) {\n if (ended === void 0) root.post({ type: ASYNC_THREAD, channel, message }, transfer);\n },\n call(message, transfer) {\n if (ended !== void 0) return Promise.reject(new Error(`link closed: ${ended}`));\n return root.call({ type: ASYNC_THREAD, channel, message }, transfer);\n },\n onMessage(handler) {\n posts.push(handler);\n for (const message of early.splice(0)) handler(message);\n },\n onClose(handler) {\n const reason = ended;\n if (reason === void 0) closes.push(handler);\n else queueMicrotask(() => handler(reason));\n },\n close: () => close(\"the thread closed its link\")\n };\n return {\n link,\n deliver(message) {\n if (posts.length === 0) early.push(message);\n else for (const handler of posts) handler(message);\n },\n close\n };\n}\nfunction threadMux(root, opened) {\n const channels = /* @__PURE__ */ new Map();\n const posts = [];\n const early = [];\n root.onMessage((message) => {\n if (!isThreadMsg(message)) {\n if (posts.length === 0) early.push(message);\n else for (const handler of posts) handler(message);\n return;\n }\n const { channel } = message;\n let end = channels.get(channel);\n if (message.closed !== void 0) {\n end?.close(message.closed);\n return;\n }\n if (!end) {\n end = channelEnd(root, channel, () => channels.delete(channel));\n channels.set(channel, end);\n opened(end.link);\n }\n end.deliver(message.message);\n });\n root.onClose((reason) => {\n for (const end of [...channels.values()]) end.close(reason);\n });\n return {\n post: (message, transfer) => root.post(message, transfer),\n call: (message, transfer) => root.call(message, transfer),\n onMessage(handler) {\n posts.push(handler);\n for (const message of early.splice(0)) handler(message);\n },\n onClose: (handler) => root.onClose(handler),\n close: () => root.close()\n };\n}\nfunction localInit(init, transport, module) {\n const { mirror: _mirror, maxMessageBytes: _max, held, program, ...rest2 } = init;\n const { image: _image, ...known } = program;\n const cwds = transport.cwds;\n const changes = transport.changes;\n return {\n ...rest2,\n sab: transport.buffer,\n ...changes ? { changes } : {},\n ...held && cwds ? { held: { ...held, sab: cwds } } : {},\n program: { ...known, module }\n };\n}\nfunction threadInit(init, transport, module, local2, main) {\n const { thread, ...shown } = init;\n const process = localInit(shown, transport, module);\n return {\n ...process,\n type: WASM_THREAD_INIT,\n thread: { ...thread, ...local2 },\n signals: main.buffer\n };\n}\nfunction running(transport, threads) {\n const kernel = guarded(transport);\n const mirrored2 = kernelWaiter(transport, kernel, true);\n waitsOn(mirrored2, transport.buffer);\n waitsOn(mirrored2, transport.changes);\n waitsOn(mirrored2, transport.cwds);\n const port = {\n postMessage: (message, transfer) => transport.post(threads.outgoing(message), transfer)\n };\n return { transport, kernel, port };\n}\nasync function started(init, transport, deps, size, threads) {\n const create = await importsOf(init, deps);\n const module = await deps.module(init.program.image);\n const { kernel, port } = running(transport, threads);\n const local2 = localInit(init, transport, module);\n const transports = (_sab, _port, memory) => {\n size.memory = memory;\n return kernel;\n };\n if (local2.program.abi !== \"wasi\")\n return runEmscriptenProcess(local2, port, { transport: transports });\n return runWasiProcess(local2, port, {\n transport: transports,\n futexes: asyncFutexes(threads.hub, transport),\n ...create ? { imports: create } : {}\n });\n}\nasync function threadStarted(init, transport, deps, threads) {\n const local2 = threads.take(init.thread.tid);\n const main = threads.main;\n if (!local2 || !main) throw new Error(ASYNC_LOST_THREAD);\n const create = await importsOf(init, deps);\n const module = await deps.module(init.program.image);\n const { kernel, port } = running(transport, threads);\n threads.hub.threads++;\n try {\n await runWasiThread(threadInit(init, transport, module, local2, main), port, {\n transport: () => kernel,\n futexes: asyncFutexes(threads.hub, transport),\n ...create ? { imports: create } : {}\n });\n } finally {\n threads.hub.threads--;\n }\n}\nfunction failure(transport) {\n return (err, code2) => transport.post({\n type: WASM_PROCESS_ERROR,\n message: err instanceof Error ? rawStack(err) ?? err.message : String(err),\n ...code2 === void 0 ? {} : { code: code2 }\n });\n}\nfunction asyncProcessEntry(link, deps) {\n const size = { memory: void 0 };\n const threads = new ProcessThreads();\n const transportOf = (on) => createAsyncTransport(on, {\n ...deps.maxMessageBytes !== void 0 ? { maxMessageBytes: deps.maxMessageBytes } : {},\n ...deps.snapshots ? { snapshots: deps.snapshots } : {},\n ...deps.deadlines === false ? { deadlines: false } : {},\n memory: () => size.memory?.()\n });\n const thread = (on) => {\n const transport2 = transportOf(on);\n const failed3 = failure(transport2);\n transport2.init.then(\n (init) => {\n if (init.type !== WASM_THREAD_INIT) return failed3(ASYNC_LOST_THREAD);\n threadStarted(init, transport2, deps, threads).catch((err) => {\n if (!transport2.closed) failed3(err);\n });\n },\n () => void 0\n );\n };\n const transport = transportOf(threadMux(link, thread));\n threads.main = transport;\n const failed2 = failure(transport);\n transport.init.then(\n (init) => {\n const refused3 = refusal(init, deps);\n if (refused3) return failed2(refused3, NOT_RUNNABLE2);\n if (init.type === WASM_THREAD_INIT) return failed2(ASYNC_LOST_THREAD);\n started(init, transport, deps, size, threads).then(\n (code2) => transport.post({ type: WASM_PROCESS_EXIT, code: code2 }),\n (err) => {\n if (transport.closed) return;\n if (err instanceof NotRunnable) failed2(err.message, NOT_RUNNABLE2);\n else failed2(err);\n }\n );\n },\n () => void 0\n );\n}\nexport {\n ASYNC_LOST_THREAD,\n ASYNC_NO_CREATE,\n ASYNC_NO_EMSCRIPTEN,\n ASYNC_NO_IMPORTS,\n ASYNC_NO_JS,\n ASYNC_NO_JSPI,\n KERNEL_WAIT,\n KernelGone,\n ProcessThreads,\n asyncProcessEntry,\n kernelWaiter,\n threadMux,\n threadStarted\n};\n";
2
+ export const PROCESS_SOURCE = "// src/kernel/protocol.ts\nvar WASM_PROCESS_INIT = \"wasm-process-init\";\nvar WASM_PROCESS_EXIT = \"wasm-process-exit\";\nvar WASM_PROCESS_ERROR = \"wasm-process-error\";\nvar WASM_PROCESS_READY = \"wasm-process-ready\";\nvar WASM_THREAD_SPAWN = \"wasm-thread-spawn\";\nvar WASM_THREAD_INIT = \"wasm-thread-init\";\nvar WASM_THREAD_EXIT = \"wasm-thread-exit\";\nvar WASM_MAX_THREADS = 256;\nvar WASM_DEFAULT_THREADS = 64;\n\n// src/async/jspi.ts\nvar jspi = WebAssembly;\nfunction jspiAvailable() {\n return typeof jspi.Suspending === \"function\" && typeof jspi.promising === \"function\";\n}\nvar AsyncFunction = (async () => {\n}).constructor;\nvar waiters = /* @__PURE__ */ new WeakMap();\nvar sleepers = /* @__PURE__ */ new WeakMap();\nvar localWaiter = (typed2, index3, value2, timeout) => {\n if (Atomics.load(typed2, index3) !== value2) return Promise.resolve(\"not-equal\");\n if (timeout !== void 0 && Number.isFinite(timeout)) return Promise.resolve(\"timed-out\");\n let set = sleepers.get(typed2.buffer);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n sleepers.set(typed2.buffer, set);\n }\n const own = set;\n return new Promise((resolve) => {\n const sleeper = {\n index: index3,\n wake: () => {\n own.delete(sleeper);\n resolve(\"ok\");\n }\n };\n own.add(sleeper);\n });\n};\nfunction atomicsNotify(typed2, index3, count) {\n let woken = 0;\n for (const sleeper of [...sleepers.get(typed2.buffer) ?? []]) {\n if (count !== void 0 && woken >= count) break;\n if (sleeper.index !== index3) continue;\n sleeper.wake();\n woken++;\n }\n return woken + Atomics.notify(typed2, index3, count);\n}\nfunction registerWaiter(buffer, waiter) {\n waiters.set(buffer, waiter);\n}\nasync function atomicsWait(typed2, index3, value2, timeout) {\n const waiter = waiters.get(typed2.buffer);\n if (waiter) return waiter(typed2, index3, value2, timeout);\n if (Atomics.load(typed2, index3) !== value2) return \"not-equal\";\n if (timeout !== void 0 && timeout <= 0) return \"timed-out\";\n throw new Error(\n \"async process: a wait on memory no process owns: nothing can wake it, and no wait runs on a local timer\"\n );\n}\nfunction checked(name2, fn) {\n return (...args) => {\n const result = fn(...args);\n if (result instanceof Promise) {\n throw new Error(\n `async process: the import ${name2} returned a promise to wasm without suspending`\n );\n }\n return result;\n };\n}\nfunction suspendingImports(imports) {\n const Suspending = jspi.Suspending;\n if (!Suspending) throw new Error(\"async process: this engine has no WebAssembly.Suspending\");\n const out = {};\n for (const [ns, table] of Object.entries(imports)) {\n const wrapped = {};\n for (const [name2, value2] of Object.entries(table)) {\n wrapped[name2] = value2 instanceof AsyncFunction ? new Suspending(value2) : typeof value2 === \"function\" ? checked(`${ns}.${name2}`, value2) : value2;\n }\n out[ns] = wrapped;\n }\n return out;\n}\nvar entries = /* @__PURE__ */ new WeakMap();\nfunction reentered(fn) {\n const known = entries.get(fn);\n if (known) return known;\n const promising = jspi.promising;\n if (!promising) throw new Error(\"async process: this engine has no WebAssembly.promising\");\n let entry;\n try {\n entry = promising(fn);\n } catch {\n entry = async (...args) => fn(...args);\n }\n entries.set(fn, entry);\n return entry;\n}\nfunction refusedModule(_bytes) {\n throw new Error(\"compiling wasm at run time is not supported by the async process host\");\n}\nfunction refusedImport(_specifier) {\n return Promise.reject(\n new Error(\"loading JavaScript at run time is not supported by the async process host\")\n );\n}\n\n// src/kernel/signals.ts\nvar SIG = {\n HUP: 1,\n INT: 2,\n QUIT: 3,\n ILL: 4,\n TRAP: 5,\n ABRT: 6,\n BUS: 7,\n FPE: 8,\n KILL: 9,\n USR1: 10,\n SEGV: 11,\n USR2: 12,\n PIPE: 13,\n ALRM: 14,\n TERM: 15,\n STKFLT: 16,\n CHLD: 17,\n CONT: 18,\n STOP: 19,\n TSTP: 20,\n TTIN: 21,\n TTOU: 22,\n URG: 23,\n XCPU: 24,\n XFSZ: 25,\n VTALRM: 26,\n PROF: 27,\n WINCH: 28,\n POLL: 29,\n PWR: 30,\n SYS: 31\n};\nvar IGNORED_BY_DEFAULT = /* @__PURE__ */ new Set([SIG.CHLD, SIG.URG, SIG.WINCH]);\nvar STOPPING = /* @__PURE__ */ new Set([SIG.STOP, SIG.TSTP, SIG.TTIN, SIG.TTOU]);\nfunction defaultAction(sig) {\n if (sig === SIG.CONT) return \"continue\";\n if (STOPPING.has(sig)) return \"stop\";\n return IGNORED_BY_DEFAULT.has(sig) ? \"ignore\" : \"terminate\";\n}\nfunction sigbit(sig) {\n return 1 << sig;\n}\nfunction signalsIn(mask) {\n const out = [];\n for (let sig = 1; sig <= 31; sig++) if (mask & sigbit(sig)) out.push(sig);\n return out;\n}\nvar SIGNAL_BY_NAME = {\n SIGINT: SIG.INT,\n SIGTERM: SIG.TERM,\n SIGKILL: SIG.KILL,\n SIGSTOP: SIG.STOP,\n SIGCONT: SIG.CONT\n};\nvar SI = { USER: 0, QUEUE: -1, TIMER: -2, TKILL: -6, KERNEL: 128 };\nvar KERNEL_SIGINFO = Object.freeze({\n code: SI.KERNEL,\n pid: 0,\n uid: 0,\n status: 0\n});\n\n// src/fs/changes.ts\nvar GEN = 0;\nvar RING = 1;\nvar RING_SIZE = 4096;\nvar SLOT = 2;\nvar SHARED_TTL_MS = 100;\nvar RENAME_WAIT_MS = 100;\nvar RENAME_WAIT_SHARED_MS = 1e3;\nfunction renameWait(view) {\n return view.foreign() ? RENAME_WAIT_SHARED_MS : RENAME_WAIT_MS;\n}\nvar DIRTY = RING + RING_SIZE * SLOT;\nvar FOREIGN = DIRTY + 1;\nvar RENAMES = FOREIGN + 1;\nvar HELD = RENAMES + 1;\nvar HELD_SLOTS = 1024;\nvar CHANGES_BYTES = (HELD + HELD_SLOTS) * 4;\nfunction heldSlot(path) {\n return HELD + (changeHash(normal(path)) & HELD_SLOTS - 1);\n}\nfunction changeHash(path) {\n let h = 2166136261;\n for (let i = 0; i < path.length; i++) {\n h ^= path.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return h === 0 ? 1 : h;\n}\nfunction normal(path) {\n const parts = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\nvar ChangeView = class {\n view;\n constructor(sab) {\n this.view = new Int32Array(sab);\n }\n now() {\n return Atomics.load(this.view, GEN);\n }\n clean() {\n return this.view.length > DIRTY && Atomics.load(this.view, DIRTY) === 0;\n }\n foreign() {\n return this.view.length > FOREIGN && Atomics.load(this.view, FOREIGN) === 1;\n }\n peerHeld(path) {\n return this.view.length > HELD && Atomics.load(this.view, heldSlot(path)) === 1;\n }\n renames() {\n return this.view.length > RENAMES ? Atomics.load(this.view, RENAMES) : 0;\n }\n async awaitRename(seen, ms) {\n if (this.view.length > RENAMES) await atomicsWait(this.view, RENAMES, seen, ms);\n return this.renames();\n }\n changedSince(seen, path) {\n const now = Atomics.load(this.view, GEN);\n const distance = now - seen >>> 0;\n if (distance === 0) return { now, changed: false };\n if (distance > RING_SIZE) return { now, changed: true };\n const hash = changeHash(normal(path));\n for (let i = 1; i <= distance; i++) {\n const g = seen + i | 0;\n const at = RING + (g & RING_SIZE - 1) * SLOT;\n if (Atomics.load(this.view, at) !== g) return { now, changed: true };\n const hit = Atomics.load(this.view, at + 1) === hash;\n if (Atomics.load(this.view, at) !== g) return { now, changed: true };\n if (hit) return { now, changed: true };\n }\n return { now, changed: false };\n }\n};\n\n// src/realm/sync-sab-wire.ts\nvar atomicLoad = Atomics.load;\nvar atomicStore = Atomics.store;\nvar atomicWaitAsync = Atomics.waitAsync;\nvar setBytes = Uint8Array.prototype.set;\nvar bytesPart = Uint8Array.prototype.subarray;\nvar decodeText = TextDecoder.prototype.decode;\nvar sabLoad = (a, i) => atomicLoad(a, i);\nvar sabStore = (a, i, v) => atomicStore(a, i, v);\nfunction copyWindow(out, window, chunk, at) {\n setBytes.call(out, bytesPart.call(window, 0, chunk), at);\n}\nvar SAB_HEADER_I32 = 18;\nvar SAB_CLOCK_OFFSET = SAB_HEADER_I32 * 4;\nvar SAB_CLOCK_I64 = 3;\nvar SAB_HEADER_BYTES = SAB_CLOCK_OFFSET + SAB_CLOCK_I64 * 8;\nvar SAB_I_STATE = 0;\nvar SAB_I_SEQ = 1;\nvar SAB_I_STATUS = 2;\nvar SAB_I_TOTAL = 3;\nvar SAB_I_CHUNK = 4;\nvar SAB_I_OFFSET = 5;\nvar SAB_I_REQ = 6;\nvar SAB_I_PUB = 7;\nvar SAB_I_SIGNALS = 8;\nvar SAB_I_TIMERS = 9;\nvar SAB_I_MEMORY = 10;\nvar SAB_I_TOTAL_HI = 11;\nvar SAB_I_OFFSET_HI = 12;\nvar SAB_I_KILLED = 13;\nvar SAB_I_ASYNC = 14;\nvar SAB_I_STOP = 15;\nvar SAB_I_BLOCKED = 16;\nvar SAB_I_BLOCKED_HI = 17;\nfunction loadBlocked(header) {\n return [sabLoad(header, SAB_I_BLOCKED), sabLoad(header, SAB_I_BLOCKED_HI)];\n}\nfunction storeBlocked(header, [low, high]) {\n sabStore(header, SAB_I_BLOCKED_HI, high);\n sabStore(header, SAB_I_BLOCKED, low);\n}\nvar anyBlocked = (mask) => mask !== void 0 && (mask[0] !== 0 || mask[1] !== 0);\nvar U32 = 2 ** 32;\nfunction loadU53(header, lo, hi) {\n return (sabLoad(header, lo) >>> 0) + sabLoad(header, hi) * U32;\n}\nfunction publishMemory(sab, bytes) {\n if (bytes > 0)\n sabStore(new Int32Array(sab, 0, SAB_HEADER_I32), SAB_I_MEMORY, Math.ceil(bytes / 65536));\n}\nvar SAB_STATE_IDLE = 0;\nvar SAB_STATE_PENDING = 1;\nvar SAB_STATE_READY = 2;\nvar SAB_STATUS_BYTES = 1;\nvar SAB_STATUS_JSON = 2;\nvar SAB_STATUS_VOID = 3;\nvar SAB_STATUS_ERRNO = 4;\nvar SAB_DEFAULT_WINDOW_BYTES = 1024 * 1024;\nvar SAB_MIN_BYTES = SAB_HEADER_BYTES + 4096;\nvar SYNC_SAB_REQ_MSG = \"sync-sab-req\";\nvar SYNC_SAB_NEXT_MSG = \"sync-sab-next\";\nvar encoder = new TextEncoder();\nvar decoder = new TextDecoder();\nfunction decodeSabResult(status2, payload) {\n switch (status2) {\n case SAB_STATUS_BYTES:\n return { ok: true, kind: \"bytes\", bytes: payload };\n case SAB_STATUS_VOID:\n return { ok: true, kind: \"void\" };\n case SAB_STATUS_JSON: {\n try {\n return { ok: true, kind: \"json\", json: JSON.parse(decodeText.call(decoder, payload)) };\n } catch {\n return { ok: false, errno: \"EIO\", message: \"sync-sab: malformed json payload\" };\n }\n }\n case SAB_STATUS_ERRNO: {\n try {\n const parsed = JSON.parse(decodeText.call(decoder, payload));\n const errno = typeof parsed.errno === \"string\" && /^E[A-Z]+$|^EAI_[A-Z]+$/.test(parsed.errno) ? parsed.errno : \"EIO\";\n const message = String(parsed.message ?? errno);\n return {\n ok: false,\n errno,\n message,\n ...parsed.direct === true ? { direct: true } : {},\n ...typeof parsed.dev === \"string\" ? { dev: parsed.dev } : {},\n ...parsed.detail === \"transport\" || parsed.detail === \"placeholder\" || parsed.detail === \"forbidden-header\" ? { detail: parsed.detail } : {}\n };\n } catch {\n return { ok: false, errno: \"EIO\", message: \"sync-sab: malformed errno payload\" };\n }\n }\n default:\n return { ok: false, errno: \"EIO\", message: `sync-sab: unknown status ${status2}` };\n }\n}\nfunction sabViews(sab) {\n if (sab.byteLength < SAB_MIN_BYTES) {\n throw new Error(`sync-sab: buffer too small (${sab.byteLength} < ${SAB_MIN_BYTES})`);\n }\n return {\n header: new Int32Array(sab, 0, SAB_HEADER_I32),\n window: new Uint8Array(sab, SAB_HEADER_BYTES)\n };\n}\n\n// src/kernel/cpu-clock.ts\nvar LOCAL = SAB_CLOCK_OFFSET;\nvar BLOCKED = 0;\nvar IDLE = 1;\nfunction epochMicros() {\n return Math.floor((performance.timeOrigin + performance.now()) * 1e3);\n}\nfunction slots(sab) {\n return new BigInt64Array(sab, LOCAL, SAB_CLOCK_I64);\n}\nvar local;\nvar localSab;\nvar localStart = 0;\nvar rawWait = Atomics.wait.bind(Atomics);\nfunction localCpuNanos() {\n if (!local || !localSab) return void 0;\n const now = epochMicros();\n const blocked = Number(Atomics.load(local, BLOCKED)) + localIdle(localSab, now).idle;\n return BigInt(Math.max(0, now - localStart - blocked)) * 1000n;\n}\nfunction localIdle(sab, now) {\n const state = Number(Atomics.load(slots(sab), IDLE));\n if (state >= 0) return { idle: state, waiting: false };\n return { idle: Math.max(0, now + state), waiting: true };\n}\n\n// src/realm/sync-fs-wire.ts\nvar SYNC_FS_OPS = [\n \"read\",\n \"write\",\n \"exists\",\n \"stat\",\n \"lstat\",\n \"readdir\",\n \"readdir-stat\",\n \"mkdir\",\n \"rm\",\n \"rename\",\n \"link\",\n \"copy\",\n \"unlink\",\n \"rmdir\",\n \"symlink\",\n \"readlink\",\n \"chmod\",\n \"utimes\",\n \"lutimes\",\n \"statfs\",\n \"hold\",\n \"create\",\n \"mkfifo\",\n \"kept\",\n \"pread\",\n \"pwrite\",\n \"append\",\n \"truncate\",\n \"chown\",\n \"lchown\",\n \"access\",\n \"renames\"\n];\nvar HOLD_READ = 4;\nvar HOLD_WRITE = 8;\nvar HOLD_CREATED = 16;\nvar SYNC_FS_REQUEST_TIMEOUT_MS = 25e3;\nvar SYNC_FS_READ_ONLY = /* @__PURE__ */ new Set([\n \"read\",\n \"pread\",\n \"exists\",\n \"stat\",\n \"lstat\",\n \"readdir\",\n \"readdir-stat\",\n \"readlink\",\n \"statfs\",\n \"kept\",\n \"access\",\n \"renames\"\n]);\nfunction parseSyncFsUsage(json) {\n const u = json;\n if (!u || typeof u.quota !== \"number\" || typeof u.usage !== \"number\") return null;\n return { quota: u.quota, usage: u.usage };\n}\nfunction syncError(code2, label) {\n return Object.assign(new Error(`${code2}: ${label}`), { code: code2 });\n}\nfunction parseSyncFsStat(json) {\n const s = json;\n if (!s || typeof s.isFile !== \"boolean\" || typeof s.isDirectory !== \"boolean\" || typeof s.size !== \"number\") {\n return null;\n }\n return {\n isFile: s.isFile,\n isDirectory: s.isDirectory,\n isSymbolicLink: s.isSymbolicLink,\n ...s.isSocket === true ? { isSocket: true } : {},\n ...s.isFifo === true ? { isFifo: true } : {},\n size: s.size,\n ...typeof s.mode === \"number\" ? { mode: s.mode } : {},\n ...typeof s.mtimeMs === \"number\" ? { mtimeMs: s.mtimeMs } : {},\n ...typeof s.atimeMs === \"number\" ? { atimeMs: s.atimeMs } : {},\n ...typeof s.ctimeMs === \"number\" ? { ctimeMs: s.ctimeMs } : {},\n ...typeof s.ino === \"number\" ? { ino: s.ino } : {},\n ...typeof s.fid === \"string\" ? { fid: s.fid } : {},\n ...typeof s.nlink === \"number\" ? { nlink: s.nlink } : {},\n ...typeof s.dev === \"number\" ? { dev: s.dev } : {},\n ...s.readonly === true ? { readonly: true } : {},\n ...typeof s.maxFile === \"number\" ? { maxFile: s.maxFile } : {},\n ...s.ranged === true ? { ranged: true } : {},\n ...s.linkable === true ? { linkable: true } : {},\n ...typeof s.version === \"string\" ? { version: s.version } : {},\n ...typeof s.gen === \"number\" ? { gen: s.gen } : {},\n ...typeof s.uid === \"number\" ? { uid: s.uid } : {},\n ...typeof s.gid === \"number\" ? { gid: s.gid } : {}\n };\n}\n\n// src/realm/sync-sab-bridge.ts\nvar UNCOUNTED_OPS = /* @__PURE__ */ new Set([...SYNC_FS_OPS, \"cwd-check\", \"cwd-chdir\"]);\nvar calls = 0;\nfunction exactBody(req, transfer = []) {\n const body = req.body;\n if (!ArrayBuffer.isView(body)) return { req, transfer };\n if (Object.prototype.toString.call(body.buffer) === \"[object SharedArrayBuffer]\") {\n return { req, transfer };\n }\n const whole = body.constructor === Uint8Array && body.byteOffset === 0 && body.byteLength === body.buffer.byteLength;\n if (whole) return { req, transfer };\n const copy = new Uint8Array(body.byteLength);\n copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n return { req: { ...req, body: copy }, transfer: [...transfer, copy.buffer] };\n}\nvar looks = 0;\nfunction lookedOutside() {\n looks++;\n}\nvar SPIN_MS = 0.06;\nvar SPIN_STRIDE = 128;\nvar SPIN_STRIDES = 256;\nvar SPIN_CORES = 4;\nvar spinning = (globalThis.navigator?.hardwareConcurrency ?? 0) >= SPIN_CORES;\nvar SPIN_CAP_MS = 1;\nfunction createSyncSabTransport(sab, port, deps = {}) {\n const views = sabViews(sab);\n const { header, window } = views;\n const wait = deps.wait ?? (async (a, i, v, t) => await rawWait(a, i, v, t));\n const now = deps.now ?? (() => performance.now());\n let seq = 0;\n let typical = 0;\n const ready = (id) => sabLoad(header, SAB_I_STATE) === SAB_STATE_READY && sabLoad(header, SAB_I_SEQ) === id;\n function spinUntil(id, until) {\n for (let stride = 0; stride < SPIN_STRIDES; stride++) {\n for (let i = 0; i < SPIN_STRIDE; i++) if (ready(id)) return true;\n if (now() >= until) return false;\n }\n return false;\n }\n function settled(start2) {\n typical += (Math.min(now() - start2, SPIN_CAP_MS) - typical) / 8;\n }\n async function awaitReady(id, deadline, label) {\n const start2 = now();\n if (spinning && typical < SPIN_MS && spinUntil(id, start2 + SPIN_MS)) {\n settled(start2);\n return;\n }\n for (; ; ) {\n const published = sabLoad(header, SAB_I_PUB);\n if (ready(id)) {\n settled(start2);\n return;\n }\n const remaining = deadline - now();\n if (remaining <= 0) throw syncError(\"EIO\", label);\n await wait(header, SAB_I_PUB, published, remaining);\n }\n }\n return {\n async call(asked, timeoutMs2, label, given = [], sink) {\n if (deps.memory) publishMemory(sab, deps.memory());\n const { req, transfer } = exactBody(asked, given);\n const id = ++seq;\n calls += Number(!UNCOUNTED_OPS.has(req.op));\n let out = null;\n let status2 = 0;\n let offset = 0;\n sabStore(header, SAB_I_REQ, id);\n try {\n for (; ; ) {\n sabStore(header, SAB_I_STATE, SAB_STATE_PENDING);\n const msg = offset === 0 ? { type: SYNC_SAB_REQ_MSG, id, req } : { type: SYNC_SAB_NEXT_MSG, id, offset };\n try {\n if (offset === 0 && transfer.length > 0) port.postMessage(msg, transfer);\n else port.postMessage(msg);\n } catch {\n throw syncError(\"EIO\", label);\n }\n await awaitReady(id, now() + timeoutMs2, label);\n const total = loadU53(header, SAB_I_TOTAL, SAB_I_TOTAL_HI);\n const chunk = sabLoad(header, SAB_I_CHUNK);\n const at = loadU53(header, SAB_I_OFFSET, SAB_I_OFFSET_HI);\n if (at !== offset || chunk < 0 || total < 0 || offset + chunk > total) {\n throw syncError(\"EIO\", label);\n }\n if (out === null) {\n status2 = sabLoad(header, SAB_I_STATUS);\n out = await landing(status2, total, sink);\n }\n copyWindow(out, window, chunk, offset);\n offset += chunk;\n if (offset >= total) break;\n if (chunk === 0) throw syncError(\"EIO\", label);\n }\n } finally {\n sabStore(header, SAB_I_REQ, 0);\n sabStore(header, SAB_I_STATE, SAB_STATE_IDLE);\n }\n return decodeSabResult(status2, out);\n }\n };\n}\nvar typed = Object.getPrototypeOf(Uint8Array.prototype);\nvar getter = (name2) => Object.getOwnPropertyDescriptor(typed, name2)?.get;\nvar bufferOf = getter(\"buffer\");\nvar offsetOf = getter(\"byteOffset\");\nvar lengthOf = getter(\"length\");\nasync function landing(status2, total, sink) {\n if (!sink || status2 !== SAB_STATUS_BYTES || total > await lengthOf.call(sink)) {\n return new Uint8Array(total);\n }\n return new Uint8Array(await bufferOf.call(sink), await offsetOf.call(sink), total);\n}\nfunction errnoError(code2, path, direct) {\n const err = syncError(code2, `sync-sab bridge, '${path}'`);\n return direct ? Object.assign(err, { direct }) : err;\n}\nfunction holdSeen(seen) {\n return { gen: seen.gen, ino: seen.ino, ...seen.nofollow ? { nofollow: true } : {} };\n}\nfunction holds(json, run) {\n const reals = /* @__PURE__ */ new Map();\n return {\n hold: async (path, held, open, handle, want = 0, seen = {}) => {\n const mode = (held ? 1 : 0) | (open ? 2 : 0);\n if (mode === 3) {\n const reply = await json({ op: \"hold\", path, mode: mode | want, ...holdSeen(seen) }, path);\n if (typeof reply !== \"object\" || reply === null) return reply;\n reals.set(reply.handle, reply.real);\n return reply.handle;\n }\n if (handle !== void 0) reals.delete(handle);\n await run({ op: \"hold\", path, mode, ...handle !== void 0 ? { handle } : {} }, path);\n return void 0;\n },\n heldReal: (handle) => reals.get(handle)\n };\n}\nfunction createSyncFsSabBridge(transport, opts = {}) {\n const direct = opts.direct ? { direct: true } : {};\n const timeoutMs2 = opts.timeoutMs ?? SYNC_FS_REQUEST_TIMEOUT_MS;\n let identity = {};\n let once = false;\n let last = null;\n async function run(req, path, transfer) {\n last = null;\n const silence = SYNC_FS_READ_ONLY.has(req.op) ? timeoutMs2 : Number.POSITIVE_INFINITY;\n const result = await transport.call(req, silence, `sync-sab bridge, '${path}'`, transfer);\n if (!result.ok) throw errnoError(result.errno, path, result.direct);\n return result;\n }\n async function bytes(req, path) {\n const r = await run(req, path);\n if (r.ok && r.kind === \"bytes\") return r.bytes;\n throw errnoError(\"EIO\", path);\n }\n async function json(req, path) {\n const r = await run(req, path);\n if (r.ok && r.kind === \"json\") return r.json;\n throw errnoError(\"EIO\", path);\n }\n const changing = async (req, path, transfer) => {\n const ask = once ? { identity: true } : identity;\n once = false;\n const r = await run({ ...req, ...ask }, path, transfer);\n if (r.ok && r.kind === \"json\") last = parseSyncFsStat(r.json);\n };\n const io = (id) => ({\n readFile: async (path) => await bytes({ op: \"read\", path, ...id }, path),\n writeFile: async (path, data, open) => {\n await changing({ op: \"write\", path, body: data, ...open ? { mode: 1 } : {}, ...id }, path);\n },\n pread: async (path, offset, length, version) => await bytes({ op: \"pread\", path, offset, length, ...version ? { version } : {}, ...id }, path),\n pwrite: async (path, offset, body, transfer) => {\n const whole = body.byteOffset === 0 && body.byteLength === body.buffer.byteLength;\n const owned = transfer && whole && body.buffer instanceof ArrayBuffer;\n const transferred = owned ? [body.buffer] : [];\n await changing({ op: \"pwrite\", path, offset, body, ...id }, path, transferred);\n },\n truncate: async (path, length) => {\n await changing({ op: \"truncate\", path, length, ...id }, path);\n },\n append: async (path, body) => await json({ op: \"append\", path, body, ...id }, path)\n });\n return {\n ...io({}),\n pinned: (handle) => io({ handle }),\n kept: async (handle) => await json({ op: \"kept\", path: \"/\", handle }, \"/\") === true,\n keptStat: async (handle) => {\n const s = parseSyncFsStat(await json({ op: \"stat\", path: \"/\", handle }, \"/\"));\n if (!s) throw errnoError(\"EIO\", \"/\");\n return s;\n },\n stat: async (path) => {\n const s = parseSyncFsStat(await json({ op: \"stat\", path, ...direct }, path));\n if (!s) throw errnoError(\"EIO\", path);\n return s;\n },\n lstat: async (path) => {\n const s = parseSyncFsStat(await json({ op: \"lstat\", path, ...direct }, path));\n if (!s) throw errnoError(\"EIO\", path);\n return s;\n },\n readdir: async (path) => {\n const list = await json({ op: \"readdir\", path }, path);\n if (!Array.isArray(list) || !list.every((s) => typeof s === \"string\")) {\n throw errnoError(\"EIO\", path);\n }\n return list;\n },\n readdirStat: async (path) => {\n const list = await json({ op: \"readdir-stat\", path }, path);\n if (!Array.isArray(list)) throw errnoError(\"EIO\", path);\n return list.map((entry) => {\n if (!Array.isArray(entry) || typeof entry[0] !== \"string\") throw errnoError(\"EIO\", path);\n if (entry[1] === null) return [entry[0], null];\n const stat = parseSyncFsStat(entry[1]);\n if (!stat) throw errnoError(\"EIO\", path);\n return [entry[0], stat];\n });\n },\n exists: async (path) => {\n const v = await json({ op: \"exists\", path }, path);\n if (typeof v !== \"boolean\") throw errnoError(\"EIO\", path);\n return v;\n },\n mkdir: async (path, mode) => {\n await run({ op: \"mkdir\", path, exclusive: true, ...mode !== void 0 ? { mode } : {} }, path);\n },\n rm: async (path) => {\n await run({ op: \"rm\", path }, path);\n },\n rename: async (from, to) => {\n const r = await run({ op: \"rename\", path: from, arg2: to }, from);\n const seq = r.ok && r.kind === \"json\" ? r.json.seq : void 0;\n return typeof seq === \"number\" ? seq : void 0;\n },\n link: async (from, to, follow2) => {\n await run({ op: \"link\", path: from, arg2: to, ...follow2 ? { mode: 1 } : {} }, from);\n },\n unlink: async (path) => {\n await run({ op: \"unlink\", path }, path);\n },\n rmdir: async (path) => {\n await run({ op: \"rmdir\", path }, path);\n },\n symlink: async (target, linkPath2) => {\n await run({ op: \"symlink\", path: linkPath2, arg2: target }, linkPath2);\n },\n readlink: async (path) => {\n const target = await json({ op: \"readlink\", path }, path);\n if (typeof target !== \"string\") throw errnoError(\"EIO\", path);\n return target;\n },\n chmod: async (path, mode) => {\n await changing({ op: \"chmod\", path, mode }, path);\n },\n utimes: async (path, atimeMs, mtimeMs, now) => {\n await changing({ op: \"utimes\", path, atimeMs, mtimeMs, ...now ? { now } : {} }, path);\n },\n identify: () => {\n identity = { identity: true };\n },\n identifyNext: () => {\n once = true;\n last = null;\n },\n identified: () => {\n once = false;\n return last;\n },\n lutimes: async (path, atimeMs, mtimeMs, now) => {\n await run({ op: \"lutimes\", path, atimeMs, mtimeMs, ...now ? { now } : {} }, path);\n },\n mkfifo: async (path, mode) => {\n await run({ op: \"mkfifo\", path, mode }, path);\n },\n copy: async (from, to, mode, exclusive) => {\n await run({ op: \"copy\", path: from, arg2: to, mode, ...exclusive ? { exclusive } : {} }, to);\n },\n create: async (path, mode, opening) => {\n const flags = { ...mode !== void 0 ? { mode } : {}, ...opening ? { opening } : {} };\n const r = await run({ op: \"create\", path, ...flags, identity: true }, path);\n if (!r.ok || r.kind !== \"json\") return void 0;\n const st = parseSyncFsStat(r.json);\n if (!st) return void 0;\n const { seen } = r.json;\n return typeof seen === \"number\" ? { ...st, seen } : st;\n },\n chown: async (path, uid, gid, follow2, handle) => {\n const ids = { ...uid !== void 0 ? { uid } : {}, ...gid !== void 0 ? { gid } : {} };\n await changing(\n {\n op: follow2 ? \"chown\" : \"lchown\",\n path,\n ...ids,\n ...handle !== void 0 ? { handle } : {}\n },\n path\n );\n },\n ...opts.owners ? { owners: true } : {},\n ...opts.links ? { links: true } : {},\n ...opts.changes ? { changes: new ChangeView(opts.changes) } : {},\n access: async (path, mode, kind = \"access\", nofollow) => {\n await run({ op: \"access\", path, mode, arg2: kind, ...nofollow ? { nofollow } : {} }, path);\n },\n ...holds(json, run),\n statfs: async (path = \"/\") => parseSyncFsUsage(await json({ op: \"statfs\", path }, path)),\n renames: async (since, held) => await json(\n { op: \"renames\", path: \"/\", offset: since, arg2: JSON.stringify(held) },\n \"/\"\n )\n };\n}\n\n// src/fs/dev-removal.ts\nvar SHM = \"/dev/shm\";\nfunction inShm(path) {\n return path === SHM || path.startsWith(`${SHM}/`);\n}\nfunction inDevTree(path) {\n if (path.startsWith(`${SHM}/`)) return false;\n return path === \"/dev\" || path.startsWith(\"/dev/\");\n}\nfunction inSys(path) {\n return path === \"/sys\" || path.startsWith(\"/sys/\");\n}\nfunction devRemoval(path, cred) {\n if (inSys(path)) return \"EROFS\";\n if (!inDevTree(path)) return void 0;\n if (cred && cred.euid !== 0) return \"EACCES\";\n return path === \"/dev\" ? \"EBUSY\" : \"EPERM\";\n}\nfunction devCreation(path, cred) {\n if (path === \"/proc\" || path.startsWith(\"/proc/\") || inSys(path)) return \"EROFS\";\n if (path === \"/dev\" || !inDevTree(path)) return void 0;\n return cred && cred.euid !== 0 ? \"EACCES\" : \"EPERM\";\n}\n\n// src/kernel/net/loopback-names.ts\nvar HOST_LOOPBACK = \"host.slicc.internal\";\nvar HOST_LOOPBACK_ADDRESS = [10, 0, 2, 2];\nvar PAGE_LOOPBACK = \"kernel.localhost\";\nvar PAGE_LOOPBACK_URL = `http://{port}.${PAGE_LOOPBACK}`;\nvar DEFAULT_HOSTNAME = \"slicc\";\nvar HOSTNAME_ADDRESS = \"127.0.1.1\";\nvar LIBC_HOSTNAMES = [\"emscripten\", \"wasmer.sh\"];\nvar LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;\nfunction reserved(name2) {\n const lower = name2.toLowerCase();\n return lower === \"localhost\" || lower.endsWith(\".localhost\") || lower === HOST_LOOPBACK || lower === \"wasmer.sh\" || /^\\d+(\\.\\d+){3}$/.test(lower);\n}\nfunction isHostname(name2) {\n if (typeof name2 !== \"string\" || name2.length > 253 || reserved(name2)) return false;\n return name2.split(\".\").every((l) => LABEL.test(l));\n}\nfunction hostnameOf(env) {\n return isHostname(env.HOSTNAME) ? env.HOSTNAME : DEFAULT_HOSTNAME;\n}\nfunction initHostname(init) {\n return isHostname(init.hostname) ? init.hostname : hostnameOf(init.env);\n}\nfunction ownNames(hostname) {\n return [.../* @__PURE__ */ new Set([hostname.toLowerCase(), ...LIBC_HOSTNAMES])];\n}\nfunction hostsFile(hostname = DEFAULT_HOSTNAME) {\n return [\n \"127.0.0.1 localhost localhost.localdomain\",\n \"::1 localhost ip6-localhost\",\n `${HOSTNAME_ADDRESS} ${ownNames(hostname).join(\" \")}`,\n `${HOST_LOOPBACK_ADDRESS.join(\".\")} ${HOST_LOOPBACK}`,\n \"\"\n ].join(\"\\n\");\n}\n\n// src/fs/types.ts\nfunction normalizePath(path) {\n const parts = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\nfunction inodeOf(path) {\n let h1 = 3735928559;\n let h2 = 1103547991;\n for (let i = 0; i < path.length; i++) {\n const c = path.charCodeAt(i);\n h1 = Math.imul(h1 ^ c, 2654435761);\n h2 = Math.imul(h2 ^ c, 1597334677);\n }\n h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);\n h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);\n return 4294967296 * (2097151 & h2) + (h1 >>> 0) || 1;\n}\n\n// src/fs/owners.ts\nvar ROOT_OWNER = Object.freeze({ uid: 0, gid: 0 });\n\n// src/fs/pages.ts\nvar PAGE = 64 * 1024;\nvar READAHEAD = 1024 * 1024;\nvar CLEAN_LIMIT = 4 * 1024 * 1024;\nvar WRITEBACK = 8 * 1024 * 1024;\nvar RUN = 1024 * 1024;\nvar Pages = class {\n length;\n stored;\n shrink;\n pages = /* @__PURE__ */ new Map();\n dirty = /* @__PURE__ */ new Set();\n free = [];\n pinned = false;\n constructor(size) {\n this.length = size;\n this.stored = size;\n }\n get dirtyBytes() {\n return this.dirty.size * PAGE;\n }\n get changed() {\n return this.dirty.size > 0 || this.shrink !== void 0 || this.length !== this.stored;\n }\n missing(at, length) {\n this.evict();\n const end = Math.min(this.stored, at + length, this.length);\n const runs = [];\n for (let page = Math.floor(at / PAGE); page * PAGE < end; page++) {\n if (this.pages.has(page)) continue;\n const last2 = runs[runs.length - 1];\n if (last2 && last2[0] + last2[1] === page * PAGE) last2[1] += PAGE;\n else runs.push([page * PAGE, PAGE]);\n }\n const last = runs[runs.length - 1];\n if (last) last[1] = Math.max(last[1], Math.min(READAHEAD, this.stored - last[0]));\n return runs.map(([start2, n]) => [start2, Math.min(n, this.stored - start2)]);\n }\n partial(at, length) {\n if (length === 0) return [];\n this.evict();\n const edges = /* @__PURE__ */ new Set([Math.floor(at / PAGE), Math.floor((at + length - 1) / PAGE)]);\n const runs = [];\n for (const page of edges) {\n const start2 = page * PAGE;\n const covered = at <= start2 && at + length >= start2 + PAGE;\n if (covered || this.pages.has(page) || start2 >= this.stored) continue;\n runs.push([start2, Math.min(PAGE, this.stored - start2)]);\n }\n return runs;\n }\n fill(start2, bytes) {\n for (let at = 0; at < bytes.length; at += PAGE) {\n const page = (start2 + at) / PAGE;\n if (this.pages.has(page)) continue;\n const part = bytes.subarray(at, Math.min(at + PAGE, bytes.length));\n const fresh = this.take(part.length);\n fresh.set(part);\n this.pages.set(page, fresh);\n }\n }\n read(at, length) {\n const out = new Uint8Array(Math.max(0, Math.min(this.length, at + length) - at));\n this.readInto(at, out);\n return out;\n }\n readInto(at, out) {\n const end = Math.min(this.length, at + out.length);\n for (let pos = at; pos < end; ) {\n const page = Math.floor(pos / PAGE);\n const from = pos - page * PAGE;\n const n = Math.min(PAGE - from, end - pos);\n const bytes = this.pages.get(page);\n if (bytes) out.set(bytes.subarray(from, from + n), pos - at);\n else out.fill(0, pos - at, pos - at + n);\n pos += n;\n }\n return Math.max(0, end - at);\n }\n write(at, bytes) {\n for (let done = 0; done < bytes.length; ) {\n const pos = at + done;\n const page = Math.floor(pos / PAGE);\n const from = pos - page * PAGE;\n const n = Math.min(PAGE - from, bytes.length - done);\n let target = this.pages.get(page);\n if (!target) {\n target = this.take(0);\n this.pages.set(page, target);\n }\n target.set(bytes.subarray(done, done + n), from);\n this.dirty.add(page);\n done += n;\n }\n this.length = Math.max(this.length, at + bytes.length);\n }\n truncate(size) {\n if (size < this.stored) {\n this.stored = size;\n this.shrink = Math.min(this.shrink ?? size, size);\n }\n if (size < this.length) {\n const edge = Math.floor(size / PAGE);\n for (const page of [...this.pages.keys()]) {\n if (page > edge || page === edge && size === edge * PAGE) this.drop(page);\n }\n this.pages.get(edge)?.fill(0, size - edge * PAGE);\n }\n this.length = size;\n }\n plan() {\n const runs = [];\n const sorted = [...this.dirty].sort((a, b) => a - b);\n for (let i = 0; i < sorted.length; ) {\n let j = i + 1;\n const first = sorted[i];\n while (j < sorted.length && sorted[j] === first + (j - i) && sorted[j] * PAGE % RUN !== 0) {\n j++;\n }\n const start2 = first * PAGE;\n const end = Math.min(this.length, (first + (j - i)) * PAGE);\n const bytes = new Uint8Array(end - start2);\n for (let k = i; k < j; k++) {\n const page = this.pages.get(sorted[k]);\n bytes.set(page.subarray(0, Math.min(PAGE, end - (k - i) * PAGE - start2)), (k - i) * PAGE);\n }\n runs.push({ offset: start2, bytes });\n i = j;\n }\n const written = Math.max(this.stored, ...runs.map((r) => r.offset + r.bytes.length));\n return {\n ...this.shrink !== void 0 ? { shrink: this.shrink } : {},\n runs,\n ...this.length > written ? { extend: this.length } : {}\n };\n }\n flushed() {\n this.dirty.clear();\n this.shrink = void 0;\n this.stored = this.length;\n this.evict();\n }\n pin() {\n this.pinned = true;\n }\n landed(at, length) {\n const end = at + length;\n for (let page = Math.floor(at / PAGE); page * PAGE < end; page++) {\n if (this.pages.has(page) && !this.dirty.has(page)) this.drop(page);\n }\n this.length = Math.max(this.length, end);\n this.stored = Math.max(this.stored, end);\n }\n reset(size) {\n if (this.pinned) return;\n for (const page of [...this.pages.keys()]) if (!this.dirty.has(page)) this.drop(page);\n if (this.changed) return;\n this.length = size;\n this.stored = size;\n }\n refresh(size) {\n if (this.pinned) return;\n for (const page of [...this.pages.keys()]) if (!this.dirty.has(page)) this.drop(page);\n const resized = this.length !== this.stored || this.shrink !== void 0;\n if (this.shrink === void 0) this.stored = size;\n this.length = resized ? Math.max(this.length, this.stored) : size;\n }\n evict() {\n if (this.pinned) return;\n let clean = (this.pages.size - this.dirty.size) * PAGE;\n for (const page of this.pages.keys()) {\n if (clean <= CLEAN_LIMIT) return;\n if (this.dirty.has(page)) continue;\n this.drop(page);\n clean -= PAGE;\n }\n }\n take(used) {\n const page = this.free.pop();\n if (!page) return new Uint8Array(PAGE);\n page.fill(0, used);\n return page;\n }\n drop(page) {\n const bytes = this.pages.get(page);\n this.pages.delete(page);\n this.dirty.delete(page);\n if (this.free.length < CLEAN_LIMIT / PAGE) this.free.push(bytes);\n }\n};\n\n// src/fs/ranged.ts\nvar signatureOf = (st) => `${st.version ?? \"\"}:${st.size}:${st.mtimeMs ?? \"\"}`;\nfunction linkedWatch(watch, st) {\n if ((st.nlink ?? 1) < 2) return watch;\n watch.linked = true;\n watch.sig = signatureOf(st);\n return watch;\n}\nasync function viaAlias(watch, seen, path) {\n if (watch.resolved === void 0) {\n let real;\n try {\n real = await watch.real?.();\n } catch {\n }\n watch.resolved = real && real !== path ? real : null;\n }\n return watch.resolved !== null && watch.view.changedSince(seen, watch.resolved).changed;\n}\nasync function viaLink(watch, path) {\n if (!watch.linked) return false;\n let sig;\n try {\n sig = signatureOf(await watch.stat(path));\n } catch {\n return false;\n }\n if (sig === watch.sig) return false;\n watch.sig = sig;\n return true;\n}\nasync function watchedChange(watch, seen, path) {\n const said = watch.view.changedSince(seen, path);\n if (said.changed || said.now === seen) return said;\n return { now: said.now, changed: await viaAlias(watch, seen, path) || await viaLink(watch, path) };\n}\nvar RangedFile = class {\n pages;\n io;\n pinned = false;\n version;\n watch;\n seen = 0;\n path;\n constructor(io, path, size, version, watch) {\n this.io = io;\n this.path = path;\n this.version = version;\n this.pages = new Pages(size);\n this.watch = watch;\n if (watch) this.seen = watch.seen ?? watch.view.now();\n }\n async fresh() {\n const watch = this.watch;\n if (!watch || this.pinned) return;\n const { now, changed: changed2 } = await watchedChange(watch, this.seen, this.path);\n this.seen = now;\n if (changed2) await this.reread();\n }\n async reread() {\n const watch = this.watch;\n if (!watch || this.pinned || this.pages.changed) return;\n let st;\n try {\n st = await watch.stat(this.path);\n } catch {\n return;\n }\n if (watch.ino !== void 0 && st.ino !== watch.ino) return;\n this.version = st.version;\n this.pages.refresh(st.size);\n }\n get changed() {\n return this.pages.changed;\n }\n async wrote(at, length) {\n this.pages.landed(at, length);\n this.version = void 0;\n await this.fresh();\n }\n get pinnedVersion() {\n return this.version;\n }\n forget() {\n this.pages.reset(this.pages.length);\n }\n async size() {\n await this.fresh();\n return this.pages.length;\n }\n async fetch(runs) {\n for (const [start2, n] of runs) {\n this.pages.fill(start2, await this.io.pread(this.path, start2, n, this.version));\n }\n }\n async read(at, length) {\n await this.fresh();\n await this.fetch(this.pages.missing(at, length));\n return this.pages.read(at, length);\n }\n async readInto(at, out) {\n await this.fresh();\n await this.fetch(this.pages.missing(at, out.length));\n return this.pages.readInto(at, out);\n }\n async write(at, bytes) {\n await this.fresh();\n await this.fetch(this.pages.partial(at, bytes.length));\n this.pages.write(at, bytes);\n if (!this.pinned && this.pages.dirtyBytes >= WRITEBACK) await this.flush();\n }\n truncate(size) {\n this.pages.truncate(size);\n }\n async flush() {\n if (this.pinned || !this.pages.changed) return;\n const plan = this.pages.plan();\n if (plan.shrink !== void 0) await this.io.truncate(this.path, plan.shrink);\n for (const run of plan.runs) await this.io.pwrite(this.path, run.offset, run.bytes, true);\n if (plan.extend !== void 0) await this.io.truncate(this.path, plan.extend);\n this.version = void 0;\n this.pages.flushed();\n }\n async pin() {\n this.pinned = true;\n this.pages.pin();\n await this.prefetch();\n }\n async prefetch() {\n await this.fresh();\n await this.fetch(this.pages.missing(0, this.pages.length));\n }\n reset(size) {\n this.pages.reset(size);\n }\n};\n\n// src/process/wasi/wasi-abi.ts\nvar E = {\n SUCCESS: 0,\n \"2BIG\": 1,\n ACCES: 2,\n ADDRINUSE: 3,\n ADDRNOTAVAIL: 4,\n AFNOSUPPORT: 5,\n AGAIN: 6,\n ALREADY: 7,\n BADF: 8,\n BADMSG: 9,\n BUSY: 10,\n CANCELED: 11,\n CHILD: 12,\n CONNABORTED: 13,\n CONNREFUSED: 14,\n CONNRESET: 15,\n DEADLK: 16,\n DESTADDRREQ: 17,\n DOM: 18,\n DQUOT: 19,\n EXIST: 20,\n FAULT: 21,\n FBIG: 22,\n HOSTUNREACH: 23,\n IDRM: 24,\n ILSEQ: 25,\n INPROGRESS: 26,\n INTR: 27,\n INVAL: 28,\n IO: 29,\n ISCONN: 30,\n ISDIR: 31,\n LOOP: 32,\n MFILE: 33,\n MLINK: 34,\n MSGSIZE: 35,\n MULTIHOP: 36,\n NAMETOOLONG: 37,\n NETDOWN: 38,\n NETRESET: 39,\n NETUNREACH: 40,\n NFILE: 41,\n NOBUFS: 42,\n NODEV: 43,\n NOENT: 44,\n NOEXEC: 45,\n NOLCK: 46,\n NOLINK: 47,\n NOMEM: 48,\n NOMSG: 49,\n NOPROTOOPT: 50,\n NOSPC: 51,\n NOSYS: 52,\n NOTCONN: 53,\n NOTDIR: 54,\n NOTEMPTY: 55,\n NOTRECOVERABLE: 56,\n NOTSOCK: 57,\n NOTSUP: 58,\n NOTTY: 59,\n NXIO: 60,\n OVERFLOW: 61,\n OWNERDEAD: 62,\n PERM: 63,\n PIPE: 64,\n PROTO: 65,\n PROTONOSUPPORT: 66,\n PROTOTYPE: 67,\n RANGE: 68,\n ROFS: 69,\n SPIPE: 70,\n SRCH: 71,\n STALE: 72,\n TIMEDOUT: 73,\n TXTBSY: 74,\n XDEV: 75,\n NOTCAPABLE: 76\n};\nfunction wasiErrnoOf(code2) {\n if (!code2) return E.IO;\n const name2 = code2.startsWith(\"E\") ? code2.slice(1) : code2;\n if (name2 === \"OPNOTSUPP\") return E.NOTSUP;\n if (name2 === \"WOULDBLOCK\") return E.AGAIN;\n if (name2 === \"NOMEDIUM\") return E.NODEV;\n return E[name2] ?? E.IO;\n}\nvar FILETYPE = {\n UNKNOWN: 0,\n BLOCK_DEVICE: 1,\n CHARACTER_DEVICE: 2,\n DIRECTORY: 3,\n REGULAR_FILE: 4,\n SOCKET_DGRAM: 5,\n SOCKET_STREAM: 6,\n SYMBOLIC_LINK: 7\n};\nvar RIGHTS = {\n FD_DATASYNC: 1n << 0n,\n FD_READ: 1n << 1n,\n FD_SEEK: 1n << 2n,\n FD_FDSTAT_SET_FLAGS: 1n << 3n,\n FD_SYNC: 1n << 4n,\n FD_TELL: 1n << 5n,\n FD_WRITE: 1n << 6n,\n ALL: (1n << 30n) - 1n\n};\nvar OFLAGS = { CREAT: 1, DIRECTORY: 2, EXCL: 4, TRUNC: 8 };\nvar FDFLAGS = { APPEND: 1, DSYNC: 2, NONBLOCK: 4, RSYNC: 8, SYNC: 16 };\nvar LOOKUP_SYMLINK_FOLLOW = 1;\nvar WHENCE = { SET: 0, CUR: 1, END: 2 };\nvar CLOCK = { REALTIME: 0, MONOTONIC: 1, PROCESS_CPUTIME: 2, THREAD_CPUTIME: 3 };\nvar FSTFLAGS = { ATIM: 1, ATIM_NOW: 2, MTIM: 4, MTIM_NOW: 8 };\nvar EVENTTYPE = { CLOCK: 0, FD_READ: 1, FD_WRITE: 2 };\nvar SUBCLOCK_ABSTIME = 1;\nvar EVENT_FD_READWRITE_HANGUP = 1;\nvar RIFLAGS = { PEEK: 1, WAITALL: 2 };\nvar SDFLAGS = { RD: 1, WR: 2 };\nvar PREOPENTYPE_DIR = 0;\nvar SIZE = {\n FILESTAT: 64,\n FDSTAT: 24,\n DIRENT: 24,\n SUBSCRIPTION: 48,\n EVENT: 32\n};\nvar WASI_SIGNAL_TO_POSIX = Object.fromEntries(\n Array.from({ length: 30 }, (_, i) => [i + 1, i + 1 < 16 ? i + 1 : i + 2])\n);\nfunction wasixSignal(sig) {\n return Number.isInteger(sig) && sig >= 1 && sig <= 31 ? sig : void 0;\n}\n\n// src/process/wasi-errno.ts\nvar WASI_ERRNO = {\n ...Object.fromEntries(Object.entries(E).map(([name2, errno]) => [`E${name2}`, errno])),\n EWOULDBLOCK: E.AGAIN,\n ENOTSUP: 138,\n EOPNOTSUPP: 138,\n ENOMEDIUM: 148\n};\nfunction wasiErrno(code2) {\n return WASI_ERRNO[code2] ?? E.IO;\n}\n\n// src/realm/live-vfs-fs.ts\nvar EARLY_WHOLE_FILE = 64 * 1024;\nvar createParentRefresh = 0;\nfunction createParentRefreshCount() {\n return createParentRefresh;\n}\n\n// src/version.ts\nvar KERNEL_VERSION = true ? \"1.193.2\" : \"0.0.0-dev\";\nvar OS_RELEASE = \"6.0.0-slicc\";\nfunction procVersion() {\n return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC\n`;\n}\n\n// src/kernel/serial-ioctl.ts\nvar IOCTL = {\n TCGETS: 21505,\n TCSETS: 21506,\n TCSETSW: 21507,\n TCSETSF: 21508,\n TCSBRK: 21513,\n TCFLSH: 21515,\n TIOCEXCL: 21516,\n TIOCNXCL: 21517,\n TIOCSCTTY: 21518,\n TIOCGPGRP: 21519,\n TIOCSPGRP: 21520,\n TIOCOUTQ: 21521,\n TIOCGWINSZ: 21523,\n TIOCSWINSZ: 21524,\n TIOCMGET: 21525,\n TIOCMBIS: 21526,\n TIOCMBIC: 21527,\n TIOCMSET: 21528,\n FIONREAD: 21531,\n TIOCNOTTY: 21538,\n TCSBRKP: 21541,\n TIOCSBRK: 21543,\n TIOCCBRK: 21544,\n TCGETS2: 2150388778,\n TCSETS2: 1076646955,\n TCSETSW2: 1076646956,\n TCSETSF2: 1076646957\n};\nvar TERMIOS_GETS = /* @__PURE__ */ new Set([IOCTL.TCGETS, IOCTL.TCGETS2]);\nvar TERMIOS_SETS = /* @__PURE__ */ new Set([\n IOCTL.TCSETS,\n IOCTL.TCSETSW,\n IOCTL.TCSETSF,\n IOCTL.TCSETS2,\n IOCTL.TCSETSW2,\n IOCTL.TCSETSF2\n]);\nvar INT_OUT = /* @__PURE__ */ new Set([\n IOCTL.TIOCMGET,\n IOCTL.FIONREAD,\n IOCTL.TIOCOUTQ\n]);\nvar INT_IN = /* @__PURE__ */ new Set([\n IOCTL.TIOCMBIS,\n IOCTL.TIOCMBIC,\n IOCTL.TIOCMSET\n]);\nvar INT_ARG = /* @__PURE__ */ new Set([IOCTL.TCSBRK, IOCTL.TCSBRKP, IOCTL.TCFLSH]);\nvar CBAUD = 4111;\nvar CSIZE = 48;\nvar CSTOPB = 64;\nvar PARENB = 256;\nvar PARODD = 512;\nvar CRTSCTS = 2147483648;\nfunction settingsOf(cflag, baudRate) {\n return {\n baudRate,\n dataBits: 5 + ((cflag & CSIZE) >> 4),\n parity: cflag & PARENB ? cflag & PARODD ? \"odd\" : \"even\" : \"none\",\n stopBits: cflag & CSTOPB ? 2 : 1,\n flowControl: cflag & CRTSCTS ? \"hardware\" : \"none\"\n };\n}\nvar SERIAL_CFLAG = 13 | 48 | 128 | 1024 | 2048;\nvar SERIAL_LFLAG = 16 | 32 | 512 | 2048;\nvar NCCS = 32;\nvar NCCS2 = 19;\nvar C_LINE = 16;\nvar C_CC = 17;\nfunction readFlags(view, at, ncc) {\n const cCc = new Array(NCCS).fill(0);\n for (let i = 0; i < ncc; i++) cCc[i] = view.getUint8(at + C_CC + i);\n return {\n c_iflag: view.getUint32(at, true),\n c_oflag: view.getUint32(at + 4, true),\n c_cflag: view.getUint32(at + 8, true),\n c_lflag: view.getUint32(at + 12, true),\n c_cc: cCc\n };\n}\nfunction writeFlags(view, at, t, ncc) {\n view.setUint32(at, t.c_iflag >>> 0, true);\n view.setUint32(at + 4, t.c_oflag >>> 0, true);\n view.setUint32(at + 8, t.c_cflag >>> 0, true);\n view.setUint32(at + 12, t.c_lflag >>> 0, true);\n view.setUint8(at + C_LINE, 0);\n for (let i = 0; i < ncc; i++) view.setUint8(at + C_CC + i, t.c_cc[i] ?? 0);\n}\nfunction ioctlArg(view, request, arg) {\n if (TERMIOS_SETS.has(request)) {\n if (request > 65535) {\n const t = readFlags(view, arg, NCCS2);\n return {\n ...t,\n c_ispeed: view.getUint32(arg + 36, true),\n c_ospeed: view.getUint32(arg + 40, true)\n };\n }\n return readFlags(view, arg, NCCS);\n }\n if (INT_IN.has(request)) return view.getInt32(arg, true);\n if (INT_ARG.has(request)) return arg | 0;\n if (request === IOCTL.TIOCSWINSZ)\n return { rows: view.getUint16(arg, true), cols: view.getUint16(arg + 2, true) };\n return void 0;\n}\nfunction ioctlResult(view, request, arg, result) {\n if (TERMIOS_GETS.has(request)) {\n const t = result;\n if (request === IOCTL.TCGETS2) {\n writeFlags(view, arg, t, NCCS2);\n view.setUint32(arg + 36, (t.c_ispeed ?? 0) >>> 0, true);\n view.setUint32(arg + 40, (t.c_ospeed ?? 0) >>> 0, true);\n } else {\n writeFlags(view, arg, t, NCCS);\n view.setUint32(arg + 52, t.c_cflag & CBAUD, true);\n view.setUint32(arg + 56, t.c_cflag & CBAUD, true);\n }\n } else if (INT_OUT.has(request)) view.setInt32(arg, Number(result) | 0, true);\n else if (request === IOCTL.TIOCGWINSZ) {\n const size = result;\n view.setUint16(arg, size.rows, true);\n view.setUint16(arg + 2, size.cols, true);\n view.setUint32(arg + 4, 0, true);\n }\n}\n\n// src/process/process-pty.ts\nvar TIOCGPTN = 2147767344;\nvar TIOCSPTLCK = 1074025521;\nvar TIOCSCTTY = 21518;\nvar TIOCSWINSZ = 21524;\nvar TIOCPKT = 21536;\n\n// src/process/process-fds.ts\nvar REFUSED = /* @__PURE__ */ new Set([wasiErrno(\"EACCES\"), wasiErrno(\"EPERM\")]);\nvar OWN_ERRORS = 128 | 131072;\nvar field = (text) => (text || \"none\").replace(/[\\s\\\\]/g, (c) => `\\\\${c.charCodeAt(0).toString(8).padStart(3, \"0\")}`);\nvar pinnedRoot;\nvar rootKind = () => globalThis.navigator?.storage ? \"opfs\" : \"memory\";\nfunction mountTable(mounts = []) {\n const root = pinnedRoot ?? rootKind();\n const lines = [`${root} / ${root} rw 0 0`, \"devfs /dev devfs rw 0 0\", \"proc /proc proc rw 0 0\"];\n for (const m of mounts) {\n const options = Object.entries(m.options).map(([k, v]) => v === \"\" ? k : `${k}=${v}`);\n if (m.state !== \"ok\") options.push(m.state);\n const access3 = options.includes(\"ro\") ? [] : [\"rw\"];\n lines.push(\n `${field(m.source)} ${field(m.target)} ${m.type} ${[...access3, ...options].join(\",\")} 0 0`\n );\n }\n return `${lines.join(\"\\n\")}\n`;\n}\nvar NAME = /^[a-z_][a-z0-9_-]*$/i;\nfunction accounts(env = {}) {\n const user = env.USER ?? \"web_user\";\n const name2 = NAME.test(user) && user !== \"root\" ? user : \"user\";\n const home = env.HOME || \"/home\";\n return {\n passwd: `root:x:0:0:root:/root:/bin/sh\n${name2}:x:1000:1000:${name2}:${home}:/bin/bash\n`,\n group: `root:x:0:\n${name2}:x:1000:\n`\n };\n}\n\n// src/process/kernel-streams.ts\nvar KILLED_BY_SIGPIPE = 128 + 13;\nvar SyscallError = class extends Error {\n code;\n constructor(code2) {\n super(code2);\n this.code = code2;\n }\n};\n\n// src/kernel/held-cwd.ts\nvar CWD_SLOTS = 1024;\nvar UNTRACKED = CWD_SLOTS - 1;\nvar HeldCwd = class {\n view;\n seen;\n dead = false;\n slot;\n at;\n ask;\n constructor(sab, slot2, ask, state) {\n this.view = new Int32Array(sab);\n this.slot = slot2;\n this.ask = ask;\n this.seen = state.seen;\n this.dead = state.dead;\n this.at = state.path;\n }\n moved(reply, path) {\n if (reply.slot === void 0) return false;\n this.slot = reply.slot;\n this.seen = reply.seen ?? Atomics.load(this.view, reply.slot);\n this.dead = reply.dead === true;\n this.at = path;\n return true;\n }\n async follow() {\n const answer = await this.ask();\n if (answer.slot !== void 0) this.slot = answer.slot;\n this.seen = answer.gen;\n this.dead = !answer.alive;\n return answer.alive;\n }\n async alive(path) {\n if (path !== void 0 && this.at !== void 0 && path !== this.at) {\n this.at = path;\n return await this.follow();\n }\n if (this.dead) return false;\n if (Atomics.load(this.view, this.slot) === this.seen) return true;\n return await this.follow();\n }\n get current() {\n return this.slot;\n }\n};\n\n// src/process/process-children.ts\nvar UNSEEDED = sigbit(SIG.KILL) | sigbit(SIG.STOP) | 1;\nfunction inheritedOf(r) {\n return r.ok && r.kind === \"json\" ? r.json & ~UNSEEDED : 0;\n}\nasync function inheritedSignals(transport) {\n return inheritedOf(\n await transport.call({ op: \"sig-inherited\" }, Number.POSITIVE_INFINITY, \"sig-inherited\")\n );\n}\n\n// src/process/process-signals.ts\nvar SignalGate = class {\n reported = { caught: 0, ignored: 0, nocldwait: false };\n restart = 0;\n lastDelivered = 0;\n depth = 0;\n reporting = false;\n unwinding = false;\n quieted = 0;\n delivered = 0;\n raised = 0;\n entering = 0;\n raw;\n header;\n hooks;\n constructor(raw, header, hooks) {\n this.raw = raw;\n this.header = header;\n this.hooks = hooks;\n }\n transport() {\n return {\n call: async (req, timeoutMs2, label) => {\n await this.report();\n this.depth++;\n try {\n const result = await this.raw.call(req, timeoutMs2, label);\n await this.deliver();\n return result;\n } finally {\n this.depth--;\n }\n }\n };\n }\n deliveries() {\n return this.delivered;\n }\n restartable() {\n return this.lastDelivered !== 0 && (this.lastDelivered & ~this.restart) === 0;\n }\n async report() {\n if (this.reporting) return;\n this.reporting = true;\n let masks;\n try {\n masks = this.hooks.masks();\n } catch {\n masks = null;\n } finally {\n this.reporting = false;\n }\n if (!masks) return;\n this.restart = masks.restart;\n const { caught, ignored, defaults = 0 } = masks;\n const nocldwait = masks.nocldwait === true;\n const was = this.reported;\n const same2 = caught === was.caught && ignored === was.ignored && nocldwait === was.nocldwait;\n if (same2 && defaults === 0) return;\n this.reported = { caught, ignored, nocldwait };\n const req = {\n op: \"sig-mask\",\n caught,\n ignored,\n ...defaults ? { defaults } : {},\n ...nocldwait ? { nocldwait } : {}\n };\n await this.raw.call(req, Number.POSITIVE_INFINITY, \"sig-mask\");\n }\n async quiet(fn) {\n this.quieted++;\n try {\n return await fn();\n } finally {\n this.quieted--;\n }\n }\n async interrupt() {\n await this.report();\n const header = this.header;\n const pending = Atomics.load(header, SAB_I_SIGNALS) & ~Atomics.load(header, SAB_I_BLOCKED) | Atomics.load(header, SAB_I_TIMERS) | Atomics.load(header, SAB_I_KILLED);\n if (pending === 0) return false;\n if (this.entering === 0) this.raised = this.quieted > 0 ? -1 : 0;\n this.entering++;\n try {\n await this.deliver();\n } finally {\n this.entering--;\n }\n return true;\n }\n raisedOnEntry() {\n return this.raised;\n }\n async deliver() {\n if (this.quieted > 0) return;\n const killed = Atomics.load(this.header, SAB_I_KILLED);\n if (killed !== 0 && !this.unwinding && this.hooks.killed) {\n this.unwinding = true;\n this.hooks.killed(killed);\n }\n const timers = Atomics.exchange(this.header, SAB_I_TIMERS, 0);\n const blocked = Atomics.load(this.header, SAB_I_BLOCKED);\n const pending = blocked === 0 ? Atomics.exchange(this.header, SAB_I_SIGNALS, 0) : Atomics.and(this.header, SAB_I_SIGNALS, blocked) & ~blocked;\n if (this.depth <= 1) this.lastDelivered = pending | (timers & 1 ? sigbit(SIG.ALRM) : 0);\n if (pending !== 0 || timers !== 0) this.delivered++;\n this.raised |= pending | (timers & 1 ? sigbit(SIG.ALRM) : 0) | (timers & ~1 ? -1 : 0);\n for (let which = 0; which < 3; which++) {\n if (timers & 1 << which) await this.hooks.timer?.(which);\n }\n for (const sig of signalsIn(pending)) await this.hooks.raise(sig);\n }\n};\n\n// src/process/process-sockets.ts\nvar KILLED_BY_SIGPIPE2 = 128 + 13;\n\n// src/kernel/cred.ts\nvar ROOT = Object.freeze({\n ruid: 0,\n euid: 0,\n suid: 0,\n rgid: 0,\n egid: 0,\n sgid: 0,\n groups: [0]\n});\nvar MAX_GROUPS = 65536;\n\n// src/kernel/proc-info.ts\nfunction mayTrace(viewer, target) {\n const by = viewer?.cred;\n const of = target.cred;\n if (!by || !of || by.euid === 0) return true;\n const uid = of.ruid === by.euid && of.euid === by.euid && of.suid === by.euid;\n return uid && of.rgid === by.egid && of.egid === by.egid && of.sgid === by.egid;\n}\nfunction fileIdentity(ino, mtimeMs) {\n if (ino === void 0 || mtimeMs === void 0 || !Number.isFinite(mtimeMs)) return void 0;\n return `${ino}:${Math.trunc(mtimeMs)}`;\n}\n\n// src/process/procfs.ts\nvar HZ = 100;\nvar KIB = 1024;\nvar FALLBACK_MEMORY = 4 * KIB * KIB * KIB;\nvar PID_FILES = [\"cmdline\", \"comm\", \"stat\", \"statm\", \"status\"];\nvar SYSTEM_FILES = [\"loadavg\", \"meminfo\", \"stat\", \"uptime\", \"version\"];\nvar SYS_TREE = {\n kernel: {\n osrelease: `${OS_RELEASE}\n`,\n ostype: \"Linux\\n\",\n slicc_wasm_memories: (listing2) => `${listing2.wasm?.live ?? 0} ${listing2.wasm?.ceiling ?? 0} ${listing2.wasm?.source ?? \"none\"}\n`,\n slicc_shared_root: (listing2) => `${listing2.peers ?? 0}\n`,\n slicc_fs_calls: (listing2) => `${listing2.fsCalls ?? 0}\n`,\n slicc_opfs_calls: (listing2) => `${listing2.opfsCalls ?? 0}\n`,\n slicc_opfs_ops: (listing2) => `${listing2.opfsOps ?? 0}\n`,\n slicc_create_parent_refresh: (_listing) => `${createParentRefreshCount()}\n`,\n slicc_meta_transactions: ({ meta }) => `${meta?.reads ?? 0} ${meta?.writes ?? 0}\n`,\n slicc_cwd_checks: (listing2) => `${listing2.cwdChecks ?? 0}\n`,\n slicc_package_swaps: ({ swaps }) => `${swaps?.swaps ?? 0} ${(swaps?.longestMs ?? 0).toFixed(1)} ${swaps?.waits ?? 0} ${(swaps?.waitedMs ?? 0).toFixed(1)}\n`,\n slicc_rename_ack_busy: (listing2) => `${listing2.renameAcks?.busy ?? 0}\n`,\n slicc_stale_fds: (listing2) => `${listing2.staleFds ?? 0}\n`,\n slicc_file_ids: (listing2) => `${listing2.fileIds ?? 0}\n`,\n slicc_peer_holds: ({ holds: holds2 }) => `${holds2?.mine ?? 0} ${holds2?.peers ?? 0} ${holds2?.sent ?? 0}\n`,\n slicc_peer_held: ({ holds: holds2 }) => (holds2?.held ?? []).map((path) => `${path}\n`).join(\"\"),\n slicc_rename_acks: (listing2) => {\n const samples = [...listing2.renameAcks?.ackMs ?? []].sort((a, b) => a - b);\n const median = samples[Math.floor(samples.length / 2)] ?? 0;\n const most = samples.at(-1) ?? 0;\n const waits = listing2.renameAcks?.waits ?? 0;\n const queries = listing2.renameAcks?.queries ?? 0;\n return `${listing2.renameAcks?.acks ?? 0} ${median.toFixed(1)} ${most.toFixed(1)} ${waits} ${queries}\n`;\n }\n }\n};\nfunction isSysFile(at) {\n return typeof at === \"string\" || typeof at === \"function\";\n}\nfunction sysEntry(parts) {\n let at = SYS_TREE;\n for (const part of parts) {\n if (isSysFile(at) || !Object.hasOwn(at, part)) return void 0;\n at = at[part];\n }\n return at;\n}\nasync function sysText(file, listing2) {\n return typeof file === \"string\" ? file : file(await listing2());\n}\nfunction commOf(info) {\n const name2 = info.argv[0] ?? \"\";\n return name2.slice(name2.lastIndexOf(\"/\") + 1).slice(0, 15);\n}\nfunction ttyNumber(tty) {\n const pts = tty && /^\\/dev\\/pts\\/(\\d+)$/.exec(tty);\n if (pts) return 136 << 8 | Number(pts[1]);\n const vt = tty && /^\\/dev\\/tty(\\d+)$/.exec(tty);\n return vt ? 4 << 8 | Number(vt[1]) : 0;\n}\nfunction pages(bytes) {\n return Math.ceil(bytes / 4096);\n}\nfunction ticks(ms) {\n return Math.max(0, Math.floor(ms * HZ / 1e3));\n}\nfunction pidStat(info, boot, state = info.state) {\n const fields = [\n info.pid,\n `(${commOf(info)})`,\n state,\n info.ppid,\n info.pgid,\n info.sid,\n ttyNumber(info.tty),\n info.tty ? info.pgid : -1,\n 4194304,\n 0,\n 0,\n 0,\n 0,\n ticks(info.utime ?? 0),\n ticks(info.stime ?? 0),\n ticks(info.cutime ?? 0),\n ticks(info.cstime ?? 0),\n 20,\n 0,\n 1,\n 0,\n ticks(info.started - boot),\n info.memory,\n pages(info.memory),\n \"18446744073709551615\",\n ...Array(12).fill(0),\n 17,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n ...Array(7).fill(0),\n 0\n ];\n return `${fields.join(\" \")}\n`;\n}\nvar sigMask = (mask = 0) => (mask >>> 1).toString(16).padStart(16, \"0\");\nvar STATES = {\n S: \"S (sleeping)\",\n T: \"T (stopped)\",\n Z: \"Z (zombie)\"\n};\nvar tagLine = (tag) => `Tag:\t${tag.replaceAll(\"\\n\", \"\\\\n\").replaceAll(\"\t\", \"\\\\t\").replaceAll(\"\\r\", \"\\\\r\")}`;\nfunction taskStat(info, tid, boot) {\n const thread = (info.threads ?? [{ tid: 1, state: info.state }]).find((t) => t.tid === tid);\n return thread && pidStat({ ...info, pid: tid }, boot, thread.state);\n}\nfunction taskIds(info) {\n return (info.threads ?? [{ tid: 1 }]).map((t) => t.tid);\n}\nfunction pidStatus(info) {\n const state = STATES[info.state];\n const c = info.cred ?? ROOT;\n const ids = (r, e, s) => `${r}\t${e}\t${s}\t${e}`;\n return [\n `Name:\t${commOf(info)}`,\n `Umask:\t${(info.umask ?? 18).toString(8).padStart(4, \"0\")}`,\n `State:\t${state}`,\n `Tgid:\t${info.pid}`,\n \"Ngid:\t0\",\n `Pid:\t${info.pid}`,\n `PPid:\t${info.ppid}`,\n \"TracerPid:\t0\",\n `Uid:\t${ids(c.ruid, c.euid, c.suid)}`,\n `Gid:\t${ids(c.rgid, c.egid, c.sgid)}`,\n ...(info.tags ?? (info.tag !== void 0 ? [info.tag] : [])).map(tagLine),\n \"FDSize:\t64\",\n `VmSize:\t${Math.ceil(info.memory / KIB)} kB`,\n `VmRSS:\t${Math.ceil(info.memory / KIB)} kB`,\n `Groups:\t${c.groups.join(\" \")}`,\n `NSpid:\t${info.pid}`,\n `NSpgid:\t${info.pgid}`,\n `NSsid:\t${info.sid}`,\n \"Threads:\t1\",\n \"SigQ:\t0/0\",\n \"SigPnd:\t0000000000000000\",\n \"ShdPnd:\t0000000000000000\",\n `SigBlk:\t${sigMask(info.sigBlk)}`,\n `SigIgn:\t${sigMask(info.sigIgn)}`,\n `SigCgt:\t${sigMask(info.sigCgt)}`,\n \"\"\n ].join(\"\\n\");\n}\nfunction pidFile(name2, info, boot) {\n if (name2 === \"cmdline\") return info.state === \"Z\" ? \"\" : `${info.argv.join(\"\\0\")}\\0`;\n if (name2 === \"comm\") return `${commOf(info)}\n`;\n if (name2 === \"stat\") return pidStat(info, boot);\n if (name2 === \"statm\") {\n const p = pages(info.memory);\n return `${p} ${p} 0 0 0 ${p} 0\n`;\n }\n return pidStatus(info);\n}\nfunction memoryInfo(source, used = 0) {\n const total = source.deviceMemory ? source.deviceMemory * KIB * KIB * KIB : FALLBACK_MEMORY;\n const free = Math.max(0, total - used - (source.usedHeap ?? 0));\n const kb = (bytes) => `${Math.floor(bytes / KIB)} kB`;\n return [\n [\"MemTotal\", kb(total)],\n [\"MemFree\", kb(free)],\n [\"MemAvailable\", kb(free)],\n [\"Buffers\", kb(0)],\n [\"Cached\", kb(0)],\n [\"SwapCached\", kb(0)],\n [\"Shmem\", kb(0)],\n [\"SReclaimable\", kb(0)],\n [\"SwapTotal\", kb(0)],\n [\"SwapFree\", kb(0)]\n ].map(([key, value2]) => `${`${key}:`.padEnd(16)}${value2.padStart(12)}`).concat(\"\").join(\"\\n\");\n}\nfunction systemFile(name2, listing2, now, memory) {\n if (name2 === \"version\") return procVersion();\n const up = Math.max(0, now - listing2.boot) / 1e3;\n if (name2 === \"uptime\") return `${up.toFixed(2)} ${up.toFixed(2)}\n`;\n if (name2 === \"meminfo\") {\n return memoryInfo(\n memory,\n listing2.processes.reduce((sum2, p) => sum2 + p.memory, 0)\n );\n }\n const live = listing2.processes.filter((p) => p.state !== \"Z\");\n if (name2 === \"loadavg\") {\n const last = Math.max(0, ...listing2.processes.map((p) => p.pid));\n const [one, five, fifteen] = (listing2.load ?? [0, 0, 0]).map((n) => n.toFixed(2));\n return `${one} ${five} ${fifteen} 1/${live.length} ${last}\n`;\n }\n const sum = (key) => listing2.cpu?.[key] ?? listing2.processes.reduce((n, p) => n + (p[key] ?? 0), 0);\n const user = ticks(sum(\"utime\"));\n const system = ticks(sum(\"stime\"));\n const idle = listing2.cpu ? ticks(listing2.cpu.idle) : Math.max(0, ticks(now - listing2.boot) - user - system);\n return [\n `cpu ${user} 0 ${system} ${idle} 0 0 0 0 0 0`,\n `cpu0 ${user} 0 ${system} ${idle} 0 0 0 0 0 0`,\n \"intr 0\",\n \"ctxt 0\",\n `btime ${Math.floor(listing2.boot / 1e3)}`,\n `processes ${listing2.processes.length}`,\n \"procs_running 1\",\n \"procs_blocked 0\",\n \"\"\n ].join(\"\\n\");\n}\nfunction memorySource(scope = globalThis) {\n const nav = scope.navigator;\n const perf = scope.performance;\n const deviceMemory = nav?.deviceMemory;\n const used = perf?.memory?.usedJSHeapSize;\n return {\n ...typeof deviceMemory === \"number\" && deviceMemory > 0 ? { deviceMemory } : {},\n ...typeof used === \"number\" ? { usedHeap: used } : {}\n };\n}\n\n// src/process/realm-user.ts\nvar LEGACY_OWNER = Object.freeze({ uid: 1e3, gid: 1e3 });\n\n// src/kernel/pipe.ts\nvar PIPE_CAPACITY = 64 * 1024;\n\n// src/kernel/fd-table.ts\nvar DEVICE_PATHS = /* @__PURE__ */ new Map([\n [\"/dev/null\", \"null\"],\n [\"/dev/zero\", \"zero\"],\n [\"/dev/full\", \"full\"],\n [\"/dev/urandom\", \"urandom\"],\n [\"/dev/random\", \"urandom\"]\n]);\nfunction deviceAt(path) {\n return DEVICE_PATHS.get(path);\n}\n\n// src/kernel/embedder.ts\nvar EMBEDDER_HEADER_MAX = 64 * 1024;\nvar EMBEDDER_WINDOW = 1024 * 1024;\nvar EMBEDDER_BUDGET = 256 * 1024 * 1024;\n\n// src/kernel/tty.ts\nvar encoder2 = new TextEncoder();\n\n// src/kernel/devices.ts\nvar DEVICE_NAME = /^tty(USB|ACM)(\\d{1,3})$/;\nvar BY_ID = \"/dev/serial/by-id\";\nvar HIGH_WATER = 64 * 1024;\nvar DEFAULT_SETTINGS = settingsOf(SERIAL_CFLAG, 9600);\n\n// src/kernel/sysfs.ts\nvar HCD = \"/sys/devices/platform/slicc_hcd.0\";\nvar VIRTUAL = \"/sys/devices/virtual/tty\";\nvar CLASS = \"/sys/class/tty\";\nvar USB_BUS = \"/sys/bus/usb\";\nvar SERIAL_BUS = \"/sys/bus/usb-serial\";\nvar ALWAYS = [\"/sys/class/tty\", \"/sys/bus/usb\", \"/sys/bus/usb-serial\", \"/sys/devices\"];\nvar DIR_MODE = 16877;\nvar FILE_MODE = 33060;\nvar LINK_MODE = 41471;\nvar MAX_HOPS = 40;\nfunction sysError(code2, path) {\n return Object.assign(new Error(`${code2}: ${path}`), { code: code2 });\n}\nfunction relative(fromDir, to) {\n const from = fromDir.split(\"/\").filter(Boolean);\n const dest = to.split(\"/\").filter(Boolean);\n let same2 = 0;\n while (same2 < from.length && from[same2] === dest[same2]) same2++;\n if (same2 === dest.length) same2--;\n return [...from.slice(same2).map(() => \"..\"), ...dest.slice(same2)].join(\"/\");\n}\nfunction parentOf2(path) {\n return path.slice(0, path.lastIndexOf(\"/\")) || \"/\";\n}\nfunction baseOf(path) {\n return path.slice(path.lastIndexOf(\"/\") + 1);\n}\nfunction inodeOf2(path) {\n let hash = 2166136261;\n for (let i = 0; i < path.length; i++) hash = Math.imul(hash ^ path.charCodeAt(i), 16777619);\n return hash >>> 0 || 1;\n}\nfunction product(vid, pid) {\n return `${Number.parseInt(vid, 16).toString(16)}/${Number.parseInt(pid, 16).toString(16)}/0`;\n}\nvar Layout = class {\n entries = /* @__PURE__ */ new Map([[\"/\", { kind: \"dir\", names: /* @__PURE__ */ new Set() }]]);\n dir(path) {\n if (this.entries.has(path)) return;\n const parent = parentOf2(path);\n this.dir(parent);\n this.entries.get(parent).names.add(baseOf(path));\n this.entries.set(path, { kind: \"dir\", names: /* @__PURE__ */ new Set() });\n }\n put(path, entry) {\n const parent = parentOf2(path);\n this.dir(parent);\n this.entries.get(parent).names.add(baseOf(path));\n this.entries.set(path, entry);\n }\n file(path, text) {\n this.put(path, { kind: \"file\", text });\n }\n link(path, to) {\n this.put(path, { kind: \"link\", target: relative(parentOf2(path), to) });\n }\n};\nfunction addNode(layout, node) {\n const name2 = node.path.slice(\"/dev/\".length);\n const family = DEVICE_NAME.exec(name2)?.[1];\n const { sys } = node;\n const bus = family === \"USB\" ? 1 : 2;\n const usb = `${HCD}/usb${bus}/${bus}-${node.minor + 1}`;\n const intf = `${usb}/${bus}-${node.minor + 1}:1.0`;\n const port = family === \"USB\" ? `${intf}/${name2}` : intf;\n const tty = sys ? `${port}/tty/${name2}` : `${VIRTUAL}/${name2}`;\n layout.link(`${CLASS}/${name2}`, tty);\n layout.file(`${tty}/dev`, `${node.major}:${node.minor}\n`);\n layout.file(`${tty}/uevent`, `MAJOR=${node.major}\nMINOR=${node.minor}\nDEVNAME=${name2}\n`);\n layout.link(`${tty}/subsystem`, CLASS);\n if (!sys) return;\n layout.link(`${tty}/device`, port);\n if (port !== intf) layout.link(`${port}/subsystem`, SERIAL_BUS);\n const id = product(sys.idVendor, sys.idProduct);\n layout.file(`${intf}/bInterfaceNumber`, \"00\\n\");\n layout.file(`${intf}/uevent`, `DEVTYPE=usb_interface\nPRODUCT=${id}\n`);\n layout.link(`${intf}/subsystem`, USB_BUS);\n layout.file(`${usb}/idVendor`, `${sys.idVendor}\n`);\n layout.file(`${usb}/idProduct`, `${sys.idProduct}\n`);\n layout.file(`${usb}/bNumInterfaces`, \" 1\\n\");\n for (const key of [\"manufacturer\", \"product\", \"serial\"]) {\n const text = sys[key];\n if (text !== void 0) layout.file(`${usb}/${key}`, `${text}\n`);\n }\n layout.file(`${usb}/uevent`, `DEVTYPE=usb_device\nPRODUCT=${id}\n`);\n layout.link(`${usb}/subsystem`, USB_BUS);\n}\nfunction sysLayout(nodes) {\n const layout = new Layout();\n for (const dir of ALWAYS) layout.dir(dir);\n for (const node of nodes) addNode(layout, node);\n return layout.entries;\n}\nvar SKELETON = sysLayout([]);\nvar FIXED = /* @__PURE__ */ new Set([\n \"/\",\n \"/sys\",\n \"/sys/class\",\n \"/sys/bus\",\n \"/sys/bus/usb\",\n \"/sys/bus/usb-serial\"\n]);\nvar BORN = Date.now();\nfunction walk(entries2, path, follow2) {\n const done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n let hops = 0;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \"..\") {\n done.pop();\n continue;\n }\n const here = entries2.get(`/${done.join(\"/\")}`);\n if (here?.kind !== \"dir\") throw sysError(\"ENOTDIR\", path);\n const entry = entries2.get(`/${[...done, part].join(\"/\")}`);\n if (!entry) throw sysError(\"ENOENT\", path);\n if (entry.kind === \"link\" && (follow2 || todo.length > 0)) {\n if (++hops > MAX_HOPS) throw sysError(\"ELOOP\", path);\n todo = [...entry.target.split(\"/\").filter((p) => p !== \"\" && p !== \".\"), ...todo];\n continue;\n }\n done.push(part);\n }\n return `/${done.join(\"/\")}`;\n}\nfunction walked(path, follow2) {\n try {\n return walk(SKELETON, path, follow2);\n } catch {\n return void 0;\n }\n}\nvar SysTree = class {\n source;\n built;\n constructor(source) {\n this.source = source;\n }\n async layout() {\n this.built ??= sysLayout(await this.source());\n return this.built;\n }\n async find(path, follow2, listing2 = false) {\n const known = walked(path, follow2);\n if (known !== void 0 && (!listing2 || FIXED.has(known)))\n return { at: known, entry: SKELETON.get(known) };\n const entries2 = await this.layout();\n const at = walk(entries2, path, follow2);\n return { at, entry: entries2.get(at) };\n }\n async resolve(path, follow2 = true) {\n return (await this.find(path, follow2)).at;\n }\n async stat(path, follow2 = true) {\n const { at, entry } = await this.find(path, follow2);\n const size = entry.kind === \"file\" ? new TextEncoder().encode(entry.text).length : entry.kind === \"link\" ? entry.target.length : 0;\n return {\n isFile: entry.kind === \"file\",\n isDirectory: entry.kind === \"dir\",\n isSymbolicLink: entry.kind === \"link\",\n size,\n mode: entry.kind === \"dir\" ? DIR_MODE : entry.kind === \"file\" ? FILE_MODE : LINK_MODE,\n mtimeMs: BORN,\n atimeMs: BORN,\n ctimeMs: BORN,\n ino: inodeOf2(at),\n nlink: entry.kind === \"dir\" ? 2 : 1,\n uid: 0,\n gid: 0,\n readonly: true\n };\n }\n async read(path) {\n const { entry } = await this.find(path, true);\n if (entry.kind !== \"file\") throw sysError(\"EISDIR\", path);\n return new TextEncoder().encode(entry.text);\n }\n async readdir(path) {\n const { entry } = await this.find(path, true, true);\n if (entry.kind !== \"dir\") throw sysError(\"ENOTDIR\", path);\n return [...entry.names].sort();\n }\n async readlink(path) {\n const { entry } = await this.find(path, false);\n if (entry.kind !== \"link\") throw sysError(\"EINVAL\", path);\n return entry.target;\n }\n async exists(path, follow2 = true) {\n try {\n await this.resolve(path, follow2);\n return true;\n } catch (err) {\n if (err.code === void 0) throw err;\n return false;\n }\n }\n async access(path, mode) {\n const { entry } = await this.find(path, true);\n if (mode & 2) throw sysError(\"EROFS\", path);\n if (mode & 1 && entry.kind !== \"dir\") throw sysError(\"EACCES\", path);\n }\n};\n\n// src/process/process-runtime.ts\nfunction ownBytes(bytes) {\n if (bytes.constructor === Uint8Array) return bytes;\n return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength).slice();\n}\nfunction ownedBuffer(body, given) {\n return body === given ? void 0 : [body.buffer];\n}\nvar FS_OPS = new Set(SYNC_FS_OPS);\nfunction deviceSys(call2) {\n const json = (r) => r.ok && r.kind === \"json\" ? r.json : void 0;\n return {\n async devNodes() {\n return json(await call2({ op: \"fd-dev-nodes\" }, \"fd-dev-nodes\"));\n },\n async openDev(path, flags) {\n return json(await call2({ op: \"fd-open-dev\", path, flags }, `fd-open-dev ${path}`));\n },\n async devIoctl(fd, request, arg) {\n const req = {\n op: \"fd-dev-ioctl\",\n fd,\n request,\n ...arg !== void 0 ? { arg } : {}\n };\n return json(await call2(req, `fd-dev-ioctl ${fd}`));\n },\n async devMeta(path, change) {\n await call2({ op: \"fd-dev-meta\", path, ...change }, `fd-dev-meta ${path}`);\n }\n };\n}\nfunction kernelSys(transport) {\n const call2 = async (req, label, transfer) => {\n const r = await transport.call(req, Number.POSITIVE_INFINITY, label, transfer);\n if (!r.ok) throw new SyscallError(r.errno);\n return r;\n };\n const json = (r) => r.ok && r.kind === \"json\" ? r.json : void 0;\n return {\n ...deviceSys(call2),\n async read(fd, max, opts) {\n const flags = {\n ...opts?.nonblock ? { nonblock: true } : {},\n ...opts?.peek ? { peek: true } : {}\n };\n const r = await call2({ op: \"fd-read\", fd, max, ...flags }, `fd-read ${fd}`);\n return r.ok && r.kind === \"bytes\" ? r.bytes : new Uint8Array(0);\n },\n async write(fd, bytes, opts) {\n const body = ownBytes(bytes);\n const req = {\n op: \"fd-write\",\n fd,\n body,\n ...opts?.nonblock ? { nonblock: true } : {}\n };\n const n = json(await call2(req, `fd-write ${fd}`, ownedBuffer(body, bytes)));\n return typeof n === \"number\" ? n : bytes.length;\n },\n async close(fd) {\n await call2({ op: \"fd-close\", fd }, `fd-close ${fd}`);\n },\n async pipe() {\n return json(await call2({ op: \"fd-pipe\" }, \"fd-pipe\"));\n },\n async poll(fd) {\n return json(await call2({ op: \"fd-poll\", fd }, `fd-poll ${fd}`));\n },\n async openVfs(path, flags, position, opts) {\n return json(\n await call2(\n {\n op: \"fd-open-vfs\",\n path,\n flags,\n position,\n ...opts?.contents !== void 0 ? { contents: opts.contents } : {},\n ...opts?.orphan ? { orphan: true } : {},\n ...opts?.truncate ? { truncate: true } : {},\n ...opts?.create ? { create: true } : {},\n ...opts?.created ? { created: true } : {},\n ...opts?.pin ? { pin: opts.pin } : {},\n ...opts?.handle !== void 0 ? { handle: opts.handle } : {},\n ...opts?.ino !== void 0 ? { ino: opts.ino } : {},\n ...opts?.nofollow ? { nofollow: true } : {},\n ...opts?.fifo ? { fifo: true } : {}\n },\n `fd-open-vfs ${path}`\n )\n );\n },\n async seek(fd, offset, whence) {\n return json(await call2({ op: \"fd-seek\", fd, offset, whence }, `fd-seek ${fd}`));\n },\n async flush(fd) {\n await call2({ op: \"fd-flush\", fd }, `fd-flush ${fd}`);\n },\n async pread(fd, max, at) {\n const r = await call2({ op: \"fd-pread\", fd, max, offset: at }, `fd-pread ${fd}`);\n return r.ok && r.kind === \"bytes\" ? r.bytes : new Uint8Array(0);\n },\n async pwrite(fd, bytes, at) {\n const body = ownBytes(bytes);\n return json(\n await call2({ op: \"fd-pwrite\", fd, offset: at, body }, `fd-pwrite ${fd}`, ownedBuffer(body, bytes))\n );\n },\n async isatty(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`))?.tty === true;\n },\n async ttyName(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`))?.name;\n },\n async kind(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`))?.kind;\n },\n async heldMeta(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`)).meta;\n },\n async access(fd) {\n return json(await call2({ op: \"fd-info\", fd }, `fd-info ${fd}`)).access;\n },\n async size(fd) {\n return json(await call2({ op: \"fd-vfs-stat\", fd }, `fd-vfs-stat ${fd}`)).size;\n },\n async fdStat(fd) {\n const r = json(await call2({ op: \"fd-vfs-stat\", fd, full: true }, `fd-vfs-stat ${fd}`));\n return r?.stat;\n },\n async fdChmod(fd, mode) {\n await call2({ op: \"fd-chmod\", fd, mode }, `fd-chmod ${fd}`);\n },\n async fdChown(fd, uid, gid) {\n const ids = { ...uid !== void 0 ? { uid } : {}, ...gid !== void 0 ? { gid } : {} };\n await call2({ op: \"fd-chown\", fd, ...ids }, `fd-chown ${fd}`);\n },\n async fdUtimes(fd, atimeMs, mtimeMs, now) {\n await call2({ op: \"fd-utimes\", fd, atimeMs, mtimeMs, now }, `fd-utimes ${fd}`);\n },\n async ttyNames() {\n return json(await call2({ op: \"fd-tty-names\" }, \"fd-tty-names\"));\n },\n async ttyOwner(name2) {\n return json(await call2({ op: \"fd-tty-owner\", name: name2 }, `fd-tty-owner ${name2}`));\n },\n async openTty(name2) {\n const req = name2 === void 0 ? { op: \"fd-open-tty\" } : { op: \"fd-open-tty\", name: name2 };\n return json(await call2(req, `fd-open-tty ${name2 ?? \"\"}`));\n },\n async tcgets(fd) {\n return json(await call2({ op: \"tty-get\", fd }, `tty-get ${fd}`));\n },\n async tcsets(fd, termios, flush, drain) {\n const how = { ...flush ? { flush } : {}, ...drain ? { drain } : {} };\n await call2({ op: \"tty-set\", fd, termios, ...how }, `tty-set ${fd}`);\n },\n async winsize(fd) {\n return json(await call2({ op: \"tty-winsz\", fd }, `tty-winsz ${fd}`));\n },\n async openPty() {\n return json(await call2({ op: \"pty-open\" }, \"pty-open\"));\n },\n async openPts(n, noctty) {\n return json(await call2({ op: \"pty-slave-open\", n, noctty }, `pty-slave-open ${n}`));\n },\n async openSealed(flags) {\n return json(await call2({ op: \"fd-open-sealed\", flags }, \"fd-open-sealed\"));\n },\n async openClipboard(flags) {\n return json(await call2({ op: \"fd-open-clipboard\", flags }, \"fd-open-clipboard\"));\n },\n async clipboardAbort(fd) {\n await call2({ op: \"fd-clipboard-abort\", fd }, \"fd-clipboard-abort\");\n },\n async openEmbedder(flags) {\n return json(await call2({ op: \"fd-open-embedder\", flags }, \"fd-open-embedder\"));\n },\n async ptyNumbers() {\n return json(await call2({ op: \"pty-list\" }, \"pty-list\"));\n },\n async procList() {\n return json(await call2({ op: \"proc-list\" }, \"proc-list\"));\n },\n async mountList() {\n return json(await call2({ op: \"mount-list\" }, \"mount-list\"));\n },\n async setLock(target, kind, start2, len, wait) {\n const req = { op: \"lk-set\", ...target, kind, start: start2, len, ...wait ? { wait } : {} };\n await call2(req, \"lk-set\");\n },\n async getLock(target, kind, start2, len) {\n return json(await call2({ op: \"lk-get\", ...target, kind, start: start2, len }, \"lk-get\"));\n },\n async closeLocks(target) {\n await call2({ op: \"lk-close\", ...target }, \"lk-close\");\n },\n async flock(fd, kind, wait) {\n await call2({ op: \"flock\", fd, kind, ...wait ? { wait } : {} }, `flock ${fd}`);\n },\n async ptyNumber(fd) {\n return json(await call2({ op: \"pty-number\", fd }, `pty-number ${fd}`));\n },\n async ptyLock(fd, lock) {\n await call2({ op: \"pty-lock\", fd, lock }, `pty-lock ${fd}`);\n },\n async setControllingTerminal(fd) {\n await call2({ op: \"pty-ctty\", fd }, `pty-ctty ${fd}`);\n },\n async setPacketMode(fd, on) {\n await call2({ op: \"pty-packet\", fd, on }, `pty-packet ${fd}`);\n },\n async setWinsize(fd, rows, cols) {\n await call2({ op: \"pty-winsz-set\", fd, rows, cols }, `pty-winsz-set ${fd}`);\n }\n };\n}\nvar GLUE_TRAILER = [\n \"if (typeof ENV !== 'undefined') Object.assign(ENV, Module.sliccEnv);\",\n \"if (typeof thisProgram !== 'undefined' && Module.thisProgram === '') thisProgram = '';\",\n \"const __sliccTake = (name, value) => {\",\n \" const own = Object.getOwnPropertyDescriptor(Module, name);\",\n \" if (own && 'value' in own && own.value != null) return;\",\n \" Object.defineProperty(Module, name, { value, writable: true, configurable: true, enumerable: true });\",\n \"};\",\n \"if (typeof FS !== 'undefined') __sliccTake('FS', FS);\",\n \"if (typeof callMain === 'function') __sliccTake('callMain', callMain);\",\n \"if (typeof sliccRunMain === 'function') __sliccTake('sliccRunMain', sliccRunMain);\",\n \"if (typeof sliccForkChild === 'function') __sliccTake('sliccForkChild', sliccForkChild);\",\n \"if (typeof PIPEFS !== 'undefined') __sliccTake('PIPEFS', PIPEFS);\",\n \"Module.sliccSyscalls ??= {\",\n \" fcntl: typeof ___syscall_fcntl64 === 'function' ? ___syscall_fcntl64 : undefined,\",\n \" pipe2: typeof ___syscall_pipe2 === 'function' ? ___syscall_pipe2 : undefined,\",\n \" dup3: typeof ___syscall_dup3 === 'function' ? ___syscall_dup3 : undefined,\",\n \" socket: typeof ___syscall_socket === 'function' ? ___syscall_socket : undefined,\",\n \" accept4: typeof ___syscall_accept4 === 'function' ? ___syscall_accept4 : undefined,\",\n \" ioctl: typeof ___syscall_ioctl === 'function' ? ___syscall_ioctl : undefined,\",\n \" setitimer: typeof __setitimer_js === 'function' ? __setitimer_js : undefined,\",\n \"};\",\n \"Module.sliccKernelImports ??= {\",\n \" openat: typeof ___syscall_openat === 'function' ? ___syscall_openat : undefined,\",\n \" mkdirat: typeof ___syscall_mkdirat === 'function' ? ___syscall_mkdirat : undefined,\",\n \" mknodat: typeof ___syscall_mknodat === 'function' ? ___syscall_mknodat : undefined,\",\n \" umask: typeof ___syscall_umask === 'function' ? ___syscall_umask : undefined,\",\n \" faccessat: typeof ___syscall_faccessat === 'function' ? ___syscall_faccessat : undefined,\",\n \" linkat: typeof ___syscall_linkat === 'function' ? ___syscall_linkat : undefined,\",\n \" symlinkat: typeof ___syscall_symlinkat === 'function' ? ___syscall_symlinkat : undefined,\",\n \" uname: typeof ___syscall_uname === 'function' ? ___syscall_uname : undefined,\",\n \" utimensat: typeof ___syscall_utimensat === 'function' ? ___syscall_utimensat : undefined,\",\n \" getppid: typeof _slicc_getppid_js === 'function' ? _slicc_getppid_js : undefined,\",\n \" resizeHeap: typeof _emscripten_resize_heap === 'function' ? _emscripten_resize_heap : undefined,\",\n \" fdWrite: typeof _fd_write === 'function' ? _fd_write : undefined,\",\n \" fdRead: typeof _fd_read === 'function' ? _fd_read : undefined,\",\n \" sleepMs: typeof slicc_sleep_ms === 'function' ? slicc_sleep_ms : undefined,\",\n \" flock: typeof __syscall_flock === 'function' ? __syscall_flock : undefined,\",\n \"};\",\n \"Module.sliccFdImports ??= {\",\n \" fd_sync: typeof _fd_sync === 'function' ? _fd_sync : undefined,\",\n \" fd_pread: typeof _fd_pread === 'function' ? _fd_pread : undefined,\",\n \" fd_pwrite: typeof _fd_pwrite === 'function' ? _fd_pwrite : undefined,\",\n \"};\",\n \"const __sliccUp = () =>\",\n \" (typeof runtimeInitialized === 'undefined' || runtimeInitialized) &&\",\n \" !(typeof runtimeExited !== 'undefined' && runtimeExited) &&\",\n \" !(typeof ABORT !== 'undefined' && ABORT);\",\n \"Module.sliccSigpipe ??= () => (__sliccUp() && typeof _slicc_sigpipe === 'function' ? _slicc_sigpipe() : -1);\",\n \"Module.sliccSigMask ??= (w) => (__sliccUp() && typeof _slicc_sig_mask === 'function' ? _slicc_sig_mask(w) : -1);\",\n \"Module.sliccRaise ??= (sig) => { if (__sliccUp() && typeof _slicc_raise === 'function') _slicc_raise(sig); };\",\n \"Module.sliccTimerFire ??= (which) => {\",\n \" if (!__sliccUp() || typeof __emscripten_timeout !== 'function') return false;\",\n \" __emscripten_timeout(which, typeof _emscripten_get_now === 'function' ? _emscripten_get_now() : performance.now());\",\n \" return true;\",\n \"};\",\n \"if (typeof SliccFork !== 'undefined' && !SliccFork.balancesKeepalive && typeof runtimeKeepalivePop === 'function') {\",\n \" let __sliccForking = SliccFork.forking === true;\",\n \" Object.defineProperty(SliccFork, 'forking', {\",\n \" get: () => __sliccForking,\",\n \" set: (on) => { if (__sliccForking && !on) runtimeKeepalivePop(); __sliccForking = on; },\",\n \" configurable: true,\",\n \" });\",\n \"}\"\n].join(\"\\n\");\nasync function identify(transport, init) {\n const r = await transport.call({ op: \"proc-identity\" }, Number.POSITIVE_INFINITY, \"proc-identity\");\n const id = r.ok && r.kind === \"json\" ? r.json : null;\n return id ?? { pid: init.pid, ppid: init.ppid ?? 1 };\n}\nfunction signalMasks(m, seeded = { bits: 0 }) {\n const mask = m.sliccSigMask;\n const caught = mask?.(0) ?? -1;\n if (!mask || caught === -1) return null;\n const ignored = mask(1);\n const defaults = seeded.bits & ~ignored & ~caught;\n seeded.bits &= ~defaults;\n return { caught, ignored, restart: mask(2), ...defaults ? { defaults } : {} };\n}\n\n// src/process/wasi/wasi-files.ts\nvar FOLLOW_MS = 2e3;\nvar WasiError = class extends Error {\n code;\n constructor(code2) {\n super(code2);\n this.code = code2;\n }\n};\nvar FileBuffer = class {\n data;\n length = 0;\n dirty = false;\n whole = false;\n from = Infinity;\n to = 0;\n orphaned = false;\n opens = 0;\n fs;\n where;\n ranged;\n watch;\n seen = 0;\n maxFile;\n handle;\n moved;\n bound;\n real;\n constructor(fs, path, empty, maxFile, size, version, watch) {\n this.fs = fs;\n this.where = path;\n this.maxFile = maxFile;\n const { pread, pwrite, truncate } = fs;\n this.watch = watch;\n this.seen = watch?.seen ?? watch?.view.now() ?? 0;\n if (size !== void 0 && pread && pwrite && truncate) {\n const io = {\n pread: async (_, ...rest2) => await this.retried(async () => await pread.call(fs, this.where, ...rest2)),\n pwrite: async (_, ...rest2) => await this.retried(async () => await pwrite.call(fs, this.where, ...rest2)),\n truncate: async (_, size2) => await this.retried(async () => await truncate.call(fs, this.where, size2))\n };\n this.ranged = new RangedFile(io, path, size, version, watch);\n } else if (empty) {\n this.data = new Uint8Array(0);\n this.dirty = true;\n this.whole = true;\n }\n }\n get path() {\n return this.where;\n }\n async emptied(empty) {\n if (empty && this.ranged) await this.truncate(0);\n return this;\n }\n async retried(op) {\n const end = performance.now() + FOLLOW_MS;\n for (; ; ) {\n try {\n return await op();\n } catch (err) {\n const code2 = err.code;\n const followable = code2 === \"ENOENT\" || code2 === \"EIO\";\n if (!followable || performance.now() > end || !await this.moved?.(true)) throw err;\n }\n }\n }\n set path(path) {\n this.where = path;\n if (this.ranged) this.ranged.path = path;\n }\n get isRanged() {\n return this.ranged !== void 0;\n }\n get pin() {\n return this.ranged?.pinnedVersion;\n }\n async keep() {\n if (this.ranged) await this.ranged.pin();\n else await this.load();\n }\n async prefetch() {\n if (this.ranged) await this.ranged.prefetch();\n else await this.load();\n }\n async load() {\n const view = this.watch?.view;\n if (this.data && view && this.watch && !this.dirty) {\n const { now, changed: changed2 } = await watchedChange(this.watch, this.seen, this.path);\n this.seen = now;\n if (changed2) this.data = void 0;\n }\n if (!this.data) {\n this.seen = view?.now() ?? 0;\n this.data = await this.retried(async () => await this.fs.readFile(this.path));\n this.length = this.data.length;\n }\n return this.data;\n }\n spoiled = false;\n spoil() {\n this.spoiled = true;\n this.dirty = false;\n }\n live() {\n if (this.spoiled) throw new WasiError(\"ESTALE\");\n }\n peered = false;\n held() {\n const view = this.watch?.view;\n if (!view) return false;\n return view.peerHeld(this.where) || this.real !== void 0 && view.peerHeld(this.real);\n }\n crowded() {\n if (this.held()) this.peered = true;\n return this.peered;\n }\n async exact() {\n await this.flush();\n const watch = this.watch;\n const size = (await this.retried(async () => await watch.stat(this.where))).size;\n this.peered = this.held();\n if (this.ranged) {\n if (size !== await this.ranged.size()) await this.ranged.reread();\n return void 0;\n }\n if (this.data && size !== this.length) this.data = void 0;\n return this.data ? void 0 : size;\n }\n async wrote(at, bytes) {\n if (this.ranged) {\n await this.ranged.wrote(at, bytes.length);\n return;\n }\n const view = this.watch.view;\n const { now, changed: changed2 } = view.changedSince(this.seen, this.where);\n this.seen = now;\n if (changed2) this.data = void 0;\n if (!this.data) return;\n const end = at + bytes.length;\n this.ensure(end);\n const buf = this.data;\n if (at > this.length) buf.fill(0, this.length, at);\n buf.set(bytes, at);\n this.length = Math.max(this.length, end);\n }\n async size() {\n this.live();\n if (this.crowded()) {\n const known = await this.exact();\n if (known !== void 0) return known;\n }\n if (this.ranged) return await this.ranged.size();\n await this.load();\n return this.length;\n }\n async pread(max, at) {\n this.live();\n if (this.ranged) return await this.ranged.read(at, max);\n const bytes = await this.load();\n const n = Math.max(0, Math.min(max, this.length - at));\n return bytes.subarray(at, at + n);\n }\n fits(end) {\n if (this.maxFile !== void 0 && end > this.maxFile) throw new WasiError(\"EFBIG\");\n }\n async pwrite(bytes, at) {\n this.live();\n if (bytes.length === 0) return 0;\n const end = at + bytes.length;\n this.fits(end);\n const { pwrite } = this.fs;\n if (pwrite && this.crowded() && end > await this.size()) {\n const copy = bytes.slice();\n await this.retried(async () => await pwrite.call(this.fs, this.where, at, copy, true));\n await this.wrote(at, bytes);\n return bytes.length;\n }\n this.dirty = true;\n if (this.ranged) {\n await this.ranged.write(at, bytes);\n return bytes.length;\n }\n await this.load();\n this.ensure(end);\n const buf = this.data;\n this.from = Math.min(this.from, at, this.length);\n this.to = Math.max(this.to, end);\n if (at > this.length) buf.fill(0, this.length, at);\n buf.set(bytes, at);\n this.length = Math.max(this.length, end);\n return bytes.length;\n }\n async append(bytes) {\n this.live();\n const { append } = this.fs;\n if (!append || this.orphaned) return void 0;\n await this.moved?.(false);\n await this.flush();\n const end = await this.retried(async () => await append.call(this.fs, this.path, bytes));\n if (!this.ranged) {\n this.data = void 0;\n this.length = 0;\n }\n return end;\n }\n async truncate(size) {\n this.live();\n this.fits(size);\n this.dirty = true;\n if (this.ranged) {\n this.ranged.truncate(size);\n return;\n }\n await this.load();\n this.ensure(size);\n this.whole = true;\n if (size > this.length) this.data.fill(0, this.length, size);\n this.length = size;\n }\n ensure(need) {\n const cur = this.data;\n if (cur.length >= need) return;\n const grown = new Uint8Array(Math.max(need, cur.length * 2, 4096));\n grown.set(cur.subarray(0, this.length));\n this.data = grown;\n }\n async orphan() {\n this.orphaned = true;\n await this.ranged?.pin();\n }\n async reread() {\n if (this.dirty || this.orphaned) return;\n if (this.ranged) await this.ranged.reread();\n else this.data = void 0;\n }\n isOrphan() {\n return this.orphaned;\n }\n isDirty() {\n return this.dirty;\n }\n async contents() {\n this.live();\n if (this.ranged) return await this.ranged.read(0, await this.ranged.size());\n return (await this.load()).slice(0, this.length);\n }\n async flush() {\n if (this.orphaned || !this.dirty) return;\n await this.moved?.(false);\n if (this.ranged) await this.ranged.flush();\n else if (!this.data) return;\n else if (this.whole || !this.fs.pwrite) {\n const whole = this.data.slice(0, this.length);\n await this.retried(async () => await this.fs.writeFile(this.path, whole, true));\n } else {\n const { pwrite } = this.fs;\n const run = this.data.slice(this.from, this.to);\n await this.retried(async () => await pwrite.call(this.fs, this.path, this.from, run, true));\n }\n this.dirty = false;\n this.whole = false;\n this.from = Infinity;\n this.to = 0;\n }\n};\nvar LocalFile = class {\n offset = 0;\n refs = 1;\n ino;\n buffer;\n readable;\n writable;\n append;\n constructor(buffer, readable, writable, append) {\n this.buffer = buffer;\n this.readable = readable;\n this.writable = writable;\n this.append = append;\n }\n get path() {\n return this.buffer.path;\n }\n async size() {\n return await this.buffer.size();\n }\n async pread(max, at) {\n return await this.buffer.pread(max, at);\n }\n async read(max) {\n const out = await this.buffer.pread(max, this.offset);\n this.offset += out.length;\n return out;\n }\n async pwrite(bytes, at) {\n return await this.buffer.pwrite(bytes, at);\n }\n async write(bytes) {\n if (this.append && bytes.length > 0) {\n this.buffer.fits(await this.buffer.size() + bytes.length);\n const end = await this.buffer.append(bytes);\n if (end !== void 0) {\n this.offset = end;\n return bytes.length;\n }\n }\n if (this.append) this.offset = await this.buffer.size();\n const n = await this.buffer.pwrite(bytes, this.offset);\n this.offset += n;\n return n;\n }\n async truncate(size) {\n await this.buffer.truncate(size);\n }\n async flush() {\n await this.buffer.flush();\n }\n};\nfunction normalize(path) {\n const out = [];\n for (const seg of path.split(\"/\")) {\n if (seg === \"\" || seg === \".\") continue;\n if (seg === \"..\") out.pop();\n else out.push(seg);\n }\n return `/${out.join(\"/\")}`;\n}\nvar MAX_LINKS = 40;\nasync function physical(fs, path) {\n let done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n let hops = 0;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \"..\") {\n done.pop();\n continue;\n }\n if (!todo.includes(\"..\")) {\n done.push(part);\n continue;\n }\n const at = `/${[...done, part].join(\"/\")}`;\n const st = await fs.lstat(at);\n if (st.isSymbolicLink) {\n if (++hops > MAX_LINKS) throw new WasiError(\"ELOOP\");\n if (fs.links) await fs.access?.(at, 0, \"follow\", true);\n const target = await fs.readlink(at);\n if (target.startsWith(\"/\")) done = [];\n todo = [...target.split(\"/\").filter((p) => p !== \"\" && p !== \".\"), ...todo];\n } else if (!st.isDirectory) {\n throw new WasiError(\"ENOTDIR\");\n } else {\n done.push(part);\n }\n }\n return `/${done.join(\"/\")}`;\n}\nasync function realOf(fs, path) {\n let done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n let hops = 0;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \"..\") {\n done.pop();\n continue;\n }\n const at = `/${[...done, part].join(\"/\")}`;\n if (!(await fs.lstat(at)).isSymbolicLink) {\n done.push(part);\n continue;\n }\n if (++hops > MAX_LINKS) throw new WasiError(\"ELOOP\");\n const target = await fs.readlink(at);\n if (target.startsWith(\"/\")) done = [];\n todo = [...target.split(\"/\").filter((p) => p !== \"\" && p !== \".\"), ...todo];\n }\n return `/${done.join(\"/\")}`;\n}\nfunction resolveUnder(dir, path) {\n return normalize(path.startsWith(\"/\") ? path : `${dir}/${path}`);\n}\nfunction pathInode(path) {\n let h = 0xcbf29ce484222325n;\n for (let i = 0; i < path.length; i++) {\n h ^= BigInt(path.charCodeAt(i));\n h = h * 0x100000001b3n & 0xffffffffffffffffn;\n }\n return h;\n}\nvar MISS_TTL_MS = 20;\nvar CACHE_CAP = 8192;\nvar FS_GEN = 4;\nvar CRED_GEN = 5;\nvar UMASK = 6;\nvar RING2 = 8;\nvar RING_SIZE2 = 64;\nvar SLOT2 = 3;\nvar FD_RING = RING2 + RING_SIZE2 * SLOT2;\nvar FD_RING_SIZE = 64;\nvar SHARED_IDS_BYTES = (FD_RING + FD_RING_SIZE * 2) * 4;\nfunction inoKey(st) {\n return \"ino\" in st && typeof st.ino === \"number\" ? st.ino % 4294967296 | 0 : 0;\n}\nfunction pathHash(path) {\n let h = 2166136261;\n for (let i = 0; i < path.length; i++) h = Math.imul(h ^ path.charCodeAt(i), 16777619);\n return h === 0 ? 1 : h;\n}\nvar StatCache = class {\n stats = /* @__PURE__ */ new Map();\n lstats = /* @__PURE__ */ new Map();\n byHash = /* @__PURE__ */ new Map();\n byIno = /* @__PURE__ */ new Map();\n missed = /* @__PURE__ */ new Map();\n shared;\n seen;\n constructor(shared) {\n this.shared = shared;\n this.seen = shared ? Atomics.load(shared, FS_GEN) : 0;\n }\n put(map, path, entry) {\n if (this.stats.size + this.lstats.size + this.byHash.size + this.byIno.size >= CACHE_CAP)\n this.clear();\n map.set(path, entry);\n if (\"until\" in entry) {\n const paths = this.missed.get(map) ?? /* @__PURE__ */ new Set();\n paths.add(path);\n this.missed.set(map, paths);\n }\n if (!this.shared) return;\n index(this.byHash, pathHash(path), path);\n const ino = inoKey(entry);\n if (ino !== 0) index(this.byIno, ino, path);\n }\n fresh() {\n if (!this.shared) return;\n const now = Atomics.load(this.shared, FS_GEN);\n if (now === this.seen) return;\n this.replay(now);\n this.seen = now;\n }\n changed(path, ino = 0) {\n const key = ino % 4294967296 | 0;\n if (this.shared) {\n const g = this.publish(this.shared, path === void 0 ? 0 : pathHash(path), key);\n this.replay(g - 1);\n this.seen = g;\n if (path === void 0) this.clear();\n else this.drop(pathHash(path), key);\n }\n if (path === void 0) return;\n this.stats.delete(path);\n this.lstats.delete(path);\n }\n mutated(paths, ino = 0) {\n const key = ino % 4294967296 | 0;\n if (paths.length === 0 || !this.shared) this.clear();\n if (!this.shared) return;\n for (const [i, hash] of (paths.length > 0 ? paths.map(pathHash) : [0]).entries()) {\n const g = this.publish(this.shared, hash, i === 0 ? key : 0);\n if (paths.length > 0) this.replay(g - 1);\n this.seen = g;\n }\n if (paths.length === 0) return;\n for (const [i, path] of paths.entries()) {\n this.stats.delete(path);\n this.lstats.delete(path);\n this.drop(pathHash(path), i === 0 ? key : 0);\n }\n this.forgetMisses();\n }\n async inoOf(path, look) {\n if (!this.shared) return 0;\n this.fresh();\n const hit = this.stats.get(path);\n if (hit && \"ino\" in hit && typeof hit.ino === \"number\") return hit.ino;\n try {\n return (await look()).ino ?? 0;\n } catch {\n return 0;\n }\n }\n publish(shared, hash, ino) {\n const g = Atomics.add(shared, FS_GEN, 1) + 1;\n const at = RING2 + g % RING_SIZE2 * SLOT2;\n Atomics.store(shared, at, 0);\n Atomics.store(shared, at + 1, hash);\n Atomics.store(shared, at + 2, ino);\n Atomics.store(shared, at, g);\n return g;\n }\n replay(upTo) {\n const shared = this.shared;\n const missed = [];\n for (let g = this.seen + 1; g <= upTo && upTo - this.seen <= RING_SIZE2; g++) {\n const at = RING2 + g % RING_SIZE2 * SLOT2;\n const tag = Atomics.load(shared, at);\n const hash = Atomics.load(shared, at + 1);\n const ino = Atomics.load(shared, at + 2);\n if (tag !== g || hash === 0 || Atomics.load(shared, at) !== g) break;\n missed.push([hash, ino]);\n }\n if (missed.length < upTo - this.seen) this.clear();\n else for (const [hash, ino] of missed) this.drop(hash, ino);\n }\n drop(hash, ino) {\n const paths = [\n ...this.byHash.get(hash) ?? [],\n ...ino === 0 ? [] : this.byIno.get(ino) ?? []\n ];\n for (const path of paths) {\n this.stats.delete(path);\n this.lstats.delete(path);\n }\n this.byHash.delete(hash);\n if (ino !== 0) this.byIno.delete(ino);\n }\n forgetMisses() {\n for (const [map, paths] of this.missed) {\n for (const path of paths) if (\"until\" in (map.get(path) ?? {})) map.delete(path);\n }\n this.missed.clear();\n }\n clear() {\n this.missed.clear();\n this.stats.clear();\n this.lstats.clear();\n this.byHash.clear();\n this.byIno.clear();\n }\n};\nfunction index(map, key, path) {\n const paths = map.get(key) ?? /* @__PURE__ */ new Set();\n paths.add(path);\n map.set(key, paths);\n}\nvar SEEN_CAP = 4096;\nvar SeenAt = class {\n view;\n lstats;\n links = /* @__PURE__ */ new Map();\n stats = /* @__PURE__ */ new Map();\n constructor(view, lstats) {\n this.view = view;\n this.lstats = lstats;\n }\n of(map) {\n return map === this.lstats ? this.links : this.stats;\n }\n lstat(path) {\n return this.links.get(path);\n }\n saw(map, path, gen) {\n const seen = this.of(map);\n if (seen.size >= SEEN_CAP) seen.clear();\n seen.set(path, gen);\n }\n changed(map, path) {\n if (this.view === void 0) return false;\n const seen = this.of(map);\n const gen = seen.get(path);\n if (gen === void 0) return true;\n const since = this.view.changedSince(gen, path);\n if (!since.changed) seen.set(path, since.now);\n return since.changed;\n }\n};\nfunction goneAbove(maps, live, path) {\n for (let at = path.lastIndexOf(\"/\"); at > 0; at = path.lastIndexOf(\"/\", at - 1)) {\n const up = path.slice(0, at);\n for (const map of maps) {\n const hit = map.get(up);\n const code2 = hit && \"until\" in hit ? hit.error.code : void 0;\n if (hit && \"until\" in hit && code2 === \"ENOENT\" && live(hit, up)) return hit;\n }\n }\n return void 0;\n}\nvar remember = (cache, seen, blind, fill) => (path, made) => {\n if (!made || blind) return made;\n const { seen: at, ...st } = made;\n fill(st);\n cache.put(cache.stats, path, st);\n if (at !== void 0) seen.saw(cache.stats, path, at);\n return made;\n};\nfunction copying(bridge, mutating, entry) {\n const { copy } = bridge;\n if (!copy) return {};\n return {\n copy: async (from, to, mode, exclusive) => await mutating(async () => await copy.call(bridge, from, to, mode, exclusive), ...entry(to))\n };\n}\nvar Fills = class {\n at = /* @__PURE__ */ new WeakMap();\n view;\n now;\n constructor(view, now) {\n this.view = view;\n this.now = now;\n }\n set(entry, at = this.now()) {\n this.at.set(entry, at);\n }\n young(entry) {\n if (!this.view?.foreign()) return true;\n return this.now() - (this.at.get(entry) ?? Number.NEGATIVE_INFINITY) < SHARED_TTL_MS;\n }\n};\nfunction listed({ cache, seen, filled }, p, list, gen, asked) {\n const base = p === \"/\" ? \"\" : p;\n for (const [name2, st] of list) {\n if (!st) continue;\n filled.set(st, asked);\n const at = `${base}/${name2}`;\n cache.put(cache.lstats, at, st);\n if (gen !== void 0) seen.saw(cache.lstats, at, gen);\n if (st.isSymbolicLink) continue;\n cache.put(cache.stats, at, st);\n if (gen !== void 0) seen.saw(cache.stats, at, gen);\n }\n}\nasync function fetched({\n view,\n now,\n seen,\n filled,\n cache\n}, map, path, get) {\n const gen = view?.now();\n const asked = now();\n let hit;\n try {\n hit = await get();\n if (gen !== void 0) seen.saw(map, path, gen);\n } catch (e) {\n hit = { error: e, until: asked + MISS_TTL_MS, ...gen !== void 0 ? { gen } : {} };\n }\n filled.set(hit, asked);\n cache.put(map, path, hit);\n return hit;\n}\nfunction cachingBridge(bridge, now = () => performance.now(), shared) {\n const blind = shared !== void 0 && shared.length * 4 < SHARED_IDS_BYTES;\n const cache = new StatCache(blind ? void 0 : shared);\n const { stats, lstats } = cache;\n const view = bridge.changes;\n const filled = new Fills(view, now);\n const young = (entry2) => filled.young(entry2);\n const live = (miss, path) => miss.until > now() && young(miss) && (view === void 0 || miss.gen === void 0 || !view.changedSince(miss.gen, path).changed);\n const seen = new SeenAt(view, lstats);\n const kept = remember(cache, seen, blind, (entry2) => filled.set(entry2));\n const gone = (path) => goneAbove([lstats, stats], live, path);\n const usable = (map, path) => {\n const hit = map.get(path);\n if (hit === void 0) return void 0;\n if (\"until\" in hit) return live(hit, path) ? hit : void 0;\n return young(hit) && !seen.changed(map, path) ? hit : void 0;\n };\n const cached = async (map, path, get) => {\n if (blind) return await get();\n cache.fresh();\n let hit = usable(map, path);\n if (hit === void 0) {\n const missing3 = gone(path);\n if (missing3) throw missing3.error;\n hit = await fetched({ view, now, seen, filled, cache }, map, path, get);\n }\n if (\"until\" in hit) throw hit.error;\n return hit;\n };\n const invalidate = () => cache.mutated([]);\n const touched = (path, ino) => cache.changed(path, ino);\n const { chown: chown2 } = bridge;\n const mutating = async (op, ...paths) => {\n try {\n return await op();\n } finally {\n cache.mutated(paths);\n }\n };\n let exact = false;\n const threaded = async () => {\n if (blind || shared === void 0 || !bridge.identify) return;\n exact = true;\n await bridge.identify();\n };\n const identified = async (p, op, also) => {\n try {\n return await op();\n } finally {\n const st = await bridge.identified?.() ?? null;\n if (st) cache.mutated([p, ...also], st.ino);\n else cache.mutated([]);\n }\n };\n const relabeling = async (p, op) => {\n if (exact || !bridge.identifyNext) return await rewriting(p, op);\n await bridge.identifyNext();\n try {\n return await op();\n } finally {\n const st = await bridge.identified?.() ?? null;\n if (st) cache.mutated([p], st.ino);\n else cache.mutated([]);\n }\n };\n const rewriting = async (p, op, ...also) => {\n if (exact) return await identified(p, op, also);\n const ino = await cache.inoOf(p, async () => await bridge.stat(p));\n try {\n return await op();\n } finally {\n cache.mutated([p, ...also], ino);\n }\n };\n const entry = (p) => [p, p.slice(0, p.lastIndexOf(\"/\")) || \"/\"];\n return {\n ...bridge.changes ? { changes: bridge.changes } : {},\n ...bridge.renames ? { renames: bridge.renames.bind(bridge) } : {},\n readFile: async (p) => await bridge.readFile(p),\n readdir: async (p) => await bridge.readdir(p),\n readdirStat: async (p) => {\n const gen = view?.now();\n const asked = now();\n const list = await bridge.readdirStat(p);\n if (!blind) listed({ cache, seen, filled }, p, list, gen, asked);\n return list;\n },\n readlink: async (p) => {\n if (!blind) cache.fresh();\n const known = blind ? void 0 : lstats.get(p);\n const gen = seen.lstat(p);\n const current2 = view !== void 0 && gen !== void 0 && !view.changedSince(gen, p).changed;\n if (known && current2 && !(\"until\" in known) && young(known) && !known.isSymbolicLink) {\n throw syncError(\"EINVAL\", `'${p}' is not a symbolic link`);\n }\n return await bridge.readlink(p);\n },\n stat: async (p) => await cached(stats, p, async () => await bridge.stat(p)),\n lstat: async (p) => await cached(lstats, p, async () => await bridge.lstat(p)),\n exists: async (p) => {\n try {\n await cached(stats, p, async () => await bridge.stat(p));\n return true;\n } catch {\n return false;\n }\n },\n writeFile: async (p, bytes, open) => await rewriting(p, async () => await bridge.writeFile(p, bytes, open), ...entry(p).slice(1)),\n mkdir: async (p) => await mutating(async () => await bridge.mkdir(p), ...entry(p)),\n rm: async (p) => await mutating(async () => await bridge.rm(p)),\n rename: async (from, to) => await mutating(async () => await bridge.rename(from, to)),\n link: async (from, to, follow2) => await mutating(async () => await bridge.link(from, to, follow2)),\n unlink: async (p) => await mutating(async () => await bridge.unlink(p)),\n rmdir: async (p) => await mutating(async () => await bridge.rmdir(p)),\n symlink: async (target, link) => await mutating(async () => await bridge.symlink(target, link), ...entry(link)),\n chmod: async (p, mode) => await relabeling(p, async () => await bridge.chmod(p, mode)),\n utimes: async (p, a, m, now2) => await relabeling(p, async () => await bridge.utimes(p, a, m, now2)),\n lutimes: async (p, a, m, now2) => await mutating(async () => await bridge.lutimes(p, a, m, now2)),\n ...bridge.hold ? { hold: bridge.hold.bind(bridge) } : {},\n ...bridge.heldReal ? { heldReal: bridge.heldReal.bind(bridge) } : {},\n ...bridge.access ? { access: bridge.access.bind(bridge) } : {},\n ...bridge.kept ? { kept: bridge.kept.bind(bridge) } : {},\n ...bridge.keptStat ? { keptStat: bridge.keptStat.bind(bridge) } : {},\n ...bridge.pinned ? { pinned: async (handle) => await pinnedIo(bridge, handle, rewriting) } : {},\n ...bridge.create ? {\n create: async (p, mode, opening) => kept(\n p,\n await mutating(async () => await bridge.create?.(p, mode, opening), ...entry(p))\n )\n } : {},\n ...bridge.mkfifo ? {\n mkfifo: async (p, mode) => await mutating(async () => await bridge.mkfifo?.(p, mode), ...entry(p))\n } : {},\n ...copying(bridge, mutating, entry),\n ...chown2 ? {\n chown: async (p, ...rest2) => await relabeling(p, async () => await chown2.call(bridge, p, ...rest2))\n } : {},\n ...bridge.pread && bridge.pwrite && bridge.truncate ? {\n pread: bridge.pread.bind(bridge),\n pwrite: async (p, at, bytes, transfer) => await rewriting(p, async () => await bridge.pwrite?.(p, at, bytes, transfer)),\n truncate: async (p, size) => await rewriting(p, async () => await bridge.truncate?.(p, size))\n } : {},\n ...bridge.append ? {\n append: async (p, bytes) => await rewriting(p, async () => await bridge.append(p, bytes))\n } : {},\n ...bridge.owners ? { owners: true } : {},\n ...bridge.links ? { links: true } : {},\n invalidate,\n touched,\n threaded\n };\n}\nasync function pinnedIo(bridge, handle, rewriting) {\n const io = await bridge.pinned(handle);\n const { pread, pwrite, truncate } = io;\n return {\n readFile: async (p) => await io.readFile(p),\n writeFile: async (p, bytes, open) => await rewriting(p, async () => await io.writeFile(p, bytes, open)),\n pread: async (p, at, n, version) => await pread(p, at, n, version),\n pwrite: async (p, at, bytes, transfer) => await rewriting(p, async () => await pwrite(p, at, bytes, transfer)),\n truncate: async (p, size) => await rewriting(p, async () => await truncate(p, size)),\n ...io.append ? {\n append: async (p, bytes) => await rewriting(p, async () => await io.append(p, bytes))\n } : {}\n };\n}\n\n// src/fs/physical-path.ts\nvar MAX_HOPS2 = 40;\nfunction start(path) {\n return { done: [], todo: path.split(\"/\").filter((p) => p !== \"\"), hops: 0 };\n}\nfunction next(walk2) {\n while (walk2.todo.length > 0) {\n const part = walk2.todo.shift();\n if (part === \".\") continue;\n if (part === \"..\") {\n walk2.done.pop();\n continue;\n }\n return part;\n }\n return void 0;\n}\nfunction lexical(path) {\n const walk2 = start(path);\n for (let part = next(walk2); part !== void 0; part = next(walk2)) walk2.done.push(part);\n return `/${walk2.done.join(\"/\")}`;\n}\nfunction rest(walk2, part) {\n return lexical(`/${[...walk2.done, part, ...walk2.todo].join(\"/\")}`);\n}\nfunction follow(walk2, target) {\n if (++walk2.hops > MAX_HOPS2) return false;\n if (target.startsWith(\"/\")) walk2.done.length = 0;\n walk2.todo = [...target.split(\"/\").filter((p) => p !== \"\"), ...walk2.todo];\n return true;\n}\nasync function physicalPath(fs, path) {\n const walk2 = start(path);\n for (let part = next(walk2); part !== void 0; part = next(walk2)) {\n const at = `/${[...walk2.done, part].join(\"/\")}`;\n let target;\n try {\n target = (await fs.lstat(at)).isSymbolicLink ? await fs.readlink(at) : void 0;\n } catch {\n return rest(walk2, part);\n }\n if (target === void 0) walk2.done.push(part);\n else if (!follow(walk2, target)) {\n throw Object.assign(new Error(\"too many levels of symbolic links\"), { code: \"ELOOP\" });\n }\n }\n return `/${walk2.done.join(\"/\")}`;\n}\nasync function physicalLeaf(fs, path) {\n const walk2 = start(path);\n for (let part = next(walk2); part !== void 0; part = next(walk2)) {\n const at = `/${[...walk2.done, part].join(\"/\")}`;\n let target;\n try {\n target = (await fs.lstat(at)).isSymbolicLink ? await fs.readlink(at) : void 0;\n } catch {\n const tail = walk2.todo;\n return tail.some((p) => p === \".\" || p === \"..\") ? void 0 : [at, ...tail].join(\"/\");\n }\n if (target === void 0) walk2.done.push(part);\n else if (!follow(walk2, target)) return void 0;\n }\n return `/${walk2.done.join(\"/\")}`;\n}\n\n// src/process/js/js-kernel.ts\nvar JsCallError = class extends Error {\n code;\n detail;\n dev;\n constructor(code2, what, detail) {\n super(`${what}: ${code2}`);\n this.name = \"JsCallError\";\n this.code = code2;\n this.detail = detail;\n }\n};\n\n// src/process/js/js-io.ts\nvar CHUNK = 64 * 1024;\nvar MAX_IO = 1024 * 1024;\nvar MAX_PREAD = 16 * 1024 * 1024;\n\n// src/process/js/js-dev.ts\nvar DEV_READ_MAX = 64 * 1024 * 1024;\nvar DEVICES = [\"null\", \"zero\", \"full\", \"random\", \"urandom\"];\nvar STDIO = [\"stdin\", \"stdout\", \"stderr\"];\nvar SELF_FD = \"/proc/self/fd\";\nvar S_IFMT = 61440;\nvar DIR = 16384;\nvar LINK = 40960;\nvar CHAR = 8192;\nvar BORN2 = Date.now();\nvar CHAR_KINDS = /* @__PURE__ */ new Set([\n \"device\",\n \"tty\",\n \"clipboard\",\n \"embedder\",\n \"sealed\"\n]);\nfunction inDev(abs) {\n return abs.startsWith(\"/dev\") && (abs.length === 4 || abs[4] === \"/\") && !inShm(abs);\n}\nfunction missing(path) {\n throw new JsCallError(\"ENOENT\", path);\n}\nfunction nodeStat(mode, size = 0, owner) {\n return {\n isFile: false,\n isDirectory: (mode & S_IFMT) === DIR,\n isSymbolicLink: (mode & S_IFMT) === LINK,\n size,\n mode,\n mtimeMs: BORN2,\n atimeMs: BORN2,\n ctimeMs: BORN2,\n nlink: 1,\n uid: owner?.uid ?? 0,\n gid: owner?.gid ?? 0\n };\n}\nvar SERIAL = \"/dev/serial\";\nfunction serialNamed(name2) {\n return DEVICE_NAME.test(name2) || name2 === \"serial\" || name2.startsWith(\"serial/\");\n}\nfunction serialNode(abs, nodes) {\n const node = nodes.find((n) => n.path === abs);\n if (node) return { kind: \"serial\", node };\n const links = nodes.some((n) => n.links.length > 0);\n if (links && (abs === SERIAL || abs === BY_ID)) return { kind: \"dir\", mode: DIR | 493 };\n const owner = nodes.find((n) => n.links.includes(abs));\n if (owner) return { kind: \"devlink\", target: `../..${owner.path.slice(4)}`, node: owner };\n return void 0;\n}\nfunction* deviceNodes() {\n return yield { op: \"fd-dev-nodes\" };\n}\nfunction* lookup(abs) {\n if (abs === \"/dev\") return { kind: \"dir\", mode: DIR | 493 };\n const name2 = abs.slice(\"/dev/\".length);\n if (serialNamed(name2)) {\n const found = serialNode(abs, yield* deviceNodes());\n if (found) return found;\n }\n if (DEVICES.includes(name2)) return { kind: \"device\" };\n if (name2 === \"tty\") return { kind: \"tty\" };\n if (name2 === \"clipboard\") return { kind: \"clipboard\" };\n if (name2 === \"embedder\") return { kind: \"embedder\" };\n if (name2 === \"sealed\") return { kind: \"sealed\" };\n const std = STDIO.indexOf(name2);\n if (std >= 0) return { kind: \"link\", target: `${SELF_FD}/${std}`, fd: std };\n if (name2 === \"fd\") return { kind: \"link\", target: SELF_FD };\n const fd = /^fd\\/(\\d+)$/.exec(name2)?.[1];\n if (fd !== void 0) return { kind: \"fd\", fd: Number(fd) };\n if (/^tty\\d+$/.test(name2)) {\n const names2 = yield { op: \"fd-tty-names\" };\n if (names2.includes(abs)) return { kind: \"terminal\", name: abs };\n }\n if (name2 === \"pts\") return { kind: \"dir\", mode: DIR | 365 };\n const pts = /^pts\\/(\\d+)$/.exec(name2)?.[1];\n if (pts !== void 0) {\n const open = yield { op: \"pty-list\" };\n if (open.includes(Number(pts))) return { kind: \"terminal\", name: abs, pts: Number(pts) };\n }\n return missing(abs);\n}\nfunction* fdInfo(fd, path) {\n try {\n return yield { op: \"fd-info\", fd };\n } catch (err) {\n if (err instanceof JsCallError && err.code === \"EBADF\") return missing(path);\n throw err;\n }\n}\nfunction* pathStat(path) {\n const s = parseSyncFsStat(yield { op: \"stat\", path });\n if (!s) throw new JsCallError(\"EIO\", \"stat\");\n return s;\n}\nfunction* terminalStat(name2) {\n const owner = yield { op: \"fd-tty-owner\", name: name2 };\n if (owner) return nodeStat(CHAR | (owner.mode ?? 400), 0, owner);\n return nodeStat(CHAR | (name2.startsWith(\"/dev/pts/\") ? 400 : 438));\n}\nfunction* fdStat(fd, path) {\n const info = yield* fdInfo(fd, path);\n if (info.meta && \"dir\" in info.meta) return yield* pathStat(info.meta.dir);\n if (info.kind === \"file\") {\n const file = yield { op: \"fd-vfs-stat\", fd };\n if (file.orphan) return { ...nodeStat(33152, file.size), isFile: true };\n const st = yield* pathStat(file.path);\n return { ...st, size: file.size };\n }\n if (info.terminal) return yield* terminalStat(info.terminal);\n if (CHAR_KINDS.has(info.kind)) return nodeStat(CHAR | 438);\n if (info.kind === \"socket\") return nodeStat(49663);\n return nodeStat(4480);\n}\nfunction* fdTarget(fd, path) {\n const info = yield* fdInfo(fd, path);\n if (info.meta && \"dir\" in info.meta) return info.meta.dir;\n if (info.kind === \"file\") return (yield { op: \"fd-vfs-stat\", fd }).path;\n if (info.terminal) return info.terminal;\n if (info.meta && \"device\" in info.meta) return `/dev/${info.meta.device}`;\n if (info.kind === \"clipboard\" || info.kind === \"sealed\" || info.kind === \"embedder\")\n return `/dev/${info.kind}`;\n return `${info.kind === \"socket\" ? \"socket\" : \"pipe\"}:[${fd}]`;\n}\nfunction devFdStat(fd) {\n return fdStat(fd, `/dev/fd/${fd}`);\n}\nfunction serialStat(node) {\n return {\n ...nodeStat(CHAR | node.mode, 0, node),\n atimeMs: node.atimeMs,\n mtimeMs: node.mtimeMs,\n ctimeMs: node.ctimeMs\n };\n}\nfunction linkStat(target) {\n return nodeStat(LINK | 511, target.length);\n}\nfunction* devStat(abs, follow2) {\n const node = yield* lookup(abs);\n switch (node.kind) {\n case \"dir\":\n return nodeStat(node.mode);\n case \"device\":\n case \"tty\":\n case \"clipboard\":\n case \"embedder\":\n case \"sealed\":\n return nodeStat(CHAR | 438);\n case \"terminal\":\n return yield* terminalStat(node.name);\n case \"serial\":\n return serialStat(node.node);\n case \"devlink\":\n return follow2 ? serialStat(node.node) : linkStat(node.target);\n case \"link\":\n if (!follow2) return linkStat(node.target);\n return node.fd === void 0 ? nodeStat(DIR | 365) : yield* fdStat(node.fd, abs);\n case \"fd\":\n return follow2 ? yield* fdStat(node.fd, abs) : linkStat(yield* fdTarget(node.fd, abs));\n }\n}\nfunction* devMeta(abs, follow2, change) {\n if (!abs.startsWith(\"/dev/\") || !serialNamed(abs.slice(5))) return false;\n const found = serialNode(abs, yield* deviceNodes());\n if (found?.kind !== \"serial\" && !(found?.kind === \"devlink\" && follow2)) return false;\n yield { op: \"fd-dev-meta\", path: found.node.path, ...change };\n return true;\n}\nfunction* devReadlink(abs) {\n const node = yield* lookup(abs);\n if (node.kind === \"link\" || node.kind === \"devlink\") return node.target;\n if (node.kind === \"fd\") return yield* fdTarget(node.fd, abs);\n throw new JsCallError(\"EINVAL\", abs);\n}\nfunction* devResolveTarget(abs) {\n const node = yield* lookup(abs);\n if (node.kind === \"fd\") return yield* fdTarget(node.fd, abs);\n if (node.kind === \"link\" && node.fd !== void 0) return yield* fdTarget(node.fd, abs);\n return void 0;\n}\nfunction* devReaddir(abs) {\n if (abs === \"/dev/fd\") {\n const fds = yield { op: \"fd-list\" };\n return fds.map(({ fd }) => String(fd));\n }\n if (abs === \"/dev/pts\") {\n const open = yield { op: \"pty-list\" };\n return open.map(String).sort();\n }\n const node = yield* lookup(abs);\n if (node.kind !== \"dir\") throw new JsCallError(\"ENOTDIR\", abs);\n if (abs === SERIAL || abs === BY_ID) {\n const nodes2 = yield* deviceNodes();\n if (abs === SERIAL) return [\"by-id\"];\n return nodes2.flatMap((n) => n.links.map((l) => l.slice(BY_ID.length + 1))).sort();\n }\n const names2 = yield { op: \"fd-tty-names\" };\n const ttys = names2.filter((n) => /^\\/dev\\/tty\\d+$/.test(n)).map((n) => n.slice(5));\n const nodes = yield* deviceNodes();\n const serial = nodes.map((n) => n.path.slice(5));\n if (nodes.some((n) => n.links.length > 0)) serial.push(\"serial\");\n return [\n ...serial,\n ...DEVICES,\n \"clipboard\",\n \"embedder\",\n \"sealed\",\n \"tty\",\n \"fd\",\n \"pts\",\n \"shm\",\n ...STDIO,\n ...ttys\n ].sort();\n}\nasync function devSync(kernel, step) {\n let next2 = step.next();\n while (!next2.done) {\n let answer;\n try {\n answer = { value: await kernel.json(next2.value) };\n } catch (error) {\n answer = { error };\n }\n next2 = \"value\" in answer ? step.next(answer.value) : step.throw(answer.error);\n }\n return next2.value;\n}\nvar WHEN = {\n now: IOCTL.TCSETS2,\n drain: IOCTL.TCSETSW2,\n flush: IOCTL.TCSETSF2\n};\n\n// src/process/wasi/slicc-lock.ts\nvar F_GETLK = 12;\nvar F_SETLK = 13;\nvar F_SETLKW = 14;\nvar F_RDLCK = 0;\nvar F_WRLCK = 1;\nvar F_UNLCK = 2;\nvar SEEK_SET = 0;\nvar SEEK_CUR = 1;\nvar SEEK_END = 2;\nvar LOCK_NB = 4;\nvar FLOCK_OPS = { 1: \"shared\", 2: \"exclusive\", 8: \"unlock\" };\nfunction kindOf(type) {\n if (type === F_RDLCK) return \"read\";\n if (type === F_WRLCK) return \"write\";\n if (type === F_UNLCK) return \"unlock\";\n throw new WasiError(\"EINVAL\");\n}\nasync function baseOf2(file, whence) {\n if (whence === SEEK_SET) return 0;\n if (whence === SEEK_CUR) return await file.offset();\n if (whence === SEEK_END) return await file.size();\n throw new WasiError(\"EINVAL\");\n}\nfunction writeHolder(view, at, found) {\n if (!found) {\n view.setInt16(at, F_UNLCK, true);\n return;\n }\n view.setInt16(at, found.kind === \"read\" ? F_RDLCK : F_WRLCK, true);\n view.setInt16(at + 2, SEEK_SET, true);\n view.setBigInt64(at + 8, BigInt(found.start), true);\n view.setBigInt64(at + 16, BigInt(found.len), true);\n view.setInt32(at + 24, found.pid, true);\n}\nfunction lockImports(host) {\n return {\n flock: async (fd, op) => {\n await host.promote(fd);\n const kind = FLOCK_OPS[op & ~LOCK_NB];\n if (!kind) throw new WasiError(\"EINVAL\");\n const shared = await host.calls.flock(fd, kind, kind !== \"unlock\" && (op & LOCK_NB) === 0);\n if (kind !== \"unlock\" && shared === true) await host.reread(fd);\n },\n fcntl_lock: async (fd, cmd, at) => {\n if (cmd !== F_GETLK && cmd !== F_SETLK && cmd !== F_SETLKW) throw new WasiError(\"EINVAL\");\n await host.promote(fd, true);\n const file = await host.file(fd);\n const view = host.mem.view();\n const kind = kindOf(view.getInt16(at, true));\n const start2 = await baseOf2(file, view.getInt16(at + 2, true)) + Number(view.getBigInt64(at + 8, true));\n const len = Number(view.getBigInt64(at + 16, true));\n if (cmd === F_GETLK) {\n if (kind === \"unlock\") throw new WasiError(\"EINVAL\");\n writeHolder(view, at, await host.calls.get(file.target, kind, start2, len));\n return;\n }\n if (kind === \"read\" && file.readable === false || kind === \"write\" && file.writable === false)\n throw new WasiError(\"EBADF\");\n if (kind !== \"write\") await host.flush(file);\n const shared = await host.calls.set(file.target, kind, start2, len, cmd === F_SETLKW);\n if (kind === \"unlock\") return;\n host.locked();\n if (shared === true) await host.reread(fd);\n }\n };\n}\n\n// src/process/wasi/slicc-sem.ts\nvar SEM_CREAT = 1;\nvar SEM_EXCL = 2;\nvar HOW = [\"block\", \"try\", \"timed\"];\nvar NS_PER_MS = 1000000n;\nfunction remainingMs(deadline, now) {\n if (deadline <= now) return 0;\n return Number((deadline - now + NS_PER_MS - 1n) / NS_PER_MS);\n}\nfunction semImports(host) {\n const { mem } = host;\n const call2 = async (req) => await host.o.kernel.call(req);\n const name2 = (ptr, len) => mem.string(ptr, len);\n return {\n sem_open: async (np, nl, oflag, mode, value2, out) => {\n const handle = await call2({\n op: \"sem-open\",\n name: name2(np, nl),\n create: (oflag & SEM_CREAT) !== 0,\n exclusive: (oflag & SEM_EXCL) !== 0,\n mode,\n value: value2\n });\n mem.view().setUint32(out, handle, true);\n },\n sem_close: async (handle) => void await call2({ op: \"sem-close\", handle }),\n sem_unlink: async (np, nl) => void await call2({ op: \"sem-unlink\", name: name2(np, nl) }),\n sem_post: async (handle) => void await call2({ op: \"sem-post\", handle }),\n sem_wait: async (handle, how, clock, deadline) => {\n const kind = HOW[how];\n if (!kind) throw new WasiError(\"EINVAL\");\n let timeoutMs2 = -1;\n if (kind === \"timed\") {\n if (deadline < 0n) throw new WasiError(\"EINVAL\");\n if (clock !== CLOCK.REALTIME && clock !== CLOCK.MONOTONIC) throw new WasiError(\"EINVAL\");\n timeoutMs2 = remainingMs(deadline, host.now(clock));\n }\n await call2({ op: \"sem-wait\", handle, how: kind, timeoutMs: timeoutMs2 });\n },\n sem_getvalue: async (handle, out) => void mem.view().setInt32(out, await call2({ op: \"sem-getvalue\", handle }), true)\n };\n}\n\n// src/process/wasi/wasi-cred.ts\nvar CredCache = class {\n cred;\n stamp = 0;\n fetch;\n shared;\n constructor(fetch, shared) {\n this.fetch = fetch;\n this.shared = shared;\n }\n gen() {\n return this.shared ? Atomics.load(this.shared, CRED_GEN) : 0;\n }\n async get() {\n const gen = this.gen();\n if (this.cred === void 0 || this.stamp !== gen) {\n this.cred = await this.fetch();\n this.stamp = gen;\n }\n return this.cred;\n }\n async change(apply2) {\n const seen = this.gen();\n const cred = await apply2();\n if (!this.shared) {\n this.cred = cred;\n return cred;\n }\n const was = Atomics.add(this.shared, CRED_GEN, 1);\n this.cred = was === seen ? cred : void 0;\n this.stamp = was + 1;\n return cred;\n }\n};\nvar KNOWN = 65536;\nvar LOCKED = 131072;\nvar UNGATED = { quiet: async (fn) => await fn(), deliver: () => {\n} };\nvar UmaskCache = class {\n mask;\n call;\n shared;\n signals;\n constructor(call2, shared, signals = UNGATED) {\n this.call = call2;\n this.shared = shared;\n this.signals = signals;\n }\n async get() {\n const { shared } = this;\n if (!shared) {\n this.mask ??= await this.call();\n return this.mask;\n }\n for (; ; ) {\n const seen = Atomics.load(shared, UMASK);\n if (seen & LOCKED) await atomicsWait(shared, UMASK, seen);\n else if (seen & KNOWN) return seen & 511;\n else {\n const mask = await this.call();\n if (Atomics.compareExchange(shared, UMASK, 0, mask | KNOWN) === 0) return mask;\n }\n }\n }\n async set(mask) {\n try {\n return await this.signals.quiet(async () => await this.change(mask));\n } finally {\n await this.signals.deliver();\n }\n }\n async change(mask) {\n const { shared } = this;\n if (!shared) {\n const old = await this.call(mask);\n this.mask = mask & 511;\n return old;\n }\n const seen = await this.lock(shared);\n let next2 = seen;\n try {\n const old = await this.call(mask);\n next2 = mask & 511 | KNOWN;\n return old;\n } finally {\n Atomics.store(shared, UMASK, next2);\n atomicsNotify(shared, UMASK);\n }\n }\n async lock(shared) {\n for (; ; ) {\n const seen = Atomics.load(shared, UMASK);\n if (seen & LOCKED) await atomicsWait(shared, UMASK, seen);\n else if (Atomics.compareExchange(shared, UMASK, seen, seen | LOCKED) === seen) return seen;\n }\n }\n};\n\n// src/process/wasi/wasi-fds.ts\nvar SYNTHETIC_DIRS = [\"usr\", \"bin\"];\nvar O_NONBLOCK2 = 2048;\nvar O_WRONLY = 1;\nvar O_RDWR = 2;\nvar O_APPEND = 1024;\nfunction stdioAlias(path) {\n const m = /^\\/dev\\/(?:(stdin)|(stdout)|(stderr)|fd\\/(\\d+))$/.exec(path);\n if (!m) return void 0;\n return m[1] ? 0 : m[2] ? 1 : m[3] ? 2 : Number(m[4]);\n}\nvar DEVICE_PATH = /^\\/dev\\/tty(?:USB|ACM)\\d+$/;\nvar SEALED_PATH = \"/dev/sealed\";\nvar CLIPBOARD_PATH = \"/dev/clipboard\";\nvar EMBEDDER_PATH = \"/dev/embedder\";\nfunction deviceOf(path) {\n return deviceAt(path);\n}\nvar NAMED_PATHS = /* @__PURE__ */ new Set([\n SEALED_PATH,\n CLIPBOARD_PATH,\n EMBEDDER_PATH,\n \"/dev/tty\"\n]);\nfunction namedDevice(path) {\n if (deviceOf(path) || stdioAlias(path) !== void 0) return true;\n return NAMED_PATHS.has(path);\n}\nfunction within(path, root) {\n return path === root || path.startsWith(root === \"/\" ? \"/\" : `${root}/`);\n}\nvar WasiFds = class {\n table = /* @__PURE__ */ new Map();\n buffers = /* @__PURE__ */ new Map();\n reported = /* @__PURE__ */ new WeakSet();\n byId = /* @__PURE__ */ new Map();\n ids = /* @__PURE__ */ new Map();\n kernel;\n fs;\n renamesSeen;\n constructor(kernel, fs) {\n this.kernel = kernel;\n this.fs = fs;\n this.renamesSeen = fs.changes?.renames() ?? 0;\n }\n ownRename(seq) {\n if (seq !== void 0 && seq === (this.renamesSeen + 1 | 0)) this.renamesSeen = seq;\n }\n async followRenames(missing3 = false) {\n const view = this.fs.changes;\n const end = missing3 && view ? performance.now() + renameWait(view) : 0;\n const start2 = this.renamesSeen;\n for (; ; ) {\n const now = view?.renames() ?? 0;\n if (now !== this.renamesSeen && this.fs.renames && await this.followTo(now)) return true;\n if (missing3 && this.renamesSeen !== start2) return true;\n const left = end - performance.now();\n if (!view || left <= 0) return false;\n await view.awaitRename(now, left);\n }\n }\n async followTo(now) {\n const held = [...this.buffers].filter(([, b]) => !b.isOrphan()).map(([p]) => p);\n if (held.length === 0) {\n this.renamesSeen = now;\n return false;\n }\n const { now: seen, renames } = await this.fs.renames(\n this.renamesSeen,\n held\n );\n this.renamesSeen = seen;\n for (const [from, to] of renames) await this.renamed(from, to, void 0, true);\n return renames.length > 0;\n }\n async setup(cwd, inherited2, root = false) {\n for (const fd of [0, 1, 2]) this.table.set(fd, await this.stdioEntry(fd));\n const preopens = await this.preopens(cwd, root);\n const top = 3 + preopens.length;\n for (const { fd, kind, flags, device } of inherited2) {\n let at = fd;\n if (fd < top) {\n at = await this.kernel.call({ op: \"fd-dup\", fd, min: top });\n await this.kernel.sys.close(fd);\n }\n if (device) {\n this.table.set(at, deviceEntry(device));\n continue;\n }\n const nonblock = ((flags ?? 0) & O_NONBLOCK2) !== 0;\n this.table.set(at, { ...kernelEntry(), nonblock, ...kind ? { kind } : {} });\n }\n for (const [i, entry] of preopens.entries()) {\n await this.kernel.call({ op: \"fd-reserve\", fd: 3 + i, meta: metaOf(entry) });\n this.table.set(3 + i, entry);\n }\n }\n async adoptCopy(fd) {\n const at = await this.kernel.call({ op: \"fd-dup\", fd, min: 3 });\n this.table.set(at, await this.stdioEntry(at));\n return at;\n }\n async preopenAt(path, name2) {\n return await this.install({ type: \"dir\", path: normalize(path), preopen: name2 });\n }\n async preopens(cwd, root) {\n const here = normalize(cwd);\n const dot = { type: \"dir\", path: here, preopen: \".\" };\n const out = [dot];\n let names2 = [];\n try {\n names2 = await this.fs.readdir(\"/\");\n } catch {\n return out;\n }\n for (const name2 of [.../* @__PURE__ */ new Set([...names2, \"dev\", ...SYNTHETIC_DIRS])].sort()) {\n const path = `/${name2}`;\n if (path === \"/dev\") {\n out.push({ type: \"dir\", path, preopen: path });\n continue;\n }\n try {\n if ((await this.fs.stat(path)).isDirectory) out.push({ type: \"dir\", path, preopen: path });\n } catch {\n }\n }\n if (root) {\n out.push(\n { type: \"dir\", path: \"/\", preopen: \"/\" },\n { type: \"dir\", path: here, preopen: \"./\" }\n );\n dot.twin = 3 + out.length - 1;\n }\n return out;\n }\n async find(fd) {\n if (!this.shared) return this.table.get(fd);\n this.sync();\n return this.table.get(fd) ?? await this.fetch(fd);\n }\n shared;\n seen = 0;\n get isShared() {\n return this.shared !== void 0;\n }\n async share(ids, fresh) {\n if (!fresh) {\n await this.promoteFiles();\n for (const fd of this.cloexec) await this.kernel.call({ op: \"fd-cloexec\", fd, on: true });\n for (const [fd, e] of this.table) {\n if (e.type === \"kernel\" && (e.nonblock || e.append)) await this.publishFlags(fd, e);\n }\n } else {\n this.table.clear();\n this.cloexec.clear();\n }\n this.shared = ids;\n this.fs.threaded?.();\n this.seen = Atomics.load(ids, GEN2);\n }\n sync() {\n const shared = this.shared;\n const gen = Atomics.load(shared, GEN2);\n if (gen === this.seen) return;\n if (!this.replay(shared, gen)) {\n this.table.clear();\n this.cloexec.clear();\n }\n this.seen = gen;\n }\n replay(shared, upTo) {\n if (upTo - this.seen > FD_RING_SIZE || !ringed(shared)) return false;\n const changed2 = [];\n for (let g = this.seen + 1; g <= upTo; g++) {\n const at = FD_RING + g % FD_RING_SIZE * 2;\n if (Atomics.load(shared, at) !== g) return false;\n const fd = Atomics.load(shared, at + 1);\n if (fd < 0 || Atomics.load(shared, at) !== g) return false;\n changed2.push(fd);\n }\n for (const fd of changed2) {\n this.table.delete(fd);\n this.cloexec.delete(fd);\n }\n return true;\n }\n bump(...fds) {\n if (!this.shared) return;\n const shared = this.shared;\n for (const fd of fds.length > 0 ? fds : [-1]) {\n const gen = Atomics.add(shared, GEN2, 1) + 1;\n if (ringed(shared)) {\n const at = FD_RING + gen % FD_RING_SIZE * 2;\n Atomics.store(shared, at, 0);\n Atomics.store(shared, at + 1, fd);\n Atomics.store(shared, at, gen);\n }\n if (gen - 1 === this.seen) this.seen = gen;\n }\n }\n async stdioEntry(fd) {\n let info;\n try {\n info = await this.kernel.call({ op: \"fd-info\", fd });\n } catch {\n return kernelEntry();\n }\n return info?.meta && \"dir\" in info.meta ? { type: \"dir\", path: info.meta.dir } : kernelEntry();\n }\n async fetch(fd) {\n let info;\n try {\n info = await this.kernel.call({ op: \"fd-info\", fd });\n } catch {\n return void 0;\n }\n const e = entryOf(info);\n if (!e) return void 0;\n this.table.set(fd, e);\n if (info.cloexec) this.cloexec.add(fd);\n return e;\n }\n async listed() {\n const out = [];\n for (const info of await this.kernel.call({ op: \"fd-list\" })) {\n const e = entryOf(info);\n if (e) out.push([info.fd, e, info.cloexec === true]);\n }\n return out;\n }\n async publishFlags(fd, e) {\n const flags = (e.nonblock ? O_NONBLOCK2 : 0) | (e.append ? O_APPEND : 0);\n await this.kernel.call({ op: \"fd-setfl\", fd, flags });\n }\n async setFlags(fd, nonblock, append) {\n const e = await this.get(fd);\n if (e.type === \"kernel\") {\n e.nonblock = nonblock;\n e.append = append;\n if (this.shared) {\n await this.publishFlags(fd, e);\n this.bump(fd);\n }\n } else if (e.type === \"file\") e.file.append = append;\n }\n async setCloexec(fd, on) {\n await this.get(fd);\n if (on) this.cloexec.add(fd);\n else this.cloexec.delete(fd);\n if (this.shared) {\n await this.kernel.call({ op: \"fd-cloexec\", fd, on });\n this.bump(fd);\n }\n }\n async cwd() {\n const dot = await this.find(3);\n return dot?.type === \"dir\" && dot.preopen === \".\" ? dot.path : void 0;\n }\n async terminals() {\n const fds = this.shared ? (await this.kernel.call({ op: \"fd-list\" })).filter((info) => info.tty).map((info) => info.fd) : [...this.table].filter(([, e]) => e.type === \"kernel\" && e.kind === \"tty\").map(([fd]) => fd);\n return fds.sort((a, b) => a - b);\n }\n sockets() {\n return [...this.table].filter(([, e]) => e.type === \"kernel\" && e.kind === \"socket\").map(([fd]) => fd).sort((a, b) => a - b);\n }\n async adopt(fd, kind, nonblock, dgram = false) {\n this.table.set(fd, { type: \"kernel\", kind, dgram, nonblock, append: false });\n if (this.shared && nonblock) await this.publishFlags(fd, { nonblock, append: false });\n this.bump(fd);\n }\n async get(fd) {\n const e = await this.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type === \"file\") await this.followRenames();\n return e;\n }\n async preopen(fd) {\n const e = await this.find(fd);\n if (e?.type !== \"dir\" || e.preopen === void 0) throw new WasiError(\"EBADF\");\n return e;\n }\n async dir(fd) {\n const e = await this.get(fd);\n if (e.type !== \"dir\") throw new WasiError(\"ENOTDIR\");\n return e;\n }\n async install(e, min = 3) {\n const meta = metaOf(e);\n const fd = await this.kernel.call({\n op: \"fd-reserve\",\n ...min > 3 ? { min } : {},\n ...meta ? { meta } : {}\n });\n this.table.set(fd, e);\n this.bump(fd);\n return fd;\n }\n cloexec = /* @__PURE__ */ new Set();\n implicitCloexec = false;\n async dup(fd, min, cloexec) {\n const e = await this.get(fd);\n let at;\n if (e.type !== \"file\") {\n at = await this.kernel.call({ op: \"fd-dup\", fd, min: Math.max(3, min) });\n this.table.set(at, { ...e });\n } else {\n e.file.refs++;\n at = await this.install(e, min);\n }\n if (cloexec) await this.setCloexec(at, true);\n this.bump(at);\n return at;\n }\n async pipe() {\n const [r, w] = await this.kernel.sys.pipe();\n this.table.set(r, { type: \"kernel\", kind: \"stream\", nonblock: false, append: false });\n this.table.set(w, { type: \"kernel\", kind: \"stream\", nonblock: false, append: false });\n this.bump(r, w);\n return [r, w];\n }\n async chdir(path) {\n const dot = await this.find(3);\n if (dot?.type !== \"dir\" || dot.preopen !== \".\") return;\n const moved = [[3, dot]];\n const twin = dot.twin === void 0 ? void 0 : await this.find(dot.twin);\n if (twin?.type === \"dir\" && twin.preopen === \"./\") moved.push([dot.twin, twin]);\n for (const [fd, e] of moved) {\n e.path = path;\n await this.kernel.call({ op: \"fd-meta\", fd, meta: metaOf(e) });\n }\n this.held?.moved(await this.kernel.call({ op: \"cwd-chdir\", path }), path);\n this.bump();\n }\n async promote(fd, moved = false) {\n const e = await this.get(fd);\n if (e.type === \"file\" && (!moved || await this.moved(fd))) await this.promoteFiles(e.file.buffer);\n }\n async promoteFiles(only) {\n const promoted = /* @__PURE__ */ new Map();\n const handed = /* @__PURE__ */ new Set();\n for (const [fd, e] of [...this.table]) {\n if (e.type !== \"file\" || only && e.file.buffer !== only) continue;\n const first = promoted.get(e.file);\n if (first !== void 0) {\n await this.kernel.call({ op: \"fd-promote\", fd, share: first });\n } else {\n await this.kernel.call(await promoteRequest(fd, e.file, handed));\n handed.add(e.file.buffer);\n promoted.set(e.file, fd);\n }\n this.table.set(fd, {\n type: \"kernel\",\n kind: \"file\",\n nonblock: false,\n append: e.file.append,\n path: e.file.path,\n ino: await this.inoOf(e.file.path)\n });\n }\n for (const file of promoted.keys()) {\n if (--file.buffer.opens <= 0) {\n this.forget(file.buffer);\n await this.letGo(file.buffer);\n }\n }\n }\n snapshot() {\n const out = [];\n if (this.shared) return out;\n for (const [fd, e] of this.table) {\n if (e.type === \"kernel\")\n out.push({ fd, type: \"kernel\", nonblock: e.nonblock, append: e.append });\n else if (e.type === \"dir\") out.push({ fd, type: \"dir\", path: e.path, ...preopenOf(e) });\n else if (e.type === \"device\") out.push({ fd, ...deviceEntry(e) });\n }\n return out;\n }\n restore(fds, cloexec) {\n this.table.clear();\n for (const f of fds) {\n if (f.type === \"kernel\")\n this.table.set(f.fd, { type: \"kernel\", nonblock: f.nonblock, append: f.append });\n else if (f.type === \"dir\")\n this.table.set(f.fd, { type: \"dir\", path: f.path, ...preopenOf(f) });\n else this.table.set(f.fd, deviceEntry(f));\n }\n for (const fd of cloexec) this.cloexec.add(fd);\n }\n async inheritable() {\n const out = /* @__PURE__ */ new Map();\n const all = this.shared ? await this.listed() : [...this.table].map(([fd, e]) => [\n fd,\n e,\n this.cloexec.has(fd)\n ]);\n for (const [fd, e, cloexec] of all) {\n if (e.type !== \"kernel\" || cloexec) continue;\n if (this.implicitCloexec && fd > 2) continue;\n out.set(fd, fd);\n }\n return out;\n }\n locking = false;\n holdLocks() {\n this.locking = true;\n }\n async dropLocks(e) {\n if (!this.locking || e?.type !== \"file\") return;\n try {\n await this.kernel.call({ op: \"lk-close\", path: e.file.path });\n } catch {\n }\n }\n async close(fd) {\n const e = await this.get(fd);\n this.table.delete(fd);\n this.cloexec.delete(fd);\n try {\n await this.kernel.sys.close(fd);\n } finally {\n await this.release(e);\n await this.dropLocks(e);\n this.bump(fd);\n }\n }\n async renumber(from, to, keep = false) {\n const e = await this.get(from);\n const old = keep ? await this.find(to) : await this.get(to);\n if (from === to) return;\n await this.kernel.call({ op: \"fd-renumber\", from, to, ...keep ? { keep } : {} });\n this.cloexec.delete(to);\n if (keep) {\n if (e.type === \"file\") e.file.refs++;\n this.table.set(to, e.type === \"file\" ? e : { ...e });\n } else {\n this.table.delete(from);\n this.table.set(to, e);\n if (this.cloexec.delete(from)) this.cloexec.add(to);\n }\n if (old) await this.release(old);\n await this.dropLocks(old);\n this.bump(from, to);\n }\n async release(e) {\n if (e.type !== \"file\" || --e.file.refs > 0) return;\n const { buffer } = e.file;\n try {\n await buffer.flush();\n this.reported.delete(buffer);\n } catch (err) {\n this.reported.add(buffer);\n await this.drop(buffer);\n throw err;\n }\n await this.drop(buffer);\n }\n async drop(buffer) {\n if (--buffer.opens > 0) return;\n this.forget(buffer);\n await this.letGo(buffer);\n }\n forget(buffer) {\n for (const [p, b] of [...this.buffers]) if (b === buffer) this.buffers.delete(p);\n const id = this.ids.get(buffer);\n if (id !== void 0 && this.byId.get(id) === buffer) this.byId.delete(id);\n this.ids.delete(buffer);\n }\n know(buffer, id) {\n if (this.ids.has(buffer)) return;\n this.ids.set(buffer, id);\n if (!this.byId.has(id)) this.byId.set(id, buffer);\n }\n identity(st) {\n if (!st || st.ino === void 0 || (st.nlink ?? 1) < 2) return void 0;\n return `${st.dev ?? 0}:${st.ino}`;\n }\n async sharing(path, st) {\n if (st?.ino === void 0) return void 0;\n const id = `${st.dev ?? 0}:${st.ino}`;\n if (!this.byId.has(id) && this.identity(st) !== void 0) await this.learn();\n const buffer = this.byId.get(id);\n if (!buffer) return void 0;\n this.buffers.set(path, buffer);\n return buffer;\n }\n async learn() {\n for (const [p, buffer] of this.buffers) {\n if (this.ids.has(buffer) || buffer.isOrphan()) continue;\n const known = this.identity(await this.statOrMissing(p));\n if (known !== void 0) this.know(buffer, known);\n }\n }\n async linked(from, to) {\n const buffer = this.buffers.get(from);\n if (!buffer || buffer.isOrphan()) return;\n const id = this.identity(await this.statOrMissing(to));\n if (id === void 0) return;\n this.know(buffer, id);\n if (!this.buffers.has(to)) this.buffers.set(to, buffer);\n }\n async letGo(buffer) {\n await this.fs.hold?.(buffer.path, false, true, buffer.handle);\n }\n async kind(fd, e) {\n if (!e.kind) {\n const info = await this.kernel.call({ op: \"fd-info\", fd });\n e.kind = info.kind ?? (info.tty ? \"tty\" : \"stream\");\n e.dgram = info.dgram === true;\n }\n return e.kind;\n }\n async datagram(fd, e) {\n if (await this.kind(fd, e) !== \"socket\") return false;\n if (e.dgram === void 0) {\n e.dgram = (await this.kernel.call({ op: \"fd-info\", fd })).dgram === true;\n }\n return e.dgram;\n }\n async flushAll() {\n for (const buffer of this.buffers.values()) {\n try {\n await buffer.flush();\n this.reported.delete(buffer);\n } catch (err) {\n if (!this.reported.has(buffer)) throw err;\n }\n }\n }\n async synced(file) {\n try {\n await file.flush();\n await this.kernel.call({ op: \"fd-path-flush\", path: file.buffer.path, durable: true });\n this.reported.delete(file.buffer);\n } catch (err) {\n this.reported.add(file.buffer);\n throw err;\n }\n }\n async flushEarly() {\n for (const buffer of this.buffers.values()) {\n try {\n await buffer.flush();\n } catch {\n }\n }\n }\n async reread(fd) {\n const e = await this.get(fd);\n if (e.type === \"file\") await e.file.buffer.reread();\n }\n async flushPath(path) {\n for (const [p, buffer] of this.buffers) if (within(p, path)) await buffer.flush();\n if (this.shared && !this.fs.changes?.clean()) await this.kernel.call({ op: \"fd-path-flush\", path });\n }\n holdsUnder(path) {\n for (const p of this.buffers.keys()) if (within(p, path)) return true;\n return false;\n }\n async replacing(path) {\n for (const [p, buffer] of this.buffers) {\n if (!within(p, path)) continue;\n try {\n await buffer.prefetch();\n } catch {\n buffer.spoil();\n }\n }\n }\n async unlinking(path, linked) {\n const buffer = this.buffers.get(path);\n if (buffer && this.survives(buffer, linked)) await buffer.flush();\n else await buffer?.keep();\n if (this.shared) await this.kernel.call({ op: \"fd-path-unlinking\", path });\n }\n async unlinked(path, linked) {\n if (this.shared) await this.kernel.call({ op: \"fd-path-unlinked\", path });\n const buffer = this.buffers.get(path);\n if (!buffer) return;\n await this.detach(buffer, linked);\n this.buffers.delete(path);\n }\n async openedIno(fd) {\n try {\n return (await this.kernel.call({ op: \"fd-vfs-stat\", fd, identity: true })).ino;\n } catch (err) {\n await this.kernel.sys.close(fd);\n throw err;\n }\n }\n async moved(fd) {\n const e = await this.get(fd);\n if (e.type !== \"file\") return false;\n if (e.file.buffer.isOrphan()) return true;\n return e.file.ino !== void 0 && await this.inoOf(e.file.path) !== e.file.ino;\n }\n async inoOf(path) {\n try {\n return (await this.fs.stat(path)).ino;\n } catch {\n return void 0;\n }\n }\n survives(buffer, linked) {\n return linked !== void 0 && buffer.handle !== void 0;\n }\n async detach(buffer, linked) {\n if (this.survives(buffer, linked)) {\n const id = this.identity(linked);\n if (id !== void 0) this.know(buffer, id);\n return;\n }\n await buffer.orphan();\n this.forget(buffer);\n }\n async renamed(from, to, replacedLinked, foreign = false) {\n if (from === to) return;\n if (this.shared && !foreign) await this.kernel.call({ op: \"fd-path-renamed\", from, to });\n for (const e of this.table.values()) {\n if (e.type === \"kernel\" && e.path !== void 0 && within(e.path, from)) {\n e.path = to + e.path.slice(from.length);\n }\n }\n const moved = [];\n for (const [p, buffer] of this.buffers) {\n if (foreign && buffer.isOrphan()) continue;\n if (within(p, from)) moved.push([p, buffer]);\n else if (within(p, to)) {\n await this.detach(buffer, replacedLinked);\n this.buffers.delete(p);\n }\n }\n for (const [p] of moved) this.buffers.delete(p);\n for (const [p, buffer] of moved) {\n const next2 = to + p.slice(from.length);\n if (buffer.path === p) buffer.path = next2;\n this.buffers.set(next2, buffer);\n }\n }\n held;\n cwdEntry(dir) {\n return dir.preopen === \".\" || dir.preopen === \"./\";\n }\n async goneCwd(dir) {\n return this.held !== void 0 && this.cwdEntry(dir) && !await this.held.alive(dir.path);\n }\n async resolve(dirfd, path) {\n if (path === \"\") throw new WasiError(\"ENOENT\");\n if (path.startsWith(\"/\")) return await this.joined(path);\n const dir = await this.dir(dirfd);\n if (path.split(\"/\")[0] !== \"..\" && await this.goneCwd(dir)) throw new WasiError(\"ENOENT\");\n return await this.joined(`${dir.path}/${path}`);\n }\n async joined(joined2) {\n return joined2.split(\"/\").includes(\"..\") ? await physical(this.fs, joined2) : normalize(joined2);\n }\n async openKernelDevice(path, oflags, fdflags, rights) {\n const { openSealed, openClipboard, openEmbedder, openTty } = this.kernel.sys;\n const nonblock = (fdflags & FDFLAGS.NONBLOCK) !== 0;\n let fd;\n let kind;\n if (path === SEALED_PATH && openSealed) {\n fd = await this.openCharDevice(openSealed, oflags, rights);\n kind = \"sealed\";\n } else if (path === CLIPBOARD_PATH && openClipboard) {\n fd = await this.openCharDevice(openClipboard, oflags, rights);\n kind = \"clipboard\";\n } else if (path === EMBEDDER_PATH && openEmbedder) {\n fd = await this.openCharDevice(openEmbedder, oflags, rights);\n kind = \"embedder\";\n } else if (path === \"/dev/tty\" || /^\\/dev\\/tty\\d+$/.test(path)) {\n const exclusive = (oflags & OFLAGS.CREAT) !== 0 && (oflags & OFLAGS.EXCL) !== 0;\n try {\n fd = await openTty?.call(this.kernel.sys, path === \"/dev/tty\" ? void 0 : path);\n } catch (err) {\n if (exclusive && err.code === \"EACCES\")\n throw new WasiError(\"EEXIST\");\n throw err;\n }\n if (fd === void 0) throw new WasiError(\"ENXIO\");\n if (exclusive) {\n await this.kernel.sys.close(fd);\n throw new WasiError(\"EEXIST\");\n }\n kind = \"tty\";\n } else return void 0;\n await this.adopt(fd, kind, nonblock);\n return fd;\n }\n async openSerial(path, oflags, fdflags, rights) {\n const { openDev } = this.kernel.sys;\n const linked = path.startsWith(`${BY_ID}/`);\n if (!openDev || !(linked || DEVICE_PATH.test(path))) return void 0;\n if (this.nofollow && linked) throw new WasiError(\"ELOOP\");\n const fd = await this.openCharDevice(\n async (flags) => await openDev.call(this.kernel.sys, path, flags),\n oflags,\n rights\n );\n await this.adopt(fd, \"tty\", (fdflags & FDFLAGS.NONBLOCK) !== 0);\n return fd;\n }\n async openCharDevice(openDevice, oflags, rights) {\n if (oflags & OFLAGS.DIRECTORY) throw new WasiError(\"ENOTDIR\");\n if (oflags & OFLAGS.CREAT && oflags & OFLAGS.EXCL) throw new WasiError(\"EEXIST\");\n const want = wantOf(oflags, rights);\n const flags = want === 6 ? O_RDWR : want === 2 ? O_WRONLY : 0;\n return await openDevice.call(this.kernel.sys, flags);\n }\n async open(path, oflags, rights, fdflags, mode, nofollow = false) {\n this.made = void 0;\n this.created = false;\n this.nofollow = nofollow;\n const exclusive = (oflags & OFLAGS.CREAT) !== 0 && (oflags & OFLAGS.EXCL) !== 0;\n const special = await this.openSpecial(path, oflags, rights, fdflags, exclusive);\n if (special !== void 0) return special;\n const outside = await this.escaped(path, oflags, rights);\n if (outside !== void 0) return await this.open(outside, oflags, rights, fdflags, mode);\n if (exclusive && !(oflags & OFLAGS.DIRECTORY) && await this.madeAtOnce(path, mode)) {\n return await this.regular(path, void 0, oflags, rights, fdflags, mode, true);\n }\n if (exclusive && !nofollow && await this.isLink(path)) throw new WasiError(\"EEXIST\");\n const s = nofollow ? await this.lstatOrMissing(path) : await this.statOrMissing(path);\n if (s?.isSymbolicLink) throw new WasiError(exclusive ? \"EEXIST\" : \"ELOOP\");\n if (exclusive && s) throw new WasiError(\"EEXIST\");\n if (s?.escape !== void 0) {\n refuseWrite({ readonly: true }, oflags, rights);\n return await this.open(s.escape, oflags, rights, fdflags, mode);\n }\n if (oflags & OFLAGS.DIRECTORY && !s?.isDirectory) {\n throw new WasiError(s ? \"ENOTDIR\" : \"ENOENT\");\n }\n if (s?.isDirectory) {\n const asked = (oflags & OFLAGS.DIRECTORY) === 0 && (rights & RIGHTS.FD_WRITE) !== 0n;\n if (asked || (oflags & (OFLAGS.CREAT | OFLAGS.TRUNC)) !== 0) throw new WasiError(\"EISDIR\");\n return await this.install({ type: \"dir\", path });\n }\n if (!s && !(oflags & OFLAGS.CREAT)) throw new WasiError(\"ENOENT\");\n refuseWrite(s, oflags, rights);\n return await this.regular(path, s, oflags, rights, fdflags, mode);\n }\n nofollow = false;\n inos = /* @__PURE__ */ new WeakMap();\n otherFile(buffer, st) {\n const ino = this.inos.get(buffer);\n return ino !== void 0 && st?.ino !== void 0 && ino !== st.ino;\n }\n async openSpecial(path, oflags, rights, fdflags, exclusive) {\n if (exclusive && namedDevice(path)) throw new WasiError(\"EEXIST\");\n const device = deviceOf(path);\n if (device) return await this.install({ type: \"device\", device });\n const serial = await this.openSerial(path, oflags, fdflags, rights);\n if (serial !== void 0) return serial;\n const kernelDevice = await this.openKernelDevice(path, oflags, fdflags, rights);\n if (kernelDevice !== void 0) return kernelDevice;\n const alias = stdioAlias(path);\n if (alias === void 0) return void 0;\n if (this.nofollow) throw new WasiError(\"ELOOP\");\n return await this.reopen(alias);\n }\n async escaped(path, oflags, rights) {\n const outside = await this.fs.escape?.(path);\n if (outside === void 0) return void 0;\n refuseWrite({ readonly: true }, oflags | (oflags & OFLAGS.CREAT ? OFLAGS.TRUNC : 0), rights);\n return outside;\n }\n async regular(path, s, oflags, rights, fdflags, mode, created = false) {\n if (s?.isFifo) return await this.kernelFifo(path, s, oflags, rights, fdflags);\n if (s?.isSocket) throw new WasiError(\"ENXIO\");\n if (this.shared || await this.kernelHolds(path, s)) {\n return await this.kernelFile(path, s, oflags, rights, fdflags, mode, created);\n }\n return await this.install({\n type: \"file\",\n file: await this.file(path, s, oflags, rights, fdflags, mode, created)\n });\n }\n async kernelHolds(path, st) {\n for (const [fd, e] of this.table) {\n if (e.type !== \"kernel\" || await this.kind(fd, e) !== \"file\") continue;\n await this.named(fd, e);\n if (e.path === path || st?.ino !== void 0 && e.ino === st.ino) return true;\n }\n return false;\n }\n learned = /* @__PURE__ */ new WeakSet();\n async named(fd, e) {\n if (e.path !== void 0 || this.learned.has(e)) return;\n this.learned.add(e);\n try {\n const vfs = await this.kernel.call({ op: \"fd-vfs-stat\", fd, identity: true });\n if (vfs.orphan || vfs.path === void 0) return;\n e.path = vfs.path;\n e.ino = vfs.ino ?? await this.inoOf(vfs.path);\n } catch {\n }\n }\n async file(path, existing, oflags, rights, fdflags, mode, created = false) {\n const { readable, writable } = openAccess(existing, oflags, rights);\n await this.followRenames();\n let buffer = created ? void 0 : this.buffers.get(path);\n if (buffer?.handle !== void 0 && await this.fs.kept?.(buffer.handle)) {\n this.buffers.delete(path);\n buffer = void 0;\n }\n buffer ??= await this.sharing(path, existing);\n if (buffer && this.nofollow && this.otherFile(buffer, existing)) buffer = void 0;\n const want = wantOf(oflags, rights);\n if (buffer) {\n if (this.fs.owners) await this.fs.access?.(path, want, \"open\");\n if (oflags & OFLAGS.TRUNC) await buffer.truncate(0);\n } else {\n buffer = await this.freshBuffer(path, existing, oflags, want, mode, created);\n }\n buffer.opens++;\n const file = new LocalFile(buffer, readable, writable, (fdflags & FDFLAGS.APPEND) !== 0);\n file.ino = existing?.ino;\n return file;\n }\n async freshBuffer(path, existing, oflags, want, mode, created = false) {\n const made = created || !existing && await this.createNew(path, oflags, mode);\n const reply = made ? this.made : void 0;\n this.made = void 0;\n const empty = made || (oflags & OFLAGS.TRUNC) !== 0;\n if (existing?.ranged) this.fs.invalidate?.();\n const seen = reply ? reply.seen : this.fs.changes?.now();\n const st = reply?.st ?? (existing?.ranged || !existing ? await this.fs.stat(path) : existing);\n const ranged = st.ranged ? st.size : void 0;\n const asked = (want & 4 ? HOLD_READ : 0) | (want & 2 ? HOLD_WRITE : 0) | (made ? HOLD_CREATED : 0);\n const asking = this.fs.owners ? asked : asked & HOLD_WRITE;\n const handle = await this.fs.hold?.(path, true, true, void 0, asking, {\n gen: st.gen,\n ...this.nofollow ? { nofollow: true } : {},\n ...st.ino !== void 0 ? { ino: st.ino } : {}\n });\n const io = handle !== void 0 && this.fs.pinned ? await this.fs.pinned(handle) : this.fs;\n const view = this.fs.changes;\n const watch = view && linkedWatch(\n {\n view,\n ino: st.ino,\n seen,\n stat: async (at) => {\n this.fs.invalidate?.();\n return await this.fs.stat(at);\n },\n real: async () => await realOf(this.fs, path)\n },\n st\n );\n const buffer = await new FileBuffer(io, path, empty, st.maxFile, ranged, st.version, watch).emptied(\n empty\n );\n buffer.moved = async (missing3) => await this.followRenames(missing3);\n buffer.bound = st;\n buffer.handle = handle;\n if (handle !== void 0) buffer.real = await this.fs.heldReal?.(handle);\n if (st.ino !== void 0) this.inos.set(buffer, st.ino);\n this.buffers.set(path, buffer);\n const id = this.identity(st);\n if (id !== void 0) this.know(buffer, id);\n return buffer;\n }\n async kernelFile(path, existing, oflags, rights, fdflags, mode, created = false) {\n const { readable, writable } = openAccess(existing, oflags, rights);\n const append = (fdflags & FDFLAGS.APPEND) !== 0;\n const flags = (writable ? readable ? O_RDWR : O_WRONLY : 0) | (append ? O_APPEND : 0);\n const made = created || !existing && await this.createNew(path, oflags, mode);\n const truncate = made || (oflags & OFLAGS.TRUNC) !== 0;\n const fd = await this.kernel.sys.openVfs(path, flags, 0, {\n ...truncate ? { truncate } : {},\n ...made ? { created: true } : {},\n ...this.nofollow && !made ? { nofollow: true } : {}\n });\n const ino = writable ? await this.openedIno(fd) ?? await this.inoOf(path) : void 0;\n if (truncate) this.fs.touched?.(path, ino);\n this.table.set(fd, { type: \"kernel\", kind: \"file\", nonblock: false, append, path, ino });\n if (append) await this.publishFlags(fd, { nonblock: false, append });\n this.bump(fd);\n return fd;\n }\n async kernelFifo(path, existing, oflags, rights, fdflags) {\n const { readable, writable } = openAccess(existing, oflags, rights);\n const nonblock = (fdflags & FDFLAGS.NONBLOCK) !== 0;\n const access3 = writable ? readable ? O_RDWR : O_WRONLY : 0;\n const fd = await this.restarting(\n async () => await this.kernel.sys.openVfs(path, access3 | (nonblock ? O_NONBLOCK2 : 0), 0, { fifo: true })\n );\n this.table.set(fd, { type: \"kernel\", kind: \"stream\", nonblock, append: false });\n if (nonblock) await this.publishFlags(fd, { nonblock, append: false });\n this.bump(fd);\n return fd;\n }\n restartable;\n async restarting(call2) {\n for (; ; ) {\n try {\n return await call2();\n } catch (err) {\n if (err.code !== \"EINTR\" || !this.restartable?.()) throw err;\n }\n }\n }\n created = false;\n made;\n async creating(path, mode) {\n const st = await this.fs.create?.(path, mode, true);\n this.made = st ? { st, seen: st.seen } : void 0;\n this.created = true;\n }\n async madeAtOnce(path, mode) {\n if (!this.fs.create) return false;\n try {\n await this.creating(path, mode);\n return true;\n } catch (err) {\n if (err.code === \"EEXIST\") throw err;\n return false;\n }\n }\n async createNew(path, oflags, mode) {\n if (!this.fs.create) {\n await this.fs.writeFile(path, new Uint8Array(0));\n this.created = true;\n return true;\n }\n try {\n await this.creating(path, mode);\n return true;\n } catch (err) {\n if (oflags & OFLAGS.EXCL || err.code !== \"EEXIST\") throw err;\n return false;\n }\n }\n async isLink(path) {\n try {\n return (await this.fs.lstat(path)).isSymbolicLink === true;\n } catch {\n return false;\n }\n }\n async lstatOrMissing(path) {\n try {\n return await this.fs.lstat(path);\n } catch (e) {\n if (e.code === \"ENOENT\") return void 0;\n throw e;\n }\n }\n async statOrMissing(path) {\n try {\n return await this.fs.stat(path);\n } catch (e) {\n if (e.code === \"ENOENT\") return void 0;\n throw e;\n }\n }\n async reopen(fd) {\n const e = await this.get(fd);\n if (e.type === \"kernel\") {\n const at = await this.kernel.call({ op: \"fd-dup\", fd });\n this.table.set(at, { ...e });\n this.bump(at);\n return at;\n }\n if (e.type === \"file\") e.file.refs++;\n return await this.install(e.type === \"file\" ? e : { ...e });\n }\n};\nfunction kernelEntry() {\n return { type: \"kernel\", nonblock: false, append: false };\n}\nvar GEN2 = 2;\nfunction ringed(shared) {\n return shared.length >= FD_RING + FD_RING_SIZE * 2;\n}\nfunction deviceEntry(meta) {\n return { type: \"device\", device: meta.device, ...meta.access ? { access: meta.access } : {} };\n}\nfunction refuseWrite(s, oflags, rights) {\n const writes = (rights & RIGHTS.FD_WRITE) !== 0n || (oflags & OFLAGS.TRUNC) !== 0;\n if (s?.readonly && writes) throw new WasiError(\"EROFS\");\n}\nfunction preopenOf(e) {\n return {\n ...e.preopen ? { preopen: e.preopen } : {},\n ...e.twin !== void 0 ? { twin: e.twin } : {}\n };\n}\nfunction metaOf(e) {\n if (e.type === \"dir\") return { dir: e.path, ...preopenOf(e) };\n if (e.type === \"device\") return { device: e.device, ...e.access ? { access: e.access } : {} };\n return void 0;\n}\nfunction entryOf(info) {\n if (info.meta && \"dir\" in info.meta) {\n return { type: \"dir\", path: info.meta.dir, ...preopenOf(info.meta) };\n }\n if (info.meta && \"device\" in info.meta) return deviceEntry(info.meta);\n if (info.kind === \"held\") return void 0;\n return {\n type: \"kernel\",\n kind: info.kind,\n dgram: info.dgram === true,\n nonblock: ((info.flags ?? 0) & O_NONBLOCK2) !== 0,\n append: ((info.flags ?? 0) & O_APPEND) !== 0\n };\n}\nfunction wantOf(oflags, rights) {\n const write2 = (rights & RIGHTS.FD_WRITE) !== 0n || (oflags & OFLAGS.TRUNC) !== 0;\n const read2 = (rights & RIGHTS.FD_READ) !== 0n || !write2;\n return (read2 ? 4 : 0) | (write2 ? 2 : 0);\n}\nfunction openAccess(existing, oflags, rights) {\n const readonly = existing?.readonly === true;\n const mutating = readonly ? OFLAGS.TRUNC : OFLAGS.CREAT | OFLAGS.TRUNC;\n const writable = (rights & RIGHTS.FD_WRITE) !== 0n || (oflags & mutating) !== 0;\n if (writable && readonly) throw new WasiError(\"EROFS\");\n return { readable: (rights & RIGHTS.FD_READ) !== 0n || !writable, writable };\n}\nasync function promoteRequest(fd, f, handed) {\n const orphan = f.buffer.isOrphan() || (f.buffer.handle ?? 0) < 0;\n if (!orphan && f.buffer.isRanged) await f.buffer.flush();\n const joins = !orphan && (handed.has(f.buffer) || f.buffer.isRanged);\n return {\n op: \"fd-promote\",\n fd,\n path: f.path,\n flags: (f.writable ? f.readable ? O_RDWR : O_WRONLY : 0) | (f.append ? O_APPEND : 0),\n position: f.offset,\n ...joins ? {} : { contents: await f.buffer.contents() },\n ...orphan ? { orphan: true } : {},\n ...!orphan && f.buffer.pin !== void 0 ? { pin: { version: f.buffer.pin, size: await f.buffer.size() } } : {},\n ...!joins && f.buffer.isDirty() ? { dirty: true } : {},\n ...f.buffer.handle !== void 0 ? { handle: f.buffer.handle } : {},\n ...f.buffer.handle !== void 0 && f.ino !== void 0 ? { ino: f.ino } : {}\n };\n}\n\n// src/process/wasi/wasi-futex.ts\nvar FUTEX_SLICE_MS = 50;\nasync function futexWait(view, index3, expected, ms, interrupted) {\n const deadline = performance.now() + ms;\n for (; ; ) {\n const slice = interrupted ? Math.min(FUTEX_SLICE_MS, ms) : ms;\n if (await atomicsWait(view, index3, expected, slice) !== \"timed-out\") return true;\n if (interrupted?.()) return true;\n ms = deadline - performance.now();\n if (ms <= 0) return false;\n }\n}\nvar atomicFutexes = {\n wait: futexWait,\n notify: (view, index3, count) => atomicsNotify(view, index3, count),\n pause: () => {\n }\n};\n\n// src/process/wasi/wasi-memory.ts\nvar decoder2 = new TextDecoder();\nvar WasiMemory = class {\n memory;\n bind(memory) {\n this.memory = memory;\n }\n buffer() {\n if (!this.memory) throw new Error(\"WASI: no memory bound\");\n return this.memory.buffer;\n }\n view() {\n return new DataView(this.buffer());\n }\n bytes(ptr, len) {\n return new Uint8Array(this.buffer(), ptr, len);\n }\n string(ptr, len) {\n return decoder2.decode(this.bytes(ptr, len).slice());\n }\n cString(ptr) {\n const bytes = new Uint8Array(this.buffer());\n let end = ptr;\n while (end < bytes.length && bytes[end] !== 0) end++;\n return decoder2.decode(bytes.slice(ptr, end));\n }\n size() {\n return this.buffer().byteLength;\n }\n iovecs(ptr, count) {\n const v = this.view();\n const out = [];\n for (let i = 0; i < count; i++) {\n out.push([v.getUint32(ptr + i * 8, true), v.getUint32(ptr + i * 8 + 4, true)]);\n }\n return out;\n }\n capacity(ptr, count) {\n return this.iovecs(ptr, count).reduce((n, [, len]) => n + len, 0);\n }\n gather(ptr, count) {\n const vecs = this.iovecs(ptr, count);\n if (vecs.length === 1) return this.bytes(vecs[0][0], vecs[0][1]).slice();\n const out = new Uint8Array(vecs.reduce((n, [, len]) => n + len, 0));\n let at = 0;\n for (const [base, len] of vecs) {\n out.set(this.bytes(base, len), at);\n at += len;\n }\n return out;\n }\n scatter(ptr, count, data) {\n let at = 0;\n for (const [base, len] of this.iovecs(ptr, count)) {\n if (at >= data.length) break;\n const n = Math.min(len, data.length - at);\n this.bytes(base, n).set(data.subarray(at, at + n));\n at += n;\n }\n return at;\n }\n putStrings(list, ptrs, buf) {\n const encoder6 = new TextEncoder();\n const v = this.view();\n let at = buf;\n list.forEach((s, i) => {\n const b = encoder6.encode(s);\n v.setUint32(ptrs + i * 4, at, true);\n this.bytes(at, b.length).set(b);\n v.setUint8(at + b.length, 0);\n at += b.length + 1;\n });\n }\n putSizes(list, countPtr, sizePtr) {\n const encoder6 = new TextEncoder();\n const v = this.view();\n v.setUint32(countPtr, list.length, true);\n v.setUint32(\n sizePtr,\n list.reduce((n, s) => n + encoder6.encode(s).length + 1, 0),\n true\n );\n }\n};\n\n// src/process/wasi/wasi-poll.ts\nfunction readSubscriptions(mem, ptr, n, now) {\n const v = mem.view();\n const at = performance.now();\n const subs = [];\n for (let i = 0; i < n; i++) {\n const p = ptr + i * SIZE.SUBSCRIPTION;\n const type = v.getUint8(p + 8);\n const sub = { userdata: v.getBigUint64(p, true), type, fd: -1, deadline: Infinity };\n if (type === EVENTTYPE.CLOCK) {\n const id = v.getUint32(p + 16, true);\n let ms = Number(v.getBigUint64(p + 24, true)) / 1e6;\n if (v.getUint16(p + 40, true) & SUBCLOCK_ABSTIME) ms -= Number(now(id)) / 1e6;\n sub.deadline = at + Math.max(0, ms);\n } else {\n sub.fd = v.getUint32(p + 16, true);\n }\n subs.push(sub);\n }\n return subs;\n}\nfunction writeEvents(mem, ptr, events) {\n const v = mem.view();\n events.forEach((ev, i) => {\n const p = ptr + i * SIZE.EVENT;\n mem.bytes(p, SIZE.EVENT).fill(0);\n v.setBigUint64(p, ev.userdata, true);\n v.setUint16(p + 8, ev.error, true);\n v.setUint8(p + 10, ev.type);\n if (ev.type !== EVENTTYPE.CLOCK) {\n v.setBigUint64(p + 16, BigInt(ev.nbytes ?? 1), true);\n if (ev.hangup) v.setUint16(p + 24, EVENT_FD_READWRITE_HANGUP, true);\n }\n });\n}\nasync function classify(fds, subs) {\n const events = [];\n const read2 = [];\n const write2 = [];\n for (const s of subs) {\n if (s.type === EVENTTYPE.CLOCK) continue;\n const e = await fds.find(s.fd);\n if (!e) events.push({ userdata: s.userdata, error: E.BADF, type: s.type });\n else if (e.type !== \"kernel\")\n events.push({ userdata: s.userdata, error: E.SUCCESS, type: s.type });\n else (s.type === EVENTTYPE.FD_READ ? read2 : write2).push(s.fd);\n }\n return { events, read: read2, write: write2 };\n}\nfunction nbytesOf(s, ready) {\n const n = s.type === EVENTTYPE.FD_READ ? ready.nread?.[s.fd] : void 0;\n return n === void 0 ? {} : { nbytes: n };\n}\nfunction readyEvents(subs, ready) {\n return subs.filter(\n (s) => s.type === EVENTTYPE.FD_READ && ready.read.includes(s.fd) || s.type === EVENTTYPE.FD_WRITE && ready.write.includes(s.fd)\n ).map((s) => ({\n userdata: s.userdata,\n error: E.SUCCESS,\n type: s.type,\n hangup: ready.hangup?.includes(s.fd) === true,\n ...nbytesOf(s, ready)\n }));\n}\nvar RESUMES = 64;\nasync function selectOnce(deps, read2, write2, timeoutMs2, mayResume) {\n try {\n const ready = await deps.kernel.call({ op: \"fd-select\", read: read2, write: write2, timeoutMs: timeoutMs2 });\n return { ready, interrupted: false };\n } catch (e) {\n if (e.code !== \"EINTR\") throw e;\n if (!deps.interruptWakes && mayResume && await deps.resumes?.()) {\n return { ready: { read: [], write: [] }, interrupted: false, resumed: true };\n }\n if (!deps.interruptWakes) throw e;\n return { ready: { read: [], write: [] }, interrupted: true };\n }\n}\nasync function waitEvents(deps, subs, { events, read: read2, write: write2 }, entered) {\n const earliest = subs.reduce((min, s) => Math.min(min, s.deadline), Infinity);\n const timeout = () => {\n if (events.length > 0 || entered) return 0;\n return earliest === Infinity ? -1 : Math.max(0, Math.ceil(earliest - performance.now()));\n };\n for (let resumes = 0; ; ) {\n const { ready, interrupted, resumed } = await selectOnce(\n deps,\n read2,\n write2,\n timeout(),\n resumes++ < RESUMES\n );\n if (resumed) continue;\n events.push(...readyEvents(subs, ready));\n if (interrupted) return true;\n if (events.length > 0 || entered || earliest === Infinity) return false;\n if (performance.now() >= earliest) return false;\n }\n}\nasync function pollOneoff(deps, inPtr, outPtr, nsubs, neventsPtr) {\n if (nsubs === 0) return E.INVAL;\n const { mem } = deps;\n const subs = readSubscriptions(mem, inPtr, nsubs, deps.now);\n const found = await classify(deps.fds, subs);\n const { events, read: read2, write: write2 } = found;\n const entered = deps.entered === true && deps.interruptWakes !== true;\n const waits = read2.length > 0 || write2.length > 0 || events.length === 0;\n const interrupted = waits && await waitEvents(deps, subs, found, entered);\n const after = performance.now();\n if (entered && events.length === 0 && !subs.some((s) => s.deadline <= after)) return E.INTR;\n for (const s of subs) {\n if (s.type === EVENTTYPE.CLOCK && (interrupted || s.deadline <= after)) {\n events.push({ userdata: s.userdata, error: E.SUCCESS, type: s.type });\n }\n }\n writeEvents(mem, outPtr, events);\n mem.view().setUint32(neventsPtr, events.length, true);\n return E.SUCCESS;\n}\n\n// src/process/wasi/wasi-sigmask.ts\nvar UNBLOCKABLE = sigbit(SIG.KILL) | sigbit(SIG.STOP);\nvar LIBC_UNBLOCKABLE = 1 << SIG.KILL - 1 | 1 << SIG.STOP - 1;\nvar FOREVER = 0xffffffffffffffffn;\nvar NS_PER_MS2 = 1000000n;\nvar POLL_MS = 50;\nvar SIG_BLOCK = 0;\nvar SIG_UNBLOCK = 1;\nvar SIG_SETMASK = 2;\nvar kernelBits = (lo) => lo << 1 & ~UNBLOCKABLE;\nvar libcBits = (bits) => bits >>> 1 & ~LIBC_UNBLOCKABLE;\nvar apply = (how, mask, set) => {\n if (how === SIG_BLOCK) return mask | set;\n if (how === SIG_UNBLOCK) return mask & ~set;\n return set;\n};\nvar WasiSigmask = class {\n lo;\n hi;\n header;\n deliver;\n process;\n tid;\n published;\n constructor(header, deliver, process, tid = 1, published) {\n this.header = header;\n this.deliver = deliver;\n this.process = process;\n this.tid = tid;\n this.published = published;\n this.lo = libcBits(Atomics.load(header, SAB_I_BLOCKED));\n this.hi = Atomics.load(header, SAB_I_BLOCKED_HI);\n }\n static unsupported(header) {\n storeBlocked(header, [0, 0]);\n }\n async set(how, setLo, setHi, old) {\n if (how !== SIG_BLOCK && how !== SIG_UNBLOCK && how !== SIG_SETMASK) return E.INVAL;\n old(this.lo >>> 0, this.hi >>> 0);\n this.lo = apply(how, this.lo, setLo | 0) & ~LIBC_UNBLOCKABLE;\n this.hi = apply(how, this.hi, setHi | 0);\n const now = kernelBits(this.lo);\n storeBlocked(this.header, [now, this.hi]);\n this.published?.();\n if ((Atomics.load(this.header, SAB_I_SIGNALS) & ~now) !== 0) await this.deliver();\n return E.SUCCESS;\n }\n swap(setLo, setHi) {\n const old = [this.lo, this.hi];\n this.lo = setLo & ~LIBC_UNBLOCKABLE;\n this.hi = setHi | 0;\n storeBlocked(this.header, [kernelBits(this.lo), this.hi]);\n this.published?.();\n return old;\n }\n async deliverUnblocked() {\n const now = Atomics.load(this.header, SAB_I_BLOCKED);\n if ((Atomics.load(this.header, SAB_I_SIGNALS) & ~now) === 0) return false;\n await this.deliver();\n return true;\n }\n async restore([lo, hi]) {\n await this.set(SIG_SETMASK, lo, hi, () => {\n });\n }\n blockedBits() {\n return Atomics.load(this.header, SAB_I_BLOCKED);\n }\n blocks(sig) {\n return (Atomics.load(this.header, SAB_I_BLOCKED) & sigbit(sig)) !== 0;\n }\n inherited() {\n return [kernelBits(this.lo), this.hi];\n }\n discard(sig) {\n Atomics.and(this.header, SAB_I_SIGNALS, ~sigbit(sig));\n if (this.process) Atomics.and(this.process, SAB_I_SIGNALS, ~sigbit(sig));\n }\n async sigwait(setLo, timeoutNs, publish, took, entered = false) {\n const set = kernelBits(setLo | 0);\n const value2 = BigInt.asUintN(64, timeoutNs);\n const deadline = value2 === FOREVER ? Number.POSITIVE_INFINITY : performance.now() + Number((value2 + NS_PER_MS2 - 1n) / NS_PER_MS2);\n await publish(set);\n try {\n for (; ; ) {\n const seen = Atomics.load(this.header, SAB_I_SIGNALS);\n const sig = this.take(set);\n if (sig !== 0) {\n took(sig);\n return E.SUCCESS;\n }\n if (entered || await this.deliverUnblocked() || await this.interrupted()) return E.INTR;\n const left = deadline - performance.now();\n if (left <= 0) return E.AGAIN;\n await atomicsWait(this.header, SAB_I_SIGNALS, seen, Math.min(left, POLL_MS));\n }\n } finally {\n await publish(0);\n }\n }\n take(set) {\n for (const header of this.process ? [this.header, this.process] : [this.header]) {\n const ready = Atomics.load(header, SAB_I_SIGNALS) & set;\n if (ready === 0) continue;\n const bit = ready & -ready;\n if ((Atomics.and(header, SAB_I_SIGNALS, ~bit) & bit) !== 0) return 31 - Math.clz32(bit);\n }\n return 0;\n }\n async interrupted() {\n const killed = this.process ?? this.header;\n if (Atomics.load(killed, SAB_I_KILLED) !== 0) {\n await this.deliver();\n return true;\n }\n if (Atomics.load(killed, SAB_I_STOP) !== 1) return false;\n while (Atomics.load(killed, SAB_I_STOP) === 1) await atomicsWait(killed, SAB_I_STOP, 1);\n return true;\n }\n pending() {\n const own = Atomics.load(this.header, SAB_I_SIGNALS);\n return libcBits(own | (this.process ? Atomics.load(this.process, SAB_I_SIGNALS) : 0));\n }\n};\n\n// src/process/wasi/wasi-termios.ts\nvar NCCS3 = 32;\nvar C_LINE2 = 16;\nvar C_CC2 = 17;\nvar ISPEED = 52;\nvar OSPEED = 56;\nvar CBAUD2 = 4111;\nvar TCSAFLUSH = 2;\nfunction writeTermios(mem, ptr, termios) {\n mem.bytes(ptr, OSPEED + 4).fill(0);\n const v = mem.view();\n v.setUint32(ptr, termios.c_iflag, true);\n v.setUint32(ptr + 4, termios.c_oflag, true);\n v.setUint32(ptr + 8, termios.c_cflag, true);\n v.setUint32(ptr + 12, termios.c_lflag, true);\n for (let i = 0; i < NCCS3; i++) v.setUint8(ptr + C_CC2 + i, termios.c_cc[i] ?? 0);\n v.setUint8(ptr + C_LINE2, 0);\n v.setUint32(ptr + ISPEED, termios.c_cflag & CBAUD2, true);\n v.setUint32(ptr + OSPEED, termios.c_cflag & CBAUD2, true);\n}\nfunction readTermios(mem, ptr) {\n const v = mem.view();\n return {\n c_iflag: v.getUint32(ptr, true),\n c_oflag: v.getUint32(ptr + 4, true),\n c_cflag: v.getUint32(ptr + 8, true),\n c_lflag: v.getUint32(ptr + 12, true),\n c_cc: Array.from({ length: NCCS3 }, (_, i) => v.getUint8(ptr + C_CC2 + i))\n };\n}\nfunction sliccTty(mem, fds, kernel, interrupted = () => void 0) {\n const { sys } = kernel;\n const terminal2 = async (fd) => {\n const e = await fds.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type !== \"kernel\" || await fds.kind(fd, e) !== \"tty\") throw new WasiError(\"ENOTTY\");\n return fd;\n };\n const needs = (value2) => {\n if (value2 === void 0) throw new WasiError(\"ENOTTY\");\n return value2;\n };\n const getAttr = async (fd, ptr) => {\n await interrupted();\n writeTermios(mem, ptr, needs(await sys.tcgets?.(await terminal2(fd))));\n };\n const setAttr = async (fd, actions, ptr) => {\n await interrupted();\n if (actions < 0 || actions > TCSAFLUSH) throw new WasiError(\"EINVAL\");\n const at = await terminal2(fd);\n needs(sys.tcsets);\n await sys.tcsets?.(at, readTermios(mem, ptr), actions === TCSAFLUSH, actions !== 0);\n };\n const control = async (fd, request, arg) => {\n await interrupted();\n const e = await fds.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type !== \"kernel\") throw new WasiError(\"ENOTTY\");\n const asked = request >>> 0;\n const value2 = ioctlArg(mem.view(), asked, arg >>> 0);\n const result = await needs(sys.devIoctl).call(sys, fd, asked, value2);\n ioctlResult(mem.view(), asked, arg >>> 0, result);\n };\n const size = async (fd, ptr) => {\n await interrupted();\n const [rows, cols] = needs(await sys.winsize?.(await terminal2(fd)));\n mem.bytes(ptr, 8).fill(0);\n const v = mem.view();\n v.setUint16(ptr, rows, true);\n v.setUint16(ptr + 2, cols, true);\n };\n return {\n tcgetattr: async (fd, ptr) => void await getAttr(fd, ptr),\n tcsetattr: async (fd, actions, ptr) => void await setAttr(fd, actions, ptr),\n winsize: async (fd, ptr) => void await size(fd, ptr),\n ioctl: async (fd, request, arg) => void await control(fd, request, arg)\n };\n}\n\n// src/process/wasi/wasix-epoll.ts\nvar EVENT_SIZE = 32;\nvar DATA_OFFSET = 8;\nvar DATA_SIZE = 24;\nvar MAX_EVENTS = 4096;\nvar FOREVER2 = 0xffffffffffffffffn;\nvar MAX_TIMEOUT_MS = 2147483647;\nvar NS_PER_MS3 = 1000000n;\nvar EVENTFD_SEMAPHORE = 1;\nvar EVENTFD_NONBLOCK = 4;\nvar EVENTFD_MAX = 0xfffffffffffffffen;\nvar WASIX_OPS = [\"add\", \"mod\", \"del\"];\nvar DUAL_OPS = [\"add\", \"set\", \"del\", \"mod\"];\nfunction timeoutMs(ns) {\n const value2 = BigInt.asUintN(64, ns);\n if (value2 === FOREVER2) return -1;\n const ms = (value2 + NS_PER_MS3 - 1n) / NS_PER_MS3;\n return ms > BigInt(MAX_TIMEOUT_MS) ? -1 : Number(ms);\n}\nfunction wasixEpollImports(host) {\n const { mem, fds, o } = host;\n const call2 = async (req) => await o.kernel.call(req);\n const kernelFd = async (fd, refusal2) => {\n const e = await fds.find(fd);\n if (!e) throw new WasiError(\"EBADF\");\n if (e.type !== \"kernel\") throw new WasiError(refusal2);\n };\n const writeEvents2 = (ptr, events) => {\n const view = mem.view();\n events.forEach((ev, i) => {\n const at = ptr + i * EVENT_SIZE;\n mem.bytes(at, EVENT_SIZE).fill(0);\n view.setUint32(at, ev.events, true);\n mem.bytes(at + DATA_OFFSET, DATA_SIZE).set(ev.data);\n });\n };\n return {\n epoll_create: async (out) => {\n const fd = await call2({ op: \"epoll-create\" });\n await fds.adopt(fd, \"stream\", false);\n mem.view().setUint32(out, fd, true);\n },\n epoll_ctl: async (epfd, op, fd, event) => {\n const how = (host.strictEpoll ? WASIX_OPS : DUAL_OPS)[op];\n if (!how) throw new WasiError(\"EINVAL\");\n await kernelFd(epfd, \"EINVAL\");\n await kernelFd(fd, \"EPERM\");\n if (how !== \"del\" && event === 0) throw new WasiError(\"EINVAL\");\n const events = event === 0 ? 0 : mem.view().getUint32(event, true);\n const data = event === 0 ? [] : [...mem.bytes(event + DATA_OFFSET, DATA_SIZE)];\n await call2({ op: \"epoll-ctl\", epfd, how, fd, events, data });\n },\n epoll_wait: async (epfd, ptr, maxevents, timeout, out) => {\n mem.view().setUint32(out, 0, true);\n if ((maxevents | 0) <= 0) throw new WasiError(\"EINVAL\");\n await kernelFd(epfd, \"EINVAL\");\n const max = Math.min(maxevents | 0, MAX_EVENTS);\n const ms = host.entered ? 0 : timeoutMs(timeout);\n const events = await call2({ op: \"epoll-wait\", epfd, max, timeoutMs: ms });\n if (host.entered && events.length === 0 && timeoutMs(timeout) !== 0) return E.INTR;\n writeEvents2(ptr, events);\n mem.view().setUint32(out, events.length, true);\n return E.SUCCESS;\n },\n fd_event: async (initial, flags, out) => {\n const value2 = BigInt.asUintN(64, initial);\n if (value2 > EVENTFD_MAX) throw new WasiError(\"EINVAL\");\n const fd = await call2({\n op: \"eventfd-open\",\n initial: value2.toString(),\n semaphore: (flags & EVENTFD_SEMAPHORE) !== 0\n });\n await fds.adopt(fd, \"stream\", (flags & EVENTFD_NONBLOCK) !== 0);\n mem.view().setUint32(out, fd, true);\n }\n };\n}\n\n// src/kernel/net/datagram-wire.ts\nfunction decodeReceived(raw) {\n const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);\n const length = view.getUint8(3);\n return {\n truncated: (view.getUint8(0) & 1) !== 0,\n unix: (view.getUint8(0) & 2) !== 0,\n port: view.getUint16(1),\n host: new TextDecoder().decode(raw.subarray(4, 4 + length)),\n bytes: raw.subarray(4 + length)\n };\n}\n\n// src/kernel/net/routes.ts\nvar HOST_ADDRESS = HOST_LOOPBACK_ADDRESS.join(\".\");\nfunction ipv4Bytes(text) {\n const parts = text.split(\".\");\n if (parts.length !== 4 || !parts.every((p) => /^\\d{1,3}$/.test(p))) return void 0;\n const bytes = parts.map(Number);\n return bytes.every((b) => b <= 255) ? bytes : void 0;\n}\nfunction ipv6Groups(text) {\n if (!text.includes(\":\")) return void 0;\n let canonical;\n try {\n canonical = new URL(`http://[${text}]/`).hostname.slice(1, -1);\n } catch {\n return void 0;\n }\n const [head, tail] = canonical.split(\"::\");\n const part = (s) => s ? s.split(\":\").map((h) => Number.parseInt(h, 16)) : [];\n const front = part(head);\n const back = part(tail);\n return tail === void 0 ? front : [...front, ...new Array(8 - front.length - back.length).fill(0), ...back];\n}\nfunction toBits(values, width) {\n return values.reduce((acc, v) => acc << BigInt(width) | BigInt(v), 0n);\n}\nfunction addressBits(host) {\n const v4 = ipv4Bytes(host);\n if (v4) return { v6: false, bits: toBits(v4, 8) };\n const v6 = ipv6Groups(host);\n return v6 ? { v6: true, bits: toBits(v6, 16) } : void 0;\n}\nfunction parsePrefix(text) {\n const parts = text.trim().split(\"/\");\n if (parts.length > 2) return void 0;\n const [address = \"\", size] = parts;\n const parsed = addressBits(address);\n if (!parsed) return void 0;\n const max = parsed.v6 ? 128 : 32;\n const length = size === void 0 ? max : /^\\d{1,3}$/.test(size) ? Number(size) : -1;\n if (length < 0 || length > max) return void 0;\n return { ...parsed, length };\n}\nvar RESERVED = [\n \"0.0.0.0/8\",\n \"127.0.0.0/8\",\n \"169.254.0.0/16\",\n \"224.0.0.0/4\",\n \"240.0.0.0/4\",\n \"::/96\",\n \"::ffff:0:0/96\",\n \"fe80::/10\",\n \"ff00::/8\"\n].map((p) => parsePrefix(p));\n\n// src/process/wasi/wasix-sockets.ts\nvar INET4 = 1;\nvar INET6 = 2;\nvar UNIX = 3;\nvar STREAM = 1;\nvar DGRAM = 2;\nvar RECV_DATA_TRUNCATED = 1;\nvar RIFLAG_PEEK = 1;\nvar MAX_DATAGRAM = 65536;\nvar ADDR_IP_SIZE = 18;\nvar LOOPBACK = \"127.0.0.1\";\nvar OPTIONS = {\n 1: [1, 15],\n 2: [1, 2],\n 3: [6, 1],\n 4: [1, 5],\n 6: [1, 6],\n 10: [1, 30],\n 11: [1, 4],\n 12: [1, 9],\n 14: [1, 10],\n 15: [1, 8],\n 16: [1, 7],\n 25: [1, 3]\n};\nfunction readAddr(view, ptr) {\n const tag = view.getUint8(ptr);\n if (tag === UNIX) {\n let end = ptr + 2;\n while (end < ptr + 110 && view.getUint8(end) !== 0) end++;\n const path = new TextDecoder().decode(\n new Uint8Array(view.buffer, ptr + 2, end - ptr - 2).slice()\n );\n return { family: \"unix\", path };\n }\n const port = view.getUint16(ptr + 2, true);\n if (tag === INET4) {\n const host = [0, 1, 2, 3].map((i) => view.getUint8(ptr + 4 + i)).join(\".\");\n return { family: \"inet\", host, port };\n }\n if (tag === INET6) {\n return { family: \"inet\", host: ipv6Host(new Uint8Array(view.buffer, ptr + 4, 16)), port };\n }\n throw new WasiError(\"EAFNOSUPPORT\");\n}\nfunction ipv6Host(bytes) {\n const zeros = (n) => bytes.subarray(0, n).every((b) => b === 0);\n if (zeros(16)) return \"0.0.0.0\";\n if (zeros(15) && bytes[15] === 1) return LOOPBACK;\n if (zeros(10) && bytes[10] === 255 && bytes[11] === 255) return bytes.subarray(12).join(\".\");\n const groups = [0, 2, 4, 6, 8, 10, 12, 14].map(\n (i) => (bytes[i] << 8 | bytes[i + 1]).toString(16)\n );\n return new URL(`http://[${groups.join(\":\")}]/`).hostname.slice(1, -1);\n}\nfunction writeAddr(view, ptr, addr) {\n new Uint8Array(view.buffer, ptr, 110).fill(0);\n if (!addr) return;\n if (addr.family === \"unix\") {\n view.setUint8(ptr, UNIX);\n new Uint8Array(view.buffer, ptr + 2, 107).set(\n new TextEncoder().encode(addr.path).subarray(0, 107)\n );\n return;\n }\n view.setUint16(ptr + 2, addr.port, true);\n const groups = ipv4(addr.host) ? void 0 : ipv6Groups(addr.host);\n if (groups) {\n view.setUint8(ptr, INET6);\n groups.forEach((g, i) => void view.setUint16(ptr + 4 + i * 2, g));\n return;\n }\n view.setUint8(ptr, INET4);\n const octets = ipv4(addr.host) ?? [127, 0, 0, 1];\n octets.forEach((b, i) => void view.setUint8(ptr + 4 + i, b));\n}\nfunction ipBytes(host) {\n const groups = ipv4(host) ? void 0 : ipv6Groups(host);\n return groups ? groups.flatMap((g) => [g >> 8, g & 255]) : ipv4(host);\n}\nfunction ipv4(host) {\n const parts = host.split(\".\");\n if (parts.length !== 4) return void 0;\n const bytes = parts.map((p) => /^\\d{1,3}$/.test(p) ? Number(p) : Number.NaN);\n return bytes.every((b) => b >= 0 && b <= 255) ? bytes : void 0;\n}\nfunction openRequest2(af, type) {\n if (af !== INET4 && af !== INET6 && af !== UNIX) throw new WasiError(\"EAFNOSUPPORT\");\n if (type !== STREAM && type !== DGRAM) throw new WasiError(\"EPROTONOSUPPORT\");\n const domain = af === UNIX ? \"unix\" : \"inet\";\n return {\n op: \"sock-open\",\n domain,\n ...type === DGRAM ? { type: \"dgram\" } : {}\n };\n}\nfunction pairRequest(af, type) {\n if (af !== UNIX)\n throw new WasiError(af === INET4 || af === INET6 ? \"EOPNOTSUPP\" : \"EAFNOSUPPORT\");\n if (type !== STREAM && type !== DGRAM) throw new WasiError(\"EPROTONOSUPPORT\");\n return {\n op: \"sock-pair\",\n domain: \"unix\",\n ...type === DGRAM ? { type: \"dgram\" } : {}\n };\n}\nfunction absolute(cwd, addr) {\n if (addr.family !== \"unix\" || addr.path === \"\" || addr.path.startsWith(\"\\0\")) return addr;\n return addr.path.startsWith(\"/\") ? addr : { family: \"unix\", path: `${cwd}/${addr.path}` };\n}\nfunction optionalAddr(view, ptr) {\n if (ptr === 0 || view.getUint8(ptr) === 0) return void 0;\n return readAddr(view, ptr);\n}\nfunction datagramCalls(host) {\n const { mem, o } = host;\n const call2 = async (req) => await o.kernel.call(req);\n return {\n async recvFrom(fd, nonblock, iovs, n, riflags, outLen, outFlags, outAddr) {\n const max = Math.min(mem.capacity(iovs, n), MAX_DATAGRAM);\n const peek = (riflags & RIFLAG_PEEK) !== 0;\n const raw = await call2({ op: \"sock-recvfrom\", fd, max, peek, nonblock });\n const got = decodeReceived(raw);\n const view = mem.view();\n view.setUint32(outLen, mem.scatter(iovs, n, got.bytes), true);\n view.setUint16(outFlags, got.truncated ? RECV_DATA_TRUNCATED : 0, true);\n const from = got.unix ? { family: \"unix\", path: got.host } : { family: \"inet\", host: got.host, port: got.port };\n if (outAddr) writeAddr(mem.view(), outAddr, from);\n return E.SUCCESS;\n },\n async sendTo(fd, nonblock, iovs, n, addr, out) {\n const named = optionalAddr(mem.view(), addr);\n const to = named && absolute(await host.workingDir(), named);\n const body = mem.gather(iovs, n);\n const sent = await call2({ op: \"sock-sendto\", fd, body, ...to ? { addr: to } : {}, nonblock });\n mem.view().setUint32(out, sent, true);\n return E.SUCCESS;\n }\n };\n}\nfunction wasixSocketImports(host, preview1) {\n const { mem, fds, o } = host;\n const call2 = async (req) => await o.kernel.call(req);\n const socket = async (fd) => {\n const e = await fds.get(fd);\n if (e.type !== \"kernel\" || await fds.kind(fd, e) !== \"socket\") throw new WasiError(\"ENOTSOCK\");\n return e;\n };\n const option = (opt) => OPTIONS[opt];\n const datagrams = async (fd) => {\n try {\n const e = await fds.get(fd);\n return e.type === \"kernel\" && await fds.datagram(fd, e);\n } catch {\n return false;\n }\n };\n const dgram = datagramCalls(host);\n return {\n sock_open: async (af, type, _proto, out) => {\n const req = openRequest2(af, type);\n const fd = await call2(req);\n await fds.adopt(fd, \"socket\", false, \"type\" in req);\n mem.view().setUint32(out, fd, true);\n },\n sock_pair: async (af, type, _proto, out1, out2) => {\n const req = pairRequest(af, type);\n mem.view().setUint32(out1, 0, true);\n mem.view().setUint32(out2, 0, true);\n const [a, b] = await call2(req);\n await fds.adopt(a, \"socket\", false, \"type\" in req);\n await fds.adopt(b, \"socket\", false, \"type\" in req);\n mem.view().setUint32(out1, a, true);\n mem.view().setUint32(out2, b, true);\n },\n sock_bind: async (fd, addr) => {\n await socket(fd);\n await call2({ op: \"sock-bind\", fd, addr: absolute(await host.workingDir(), readAddr(mem.view(), addr)) });\n },\n sock_listen: async (fd, backlog) => {\n await socket(fd);\n await call2({ op: \"sock-listen\", fd, backlog });\n },\n sock_connect: async (fd, addr) => {\n const e = await socket(fd);\n const to = absolute(await host.workingDir(), readAddr(mem.view(), addr));\n await call2({ op: \"sock-connect\", fd, addr: to, nonblock: e.nonblock });\n },\n sock_accept_v2: async (fd, flags, outFd, outAddr) => {\n const e = await socket(fd);\n const r = await call2({ op: \"sock-accept\", fd, nonblock: e.nonblock });\n await fds.adopt(r.fd, \"socket\", (flags & FDFLAGS.NONBLOCK) !== 0);\n mem.view().setUint32(outFd, r.fd, true);\n writeAddr(mem.view(), outAddr, r.peer);\n },\n sock_addr_local: async (fd, out) => {\n await socket(fd);\n writeAddr(mem.view(), out, await call2({ op: \"sock-name\", fd, peer: false }));\n },\n sock_addr_peer: async (fd, out) => {\n await socket(fd);\n writeAddr(mem.view(), out, await call2({ op: \"sock-name\", fd, peer: true }));\n },\n sock_recv_from: async (fd, iovs, n, riflags, outLen, outFlags, outAddr) => {\n if (await datagrams(fd)) {\n const e = await socket(fd);\n return await dgram.recvFrom(fd, e.nonblock, iovs, n, riflags, outLen, outFlags, outAddr);\n }\n const r = await preview1.sock_recv(\n fd,\n iovs,\n n,\n riflags,\n outLen,\n outFlags\n );\n if (r !== E.SUCCESS) return r;\n writeAddr(mem.view(), outAddr, await call2({ op: \"sock-name\", fd, peer: true }));\n return E.SUCCESS;\n },\n sock_send_to: async (fd, iovs, n, flags, addr, out) => {\n if (await datagrams(fd)) return await dgram.sendTo(fd, (await socket(fd)).nonblock, iovs, n, addr, out);\n return await preview1.sock_send(\n fd,\n iovs,\n n,\n flags,\n out\n );\n },\n sock_status: async (fd, out) => {\n await socket(fd);\n mem.view().setUint8(out, 1);\n },\n sock_get_opt_flag: async (fd, opt, out) => {\n await socket(fd);\n const pair = option(opt);\n const v = pair ? await call2({ op: \"sock-getopt\", fd, level: pair[0], name: pair[1] }) : 0;\n mem.view().setUint8(out, v ? 1 : 0);\n },\n sock_set_opt_flag: async (fd, opt, flag) => {\n await socket(fd);\n const pair = option(opt);\n if (pair) await call2({ op: \"sock-setopt\", fd, level: pair[0], name: pair[1], value: flag ? 1 : 0 });\n },\n sock_get_opt_size: async (fd, opt, out) => {\n await socket(fd);\n const pair = option(opt);\n const v = pair ? await call2({ op: \"sock-getopt\", fd, level: pair[0], name: pair[1] }) : 0;\n mem.view().setBigUint64(out, BigInt(v), true);\n },\n sock_set_opt_size: async (fd, opt, size) => {\n await socket(fd);\n const pair = option(opt);\n if (pair) await call2({ op: \"sock-setopt\", fd, level: pair[0], name: pair[1], value: Number(size) });\n },\n sock_get_opt_time: async (fd, _opt, out) => {\n await socket(fd);\n new Uint8Array(mem.view().buffer, out, 16).fill(0);\n },\n sock_set_opt_time: async (fd) => void await socket(fd),\n sock_send_file: () => E.NOSYS,\n resolve: async (name2, len, _port, addrs, naddrs, out) => {\n const found = await call2({ op: \"sock-resolve\", name: mem.string(name2, len), family: 0 });\n const ips = found.map(ipBytes).filter((ip) => ip !== void 0);\n if (ips.length === 0) throw new WasiError(\"ENOENT\");\n if (naddrs < 1) throw new WasiError(\"EINVAL\");\n const view = mem.view();\n const count = Math.min(ips.length, naddrs);\n new Uint8Array(view.buffer, addrs, ADDR_IP_SIZE * count).fill(0);\n for (let i = 0; i < count; i++) {\n const at = addrs + i * ADDR_IP_SIZE;\n view.setUint8(at, ips[i].length === 4 ? INET4 : INET6);\n new Uint8Array(view.buffer, at + 2, ips[i].length).set(ips[i]);\n }\n view.setUint32(out, count, true);\n }\n };\n}\n\n// src/process/wasi/wasi-host.ts\nvar WasiExit = class extends Error {\n code;\n constructor(code2) {\n super(`exit ${code2}`);\n this.code = code2;\n }\n};\nvar IDS = [\"ruid\", \"euid\", \"suid\", \"rgid\", \"egid\", \"sgid\"];\nvar NS_PER_MS4 = 1000000n;\nvar AT_SYMLINK_NOFOLLOW = 1;\nvar AT_FDCWD = -2;\nvar COPY_EXCL = 1;\nvar COPY_MODE = 2;\nvar AT_EACCESS = 2;\nvar ROOT_IDS = Object.freeze({ uid: 0, gid: 0 });\nvar GONE = /* @__PURE__ */ new Set([\"ENOENT\", \"ENOTDIR\"]);\nfunction timesChange(atim, mtim, flags) {\n const now = Date.now();\n const pick = (set, setNow, value2) => flags & setNow ? now : flags & set ? Number(value2 / NS_PER_MS4) : null;\n return {\n atimeMs: pick(FSTFLAGS.ATIM, FSTFLAGS.ATIM_NOW, atim),\n mtimeMs: pick(FSTFLAGS.MTIM, FSTFLAGS.MTIM_NOW, mtim),\n now: (flags & (FSTFLAGS.ATIM | FSTFLAGS.MTIM)) === 0\n };\n}\nfunction idOf(value2) {\n return value2 >>> 0 === 4294967295 ? void 0 : value2 >>> 0;\n}\nvar S_IFIFO = 4096;\nvar S_IFLNK = 40960;\nvar DEFAULT_UMASK = 18;\nvar MONOTONIC_BASE = BigInt(Math.round(performance.timeOrigin)) * NS_PER_MS4;\nvar MAX_READ = 1024 * 1024;\nvar SIGINFO_BYTES = 24;\nvar FD_ALIAS = /^\\/(?:dev\\/(stdin|stdout|stderr)|dev\\/fd\\/(\\d+)|proc\\/(self|[1-9]\\d*)\\/fd\\/(\\d+))$/;\nvar STDIO_FDS = { stdin: 0, stdout: 1, stderr: 2 };\nvar SIGPIPE_EXIT = 128 + SIG.PIPE;\nvar SIG_IGN = 1;\nfunction linkedOf(st) {\n return (st.nlink ?? 1) > 1 ? st : void 0;\n}\nasync function linkedElsewhere(fs, path) {\n try {\n return linkedOf(await fs.lstat(path));\n } catch {\n return void 0;\n }\n}\nfunction filetypeOf(s) {\n if (!s) return FILETYPE.UNKNOWN;\n if (s.isSymbolicLink) return FILETYPE.SYMBOLIC_LINK;\n if (s.isDirectory) return FILETYPE.DIRECTORY;\n if (s.isSocket) return FILETYPE.SOCKET_STREAM;\n if (((s.mode ?? 0) & 61440) === 8192) return FILETYPE.CHARACTER_DEVICE;\n return s.isFile ? FILETYPE.REGULAR_FILE : FILETYPE.UNKNOWN;\n}\nfunction filestatOf(path, s) {\n return {\n filetype: filetypeOf(s),\n size: BigInt(s.size),\n ino: s.ino !== void 0 ? BigInt(s.ino) : pathInode(path),\n ...s.nlink !== void 0 ? { nlink: BigInt(s.nlink) } : {},\n mtimeNs: BigInt(Math.round(s.mtimeMs ?? 0)) * NS_PER_MS4\n };\n}\nvar SEALED_MODE = 8630;\nvar DEVICE_MODE = 8630;\nfunction kernelDev(path) {\n return inDev(path) && path !== SEALED_PATH && path !== CLIPBOARD_PATH;\n}\nfunction kernelFiletype(kind) {\n switch (kind) {\n case \"tty\":\n case \"sealed\":\n case \"clipboard\":\n case \"embedder\":\n return { filetype: FILETYPE.CHARACTER_DEVICE, seeks: false };\n case \"device\":\n return { filetype: FILETYPE.CHARACTER_DEVICE, seeks: true };\n case \"socket\":\n return { filetype: FILETYPE.SOCKET_STREAM, seeks: false };\n case \"dgram\":\n return { filetype: FILETYPE.SOCKET_DGRAM, seeks: false };\n case \"file\":\n return { filetype: FILETYPE.REGULAR_FILE, seeks: true };\n default:\n return { filetype: FILETYPE.UNKNOWN, seeks: false };\n }\n}\nvar WasiHost = class {\n mem = new WasiMemory();\n fds;\n creds;\n umasks;\n started = performance.now();\n cache;\n startCwd;\n interruptWakes = false;\n strictEpoll = false;\n cwdFd = false;\n entered = false;\n enteredSignals = 0;\n raisedOnEntry;\n onRaise;\n muted;\n signals;\n sigmask;\n tid = 1;\n linkedTls;\n threadEntry;\n linkedModules;\n interrupted;\n quietly = UNGATED.quiet;\n deliverDue = UNGATED.deliver;\n futexes = atomicFutexes;\n listening = [];\n o;\n constructor(o) {\n const { kernel } = o;\n const call2 = async (req) => {\n if (req.op !== \"fd-promote\") await this.fds.flushEarly();\n return await kernel.call(req);\n };\n const sys = new Proxy(kernel.sys, {\n get: (target, name2) => {\n const member = Reflect.get(target, name2);\n if (typeof member !== \"function\") return member;\n return async (...args) => {\n await this.fds.flushEarly();\n return member.apply(target, args);\n };\n }\n });\n this.o = { ...o, kernel: { sys, call: call2 } };\n this.startCwd = o.cwd;\n this.fds = new WasiFds(this.o.kernel, o.fs);\n if (o.held) this.fds.held = o.held;\n this.creds = new CredCache(\n async () => await this.o.kernel.call({ op: \"proc-cred\" }),\n o.credGen ?? o.shared\n );\n this.umasks = new UmaskCache(\n async (mask) => await this.o.kernel.call(\n mask === void 0 ? { op: \"proc-umask\" } : { op: \"proc-umask\", mask }\n ),\n o.credGen ?? o.shared,\n { quiet: async (fn) => await this.quietly(fn), deliver: async () => await this.deliverDue() }\n );\n }\n async attach() {\n const o = this.o;\n if (o.shared) await this.fds.share(o.shared, true);\n else if (o.forked) this.fds.restore(o.forked.fds, o.forked.cloexec);\n else if (!o.bare) await this.fds.setup(o.cwd, o.inherited ?? [], o.preopenRoot === true);\n this.listening = o.shared ? [] : this.fds.sockets();\n return this;\n }\n async fromCwd(raw) {\n return await this.fds.cwd() === void 0 ? await this.fds.resolve(3, `${await this.workingDir()}/${raw}`) : await this.fds.resolve(3, raw);\n }\n async workingDir() {\n return await this.fds.cwd() ?? this.startCwd;\n }\n async umask(mask) {\n return mask === void 0 ? await this.umasks.get() : await this.umasks.set(mask);\n }\n copyImport() {\n const { mem, fds } = this;\n const named = async (dirfd, p, l) => {\n const raw = mem.string(p, l);\n if (raw === \"\") throw new WasiError(\"ENOENT\");\n if (raw.startsWith(\"/\")) return await fds.resolve(3, raw);\n return dirfd === AT_FDCWD ? await this.fromCwd(raw) : await fds.resolve(dirfd, raw);\n };\n return async (...args) => {\n const [srcDirfd, sp, sl, dstDirfd, dp, dl, mode, flags] = args;\n if (!this.o.fs.copy) return E.NOSYS;\n if ((flags & ~(COPY_EXCL | COPY_MODE)) !== 0) throw new WasiError(\"EINVAL\");\n const from = await named(srcDirfd, sp, sl);\n const to = await named(dstDirfd, dp, dl);\n const bits = flags & COPY_MODE ? (await this.o.fs.stat(from)).mode ?? 0 : mode;\n await this.copyFile(from, to, bits, (flags & COPY_EXCL) !== 0);\n return E.SUCCESS;\n };\n }\n async copyFile(from, to, mode, exclusive) {\n const { copy } = this.o.fs;\n if (!copy) throw new WasiError(\"ENOSYS\");\n await this.fds.flushPath(from);\n await copy.call(this.o.fs, from, to, mode & 4095 & ~await this.umasks.get(), exclusive);\n }\n async created(path, mode) {\n const umask = await this.umasks.get();\n if (umask !== DEFAULT_UMASK) await this.o.fs.chmod(path, mode & ~umask);\n }\n sliccTtyImports() {\n return wrap(sliccTty(this.mem, this.fds, this.o.kernel, async () => await this.interrupted?.()));\n }\n sliccFsImports() {\n const { mem, fds } = this;\n const at = async (dirfd, p, l) => await fds.resolve(dirfd, mem.string(p, l));\n const pathOf = async (fd) => {\n const e = await fds.get(fd);\n if (e.type === \"dir\") return e.path;\n if (e.type === \"file\") return e.file.path;\n const path = e.type === \"kernel\" && await fds.kind(fd, e) === \"file\" ? (await this.kernelStat(fd)).path : void 0;\n if (path === void 0) throw new WasiError(\"EBADF\");\n return path;\n };\n const target = async (path, flags) => {\n if (flags & AT_SYMLINK_NOFOLLOW && (await this.o.fs.lstat(path)).isSymbolicLink) {\n throw new WasiError(\"ENOTSUP\");\n }\n return path;\n };\n const modeOf2 = (st) => (st.mode ?? 0) & 4095;\n const caller = async () => {\n const cred = await this.creds.get();\n return [cred.euid, cred.egid];\n };\n const owner = async (st, out) => {\n const [uid, gid] = st?.uid === void 0 ? await caller() : [st.uid, st.gid];\n const view = mem.view();\n view.getUint32(out + 4, true);\n view.setUint32(out, uid, true);\n view.setUint32(out + 4, gid, true);\n };\n const dev = {\n json: async (req) => await this.o.kernel.call(req)\n };\n const fdOwned = async (fd) => {\n const e = await fds.get(fd);\n if (e.type === \"device\") return ROOT_IDS;\n const kind = e.type === \"kernel\" ? await fds.kind(fd, e) : \"file\";\n if (kind === \"sealed\" || kind === \"clipboard\") return ROOT_IDS;\n if (kind === \"tty\") return await devSync(dev, devFdStat(fd));\n if (kind !== \"file\") return void 0;\n try {\n return await this.o.fs.stat(await pathOf(fd));\n } catch (err) {\n if (!GONE.has(err?.code)) throw err;\n return void 0;\n }\n };\n const fdMode = async (fd) => {\n const e = await fds.get(fd);\n if (e.type === \"device\") return DEVICE_MODE;\n const kind = e.type === \"kernel\" ? await fds.kind(fd, e) : void 0;\n if (kind === \"stream\") return S_IFIFO | 384;\n if (kind === \"sealed\" || kind === \"clipboard\") return SEALED_MODE;\n if (kind !== void 0 && kind !== \"file\")\n return (await devSync(dev, devFdStat(fd))).mode ?? DEVICE_MODE;\n return modeOf2(await this.o.fs.stat(await pathOf(fd)));\n };\n const pathOwned = async (path, follow2) => {\n const alias = this.fdAlias(path);\n if (alias && !follow2) return alias.stdio ? ROOT_IDS : void 0;\n if (alias) {\n await this.openFd(alias.fd);\n return await fdOwned(alias.fd);\n }\n if (this.synthetic(path)) return ROOT_IDS;\n if (kernelDev(path)) return await devSync(dev, devStat(path, follow2));\n return await this.viaDev(path, follow2, async () => await this.statOf(path, follow2), pathOwned);\n };\n const pathMode = async (path, follow2) => {\n const alias = this.fdAlias(path);\n if (alias && !follow2) {\n await this.fdTarget(alias);\n return S_IFLNK | 511;\n }\n if (alias) {\n await this.openFd(alias.fd);\n return await fdMode(alias.fd);\n }\n if (this.synthetic(path) && deviceOf(path) === void 0) return SEALED_MODE;\n if (kernelDev(path)) return (await devSync(dev, devStat(path, follow2))).mode ?? DEVICE_MODE;\n const fileMode = (st) => (st.isFifo ? S_IFIFO : 0) | modeOf2(st);\n return await this.viaDev(path, follow2, async () => fileMode(await this.statOf(path, follow2)), pathMode);\n };\n return wrap({\n fd_chown: async (fd, uid, gid) => {\n if (await this.serialFd(fd)) return void await this.o.kernel.sys.fdChown?.(fd, idOf(uid), idOf(gid));\n const e = await fds.get(fd);\n const handle = e.type === \"file\" ? e.file.buffer.handle : void 0;\n void await this.chownPath(await pathOf(fd), uid, gid, true, handle);\n },\n path_chown: async (dirfd, p, l, uid, gid, flags) => void await this.pathChown(await at(dirfd, p, l), uid, gid, (flags & AT_SYMLINK_NOFOLLOW) === 0),\n fd_owner: async (fd, out) => {\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n await owner(await fdOwned(fd), out);\n },\n fd_filestat_owner: async (fd, statOut, out) => {\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n this.writeFilestat(statOut, await this.fdFilestat(fd));\n await owner(await fdOwned(fd), out);\n },\n path_filestat_owner: async (dirfd, lookup2, p, l, statOut, out) => {\n const path = await at(dirfd, p, l);\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n this.writeFilestat(statOut, await this.pathFilestat(path, lookup2));\n await owner(await pathOwned(path, (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0), out);\n },\n path_owner: async (dirfd, p, l, flags, out) => {\n const path = await at(dirfd, p, l);\n if (!this.o.fs.owners) throw new WasiError(\"ENOTSUP\");\n await owner(await pathOwned(path, (flags & AT_SYMLINK_NOFOLLOW) === 0), out);\n },\n path_access: async (dirfd, p, l, amode, flags) => {\n const path = await at(dirfd, p, l);\n const nofollow = (flags & AT_SYMLINK_NOFOLLOW) !== 0;\n if (this.synthetic(path)) {\n if (this.o.fs.owners && amode & 1) throw new WasiError(\"EACCES\");\n return;\n }\n const st = await pathOwned(path, !nofollow);\n if (amode & 2 && st.readonly) throw new WasiError(\"EROFS\");\n if (!this.o.fs.owners) return;\n const kind = flags & AT_EACCESS ? \"eaccess\" : \"access\";\n await this.o.fs.access?.(path, amode & 7, kind, nofollow);\n },\n fd_chmod: async (fd, mode) => {\n if (await this.serialFd(fd)) return void await this.o.kernel.sys.fdChmod?.(fd, mode & 4095);\n await this.o.fs.chmod(await pathOf(fd), mode & 4095);\n },\n path_chmod: async (dirfd, p, l, mode, flags) => {\n const path = await target(await at(dirfd, p, l), flags);\n const bits = mode & 4095;\n await this.devChange(path, true, { mode: bits }, async () => await this.o.fs.chmod(path, bits));\n },\n path_mkfifo: async (dirfd, p, l, mode) => {\n const { mkfifo } = this.o.fs;\n if (!mkfifo) return E.NOSYS;\n const raw = mem.string(p, l);\n if (raw === \"\") throw new WasiError(\"ENOENT\");\n const path = dirfd === AT_FDCWD && !raw.startsWith(\"/\") ? await this.fromCwd(raw) : await at(dirfd, p, l);\n const umask = await this.umasks.get();\n const want = mode & 4095 & ~umask;\n await mkfifo.call(this.o.fs, path, want);\n const made = ((await this.o.fs.lstat(path)).mode ?? 0) & 4095;\n if ((made & ~want) !== 0) await this.o.fs.chmod(path, made & want);\n return E.SUCCESS;\n },\n path_copy_file: this.copyImport(),\n umask: async (mask, out) => {\n const old = await this.umasks.set(mask);\n mem.view().setUint32(out, old, true);\n },\n fd_mode: async (fd, out) => void mem.view().setUint32(out, await fdMode(fd), true),\n path_mode: async (dirfd, p, l, flags, out) => {\n const path = await at(dirfd, p, l);\n const mode = await pathMode(path, (flags & AT_SYMLINK_NOFOLLOW) === 0);\n mem.view().setUint32(out, mode, true);\n }\n });\n }\n async pathChown(path, uid, gid, follow2) {\n const ids = { uid: idOf(uid), gid: idOf(gid) };\n await this.devChange(path, follow2, ids, async () => await this.chownPath(path, uid, gid, follow2));\n }\n async chownPath(path, uid, gid, follow2, handle) {\n const { chown: own } = this.o.fs;\n if (!own) throw new WasiError(\"ENOSYS\");\n await own.call(this.o.fs, path, idOf(uid), idOf(gid), follow2, handle);\n }\n lockHost(mem) {\n return {\n mem,\n file: async (fd) => await this.lockedFile(fd),\n flush: async (file) => {\n if (file.path !== void 0) await this.fds.flushPath(file.path);\n else if (file.target.fd !== void 0) await this.o.kernel.sys.flush(file.target.fd);\n },\n locked: () => this.fds.holdLocks(),\n promote: async (fd, moved) => await this.fds.promote(fd, moved),\n reread: async (fd) => await this.fds.reread(fd),\n calls: {\n flock: async (fd, kind, wait) => await this.fds.restarting(\n async () => await this.o.kernel.call({ op: \"flock\", fd, kind, ...wait ? { wait } : {} })\n ),\n set: async (target, kind, start2, len, wait) => await this.fds.restarting(\n async () => await this.o.kernel.call({\n op: \"lk-set\",\n ...target,\n kind,\n start: start2,\n len,\n ...wait ? { wait } : {}\n })\n ),\n get: async (target, kind, start2, len) => await this.o.kernel.call({ op: \"lk-get\", ...target, kind, start: start2, len })\n }\n };\n }\n sliccImports() {\n const { mem } = this;\n const path = async (p, l) => {\n const text = mem.string(p, l);\n return text === \"\" || text.startsWith(\"/\") ? text : normalize(`${await this.workingDir()}/${text}`);\n };\n return wrap({\n mount: async (sp, sl, tp, tl, fp, fl, flags, dp, dl) => void await this.o.kernel.call({\n op: \"mount\",\n source: mem.string(sp, sl),\n target: await path(tp, tl),\n type: mem.string(fp, fl),\n flags,\n data: mem.string(dp, dl)\n }),\n umount2: async (tp, tl, flags) => void await this.o.kernel.call({ op: \"umount\", target: await path(tp, tl), flags }),\n cred_get: async (out) => {\n const cred = await this.creds.get();\n const view = mem.view();\n view.getUint32(out + 20, true);\n IDS.forEach((key, i) => void view.setUint32(out + i * 4, cred[key], true));\n },\n cred_set: async (...ids) => {\n const change = {};\n IDS.forEach((key, i) => {\n if (ids[i] !== -1) change[key] = ids[i] >>> 0;\n });\n void await this.creds.change(async () => await this.o.kernel.call({ op: \"proc-setcred\", change }));\n },\n ...semImports(this),\n ...lockImports(this.lockHost(mem)),\n groups_get: async (buf, cap, count) => {\n const { groups } = await this.creds.get();\n if (cap !== 0 && cap < groups.length) throw new WasiError(\"EINVAL\");\n const shown = cap === 0 ? [] : groups;\n const view = mem.view();\n view.getUint32(count, true);\n if (shown.length > 0) view.getUint32(buf + (shown.length - 1) * 4, true);\n shown.forEach((g, i) => void view.setUint32(buf + i * 4, g, true));\n view.setUint32(count, groups.length, true);\n },\n groups_set: async (buf, n) => {\n if (n < 0 || n > MAX_GROUPS) throw new WasiError(\"EINVAL\");\n const view = mem.view();\n const groups = Array.from({ length: n }, (_, i) => view.getUint32(buf + i * 4, true));\n void await this.creds.change(\n async () => await this.o.kernel.call({ op: \"proc-setcred\", change: { groups } })\n );\n },\n sigaction_set: (sig, disposition, flags) => {\n if (!this.signals) return E.NOSYS;\n const errno = this.signals.disposition(sig, disposition, flags);\n if (errno === E.SUCCESS && disposition === SIG_IGN) this.sigmask?.discard(sig);\n return errno;\n },\n sigmask_set: async (how, lo, hi, old) => {\n if (!this.sigmask) return E.NOSYS;\n if (how === SIG_UNBLOCK || how === SIG_SETMASK) {\n this.signals?.unblocking(how === SIG_UNBLOCK ? lo << 1 : ~(lo << 1));\n }\n return await this.sigmask.set(how, lo, hi, (oldLo, oldHi) => {\n if (old === 0) return;\n const view = mem.view();\n view.setUint32(old, oldLo, true);\n view.setUint32(old + 4, oldHi, true);\n });\n },\n sigmask_poll: async (lo, hi, inPtr, outPtr, n, nevents) => this.sigmask ? await this.maskedPoll(this.sigmask, [lo, hi], [inPtr, outPtr, n, nevents]) : E.NOSYS,\n sigmask_epoll_wait: async (lo, hi, epfd, events, max, timeout, nevents) => this.sigmask ? await this.maskedEpoll(\n this.sigmask,\n [lo, hi],\n nevents,\n async (epoll) => await epoll(epfd, events, max, timeout, nevents)\n ) : E.NOSYS,\n sigwait: async (lo, _hi, timeout, out) => {\n const mask = this.sigmask;\n if (!mask) return E.NOSYS;\n mem.view().setUint32(out, 0, true);\n return await mask.sigwait(\n lo,\n timeout,\n async (set) => void await this.o.kernel.call({ op: \"sig-waiting\", tid: mask.tid, set }),\n (sig) => void mem.view().setUint32(out, sig, true),\n this.entered\n );\n },\n sigwait_info: async (lo, _hi, timeout, info) => {\n const mask = this.sigmask;\n if (!mask) return E.NOSYS;\n let took = 0;\n const r = await mask.sigwait(\n lo,\n timeout,\n async (set) => void await this.o.kernel.call({ op: \"sig-waiting\", tid: mask.tid, set }),\n (sig) => {\n took = sig;\n },\n this.entered\n );\n if (r === E.SUCCESS) await this.writeSiginfo(info, took, mask.tid);\n return r;\n },\n siginfo_take: async (sig, info) => await this.writeSiginfo(info, sig, this.sigmask?.tid ?? this.tid, false) ? E.SUCCESS : E.NOENT,\n sigaction_inherited: async (out) => {\n const bits = await this.o.kernel.call({ op: \"sig-inherited\" });\n mem.view().setBigUint64(out, BigInt(libcBits(bits) >>> 0), true);\n return E.SUCCESS;\n },\n sigpending_get: (out) => {\n if (!this.sigmask) return E.NOSYS;\n mem.view().setBigUint64(out, BigInt(this.sigmask.pending()), true);\n return E.SUCCESS;\n }\n });\n }\n async poll(inPtr, outPtr, n, nevents, resume = true) {\n const ran = this.signals?.ran ?? 0;\n try {\n return await pollOneoff(\n {\n mem: this.mem,\n fds: this.fds,\n kernel: this.o.kernel,\n now: (id) => this.now(id),\n interruptWakes: this.interruptWakes,\n entered: this.entered,\n ...resume ? { resumes: async () => await this.resumesPoll(ran) } : {}\n },\n inPtr,\n outPtr,\n n,\n nevents\n );\n } finally {\n this.o.fs.invalidate?.();\n }\n }\n async resumesPoll(ran) {\n await this.interrupted?.();\n return (this.signals?.ran ?? 0) === ran;\n }\n async maskedPoll(mask, set, [inPtr, outPtr, n, nevents]) {\n const old = mask.swap(set[0], set[1]);\n try {\n this.mem.view().setUint32(nevents, 0, true);\n if (await mask.deliverUnblocked()) return E.INTR;\n this.settleEntry(mask);\n if (n > 0) return await this.poll(inPtr, outPtr, n, nevents, false);\n return this.entered ? E.INTR : await this.suspend();\n } finally {\n await mask.deliverUnblocked();\n await mask.restore(old);\n }\n }\n epollWait;\n settleEntry(mask) {\n if (this.entered && (this.enteredSignals & ~mask.blockedBits()) === 0) this.entered = false;\n }\n async maskedEpoll(mask, set, nevents, wait) {\n const old = mask.swap(set[0], set[1]);\n try {\n this.mem.view().setUint32(nevents, 0, true);\n if (await mask.deliverUnblocked()) return E.INTR;\n this.settleEntry(mask);\n this.epollWait ??= wasixEpollImports(this).epoll_wait;\n return await wait(this.epollWait) ?? E.SUCCESS;\n } finally {\n await mask.deliverUnblocked();\n await mask.restore(old);\n }\n }\n async suspend() {\n for (; ; ) {\n try {\n await this.o.kernel.call({ op: \"fd-select\", read: [], write: [], timeoutMs: -1 });\n } catch (e) {\n if (e.code === \"EINTR\") return E.INTR;\n throw e;\n }\n }\n }\n imports() {\n this.cache ??= wrap({\n ...this.processImports(),\n ...this.ioImports(),\n ...this.statImports(),\n ...this.pathImports(),\n ...this.socketImports(),\n poll_oneoff: async (inPtr, outPtr, n, nevents) => await this.poll(inPtr, outPtr, n, nevents)\n });\n return this.cache;\n }\n now(id) {\n if (id === CLOCK.REALTIME) return BigInt(Date.now()) * NS_PER_MS4;\n if (id === CLOCK.MONOTONIC) {\n return MONOTONIC_BASE + BigInt(Math.round(performance.now() * 1e6));\n }\n return (localCpuNanos() ?? BigInt(Math.round((performance.now() - this.started) * 1e6))) + 1n;\n }\n async environ() {\n if (this.o.bare) return Object.entries(this.o.env).map(([k, v]) => `${k}=${v}`);\n const listen = this.listening.length > 0 ? { SLICC_LISTEN_FDS: this.listening.join(\" \") } : {};\n const env = { PWD: await this.workingDir(), ...this.o.env, ...listen };\n return Object.entries(env).map(([k, v]) => `${k}=${v}`);\n }\n processImports() {\n const { mem } = this;\n return {\n args_get: (argv, buf) => void mem.putStrings(this.o.args, argv, buf),\n args_sizes_get: (n, size) => void mem.putSizes(this.o.args, n, size),\n environ_get: async (envp, buf) => void mem.putStrings(await this.environ(), envp, buf),\n environ_sizes_get: async (n, size) => void mem.putSizes(await this.environ(), n, size),\n clock_res_get: (_id, out) => void mem.view().setBigUint64(out, 1000n, true),\n clock_time_get: (id, _precision, out) => void mem.view().setBigUint64(out, this.now(id), true),\n random_get: (buf, len) => {\n for (let at = 0; at < len; at += 65536) {\n const chunk = new Uint8Array(Math.min(65536, len - at));\n crypto.getRandomValues(chunk);\n mem.bytes(buf + at, chunk.length).set(chunk);\n }\n },\n sched_yield: async () => {\n await this.futexes.pause();\n return E.SUCCESS;\n },\n proc_exit: (code2) => {\n throw new WasiExit(code2);\n },\n proc_raise: async (sig) => {\n const posix = WASI_SIGNAL_TO_POSIX[sig];\n if (posix === void 0) throw new WasiError(\"EINVAL\");\n if (await this.onRaise?.(posix)) return;\n await this.o.kernel.call({ op: \"proc-kill\", pid: this.o.pid, sig: posix });\n }\n };\n }\n ioImports() {\n const { mem, fds } = this;\n return {\n fd_write: async (fd, iovs, n, out) => void mem.view().setUint32(out, await this.write(fd, mem.gather(iovs, n)), true),\n fd_read: async (fd, iovs, n, out) => {\n const data = await this.read(fd, mem.capacity(iovs, n));\n mem.view().setUint32(out, mem.scatter(iovs, n, data), true);\n },\n fd_pread: async (fd, iovs, n, at, out) => {\n const data = await (await this.positional(fd, \"read\")).pread(mem.capacity(iovs, n), Number(at));\n mem.view().setUint32(out, mem.scatter(iovs, n, data), true);\n },\n fd_pwrite: async (fd, iovs, n, at, out) => void mem.view().setUint32(\n out,\n await (await this.positional(fd, \"write\")).pwrite(mem.gather(iovs, n), Number(at)),\n true\n ),\n fd_seek: async (fd, offset, whence, out) => void mem.view().setBigUint64(out, BigInt(await this.seek(fd, Number(offset), whence)), true),\n fd_tell: async (fd, out) => void mem.view().setBigUint64(out, BigInt(await this.seek(fd, 0, WHENCE.CUR)), true),\n fd_close: async (fd) => void await fds.close(fd),\n fd_renumber: async (from, to) => void await fds.renumber(from, to),\n fd_sync: async (fd) => void await this.sync(fd),\n fd_datasync: async (fd) => void await this.sync(fd),\n fd_advise: async (fd) => void await fds.get(fd),\n fd_allocate: async (fd, offset, len) => {\n const file = await this.positional(fd, \"write\");\n const end = Number(offset + len);\n if (end > await file.size()) await file.truncate(end);\n }\n };\n }\n statImports() {\n const { mem, fds } = this;\n return {\n fd_fdstat_get: async (fd, out) => void await this.fdstat(fd, out),\n fd_fdstat_set_flags: async (fd, flags) => void await fds.setFlags(fd, (flags & FDFLAGS.NONBLOCK) !== 0, (flags & FDFLAGS.APPEND) !== 0),\n fd_fdstat_set_rights: async (fd) => void await fds.get(fd),\n fd_filestat_get: async (fd, out) => void this.writeFilestat(out, await this.fdFilestat(fd)),\n fd_filestat_set_size: async (fd, size) => void await (await this.positional(fd, \"write\")).truncate(Number(size)),\n fd_filestat_set_times: async (fd, atim, mtim, flags) => {\n const e = await fds.get(fd);\n if (e.type === \"file\") {\n await e.file.flush();\n await this.setTimes(e.file.path, atim, mtim, flags);\n } else if (e.type === \"dir\") await this.setTimes(e.path, atim, mtim, flags);\n else if (await this.serialFd(fd)) {\n const { atimeMs, mtimeMs, now } = timesChange(atim, mtim, flags);\n await this.o.kernel.sys.fdUtimes?.(fd, atimeMs, mtimeMs, now);\n }\n },\n fd_prestat_get: async (fd, out) => {\n const name2 = new TextEncoder().encode((await fds.preopen(fd)).preopen);\n mem.view().setUint8(out, PREOPENTYPE_DIR);\n mem.view().setUint32(out + 4, name2.length, true);\n },\n fd_prestat_dir_name: async (fd, buf, len) => {\n const name2 = new TextEncoder().encode((await fds.preopen(fd)).preopen);\n mem.bytes(buf, Math.min(len, name2.length)).set(name2.subarray(0, len));\n },\n fd_readdir: async (fd, buf, len, cookie, used) => void await this.readdir(fd, buf, len, Number(cookie), used)\n };\n }\n pathImports() {\n const { mem, fds, o } = this;\n const at = async (dirfd, p, l) => await fds.resolve(dirfd, mem.string(p, l));\n return {\n path_open: async (dirfd, lookup2, p, l, oflags, rights, _inheriting, fdflags, out) => {\n const follow2 = (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0;\n try {\n const asked = await at(dirfd, p, l);\n const alias = this.fdAlias(asked);\n if (alias && !alias.stdio) await this.openFd(alias.fd);\n const path = alias && !alias.stdio ? `/dev/fd/${alias.fd}` : asked;\n if (deviceOf(path)) await this.interrupted?.();\n mem.view().setUint32(out, await fds.open(path, oflags, rights, fdflags, void 0, !follow2), true);\n if (fds.created) await this.created(path, 438);\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n const raw = mem.string(p, l);\n const joined2 = raw.startsWith(\"/\") ? raw : `${(await fds.dir(dirfd)).path}/${raw}`;\n const resolved2 = await this.resolveForDev(joined2, follow2);\n if (!resolved2) throw err;\n mem.view().setUint32(out, await fds.open(resolved2, oflags, rights, fdflags, void 0, !follow2), true);\n }\n },\n path_filestat_get: async (dirfd, lookup2, p, l, out) => {\n try {\n this.writeFilestat(out, await this.pathFilestat(await at(dirfd, p, l), lookup2));\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n const raw = mem.string(p, l);\n const joined2 = raw.startsWith(\"/\") ? raw : `${(await fds.dir(dirfd)).path}/${raw}`;\n const resolved2 = await this.resolveForDev(joined2, (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0);\n if (!resolved2) throw err;\n this.writeFilestat(out, await this.pathFilestat(resolved2, lookup2));\n }\n },\n path_filestat_set_times: async (dirfd, lookup2, p, l, atim, mtim, flags) => {\n const path = await at(dirfd, p, l);\n await fds.flushPath(path);\n await this.setTimes(path, atim, mtim, flags, (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0);\n },\n path_create_directory: async (dirfd, p, l) => {\n const path = await at(dirfd, p, l);\n if (await o.fs.exists(path)) throw new WasiError(\"EEXIST\");\n await o.fs.mkdir(path);\n await this.created(path, 511);\n },\n path_remove_directory: async (dirfd, p, l) => void await o.fs.rmdir(await at(dirfd, p, l)),\n path_unlink_file: async (dirfd, p, l) => {\n const path = await at(dirfd, p, l);\n if (inDevTree(path)) return void await o.fs.unlink(path);\n const st = await o.fs.lstat(path);\n if (st.isDirectory) throw new WasiError(\"EISDIR\");\n const linked = linkedOf(st);\n await fds.unlinking(path, linked);\n await o.fs.unlink(path);\n await fds.unlinked(path, linked);\n },\n path_rename: async (fd, p, l, fd2, p2, l2) => {\n const from = await at(fd, p, l);\n const to = await at(fd2, p2, l2);\n await fds.flushPath(from);\n const replaced = fds.holdsUnder(to) ? await linkedElsewhere(o.fs, to) : void 0;\n if (replaced === void 0) await fds.replacing(to);\n const seq = await o.fs.rename(from, to);\n await fds.renamed(from, to, replaced);\n fds.ownRename(typeof seq === \"number\" ? seq : void 0);\n },\n path_symlink: async (tp, tl, dirfd, p, l) => {\n const path = await at(dirfd, p, l);\n if (tl === 0) throw new WasiError(\"ENOENT\");\n await o.fs.symlink(mem.string(tp, tl), path);\n },\n path_readlink: async (dirfd, p, l, buf, len, used) => {\n const path = await at(dirfd, p, l);\n const alias = this.fdAlias(path);\n const target = new TextEncoder().encode(alias ? await this.fdTarget(alias) : await o.fs.readlink(path));\n const n = Math.min(len, target.length);\n mem.bytes(buf, n).set(target.subarray(0, n));\n mem.view().setUint32(used, n, true);\n },\n path_link: async (fd, lookup2, p, l, fd2, p2, l2) => {\n const from = await at(fd, p, l);\n const to = await at(fd2, p2, l2);\n const follow2 = (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0;\n const source = follow2 ? await physicalPath(o.fs, from) : from;\n await fds.flushPath(from);\n if (source !== from) await fds.flushPath(source);\n await o.fs.link(from, to, follow2);\n await fds.linked(from, to);\n if (source !== from) await fds.linked(source, to);\n }\n };\n }\n async socket(fd) {\n const e = await this.fds.get(fd);\n if (e.type !== \"kernel\" || await this.fds.kind(fd, e) !== \"socket\") throw new WasiError(\"ENOTSOCK\");\n return e;\n }\n socketImports() {\n const { mem, fds, o } = this;\n return {\n sock_accept: async (fd, flags, out) => {\n const listener = await this.socket(fd);\n const r = await o.kernel.call({ op: \"sock-accept\", fd, nonblock: listener.nonblock });\n await fds.adopt(r.fd, \"socket\", (flags & FDFLAGS.NONBLOCK) !== 0);\n mem.view().setUint32(out, r.fd, true);\n },\n sock_recv: async (fd, iovs, n, riflags, outLen, outFlags) => {\n const e = await this.socket(fd);\n if (await this.fds.datagram(fd, e)) {\n return await datagramCalls(this).recvFrom(\n fd,\n e.nonblock,\n iovs,\n n,\n riflags,\n outLen,\n outFlags,\n 0\n );\n }\n const peek = (riflags & RIFLAGS.PEEK) !== 0;\n const want = mem.capacity(iovs, n);\n const data = (riflags & RIFLAGS.WAITALL) !== 0 && !peek ? await this.recvAll(fd, want, e.nonblock) : await o.kernel.sys.read(fd, Math.min(want, MAX_READ), { nonblock: e.nonblock, peek });\n mem.view().setUint32(outLen, mem.scatter(iovs, n, data), true);\n mem.view().setUint16(outFlags, 0, true);\n },\n sock_send: async (fd, iovs, n, _flags, out) => {\n const e = await this.socket(fd);\n const sent = await o.kernel.sys.write(fd, mem.gather(iovs, n), { nonblock: e.nonblock });\n mem.view().setUint32(out, sent, true);\n },\n sock_shutdown: async (fd, how) => {\n await this.socket(fd);\n const both = SDFLAGS.RD | SDFLAGS.WR;\n if (how === 0 || (how & ~both) !== 0) throw new WasiError(\"EINVAL\");\n await o.kernel.call({\n op: \"sock-shutdown\",\n fd,\n how: how === both ? 2 : how === SDFLAGS.WR ? 1 : 0\n });\n }\n };\n }\n async recvAll(fd, want, nonblock) {\n const chunks = [];\n let got = 0;\n while (got < want) {\n let chunk;\n try {\n chunk = await this.o.kernel.sys.read(fd, Math.min(want - got, MAX_READ), { nonblock });\n } catch (err) {\n if (got === 0) throw err;\n break;\n }\n if (chunk.length === 0) break;\n chunks.push(chunk);\n got += chunk.length;\n }\n const out = new Uint8Array(got);\n let at = 0;\n for (const chunk of chunks) {\n out.set(chunk, at);\n at += chunk.length;\n }\n return out;\n }\n async file(fd, access3) {\n const e = await this.fds.get(fd);\n if (e.type !== \"file\") {\n throw new WasiError(e.type === \"dir\" ? \"EISDIR\" : e.type === \"kernel\" ? \"ESPIPE\" : \"EINVAL\");\n }\n if (access3 === \"read\" && !e.file.readable || access3 === \"write\" && !e.file.writable) {\n throw new WasiError(\"EBADF\");\n }\n return e.file;\n }\n async positional(fd, access3) {\n const e = await this.fds.get(fd);\n const kind = e.type === \"kernel\" ? await this.fds.kind(fd, e) : e.type;\n if (kind === \"device\") await this.interrupted?.();\n if (kind !== \"file\" || e.type !== \"kernel\") return await this.file(fd, access3);\n const kernel = this.o.kernel;\n return {\n pread: async (max, at) => {\n if (!kernel.sys.pread) throw new WasiError(\"ESPIPE\");\n return await kernel.sys.pread(fd, Math.min(max, MAX_READ), at);\n },\n pwrite: async (body, at) => await this.changed(fd, e, await kernel.call({ op: \"fd-pwrite\", fd, offset: at, body })),\n size: async () => (await this.kernelStat(fd)).size,\n truncate: async (size) => await this.changed(fd, e, void await kernel.call({ op: \"fd-resize\", fd, size }))\n };\n }\n unnamed = /* @__PURE__ */ new WeakSet();\n async changed(fd, e, result) {\n if (e.path === void 0 && !this.unnamed.has(e)) await this.learnPath(fd, e);\n this.o.fs.touched?.(e.path, e.ino);\n return result;\n }\n async learnPath(fd, e) {\n this.unnamed.add(e);\n let path;\n try {\n const st = await this.o.kernel.call({ op: \"fd-vfs-stat\", fd, identity: true });\n path = st.orphan ? void 0 : st.path;\n if (path !== void 0) e.ino = st.ino ?? (await this.o.fs.stat(path)).ino;\n } catch {\n return;\n }\n e.path = path;\n }\n async lockedFile(fd) {\n const e = await this.fds.get(fd);\n if (e.type === \"file\") {\n const { file } = e;\n return {\n target: { path: file.path },\n path: file.path,\n readable: file.readable,\n writable: file.writable,\n offset: () => file.offset,\n size: async () => await file.size()\n };\n }\n if (e.type !== \"kernel\") throw new WasiError(\"EBADF\");\n if (await this.fds.kind(fd, e) !== \"file\") return { target: { fd }, offset: () => 0, size: () => 0 };\n return {\n target: { fd },\n offset: async () => await this.o.kernel.sys.seek(fd, 0, WHENCE.CUR),\n size: async () => (await this.kernelStat(fd)).size\n };\n }\n async kernelStat(fd) {\n return await this.o.kernel.call({ op: \"fd-vfs-stat\", fd });\n }\n async write(fd, data) {\n if (this.muted?.(fd, data)) return data.length;\n const e = await this.fds.get(fd);\n if (e.type === \"kernel\") {\n try {\n const n = await this.o.kernel.sys.write(fd, data, { nonblock: e.nonblock });\n return await this.fds.kind(fd, e) === \"file\" ? await this.changed(fd, e, n) : n;\n } catch (err) {\n const broken = err.code === \"EPIPE\";\n if (broken && await this.fds.kind(fd, e) !== \"socket\") await this.brokenPipe();\n throw err;\n }\n }\n if (e.type === \"device\") {\n await this.interrupted?.();\n if (e.access === \"read\") throw new WasiError(\"EBADF\");\n if (e.device === \"full\" && data.length > 0) throw new WasiError(\"ENOSPC\");\n return data.length;\n }\n return await (await this.file(fd, \"write\")).write(data);\n }\n async brokenPipe() {\n let action;\n try {\n action = await this.o.kernel.call({ op: \"proc-kill-self\", sig: SIG.PIPE, dry: true });\n } catch {\n action = \"terminate\";\n }\n if (action === \"ignore\") return;\n if (action === \"terminate\" && !this.sigmask?.blocks(SIG.PIPE)) throw new WasiExit(SIGPIPE_EXIT);\n await this.o.kernel.call({ op: \"thread-kill\", tid: this.tid, sig: SIG.PIPE });\n }\n async read(fd, max) {\n const e = await this.fds.get(fd);\n if (e.type === \"kernel\") {\n return await this.o.kernel.sys.read(fd, Math.min(max, MAX_READ), { nonblock: e.nonblock });\n }\n if (e.type === \"device\") {\n await this.interrupted?.();\n if (e.access === \"write\") throw new WasiError(\"EBADF\");\n if (e.device === \"null\") return new Uint8Array(0);\n const out = new Uint8Array(Math.min(max, 65536));\n return e.device === \"urandom\" ? crypto.getRandomValues(out) : out;\n }\n return await (await this.file(fd, \"read\")).read(max);\n }\n async local(answer) {\n await this.interrupted?.();\n return answer;\n }\n async seek(fd, offset, whence) {\n const e = await this.fds.get(fd);\n if (e.type === \"kernel\") {\n const kind = await this.fds.kind(fd, e);\n if (kind === \"device\") return await this.local(0);\n if (kind !== \"file\") throw new WasiError(\"ESPIPE\");\n return await this.o.kernel.sys.seek(fd, offset, whence);\n }\n if (e.type === \"device\") return await this.local(0);\n const file = await this.file(fd);\n const base = whence === WHENCE.SET ? 0 : whence === WHENCE.CUR ? file.offset : await file.size();\n if (whence > WHENCE.END || base + offset < 0) throw new WasiError(\"EINVAL\");\n file.offset = base + offset;\n return file.offset;\n }\n async sync(fd) {\n const e = await this.fds.get(fd);\n if (e.type === \"file\") await this.fds.synced(e.file);\n else if (e.type === \"device\") await this.interrupted?.();\n else if (e.type === \"kernel\") {\n const kind = await this.fds.kind(fd, e);\n if (kind === \"file\") await this.o.kernel.sys.flush(fd);\n else if (kind === \"device\") await this.interrupted?.();\n }\n }\n async fdstat(fd, out) {\n const e = await this.fds.get(fd);\n if (e.type === \"device\") await this.interrupted?.();\n let filetype = FILETYPE.CHARACTER_DEVICE;\n let seeks = true;\n let flags = 0;\n if (e.type === \"kernel\") {\n const kind = await this.fds.kind(fd, e);\n if (kind === \"device\") await this.interrupted?.();\n ({ filetype, seeks } = kernelFiletype(await this.fds.datagram(fd, e) ? \"dgram\" : kind));\n if (e.nonblock) flags |= FDFLAGS.NONBLOCK;\n if (e.append) flags |= FDFLAGS.APPEND;\n } else if (e.type === \"file\") {\n filetype = FILETYPE.REGULAR_FILE;\n if (e.file.append) flags |= FDFLAGS.APPEND;\n } else if (e.type === \"dir\") filetype = FILETYPE.DIRECTORY;\n const v = this.mem.view();\n v.setUint8(out, filetype);\n v.setUint16(out + 2, flags, true);\n let rights = seeks ? RIGHTS.ALL : RIGHTS.ALL & ~(RIGHTS.FD_SEEK | RIGHTS.FD_TELL);\n if (e.type === \"kernel\") {\n const access3 = await this.o.kernel.sys.access?.(fd);\n if (access3 === \"read\") rights &= ~RIGHTS.FD_WRITE;\n else if (access3 === \"write\") rights &= ~RIGHTS.FD_READ;\n }\n v.setBigUint64(out + 8, rights, true);\n v.setBigUint64(out + 16, RIGHTS.ALL, true);\n }\n writeFilestat(ptr, f) {\n const v = this.mem.view();\n v.setBigUint64(ptr, 1n, true);\n v.setBigUint64(ptr + 8, f.ino, true);\n v.setUint8(ptr + 16, f.filetype);\n v.setBigUint64(ptr + 24, f.nlink ?? 1n, true);\n v.setBigUint64(ptr + 32, f.size, true);\n v.setBigUint64(ptr + 40, f.mtimeNs, true);\n v.setBigUint64(ptr + 48, f.mtimeNs, true);\n v.setBigUint64(ptr + 56, f.mtimeNs, true);\n }\n async fdFilestat(fd) {\n const e = await this.fds.get(fd);\n if (e.type === \"dir\") return filestatOf(e.path, await this.o.fs.stat(e.path));\n if (e.type === \"file\") return await this.localFilestat(e.file);\n const kind = e.type === \"kernel\" ? await this.fds.kind(fd, e) : void 0;\n if (kind === \"file\") {\n const vfs = await this.kernelStat(fd);\n if (vfs.path) return await this.statOrphanable(vfs.path, vfs.size, vfs.orphan, vfs.orphan);\n }\n const filetype = kind ? kernelFiletype(kind).filetype : FILETYPE.CHARACTER_DEVICE;\n return await this.local({ filetype, size: 0n, ino: BigInt(fd + 1), mtimeNs: 0n });\n }\n async localFilestat(file) {\n const { buffer } = file;\n if (buffer.isOrphan()) {\n const bound2 = buffer.bound;\n if (!bound2) return await this.statOrphanable(file.path, await file.size(), false, true);\n return { ...this.sized(file.path, bound2, await file.size()), nlink: 0n };\n }\n let s;\n try {\n s = await this.o.fs.stat(file.path);\n } catch {\n s = await this.keptStat(buffer.handle);\n }\n const bound = buffer.bound;\n if (s && bound?.ino !== void 0 && s.ino !== bound.ino) {\n s = await this.keptStat(buffer.handle) ?? bound;\n }\n return this.sized(file.path, s, await file.size());\n }\n async keptStat(handle) {\n if (handle === void 0) return void 0;\n try {\n return await this.o.fs.keptStat?.(handle);\n } catch {\n return void 0;\n }\n }\n sized(path, s, size) {\n return {\n ...filestatOf(path, s ?? { isFile: true, isDirectory: false, size: 0 }),\n size: BigInt(size)\n };\n }\n async statOrphanable(path, size, orphan = false, gone = false) {\n let s;\n if (!orphan) {\n try {\n s = await this.o.fs.stat(path);\n } catch {\n }\n }\n const out = this.sized(path, s, size);\n return gone ? { ...out, nlink: 0n } : out;\n }\n synthetic(path) {\n return deviceOf(path) !== void 0 || path === SEALED_PATH && !!this.o.kernel.sys.openSealed || path === CLIPBOARD_PATH && !!this.o.kernel.sys.openClipboard || path === EMBEDDER_PATH && !!this.o.kernel.sys.openEmbedder;\n }\n async serialFd(fd) {\n const e = await this.fds.get(fd);\n if (e.type !== \"kernel\" || await this.fds.kind(fd, e) !== \"tty\") return false;\n const { terminal: terminal2 } = await this.o.kernel.call({ op: \"fd-info\", fd });\n return terminal2?.startsWith(\"/dev/\") === true && DEVICE_NAME.test(terminal2.slice(5));\n }\n async devChange(path, follow2, change, plain) {\n const dev = {\n json: async (req) => await this.o.kernel.call(req)\n };\n if (await devSync(dev, devMeta(path, follow2, change))) return;\n try {\n await plain();\n } catch (err) {\n const gone = err.code === \"ENOENT\";\n const linked = gone ? await this.linkedDev(path, follow2) : void 0;\n if (linked === void 0 || !await devSync(dev, devMeta(linked, true, change))) throw err;\n }\n }\n async linkedDev(path, follow2) {\n if (!follow2) return void 0;\n const real = await physicalLeaf(this.o.fs, path);\n return real !== void 0 && real !== path && kernelDev(real) ? real : void 0;\n }\n async statOf(path, follow2) {\n return follow2 ? await this.o.fs.stat(path) : await this.o.fs.lstat(path);\n }\n async viaDev(path, follow2, stat, device) {\n try {\n return await stat();\n } catch (err) {\n const linked = err.code === \"ENOENT\" && await this.linkedDev(path, follow2);\n if (!linked) throw err;\n return await device(linked, true);\n }\n }\n async devChar(path, follow2) {\n try {\n const json = async (req) => await this.o.kernel.call(req);\n const st = await devSync({ json }, devStat(path, follow2));\n return ((st.mode ?? 0) & 61440) === 8192;\n } catch {\n return false;\n }\n }\n async resolveForDev(path, follow2 = true) {\n try {\n if (!follow2) {\n const slash = path.lastIndexOf(\"/\");\n if (slash <= 0) return void 0;\n const parent = await physicalLeaf(this.o.fs, path.slice(0, slash));\n const resolved3 = parent === void 0 ? void 0 : `${parent}/${path.slice(slash + 1)}`;\n return resolved3 !== void 0 && resolved3 !== path && this.synthetic(resolved3) ? resolved3 : void 0;\n }\n const resolved2 = await physicalLeaf(this.o.fs, path);\n return resolved2 !== void 0 && resolved2 !== path && this.synthetic(resolved2) ? resolved2 : void 0;\n } catch {\n return void 0;\n }\n }\n async writeSiginfo(at, sig, tid, waited = true) {\n const taken = await this.o.kernel.call({ op: \"sig-info\", sig, tid });\n if (!taken && !waited) return false;\n const info = taken ?? KERNEL_SIGINFO;\n const view = this.mem.view();\n const size = Math.min(view.getUint32(at, true), SIGINFO_BYTES);\n const fields = [sig, info.code, info.pid, info.uid, info.status];\n let filled = 4;\n for (const [i, value2] of fields.entries()) {\n if (4 + (i + 1) * 4 > size) break;\n view.setInt32(4 + at + i * 4, value2, true);\n filled = 4 + (i + 1) * 4;\n }\n view.setUint32(at, filled, true);\n return true;\n }\n fdAlias(path) {\n const m = FD_ALIAS.exec(path);\n if (!m) return void 0;\n if (m[1]) return { fd: STDIO_FDS[m[1]], stdio: true };\n if (m[3] !== void 0 && m[3] !== \"self\" && Number(m[3]) !== this.o.pid) return void 0;\n return { fd: Number(m[2] ?? m[4]), stdio: false };\n }\n async openFd(fd) {\n try {\n await this.fds.get(fd);\n } catch {\n throw new WasiError(\"ENOENT\");\n }\n }\n async fdTarget(alias) {\n if (alias.stdio) return `/proc/self/fd/${alias.fd}`;\n await this.openFd(alias.fd);\n const e = await this.fds.get(alias.fd);\n if (e.type === \"file\") return e.file.path;\n if (e.type === \"dir\") return e.path;\n if (e.type === \"device\") return `/dev/${e.device}`;\n const kind = e.type === \"kernel\" ? await this.fds.kind(alias.fd, e) : void 0;\n if (kind === \"file\") {\n const vfs = await this.kernelStat(alias.fd);\n if (vfs.path) return vfs.path;\n }\n if (kind === \"tty\") return \"/dev/tty\";\n if (kind === \"device\") return \"/dev/null\";\n if (kind === \"stream\") {\n const { fifo } = await this.o.kernel.call({ op: \"fd-info\", fd: alias.fd });\n if (fifo !== void 0) return fifo;\n }\n const ino = (await this.fdFilestat(alias.fd)).ino;\n if (kind === \"stream\") return `pipe:[${ino}]`;\n if (kind === \"socket\") return `socket:[${ino}]`;\n return `anon_inode:[${kind ?? \"fd\"}]`;\n }\n async aliasFilestat(path, alias, lookup2) {\n if ((lookup2 & LOOKUP_SYMLINK_FOLLOW) === 0) {\n const target = await this.fdTarget(alias);\n return await this.local({\n filetype: FILETYPE.SYMBOLIC_LINK,\n size: BigInt(new TextEncoder().encode(target).length),\n ino: pathInode(path),\n mtimeNs: 0n\n });\n }\n await this.openFd(alias.fd);\n return await this.fdFilestat(alias.fd);\n }\n async pathFilestat(path, lookup2) {\n const alias = this.fdAlias(path);\n if (alias) return await this.aliasFilestat(path, alias, lookup2);\n if (this.synthetic(path)) {\n return await this.local({\n filetype: FILETYPE.CHARACTER_DEVICE,\n size: 0n,\n ino: pathInode(path),\n mtimeNs: 0n\n });\n }\n await this.fds.flushPath(path);\n const follow2 = (lookup2 & LOOKUP_SYMLINK_FOLLOW) !== 0;\n try {\n return filestatOf(path, follow2 ? await this.o.fs.stat(path) : await this.o.fs.lstat(path));\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n const device = kernelDev(path) ? path : await this.linkedDev(path, follow2);\n const alias2 = device && device !== path ? this.fdAlias(device) : void 0;\n if (device && alias2) return await this.aliasFilestat(device, alias2, lookup2);\n if (device && await this.devChar(device, true)) {\n return await this.local({\n filetype: FILETYPE.CHARACTER_DEVICE,\n size: 0n,\n ino: pathInode(device),\n mtimeNs: 0n\n });\n }\n const resolved2 = await this.resolveForDev(path, follow2);\n if (!resolved2) throw err;\n return await this.local({\n filetype: FILETYPE.CHARACTER_DEVICE,\n size: 0n,\n ino: pathInode(resolved2),\n mtimeNs: 0n\n });\n }\n }\n async setTimes(path, atim, mtim, flags, follow2 = true) {\n const asked = FSTFLAGS.ATIM | FSTFLAGS.ATIM_NOW | FSTFLAGS.MTIM | FSTFLAGS.MTIM_NOW;\n if (this.o.fs.owners && (flags & asked) === 0) return;\n await this.devChange(\n path,\n follow2,\n timesChange(atim, mtim, flags),\n async () => await this.fileTimes(path, atim, mtim, flags, follow2)\n );\n }\n async fileTimes(path, atim, mtim, flags, follow2) {\n const now = Date.now();\n let current2;\n const statOf = follow2 ? this.o.fs.stat.bind(this.o.fs) : this.o.fs.lstat.bind(this.o.fs);\n const kept = async (field2) => {\n current2 ??= await statOf(path);\n return current2[field2] ?? current2.mtimeMs ?? now;\n };\n const pick = async (set, setNow, value2, field2) => flags & setNow ? now : flags & set ? Number(value2 / NS_PER_MS4) : await kept(field2);\n await (follow2 ? this.o.fs.utimes : this.o.fs.lutimes).call(\n this.o.fs,\n path,\n await pick(FSTFLAGS.ATIM, FSTFLAGS.ATIM_NOW, atim, \"atimeMs\"),\n await pick(FSTFLAGS.MTIM, FSTFLAGS.MTIM_NOW, mtim, \"mtimeMs\"),\n (flags & (FSTFLAGS.ATIM | FSTFLAGS.MTIM)) === 0\n );\n }\n async readdir(fd, buf, len, cookie, usedPtr) {\n const dir = await this.fds.dir(fd);\n if (cookie === 0 || !dir.listing) {\n dir.listing = await this.fds.goneCwd(dir) ? { names: [], stats: /* @__PURE__ */ new Map() } : await this.list(dir.path);\n }\n const { names: names2, stats } = dir.listing;\n let at = 0;\n for (let i = cookie; i < names2.length && at < len; i++) {\n const name2 = names2[i];\n const full = name2 === \".\" ? dir.path : name2 === \"..\" ? normalize(`${dir.path}/..`) : resolveUnder(dir.path, name2);\n if (!stats.has(name2)) stats.set(name2, await this.lstatOrNull(full));\n const st = stats.get(name2) ?? null;\n const record = direntRecord(\n i + 1,\n st?.ino !== void 0 ? BigInt(st.ino) : pathInode(full),\n name2,\n filetypeOf(st)\n );\n const n = Math.min(record.length, len - at);\n this.mem.bytes(buf + at, n).set(record.subarray(0, n));\n at += n;\n }\n this.mem.view().setUint32(usedPtr, at, true);\n }\n async list(path) {\n const { fs } = this.o;\n const listed3 = await fs.readdirStat(path);\n return { names: [\".\", \"..\", ...listed3.map(([name2]) => name2)], stats: new Map(listed3) };\n }\n async lstatOrNull(path) {\n try {\n return await this.o.fs.lstat(path);\n } catch {\n return null;\n }\n }\n async flushAll() {\n await this.fds.flushAll();\n }\n};\nfunction direntRecord(next2, ino, name2, filetype) {\n const nameBytes = new TextEncoder().encode(name2);\n const record = new Uint8Array(SIZE.DIRENT + nameBytes.length);\n const v = new DataView(record.buffer);\n v.setBigUint64(0, BigInt(next2), true);\n v.setBigUint64(8, ino, true);\n v.setUint32(16, nameBytes.length, true);\n v.setUint8(20, filetype);\n record.set(nameBytes, SIZE.DIRENT);\n return record;\n}\nfunction wrap(table) {\n const out = {};\n for (const [name2, fn] of Object.entries(table)) {\n out[name2] = async (...args) => {\n try {\n return await fn(...args) ?? E.SUCCESS;\n } catch (e) {\n if (e instanceof WasiExit) throw e;\n if (e instanceof WasiError) return wasiErrnoOf(e.code);\n const code2 = e?.code;\n if (typeof code2 === \"string\") return wasiErrnoOf(code2);\n if (e instanceof RangeError) return E.FAULT;\n throw e;\n }\n };\n }\n return out;\n}\n\n// src/process/wasi/wasi-procfs.ts\nvar DIR_MODE2 = 16749;\nvar FILE_MODE2 = 33060;\nvar LINK_MODE2 = 41471;\nvar PID_NAMES = PID_FILES;\nvar SYSTEM_NAMES = SYSTEM_FILES;\nfunction inProc(path) {\n return path === \"/proc\" || path.startsWith(\"/proc/\");\n}\nvar ProcTree = class {\n source;\n pid;\n memory;\n constructor(source, pid, memory = memorySource()) {\n this.source = source;\n this.pid = pid;\n this.memory = memory;\n }\n async listing() {\n return await this.source.procList();\n }\n async alive(pid) {\n return (await this.listing()).processes.some((p) => p.pid === pid);\n }\n async node(parts) {\n const [top, leaf, ...rest2] = parts;\n if (top === void 0) {\n return {\n kind: \"dir\",\n names: async () => [\n ...SYSTEM_NAMES,\n \"mounts\",\n \"sys\",\n \"self\",\n ...(await this.listing()).processes.map((p) => String(p.pid))\n ]\n };\n }\n if (top === \"sys\") {\n const entry = sysEntry(parts.slice(1));\n if (typeof entry === \"string\" || typeof entry === \"function\") {\n return { kind: \"file\", content: async () => await sysText(entry, async () => await this.listing()) };\n }\n return entry && { kind: \"dir\", names: () => Object.keys(entry) };\n }\n if (top === \"self\") {\n return leaf === void 0 ? { kind: \"link\", target: String(this.pid) } : void 0;\n }\n if (leaf === void 0 && top === \"mounts\") {\n return { kind: \"file\", content: async () => mountTable(await this.source.mountList()) };\n }\n if (leaf === void 0 && SYSTEM_NAMES.includes(top)) {\n return {\n kind: \"file\",\n content: async () => systemFile(top, await this.listing(), Date.now(), this.memory)\n };\n }\n if (!/^[1-9]\\d*$/.test(top) || !await this.alive(Number(top))) return void 0;\n if (leaf === \"task\") return await this.task(Number(top), rest2);\n if (rest2.length > 0) return void 0;\n if (leaf === void 0) {\n const exe = async () => (await this.info(Number(top)))?.exe === void 0 ? [] : [\"exe\"];\n return { kind: \"dir\", names: async () => [...PID_NAMES, ...await exe(), \"task\"] };\n }\n if (leaf === \"exe\") return await this.exe(Number(top));\n if (!PID_NAMES.includes(leaf)) return void 0;\n return {\n kind: \"file\",\n content: async () => {\n const listing2 = await this.listing();\n const info = listing2.processes.find((p) => p.pid === Number(top));\n if (!info) throw syncError(\"ENOENT\", `/proc/${top}/${leaf}`);\n return pidFile(leaf, info, listing2.boot);\n }\n };\n }\n async exe(pid) {\n const info = await this.info(pid);\n if (info?.exe === void 0) return void 0;\n const denied = !mayTrace(await this.ownInfo(), info);\n const id = info.exeId === void 0 ? {} : { id: info.exeId };\n return { kind: \"link\", target: info.exe, ...denied ? { denied } : {}, ...id };\n }\n async ownInfo() {\n const processes2 = (await this.listing()).processes;\n return processes2.find((p) => p.tid === this.pid) ?? processes2.find((p) => p.pid === this.pid);\n }\n async info(pid) {\n return (await this.listing()).processes.find((p) => p.pid === pid);\n }\n async task(pid, rest2) {\n const [tid, leaf, ...more] = rest2;\n const tids = async () => taskIds(await this.info(pid));\n if (tid === void 0) return { kind: \"dir\", names: async () => (await tids()).map(String) };\n if (!/^[1-9]\\d*$/.test(tid) || more.length > 0 || !(await tids()).includes(Number(tid)))\n return void 0;\n if (leaf === void 0) return { kind: \"dir\", names: () => [\"stat\"] };\n if (leaf !== \"stat\") return void 0;\n return {\n kind: \"file\",\n content: async () => {\n const listing2 = await this.listing();\n const info = listing2.processes.find((p) => p.pid === pid);\n const line = info && taskStat(info, Number(tid), listing2.boot);\n if (line === void 0) throw syncError(\"ENOENT\", `/proc/${pid}/task/${tid}/stat`);\n return line;\n }\n };\n }\n parts(path, follow2) {\n const parts = path.split(\"/\").filter((p) => p !== \"\").slice(1);\n if (parts[0] === \"self\" && (follow2 || parts.length > 1)) parts[0] = String(this.pid);\n return parts;\n }\n async find(path, follow2) {\n const node = await this.node(this.parts(path, follow2));\n if (!node) throw syncError(\"ENOENT\", path);\n return node;\n }\n async stat(path, follow2 = true) {\n const node = await this.find(path, follow2);\n const base = {\n isFile: false,\n isDirectory: false,\n size: 0,\n mtimeMs: Date.now(),\n readonly: true\n };\n if (node.kind === \"dir\") return { ...base, isDirectory: true, mode: DIR_MODE2 };\n if (node.kind === \"link\") {\n return { ...base, isSymbolicLink: true, mode: LINK_MODE2, size: node.target.length };\n }\n return { ...base, isFile: true, mode: FILE_MODE2, size: (await this.bytes(node)).length };\n }\n async bytes(node) {\n return new TextEncoder().encode(node.kind === \"file\" ? await node.content() : \"\");\n }\n async read(path) {\n const node = await this.find(path, true);\n if (node.kind !== \"file\") throw syncError(\"EISDIR\", path);\n return await this.bytes(node);\n }\n async readdir(path) {\n const node = await this.find(path, true);\n if (node.kind !== \"dir\") throw syncError(\"ENOTDIR\", path);\n return await node.names();\n }\n async escape(path) {\n return (await this.escapeTo(path))?.target;\n }\n async escapeTo(path) {\n const node = await this.node(this.parts(path, true));\n if (node?.kind !== \"link\" || !node.target.startsWith(\"/\")) return void 0;\n if (node.denied) throw syncError(\"EACCES\", path);\n return node.id === void 0 ? { target: node.target } : { target: node.target, id: node.id };\n }\n async linkTo(path) {\n const node = await this.node(this.parts(path, false));\n if (node?.kind !== \"link\" || node.id === void 0 || node.denied) return void 0;\n return { target: node.target, id: node.id };\n }\n async readlink(path) {\n const node = await this.find(path, false);\n if (node.kind !== \"link\") throw syncError(\"EINVAL\", path);\n if (node.denied) throw syncError(\"EACCES\", path);\n return node.target;\n }\n async exists(path) {\n try {\n await this.find(path, true);\n return true;\n } catch {\n return false;\n }\n }\n};\nvar FOLLOWING = [\"writeFile\", \"chmod\", \"utimes\", \"pwrite\", \"truncate\"];\nvar NOT_FOLLOWING = [\"mkdir\", \"rm\", \"unlink\", \"rmdir\", \"lutimes\", \"create\", \"mkfifo\"];\nvar MAX_HOPS3 = 40;\nfunction* procWalk(path, follow2) {\n let done = [];\n let todo = path.split(\"/\").filter((part) => part !== \"\");\n let hops = 0;\n let broken;\n while (todo.length > 0) {\n const part = todo.shift();\n if (part === \".\") continue;\n if (part === \"..\") {\n done.pop();\n continue;\n }\n const at = `/${[...done, part].join(\"/\")}`;\n const whole = normalize(`/${[...done, part, ...todo].join(\"/\")}`);\n if (inProc(at) && inProc(whole)) return broken ?? whole;\n if (!follow2 && todo.length === 0) return void 0;\n const target = yield { at, check: todo.find((next2) => next2 !== \".\") === \"..\" };\n if (typeof target === \"string\") {\n if (++hops > MAX_HOPS3) return void 0;\n [done, todo] = throughLink(target, done, todo);\n } else {\n broken ??= refusalOf(target);\n done.push(part);\n }\n }\n return void 0;\n}\nfunction failed(err) {\n const code2 = err?.code;\n return { refused: typeof code2 === \"string\" ? code2 : \"ENOENT\" };\n}\nfunction refusalOf(found) {\n if (found === true) return void 0;\n return found === false ? { refused: \"ENOTDIR\" } : found;\n}\nfunction throughLink(target, done, todo) {\n const parts = target.split(\"/\").filter((part) => part !== \"\");\n return [target.startsWith(\"/\") ? [] : done, [...parts, ...todo]];\n}\nasync function procPath(fs, path, follow2) {\n const walk2 = procWalk(path, follow2);\n let step = walk2.next();\n while (!step.done) {\n const { at, check } = step.value;\n let target;\n try {\n const st = await fs.lstat(at);\n target = st.isSymbolicLink ? await fs.readlink(at) : !check || st.isDirectory;\n } catch (err) {\n target = failed(err);\n }\n step = walk2.next(target);\n }\n const result = step.value;\n if (typeof result === \"object\") throw syncError(result.refused, path);\n return result;\n}\nfunction frozen(bytes) {\n const refuse2 = () => {\n throw syncError(\"EROFS\", \"/proc\");\n };\n return {\n readFile: () => bytes,\n pread: (_p, at, n) => bytes.subarray(at, at + n),\n writeFile: refuse2,\n pwrite: refuse2,\n truncate: refuse2\n };\n}\nfunction physicalProc(fs, now = () => performance.now()) {\n const view = fs.changes;\n let seen;\n return async () => {\n if (seen && view && (!view.foreign() || now() - seen.at < SHARED_TTL_MS)) {\n const proc = view.changedSince(seen.gen, \"/proc\");\n if (!proc.changed && !view.changedSince(seen.gen, \"/\").changed) {\n seen.gen = proc.now;\n return seen.physical;\n }\n }\n const gen = view?.now();\n const at = now();\n let physical2;\n try {\n await fs.stat(\"/proc\");\n physical2 = true;\n } catch (err) {\n const code2 = err.code;\n if (code2 !== \"ENOENT\" && code2 !== \"ENOTDIR\") {\n seen = void 0;\n return false;\n }\n physical2 = false;\n }\n seen = gen === void 0 ? void 0 : { gen, physical: physical2, at };\n return physical2;\n };\n}\nfunction directMiss(err, path) {\n if (err?.direct !== true) return false;\n return !path.split(\"/\").some((part) => part === \".\" || part === \"..\");\n}\nvar GONE2 = /* @__PURE__ */ new Set([\"ENOENT\", \"ENOTDIR\"]);\nasync function same(fs, path, id) {\n let st;\n try {\n st = await fs.stat(path);\n } catch (err) {\n if (GONE2.has(err?.code ?? \"\")) return false;\n throw err;\n }\n if (id.startsWith(\"fid:\")) return st.fid !== void 0 && id.startsWith(`fid:${st.fid}:`);\n const now = fileIdentity(st.ino, st.mtimeMs);\n return now === void 0 || now === id;\n}\nasync function current(fs, tree, q) {\n const to = await tree.escapeTo(q);\n if (!to || to.id === void 0) return to?.target;\n if (!await same(fs, to.target, to.id)) throw syncError(\"ENOENT\", q);\n return to.target;\n}\nfunction guard(toProc, shadowing) {\n return async (paths, run) => {\n const physical2 = await shadowing();\n for (const [p, follow2] of paths) {\n if (inProc(p) || physical2 && await toProc(p, follow2) !== void 0) throw syncError(\"EROFS\", p);\n }\n return await run();\n };\n}\nasync function shownLink(fs, tree, q) {\n const target = await tree.readlink(q);\n const to = await tree.linkTo(q);\n if (!to) return target;\n try {\n return await same(fs, to.target, to.id) ? target : `${target} (deleted)`;\n } catch {\n return target;\n }\n}\nfunction routing(fs, tree, toProc, shadowing) {\n return async (p, inner, own, follow2 = true, outside) => {\n const proc = async (q) => {\n const target = outside ? await current(fs, tree, q) : void 0;\n return target === void 0 ? await inner(q) : await outside(target);\n };\n if (inProc(p)) return await proc(p);\n if (await shadowing()) {\n const real = await toProc(p, follow2);\n if (real !== void 0) return await proc(real);\n }\n try {\n return await own();\n } catch (err) {\n if (directMiss(err, p)) throw err;\n const real = await toProc(p, follow2);\n if (real === void 0) throw err;\n return await proc(real);\n }\n };\n}\nfunction procfsBridge(fs, tree) {\n const toProc = async (path, follow2) => await procPath(fs, path, follow2);\n const shadowing = physicalProc(fs);\n const via = routing(fs, tree, toProc, shadowing);\n const readOnly = guard(toProc, shadowing);\n const snapshots = /* @__PURE__ */ new Map();\n let lastSnapshot = 0;\n const snapshot = async (q) => {\n lastSnapshot--;\n snapshots.set(lastSnapshot, await tree.read(q));\n return lastSnapshot;\n };\n const late = async (p) => {\n const q = await toProc(p, true);\n return q === void 0 ? void 0 : await snapshot(q);\n };\n const over = {\n readFile: async (p) => await via(\n p,\n async (q) => await tree.read(q),\n async () => await fs.readFile(p),\n true,\n async (t) => await fs.readFile(t)\n ),\n stat: async (p) => await via(\n p,\n async (q) => await tree.stat(q),\n async () => await fs.stat(p),\n true,\n async (t) => ({ ...await fs.stat(t), escape: t })\n ),\n lstat: async (p) => await via(\n p,\n async (q) => await tree.stat(q, false),\n async () => await fs.lstat(p),\n false\n ),\n readdir: async (p) => await via(\n p,\n async (q) => await tree.readdir(q),\n async () => {\n const names2 = await fs.readdir(p);\n return p === \"/\" && !names2.includes(\"proc\") ? [...names2, \"proc\"] : names2;\n }\n ),\n exists: async (p) => {\n if (inProc(p)) return await tree.exists(p);\n const probe = async () => {\n try {\n return await toProc(p, true);\n } catch {\n return null;\n }\n };\n const real = await shadowing() ? await probe() : void 0;\n if (real === null) return false;\n if (real !== void 0) return await tree.exists(real);\n try {\n await fs.stat(p);\n return true;\n } catch (err) {\n if (directMiss(err, p)) return false;\n }\n const late2 = await probe();\n return typeof late2 === \"string\" && await tree.exists(late2);\n },\n readlink: async (p) => await via(\n p,\n async (q) => await shownLink(fs, tree, q),\n async () => await fs.readlink(p),\n false\n ),\n readdirStat: async (p) => await via(\n p,\n async (q) => {\n const listed3 = [];\n for (const name2 of await tree.readdir(q)) {\n try {\n listed3.push([name2, await tree.stat(`${q}/${name2}`, false)]);\n } catch {\n listed3.push([name2, null]);\n }\n }\n return listed3;\n },\n async () => {\n const listed3 = await fs.readdirStat(p);\n if (p !== \"/\" || listed3.some(([name2]) => name2 === \"proc\")) return listed3;\n return [...listed3, [\"proc\", await tree.stat(\"/proc\")]];\n }\n ),\n rename: async (from, to) => await readOnly(\n [\n [from, false],\n [to, false]\n ],\n async () => await fs.rename(from, to)\n ),\n symlink: async (target, link) => await readOnly([[link, false]], async () => await fs.symlink(target, link)),\n link: async (from, to, follow2) => await readOnly(\n [\n [from, follow2 === true],\n [to, false]\n ],\n async () => await fs.link(from, to, follow2)\n ),\n hold: async (p, held, open, handle, want, seen) => {\n if (handle !== void 0 && snapshots.delete(handle)) return void 0;\n if (!held) return await fs.hold?.(p, held, open, handle);\n return await via(p, snapshot, async () => await fs.hold?.(p, held, open, void 0, want, seen) ?? await late(p));\n },\n kept: async (handle) => snapshots.has(handle) || await fs.kept?.(handle) === true,\n escape: async (p) => inProc(p) ? await current(fs, tree, p) : void 0,\n pinned: async (handle) => {\n const bytes = snapshots.get(handle);\n return bytes ? frozen(bytes) : await fs.pinned?.(handle) ?? fs;\n },\n ...fs.pread ? {\n pread: async (p, at, n, version) => await via(\n p,\n async (q) => (await tree.read(q)).subarray(at, at + n),\n async () => await fs.pread(p, at, n, version)\n )\n } : {}\n };\n for (const [names2, follow2] of [\n [FOLLOWING, true],\n [NOT_FOLLOWING, false]\n ]) {\n for (const name2 of names2) {\n const fn = fs[name2];\n if (!fn) continue;\n over[name2] = (async (p, ...rest2) => await readOnly([[p, follow2]], async () => await fn.call(fs, p, ...rest2)));\n }\n }\n const { chown: chown2 } = fs;\n if (chown2) {\n over.chown = async (p, ...rest2) => await readOnly([[p, rest2[2] === true]], async () => await chown2.call(fs, p, ...rest2));\n }\n return new Proxy(fs, {\n get: (target, key, receiver) => key in over ? over[key] : Reflect.get(target, key, receiver)\n });\n}\n\n// src/process/wasi/wasi-ptsfs.ts\nvar PTS = \"/dev/pts\";\nvar PTS_ENTRY = /^\\/dev\\/pts\\/(\\d+)$/;\nvar SERIAL_AREA = /^\\/dev\\/(?:tty(?:USB|ACM)\\d+|serial(?:\\/.*)?)$/;\nfunction ptsBridge(fs, call2) {\n const open = async () => await call2({ op: \"pty-list\" });\n const kernel = { json: async (req) => await call2(req) };\n const entry = async (p, given) => {\n const known = given === void 0 ? await open() : given;\n const n = PTS_ENTRY.exec(p)?.[1];\n if (n === void 0 || !known.includes(Number(n))) throw syncError(\"ENOENT\", p);\n return await devSync(kernel, devStat(p, true));\n };\n const listedEntry = async (name2, known) => {\n try {\n return [name2, await entry(`${PTS}/${name2}`, known)];\n } catch {\n return [name2, null];\n }\n };\n const dir = async () => await devSync(kernel, devStat(PTS, true));\n const statOf = async (p, real, follow2 = true) => {\n if (p === PTS) return await dir();\n if (SERIAL_AREA.test(p)) return await devSync(kernel, devStat(p, follow2));\n return PTS_ENTRY.test(p) ? await entry(p) : await real();\n };\n const serialNames = async () => (await devSync(kernel, devReaddir(\"/dev\"))).filter((n) => SERIAL_AREA.test(`/dev/${n}`));\n const withSerial = async (listed3) => [\n ...listed3,\n ...(await serialNames()).filter((n) => !listed3.includes(n))\n ];\n const names2 = async (given) => (given === void 0 ? await open() : given).map(String).sort();\n const serialEntry = async (p, name2) => {\n try {\n return [name2, await devSync(kernel, devStat(p, false))];\n } catch {\n return [name2, null];\n }\n };\n const over = {\n stat: async (p) => await statOf(p, async () => await fs.stat(p)),\n lstat: async (p) => await statOf(p, async () => await fs.lstat(p), false),\n readlink: async (p) => SERIAL_AREA.test(p) ? await devSync(kernel, devReadlink(p)) : await fs.readlink(p),\n exists: async (p) => {\n if (p === PTS) return true;\n if (SERIAL_AREA.test(p)) {\n try {\n await devSync(kernel, devStat(p, true));\n return true;\n } catch {\n return false;\n }\n }\n if (!PTS_ENTRY.test(p)) return await fs.exists(p);\n return (await open()).includes(Number(PTS_ENTRY.exec(p)?.[1]));\n },\n readdir: async (p) => {\n if (p === PTS) return await names2();\n if (SERIAL_AREA.test(p)) return await devSync(kernel, devReaddir(p));\n const listed3 = await fs.readdir(p);\n if (p !== \"/dev\") return listed3;\n return await withSerial(listed3.includes(\"pts\") ? listed3 : [...listed3, \"pts\"]);\n },\n readdirStat: async (p) => {\n if (p === PTS) {\n const known = await open();\n const listed4 = [];\n for (const name2 of await names2(known)) listed4.push(await listedEntry(name2, known));\n return listed4;\n }\n if (SERIAL_AREA.test(p)) {\n const serial = [];\n for (const name2 of await devSync(kernel, devReaddir(p))) {\n serial.push(await serialEntry(`${p}/${name2}`, name2));\n }\n return serial;\n }\n const listed3 = await fs.readdirStat(p);\n if (p !== \"/dev\") return listed3;\n const all = listed3.some(([name2]) => name2 === \"pts\") ? [...listed3] : [...listed3, [\"pts\", await dir()]];\n const have = all.map(([name2]) => name2);\n for (const name2 of await serialNames()) {\n if (!have.includes(name2)) all.push(await serialEntry(`/dev/${name2}`, name2));\n }\n return all;\n }\n };\n return new Proxy(fs, {\n get(target, key, receiver) {\n if (Object.hasOwn(over, key)) return over[key];\n const value2 = Reflect.get(target, key, receiver);\n return typeof value2 === \"function\" ? value2.bind(target) : value2;\n }\n });\n}\n\n// src/process/raw-stack.ts\nvar reader = (error) => error.stack;\nfunction rawStack(error) {\n const stack = reader(error);\n return typeof stack === \"string\" ? stack : void 0;\n}\n\n// src/process/wasi/dylink.ts\nvar MEM_INFO = 1;\nvar NEEDED = 2;\nvar RUNTIME_PATH = 5;\nfunction dylinkInfo(module) {\n const [section2] = WebAssembly.Module.customSections(module, \"dylink.0\");\n if (!section2) return void 0;\n const bytes = new Uint8Array(section2);\n let at = 0;\n const uleb = () => {\n let value2 = 0;\n let shift = 0;\n for (; ; ) {\n const b = bytes[at++];\n value2 += (b & 127) * 2 ** shift;\n if (!(b & 128)) return value2;\n shift += 7;\n }\n };\n const string = () => {\n const len = uleb();\n const s = new TextDecoder().decode(bytes.subarray(at, at + len));\n at += len;\n return s;\n };\n const info = {\n memorySize: 0,\n memoryAlign: 0,\n tableSize: 0,\n tableAlign: 0,\n needed: [],\n runtimePath: []\n };\n while (at < bytes.length) {\n const kind = bytes[at++];\n const len = uleb();\n const end = at + len;\n if (kind === MEM_INFO) {\n info.memorySize = uleb();\n info.memoryAlign = uleb();\n info.tableSize = uleb();\n info.tableAlign = uleb();\n } else if (kind === NEEDED) {\n for (let n = uleb(); n > 0; n--) info.needed.push(string());\n } else if (kind === RUNTIME_PATH) {\n for (let n = uleb(); n > 0; n--) info.runtimePath.push(string());\n }\n at = end;\n }\n return info;\n}\n\n// src/process/wasi/wasi-threads.ts\nvar LAST_TID = 0;\nvar RUNNING = 1;\nvar MAIN_TID = 1;\nvar ThreadExit = class extends Error {\n constructor() {\n super(\"thread exit\");\n }\n};\nfunction threadCap(env) {\n const asked = Number.parseInt(env.SLICC_WASM_THREADS ?? \"\", 10);\n return asked >= 1 ? Math.min(asked, WASM_MAX_THREADS) : WASM_DEFAULT_THREADS;\n}\nvar WasiThreads = class {\n ids;\n beforeSpawn;\n modules;\n received;\n blocked;\n port;\n memory;\n cap;\n tid;\n constructor(port, memory, cap, tid, ids) {\n this.port = port;\n this.memory = memory;\n this.cap = cap;\n this.tid = tid;\n this.ids = new Int32Array(ids ?? new SharedArrayBuffer(SHARED_IDS_BYTES));\n if (!ids) Atomics.store(this.ids, LAST_TID, MAIN_TID);\n }\n async spawn(arg) {\n if (Atomics.add(this.ids, RUNNING, 1) + 1 >= this.cap) {\n Atomics.sub(this.ids, RUNNING, 1);\n return -1;\n }\n await this.beforeSpawn?.();\n const tid = Atomics.add(this.ids, LAST_TID, 1) + 1;\n const modules = this.modules?.();\n const blocked = this.blocked?.();\n this.port.postMessage({\n type: WASM_THREAD_SPAWN,\n thread: {\n tid,\n arg,\n memory: this.memory,\n ids: this.ids.buffer,\n ...modules ? { modules } : {},\n ...anyBlocked(blocked) ? { blocked } : {}\n }\n });\n return tid;\n }\n exited() {\n Atomics.sub(this.ids, RUNNING, 1);\n this.port.postMessage({ type: WASM_THREAD_EXIT });\n }\n known(tid) {\n return tid >= MAIN_TID && tid <= Atomics.load(this.ids, LAST_TID);\n }\n parallelism() {\n const cores = globalThis.navigator?.hardwareConcurrency;\n return Math.max(1, Math.min(this.cap, cores ?? this.cap));\n }\n};\n\n// src/process/wasi/wasix-process.ts\nasync function restarted(issue) {\n for (; ; ) {\n try {\n return await issue();\n } catch (e) {\n if (e?.code !== \"EINTR\") throw e;\n }\n }\n}\nfunction resolveFrom(cwd, path) {\n return normalize(path.startsWith(\"/\") ? path : `${cwd}/${path}`);\n}\nvar O_WRONLY2 = 1;\nvar O_RDWR2 = 2;\nvar O_APPEND2 = 1024;\nvar OFLAG_CREAT = 1;\nvar OFLAG_TRUNC = 8;\nvar JOIN_NON_BLOCKING = 1;\nvar JOIN_WAKE_STOPPED = 2;\nvar JOIN_STOPPED = 3;\nvar WasixProcess = class {\n host;\n driver;\n inThread;\n constructor(host, driver, inThread = () => false) {\n this.host = host;\n this.driver = driver;\n this.inThread = inThread;\n }\n restart() {\n return this.inThread() ? {} : { restart: true };\n }\n async call(req) {\n return await this.host.o.kernel.call(req);\n }\n async environment() {\n return { ...this.host.o.env, PWD: await this.host.workingDir() };\n }\n async locate(name2, search, path) {\n if (name2.includes(\"/\"))\n return name2.startsWith(\"/\") ? name2 : normalize(`${await this.host.workingDir()}/${name2}`);\n if (!search) return name2;\n for (const dir of path.split(\":\")) {\n if (!dir) continue;\n const candidate = normalize(\n `${dir.startsWith(\"/\") ? \"\" : `${await this.host.workingDir()}/`}${dir}/${name2}`\n );\n if (await this.host.o.fs.exists(candidate)) return candidate;\n }\n return name2;\n }\n async childFds(ops) {\n const { fds } = this.host;\n await fds.promoteFiles();\n const map = await fds.inheritable();\n const nulls = /* @__PURE__ */ new Set();\n const opened = [];\n let cwd = await this.host.workingDir();\n try {\n for (const op of ops) cwd = await this.applyFdOp(op, { map, nulls, opened }, cwd);\n } catch (e) {\n for (const kfd of opened) await this.host.o.kernel.sys.close(kfd);\n throw e;\n }\n const stdio = [0, 1, 2].map((fd) => {\n const k = map.get(fd);\n return k === void 0 ? { none: true } : { fd: k };\n });\n const inherit = [\n ...[...map].filter(([fd]) => fd > 2).map(([fd, kernel]) => ({ fd, kernel })),\n ...[...nulls].filter((fd) => fd > 2).map((fd) => ({ fd, device: \"null\" }))\n ];\n return { stdio, inherit, cwd, opened };\n }\n async applyFdOp(op, slots2, cwd) {\n const { map, nulls, opened } = slots2;\n const { fds } = this.host;\n const point = (fd, kfd) => {\n if (kfd === void 0) {\n map.delete(fd);\n nulls.add(fd);\n } else {\n map.set(fd, kfd);\n nulls.delete(fd);\n }\n };\n if (op.cmd === \"close\") {\n map.delete(op.fd);\n nulls.delete(op.fd);\n } else if (op.cmd === \"dup2\" && nulls.has(op.srcFd)) point(op.fd, void 0);\n else if (op.cmd === \"dup2\") {\n const src = map.get(op.srcFd) ?? ((await fds.find(op.srcFd))?.type === \"kernel\" ? op.srcFd : void 0);\n if (src === void 0) throw Object.assign(new Error(\"EBADF\"), { code: \"EBADF\" });\n point(op.fd, src);\n } else if (op.cmd === \"open\" && resolveFrom(cwd, op.path) === \"/dev/null\") {\n point(op.fd, void 0);\n } else if (op.cmd === \"open\") {\n const kfd = await this.openFor(op, cwd);\n opened.push(kfd);\n point(op.fd, kfd);\n } else if (op.cmd === \"chdir\") return await this.physicalFrom(cwd, op.path);\n else return await physicalPath(this.host.o.fs, (await fds.dir(op.fd)).path);\n return cwd;\n }\n async physicalFrom(cwd, path) {\n return await physicalPath(this.host.o.fs, path.startsWith(\"/\") ? path : `${cwd}/${path}`);\n }\n async openFor(op, cwd) {\n const path = resolveFrom(cwd, op.path);\n const create = (op.oflags & OFLAG_CREAT) !== 0;\n if (!create && !await this.host.o.fs.exists(path)) {\n throw Object.assign(new Error(\"ENOENT\"), { code: \"ENOENT\" });\n }\n const flags = (op.rightsWrite ? O_RDWR2 : 0) | (op.append ? O_APPEND2 : 0);\n return await this.host.o.kernel.sys.openVfs(path, op.rightsWrite ? flags || O_WRONLY2 : 0, 0, {\n ...create ? { create } : {},\n ...op.oflags & OFLAG_TRUNC ? { truncate: true } : {}\n });\n }\n async spawn(req, exec = false) {\n const ops = req.ops ?? [];\n const { stdio, inherit, cwd, opened } = await this.childFds(ops);\n const moved = ops.some((op) => op.cmd === \"chdir\" || op.cmd === \"fchdir\");\n try {\n const spawn = {\n op: \"proc-spawn\",\n file: await this.locate(req.name, req.search, req.path),\n ...req.search ? {} : { search: false },\n argv: req.argv.length > 0 ? req.argv : [req.name],\n env: req.env ?? await this.environment(),\n cwd,\n ...moved ? { chdir: true } : {},\n stdio,\n inherit,\n ...exec ? { exec } : {},\n ...this.restart()\n };\n return await restarted(async () => await this.call(spawn));\n } finally {\n for (const kfd of opened) await this.host.o.kernel.sys.close(kfd);\n this.host.o.fs.invalidate?.();\n }\n }\n async exec(req) {\n const pid = await this.spawn(req, true);\n const [, status2] = await this.call({ op: \"proc-exec\", pid });\n const sig = status2 & 127;\n throw new WasiExit(sig ? 128 + sig : status2 >> 8 & 255);\n }\n async join(pidPtr, flags, statusPtr) {\n const v = this.host.mem.view();\n const pid = v.getUint8(pidPtr) === 1 ? v.getUint32(pidPtr + 4, true) : -1;\n this.host.mem.bytes(statusPtr, 6).fill(0);\n const [child, status2] = await this.call({\n op: \"proc-wait\",\n pid,\n nohang: (flags & JOIN_NON_BLOCKING) !== 0,\n ...flags & JOIN_WAKE_STOPPED ? { untraced: true } : {}\n });\n if (child === 0) return;\n this.host.o.fs.invalidate?.();\n v.setUint8(pidPtr, 1);\n v.setUint32(pidPtr + 4, child, true);\n const sig = status2 & 127;\n if (sig === 127) {\n v.setUint8(statusPtr, JOIN_STOPPED);\n v.setUint8(statusPtr + 2, status2 >> 8 & 255);\n } else if (sig) {\n v.setUint8(statusPtr, 2);\n v.setUint8(statusPtr + 4, sig);\n } else {\n v.setUint8(statusPtr, 1);\n v.setUint16(statusPtr + 2, status2 >> 8 & 255, true);\n }\n }\n fork(pidPtr) {\n const back = this.driver.rewound();\n if (back !== void 0) {\n this.host.mem.view().setUint32(pidPtr, back, true);\n return void 0;\n }\n return this.driver.fork(\n async (asyncifyData, globals, forkSp) => await restarted(async () => await this.forkCall(asyncifyData, globals, forkSp))\n );\n }\n async forkCall(asyncifyData, globals, forkSp) {\n const { fds } = this.host;\n await fds.promoteFiles();\n const memory = this.host.mem.bytes(0, this.host.mem.size()).slice();\n const wasi = {\n asyncifyData,\n globals,\n fds: fds.snapshot(),\n cloexec: [...fds.cloexec],\n cwd: await this.host.workingDir(),\n ...fds.isShared ? { shared: true } : {},\n setjmps: this.driver.setjmps(),\n ...this.host.signals ? { signals: this.host.signals.snapshot() } : {},\n ...this.host.sigmask ? { blocked: this.host.sigmask.inherited() } : {},\n ...this.host.linkedTls ? { tls: this.host.linkedTls() } : {},\n ...this.host.linkedModules ? { modules: this.host.linkedModules() } : {}\n };\n if (this.host.threadEntry) wasi.entry = this.host.threadEntry;\n return await this.call({\n op: \"proc-fork\",\n state: { memory, currData: 0, forkSp, callStackNames: [], ppid: this.host.o.pid, wasi },\n ...this.restart()\n });\n }\n};\n\n// src/process/wasi/wasi-imports.ts\nvar UID = 1e3;\nfunction base64(text) {\n const bytes = new TextEncoder().encode(text);\n let binary = \"\";\n for (let at = 0; at < bytes.length; at += 32768) {\n binary += String.fromCharCode(...bytes.subarray(at, at + 32768));\n }\n return btoa(binary);\n}\nfunction importSource(source) {\n return refusedImport(`data:text/javascript;base64,${base64(source)}`);\n}\nasync function loadImports(source) {\n const loaded = await importSource(source);\n if (typeof loaded.createImports !== \"function\") {\n throw new Error(\"the imports module exports no createImports function\");\n }\n return loaded.createImports;\n}\nfunction value(result) {\n if (!result.ok) throw new WasiError(result.errno);\n if (result.kind === \"json\") return result.json;\n return result.kind === \"bytes\" ? result.bytes : void 0;\n}\nfunction code(err) {\n const c = err?.code;\n return typeof c === \"string\" ? c : void 0;\n}\nfunction importsContext({\n host,\n raw,\n tid,\n memory,\n instance\n}) {\n const { fs } = host.o;\n const call2 = async (req) => value(await raw(req));\n const pathOf = async (fd) => {\n const e = await host.fds.get(fd);\n if (e.type === \"file\") return e.file.path;\n if (e.type === \"dir\") return e.path;\n if (e.type === \"kernel\" && await host.fds.kind(fd, e) === \"file\") {\n return (await call2({ op: \"fd-vfs-stat\", fd })).path;\n }\n return void 0;\n };\n const sizedOf = async (fd) => {\n const e = await host.fds.get(fd);\n if (e.type === \"file\") return { path: e.file.path, size: await e.file.size() };\n if (e.type === \"kernel\" && await host.fds.kind(fd, e) === \"file\") {\n return await call2({ op: \"fd-vfs-stat\", fd });\n }\n return { path: await pathOf(fd) };\n };\n const requirePath = async (fd) => {\n const path = await pathOf(fd);\n if (path === void 0) throw new WasiError(\"EBADF\");\n return path;\n };\n const owners = fs.owners === true;\n const live = async () => {\n if (!owners) return { uid: UID, gid: UID };\n const cred = await call2({ op: \"proc-cred\" });\n return { uid: cred.euid, gid: cred.egid };\n };\n const fds = {\n async open(path, o = {}) {\n const abs = await host.fds.resolve(3, path);\n const fresh = o.create === true && o.exclusive === true && owners && fs.create !== void 0;\n const existed = !fresh && await fs.exists(abs);\n const oflags = (o.create ? OFLAGS.CREAT : 0) | (o.exclusive ? OFLAGS.EXCL : 0) | (o.truncate ? OFLAGS.TRUNC : 0) | (o.directory ? OFLAGS.DIRECTORY : 0);\n const rights = (o.write ? RIGHTS.FD_WRITE : 0n) | (o.read || !o.write ? RIGHTS.FD_READ : 0n);\n const flags = o.append ? FDFLAGS.APPEND : 0;\n const fd = await host.fds.open(\n abs,\n oflags,\n rights,\n flags,\n fresh ? o.mode : void 0,\n o.nofollow === true\n );\n if (o.mode !== void 0 && !existed && !fresh) await fs.chmod(abs, o.mode);\n return fd;\n },\n async close(fd) {\n await host.fds.close(fd);\n },\n async fstat(fd) {\n const e = await host.fds.get(fd);\n const { path, size } = await sizedOf(fd);\n if (path === void 0) {\n const kind = e.type === \"device\" ? \"device\" : \"stream\";\n return { kind, mode: kind === \"device\" ? 8630 : 4480, ...await live(), size: 0 };\n }\n if (size === void 0) await host.fds.flushPath(path);\n const s = await fs.stat(path);\n return {\n kind: s.isDirectory ? \"dir\" : \"file\",\n path,\n mode: s.mode ?? (s.isDirectory ? 16877 : 33188),\n ...s.uid !== void 0 && s.gid !== void 0 ? { uid: s.uid, gid: s.gid } : await live(),\n size: size ?? s.size,\n ...s.ino !== void 0 ? { ino: s.ino } : {},\n ...s.mtimeMs !== void 0 ? { mtimeMs: s.mtimeMs } : {}\n };\n },\n async fchmod(fd, mode) {\n await fs.chmod(await requirePath(fd), mode);\n },\n async tryLock(fd, exclusive) {\n const path = await requirePath(fd);\n await host.fds.promote(fd);\n try {\n await call2({ op: \"lock\", path, exclusive, fd });\n } catch (err) {\n if (code(err) === \"EAGAIN\") return E.AGAIN;\n throw err;\n }\n return E.SUCCESS;\n },\n async unlock(fd) {\n await call2({ op: \"unlock\", path: await requirePath(fd), fd });\n }\n };\n const ctx = {\n memory,\n instance,\n tid,\n argv: host.o.args,\n env: host.o.env,\n cwd: async () => await host.workingDir(),\n fs: Object.assign(Object.create(fs), {\n async copyFile(from, to, options = {}) {\n const at = async (p) => await host.fds.resolve(3, p.startsWith(\"/\") ? p : `${await host.workingDir()}/${p}`);\n await host.copyFile(await at(from), await at(to), options.mode ?? 438, options.excl === true);\n }\n }),\n fds,\n syscall: async (req) => req.op === \"proc-umask\" ? await host.umask(req.mask) : await call2(req),\n net: network(raw, call2),\n ...processes(host, call2, tid !== MAIN_TID),\n async: {\n submit: async (req) => await call2({ op: \"async-submit\", req }),\n async wait(timeoutMs2) {\n for (; ; ) {\n try {\n return await call2({\n op: \"async-wait\",\n ...timeoutMs2 !== void 0 ? { timeoutMs: timeoutMs2 } : {}\n });\n } catch (err) {\n if (code(err) !== \"EINTR\") throw err;\n if (timeoutMs2 !== void 0) return 0;\n }\n }\n },\n async take(id) {\n const result = await raw({ op: \"async-take\", id });\n if (!result.ok && result.errno === \"EAGAIN\") return void 0;\n if (!result.ok) return { error: result.errno };\n return { value: value(result) };\n },\n resolve: async (v) => await call2({ op: \"async-resolve\", value: v }),\n hold: async () => await call2({ op: \"async-hold\" }),\n cancel: async (id) => void await raw({ op: \"async-cancel\", id }),\n close: async () => void await call2({ op: \"async-close\" })\n },\n errno: (err) => wasiErrnoOf(code(err))\n };\n if (!owners) return ctx;\n return Object.defineProperties(ctx, {\n uid: { get: async () => (await live()).uid, enumerable: true },\n gid: { get: async () => (await live()).gid, enumerable: true }\n });\n}\nvar LOOPBACK2 = /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nvar SOL_SOCKET = 1;\nvar SO_ERROR = 4;\nfunction loopbackHost(host) {\n if (host === \"localhost\") return \"127.0.0.1\";\n if (typeof host === \"string\" && LOOPBACK2.test(host)) return host;\n throw new WasiError(\"EINVAL\");\n}\nfunction network(raw, call2) {\n return {\n async connect({ host, port, nonblock = false }) {\n const to = loopbackHost(host);\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new WasiError(\"EINVAL\");\n const fd = await call2({ op: \"sock-open\", domain: \"inet\" });\n const addr = { family: \"inet\", host: to, port };\n const r = await raw({ op: \"sock-connect\", fd, addr, ...nonblock ? { nonblock: true } : {} });\n if (r.ok || nonblock && r.errno === \"EINPROGRESS\") return fd;\n await raw({ op: \"fd-close\", fd });\n throw new WasiError(r.errno);\n },\n async ready(fd) {\n const sel = await call2({ op: \"fd-select\", read: [], write: [fd], timeoutMs: 0 });\n if (!sel.write.includes(fd)) return E.INPROGRESS;\n return await call2({ op: \"sock-getopt\", fd, level: SOL_SOCKET, name: SO_ERROR });\n }\n };\n}\nvar STDIO2 = [\"stdin\", \"stdout\", \"stderr\"];\nfunction processes(host, call2, inThread) {\n const close = async (fd) => void await call2({ op: \"fd-close\", fd });\n const slot2 = async (n, how, mine, theirs) => {\n if (how === \"inherit\") return { fd: n };\n if (how === \"null\") return { none: true };\n const [read2, write2] = await call2({ op: \"fd-pipe\" });\n mine[n] = n === 0 ? write2 : read2;\n theirs.push(n === 0 ? read2 : write2);\n return { fd: n === 0 ? read2 : write2 };\n };\n return {\n async spawn(o) {\n const mine = [];\n const theirs = [];\n await host.fds.promoteFiles();\n try {\n const stdio = [];\n for (const [n, name2] of STDIO2.entries())\n stdio.push(await slot2(n, o[name2] ?? \"inherit\", mine, theirs));\n const req = {\n op: \"proc-spawn\",\n file: o.argv[0],\n argv: o.argv,\n env: o.env ?? { ...host.o.env },\n cwd: o.cwd ?? await host.workingDir(),\n ...o.cwd !== void 0 ? { chdir: true } : {},\n stdio,\n ...inThread ? {} : { restart: true }\n };\n const pid = await restarted(async () => await call2(req));\n const out = { pid };\n STDIO2.forEach((name2, n) => {\n if (mine[n] !== void 0) out[name2] = mine[n];\n });\n return out;\n } catch (err) {\n for (const fd of mine) if (fd !== void 0) await close(fd);\n throw err;\n } finally {\n for (const fd of theirs) await close(fd);\n host.o.fs.invalidate?.();\n }\n },\n async wait(pid) {\n for (; ; ) {\n try {\n const [, status2] = await call2({ op: \"proc-wait\", pid, nohang: false });\n host.o.fs.invalidate?.();\n const signal = status2 & 127;\n return signal ? { status: 128 + signal, signal } : { status: status2 >> 8 & 255 };\n } catch (err) {\n if (code(err) !== \"EINTR\") throw err;\n }\n }\n },\n async kill(pid, sig) {\n await call2({ op: \"proc-kill\", pid, sig });\n }\n };\n}\n\n// src/process/wasi/wasi-module.ts\nvar RESERVED_NAMESPACES = /* @__PURE__ */ new Set([\n \"wasi_snapshot_preview1\",\n \"wasix_32v1\",\n \"wasi\",\n \"env\"\n]);\nvar LIBC_MARK = /^wasix-sysroot \\d{4}\\.\\d+\\.\\d+-(\\d+)/;\nfunction libcOf(sections) {\n for (const section2 of sections) {\n const found = LIBC_MARK.exec(new TextDecoder().decode(section2));\n if (found) return Number(found[1]);\n }\n return void 0;\n}\nfunction libcVersion(module) {\n return libcOf(WebAssembly.Module.customSections(module, \"slicc.libc\"));\n}\n\n// src/process/wasi/wasi-signals.ts\nvar DELIVERED_MASK = Object.values(SIG).filter((sig) => sig !== SIG.KILL && sig !== SIG.STOP).reduce((m, sig) => m | sigbit(sig), 0);\nvar KERNEL_DEFAULTS = [SIG.TSTP, SIG.TTIN, SIG.TTOU, SIG.CHLD, SIG.CONT, SIG.URG, SIG.WINCH].map(sigbit).reduce((m, bit) => m | bit, 0);\nvar LIBC_DEFAULT_EXIT = 127;\nvar SA_RESTART = 268435456;\nvar SA_NODEFER = 1073741824;\nvar SA_NOCLDWAIT = 2;\nvar DISPOSITION_IGNORE = 1;\nvar DISPOSITION_HANDLER = 2;\nvar withBit = (mask, bit, on) => on ? mask | bit : mask & ~bit;\nvar WASIX_LIBC_DEFAULT_LINE = /^Program recieved (?:stop|termination|fatal) signal: [^\\n]+\\n$/;\nvar WasiSignals = class {\n exports;\n callback;\n uncaught = 0;\n delivering;\n defaulted = false;\n libcDefault = false;\n hooked = false;\n handlers = 0;\n ignoring = 0;\n restarting = 0;\n nodefer = 0;\n running = 0;\n deferred = 0;\n lifted = 0;\n unblocking(bits) {\n this.lifted |= bits & this.running;\n }\n defaults = 0;\n nocldwait = false;\n fallBack;\n onKilled;\n constructor(fallBack, onKilled) {\n this.fallBack = fallBack;\n this.onKilled = onKilled;\n }\n killed(code2) {\n this.onKilled?.(code2);\n }\n bind(exports) {\n this.exports = exports;\n }\n register(name2) {\n if (typeof this.exports?.[name2] === \"function\") this.callback = name2;\n }\n useHook() {\n this.hooked = true;\n }\n disposition(sig, disposition, flags) {\n if (sig < 1 || sig > 31 || (DELIVERED_MASK & sigbit(sig)) === 0) return E.INVAL;\n const bit = sigbit(sig);\n this.handlers = withBit(this.handlers, bit, disposition === DISPOSITION_HANDLER);\n this.ignoring = withBit(this.ignoring, bit, disposition === DISPOSITION_IGNORE);\n this.restarting = withBit(this.restarting, bit, (flags & SA_RESTART) !== 0);\n this.nodefer = withBit(this.nodefer, bit, (flags & SA_NODEFER) !== 0);\n this.defaults = withBit(this.defaults, bit, disposition === 0);\n if (sig === SIG.CHLD) this.nocldwait = (flags & SA_NOCLDWAIT) !== 0;\n return E.SUCCESS;\n }\n snapshot() {\n return {\n ...this.callback ? { callback: this.callback } : {},\n ...this.hooked ? { hooked: true } : {},\n handlers: this.handlers,\n ignoring: this.ignoring,\n restarting: this.restarting,\n uncaught: this.uncaught,\n ...this.nocldwait ? { nocldwait: true } : {}\n };\n }\n restore(state) {\n if (state.callback) this.register(state.callback);\n if (state.hooked) this.hooked = true;\n this.handlers = state.handlers;\n this.ignoring = state.ignoring;\n this.restarting = state.restarting;\n this.uncaught = state.uncaught;\n this.nocldwait = state.nocldwait === true;\n }\n masks() {\n if (this.hooked) {\n const caught = this.handler() ? this.handlers : 0;\n const defaults = this.defaults;\n this.defaults = 0;\n const nocldwait = this.nocldwait ? { nocldwait: true } : {};\n return { caught, ignored: this.ignoring, restart: this.restarting, defaults, ...nocldwait };\n }\n if (!this.handler()) return null;\n return { caught: DELIVERED_MASK & ~this.uncaught & ~KERNEL_DEFAULTS, ignored: 0, restart: 0 };\n }\n async raise(sig) {\n const handler = this.handler();\n if (!handler && !this.hooked) return;\n if (!handler || this.hooked && (this.handlers & sigbit(sig)) === 0) {\n if ((this.ignoring & sigbit(sig)) === 0) await this.defaultAction(sig);\n return;\n }\n const bit = sigbit(sig);\n if ((this.running & bit) !== 0 && ((this.nodefer | this.lifted) & bit) === 0) {\n this.deferred |= bit;\n return;\n }\n const outer = { running: this.running & bit, lifted: this.lifted & bit };\n this.running |= bit;\n this.lifted &= ~bit;\n try {\n await this.run(handler, sig);\n } finally {\n this.running = this.running & ~bit | outer.running;\n this.lifted = this.lifted & ~bit | outer.lifted;\n }\n if ((this.deferred & bit) === 0) return;\n this.deferred &= ~bit;\n await this.raise(sig);\n }\n ran = 0;\n async run(handler, sig) {\n this.ran++;\n const outer = { sig: this.delivering, defaulted: this.defaulted, libc: this.libcDefault };\n this.delivering = sig;\n this.defaulted = false;\n this.libcDefault = false;\n try {\n await handler(sig);\n } catch (e) {\n const libcExit = e instanceof WasiExit && e.code === LIBC_DEFAULT_EXIT && this.libcDefault;\n if (!(libcExit && !this.defaulted) && !(e instanceof WebAssembly.RuntimeError)) throw e;\n if (!this.defaulted) await this.defaultAction(sig);\n } finally {\n this.delivering = outer.sig;\n this.defaulted = outer.defaulted;\n this.libcDefault = outer.libc;\n }\n }\n muted(fd, data) {\n if (fd !== 2 || this.delivering === void 0) return false;\n if (!WASIX_LIBC_DEFAULT_LINE.test(new TextDecoder().decode(data))) return false;\n this.libcDefault = true;\n return true;\n }\n async raised(sig) {\n if (sig !== SIG.ABRT || this.delivering === void 0) return false;\n if (!this.defaulted) await this.defaultAction(this.delivering);\n return true;\n }\n async defaultAction(sig) {\n this.defaulted = true;\n this.uncaught |= sigbit(sig);\n await this.fallBack(sig);\n if (defaultAction(sig) !== \"terminate\") this.uncaught &= ~sigbit(sig);\n }\n handler() {\n const fn = this.callback ? this.exports?.[this.callback] : void 0;\n return typeof fn === \"function\" ? reentered(fn) : void 0;\n }\n};\n\n// src/process/wasi/wasi-stats.ts\nvar WasiStats = class {\n rows = /* @__PURE__ */ new Map();\n phases = [];\n mark = performance.now();\n wrap(tag, table) {\n return Object.fromEntries(\n Object.entries(table).map(([name2, value2]) => {\n if (typeof value2 !== \"function\") return [name2, value2];\n const fn = value2;\n const key = `${tag}.${name2}`;\n return [name2, async (...args) => await this.time(key, async () => await fn.apply(table, args))];\n })\n );\n }\n async time(key, fn) {\n const t = performance.now();\n try {\n return await fn();\n } finally {\n this.count(key, performance.now() - t);\n }\n }\n phase(name2) {\n const now = performance.now();\n this.phases.push([name2, now - this.mark]);\n this.mark = now;\n }\n count(key, ms) {\n const row = this.rows.get(key) ?? { n: 0, ms: 0, max: 0 };\n row.n++;\n row.ms += ms;\n row.max = Math.max(row.max, ms);\n this.rows.set(key, row);\n }\n report() {\n const ms = (v) => v.toFixed(1).padStart(9);\n const lines = this.phases.map(([name2, t]) => `${ms(t)} ms ${name2}`);\n lines.push(`${\"total ms\".padStart(12)} ${\"calls\".padStart(7)} ${\"max ms\".padStart(9)} call`);\n const sorted = [...this.rows].sort((a, b) => b[1].ms - a[1].ms);\n for (const [key, row] of sorted) {\n lines.push(`${ms(row.ms)} ${String(row.n).padStart(7)} ${ms(row.max)} ${key}`);\n }\n return `${lines.join(\"\\n\")}\n`;\n }\n};\n\n// src/process/wasi/wasi-sysfs.ts\nvar ONE = [\n \"writeFile\",\n \"mkdir\",\n \"rm\",\n \"unlink\",\n \"rmdir\",\n \"chmod\",\n \"utimes\",\n \"lutimes\",\n \"create\",\n \"mkfifo\",\n \"chown\",\n \"pwrite\",\n \"truncate\",\n \"append\"\n];\nvar TWO = [\"rename\", \"link\", \"copy\"];\nfunction refuse(p) {\n throw syncError(\"EROFS\", p);\n}\nasync function listed2(tree, p) {\n const out = [];\n for (const name2 of await tree.readdir(p)) out.push([name2, await tree.stat(`${p}/${name2}`, false)]);\n return out;\n}\nfunction sysfsBridge(fs, nodes) {\n const tree = () => new SysTree(nodes);\n const over = {\n readFile: async (p) => inSys(p) ? await tree().read(p) : await fs.readFile(p),\n stat: async (p) => inSys(p) ? await tree().stat(p) : await fs.stat(p),\n lstat: async (p) => inSys(p) ? await tree().stat(p, false) : await fs.lstat(p),\n readlink: async (p) => inSys(p) ? await tree().readlink(p) : await fs.readlink(p),\n exists: async (p) => inSys(p) ? await tree().exists(p) : await fs.exists(p),\n readdir: async (p) => {\n if (inSys(p)) return await tree().readdir(p);\n const names2 = await fs.readdir(p);\n return p !== \"/\" || names2.includes(\"sys\") ? names2 : [...names2, \"sys\"];\n },\n readdirStat: async (p) => {\n if (inSys(p)) return await listed2(tree(), p);\n const entries2 = await fs.readdirStat(p);\n if (p !== \"/\" || entries2.some(([name2]) => name2 === \"sys\")) return entries2;\n return [...entries2, [\"sys\", await new SysTree(() => []).stat(\"/sys\")]];\n },\n symlink: async (target, link) => inSys(link) ? refuse(link) : await fs.symlink(target, link)\n };\n const { access: access3, hold, pread } = fs;\n if (access3)\n over.access = async (p, mode, ...rest2) => inSys(p) ? await tree().access(p, mode) : await access3.call(fs, p, mode, ...rest2);\n if (hold) over.hold = async (p, ...rest2) => inSys(p) ? void 0 : await hold.call(fs, p, ...rest2);\n if (pread)\n over.pread = async (p, at, n, version) => inSys(p) ? (await tree().read(p)).subarray(at, at + n) : await pread.call(fs, p, at, n, version);\n for (const name2 of ONE) {\n const fn = fs[name2];\n if (!fn) continue;\n over[name2] = (async (p, ...rest2) => inSys(p) ? refuse(p) : await fn.call(fs, p, ...rest2));\n }\n for (const name2 of TWO) {\n const fn = fs[name2];\n if (!fn) continue;\n over[name2] = (async (from, to, ...rest2) => inSys(to) || name2 !== \"copy\" && inSys(from) ? refuse(inSys(to) ? to : from) : await fn.call(fs, from, to, ...rest2));\n }\n return new Proxy(fs, {\n get: (target, key, receiver) => key in over ? over[key] : Reflect.get(target, key, receiver)\n });\n}\n\n// src/process/wasi/wasix-fork.ts\nvar STACK_POINTER = \"__stack_pointer\";\nvar UNWINDING = 1;\nvar REWINDING = 2;\nfunction mutableGlobals(exports) {\n const out = [];\n for (const [name2, value2] of Object.entries(exports)) {\n if (!(value2 instanceof WebAssembly.Global) || typeof value2.value !== \"number\") continue;\n try {\n const v = value2.value;\n value2.value = v;\n out.push([name2, v]);\n } catch {\n }\n }\n return out;\n}\nfunction reseatTls(exports, bytes) {\n const init = exports.__wasm_init_tls;\n const base = exports.__tls_base;\n const size = exports.__tls_size;\n if (typeof init !== \"function\" || !(base instanceof WebAssembly.Global) || !(size instanceof WebAssembly.Global)) {\n return;\n }\n const at = base.value;\n const block = bytes(at, size.value).slice();\n init(at);\n bytes(at, block.length).set(block);\n}\nvar AsyncifyDriver = class {\n exports = {};\n stackUpper = 0;\n linked;\n pending;\n answer = 0;\n snapshots = /* @__PURE__ */ new Map();\n nextSnapshot = 1;\n mem;\n constructor(mem) {\n this.mem = mem;\n }\n useStack(pointer, low) {\n this.linked = { pointer, low };\n }\n threadStack = false;\n useThreadStack(pointer, low) {\n this.useStack(pointer, low);\n this.threadStack = true;\n }\n bind(exports) {\n this.exports = exports;\n this.stackUpper = this.stackPointer();\n }\n get supported() {\n return typeof this.exports.asyncify_start_unwind === \"function\";\n }\n get idle() {\n const state = this.exports.asyncify_get_state;\n return !this.supported || typeof state !== \"function\" || state() === 0;\n }\n async resume() {\n if (this.exports.asyncify_get_state?.() !== UNWINDING) return false;\n this.exports.asyncify_stop_unwind?.();\n const op = this.pending;\n this.pending = void 0;\n if (!op) throw new Error(\"WASIX: unwound with nothing to do\");\n this.exports.asyncify_start_rewind?.(await op());\n return true;\n }\n setjmps() {\n return { next: this.nextSnapshot, snapshots: [...this.snapshots] };\n }\n startChild(state) {\n for (const [id, snap] of state.setjmps?.snapshots ?? []) this.snapshots.set(id, snap);\n this.nextSnapshot = Math.max(this.nextSnapshot, state.setjmps?.next ?? 1);\n this.restoreGlobals(state.globals);\n reseatTls(this.exports, (at, length) => this.mem.bytes(at, length));\n this.answer = 0;\n this.exports.asyncify_start_rewind?.(state.asyncifyData);\n }\n rewound() {\n if (this.exports.asyncify_get_state?.() !== REWINDING) return void 0;\n this.exports.asyncify_stop_rewind?.();\n return this.answer;\n }\n fork(fork) {\n const sp = this.stackPointer();\n const globals = this.globals();\n return this.unwind(async (data) => {\n this.answer = await fork(data, globals, sp);\n });\n }\n checkpoint(snapPtr, retPtr) {\n const id = this.nextSnapshot++;\n const v = this.mem.view();\n v.setBigUint64(snapPtr, BigInt(retPtr), true);\n v.setBigUint64(snapPtr + 8, BigInt(id), true);\n v.setBigUint64(snapPtr + 16, 0x51cc5117n, true);\n const globals = this.globals();\n return this.unwind((data) => {\n const end = this.mem.view().getUint32(data, true);\n this.snapshots.set(id, { frames: this.mem.bytes(data + 8, end - data - 8).slice(), globals });\n this.answer = 0;\n });\n }\n restore(snapPtr, val) {\n const id = Number(this.mem.view().getBigUint64(snapPtr + 8, true));\n const snap = this.snapshots.get(id);\n if (!snap) throw new Error(`WASIX: longjmp to an unknown setjmp (${id})`);\n return this.unwind((data) => {\n this.mem.bytes(data + 8, snap.frames.length).set(snap.frames);\n this.mem.view().setUint32(data, data + 8 + snap.frames.length, true);\n this.restoreGlobals(snap.globals);\n this.answer = Number(val) || 1;\n });\n }\n stackGlobal() {\n const g = this.exports[STACK_POINTER];\n return g instanceof WebAssembly.Global ? g : this.linked?.pointer;\n }\n stackPointer() {\n return this.stackGlobal()?.value ?? 0;\n }\n globals() {\n const out = mutableGlobals(this.exports);\n if (this.linked && !out.some(([name2]) => name2 === STACK_POINTER)) {\n out.push([STACK_POINTER, this.linked.pointer.value]);\n }\n return out;\n }\n dataPointer() {\n const own = this.exports[STACK_POINTER] instanceof WebAssembly.Global;\n if (this.linked && (this.threadStack || !own)) return this.linked.low + 15 & ~15;\n const g = this.exports.__data_end;\n const dataEnd = g instanceof WebAssembly.Global ? g.value : 0;\n return dataEnd < this.stackUpper ? dataEnd + 15 & ~15 : 16;\n }\n unwind(then) {\n if (!this.supported) return E.NOSYS;\n const data = this.dataPointer();\n const v = this.mem.view();\n v.setUint32(data, data + 8, true);\n v.setUint32(data + 4, this.stackPointer() - 16, true);\n this.pending = async () => {\n await then(data);\n return data;\n };\n this.exports.asyncify_start_unwind?.(data);\n return E.SUCCESS;\n }\n restoreGlobals(globals) {\n for (const [name2, value2] of globals) {\n const g = name2 === STACK_POINTER ? this.stackGlobal() : this.exports[name2];\n if (g instanceof WebAssembly.Global) g.value = value2;\n }\n }\n};\n\n// src/process/wasi/wasix-ffi.ts\nvar SIZE2 = { i32: 4, i64: 8, f32: 4, f64: 8 };\nfunction read(view, at, type) {\n if (type === \"i32\") return view.getInt32(at, true);\n if (type === \"i64\") return view.getBigInt64(at, true);\n if (type === \"f32\") return view.getFloat32(at, true);\n return view.getFloat64(at, true);\n}\nfunction readSome(view, at, end, type) {\n if (at + SIZE2[type] <= end) return read(view, at, type);\n const some = new DataView(new ArrayBuffer(8));\n for (let i = 0; at + i < end; i++) some.setUint8(i, view.getUint8(at + i));\n return read(some, 0, type);\n}\nfunction write(view, at, type, value2) {\n if (type === \"i32\") view.setInt32(at, Number(value2), true);\n else if (type === \"i64\") view.setBigInt64(at, BigInt(value2), true);\n else if (type === \"f32\") view.setFloat32(at, Number(value2), true);\n else view.setFloat64(at, Number(value2), true);\n}\nfunction scalars(types) {\n if (types.includes(\"other\")) throw new WasiError(\"EINVAL\");\n return types;\n}\nasync function callDynamic(ctx, ...operands) {\n const [id, values, valuesLen, results, resultsLen, strict] = operands.map((n) => n >>> 0);\n const table = ctx.table();\n if (!table) throw new WasiError(\"ENOTSUP\");\n const fn = id < table.length ? table.get(id) : null;\n const sig = fn ? await ctx.types.of(fn) : void 0;\n if (!fn || !sig) throw new WasiError(\"EINVAL\");\n const params = scalars(sig.params);\n const outs = scalars(sig.results);\n const size = (types) => types.reduce((n, type) => n + SIZE2[type], 0);\n if (strict && (size(params) !== valuesLen || size(outs) !== resultsLen)) {\n throw new WasiError(\"EINVAL\");\n }\n const view = ctx.mem.view();\n if (values + valuesLen > view.byteLength || results + resultsLen > view.byteLength) {\n throw new WasiError(\"EFAULT\");\n }\n const end = values + valuesLen;\n let at = values;\n const args = params.map((type) => {\n const v = readSome(view, at, end, type);\n at += SIZE2[type];\n return v;\n });\n const returned = await reentered(fn)(...args);\n const got = outs.length === 1 ? [returned] : returned ?? [];\n const after = ctx.mem.view();\n const stop = results + resultsLen;\n let out = results;\n outs.forEach((type, i) => {\n if (out + SIZE2[type] > stop) return;\n write(after, out, type, got[i]);\n out += SIZE2[type];\n });\n}\n\n// src/process/wasi/wasix-trampoline.ts\nvar CODES = [\"i32\", \"i64\", \"f32\", \"f64\", \"v128\"];\nvar VALTYPE = {\n i32: 127,\n i64: 126,\n f32: 125,\n f64: 124,\n v128: 123\n};\nvar SIZE3 = { i32: 4, i64: 8, f32: 4, f64: 8, v128: 16 };\nvar STORE = {\n i32: [54],\n i64: [55],\n f32: [56],\n f64: [57],\n v128: [253, 11]\n};\nvar LOAD = {\n i32: [40],\n i64: [41],\n f32: [42],\n f64: [43],\n v128: [253, 0]\n};\nfunction valueTypes(codes) {\n const out = [];\n for (const code2 of codes) {\n const type = CODES[code2];\n if (!type) return void 0;\n out.push(type);\n }\n return out;\n}\nfunction u32(n) {\n const out = [];\n let v = n >>> 0;\n do {\n let b = v & 127;\n v >>>= 7;\n if (v) b |= 128;\n out.push(b);\n } while (v);\n return out;\n}\nfunction s32(n) {\n const out = [];\n let v = n | 0;\n for (; ; ) {\n const b = v & 127;\n v >>= 7;\n if (v === 0 && !(b & 64) || v === -1 && b & 64) {\n out.push(b);\n return out;\n }\n out.push(b | 128);\n }\n}\nfunction name(s) {\n const bytes = [...new TextEncoder().encode(s)];\n return [...u32(bytes.length), ...bytes];\n}\nfunction section(id, body) {\n return [id, ...u32(body.length), ...body];\n}\nfunction vec(items) {\n return [...u32(items.length), ...items.flat()];\n}\nfunction align16(n) {\n return Math.ceil(n / 16) * 16;\n}\nfunction trampolineBytes(params, results, shared) {\n const sig = [\n 96,\n ...vec(params.map((t) => [VALTYPE[t]])),\n ...vec(results.map((t) => [VALTYPE[t]]))\n ];\n const backing = [96, ...vec([[127], [127], [127]]), ...vec([])];\n const memory = shared ? [3, 0, ...u32(65536)] : [0, 0];\n const imports = vec([\n [...name(\"env\"), ...name(\"memory\"), 2, ...memory],\n [...name(\"env\"), ...name(\"__indirect_function_table\"), 1, 112, 0, 0],\n [...name(\"env\"), ...name(\"__stack_pointer\"), 3, 127, 1],\n [...name(\"env\"), ...name(\"backing\"), 3, 127, 0],\n [...name(\"env\"), ...name(\"user_data\"), 3, 127, 0]\n ]);\n const n = params.length;\n const [orig, args, res] = [n, n + 1, n + 2];\n const valuesSize = align16(params.reduce((sum, t) => sum + SIZE3[t], 0));\n const resultsSize = align16(results.reduce((sum, t) => sum + SIZE3[t], 0));\n const body = [\n 35,\n 0,\n 34,\n ...u32(orig),\n 65,\n ...s32(resultsSize),\n 107,\n 34,\n ...u32(res)\n ];\n body.push(65, ...s32(valuesSize), 107, 34, ...u32(args), 36, 0);\n let at = 0;\n params.forEach((t, i) => {\n body.push(32, ...u32(args), 32, ...u32(i), ...STORE[t], 0, ...u32(at));\n at += SIZE3[t];\n });\n body.push(32, ...u32(args), 32, ...u32(res), 35, 2, 35, 1, 17, 1, 0);\n at = 0;\n for (const t of results) {\n body.push(32, ...u32(res), ...LOAD[t], 0, ...u32(at));\n at += SIZE3[t];\n }\n body.push(32, ...u32(orig), 36, 0, 11);\n const func = [...vec([[...u32(3), 127]]), ...body];\n return Uint8Array.from([\n 0,\n 97,\n 115,\n 109,\n 1,\n 0,\n 0,\n 0,\n ...section(1, vec([sig, backing])),\n ...section(2, imports),\n ...section(3, vec([[0]])),\n ...section(7, vec([[...name(\"t\"), 0, 0]])),\n ...section(10, vec([[...u32(func.length), ...func]]))\n ]);\n}\nvar Trampolines = class {\n modules = /* @__PURE__ */ new Map();\n get compiled() {\n return this.modules.size;\n }\n make(params, results, env) {\n const shared = env.memory.buffer instanceof SharedArrayBuffer;\n const key = `${params.join(\",\")}>${results.join(\",\")}${shared ? \"s\" : \"\"}`;\n let module = this.modules.get(key);\n if (!module) {\n module = refusedModule(trampolineBytes(params, results, shared));\n this.modules.set(key, module);\n }\n const i32 = (v) => new WebAssembly.Global({ value: \"i32\", mutable: false }, v);\n const instance = new WebAssembly.Instance(module, suspendingImports({\n env: {\n memory: env.memory,\n __indirect_function_table: env.table,\n __stack_pointer: env.stackPointer,\n backing: i32(env.backing),\n user_data: i32(env.userData)\n }\n }));\n const sig = {\n params: params.map((t) => t === \"v128\" ? \"other\" : t),\n results: results.map((t) => t === \"v128\" ? \"other\" : t)\n };\n return { fn: instance.exports.t, sig };\n }\n};\n\n// src/process/wasi/wasm-functypes.ts\nvar VALTYPES = {\n 127: \"i32\",\n 126: \"i64\",\n 125: \"f32\",\n 124: \"f64\"\n};\nvar TABLE_BASE = \"__table_base\";\nvar Reader = class {\n at = 8;\n bytes;\n constructor(bytes) {\n this.bytes = bytes;\n }\n byte() {\n return this.bytes[this.at++] ?? 0;\n }\n u32() {\n let result = 0;\n let shift = 0;\n for (; ; ) {\n const b = this.byte();\n result |= (b & 127) << shift;\n if (!(b & 128)) return result >>> 0;\n shift += 7;\n }\n }\n s32() {\n let result = 0;\n let shift = 0;\n let b;\n do {\n b = this.byte();\n result |= (b & 127) << shift;\n shift += 7;\n } while (b & 128);\n return shift < 32 && b & 64 ? result | -1 << shift : result;\n }\n name() {\n const len = this.u32();\n const s = new TextDecoder().decode(this.bytes.subarray(this.at, this.at + len));\n this.at += len;\n return s;\n }\n valtype() {\n const code2 = this.byte();\n if (code2 === 99 || code2 === 100) this.s32();\n return VALTYPES[code2] ?? \"other\";\n }\n limits() {\n const flags = this.byte();\n this.u32();\n if (flags & 1) this.u32();\n }\n};\nfunction readTypes(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n r.byte();\n const params = [];\n for (let n = r.u32(); n > 0; n--) params.push(r.valtype());\n const results = [];\n for (let n = r.u32(); n > 0; n--) results.push(r.valtype());\n s.info.sigs.push({ params, results });\n }\n}\nfunction readImports(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n r.name();\n const field2 = r.name();\n const kind = r.byte();\n if (kind === 0) s.info.funcs.push(r.u32());\n else if (kind === 1) {\n r.valtype();\n r.limits();\n } else if (kind === 2) r.limits();\n else if (kind === 3) {\n r.valtype();\n r.byte();\n s.globals.push(field2);\n } else {\n r.byte();\n r.u32();\n }\n }\n}\nfunction readFunctions(r, s) {\n for (let i = r.u32(); i > 0; i--) s.info.funcs.push(r.u32());\n}\nvar SKIP = {\n 66: (r) => r.s32(),\n 67: (r) => {\n r.at += 4;\n },\n 68: (r) => {\n r.at += 8;\n },\n 208: (r) => r.valtype()\n};\nfunction constExpr(r, s) {\n let value2 = 0;\n let tableBase = false;\n let known = true;\n for (; ; ) {\n const op = r.byte();\n if (op === 11) return known ? { value: value2, tableBase } : void 0;\n if (op === 65) value2 += r.s32();\n else if (op === 35) {\n const g = s.globals[r.u32()];\n if (g === TABLE_BASE) tableBase = true;\n else if (typeof g === \"number\") value2 += g;\n else known = false;\n } else if (op === 210) {\n value2 = r.u32();\n } else if (op in SKIP) {\n SKIP[op]?.(r);\n known = false;\n } else if (op !== 106) {\n r.at = r.bytes.length;\n return void 0;\n }\n }\n}\nfunction readGlobals(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n r.valtype();\n r.byte();\n const init = constExpr(r, s);\n s.globals.push(init && !init.tableBase ? init.value : void 0);\n }\n}\nfunction readExports(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n const name2 = r.name();\n const kind = r.byte();\n const index3 = r.u32();\n if (kind === 0) s.info.exports[name2] = index3;\n }\n}\nfunction readElems(r, s) {\n for (let i = r.u32(); i > 0; i--) {\n const flags = r.u32();\n const active = (flags & 1) === 0;\n const table = flags & 2 ? active ? r.u32() : 0 : 0;\n const offset = active ? constExpr(r, s) : void 0;\n if (flags & 3) r.valtype();\n const funcs = [];\n for (let n = r.u32(); n > 0; n--) {\n if (flags & 4) {\n const ref = constExpr(r, s);\n funcs.push(ref ? ref.value : -1);\n } else funcs.push(r.u32());\n }\n if (offset && table === 0) {\n s.info.elems.push({ offset: offset.value, tableBase: offset.tableBase, funcs });\n }\n }\n}\nvar SECTIONS = {\n 1: readTypes,\n 2: readImports,\n 3: readFunctions,\n 6: readGlobals,\n 7: readExports,\n 9: readElems\n};\nfunction funcTypeInfo(bytes) {\n const r = new Reader(bytes);\n const s = { info: { sigs: [], funcs: [], exports: {}, elems: [] }, globals: [] };\n while (r.at < bytes.length) {\n const id = r.byte();\n const end = r.u32() + r.at;\n SECTIONS[id]?.(r, s);\n r.at = end;\n }\n return s.info;\n}\nvar FuncTypes = class {\n known = /* @__PURE__ */ new WeakMap();\n pending = [];\n register(read2, instance, table, tableBase) {\n this.pending.push(async () => {\n const bytes = await read2();\n if (bytes) this.add(funcTypeInfo(bytes), instance, table, tableBase);\n });\n }\n add(info, instance, table, tableBase) {\n const sig = (func) => info.sigs[info.funcs[func] ?? -1];\n for (const [name2, func] of Object.entries(info.exports)) {\n const fn = instance.exports[name2];\n const type = sig(func);\n if (typeof fn === \"function\" && type) this.known.set(fn, type);\n }\n if (!table) return;\n for (const seg of info.elems) {\n const start2 = seg.offset + (seg.tableBase ? tableBase : 0);\n seg.funcs.forEach((func, i) => {\n const type = sig(func);\n const fn = start2 + i < table.length ? table.get(start2 + i) : null;\n if (fn && type) this.known.set(fn, type);\n });\n }\n }\n set(fn, sig) {\n this.known.set(fn, sig);\n }\n async of(fn) {\n const known = this.known.get(fn);\n if (known || this.pending.length === 0) return known;\n const pending = this.pending;\n this.pending = [];\n for (const run of pending) await run();\n return this.known.get(fn);\n }\n};\n\n// src/process/wasi/wasix-linker.ts\nvar TABLE_BASE2 = 1;\nvar PAGE2 = 65536;\nvar STACK_SIZE = 8 * 1024 * 1024;\nvar LIBRARY_DIRS = [\"/lib\", \"/usr/lib\", \"/usr/local/lib\"];\nfunction expandOrigin(entry, dir) {\n return entry.replace(/\\$(?:ORIGIN\\b|\\{ORIGIN\\})/g, dir);\n}\nvar DlError = class extends Error {\n};\nvar WasixLinker = class {\n table;\n stackPointer;\n memoryBase;\n stackLow;\n stackHigh;\n cLongjmp;\n cppException;\n main;\n modules = /* @__PURE__ */ new Map();\n forkedTls;\n byPath = /* @__PURE__ */ new Map();\n mainGot = [];\n slots = /* @__PURE__ */ new Map();\n nextHandle = 1;\n publisher;\n indices;\n types = new FuncTypes();\n trampolines = new Trampolines();\n memory;\n host;\n constructor(memory, mainInfo, host, thread = false) {\n this.memory = memory;\n this.host = host;\n this.memoryBase = Math.max(1, 2 ** mainInfo.memoryAlign);\n this.stackLow = align(this.memoryBase + mainInfo.memorySize, 1024);\n this.stackHigh = this.stackLow + STACK_SIZE;\n if (!thread) growTo(memory, this.stackHigh);\n this.table = new WebAssembly.Table({\n element: \"anyfunc\",\n initial: TABLE_BASE2 + mainInfo.tableSize\n });\n this.stackPointer = new WebAssembly.Global(\n { value: \"i32\", mutable: true },\n thread ? 0 : this.stackHigh\n );\n const tag = () => new WebAssembly.Tag({\n parameters: [\"i32\"]\n });\n this.cLongjmp = tag();\n this.cppException = tag();\n }\n mainImports(module) {\n const i32 = (v) => new WebAssembly.Global({ value: \"i32\", mutable: false }, v);\n const got = (v) => new WebAssembly.Global({ value: \"i32\", mutable: true }, v);\n const env = {\n memory: this.memory,\n __indirect_function_table: this.table,\n __stack_pointer: this.stackPointer,\n __memory_base: i32(this.memoryBase),\n __table_base: i32(TABLE_BASE2),\n __c_longjmp: this.cLongjmp,\n __cpp_exception: this.cppException\n };\n const gotMem = {\n __stack_high: got(this.stackHigh),\n __stack_low: got(this.stackLow),\n __heap_base: got(this.stackHigh)\n };\n const gotFunc = {};\n this.mainGot = [];\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module === \"env\" && imp.kind === \"function\" && !(imp.name in env)) {\n env[imp.name] = this.functionImport(imp.name);\n } else if (imp.module === \"GOT.func\" || imp.module === \"GOT.mem\" && !(imp.name in gotMem)) {\n const g = got(0);\n (imp.module === \"GOT.func\" ? gotFunc : gotMem)[imp.name] = g;\n const kind = imp.module;\n this.mainGot.push(async () => {\n g.value = kind === \"GOT.func\" ? await this.slotOrNull(imp.name) : this.addressOrNull(imp.name);\n });\n }\n }\n return { env, \"GOT.mem\": gotMem, \"GOT.func\": gotFunc };\n }\n async bindMainGot() {\n for (const resolve of this.mainGot) await resolve();\n }\n async bindMain(instance, relocate) {\n this.main = instance;\n if (relocate) await call(instance, \"__wasm_apply_data_relocs\");\n }\n mainPath;\n async isMain(path) {\n if (this.mainPath === void 0) return false;\n if (path === this.mainPath) return true;\n const real = this.host.real;\n if (real === void 0) return false;\n try {\n return await real(path) === await real(this.mainPath);\n } catch {\n return false;\n }\n }\n async open(name2, cwd, ldPath) {\n const path = await this.locate(name2, cwd, ldPath);\n if (await this.isMain(path)) return 0;\n await this.indices?.lock();\n try {\n return (await this.load(path, cwd, ldPath)).handle;\n } finally {\n await this.indices?.unlock();\n }\n }\n async symbol(handle, name2) {\n const found = handle === 0 ? this.find(name2) : this.findIn(this.module(handle), name2, /* @__PURE__ */ new Set());\n if (!found) throw new DlError(`undefined symbol: ${name2}`);\n const [owner, value2] = found;\n if (typeof value2 === \"function\") return await this.slot(value2, owner, name2);\n if (value2 instanceof WebAssembly.Global) return this.baseOf(owner) + value2.value;\n throw new DlError(`${name2} is neither a function nor data`);\n }\n invalid(handle) {\n return !this.modules.has(handle);\n }\n cache;\n compiled() {\n const out = {};\n for (const [path, linked] of this.byPath) out[path] = linked.module;\n return out;\n }\n async allocateClosure() {\n const index3 = await this.indices.allocate(this.table.length);\n growTable(this.table, index3 + 1);\n this.live.add(index3);\n return index3;\n }\n async freeClosure(index3) {\n await this.indices?.free(index3);\n this.live.delete(index3);\n this.table.set(index3, null);\n }\n live = /* @__PURE__ */ new Set();\n async prepareClosure(record) {\n if (!this.live.has(record.index)) throw new DlError(`closure ${record.index}: not allocated`);\n const full = { kind: \"closure-prepare\", ...record };\n this.install(full);\n await this.publisher?.(full);\n }\n install(record) {\n growTable(this.table, record.index + 1);\n const { fn, sig } = this.trampolines.make(record.params, record.results, {\n memory: this.memory,\n table: this.table,\n stackPointer: this.stackPointer,\n backing: record.backing,\n userData: record.userData\n });\n this.table.set(record.index, fn);\n this.types.set(fn, sig);\n }\n async reserveLoad(size) {\n return await this.indices?.load(this.table.length, size) ?? {\n base: this.table.length,\n handle: this.nextHandle++\n };\n }\n async reserve(size) {\n return await this.indices?.reserve(this.table.length, size) ?? this.table.length;\n }\n tlsBases() {\n const bases = [];\n for (const [handle, linked] of this.modules) {\n const base = linked.instance.exports.__tls_base;\n if (base instanceof WebAssembly.Global) bases.push([handle, base.value]);\n }\n return bases;\n }\n carryTls(linked) {\n const base = this.forkedTls?.get(linked.handle);\n const global = linked.instance.exports.__tls_base;\n if (base === void 0 || !(global instanceof WebAssembly.Global)) return false;\n global.value = base;\n reseatTls(\n linked.instance.exports,\n (at, length) => new Uint8Array(this.memory.buffer, at, length)\n );\n return true;\n }\n async replay(record) {\n if (record.kind === \"closure\") {\n growTable(this.table, record.index + 1);\n this.live.add(record.index);\n return;\n }\n if (record.kind === \"closure-free\") {\n this.live.delete(record.index);\n if (record.index < this.table.length) this.table.set(record.index, null);\n return;\n }\n if (record.kind === \"closure-prepare\") {\n this.install(record);\n return;\n }\n if (record.kind === \"load\") {\n if (this.modules.has(record.handle)) return;\n const linked = await this.instantiate(record.path, await this.moduleAt(record.path), record, false);\n linked.needed.push(...record.needed ?? []);\n this.nextHandle = Math.max(this.nextHandle, record.handle + 1);\n return;\n }\n const value2 = record.handle === 0 ? this.main?.exports[record.name] : this.module(record.handle).instance.exports[record.name];\n if (typeof value2 !== \"function\") throw new DlError(`${record.name}: not a function`);\n growTable(this.table, record.index + 1);\n this.table.set(record.index, value2);\n this.slots.set(value2, record.index);\n }\n async moduleAt(path) {\n const cached = this.cache?.[path];\n if (cached) return cached;\n const bytes = await this.host.read(path);\n if (!bytes) throw new DlError(`${path}: gone`);\n return refusedModule(bytes);\n }\n module(handle) {\n const m = this.modules.get(handle);\n if (!m) throw new DlError(`invalid handle ${handle}`);\n return m;\n }\n async locate(name2, cwd, ldPath) {\n if (name2.includes(\"/\"))\n return name2.startsWith(\"/\") ? normalize(name2) : normalize(`${cwd}/${name2}`);\n for (const dir of [...ldPath.filter(Boolean), ...LIBRARY_DIRS]) {\n const path = normalize(`${dir.startsWith(\"/\") ? \"\" : `${cwd}/`}${dir}/${name2}`);\n if (this.byPath.has(path) || await this.host.read(path)) return path;\n }\n throw new DlError(`${name2}: not found`);\n }\n async load(path, cwd, ldPath) {\n const loaded = this.byPath.get(path);\n if (loaded) return loaded;\n const bytes = await this.host.read(path);\n if (!bytes) throw new DlError(`${path}: no such file`);\n let module;\n try {\n module = refusedModule(bytes);\n } catch (e) {\n throw new DlError(`${path}: not a wasm module (${e.message})`);\n }\n const info = dylinkInfo(module);\n if (!info) throw new DlError(`${path}: not a side module (no dylink.0)`);\n const dir = path.slice(0, path.lastIndexOf(\"/\")) || \"/\";\n const search = [dir, ...ldPath, ...info.runtimePath.map((p) => expandOrigin(p, dir))];\n const needed = [];\n for (const n of info.needed)\n needed.push((await this.load(await this.locate(n, cwd, search), cwd, ldPath)).handle);\n const memoryBase = await this.allocate(info.memorySize, 2 ** info.memoryAlign);\n const { base: tableBase, handle } = await this.reserveLoad(info.tableSize);\n const record = {\n kind: \"load\",\n handle,\n path,\n memoryBase,\n tableBase,\n ...needed.length > 0 ? { needed } : {}\n };\n const linked = await this.instantiate(path, module, record, true);\n linked.needed.push(...needed);\n await this.publisher?.(record);\n return linked;\n }\n async instantiate(path, module, at, init) {\n const info = dylinkInfo(module);\n growTable(this.table, at.tableBase + info.tableSize);\n const pending = [];\n const env = {\n memory: this.memory,\n __indirect_function_table: this.table,\n __stack_pointer: this.stackPointer,\n __memory_base: new WebAssembly.Global({ value: \"i32\", mutable: false }, at.memoryBase),\n __table_base: new WebAssembly.Global({ value: \"i32\", mutable: false }, at.tableBase),\n __c_longjmp: this.cLongjmp,\n __cpp_exception: this.cppException\n };\n const gotMem = {};\n const gotFunc = {};\n const linked = {\n handle: at.handle,\n path,\n module,\n info,\n instance: void 0,\n memoryBase: at.memoryBase,\n tableBase: at.tableBase,\n needed: []\n };\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module === \"env\" && imp.kind === \"function\" && !(imp.name in env)) {\n env[imp.name] = this.functionImport(imp.name);\n } else if (imp.module === \"GOT.mem\") {\n const g = new WebAssembly.Global({ value: \"i32\", mutable: true }, 0);\n gotMem[imp.name] = g;\n pending.push(() => {\n g.value = this.addressOrNull(imp.name);\n });\n } else if (imp.module === \"GOT.func\") {\n const g = new WebAssembly.Global({ value: \"i32\", mutable: true }, 0);\n gotFunc[imp.name] = g;\n pending.push(async () => {\n g.value = await this.slotOrNull(imp.name);\n });\n }\n }\n const imports = {\n ...this.host.hostImports(module),\n env,\n \"GOT.mem\": gotMem,\n \"GOT.func\": gotFunc\n };\n linked.instance = new WebAssembly.Instance(module, suspendingImports(imports));\n this.types.register(async () => await this.host.read(path), linked.instance, this.table, at.tableBase);\n this.modules.set(at.handle, linked);\n const first = this.byPath.get(path);\n if (!first || at.handle < first.handle) this.byPath.set(path, linked);\n for (const resolve of pending) await resolve();\n if (init) {\n await call(linked.instance, \"__wasm_apply_data_relocs\");\n await call(linked.instance, \"__wasm_call_ctors\");\n } else if (!this.carryTls(linked)) {\n await call(linked.instance, \"__wasix_init_tls\");\n }\n return linked;\n }\n functionImport(name2) {\n const now = this.find(name2);\n if (now && typeof now[1] === \"function\") return now[1];\n let resolved2;\n return async (...args) => {\n if (!resolved2) {\n const later2 = this.find(name2);\n if (!later2 || typeof later2[1] !== \"function\")\n throw new WebAssembly.RuntimeError(`unresolved symbol ${name2}`);\n resolved2 = later2[1];\n }\n return await resolved2(...args);\n };\n }\n addressOrNull(name2) {\n const found = this.find(name2);\n if (!found || !(found[1] instanceof WebAssembly.Global)) return 0;\n return this.baseOf(found[0]) + found[1].value;\n }\n async slotOrNull(name2) {\n const found = this.find(name2);\n if (!found || typeof found[1] !== \"function\") return 0;\n return await this.slot(found[1], found[0], name2);\n }\n find(name2) {\n const inMain = this.main?.exports[name2];\n if (inMain !== void 0) return [0, inMain];\n for (const m of this.modules.values()) {\n const v = m.instance?.exports[name2];\n if (v !== void 0) return [m.handle, v];\n }\n return void 0;\n }\n findIn(m, name2, seen) {\n if (seen.has(m.handle)) return void 0;\n seen.add(m.handle);\n const v = m.instance.exports[name2];\n if (v !== void 0) return [m.handle, v];\n for (const h of m.needed) {\n const found = this.findIn(this.module(h), name2, seen);\n if (found) return found;\n }\n return void 0;\n }\n baseOf(handle) {\n return handle === 0 ? this.memoryBase : this.module(handle).memoryBase;\n }\n indexed = 0;\n indexTable() {\n for (let i = this.indexed; i < this.table.length; i++) {\n const fn = this.table.get(i);\n if (fn && !this.slots.has(fn)) this.slots.set(fn, i);\n }\n this.indexed = this.table.length;\n }\n async slot(fn, handle, name2) {\n this.indexTable();\n const known = this.slots.get(fn);\n if (known !== void 0) return known;\n const index3 = await this.reserve(1);\n growTable(this.table, index3 + 1);\n this.table.set(index3, fn);\n this.slots.set(fn, index3);\n await this.publisher?.({ kind: \"slot\", index: index3, handle, name: name2 });\n return index3;\n }\n async heapAlloc(bytes) {\n const exports = this.main?.exports;\n const calloc = exports?.calloc;\n if (typeof calloc !== \"function\") return void 0;\n const state = exports?.asyncify_get_state;\n if (typeof state === \"function\" && await state() !== 0) return void 0;\n const at = await calloc(1, bytes) >>> 0;\n return at === 0 ? void 0 : at;\n }\n async allocate(size, alignment) {\n if (size === 0) return 0;\n const to = Math.max(alignment, 16);\n const heap = await this.heapAlloc(size + to - 16);\n if (heap !== void 0) return align(heap, to);\n const pages2 = Math.ceil((size + (to > PAGE2 ? to : 0)) / PAGE2);\n return align(this.memory.grow(pages2) * PAGE2, to);\n }\n};\nfunction align(n, to) {\n return Math.ceil(n / to) * to;\n}\nfunction growTo(memory, bytes) {\n const pages2 = Math.ceil(bytes / PAGE2) - memory.buffer.byteLength / PAGE2;\n if (pages2 > 0) memory.grow(pages2);\n}\nfunction growTable(table, length) {\n if (table.length < length) table.grow(length - table.length);\n}\nasync function call(instance, name2) {\n const fn = instance.exports[name2];\n if (typeof fn === \"function\") await fn();\n}\n\n// src/process/wasi/wasix-host.ts\nvar FDFLAGSEXT_CLOEXEC = 1;\nvar SPAWN_OP_SIZE = 56;\nvar SPAWN_OPS = [\"close\", \"dup2\", \"open\", \"chdir\", \"fchdir\"];\nvar RIGHTS_FD_WRITE = 1n << 6n;\nvar ICANON = 2;\nvar ECHO = 8;\nvar EINTR_LIBC = 22;\nvar STRICT_EPOLL_LIBC = 29;\nvar CWD_FD_LIBC = 41;\nvar MAIN_HANDLE = 2147483647;\nvar WasixHost = class _WasixHost {\n process;\n threads;\n linker;\n types = new FuncTypes();\n table;\n signals;\n host;\n driver;\n constructor(host, driver, module) {\n this.host = host;\n this.driver = driver;\n this.process = new WasixProcess(\n host,\n driver,\n () => (this.threads?.tid ?? MAIN_TID) !== MAIN_TID\n );\n const libc = module ? libcVersion(module) ?? 0 : void 0;\n if (libc !== void 0) host.strictEpoll = libc >= STRICT_EPOLL_LIBC;\n if (libc !== void 0) host.cwdFd = libc >= CWD_FD_LIBC;\n if (module && !WebAssembly.Module.imports(module).some((i) => i.name === \"fd_fdflags_set\")) {\n host.fds.implicitCloexec = true;\n host.interruptWakes = (libcVersion(module) ?? 0) < EINTR_LIBC;\n }\n }\n get mem() {\n return this.host.mem;\n }\n str(ptr, len) {\n const s = this.mem.string(ptr, len);\n return s.endsWith(\"\\0\") ? s.slice(0, -1) : s;\n }\n cStrings(ptr, count) {\n const v = this.mem.view();\n return Array.from(\n { length: count },\n (_, i) => this.mem.cString(v.getUint32(ptr + i * 4, true))\n );\n }\n async execOrExit(n, nl, a, al, e, el) {\n try {\n return await this.process.exec({\n name: this.str(n, nl),\n argv: _WasixHost.lines(this.str(a, al)),\n env: _WasixHost.env(e === 0 ? void 0 : _WasixHost.lines(this.str(e, el))),\n search: false,\n path: \"\"\n });\n } catch (err) {\n if (err instanceof WasiExit) throw err;\n const code2 = err instanceof WasiError ? err.code : err?.code;\n throw new WasiExit(wasiErrnoOf(typeof code2 === \"string\" ? code2 : \"ENOEXEC\"));\n }\n }\n static env(entries2) {\n if (!entries2) return void 0;\n const env = {};\n for (const line of entries2) {\n const eq = line.indexOf(\"=\");\n if (eq > 0) env[line.slice(0, eq)] = line.slice(eq + 1);\n }\n return env;\n }\n static lines(text) {\n return text.split(\"\\n\").filter((line, i, all) => line !== \"\" || i < all.length - 1);\n }\n spawnOps(ptr, count) {\n const v = this.mem.view();\n return Array.from({ length: count }, (_, i) => {\n const p = ptr + i * SPAWN_OP_SIZE;\n const cmd = SPAWN_OPS[v.getUint8(p)];\n if (!cmd) throw new WasiError(\"EINVAL\");\n return {\n cmd,\n fd: v.getUint32(p + 4, true),\n srcFd: v.getUint32(p + 8, true),\n path: this.str(v.getUint32(p + 12, true), v.getUint32(p + 16, true)),\n oflags: v.getUint16(p + 24, true),\n rightsWrite: (v.getBigUint64(p + 32, true) & RIGHTS_FD_WRITE) !== 0n,\n append: (v.getUint16(p + 48, true) & FDFLAGS.APPEND) !== 0\n };\n });\n }\n imports() {\n return wrap({\n ...this.startupImports(),\n ...this.fdImports(),\n ...this.processImports(),\n ...this.threadImports(),\n ...this.dlImports(),\n closure_allocate: async (out) => {\n if (!this.linker) throw new WasiError(\"ENOTSUP\");\n this.mem.view().setUint32(out, await this.linker.allocateClosure(), true);\n },\n closure_prepare: async (backing, index3, argTypes, argCount, resultTypes, resultCount, userData) => {\n if (!this.linker) throw new WasiError(\"ENOTSUP\");\n const params = valueTypes(this.mem.bytes(argTypes, argCount));\n const results = valueTypes(this.mem.bytes(resultTypes, resultCount));\n if (!params || !results) throw new WasiError(\"EINVAL\");\n try {\n await this.linker.prepareClosure({ index: index3, backing, userData, params, results });\n } catch (e) {\n if (e instanceof DlError) throw new WasiError(\"EINVAL\");\n throw e;\n }\n },\n closure_free: async (index3) => {\n if (!this.linker) throw new WasiError(\"ENOTSUP\");\n await this.linker.freeClosure(index3);\n },\n call_dynamic: async (...a) => void await callDynamic(\n { mem: this.mem, table: () => this.table, types: this.types },\n ...a\n ),\n ...wasixSocketImports(this.host, this.host.imports()),\n ...wasixEpollImports(this.host)\n });\n }\n preview1() {\n const { fds } = this.host;\n return wrap({\n fd_renumber: async (from, to) => void await fds.renumber(from, to, true),\n fd_close: async (fd) => {\n const e = await fds.get(fd);\n if (e.type !== \"dir\" || !e.preopen) await fds.close(fd);\n }\n });\n }\n startupImports() {\n const { host, mem } = this;\n return {\n proc_exit2: (code2) => {\n throw new WasiExit(code2);\n },\n proc_signals_sizes_get: (out) => void mem.view().setUint32(out, 0, true),\n proc_signals_get: () => E.SUCCESS,\n callback_signal: (name2, len) => void this.signals?.register(this.str(name2, len)),\n proc_raise_interval: async (sig, interval, repeat) => void await host.o.kernel.call({\n op: \"proc-alarm\",\n sig: posixSignal(sig),\n ms: nsToMs(interval),\n repeat: repeat !== 0\n }),\n proc_raise_interval2: async (sig, initial, interval, repeat) => {\n const ms = nsToMs(interval);\n await host.o.kernel.call({\n op: \"proc-alarm\",\n sig: posixSignal(sig),\n ms,\n firstMs: nsToMs(initial),\n repeat: repeat !== 0 && ms > 0\n });\n },\n proc_id: (out) => void mem.view().setUint32(out, host.o.pid, true),\n proc_parent: async (pid, out) => {\n if (pid !== 0 && pid !== host.o.pid) throw new WasiError(\"ESRCH\");\n mem.view().setUint32(out, await host.o.parent?.() ?? host.o.ppid ?? 1, true);\n },\n getcwd: async (buf, lenPtr) => {\n if (host.cwdFd && host.fds.held && !await host.fds.held.alive()) return E.NOENT;\n const bytes = new TextEncoder().encode(await host.workingDir());\n const max = mem.view().getUint32(lenPtr, true);\n mem.view().setUint32(lenPtr, bytes.length, true);\n if (bytes.length > max) return E.RANGE;\n mem.bytes(buf, bytes.length).set(bytes);\n if (bytes.length < max) mem.view().setUint8(buf + bytes.length, 0);\n return E.SUCCESS;\n },\n chdir: async (ptr, len) => {\n const path = await host.fds.resolve(3, this.str(ptr, len));\n if (!(await host.o.fs.stat(path)).isDirectory) throw new WasiError(\"ENOTDIR\");\n await host.fds.chdir(path);\n }\n };\n }\n fdImports() {\n const { host, mem } = this;\n const preview1 = host.imports();\n return {\n fd_dup: async (fd, out) => void mem.view().setUint32(out, await host.fds.dup(fd, 0, false), true),\n fd_dup2: async (fd, min, cloexec, out) => void mem.view().setUint32(out, await host.fds.dup(fd, min, cloexec !== 0), true),\n fd_pipe: async (rPtr, wPtr) => {\n const [r, w] = await host.fds.pipe();\n mem.view().setUint32(rPtr, r, true);\n mem.view().setUint32(wPtr, w, true);\n },\n fd_fdflags_get: async (fd, out) => {\n await host.fds.get(fd);\n mem.view().setUint16(out, host.fds.cloexec.has(fd) ? FDFLAGSEXT_CLOEXEC : 0, true);\n },\n fd_fdflags_set: async (fd, flags) => void await host.fds.setCloexec(fd, (flags & FDFLAGSEXT_CLOEXEC) !== 0),\n path_open2: async (dirfd, lookup2, p, l, oflags, rights, inheriting, fdflags, fdflagsext, out) => {\n const r = preview1.path_open(dirfd, lookup2, p, l, oflags, rights, inheriting, fdflags, out);\n if (r === E.SUCCESS && fdflagsext & FDFLAGSEXT_CLOEXEC)\n await host.fds.setCloexec(mem.view().getUint32(out, true), true);\n return r;\n },\n tty_get: async (ptr) => void await this.ttyGet(ptr),\n tty_set: async (ptr) => void await this.ttySet(ptr)\n };\n }\n processImports() {\n const { mem, process } = this;\n return {\n proc_fork: (_copy, pidPtr) => process.fork(pidPtr),\n stack_checkpoint: (snapPtr, retPtr) => {\n const back = this.driver.rewound();\n if (back === void 0) return this.driver.checkpoint(snapPtr, retPtr);\n mem.view().setBigUint64(retPtr, BigInt(back), true);\n return E.SUCCESS;\n },\n stack_restore: (snapPtr, val) => void this.driver.restore(snapPtr, val),\n proc_join: async (pidPtr, flags, statusPtr) => void await process.join(pidPtr, flags, statusPtr),\n proc_signal: async (pid, sig) => {\n const posix = sig === 0 ? 0 : wasixSignal(sig);\n if (posix === void 0) throw new WasiError(\"EINVAL\");\n if (pid === this.host.o.pid && posix !== 0 && await this.host.onRaise?.(posix)) return;\n await this.host.o.kernel.call({ op: \"proc-kill\", pid, sig: posix });\n },\n proc_exec: async (n, nl, a, al) => await this.execOrExit(n, nl, a, al, 0, 0),\n proc_exec2: async (n, nl, a, al, e, el) => await this.execOrExit(n, nl, a, al, e, el),\n proc_exec3: async (n, nl, a, al, e, el, search, p, pl) => await process.exec({\n name: this.str(n, nl),\n argv: _WasixHost.lines(this.str(a, al)),\n env: _WasixHost.env(_WasixHost.lines(this.str(e, el))),\n search: search !== 0,\n path: this.str(p, pl)\n }),\n proc_exec4: async (n, nl, a, ac, e, ec, search, p, pl) => await process.exec({\n name: this.str(n, nl),\n argv: this.cStrings(a, ac),\n env: _WasixHost.env(e === 0 ? void 0 : this.cStrings(e, ec)),\n search: search !== 0,\n path: this.str(p, pl)\n }),\n proc_spawn2: async (...args) => {\n const [n, nl, a, al, e, el, ops, opc, , , search, p, pl, out] = args;\n const pid = await process.spawn({\n name: this.str(n, nl),\n argv: _WasixHost.lines(this.str(a, al)),\n env: _WasixHost.env(_WasixHost.lines(this.str(e, el))),\n search: search !== 0,\n path: this.str(p, pl),\n ops: this.spawnOps(ops, opc)\n });\n mem.view().setUint32(out, pid, true);\n },\n proc_spawn3: async (...args) => {\n const [n, nl, a, ac, e, ec, ops, opc, , , search, p, pl, out] = args;\n const pid = await process.spawn({\n name: this.str(n, nl),\n argv: this.cStrings(a, ac),\n env: _WasixHost.env(e === 0 ? void 0 : this.cStrings(e, ec)),\n search: search !== 0,\n path: this.str(p, pl),\n ops: this.spawnOps(ops, opc)\n });\n mem.view().setUint32(out, pid, true);\n }\n };\n }\n dlImports() {\n const { mem, host } = this;\n const failed2 = (message, buf, len) => {\n if (len > 0) {\n const bytes = new TextEncoder().encode(message).subarray(0, len - 1);\n mem.bytes(buf, bytes.length).set(bytes);\n mem.view().setUint8(buf + bytes.length, 0);\n }\n return E.NOEXEC;\n };\n const linked = async (buf, len, op, out) => {\n if (!this.linker) return failed2(\"not a dynamically-linked program\", buf, len);\n try {\n out(await op(this.linker));\n return E.SUCCESS;\n } catch (e) {\n if (e instanceof DlError) return failed2(e.message, buf, len);\n throw e;\n }\n };\n return {\n dlopen: async (p, pl, _flags, buf, len, lp, ll, out) => {\n if (p === 0) {\n if (!this.linker) return failed2(\"not a dynamically-linked program\", buf, len);\n mem.view().setUint32(out, MAIN_HANDLE, true);\n return E.SUCCESS;\n }\n return await linked(\n buf,\n len,\n async (l) => await l.open(this.str(p, pl), await host.workingDir(), lp === 0 ? [] : this.str(lp, ll).split(\":\")),\n (h) => void mem.view().setUint32(out, h === 0 ? MAIN_HANDLE : h, true)\n );\n },\n dlsym: async (handle, s, sl, buf, len, out) => await linked(\n buf,\n len,\n async (l) => await l.symbol(handle === MAIN_HANDLE ? 0 : handle, this.str(s, sl)),\n (v) => void mem.view().setUint32(out, v, true)\n ),\n dl_invalid_handle: (handle) => this.linker && (handle === MAIN_HANDLE || handle !== 0 && !this.linker.invalid(handle)) ? E.SUCCESS : E.NOEXEC\n };\n }\n threadImports() {\n const { mem, host } = this;\n const i32 = () => new Int32Array(mem.view().buffer);\n return {\n thread_id: (out) => void mem.view().setUint32(out, this.threads?.tid ?? MAIN_TID, true),\n thread_parallelism: (out) => void mem.view().setUint32(out, this.threads?.parallelism() ?? 1, true),\n thread_exit: (code2) => {\n if (this.threads && this.threads.tid !== MAIN_TID) throw new ThreadExit();\n throw new WasiExit(code2);\n },\n thread_signal: async (tid, sig) => {\n if (!(this.threads?.known(tid) ?? tid === MAIN_TID)) throw new WasiError(\"ESRCH\");\n const posix = posixSignal(sig);\n if (await host.onRaise?.(posix)) return;\n await host.o.kernel.call({ op: \"thread-kill\", tid, sig: posix });\n },\n thread_spawn_v2: async (startPtr, tidPtr) => {\n if (!this.threads) return E.NOTSUP;\n const tid = await this.threads.spawn(startPtr);\n if (tid < 0) return E.AGAIN;\n mem.view().setUint32(tidPtr, tid, true);\n return E.SUCCESS;\n },\n futex_wait: async (ptr, expected, timeoutPtr, wokenPtr) => {\n const v = mem.view();\n const timed = timeoutPtr !== 0 && v.getUint8(timeoutPtr) === 1;\n const ms = timed ? Number(v.getBigUint64(timeoutPtr + 8, true)) / 1e6 : Number.POSITIVE_INFINITY;\n const woken = host.entered || await host.futexes.wait(i32(), ptr >> 2, expected | 0, ms, host.interrupted);\n v.setUint8(wokenPtr, woken ? 1 : 0);\n },\n futex_wake: (ptr, wokenPtr) => {\n host.futexes.notify(i32(), ptr >> 2, 1);\n mem.view().setUint8(wokenPtr, 1);\n },\n futex_wake_all: (ptr, wokenPtr) => {\n host.futexes.notify(i32(), ptr >> 2);\n mem.view().setUint8(wokenPtr, 1);\n }\n };\n }\n async ttyFd() {\n for (const fd of [0, 1, 2]) {\n const e = await this.host.fds.find(fd);\n if (e?.type === \"kernel\" && await this.host.fds.kind(fd, e) === \"tty\") return fd;\n }\n return (await this.host.fds.terminals()).find((fd) => fd > 2);\n }\n async ttyGet(ptr) {\n const { host, mem } = this;\n await host.interrupted?.();\n const v = mem.view();\n mem.bytes(ptr, 24).fill(0);\n const fd = await this.ttyFd();\n const isTty2 = async (n) => {\n const e = await host.fds.find(n);\n return e?.type === \"kernel\" && await host.fds.kind(n, e) === \"tty\" ? 1 : 0;\n };\n v.setUint8(ptr + 16, await isTty2(0));\n v.setUint8(ptr + 17, await isTty2(1));\n v.setUint8(ptr + 18, await isTty2(2));\n if (fd === void 0) throw new WasiError(\"ENOTTY\");\n const [rows, cols] = await host.o.kernel.sys.winsize?.(fd) ?? [24, 80];\n const termios = await host.o.kernel.sys.tcgets?.(fd);\n v.setUint32(ptr, cols, true);\n v.setUint32(ptr + 4, rows, true);\n v.setUint8(ptr + 19, termios && termios.c_lflag & ECHO ? 1 : 0);\n v.setUint8(ptr + 20, termios && termios.c_lflag & ICANON ? 1 : 0);\n }\n async ttySet(ptr) {\n await this.host.interrupted?.();\n const fd = await this.ttyFd();\n if (fd === void 0) throw new WasiError(\"ENOTTY\");\n const { sys } = this.host.o.kernel;\n const termios = await sys.tcgets?.(fd);\n if (!termios) throw new WasiError(\"ENOTTY\");\n const v = this.mem.view();\n let lflag = termios.c_lflag & ~(ECHO | ICANON);\n if (v.getUint8(ptr + 19)) lflag |= ECHO;\n if (v.getUint8(ptr + 20)) lflag |= ICANON;\n await sys.tcsets?.(fd, { ...termios, c_lflag: lflag });\n }\n};\nfunction posixSignal(sig) {\n const posix = wasixSignal(sig);\n if (posix === void 0) throw new WasiError(\"EINVAL\");\n return posix;\n}\nfunction nsToMs(ns) {\n return Math.ceil(Number(ns) / 1e6);\n}\n\n// src/process/wasi/wasm-names.ts\nfunction parseFunctionNames(payload) {\n const names2 = /* @__PURE__ */ new Map();\n const decoder3 = new TextDecoder();\n let at = 0;\n const leb = () => {\n let value2 = 0;\n let shift = 0;\n let byte;\n do {\n if (at >= payload.length) throw new RangeError(\"truncated name section\");\n byte = payload[at++];\n value2 += (byte & 127) * 2 ** shift;\n shift += 7;\n } while (byte & 128);\n return value2;\n };\n while (at < payload.length) {\n const id = payload[at++];\n const size = leb();\n const end = at + size;\n if (end > payload.length) throw new RangeError(\"truncated name section\");\n if (id === 1) {\n for (let count = leb(); count > 0; count--) {\n const index3 = leb();\n const length = leb();\n if (at + length > end) throw new RangeError(\"truncated name section\");\n names2.set(index3, decoder3.decode(payload.subarray(at, at + length)));\n at += length;\n }\n }\n at = end;\n }\n return names2;\n}\nvar UNNAMED_FRAME = /^(\\s+at )(wasm:\\/\\/wasm\\/([^\\s()]+?):wasm-function\\[(\\d+)\\]:0x[0-9a-f]+)$/;\nvar WASM_MODULE = /wasm:\\/\\/wasm\\/([^\\s()]+?):wasm-function\\[/;\nfunction mainModule(lines) {\n for (let i = lines.length - 1; i >= 0; i--) {\n const m = WASM_MODULE.exec(lines[i]);\n if (!m) continue;\n return lines.slice(i + 1).some((line) => /^\\s+at /.test(line)) ? m[1] : void 0;\n }\n return void 0;\n}\nasync function nameFrame(line, module, name2) {\n const m = UNNAMED_FRAME.exec(line);\n if (!m || m[3] !== module) return line;\n const found = await name2(Number(m[4]));\n return found === void 0 ? line : `${m[1]}${found} (${m[2]})`;\n}\nfunction definedFunctions(bytes) {\n let at = 8;\n const leb = () => {\n let value2 = 0;\n let shift = 0;\n let byte;\n do {\n if (at >= bytes.length) throw new RangeError(\"truncated module\");\n byte = bytes[at++];\n value2 += (byte & 127) * 2 ** shift;\n shift += 7;\n } while (byte & 128);\n return value2;\n };\n while (at < bytes.length) {\n const id = bytes[at++];\n const size = leb();\n if (id === 3) return leb();\n at += size;\n }\n return 0;\n}\nfunction sidecarNames(read2, path, fit) {\n let names2;\n return async (index3) => {\n if (!names2) {\n try {\n names2 = parseFunctionNames(await read2(path));\n } catch {\n names2 = /* @__PURE__ */ new Map();\n }\n let want = names2.size;\n try {\n if (fit) want = await fit.functions();\n } catch {\n fit?.warn(`${path} can't be checked against the module, so the frames show raw indices`);\n names2 = /* @__PURE__ */ new Map();\n return void 0;\n }\n if (fit && names2.size !== want) {\n fit.warn(\n `${path} names ${names2.size} functions, but the module has ${want}: it doesn't fit, so the frames show raw indices`\n );\n names2 = /* @__PURE__ */ new Map();\n }\n }\n return names2.get(index3);\n };\n}\n\n// src/process/wasi/wasi-runtime.ts\nvar TRAPPED = 134;\nvar PREVIEW1 = \"wasi_snapshot_preview1\";\nvar WASIX = \"wasix_32v1\";\nvar SLICC = \"slicc\";\nvar SIGNAL_CALLBACK = \"__wasm_signal\";\nvar takeDefault = (call2, pid) => async (sig) => {\n await call2({ op: \"proc-kill\", pid, sig });\n if (defaultAction(sig) === \"terminate\") throw new WasiExit(128 + sig);\n};\nvar takeThreadDefault = (call2, pid) => async (sig) => {\n if (defaultAction(sig) !== \"terminate\") {\n await call2({ op: \"proc-kill\", pid, sig });\n return;\n }\n try {\n await call2({ op: \"proc-kill-self\", sig });\n } catch {\n }\n throw new WasiExit(128 + sig);\n};\nvar SLICC_FS = \"slicc_fs\";\nvar SLICC_TTY = \"slicc_tty\";\nvar RESERVED2 = RESERVED_NAMESPACES;\nvar UNDELIVERED = {\n [PREVIEW1]: [\"proc_exit\", \"clock_time_get\"],\n [WASIX]: [\"proc_exit2\", \"thread_exit\", \"thread_spawn_v2\", \"callback_signal\"],\n [SLICC]: [\"sigaction_set\", \"siginfo_take\"],\n wasi: [\"thread-spawn\"]\n};\nvar DELIVERED = [PREVIEW1, WASIX, SLICC, SLICC_FS, SLICC_TTY];\nfunction wireSignals(host, gate) {\n host.interrupted = async () => await gate.interrupt();\n host.raisedOnEntry = () => gate.raisedOnEntry();\n host.quietly = async (fn) => await gate.quiet(fn);\n host.deliverDue = async () => void await gate.interrupt();\n host.fds.restartable = () => gate.restartable();\n}\nfunction catchUpFirst(host, sync) {\n return sync && (async () => await host.quietly(() => sync.current()));\n}\nfunction deliverAll(imports, host, driver, before) {\n for (const ns of DELIVERED) {\n const table = imports[ns];\n if (table) imports[ns] = delivering(ns, table, host, driver, before);\n }\n}\nfunction delivering(ns, table, host, driver, before) {\n const exempt = new Set(UNDELIVERED[ns]);\n const out = {};\n for (const [name2, value2] of Object.entries(table)) {\n if (exempt.has(name2) || typeof value2 !== \"function\") {\n out[name2] = value2;\n continue;\n }\n const fn = value2;\n out[name2] = async (...args) => {\n host.entered = false;\n if (driver.idle) {\n await before?.();\n host.entered = await host.interrupted?.() === true;\n host.enteredSignals = host.entered ? host.raisedOnEntry?.() ?? -1 : 0;\n }\n return await fn(...args);\n };\n }\n return out;\n}\nvar importsSlicc = (module, name2) => WebAssembly.Module.imports(module).some((i) => i.module === SLICC && i.name === name2);\nvar importsSigactionHook = (module) => importsSlicc(module, \"sigaction_set\");\nfunction sigmaskOf(module, sab, gate, threads, process, published) {\n const header = new Int32Array(sab, 0, SAB_HEADER_I32);\n if (!importsSlicc(module, \"sigmask_set\")) {\n WasiSigmask.unsupported(header);\n return void 0;\n }\n if (threads) threads.blocked = () => loadBlocked(header);\n const shared = process && new Int32Array(process, 0, SAB_HEADER_I32);\n return new WasiSigmask(header, async () => await gate.deliver(), shared, threads?.tid ?? MAIN_TID, published);\n}\nvar noErrno = (key) => `imports ${key}: its result cannot carry ENOSYS, and this host does not provide it`;\nfunction enosys(module, name2, foreign) {\n const type = foreign?.[module]?.[name2];\n if (type === \"other\") throw new Error(noErrno(`${module}.${name2}`));\n if (type === \"none\") return () => void 0;\n if (type === \"i64\") return () => 52n;\n return () => 52;\n}\nfunction firstOther(foreign) {\n for (const [module, fields] of Object.entries(foreign)) {\n const name2 = Object.keys(fields).find((field2) => fields[field2] === \"other\");\n if (name2 !== void 0) return `${module}.${name2}`;\n }\n return void 0;\n}\nfunction accepted(imp, scope) {\n const { module, name: name2, kind } = imp;\n if (module === PREVIEW1 || module === WASIX) return true;\n if (!RESERVED2.has(module) && (scope.extended || scope.wasi && kind === \"function\")) return true;\n if (scope.pie && (module === \"GOT.mem\" || module === \"GOT.func\")) return true;\n if (scope.pie && module === \"env\" && kind !== \"memory\") return true;\n if (kind === \"memory\" && scope.memory?.module === module && scope.memory.name === name2)\n return true;\n return module === \"wasi\" && name2 === \"thread-spawn\" && (scope.wasix || !!scope.memory?.shared);\n}\nfunction unsupportedImport(module, memory, extended = false, foreign = {}) {\n const imports = WebAssembly.Module.imports(module);\n const wasix = imports.some((i) => i.module === WASIX);\n const wasi = wasix || imports.some((i) => i.module === PREVIEW1);\n const scope = { extended, wasi, wasix, pie: dylinkInfo(module) !== void 0, memory };\n const refused3 = imports.find((imp) => !accepted(imp, scope));\n if (refused3) {\n if (refused3.kind === \"memory\" || refused3.module === \"wasi\") {\n return `imports ${refused3.module}.${refused3.name}: no WASI program this host runs`;\n }\n return `imports ${refused3.module}.${refused3.name}: no WASI preview1 program (an Emscripten one runs with its glue)`;\n }\n const unanswerable = extended ? void 0 : firstOther(foreign);\n if (unanswerable) return noErrno(unanswerable);\n if (!WebAssembly.Module.exports(module).some((e) => e.name === \"_start\")) {\n return \"no WASI command (it exports no _start)\";\n }\n return void 0;\n}\nfunction linkImports(module, preview1, wasix, memory, threads, program = {}, foreign, slicc = {}, sliccFs = {}, sliccTty2 = {}) {\n for (const ns of Object.keys(program)) {\n if (RESERVED2.has(ns) || ns === SLICC || ns === SLICC_FS || ns === SLICC_TTY)\n throw new Error(`the imports module may not define ${ns}`);\n }\n const imports = {\n ...program,\n [SLICC]: { ...slicc },\n [SLICC_FS]: { ...sliccFs },\n [SLICC_TTY]: { ...sliccTty2 },\n [PREVIEW1]: preview1,\n ...wasix ? { [WASIX]: { ...wasix } } : {},\n ...threads ? { wasi: { \"thread-spawn\": async (arg) => await threads.spawn(arg) } } : {}\n };\n for (const imp of WebAssembly.Module.imports(module)) {\n const ns = imports[imp.module] ??= {};\n if (imp.name in ns) continue;\n if (imp.kind === \"memory\" && memory) ns[imp.name] = memory;\n else if (imp.module === \"wasi\" && imp.name === \"thread-spawn\") ns[imp.name] = () => -1;\n else if (imp.kind === \"function\") ns[imp.name] = enosys(imp.module, imp.name, foreign);\n }\n return imports;\n}\nvar FALLBACK_MAXIMUM_PAGES = 32768;\nfunction newImportedMemory(spec) {\n const maximum = spec.maximum ?? 65536;\n try {\n return new WebAssembly.Memory({ initial: spec.initial, maximum, shared: spec.shared });\n } catch (err) {\n if (!(err instanceof RangeError) || maximum <= FALLBACK_MAXIMUM_PAGES) throw err;\n if (spec.initial > FALLBACK_MAXIMUM_PAGES) throw err;\n return new WebAssembly.Memory({\n initial: spec.initial,\n maximum: FALLBACK_MAXIMUM_PAGES,\n shared: spec.shared\n });\n }\n}\nfunction createImportedMemory(spec, copy) {\n if (!spec) return void 0;\n const memory = newImportedMemory(spec);\n if (copy) fillMemory(memory, copy);\n return memory;\n}\nfunction restoreExportedMemory(instance, imported, init) {\n if (imported || !init.fork?.wasi) return;\n fillMemory(instance.exports.memory, init.fork.memory);\n init.fork.memory = new Uint8Array(0);\n}\nfunction fillMemory(memory, copy) {\n const pages2 = copy.byteLength / 65536 - memory.buffer.byteLength / 65536;\n if (pages2 > 0) memory.grow(pages2);\n new Uint8Array(memory.buffer).set(copy);\n}\nfunction sizeOf(main) {\n return () => main.memory?.buffer.byteLength ?? 0;\n}\nfunction memoryOf(instance, imported) {\n return imported ?? instance.exports.memory;\n}\nvar sabTransport = (sab, port, memory) => createSyncSabTransport(sab, port, memory ? { memory } : {});\nfunction kernelOf(init, port, hooks = { masks: () => null, raise: () => {\n} }, memory, transports = sabTransport) {\n const raw = transports(init.sab, port, memory);\n const gate = new SignalGate(raw, new Int32Array(init.sab, 0, SAB_HEADER_I32), hooks);\n const transport = gate.transport();\n const sys = kernelSys(transport);\n const call2 = async (req) => {\n const r = await transport.call(req, Number.POSITIVE_INFINITY, req.op);\n if (!r.ok) throw new SyscallError(r.errno);\n return r.kind === \"json\" ? r.json : r.kind === \"bytes\" ? r.bytes : void 0;\n };\n const say = async (text) => await sys.write(2, new TextEncoder().encode(`${init.argv0}: ${text}\n`));\n const published = raw.publish && (() => raw.publish?.());\n return { transport, sys, call: call2, say, gate, published };\n}\nfunction traced(stats, tag, table) {\n return stats ? stats.wrap(tag, table) : table;\n}\nfunction timedCalls(stats, call2) {\n return async (req) => await stats.time(`kernel.${req.op}`, async () => await call2(req));\n}\nasync function report(stats, sys) {\n stats.phase(\"run\");\n try {\n await sys.write(2, new TextEncoder().encode(stats.report()));\n } catch {\n }\n}\nvar START_STACK = 0;\nvar START_STACK_SIZE = 56;\nfunction isWasix(module) {\n return WebAssembly.Module.imports(module).some((i) => i.module === WASIX);\n}\nvar MIN_THREAD_STACK = 4096;\nvar START_ARGS_SLACK = 64;\nfunction threadStackLow(memory, start2) {\n if (start2 < 0 || start2 + START_ARGS_SLACK > memory.byteLength) return void 0;\n const stack = memory.getUint32(start2 + START_STACK, true);\n const size = memory.getUint32(start2 + START_STACK_SIZE, true);\n if (size < MIN_THREAD_STACK || size > memory.byteLength || size > stack) return void 0;\n if (stack % 16 !== 0 || stack > start2 + START_ARGS_SLACK || stack + START_ARGS_SLACK < start2) {\n return void 0;\n }\n return stack - size;\n}\nfunction ownStack(driver, instance, linked, low) {\n const own = instance.exports.__stack_pointer;\n const pointer = own instanceof WebAssembly.Global ? own : linked;\n if (!pointer) return false;\n driver.useThreadStack(pointer, low);\n return true;\n}\nasync function untilDone(run, driver) {\n do\n await run();\n while (await driver.resume());\n}\nfunction threadStart(instance) {\n return reentered(instance.exports.wasi_thread_start);\n}\nfunction spawnsThreads(module) {\n return WebAssembly.Module.imports(module).some(\n (i) => i.module === \"wasi\" && i.name === \"thread-spawn\" || i.module === WASIX && i.name === \"thread_spawn_v2\"\n );\n}\nasync function instantiate(host, module, memory, threads, {\n thread = false,\n forked,\n stats,\n signals,\n program,\n foreign,\n path\n} = {}) {\n const driver = new AsyncifyDriver(host.mem);\n const wasixHost = WebAssembly.Module.imports(module).some((i) => i.module === WASIX) ? new WasixHost(host, driver, module) : void 0;\n if (wasixHost) {\n wasixHost.threads = threads;\n wasixHost.signals = signals;\n }\n let preview1 = traced(stats, \"wasi\", {\n ...host.imports(),\n ...wasixHost?.preview1()\n });\n let wasix = wasixHost && traced(stats, \"wasix\", wasixHost.imports());\n const info = dylinkInfo(module);\n const sync = info && memory ? new LinkSync(\n new WasixLinker(\n memory,\n info,\n linkerHost(host, () => imports),\n thread\n ),\n async (req) => await host.o.kernel.call(req),\n threads\n ) : void 0;\n if (sync) {\n ({ preview1, wasix } = sync.guard(preview1, wasix));\n if (wasixHost) {\n wasixHost.linker = sync.linker;\n wasixHost.types = sync.linker.types;\n }\n if (threads) {\n sync.linker.cache = threads.received;\n threads.modules = () => sync.linker.compiled();\n }\n }\n let instance;\n const extra = await program?.(\n () => memory ?? instance?.exports.memory,\n () => instance\n );\n const slicc = traced(stats, \"slicc\", host.sliccImports());\n const sliccFs = traced(stats, \"slicc_fs\", host.sliccFsImports());\n const sliccTty2 = traced(stats, \"slicc_tty\", host.sliccTtyImports());\n const hostImports = linkImports(\n module,\n preview1,\n wasix,\n memory,\n threads,\n extra,\n foreign,\n slicc,\n sliccFs,\n sliccTty2\n );\n deliverAll(hostImports, host, driver, catchUpFirst(host, sync));\n const imports = sync ? merge(hostImports, sync.linker.mainImports(module)) : hostImports;\n instance = await WebAssembly.instantiate(module, suspendingImports(imports));\n stats?.phase(\"instantiate\");\n const exports = instance.exports;\n host.mem.bind(memory ?? exports.memory);\n if (wasixHost) {\n const table = sync?.linker.table ?? exportedTable(instance);\n wasixHost.table = table;\n if (path !== void 0) {\n const read2 = linkerHost(host, () => ({})).read;\n wasixHost.types.register(async () => await read2(path), instance, table, sync ? TABLE_BASE2 : 0);\n }\n }\n if (sync) await bindLinker(host, sync, instance, { thread, forked, path });\n if (sync && !thread) driver.useStack(sync.linker.stackPointer, sync.linker.stackLow);\n return { instance, driver, linkedStack: sync?.linker.stackPointer };\n}\nasync function bindLinker(host, sync, instance, at) {\n await sync.linker.bindMain(instance, !at.thread && !at.forked);\n if (at.path !== void 0) sync.linker.mainPath = at.path;\n host.linkedTls = () => sync.linker.tlsBases();\n host.linkedModules = () => sync.linker.compiled();\n if (at.forked) {\n sync.linker.forkedTls = new Map(at.forked.tls ?? []);\n sync.linker.cache = at.forked.modules;\n }\n if (at.thread || at.forked) await sync.catchUp();\n await sync.linker.bindMainGot();\n}\nfunction procTree(call2, pid) {\n return new ProcTree(\n {\n procList: async () => await call2({ op: \"proc-list\" }),\n mountList: async () => await call2({ op: \"mount-list\" })\n },\n pid\n );\n}\nfunction devNodes(call2) {\n return async () => await call2({ op: \"fd-dev-nodes\" });\n}\nfunction exportedTable(instance) {\n const table = instance.exports.__indirect_function_table;\n return table instanceof WebAssembly.Table ? table : void 0;\n}\nfunction linkerHost(host, imports) {\n return {\n read: async (path) => {\n try {\n return await host.o.fs.readFile(path);\n } catch {\n return void 0;\n }\n },\n hostImports: () => {\n const { env: _env, \"GOT.mem\": _mem, \"GOT.func\": _func, ...rest2 } = imports();\n return rest2;\n },\n real: async (path) => await physicalPath(host.o.fs, path)\n };\n}\nfunction merge(base, extra) {\n const out = { ...base };\n for (const [ns, values] of Object.entries(extra)) out[ns] = { ...base[ns], ...values };\n return out;\n}\nvar LinkSync = class {\n count = 0;\n gen = 0;\n linker;\n call;\n ids;\n owner;\n constructor(linker, call2, threads) {\n this.linker = linker;\n this.call = call2;\n this.ids = threads?.ids;\n this.owner = threads?.tid ?? 0;\n linker.publisher = async (record) => await this.publish(record);\n linker.indices = {\n reserve: async (floor, size) => await this.call({ op: \"dl-reserve\", floor, size }),\n load: async (floor, size) => await this.call({ op: \"dl-load-reserve\", floor, size }),\n lock: async () => {\n await this.call({ op: \"dl-lock\", owner: this.owner });\n try {\n await this.catchUp();\n } catch (e) {\n await this.call({ op: \"dl-unlock\", owner: this.owner });\n throw e;\n }\n },\n unlock: async () => await this.call({ op: \"dl-unlock\", owner: this.owner }),\n allocate: async (floor) => {\n const index3 = await this.call({ op: \"dl-closure\", floor });\n await this.catchUp();\n this.bump();\n return index3;\n },\n free: async (index3) => {\n await this.call({ op: \"dl-closure-free\", index: index3 });\n this.bump();\n }\n };\n }\n bump() {\n if (this.ids) Atomics.add(this.ids, DL_GEN, 1);\n }\n async publish(record) {\n const since = await this.call({ op: \"dl-log\", append: record, from: this.count });\n for (const r of since.slice(0, -1)) await this.linker.replay(r);\n this.count += since.length;\n this.bump();\n await this.catchUp();\n }\n async current() {\n if (this.ids && Atomics.load(this.ids, DL_GEN) !== this.gen) await this.catchUp();\n }\n async catchUp() {\n for (; ; ) {\n const gen = this.ids ? Atomics.load(this.ids, DL_GEN) : 0;\n const since = await this.call({ op: \"dl-log\", from: this.count });\n for (const r of since) await this.linker.replay(r);\n this.count += since.length;\n if (!this.ids || Atomics.load(this.ids, DL_GEN) === gen) {\n this.gen = gen;\n return;\n }\n }\n }\n guard(preview1, wasix) {\n const ids = this.ids;\n if (!ids) return { preview1, wasix };\n const wrap2 = (table) => Object.fromEntries(\n Object.entries(table).map(([name2, fn]) => [\n name2,\n (async (...args) => {\n await this.current();\n const result = await fn(...args);\n await this.current();\n return result;\n })\n ])\n );\n return { preview1: wrap2(preview1), wasix: wasix && wrap2(wasix) };\n }\n};\nvar DL_GEN = 3;\nfunction descriptors(init, fork, threads) {\n if (fork?.shared && threads) return { shared: threads.ids };\n if (fork) return { forked: { fds: fork.fds, cloexec: fork.cloexec } };\n return { inherited: init.fds ?? [], ...init.program.preopenRoot ? { preopenRoot: true } : {} };\n}\nfunction ownersOf(init) {\n return {\n ...init.owners ? { owners: true } : {},\n ...init.links ? { links: true } : {},\n ...init.changes ? { changes: init.changes } : {}\n };\n}\nfunction heldOf(init, call2) {\n const { held } = init;\n if (!held) return {};\n const ask = async () => await call2({ op: \"cwd-check\" });\n return { held: new HeldCwd(held.sab, held.slot, ask, { ...held, path: init.cwd }) };\n}\nfunction mainThreads(port, module, memory, cap) {\n return memory?.buffer instanceof SharedArrayBuffer && spawnsThreads(module) ? new WasiThreads(port, memory, cap, MAIN_TID) : void 0;\n}\nasync function runWasiProcess(init, port, given = {}) {\n captureBacktraces(init.env);\n const signals = new WasiSignals(\n takeDefault(async (req) => await call2(req), init.pid),\n (code2) => {\n throw new WasiExit(code2);\n }\n );\n const main = {};\n const {\n transport,\n sys,\n call: kernelCall,\n say,\n gate,\n published\n } = kernelOf(init, port, signals, sizeOf(main), given.transport);\n const id = await identify(transport, init);\n const stats = init.env.SLICC_WASI_STATS === \"1\" ? new WasiStats() : void 0;\n const call2 = stats ? timedCalls(stats, kernelCall) : kernelCall;\n const { module } = init.program;\n const refused3 = unsupportedImport(\n module,\n init.program.memory,\n init.program.imports !== void 0,\n init.program.foreign\n );\n if (refused3) {\n await say(refused3);\n return 126;\n }\n const fork = init.fork?.wasi;\n const memory = createImportedMemory(init.program.memory, fork ? init.fork?.memory : void 0);\n const threads = mainThreads(port, module, memory, given.threadCap ?? threadCap(init.env));\n const host = await new WasiHost({\n args: [init.argv0, ...init.args],\n env: init.env,\n cwd: fork?.cwd ?? init.cwd,\n pid: id.pid,\n ppid: id.ppid,\n parent: async () => (await identify(transport, init)).ppid,\n kernel: { sys: traced(stats, \"kernel\", sys), call: call2 },\n fs: ptsBridge(\n sysfsBridge(\n procfsBridge(\n cachingBridge(\n traced(\n stats,\n \"fs\",\n createSyncFsSabBridge(transport, { ...ownersOf(init), direct: true })\n ),\n void 0,\n threads?.ids\n ),\n procTree(call2, id.pid)\n ),\n devNodes(call2)\n ),\n call2\n ),\n ...descriptors(init, fork, threads),\n ...heldOf(init, call2),\n ...threads ? { credGen: threads.ids } : {}\n }).attach();\n if (given.futexes) host.futexes = given.futexes;\n host.sigmask = sigmaskOf(module, init.sab, gate, threads, void 0, published);\n if (threads) {\n threads.beforeSpawn = async () => {\n if (!host.fds.isShared) await host.fds.share(threads.ids, false);\n };\n }\n const program = await programImports(init.program, host, transport, MAIN_TID, given.imports);\n const { instance, driver, linkedStack } = await instantiate(host, module, memory, threads, {\n ...fork ? { forked: fork } : {},\n stats,\n signals,\n foreign: init.program.foreign,\n path: init.program.path,\n ...program ? { program } : {}\n });\n restoreExportedMemory(instance, memory, init);\n main.memory = memoryOf(instance, memory);\n publishMemory(init.sab, sizeOf(main)());\n port.postMessage({ type: WASM_PROCESS_READY });\n signals.bind(instance.exports);\n if (importsSigactionHook(module)) signals.useHook();\n if (fork?.signals) signals.restore(fork.signals);\n host.signals = signals;\n wireSignals(host, gate);\n host.onRaise = async (sig) => await signals.raised(sig);\n host.muted = (fd, data) => signals.muted(fd, data);\n const exports = instance.exports;\n driver.bind(instance.exports);\n const entry = fork?.entry;\n if (entry) {\n ownStack(driver, instance, linkedStack, entry.low);\n host.threadEntry = entry;\n }\n const run = entry ? async () => await threadStart(instance)(entry.tid, entry.arg) : async () => await reentered(exports._start)();\n try {\n if (fork) driver.startChild(fork);\n await untilDone(run, driver);\n return 0;\n } catch (e) {\n if (e instanceof WasiExit) return e.code;\n if (!(e instanceof WebAssembly.RuntimeError)) throw e;\n try {\n await say(await trapReport(e, init, host, \"\"));\n } catch {\n throw new Error(`${init.argv0}: wasm trap: ${e.message}`);\n }\n return TRAPPED;\n } finally {\n await host.flushAll();\n if (stats) await report(stats, sys);\n }\n}\nvar BACKTRACE_FRAMES = 40;\nasync function trapMessage(e, env, where = \"\", name2) {\n const head = `wasm trap${where}: ${e.message}`;\n if (env.SLICC_WASM_BACKTRACE !== \"1\") return head;\n const lines = (rawStack(e) ?? \"\").split(\"\\n\");\n const main = name2 && mainModule(lines);\n const frames = [];\n const shown = lines.filter((line) => /^\\s+at .*wasm:\\/\\/wasm\\//.test(line)).slice(0, BACKTRACE_FRAMES);\n for (const line of shown) frames.push(name2 && main ? await nameFrame(line, main, name2) : line);\n return frames.length ? `${head}\n${frames.join(\"\\n\")}` : head;\n}\nasync function trapReport(e, init, host, where) {\n const warned = [];\n const message = await trapMessage(e, init.env, where, programNames(host, init.program, warned));\n return [...warned, message].join(`\n${init.argv0}: `);\n}\nfunction programNames(host, program, warned) {\n const path = program.names;\n if (path === void 0) return void 0;\n const read2 = async (p) => await host.o.fs.readFile(p);\n const imported = WebAssembly.Module.imports(program.module).filter((i) => i.kind === \"function\");\n return sidecarNames(read2, path, {\n functions: async () => imported.length + definedFunctions(await read2(program.path)),\n warn: (line) => warned.push(line)\n });\n}\nasync function programImports(program, host, transport, tid, given) {\n if (program.imports === void 0) return void 0;\n const create = given ?? await loadImports(program.imports);\n const raw = async (req) => await transport.call(req, Number.POSITIVE_INFINITY, req.op);\n return async (memory, instance) => await create(importsContext({ host, raw, tid, memory, instance }));\n}\nfunction captureBacktraces(env) {\n if (env.SLICC_WASM_BACKTRACE !== \"1\") return;\n const v8 = Error;\n v8.stackTraceLimit = Math.max(v8.stackTraceLimit ?? 0, BACKTRACE_FRAMES + 20);\n}\nasync function runWasiThread(init, port, given = {}) {\n captureBacktraces(init.env);\n const { thread } = init;\n const kernelFor = (hooks) => kernelOf(init, port, hooks, void 0, given.transport);\n const { transport, sys, call: call2, say, gate, published } = kernelFor({\n masks: () => null,\n raise: async (sig) => await signals.raise(sig)\n });\n const signals = new WasiSignals(takeThreadDefault(call2, init.pid));\n const cap = given.threadCap ?? threadCap(init.env);\n const threads = new WasiThreads(port, thread.memory, cap, thread.tid, thread.ids);\n threads.received = thread.modules;\n const id = await identify(transport, init);\n const host = await new WasiHost({\n args: [init.argv0, ...init.args],\n env: init.env,\n cwd: init.cwd,\n pid: id.pid,\n ppid: id.ppid,\n parent: async () => (await identify(transport, init)).ppid,\n kernel: { sys, call: call2 },\n fs: ptsBridge(\n sysfsBridge(\n procfsBridge(\n cachingBridge(\n createSyncFsSabBridge(transport, { ...ownersOf(init), direct: true }),\n void 0,\n threads.ids\n ),\n procTree(call2, id.pid)\n ),\n devNodes(call2)\n ),\n call2\n ),\n shared: threads.ids,\n ...heldOf(init, call2)\n }).attach();\n host.tid = thread.tid;\n if (given.futexes) host.futexes = given.futexes;\n host.sigmask = sigmaskOf(init.program.module, init.sab, gate, threads, init.signals, published);\n const program = await programImports(init.program, host, transport, thread.tid, given.imports);\n const { module } = init.program;\n const { memory } = thread;\n const { instance, driver, linkedStack } = await instantiate(host, module, memory, threads, {\n thread: true,\n foreign: init.program.foreign,\n path: init.program.path,\n ...program ? { program } : {}\n });\n signals.bind(instance.exports);\n signals.register(SIGNAL_CALLBACK);\n wireSignals(host, gate);\n host.onRaise = async (sig) => await signals.raised(sig);\n const low = isWasix(module) ? threadStackLow(host.mem.view(), thread.arg) : void 0;\n if (low !== void 0 && ownStack(driver, instance, linkedStack, low)) {\n driver.bind(instance.exports);\n host.threadEntry = { tid: thread.tid, arg: thread.arg, low };\n }\n const start2 = threadStart(instance);\n try {\n await untilDone(async () => await start2(thread.tid, thread.arg), driver);\n threads.exited();\n } catch (e) {\n if (e instanceof ThreadExit) {\n threads.exited();\n return;\n }\n if (e instanceof WasiExit) {\n port.postMessage({ type: WASM_PROCESS_EXIT, code: e.code });\n return;\n }\n if (e instanceof WebAssembly.RuntimeError) {\n try {\n await say(await trapReport(e, init, host, ` in thread ${thread.tid}`));\n } catch {\n }\n port.postMessage({ type: WASM_PROCESS_EXIT, code: TRAPPED });\n return;\n }\n throw e;\n }\n}\n\n// src/process/emscripten/errno.ts\nvar EM = {\n AGAIN: 6,\n BADF: 8,\n BUSY: 10,\n CHILD: 12,\n EXIST: 20,\n FAULT: 21,\n INTR: 27,\n INVAL: 28,\n IO: 29,\n ISDIR: 31,\n LOOP: 32,\n MLINK: 34,\n NAMETOOLONG: 37,\n NOENT: 44,\n NOMEM: 48,\n NOSYS: 52,\n NOTDIR: 54,\n NOTEMPTY: 55,\n NOTSOCK: 57,\n NOTTY: 59,\n NXIO: 60,\n OVERFLOW: 61,\n PERM: 63,\n PIPE: 64,\n RANGE: 68,\n SPIPE: 70,\n XDEV: 75,\n NOTSUP: 138\n};\nvar EmError = class extends Error {\n errno;\n constructor(errno) {\n super(`errno ${errno}`);\n this.errno = errno;\n }\n};\nfunction errnoOf(e) {\n if (e instanceof EmError) return e.errno;\n const code2 = e?.code;\n if (typeof code2 === \"string\") return wasiErrno(code2);\n if (e instanceof RangeError) return EM.FAULT;\n return void 0;\n}\nfunction negated(fn) {\n return async (...args) => {\n try {\n return Number(await fn(...args) ?? 0);\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n };\n}\nfunction positive(fn) {\n return async (...args) => {\n try {\n return Number(await fn(...args) ?? 0);\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return errno;\n }\n };\n}\n\n// src/process/emscripten/cwd.ts\nvar AT_FDCWD2 = -100;\nvar X_OK2 = 1;\nvar EmCwd = class {\n path;\n held;\n host;\n call;\n constructor(host, path, call2, held) {\n this.host = host;\n this.path = path;\n this.call = call2;\n if (held) {\n const ask = async () => await call2({ op: \"cwd-check\" });\n this.held = new HeldCwd(held.sab, held.slot, ask, { ...held, path });\n }\n }\n async gone() {\n return this.held !== void 0 && !await this.held.alive(this.path);\n }\n async base(dirfd) {\n if (dirfd === AT_FDCWD2) return this.path;\n const e = await this.host.fds.get(dirfd);\n if (e.type === \"dir\") return e.path;\n if (e.type === \"file\") return e.file.path;\n throw new EmError(EM.NOTDIR);\n }\n async resolve(dirfd, raw, allowEmpty = false) {\n if (raw === \"\") {\n if (!allowEmpty) throw new EmError(EM.NOENT);\n return await this.base(dirfd);\n }\n if (raw.startsWith(\"/\")) return await this.host.fds.resolve(0, raw);\n const relativeHere = raw.split(\"/\")[0] !== \"..\";\n if (dirfd === AT_FDCWD2 && relativeHere && await this.gone()) throw new EmError(EM.NOENT);\n const base = await this.base(dirfd);\n return await this.host.fds.resolve(0, `${base === \"/\" ? \"\" : base}/${raw}`);\n }\n async chdir(abs) {\n const fs = this.host.o.fs;\n const real = await physicalPath(fs, abs);\n const st = await fs.stat(real);\n if (!st.isDirectory) throw new EmError(EM.NOTDIR);\n if (fs.owners) await fs.access?.(real, X_OK2, \"eaccess\", false);\n this.path = real;\n if (this.held) {\n const reply = await this.call({ op: \"cwd-chdir\", path: real });\n this.held.moved(reply, real);\n }\n }\n};\n\n// src/process/emscripten/dns.ts\nvar htons = (v) => (v & 255) << 8 | v >> 8 & 255;\nvar htonl = (v) => ((v & 255) << 24 | (v & 65280) << 8 | v >>> 8 & 65280 | v >>> 24 & 255) >>> 0;\nfunction pton4(str) {\n const b = str.split(\".\");\n const n = [];\n for (let i = 0; i < 4; i++) {\n const tmp = Number(b[i]);\n if (Number.isNaN(tmp)) return null;\n n.push(tmp);\n }\n return (n[0] | n[1] << 8 | n[2] << 16 | n[3] << 24) >>> 0;\n}\nvar VALID6 = /^((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|$))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})$/i;\nfunction pton6(input) {\n if (!VALID6.test(input)) return null;\n if (input === \"::\") return [0, 0, 0, 0, 0, 0, 0, 0];\n let str = input.startsWith(\"::\") ? input.replace(\"::\", \"Z:\") : input.replace(\"::\", \":Z:\");\n let words;\n if (str.indexOf(\".\") > 0) {\n str = str.replace(/[.]/g, \":\");\n words = str.split(\":\");\n const n = words.length;\n words[n - 4] = Number(words[n - 4]) + Number(words[n - 3]) * 256;\n words[n - 3] = Number(words[n - 2]) + Number(words[n - 1]) * 256;\n words = words.slice(0, n - 2);\n } else {\n words = str.split(\":\");\n }\n const parts = [];\n let offset = 0;\n for (let w = 0; w < words.length; w++) {\n const word = words[w];\n if (typeof word === \"string\") {\n if (word === \"Z\") {\n let z = 0;\n for (z = 0; z < 8 - words.length + 1; z++) parts[w + z] = 0;\n offset = z - 1;\n } else {\n parts[w + offset] = htons(Number.parseInt(word, 16));\n }\n } else {\n parts[w + offset] = word;\n }\n }\n const p = (i) => parts[i] ?? 0;\n return [p(1) << 16 | p(0), p(3) << 16 | p(2), p(5) << 16 | p(4), p(7) << 16 | p(6)];\n}\nvar names = /* @__PURE__ */ new Map();\nvar nextId = 1;\nfunction lookupName(name2) {\n if (pton4(name2) !== null || pton6(name2) !== null) return name2;\n const known = names.get(name2);\n if (known) return known;\n const id = nextId++;\n const addr = `172.29.${id & 255}.${id & 65280}`;\n names.set(name2, addr);\n return addr;\n}\nfunction writeSockaddr(ctx, sa, family, addr, port) {\n const v = ctx.mem.view();\n if (family === 2) {\n ctx.mem.bytes(sa, 16).fill(0);\n v.setInt16(sa, family, true);\n v.setInt32(sa + 4, addr, true);\n v.setInt16(sa + 2, htons(port), true);\n return;\n }\n const a = addr;\n ctx.mem.bytes(sa, 28).fill(0);\n v.setInt32(sa, family, true);\n for (let i = 0; i < 4; i++) v.setInt32(sa + 8 + i * 4, a[i] ?? 0, true);\n v.setInt16(sa + 2, htons(port), true);\n}\nfunction allocInfo(ctx, ai) {\n const malloc = ctx.exports().malloc;\n const salen = ai.family === 10 ? 28 : 16;\n const sa = malloc(salen);\n writeSockaddr(ctx, sa, ai.family, ai.addr, ai.port);\n const out = malloc(32);\n const v = ctx.mem.view();\n v.setInt32(out + 4, ai.family, true);\n v.setInt32(out + 8, ai.type, true);\n v.setInt32(out + 12, ai.proto, true);\n v.setUint32(out + 24, ai.canon >>> 0, true);\n v.setUint32(out + 20, sa, true);\n v.setInt32(out + 16, salen, true);\n v.setInt32(out + 28, 0, true);\n return out;\n}\nfunction hintsOf(ctx, hint) {\n const v = ctx.mem.view();\n const h = hint ? {\n flags: v.getInt32(hint, true),\n family: v.getInt32(hint + 4, true),\n type: v.getInt32(hint + 8, true),\n proto: v.getInt32(hint + 12, true)\n } : { flags: 0, family: 0, type: 0, proto: 0 };\n if (h.type && !h.proto) h.proto = h.type === 2 ? 17 : 6;\n if (!h.type && h.proto) h.type = h.proto === 17 ? 2 : 1;\n if (h.proto === 0) h.proto = 6;\n if (h.type === 0) h.type = 1;\n return h;\n}\nfunction refused2(h, node, service) {\n if (!node && !service) return -2;\n if (h.flags & ~(1 | 2 | 4 | 1024 | 8 | 16 | 32)) return -1;\n if (h.flags & 2 && !node) return -1;\n if (h.flags & 32) return -2;\n if (h.type !== 0 && h.type !== 1 && h.type !== 2) return -7;\n if (h.family !== 0 && h.family !== 2 && h.family !== 10) return -6;\n return 0;\n}\nfunction numeric(h, node) {\n const four = pton4(node);\n if (four !== null) {\n if (h.family === 0 || h.family === 2) {\n h.family = 2;\n return four;\n }\n if (h.family === 10 && h.flags & 8) return [0, 0, htonl(65535), four];\n return void 0;\n }\n const six = pton6(node);\n if (six === null) return null;\n if (h.family !== 0 && h.family !== 10) return void 0;\n h.family = 10;\n return six;\n}\nfunction getaddrinfo(ctx, nodePtr, servicePtr, hint, out) {\n const h = hintsOf(ctx, hint);\n const bad = refused2(h, nodePtr, servicePtr);\n if (bad !== 0) return bad;\n let port = 0;\n if (servicePtr) {\n port = Number.parseInt(ctx.mem.cString(servicePtr), 10);\n if (Number.isNaN(port)) return h.flags & 1024 ? -2 : -8;\n }\n const put = (canon, addr2) => {\n const ai = allocInfo(ctx, {\n family: h.family,\n type: h.type,\n proto: h.proto,\n canon,\n addr: addr2,\n port\n });\n ctx.mem.view().setUint32(out, ai, true);\n return 0;\n };\n if (!nodePtr) {\n if (h.family === 0) h.family = 2;\n if (h.flags & 1) return put(0, 0);\n return put(0, h.family === 2 ? htonl(2130706433) : [0, 0, 0, htonl(1)]);\n }\n const node = ctx.mem.cString(nodePtr);\n const addr = numeric(h, node);\n if (addr === void 0) return -2;\n if (addr !== null) return put(Number(node) >>> 0, addr);\n if (h.flags & 4) return -2;\n const fake = pton4(lookupName(node));\n if (h.family === 0) h.family = 2;\n return put(0, h.family === 10 ? [0, 0, htonl(65535), fake] : fake);\n}\nfunction dnsImports(ctx) {\n return {\n getaddrinfo: (node, service, hint, out) => getaddrinfo(ctx, node, service, hint, out),\n _emscripten_lookup_name: (name2) => pton4(lookupName(ctx.mem.cString(name2)))\n };\n}\n\n// src/process/emscripten/layout.ts\nvar S_IFMT2 = 61440;\nvar S_IFSOCK = 49152;\nvar S_IFLNK2 = 40960;\nvar S_IFREG = 32768;\nvar S_IFDIR = 16384;\nvar S_IFCHR = 8192;\nvar S_IFIFO2 = 4096;\nfunction putTime(v, at, ms) {\n v.setBigInt64(at, BigInt(Math.floor(ms / 1e3)), true);\n v.setUint32(at + 8, Math.round(ms % 1e3 * 1e3 * 1e3) >>> 0, true);\n}\nfunction writeStat(mem, buf, st) {\n const v = mem.view();\n v.setUint32(buf, st.dev >>> 0, true);\n v.setUint32(buf + 4, st.mode >>> 0, true);\n v.setUint32(buf + 8, st.nlink >>> 0, true);\n v.setUint32(buf + 12, st.uid >>> 0, true);\n v.setUint32(buf + 16, st.gid >>> 0, true);\n v.setUint32(buf + 20, st.rdev >>> 0, true);\n v.setBigInt64(buf + 24, BigInt(st.size), true);\n v.setInt32(buf + 32, 4096, true);\n v.setInt32(buf + 36, st.blocks, true);\n putTime(v, buf + 40, st.atimeMs);\n putTime(v, buf + 56, st.mtimeMs);\n putTime(v, buf + 72, st.ctimeMs);\n v.setBigInt64(buf + 88, BigInt(st.ino), true);\n}\nfunction writeStatfs(mem, buf, s) {\n const v = mem.view();\n v.setUint32(buf + 4, s.bsize, true);\n v.setUint32(buf + 60, s.bsize, true);\n v.setBigInt64(buf + 8, BigInt(s.blocks), true);\n v.setBigInt64(buf + 16, BigInt(s.bfree), true);\n v.setBigInt64(buf + 24, BigInt(s.bavail), true);\n v.setBigInt64(buf + 32, BigInt(s.files), true);\n v.setBigInt64(buf + 40, BigInt(s.ffree), true);\n v.setUint32(buf + 48, s.fsid, true);\n v.setUint32(buf + 64, s.flags, true);\n v.setUint32(buf + 56, s.namelen, true);\n}\nvar DIRENT_SIZE = 280;\nvar encoder3 = new TextEncoder();\nfunction writeDirent(mem, at, ino, next2, type, name2) {\n const v = mem.view();\n v.setBigInt64(at, BigInt(ino), true);\n v.setBigInt64(at + 8, BigInt(next2), true);\n v.setUint16(at + 16, DIRENT_SIZE, true);\n v.setUint8(at + 18, type);\n putString(mem, at + 19, name2, 256);\n}\nfunction putString(mem, at, text, max) {\n if (max <= 0) return 0;\n const bytes = encoder3.encode(text);\n let n = Math.min(bytes.length, max - 1);\n while (n > 0 && n < bytes.length && (bytes[n] & 192) === 128) n--;\n const out = mem.bytes(at, n + 1);\n out.set(bytes.subarray(0, n));\n out[n] = 0;\n return n;\n}\n\n// src/process/emscripten/files.ts\nvar O_ACCMODE = 3;\nvar O_WRONLY3 = 1;\nvar O_RDWR3 = 2;\nvar O_CREAT = 64;\nvar O_EXCL = 128;\nvar O_TRUNC = 512;\nvar O_APPEND3 = 1024;\nvar O_NONBLOCK3 = 2048;\nvar O_DIRECTORY = 65536;\nvar O_NOFOLLOW = 131072;\nvar O_CLOEXEC2 = 524288;\nvar O_PATH = 2097152;\nvar AT_SYMLINK_NOFOLLOW2 = 256;\nvar AT_REMOVEDIR = 512;\nvar AT_SYMLINK_FOLLOW = 1024;\nvar AT_EACCESS2 = 512;\nvar AT_EMPTY_PATH = 4096;\nvar UTIME_NOW = 1073741823;\nvar UTIME_OMIT = 1073741822;\nvar FD_ALIAS2 = /^\\/(?:dev\\/(stdin|stdout|stderr)|dev\\/fd\\/(\\d+)|proc\\/(self|[1-9]\\d*)\\/fd\\/(\\d+))$/;\nvar STDIO3 = { stdin: 0, stdout: 1, stderr: 2 };\nvar DT_CHR = 2;\nvar DT_DIR = 4;\nvar DT_REG = 8;\nvar DT_LNK = 10;\nvar encoder4 = new TextEncoder();\nfunction fdAlias(ctx, path) {\n const m = FD_ALIAS2.exec(path);\n if (!m) return void 0;\n if (m[1]) return STDIO3[m[1]];\n if (m[3] !== void 0 && m[3] !== \"self\" && Number(m[3]) !== ctx.pid) return void 0;\n return Number(m[2] ?? m[4]);\n}\nasync function credOf(ctx) {\n return await ctx.call({ op: \"proc-cred\" });\n}\nfunction typeOf(st) {\n if (st.isSymbolicLink) return S_IFLNK2;\n if (st.isDirectory) return S_IFDIR;\n if (st.isSocket) return S_IFSOCK;\n if (st.isFifo) return S_IFIFO2;\n if (st.isFile) return S_IFREG;\n const own = (st.mode ?? 0) & S_IFMT2;\n return own || S_IFREG;\n}\nvar RDEV = {\n \"/dev/null\": 259,\n \"/dev/zero\": 261,\n \"/dev/full\": 263,\n \"/dev/random\": 16384,\n \"/dev/urandom\": 16640,\n \"/dev/tty\": 1280,\n \"/dev/ptmx\": 1282,\n \"/dev/sealed\": 2810,\n \"/dev/clipboard\": 2811,\n \"/dev/embedder\": 2812\n};\nvar PTS2 = /^\\/dev\\/pts\\/(\\d+)$/;\nfunction rdevOf(path) {\n const n = PTS2.exec(path)?.[1];\n if (n === void 0) return RDEV[path] ?? 0;\n const minor = Number(n);\n return (minor & 1048320) << 12 | 136 << 8 | minor & 255;\n}\nasync function emStat(ctx, path, st, size) {\n const owners = ctx.host.o.fs.owners === true;\n const type = typeOf(st);\n const fallback = type === S_IFDIR || type === S_IFLNK2 ? 511 : 438;\n const perm = (st.mode ?? fallback) & 4095;\n const mode = type | (owners ? perm : perm || fallback);\n const bytes = type === S_IFDIR ? 4096 : size ?? st.size;\n const mtimeMs = st.mtimeMs ?? 0;\n let uid = owners ? st.uid ?? 0 : 0;\n let gid = owners ? st.gid ?? 0 : 0;\n if (!ctx.init.owners && !ctx.credAbi) {\n uid = 1e3;\n gid = 1e3;\n } else if (!ctx.init.owners) {\n const cred = await credOf(ctx);\n uid = cred.euid;\n gid = cred.egid;\n }\n return {\n dev: st.dev ?? 1,\n ino: st.ino ?? inodeOf(path),\n mode,\n nlink: st.nlink ?? 1,\n uid,\n gid,\n rdev: type === S_IFCHR ? rdevOf(path) : 0,\n size: bytes,\n atimeMs: st.atimeMs ?? mtimeMs,\n mtimeMs,\n ctimeMs: st.ctimeMs ?? mtimeMs,\n blocks: Math.ceil(bytes / 4096) * 8\n };\n}\nfunction devKernel(ctx) {\n return { json: async (req) => await ctx.call(req) };\n}\nvar PTMX = \"/dev/ptmx\";\nfunction ptmxStat() {\n return {\n isFile: false,\n isDirectory: false,\n size: 0,\n mode: S_IFCHR | 438,\n mtimeMs: Date.now(),\n uid: 0,\n gid: 0\n };\n}\nasync function bridgeStat(ctx, path, follow2) {\n const fs = ctx.host.o.fs;\n if (path === PTMX && ctx.sys.openPty) return ptmxStat();\n if (inDev(path)) {\n try {\n return await devSync(devKernel(ctx), devStat(path, follow2));\n } catch (err) {\n if (err.code !== \"ENOENT\") throw err;\n }\n }\n await ctx.host.fds.flushPath(path);\n try {\n return follow2 ? await fs.stat(path) : await fs.lstat(path);\n } catch (err) {\n const real = follow2 && missing2(err) ? await devTarget(ctx, path) : void 0;\n if (real === void 0) throw err;\n return await bridgeStat(ctx, real, true);\n }\n}\nasync function devTarget(ctx, path) {\n let real;\n try {\n real = await physicalPath(ctx.host.o.fs, path);\n } catch {\n return void 0;\n }\n return real !== path && inDev(real) ? real : void 0;\n}\nfunction linkStat2(target) {\n return {\n isFile: false,\n isDirectory: false,\n isSymbolicLink: true,\n size: encoder4.encode(target).length,\n mode: S_IFLNK2 | 511,\n mtimeMs: Date.now()\n };\n}\nasync function fdTarget2(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") return e.file.path;\n if (e.type === \"dir\") return e.path;\n if (e.type === \"device\") return `/dev/${e.device}`;\n if (await ctx.host.fds.kind(fd, e) === \"stream\") {\n const info = await ctx.call({ op: \"fd-info\", fd });\n if (info.fifo !== void 0) return info.fifo;\n }\n const target = await devSync(devKernel(ctx), devResolveTarget(`/dev/fd/${fd}`));\n return target ?? `pipe:[${fd}]`;\n}\nasync function pathStat2(ctx, path, follow2) {\n const alias = fdAlias(ctx, path);\n if (alias !== void 0) {\n if (follow2) return await fdStat2(ctx, alias);\n const target = /^\\/dev\\/std/.test(path) ? \"\" : await fdTarget2(ctx, alias);\n if (/^\\/dev\\/std/.test(path)) return await emStat(ctx, path, linkStat2(`/proc/self/fd/${alias}`));\n return await emStat(ctx, path, { ...linkStat2(target), size: 0, mode: S_IFLNK2 | 448 });\n }\n if (procFdDir(ctx, path)) {\n return await emStat(ctx, path, {\n isFile: false,\n isDirectory: true,\n size: 0,\n mode: S_IFDIR | 365,\n mtimeMs: Date.now()\n });\n }\n return await emStat(ctx, path, await bridgeStat(ctx, path, follow2));\n}\nasync function kernelFdStat(ctx, fd, kind) {\n if (kind === \"file\") {\n const st = await ctx.call({ op: \"fd-vfs-stat\", fd, full: true });\n const path = st.path ?? `/proc/self/fd/${fd}`;\n const base = st.stat ?? { isFile: true, isDirectory: false, size: st.size };\n return await emStat(ctx, path, base, st.size);\n }\n if (kind === \"tty\" || kind === \"device\") {\n return await emStat(ctx, await fdTarget2(ctx, fd), await devSync(devKernel(ctx), devFdStat(fd)));\n }\n const type = kind === \"socket\" ? S_IFSOCK : kind === \"stream\" ? S_IFIFO2 : S_IFCHR;\n const now = Date.now();\n return await emStat(ctx, `pipe:${fd}`, {\n isFile: false,\n isDirectory: false,\n ...type === S_IFSOCK ? { isSocket: true } : {},\n ...type === S_IFIFO2 ? { isFifo: true } : {},\n size: 0,\n mode: type | 384,\n mtimeMs: now\n });\n}\nasync function fdStat2(ctx, fd) {\n const { fds } = ctx.host;\n const e = await fds.get(fd);\n if (e.type === \"dir\") return await emStat(ctx, e.path, await bridgeStat(ctx, e.path, true));\n if (e.type === \"device\") {\n return await emStat(ctx, `/dev/${e.device}`, await bridgeStat(ctx, `/dev/${e.device}`, true));\n }\n if (e.type === \"file\") {\n const file = e.file;\n let st;\n const kept = async () => {\n const handle = file.buffer.handle;\n try {\n return handle === void 0 ? void 0 : await ctx.host.o.fs.keptStat?.(handle);\n } catch {\n return void 0;\n }\n };\n try {\n await file.buffer.flush();\n st = await ctx.host.o.fs.stat(file.path);\n } catch {\n st = await kept();\n }\n const bound = file.buffer.bound;\n if (st && bound?.ino !== void 0 && st.ino !== bound.ino) st = await kept() ?? bound;\n const base = st ?? { isFile: true, isDirectory: false, size: 0, nlink: 0 };\n const orphan = file.buffer.isOrphan();\n return await emStat(ctx, file.path, orphan ? { ...base, nlink: 0 } : base, await file.size());\n }\n return await kernelFdStat(ctx, fd, await fds.kind(fd, e));\n}\nasync function accessFlags(ctx, fd, e) {\n if (e.type === \"dir\") return O_DIRECTORY;\n if (e.type === \"file\") {\n const acc2 = e.file.writable ? e.file.readable ? O_RDWR3 : O_WRONLY3 : 0;\n return acc2 | (e.file.append ? O_APPEND3 : 0);\n }\n if (e.type === \"device\")\n return e.access === \"read\" ? 0 : e.access === \"write\" ? O_WRONLY3 : O_RDWR3;\n const access3 = await ctx.sys.access?.(fd);\n const acc = access3 === \"read\" ? 0 : access3 === \"write\" ? O_WRONLY3 : O_RDWR3;\n return acc | (e.append ? O_APPEND3 : 0) | (e.nonblock ? O_NONBLOCK3 : 0);\n}\nfunction rightsOf(flags) {\n const acc = flags & O_ACCMODE;\n if (acc === O_WRONLY3) return RIGHTS.ALL & ~RIGHTS.FD_READ;\n if (acc === O_RDWR3) return RIGHTS.ALL;\n return RIGHTS.ALL & ~RIGHTS.FD_WRITE;\n}\nfunction oflagsOf(flags) {\n return (flags & O_CREAT ? OFLAGS.CREAT : 0) | (flags & O_DIRECTORY ? OFLAGS.DIRECTORY : 0) | (flags & O_EXCL ? OFLAGS.EXCL : 0) | (flags & O_TRUNC ? OFLAGS.TRUNC : 0);\n}\nfunction fdflagsOf(flags) {\n return (flags & O_APPEND3 ? FDFLAGS.APPEND : 0) | (flags & O_NONBLOCK3 ? FDFLAGS.NONBLOCK : 0);\n}\nasync function refusedCreation(ctx, path) {\n const cred = ctx.host.o.fs.owners ? await credOf(ctx) : void 0;\n const refused3 = devCreation(path, cred);\n if (!refused3) return;\n try {\n await bridgeStat(ctx, path, false);\n } catch {\n throw new EmError(wasiErrno(refused3));\n }\n}\nfunction etcDefaults(ctx) {\n const env = { ...ctx.init.env, HOSTNAME: initHostname(ctx.init) };\n const { passwd, group } = accounts(env);\n return {\n \"/etc/passwd\": passwd,\n \"/etc/group\": group,\n \"/etc/hosts\": hostsFile(hostnameOf(env)),\n \"/etc/hostname\": `${hostnameOf(env)}\n`\n };\n}\nasync function seed(ctx, path, text) {\n const fs = ctx.host.o.fs;\n if (await fs.exists(path)) return;\n try {\n await fs.create?.(path, fs.owners ? 420 : void 0, false);\n await fs.writeFile(path, encoder4.encode(text));\n if ((((await fs.stat(path)).mode ?? 420) & 4095) !== 420) await fs.chmod(path, 420);\n } catch {\n }\n}\nfunction missing2(err) {\n return err.code === \"ENOENT\";\n}\nasync function openPath(ctx, path, flags, mode) {\n const writes = (flags & (O_ACCMODE | O_CREAT)) !== 0;\n const text = path.startsWith(\"/etc/\") ? etcDefaults(ctx)[path] : void 0;\n if (text !== void 0 && writes) await seed(ctx, path, text);\n if (text === void 0 && path !== \"/etc/mtab\" || writes) return await openAt(ctx, path, flags, mode);\n try {\n return await openAt(ctx, path, flags, mode);\n } catch (err) {\n if (!missing2(err)) throw err;\n if (text === void 0) return await openAt(ctx, \"/proc/mounts\", flags, mode);\n const fd = await ctx.sys.openVfs(path, 0, 0, { contents: encoder4.encode(text), orphan: true });\n await ctx.host.fds.adopt(fd, \"file\", false);\n if (flags & O_CLOEXEC2) await ctx.host.fds.setCloexec(fd, true);\n return fd;\n }\n}\nvar O_NOCTTY = 256;\nasync function openPty(ctx, path, flags) {\n const pts = PTS2.exec(path)?.[1];\n if (path !== PTMX && pts === void 0) return void 0;\n const { openPty: master, openPts } = ctx.sys;\n if (!master || !openPts) return void 0;\n const fd = pts === void 0 ? await master.call(ctx.sys) : await openPts.call(ctx.sys, Number(pts), (flags & O_NOCTTY) !== 0);\n await ctx.host.fds.adopt(fd, \"tty\", (flags & O_NONBLOCK3) !== 0);\n if (flags & O_CLOEXEC2) await ctx.host.fds.setCloexec(fd, true);\n return fd;\n}\nasync function openAt(ctx, path, flags, mode) {\n const pty = await openPty(ctx, path, flags);\n if (pty !== void 0) return pty;\n try {\n return await openFile(ctx, path, flags, mode);\n } catch (err) {\n const real = missing2(err) && !(flags & O_NOFOLLOW) ? await devTarget(ctx, path) : void 0;\n if (real === void 0) throw err;\n return await openAt(ctx, real, flags, mode);\n }\n}\nasync function openFile(ctx, path, flags, mode) {\n const { fds } = ctx.host;\n if (flags & O_CREAT) await refusedCreation(ctx, path);\n const alias = fdAlias(ctx, path);\n const target = alias !== void 0 && alias > 2 ? `/dev/fd/${alias}` : path;\n if (alias !== void 0 && alias > 2) await fds.get(alias);\n if (procFdDir(ctx, path) || path === \"/dev/fd\") {\n if ((flags & O_ACCMODE) !== 0 || flags & (O_CREAT | O_TRUNC)) throw new EmError(EM.ISDIR);\n const fd2 = await fds.preopenAt(path, \"\");\n if (flags & O_CLOEXEC2) await fds.setCloexec(fd2, true);\n return fd2;\n }\n const umask = await ctx.host.umask();\n const created = flags & O_CREAT ? mode & 4095 & ~umask : void 0;\n const nofollow = (flags & O_NOFOLLOW) !== 0;\n if (deviceOf(target)) await ctx.host.interrupted?.();\n if (target === path && !deviceOf(path) && !inDev(path)) await refusedLookup(ctx, path);\n const opened = await readOnlyCreate(ctx, target, flags, created);\n const fd = await fds.open(\n target,\n oflagsOf(opened),\n rightsOf(flags),\n fdflagsOf(flags),\n created,\n nofollow\n );\n await dirAccess(ctx, fd, flags);\n if (flags & O_CLOEXEC2) await fds.setCloexec(fd, true);\n return fd;\n}\nasync function refusedLookup(ctx, path) {\n try {\n await ctx.host.o.fs.lstat(path);\n } catch (err) {\n const code2 = err.code;\n if (code2 === \"EACCES\" || code2 === \"EPERM\") throw err;\n }\n}\nasync function readOnlyCreate(ctx, path, flags, mode) {\n if (!(flags & O_CREAT) || (flags & O_ACCMODE) !== 0 || flags & O_DIRECTORY) return flags;\n if (deviceOf(path) || fdAlias(ctx, path) !== void 0 || inDev(path)) return flags;\n const fs = ctx.host.o.fs;\n let exists = true;\n try {\n await fs.lstat(path);\n } catch (err) {\n if (!missing2(err)) throw err;\n exists = false;\n }\n if (exists && flags & O_EXCL) throw new EmError(EM.EXIST);\n if (!exists) {\n try {\n if (fs.create) await fs.create(path, fs.owners ? mode : void 0, false);\n else await fs.writeFile(path, new Uint8Array(0));\n } catch (err) {\n if (err.code !== \"EEXIST\" || flags & O_EXCL) throw err;\n }\n }\n return flags & ~(O_CREAT | O_EXCL);\n}\nasync function dirAccess(ctx, fd, flags) {\n const fs = ctx.host.o.fs;\n if (!fs.owners || !fs.access || flags & O_PATH) return;\n const e = await ctx.host.fds.find(fd);\n if (e?.type !== \"dir\") return;\n const acc = flags & O_ACCMODE;\n const want = (acc === O_WRONLY3 ? 0 : 4) | (acc !== 0 || flags & O_TRUNC ? 2 : 0);\n try {\n await fs.access(e.path, want, \"open\");\n } catch (err) {\n await ctx.host.fds.close(fd);\n throw err;\n }\n}\nfunction times(ctx, ptr) {\n const now = Date.now();\n if (!ptr) return [now, now];\n const v = ctx.mem.view();\n const one = (at) => {\n const nsec = v.getInt32(at + 8, true);\n if (nsec === UTIME_NOW) return now;\n if (nsec === UTIME_OMIT) return null;\n const sec = v.getUint32(at, true) + v.getInt32(at + 4, true) * 4294967296;\n return sec * 1e3 + nsec / 1e6;\n };\n return [one(ptr), one(ptr + 16)];\n}\nfunction touching(ctx, ptr) {\n if (!ptr) return true;\n const v = ctx.mem.view();\n const a = v.getInt32(ptr + 8, true);\n const m = v.getInt32(ptr + 24, true);\n return (a === UTIME_NOW || a === UTIME_OMIT) && (m === UTIME_NOW || m === UTIME_OMIT);\n}\nasync function setTimes(ctx, path, atime, mtime, follow2, now) {\n const fs = ctx.host.o.fs;\n await ctx.host.fds.flushPath(path);\n let a = atime;\n let m = mtime;\n if (a === null || m === null) {\n const st = follow2 ? await fs.stat(path) : await fs.lstat(path);\n a ??= st.atimeMs ?? st.mtimeMs ?? Date.now();\n m ??= st.mtimeMs ?? Date.now();\n }\n await (follow2 ? fs.utimes : fs.lutimes).call(fs, path, a, m, now);\n}\nvar PROC_FD = /^\\/proc\\/(self|[1-9]\\d*)\\/fd$/;\nfunction procFdDir(ctx, path) {\n const m = PROC_FD.exec(path);\n return m !== null && (m[1] === \"self\" || Number(m[1]) === ctx.pid);\n}\nasync function fdNames(ctx) {\n const listed3 = await ctx.call({ op: \"fd-list\" });\n const fds = [];\n for (const entry of listed3) fds.push(entry.fd);\n fds.sort((a, b) => a - b);\n const names2 = [];\n for (const fd of fds) names2.push(String(fd));\n return names2;\n}\nvar PROC_PID = /^\\/proc\\/(self|[1-9]\\d*)$/;\nfunction procListing(ctx, path, listed3) {\n const stats = /* @__PURE__ */ new Map();\n for (const [name2, st] of listed3) if (name2 !== \"task\") stats.set(name2, st);\n stats.set(\"fd\", { isFile: false, isDirectory: true, size: 0, mode: S_IFDIR | 365 });\n const sorted = [...stats.keys()].sort();\n return { names: [\".\", \"..\", ...sorted], stats, path };\n}\nasync function listing(ctx, path) {\n if (procFdDir(ctx, path) || path === \"/dev/fd\") {\n const names3 = [\".\", \"..\"];\n const stats2 = /* @__PURE__ */ new Map();\n for (const name2 of await fdNames(ctx)) {\n names3.push(name2);\n stats2.set(name2, { ...linkStat2(\"\"), mode: S_IFLNK2 | 448 });\n }\n return { names: names3, stats: stats2, path };\n }\n if (inDev(path) && path !== \"/dev/shm\" && !path.startsWith(\"/dev/shm/\")) {\n const names3 = [\".\", \"..\"];\n const stats2 = /* @__PURE__ */ new Map();\n const listed4 = await devSync(devKernel(ctx), devReaddir(path));\n if (path === \"/dev\" && !listed4.includes(\"fd\")) listed4.push(\"fd\");\n if (path === \"/dev\" && ctx.sys.openPty && !listed4.includes(\"ptmx\")) listed4.push(\"ptmx\");\n listed4.sort();\n for (const name2 of listed4) {\n names3.push(name2);\n const child = childPath(path, name2);\n try {\n stats2.set(name2, await bridgeStat(ctx, child, false));\n } catch {\n stats2.set(name2, null);\n }\n }\n return { names: names3, stats: stats2, path };\n }\n const listed3 = await ctx.host.o.fs.readdirStat(path);\n if (PROC_PID.test(path)) return procListing(ctx, path, listed3);\n const names2 = [\".\", \"..\"];\n const stats = /* @__PURE__ */ new Map();\n for (const [name2, st] of listed3) {\n names2.push(name2);\n stats.set(name2, st);\n }\n return { names: names2, stats, path };\n}\nfunction direntType(st) {\n if (!st) return DT_REG;\n if (st.isDirectory) return DT_DIR;\n if (st.isSymbolicLink) return DT_LNK;\n if (!st.isFile && ((st.mode ?? 0) & S_IFMT2) === S_IFCHR) return DT_CHR;\n return DT_REG;\n}\nfunction childPath(dir, name2) {\n return dir === \"/\" ? `/${name2}` : `${dir}/${name2}`;\n}\nasync function dirOf(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type !== \"dir\") throw new EmError(EM.NOTDIR);\n return e;\n}\nasync function getdents(ctx, state, fd, dirp, count) {\n const dir = await dirOf(ctx, fd);\n let held = state.listings.get(dir);\n if (!held) {\n held = { listing: await listing(ctx, dir.path), pos: 0 };\n state.listings.set(dir, held);\n }\n const { names: names2, stats, path } = held.listing;\n const start2 = Math.floor(held.pos / DIRENT_SIZE);\n const end = Math.min(names2.length, start2 + Math.floor(count / DIRENT_SIZE));\n let pos = 0;\n let idx = start2;\n for (; idx < end; idx++) {\n const name2 = names2[idx];\n let ino;\n let type;\n if (name2 === \".\" || name2 === \"..\") {\n const at = name2 === \".\" ? path : parentOf3(path);\n ino = inodeOf(at);\n type = DT_DIR;\n try {\n ino = (await ctx.host.o.fs.stat(at)).ino ?? ino;\n } catch {\n }\n } else {\n const full = childPath(path, name2);\n let st = stats.get(name2) ?? null;\n if (st === null) {\n try {\n st = await ctx.host.o.fs.lstat(full);\n } catch {\n st = null;\n }\n }\n ino = st?.ino ?? inodeOf(full);\n type = direntType(st);\n }\n writeDirent(ctx.mem, dirp + pos, ino, (idx + 1) * DIRENT_SIZE, type, name2);\n pos += DIRENT_SIZE;\n }\n held.pos = idx * DIRENT_SIZE;\n return pos;\n}\nfunction seekDir(state, entry, offset, whence) {\n const held = state.listings.get(entry);\n const base = whence === 1 ? held?.pos ?? 0 : 0;\n const pos = base + offset;\n if (pos < 0) throw new EmError(EM.INVAL);\n if (pos === 0 && whence === 0) {\n state.listings.delete(entry);\n return 0;\n }\n if (held) held.pos = pos;\n return pos;\n}\nvar UTS_FIELD = 65;\nfunction unameHost(ctx) {\n return initHostname(ctx.init);\n}\nasync function chown(ctx, path, uid, gid, follow2) {\n const fs = ctx.host.o.fs;\n if (!fs.chown) throw new EmError(EM.NOSYS);\n const id = (v) => v >>> 0 === 4294967295 ? void 0 : v >>> 0;\n await fs.chown.call(fs, path, id(uid), id(gid), follow2);\n}\nasync function chmodPath(ctx, path, mode, follow2) {\n const fs = ctx.host.o.fs;\n const alias = fdAlias(ctx, path);\n if (alias !== void 0 && follow2) {\n await chmodFd(ctx, alias, mode);\n return;\n }\n if (!follow2 && (await fs.lstat(path)).isSymbolicLink) throw new EmError(EM.NOTSUP);\n await fs.chmod(follow2 ? await physicalPath(fs, path) : path, mode & 4095);\n}\nasync function chmodFd(ctx, fd, mode) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") {\n await ctx.sys.fdChmod?.(fd, mode & 4095);\n return;\n }\n if (e.type === \"dir\") return void await ctx.host.o.fs.chmod(e.path, mode & 4095);\n if (e.type === \"file\") return void await ctx.host.o.fs.chmod(e.file.path, mode & 4095);\n throw new EmError(EM.PERM);\n}\nasync function access2(ctx, path, amode, flags) {\n if (amode & ~7) throw new EmError(EM.INVAL);\n const fs = ctx.host.o.fs;\n const follow2 = (flags & AT_SYMLINK_NOFOLLOW2) === 0;\n const alias = fdAlias(ctx, path);\n if (alias !== void 0) {\n await ctx.host.fds.get(alias);\n return;\n }\n const st = await bridgeStat(ctx, path, follow2);\n if (amode & 2 && st.readonly) throw new EmError(69);\n if (!fs.owners || !fs.access || inDev(path)) return;\n const kind = flags & AT_EACCESS2 ? \"eaccess\" : \"access\";\n await fs.access(path, amode & 7, kind, !follow2);\n}\nasync function devRemove(ctx, path) {\n const cred = ctx.host.o.fs.owners ? await credOf(ctx) : void 0;\n const refused3 = devRemoval(path, cred);\n if (refused3) throw new EmError(wasiErrno(refused3));\n}\nasync function unlinkPath(ctx, path) {\n await devRemove(ctx, path);\n const fs = ctx.host.o.fs;\n const { fds } = ctx.host;\n const st = await fs.lstat(path);\n if (st.isDirectory) throw new EmError(EM.ISDIR);\n const linked = (st.nlink ?? 1) > 1 ? st : void 0;\n await fds.unlinking(path, linked);\n await fs.unlink(path);\n await fds.unlinked(path, linked);\n}\nfunction parentOf3(path) {\n const slash = path.lastIndexOf(\"/\");\n return slash <= 0 ? \"/\" : path.slice(0, slash);\n}\nasync function mountOf(ctx, state, dir) {\n if (dir === \"/dev/shm\" || dir.startsWith(\"/dev/shm/\")) return \"/dev/shm\";\n if (dir === \"/\") return \"/\";\n const top = `/${dir.split(\"/\")[1]}`;\n return (await mountPoints(ctx, state)).has(top) ? top : \"/\";\n}\nvar OWN_MOUNTS = /* @__PURE__ */ new Set([\"dev\", \"proc\", \"sys\"]);\nasync function mountPoints(ctx, state) {\n if (state.mounts) return state.mounts;\n const fs = ctx.host.o.fs;\n const out = /* @__PURE__ */ new Set([\"/dev\", \"/proc\", \"/sys\"]);\n let names2 = [];\n try {\n names2 = await fs.readdir(\"/\");\n } catch {\n }\n for (const name2 of [...names2, \"usr\", \"bin\"]) {\n if (!name2 || name2.includes(\"/\") || OWN_MOUNTS.has(name2)) continue;\n try {\n if ((await fs.stat(`/${name2}`)).isDirectory) out.add(`/${name2}`);\n } catch {\n }\n }\n try {\n if ((await fs.stat(\"/dev/shm\")).isDirectory) out.add(\"/dev/shm\");\n } catch {\n }\n state.mounts = out;\n return out;\n}\nasync function removeDir(ctx, state, path) {\n await devRemove(ctx, path);\n if (path === \"/\" || (await mountPoints(ctx, state)).has(path)) {\n await ctx.host.o.fs.lstat(path);\n throw new EmError(EM.BUSY);\n }\n await ctx.host.o.fs.rmdir(path);\n}\nasync function renamePath(ctx, state, from, to) {\n const fs = ctx.host.o.fs;\n const { fds } = ctx.host;\n const points = await mountPoints(ctx, state);\n if (points.has(from)) {\n await fs.lstat(from);\n throw new EmError(EM.XDEV);\n }\n if (points.has(to)) {\n await fs.lstat(from);\n throw new EmError(EM.BUSY);\n }\n if (await mountOf(ctx, state, parentOf3(from)) !== await mountOf(ctx, state, parentOf3(to))) {\n await fs.lstat(from);\n throw new EmError(EM.XDEV);\n }\n await fds.flushPath(from);\n let replaced;\n if (fds.holdsUnder(to)) {\n try {\n const st = await fs.lstat(to);\n replaced = (st.nlink ?? 1) > 1 ? st : void 0;\n } catch {\n }\n }\n if (replaced === void 0) await fds.replacing(to);\n const seq = await fs.rename(from, to);\n await fds.renamed(from, to, replaced);\n fds.ownRename(typeof seq === \"number\" ? seq : void 0);\n}\nasync function linkPath(ctx, from, to, follow2) {\n const fs = ctx.host.o.fs;\n const { fds } = ctx.host;\n const source = follow2 ? await physicalPath(fs, from) : from;\n await fds.flushPath(from);\n if (source !== from) await fds.flushPath(source);\n try {\n await fs.link(from, to, follow2);\n } catch (err) {\n if (err.code !== \"EPERM\" || await linkable(ctx, source)) throw err;\n throw new EmError(EM.MLINK);\n }\n await fds.linked(from, to);\n if (source !== from) await fds.linked(source, to);\n}\nasync function linkable(ctx, path) {\n try {\n return (await ctx.host.o.fs.lstat(path)).linkable === true;\n } catch {\n return false;\n }\n}\nasync function truncateFd(ctx, fd, size) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") {\n if (!e.file.writable) throw new EmError(EM.INVAL);\n await e.file.buffer.truncate(size);\n return;\n }\n if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") {\n await ctx.call({ op: \"fd-resize\", fd, size });\n ctx.host.o.fs.touched?.(e.path, e.ino);\n return;\n }\n throw new EmError(EM.INVAL);\n}\nasync function syncFd(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") await ctx.host.fds.synced(e.file);\n else if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") await ctx.sys.flush(fd);\n}\nasync function readlink(ctx, path) {\n const alias = fdAlias(ctx, path);\n if (alias !== void 0) {\n if (/^\\/dev\\/(stdin|stdout|stderr)$/.test(path)) return `/proc/self/fd/${alias}`;\n return await fdTarget2(ctx, alias);\n }\n return await ctx.host.o.fs.readlink(path);\n}\nfunction fileImports(ctx, state) {\n const { mem } = ctx;\n const str = (ptr) => mem.cString(ptr);\n const at = async (dirfd, ptr, empty = false) => await ctx.cwd.resolve(dirfd, str(ptr), empty);\n const fds = () => ctx.host.fds;\n return {\n __syscall_chdir: negated(async (p) => await ctx.cwd.chdir(await at(AT_FDCWD2, p))),\n __syscall_fchdir: negated(async (fd) => await ctx.cwd.chdir((await dirOf(ctx, fd)).path)),\n __syscall_getcwd: negated(async (buf, size) => {\n if (size === 0) return -EM.INVAL;\n if (await ctx.cwd.gone()) return -EM.NOENT;\n const cwd = ctx.cwd.path;\n const n = encoder4.encode(cwd).length + 1;\n if (size < n) return -EM.RANGE;\n putString(mem, buf, cwd, size);\n return n;\n }),\n __syscall_chmod: negated(\n async (p, mode) => await chmodPath(ctx, await at(AT_FDCWD2, p), mode, true)\n ),\n __syscall_fchmod: negated(async (fd, mode) => await chmodFd(ctx, fd, mode)),\n __syscall_fchmodat2: negated(\n async (dirfd, p, mode, flags) => await chmodPath(ctx, await at(dirfd, p), mode, (flags & AT_SYMLINK_NOFOLLOW2) === 0)\n ),\n __syscall_fchown32: negated(async (fd, uid, gid) => {\n const e = await fds().get(fd);\n if (e.type === \"kernel\" && await fds().kind(fd, e) === \"file\") {\n const id = (v) => v >>> 0 === 4294967295 ? void 0 : v >>> 0;\n await ctx.sys.fdChown?.(fd, id(uid), id(gid));\n return;\n }\n await chown(ctx, await fdTarget2(ctx, fd), uid, gid, true);\n }),\n __syscall_fchownat: negated(\n async (dirfd, p, uid, gid, flags) => await chown(\n ctx,\n await at(dirfd, p, (flags & AT_EMPTY_PATH) !== 0),\n uid,\n gid,\n !(flags & AT_SYMLINK_NOFOLLOW2)\n )\n ),\n __syscall_faccessat: negated(\n async (dirfd, p, amode, flags) => await access2(ctx, await at(dirfd, p), amode, flags)\n ),\n __syscall_fadvise64: () => 0,\n __syscall_fdatasync: negated(async (fd) => await syncFd(ctx, fd)),\n __syscall_fstat64: negated(async (fd, buf) => writeStat(mem, buf, await fdStat2(ctx, fd))),\n __syscall_stat64: negated(\n async (p, buf) => writeStat(mem, buf, await pathStat2(ctx, await at(AT_FDCWD2, p), true))\n ),\n __syscall_lstat64: negated(\n async (p, buf) => writeStat(mem, buf, await pathStat2(ctx, await at(AT_FDCWD2, p), false))\n ),\n __syscall_newfstatat: negated(async (dirfd, p, buf, flags) => {\n const raw = str(p);\n if (raw === \"\" && flags & AT_EMPTY_PATH && dirfd !== AT_FDCWD2) {\n return writeStat(mem, buf, await fdStat2(ctx, dirfd));\n }\n const path = await ctx.cwd.resolve(dirfd, raw, (flags & AT_EMPTY_PATH) !== 0);\n writeStat(mem, buf, await pathStat2(ctx, path, (flags & AT_SYMLINK_NOFOLLOW2) === 0));\n }),\n __syscall_statfs64: negated(async (p, _size, buf) => {\n const path = await at(AT_FDCWD2, p);\n await bridgeStat(ctx, path, true);\n const usage = await ctx.statfs(path);\n const blocks = usage ? Math.ceil(usage.quota / 4096) : 1e6;\n const free = usage ? Math.max(0, Math.floor((usage.quota - usage.usage) / 4096)) : 5e5;\n writeStatfs(mem, buf, {\n bsize: 4096,\n blocks,\n bfree: free,\n bavail: free,\n files: 1e6,\n ffree: 5e5,\n fsid: 42,\n flags: 2,\n namelen: 255\n });\n }),\n __syscall_ftruncate64: negated(async (fd, length) => {\n const size = Number(length);\n if (!Number.isSafeInteger(size)) return -EM.OVERFLOW;\n if (size < 0) return -EM.INVAL;\n await truncateFd(ctx, fd, size);\n }),\n ...moreFileImports(ctx, state)\n };\n}\nfunction moreFileImports(ctx, state) {\n const { mem } = ctx;\n const str = (ptr) => mem.cString(ptr);\n const at = async (dirfd, ptr, empty = false) => await ctx.cwd.resolve(dirfd, str(ptr), empty);\n return {\n __syscall_getdents64: negated(\n async (fd, dirp, count) => await getdents(ctx, state, fd, dirp, count)\n ),\n __syscall_mkdirat: negated(async (dirfd, p, mode) => {\n const path = await at(dirfd, p);\n await refusedCreation(ctx, path);\n const fs = ctx.host.o.fs;\n if (await fs.exists(path)) throw new EmError(EM.EXIST);\n const perm = mode & 4095 & ~await ctx.host.umask();\n await fs.mkdir(path, fs.owners ? perm : void 0);\n if (!fs.owners && perm !== 493) await fs.chmod(path, perm);\n }),\n __syscall_mknodat: negated(async (dirfd, p, mode) => {\n const path = await at(dirfd, p);\n const type = mode & S_IFMT2;\n if (type !== S_IFREG && type !== S_IFCHR && type !== 24576 && type !== S_IFIFO2 && type !== S_IFSOCK) {\n return -EM.INVAL;\n }\n await refusedCreation(ctx, path);\n const fs = ctx.host.o.fs;\n const perm = mode & 4095 & ~await ctx.host.umask();\n if (type === S_IFIFO2 && fs.mkfifo) return void await fs.mkfifo(path, perm);\n if (type === S_IFREG) {\n if (await fs.exists(path)) throw new EmError(EM.EXIST);\n if (fs.create) await fs.create(path, fs.owners ? perm : void 0);\n else await fs.writeFile(path, new Uint8Array(0));\n return;\n }\n throw new EmError(EM.PERM);\n }),\n __syscall_openat: negated(async (dirfd, p, flags, varargs) => {\n const mode = varargs ? mem.view().getInt32(varargs, true) : 0;\n return await openPath(ctx, await at(dirfd, p), flags, mode);\n }),\n __syscall_readlinkat: negated(async (dirfd, p, buf, bufsize) => {\n const path = await at(dirfd, p);\n if (bufsize <= 0) return -EM.INVAL;\n const target = encoder4.encode(await readlink(ctx, path));\n const n = Math.min(bufsize, target.length);\n mem.bytes(buf, n).set(target.subarray(0, n));\n return n;\n }),\n __syscall_renameat: negated(\n async (od, op, nd, np) => await renamePath(ctx, state, await at(od, op), await at(nd, np))\n ),\n __syscall_rmdir: negated(async (p) => await removeDir(ctx, state, await at(AT_FDCWD2, p))),\n __syscall_symlinkat: negated(async (target, dirfd, p) => {\n const path = await at(dirfd, p);\n await refusedCreation(ctx, path);\n await ctx.host.o.fs.symlink(str(target), path);\n }),\n __syscall_linkat: negated(\n async (od, op, nd, np, flags) => await linkPath(ctx, await at(od, op), await at(nd, np), (flags & AT_SYMLINK_FOLLOW) !== 0)\n ),\n __syscall_unlinkat: negated(async (dirfd, p, flags) => {\n const path = await at(dirfd, p);\n if (flags === 0) return void await unlinkPath(ctx, path);\n if (flags === AT_REMOVEDIR) return void await removeDir(ctx, state, path);\n return -EM.INVAL;\n }),\n __syscall_utimensat: negated(async (dirfd, p, ptr, flags) => {\n const path = await at(dirfd, p, true);\n const [atime, mtime] = times(ctx, ptr);\n if ((mtime ?? atime) === null) return;\n await setTimes(ctx, path, atime, mtime, (flags & AT_SYMLINK_NOFOLLOW2) === 0, touching(ctx, ptr));\n }),\n __syscall_umask: async (mask) => await ctx.host.umask(mask & 511),\n __syscall_uname: negated((buf) => {\n if (!buf) return -EM.FAULT;\n const fields = [\n \"Linux\",\n unameHost(ctx),\n OS_RELEASE,\n \"#1 SMP PREEMPT_DYNAMIC\",\n \"wasm32\",\n \"(none)\"\n ];\n mem.bytes(buf, UTS_FIELD * fields.length).fill(0);\n for (let i = 0; i < fields.length; i++) {\n putString(mem, buf + i * UTS_FIELD, fields[i], UTS_FIELD);\n }\n })\n };\n}\nasync function fdFlags(ctx, fd) {\n return await accessFlags(ctx, fd, await ctx.host.fds.get(fd));\n}\n\n// src/process/emscripten/net.ts\nvar KILLED_BY_SIGPIPE3 = 128 + SIG.PIPE;\nasync function guard2(ctx, op) {\n for (; ; ) {\n try {\n return await op();\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n if (errno === 27 && ctx.gate.restartable()) continue;\n return -errno;\n }\n }\n}\nasync function socketFd(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n if (e.type !== \"kernel\" || await ctx.host.fds.kind(fd, e) !== \"socket\") throw new EmError(EM.NOTSOCK);\n return e;\n}\nfunction resolved(ctx, addr) {\n if (addr.family !== \"unix\" || !addr.path || addr.path.startsWith(\"\\0\")) return addr;\n const path = addr.path.startsWith(\"/\") ? addr.path : `${ctx.cwd.path}/${addr.path}`;\n return { family: \"unix\", path: normalizePath(path) };\n}\nasync function install(ctx, fd, nonblock, cloexec) {\n await ctx.host.fds.adopt(fd, \"socket\", nonblock);\n if (nonblock) await ctx.host.fds.setFlags(fd, true, false);\n if (cloexec) await ctx.host.fds.setCloexec(fd, true);\n return fd;\n}\nfunction writeAddr2(ctx, out, a) {\n if (!a) return;\n const v = ctx.mem.view();\n if (a.family === \"unix\") {\n v.setInt32(out, 1, true);\n const bytes = new TextEncoder().encode(a.path).subarray(0, 107);\n ctx.mem.bytes(out + 12, bytes.length + 1).set(bytes);\n ctx.mem.bytes(out + 12 + bytes.length, 1)[0] = 0;\n return;\n }\n const q = a.host.split(\".\");\n const ip = (Number(q[0]) << 24 | Number(q[1]) << 16 | Number(q[2]) << 8 | Number(q[3])) >>> 0;\n v.setInt32(out, 2, true);\n v.setUint32(out + 4, ip, true);\n v.setInt32(out + 8, a.port, true);\n}\nfunction netImports(ctx) {\n const { mem } = ctx;\n const json = async (req) => await ctx.call(req);\n return {\n slicc_net_ready: () => 1,\n slicc_socket_js: async (unix, nonblock, cloexec) => await guard2(ctx, async () => {\n const fd = await json({ op: \"sock-open\", domain: unix ? \"unix\" : \"inet\" });\n return await install(ctx, fd, !!nonblock, !!cloexec);\n }),\n slicc_bind_js: async (fd, family, ip, port, path, connect) => await guard2(ctx, async () => {\n const host = [ip >>> 24, ip >>> 16 & 255, ip >>> 8 & 255, ip & 255].join(\".\");\n const given = family === 1 ? { family: \"unix\", path: mem.cString(path) } : { family: \"inet\", host, port };\n const e = await socketFd(ctx, fd);\n const addr = resolved(ctx, given);\n if (connect) await json({ op: \"sock-connect\", fd, addr, nonblock: e.nonblock });\n else await json({ op: \"sock-bind\", fd, addr });\n return 0;\n }),\n slicc_socketpair_js: async (unix, nonblock, cloexec, out) => await guard2(ctx, async () => {\n const pair = await json({ op: \"sock-pair\", domain: unix ? \"unix\" : \"inet\" });\n await install(ctx, pair[0], !!nonblock, !!cloexec);\n await install(ctx, pair[1], !!nonblock, !!cloexec);\n mem.view().setInt32(out, pair[0], true);\n mem.view().setInt32(out + 4, pair[1], true);\n return 0;\n }),\n slicc_listen_js: async (fd, backlog) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n await json({ op: \"sock-listen\", fd, backlog });\n return 0;\n }),\n slicc_addr_call_js: async (op, fd, arg, out) => await guard2(ctx, async () => {\n const e = await socketFd(ctx, fd);\n if (op === 0) {\n const got = await json({ op: \"sock-accept\", fd, nonblock: e.nonblock });\n const at = await install(ctx, got.fd, (arg & 1) !== 0, (arg & 2) !== 0);\n writeAddr2(ctx, out, got.peer);\n return at;\n }\n writeAddr2(ctx, out, await json({ op: \"sock-name\", fd, peer: op === 2 }));\n return 0;\n }),\n slicc_shutdown_js: async (fd, how) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n await json({ op: \"sock-shutdown\", fd, how });\n return 0;\n }),\n slicc_getopt_js: async (fd, level, name2, value2) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n const got = await json({ op: \"sock-getopt\", fd, level, name: name2 });\n mem.view().setInt32(value2, got, true);\n return 0;\n }),\n slicc_setopt_js: async (fd, level, name2, value2) => await guard2(ctx, async () => {\n await socketFd(ctx, fd);\n await json({ op: \"sock-setopt\", fd, level, name: name2, value: value2 });\n return 0;\n }),\n slicc_send_js: async (fd, buf, len, dontwait, nosignal) => await guard2(ctx, async () => {\n const e = await socketFd(ctx, fd);\n const bytes = mem.bytes(buf, len).slice();\n try {\n return await ctx.sys.write(fd, bytes, { nonblock: !!dontwait || e.nonblock });\n } catch (err) {\n const broken = err.code === \"EPIPE\";\n if (broken && !nosignal && !await sigpipeSpared(ctx)) throw new WasiExit(KILLED_BY_SIGPIPE3);\n throw err;\n }\n }),\n slicc_recv_js: async (fd, buf, len, dontwait, peek) => await guard2(ctx, async () => {\n const e = await socketFd(ctx, fd);\n const got = await ctx.sys.read(fd, len, { nonblock: !!dontwait || e.nonblock, peek: !!peek });\n mem.bytes(buf, got.length).set(got);\n return got.length;\n }),\n slicc_resolve_js: async (name2, out, max) => {\n let r;\n try {\n r = await json({ op: \"sock-resolve\", name: mem.cString(name2), family: 4 });\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n if (!Array.isArray(r)) return -EM.NOSYS;\n let n = 0;\n for (const a of r) {\n const parts = String(a).split(\".\");\n if (parts.length !== 4 || n >= max) continue;\n let ok = true;\n let ip = 0;\n for (let i = 0; i < 4; i++) {\n const x = Number(parts[i]);\n if (String(x) !== parts[i] || x > 255) ok = false;\n ip = ip << 8 | x & 255;\n }\n if (!ok) continue;\n mem.view().setUint32(out + 4 * n++, ip >>> 0, true);\n }\n return n;\n }\n };\n}\nasync function sigpipeSpared(ctx) {\n const spare = ctx.exports().slicc_sigpipe;\n if (typeof spare === \"function\" && await ctx.enter(\"slicc_sigpipe\", spare, []) === 1) {\n return true;\n }\n try {\n const r = await ctx.call({ op: \"proc-kill-self\", sig: SIG.PIPE, probe: true });\n return r !== \"terminate\";\n } catch {\n return false;\n }\n}\n\n// src/process/emscripten/wasi.ts\nvar EINTR = 27;\nvar KILLED_BY_SIGPIPE4 = 141;\nvar encoder5 = new TextEncoder();\nasync function holdStopped(ctx) {\n const header = new Int32Array(ctx.init.sab, 0, SAB_HEADER_I32);\n while (Atomics.load(header, SAB_I_STOP) === 1) await atomicsWait(header, SAB_I_STOP, 1);\n}\nasync function sleepFor(ms) {\n await atomicsWait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\nasync function sleepIn(ctx, ms) {\n if (ctx.init.sab instanceof SharedArrayBuffer || !(ms > 0)) {\n await sleepFor(ms);\n return;\n }\n try {\n await ctx.call({ op: \"fd-select\", read: [], write: [], timeoutMs: ms });\n } catch (e) {\n if (errnoOf(e) === void 0) throw e;\n }\n}\nasync function afterStopped(ctx) {\n const header = new Int32Array(ctx.init.sab, 0, SAB_HEADER_I32);\n await holdStopped(ctx);\n const due = Atomics.load(header, SAB_I_SIGNALS) | Atomics.load(header, SAB_I_TIMERS) | Atomics.load(header, SAB_I_KILLED);\n if (due !== 0) await ctx.gate.interrupt();\n}\nfunction envStrings(ctx) {\n const out = [];\n for (const [key, value2] of Object.entries(ctx.init.env)) {\n if (value2 !== void 0) out.push(`${key}=${value2}`);\n }\n return out;\n}\nvar NODE_CLOCK = Boolean(\n globalThis.process?.versions?.node\n);\nasync function restarting(ctx, fn, args) {\n for (; ; ) {\n const r = await fn(...args) ?? 0;\n if (r !== EINTR || !ctx.gate.restartable()) return r;\n }\n}\nvar STRERROR = {\n EACCES: \"Permission denied\",\n EIO: \"I/O error\",\n ENOTSUP: \"Not supported\",\n EOPNOTSUPP: \"Not supported\",\n EFBIG: \"File too large\",\n EILSEQ: \"Illegal byte sequence\",\n EINTR: \"Interrupted system call\"\n};\nvar REPORTING = /* @__PURE__ */ new Set([\"clipboard\", \"embedder\"]);\nasync function commitStdout(ctx) {\n const e = await ctx.host.fds.find(1);\n if (e?.type !== \"kernel\" || !REPORTING.has(await ctx.host.fds.kind(1, e))) return;\n try {\n await ctx.host.fds.close(1);\n } catch (err) {\n const code2 = err.code;\n if (typeof code2 !== \"string\") throw err;\n ctx.quit.failed = true;\n try {\n await ctx.sys.write(\n 2,\n encoder5.encode(`${ctx.init.argv0}: write error: ${STRERROR[code2] ?? code2}\n`)\n );\n } catch {\n }\n }\n}\nvar WASI_NOTSUP = 58;\nfunction emscriptenErrno(errno) {\n return errno === WASI_NOTSUP ? EM.NOTSUP : errno;\n}\nfunction emscriptenErrnos(fn) {\n return (async (...args) => emscriptenErrno(await fn(...args) ?? 0));\n}\nasync function streamed(ctx, fd) {\n const e = await ctx.host.fds.find(fd);\n if (e?.type !== \"kernel\") return false;\n const kind = await ctx.host.fds.kind(fd, e);\n return kind !== \"file\" && kind !== \"socket\";\n}\nfunction streamWrite(ctx) {\n return positive(async (fd, iov, n, out) => {\n const e = await ctx.host.fds.get(fd);\n const nonblock = e.type === \"kernel\" && e.nonblock;\n let written;\n try {\n written = await ctx.sys.write(fd, ctx.mem.gather(iov, n), { nonblock });\n } catch (err) {\n if (err.code === \"EPIPE\" && !await sigpipeSpared(ctx)) {\n throw new WasiExit(KILLED_BY_SIGPIPE4);\n }\n throw err;\n }\n ctx.mem.view().setUint32(out, written, true);\n });\n}\nfunction wasiImports(ctx, state) {\n const host = ctx.host.imports();\n const { mem } = ctx;\n const call2 = (name2) => emscriptenErrnos(host[name2]);\n return {\n fd_write: async (fd, iov, n, out) => {\n await holdStopped(ctx);\n const r = await streamed(ctx, fd) ? await restarting(ctx, streamWrite(ctx), [fd, iov, n, out]) : await restarting(ctx, call2(\"fd_write\"), [fd, iov, n, out]);\n await afterStopped(ctx);\n return r;\n },\n fd_read: async (fd, iov, n, out) => {\n await holdStopped(ctx);\n const r = await restarting(ctx, call2(\"fd_read\"), [fd, iov, n, out]);\n await afterStopped(ctx);\n return r;\n },\n fd_pread: async (fd, iov, n, at, out) => {\n if (at < 0n || at > BigInt(Number.MAX_SAFE_INTEGER)) return EM.OVERFLOW;\n return await call2(\"fd_pread\")(...[fd, iov, n, at, out]) ?? 0;\n },\n fd_pwrite: async (fd, iov, n, at, out) => {\n if (at < 0n || at > BigInt(Number.MAX_SAFE_INTEGER)) return EM.OVERFLOW;\n return await call2(\"fd_pwrite\")(...[fd, iov, n, at, out]) ?? 0;\n },\n fd_close: async (fd) => {\n const e = await ctx.host.fds.find(fd);\n if (e) state.listings.delete(e);\n if (fd === 2 && ctx.quit.atExit) await commitStdout(ctx);\n return await call2(\"fd_close\")(...[fd]) ?? 0;\n },\n fd_seek: positive(async (fd, offset, whence, out) => {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"dir\") {\n const pos = seekDir(state, e, Number(offset), whence);\n mem.view().setBigInt64(out, BigInt(pos), true);\n return 0;\n }\n return await call2(\"fd_seek\")(...[fd, offset, whence, out]) ?? 0;\n }),\n fd_sync: positive(async (fd) => {\n const e = await ctx.host.fds.get(fd);\n if (e.type === \"file\") await ctx.host.fds.synced(e.file);\n else if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\") await ctx.sys.flush(fd);\n }),\n fd_fdstat_get: positive(async (fd, out) => {\n const e = await ctx.host.fds.get(fd);\n let type = 4;\n if (e.type === \"dir\") type = 3;\n else if (e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"tty\") type = 2;\n const v = mem.view();\n v.setInt8(out, type);\n v.setInt16(out + 2, 0, true);\n v.setBigInt64(out + 8, 0n, true);\n v.setBigInt64(out + 16, 0n, true);\n }),\n environ_sizes_get: (count, size) => {\n const list = envStrings(ctx);\n let bytes = 0;\n for (const s of list) bytes += encoder5.encode(s).length + 1;\n const v = mem.view();\n v.setUint32(count, list.length, true);\n v.setUint32(size, bytes, true);\n return 0;\n },\n environ_get: (envp, buf) => {\n const list = envStrings(ctx);\n let at = buf;\n for (let i = 0; i < list.length; i++) {\n const bytes = encoder5.encode(list[i]);\n mem.view().setUint32(envp + i * 4, at, true);\n mem.bytes(at, bytes.length + 1).set(bytes);\n mem.bytes(at + bytes.length, 1)[0] = 0;\n at += bytes.length + 1;\n }\n return 0;\n },\n clock_time_get: (id, _precision, out) => {\n lookedOutside();\n if (id < 0 || id > 3) return EM.INVAL;\n const now = id === 0 ? Date.now() : performance.now();\n mem.view().setBigInt64(out, BigInt(Math.round(now * 1e3 * 1e3)), true);\n return 0;\n },\n clock_res_get: (id, out) => {\n if (id < 0 || id > 3) return EM.INVAL;\n const nsec = id === 0 ? 1e3 * 1e3 : NODE_CLOCK ? 1 : 1e3;\n mem.view().setBigInt64(out, BigInt(nsec), true);\n return 0;\n },\n random_get: (buf, len) => {\n lookedOutside();\n for (let at = 0; at < len; at += 65536) {\n const chunk = new Uint8Array(Math.min(65536, len - at));\n crypto.getRandomValues(chunk);\n mem.bytes(buf + at, chunk.length).set(chunk);\n }\n return 0;\n },\n proc_exit: (code2) => {\n throw new WasiExit(code2);\n }\n };\n}\n\n// src/process/emscripten/fds.ts\nvar F_DUPFD = 0;\nvar F_GETFD = 1;\nvar F_SETFD = 2;\nvar F_GETFL = 3;\nvar F_SETFL = 4;\nvar F_GETLK2 = 12;\nvar F_SETLK2 = 13;\nvar F_SETLKW2 = 14;\nvar F_DUPFD_CLOEXEC = 1030;\nvar FD_CLOEXEC = 1;\nvar TCGETS = 21505;\nvar TCSETS = 21506;\nvar TCSETSW = 21507;\nvar TCSETSF = 21508;\nvar TCSBRK = 21509;\nvar TCXONC = 21510;\nvar TCFLSH = 21515;\nvar TIOCGPGRP = 21519;\nvar TIOCSPGRP = 21520;\nvar TIOCGWINSZ = 21523;\nvar FIONREAD = 21531;\nvar FIONBIO = 21537;\nvar POLLIN = 1;\nvar POLLOUT = 4;\nvar POLLERR = 8;\nvar POLLHUP = 16;\nvar POLLNVAL = 32;\nvar POLLRDNORM = 64;\nvar POLLWRNORM = 256;\nasync function isTty(ctx, fd) {\n const e = await ctx.host.fds.get(fd);\n return e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"tty\";\n}\nasync function isKernel(ctx, fd) {\n return (await ctx.host.fds.find(fd))?.type === \"kernel\";\n}\nfunction readTermios2(ctx, ptr) {\n const v = ctx.mem.view();\n const cCc = [];\n for (let i = 0; i < 32; i++) cCc.push(v.getInt8(ptr + 17 + i));\n return {\n c_iflag: v.getInt32(ptr, true),\n c_oflag: v.getInt32(ptr + 4, true),\n c_cflag: v.getInt32(ptr + 8, true),\n c_lflag: v.getInt32(ptr + 12, true),\n c_cc: cCc\n };\n}\nfunction writeTermios2(ctx, ptr, t) {\n const v = ctx.mem.view();\n v.setInt32(ptr, t.c_iflag || 0, true);\n v.setInt32(ptr + 4, t.c_oflag || 0, true);\n v.setInt32(ptr + 8, t.c_cflag || 0, true);\n v.setInt32(ptr + 12, t.c_lflag || 0, true);\n for (let i = 0; i < 32; i++) v.setInt8(ptr + 17 + i, t.c_cc[i] || 0);\n}\nasync function ptyIoctl2(ctx, fd, request, argp) {\n const v = ctx.mem.view();\n switch (request) {\n case TIOCGPTN:\n v.setInt32(argp, await ctx.sys.ptyNumber(fd), true);\n return 0;\n case TIOCSPTLCK:\n await ctx.sys.ptyLock(fd, v.getInt32(argp, true) !== 0);\n return 0;\n case TIOCSCTTY:\n await ctx.sys.setControllingTerminal(fd);\n return 0;\n case TIOCPKT:\n await ctx.sys.setPacketMode(fd, v.getInt32(argp, true) !== 0);\n return 0;\n default: {\n const word = v.getInt32(argp, true);\n await ctx.sys.setWinsize(fd, word & 65535, word >>> 16 & 65535);\n return 0;\n }\n }\n}\nvar PTY_REQUESTS = /* @__PURE__ */ new Set([\n TIOCGPTN,\n TIOCSPTLCK,\n TIOCSCTTY,\n TIOCSWINSZ,\n TIOCPKT\n]);\nvar TTY_NOOPS = /* @__PURE__ */ new Set([TCSBRK, TCXONC, TCXONC + 1, TCXONC + 2, TCFLSH]);\nasync function ptyRequest(ctx, fd, request, argp) {\n await ctx.host.fds.get(fd);\n if (await isKernel(ctx, fd)) return await ptyIoctl2(ctx, fd, request, argp());\n if (request === TIOCSWINSZ) return await isTty(ctx, fd) ? 0 : -EM.NOTTY;\n return -EM.INVAL;\n}\nasync function termiosRequest(ctx, fd, request, argp) {\n if (!await isTty(ctx, fd)) return -EM.NOTTY;\n if (request === TCGETS) {\n const t = await ctx.sys.tcgets?.(fd);\n if (t) writeTermios2(ctx, argp(), t);\n return 0;\n }\n if (!ctx.sys.tcsets) return 0;\n await ctx.sys.tcsets(fd, readTermios2(ctx, argp()), request === TCSETSF);\n return 0;\n}\nasync function winsize(ctx, fd, argp) {\n if (!await isTty(ctx, fd)) return -EM.NOTTY;\n const [rows, cols] = await ctx.sys.winsize?.(fd) ?? [24, 80];\n const at = argp();\n const v = ctx.mem.view();\n v.setInt16(at, rows, true);\n v.setInt16(at + 2, cols, true);\n return 0;\n}\nasync function ioctl(ctx, fd, op, varargs) {\n const request = op >>> 0;\n const argp = () => ctx.mem.view().getUint32(varargs, true);\n if (PTY_REQUESTS.has(request)) return await ptyRequest(ctx, fd, request, argp);\n if (TTY_NOOPS.has(request)) return await isTty(ctx, fd) ? 0 : -EM.NOTTY;\n if (request === TCGETS || request === TCSETS || request === TCSETSW || request === TCSETSF) {\n return await termiosRequest(ctx, fd, request, argp);\n }\n if (request === TIOCGWINSZ) return await winsize(ctx, fd, argp);\n if (request === TIOCGPGRP) {\n if (!await isTty(ctx, fd)) return -EM.NOTTY;\n ctx.mem.view().setInt32(argp(), 0, true);\n return 0;\n }\n if (request === TIOCSPGRP) return await isTty(ctx, fd) ? -EM.INVAL : -EM.NOTTY;\n await ctx.host.fds.get(fd);\n return request === FIONREAD || request === FIONBIO ? -EM.NOTTY : -EM.INVAL;\n}\nasync function lockAllowed(ctx, fd, varargs) {\n const at = ctx.mem.view().getUint32(varargs, true);\n const type = ctx.mem.view().getInt16(at, true);\n const acc = await fdFlags(ctx, fd) & 3;\n if (type === 0) return acc !== 1;\n if (type === 1) return acc !== 0;\n return true;\n}\nasync function fcntl(ctx, fd, cmd, varargs) {\n const { fds } = ctx.host;\n const arg = () => ctx.mem.view().getInt32(varargs, true);\n await fds.get(fd);\n switch (cmd) {\n case F_DUPFD:\n case F_DUPFD_CLOEXEC: {\n const min = arg();\n if (min < 0) return -EM.INVAL;\n return await fds.dup(fd, min, cmd === F_DUPFD_CLOEXEC);\n }\n case F_GETFD:\n return fds.cloexec.has(fd) ? FD_CLOEXEC : 0;\n case F_SETFD:\n await fds.setCloexec(fd, (arg() & FD_CLOEXEC) !== 0);\n return 0;\n case F_GETFL:\n return await fdFlags(ctx, fd);\n case F_SETFL: {\n const flags = arg();\n await fds.setFlags(fd, (flags & O_NONBLOCK3) !== 0, (flags & O_APPEND3) !== 0);\n return 0;\n }\n case F_GETLK2:\n case F_SETLK2:\n case F_SETLKW2: {\n if (cmd !== F_GETLK2 && !await lockAllowed(ctx, fd, varargs)) return -EM.BADF;\n const lock = ctx.host.sliccImports().fcntl_lock;\n const r = await lock(fd, cmd, ctx.mem.view().getUint32(varargs, true));\n return r === 0 ? 0 : -emscriptenErrno(r);\n }\n default:\n return -EM.INVAL;\n }\n}\nasync function pollMask(ctx, fd) {\n const e = await ctx.host.fds.find(fd);\n if (!e) return POLLNVAL;\n if (e.type !== \"kernel\") return POLLIN | POLLOUT;\n const state = await ctx.sys.poll(fd);\n let mask = 0;\n if (state.readable) mask |= POLLIN | POLLRDNORM;\n if (state.writable) mask |= POLLOUT | POLLWRNORM;\n if (state.hangup) mask |= state.readable ? POLLHUP : POLLERR;\n return mask;\n}\nasync function select(ctx, read2, write2, timeoutMs2) {\n const { fds } = ctx.host;\n const localRead = [];\n const localWrite = [];\n const kernelRead = [];\n const kernelWrite = [];\n for (const fd of read2) {\n const e = await fds.find(fd);\n if (e?.type === \"kernel\") kernelRead.push(fd);\n else localRead.push(fd);\n }\n for (const fd of write2) {\n const e = await fds.find(fd);\n if (e?.type === \"kernel\") kernelWrite.push(fd);\n else localWrite.push(fd);\n }\n const local2 = localRead.length + localWrite.length > 0;\n if (kernelRead.length + kernelWrite.length === 0 && local2) {\n return { read: localRead, write: localWrite };\n }\n const got = await ctx.call({\n op: \"fd-select\",\n read: kernelRead,\n write: kernelWrite,\n timeoutMs: local2 ? 0 : timeoutMs2\n });\n const out = { read: [], write: [] };\n for (const fd of read2) {\n if (localRead.includes(fd) || got.read.includes(fd)) out.read.push(fd);\n }\n for (const fd of write2) {\n if (localWrite.includes(fd) || got.write.includes(fd)) out.write.push(fd);\n }\n return out;\n}\nfunction bitsOf(ctx, set, n) {\n const out = [];\n if (!set) return out;\n const v = ctx.mem.view();\n for (let fd = 0; fd < n; fd++) {\n if (v.getUint32(set + (fd >> 5) * 4, true) & 1 << (fd & 31)) out.push(fd);\n }\n return out;\n}\nfunction storeBits(ctx, set, n, ready) {\n if (!set) return;\n const v = ctx.mem.view();\n for (let w = 0; w < n + 31 >> 5; w++) v.setUint32(set + w * 4, 0, true);\n for (const fd of ready) {\n const at = set + (fd >> 5) * 4;\n v.setUint32(at, (v.getUint32(at, true) | 1 << (fd & 31)) >>> 0, true);\n }\n}\nasync function blockingPoll(ctx, ptr, n, timeoutMs2) {\n const IN = POLLIN | POLLRDNORM;\n const OUT = POLLOUT | POLLWRNORM;\n const v = () => ctx.mem.view();\n const read2 = [];\n const write2 = [];\n for (let i = 0; i < n; i++) {\n const fd = v().getInt32(ptr + i * 8, true);\n const events = v().getInt16(ptr + i * 8 + 4, true);\n if (fd < 0) continue;\n if (events & IN) read2.push(fd);\n if (events & OUT) write2.push(fd);\n }\n const ready = await select(ctx, read2, write2, timeoutMs2);\n let count = 0;\n for (let i = 0; i < n; i++) {\n const fd = v().getInt32(ptr + i * 8, true);\n const events = v().getInt16(ptr + i * 8 + 4, true);\n let revents = 0;\n if (fd >= 0 && ready.read.includes(fd)) revents |= events & IN;\n if (fd >= 0 && ready.write.includes(fd)) revents |= events & OUT;\n v().setInt16(ptr + i * 8 + 6, revents, true);\n if (revents) count++;\n }\n return count;\n}\nfunction fdImports(ctx) {\n const { fds } = ctx.host;\n return {\n __syscall_dup: negated(async (fd) => await fds.dup(fd, 0, false)),\n __syscall_dup3: negated(async (fd, newfd, flags) => {\n await fds.get(fd);\n if (fd === newfd) return -EM.INVAL;\n if (newfd < 0 || newfd >= 4096) return -EM.BADF;\n if (flags === 0 && await fds.find(newfd)) {\n try {\n await fds.close(newfd);\n } catch {\n }\n }\n await fds.renumber(fd, newfd, true);\n if (flags & O_CLOEXEC2) await fds.setCloexec(newfd, true);\n return newfd;\n }),\n __syscall_fcntl64: negated(\n async (fd, cmd, varargs) => await fcntl(ctx, fd, cmd, varargs)\n ),\n __syscall_ioctl: negated(\n async (fd, op, varargs) => await ioctl(ctx, fd, op, varargs)\n ),\n __syscall_pipe: negated(async (ptr) => {\n if (ptr === 0) return -EM.FAULT;\n const [r, w] = await fds.pipe();\n const v = ctx.mem.view();\n v.setInt32(ptr, r, true);\n v.setInt32(ptr + 4, w, true);\n }),\n __syscall_flock: negated(async (fd, op) => {\n const flock = ctx.host.sliccImports().flock;\n const r = await flock(fd, op);\n return r === 0 ? 0 : -emscriptenErrno(r);\n }),\n _poll_js: negated(async (ptr, nfds) => {\n let count = 0;\n const v = () => ctx.mem.view();\n for (let i = 0; i < nfds; i++) {\n const at = ptr + 8 * i;\n const fd = v().getInt32(at, true);\n const events = v().getInt16(at + 4, true);\n const flags = await pollMask(ctx, fd) & (events | POLLERR | POLLHUP);\n if (flags) count++;\n v().setInt16(at + 6, flags, true);\n }\n return count;\n }),\n slicc_select_js: negated(async (n, rfds, wfds, timeoutMs2) => {\n const r = await select(ctx, bitsOf(ctx, rfds, n), bitsOf(ctx, wfds, n), timeoutMs2);\n storeBits(ctx, rfds, n, r.read);\n storeBits(ctx, wfds, n, r.write);\n return r.read.length + r.write.length;\n }),\n slicc_poll_js: negated(\n async (ptr, n, timeoutMs2) => await blockingPoll(ctx, ptr, n, timeoutMs2)\n )\n };\n}\n\n// src/process/emscripten/errno-cell.ts\nvar ENOMEM = 48;\nvar IMPOSSIBLE = 3221225472;\nvar ErrnoCell = class {\n at;\n ctx;\n constructor(ctx) {\n this.ctx = ctx;\n }\n find() {\n const malloc = this.ctx.exports().malloc;\n if (typeof malloc !== \"function\") return void 0;\n const before = new Int32Array(this.ctx.mem.bytes(0, this.ctx.mem.size()).slice().buffer);\n const got = malloc(IMPOSSIBLE);\n if (got !== 0) {\n this.ctx.exports().free?.(got);\n return void 0;\n }\n const after = new Int32Array(this.ctx.exports().memory.buffer, 0, before.length);\n let found;\n for (let i = 0; i < before.length; i++) {\n if (after[i] !== ENOMEM || before[i] === ENOMEM) continue;\n if (found !== void 0) return void 0;\n found = i * 4;\n }\n return found;\n }\n set(errno) {\n this.at ??= this.find();\n if (this.at === void 0) return false;\n this.ctx.mem.view().setInt32(this.at, errno, true);\n return true;\n }\n};\n\n// src/process/emscripten/fork.ts\nvar REWINDING2 = 2;\nvar ASYNCIFY_STACK = 1048576;\nvar EmFork = class {\n forking = false;\n forkSp = 0;\n data = 0;\n value = 0;\n ctx;\n errno;\n constructor(ctx) {\n this.ctx = ctx;\n this.errno = new ErrnoCell(ctx);\n }\n supported() {\n return typeof this.ctx.exports().asyncify_start_unwind === \"function\";\n }\n forkImport() {\n const ex = this.ctx.exports();\n if (ex.asyncify_get_state?.() === REWINDING2) {\n ex.asyncify_stop_rewind?.();\n ex.free?.(this.data);\n this.data = 0;\n return this.value;\n }\n this.forking = true;\n this.forkSp = ex.emscripten_stack_get_current();\n const ptr = ex.malloc(12 + ASYNCIFY_STACK);\n const v = this.ctx.mem.view();\n v.setUint32(ptr, ptr + 12, true);\n v.setUint32(ptr + 4, ptr + 12 + ASYNCIFY_STACK, true);\n v.setInt32(ptr + 8, 0, true);\n this.data = ptr;\n ex.asyncify_start_unwind?.(ptr);\n return 0;\n }\n async settle(ret) {\n let result = ret;\n for (; ; ) {\n const name2 = this.ctx.reentry.unwound;\n if (name2 === void 0) return result;\n this.ctx.reentry.unwound = void 0;\n if (!this.forking) {\n throw new Error(`${this.ctx.init.argv0}: unexpected Asyncify suspension (not a fork)`);\n }\n this.forking = false;\n result = await this.resume(name2, this.failed(await this.kernelFork(name2)));\n }\n }\n failed(pid) {\n if (pid >= 0) return pid;\n this.errno.set(-pid);\n return -1;\n }\n async resume(name2, value2) {\n const ex = this.ctx.exports();\n ex._emscripten_stack_restore(this.forkSp);\n this.value = value2;\n ex.asyncify_start_rewind?.(this.data);\n return await this.ctx.enter(name2, ex[name2], []);\n }\n async child(state) {\n const memory = this.ctx.exports().memory;\n if (state.memory.length > memory.buffer.byteLength) {\n memory.grow(Math.ceil((state.memory.length - memory.buffer.byteLength) / 65536));\n }\n new Uint8Array(memory.buffer).set(state.memory);\n state.memory = new Uint8Array(0);\n this.data = state.currData;\n this.forkSp = state.forkSp;\n const name2 = state.callStackNames[0]?.[1] ?? \"main\";\n return await this.settle(await this.resume(name2, 0));\n }\n snapshot(name2) {\n const { host, cwd } = this.ctx;\n const memory = this.ctx.mem.bytes(0, this.ctx.mem.size()).slice();\n const wasi = {\n asyncifyData: this.data,\n globals: [],\n fds: host.fds.snapshot(),\n cloexec: [...host.fds.cloexec],\n cwd: cwd.path\n };\n return {\n memory,\n currData: this.data,\n forkSp: this.forkSp,\n callStackNames: [[0, name2]],\n ppid: this.ctx.pid,\n wasi\n };\n }\n async kernelFork(name2) {\n const { host, gate } = this.ctx;\n try {\n await host.fds.flushAll();\n await host.fds.promoteFiles();\n } catch (e) {\n const code2 = e.code;\n if (typeof code2 !== \"string\") throw e;\n return -wasiErrno(code2);\n }\n let seen = gate.deliveries();\n let state = this.snapshot(name2);\n for (; ; ) {\n try {\n return await this.ctx.call({ op: \"proc-fork\", state, restart: true });\n } catch (e) {\n const code2 = e.code;\n if (code2 !== \"EINTR\") {\n if (typeof code2 !== \"string\") throw e;\n return -wasiErrno(code2);\n }\n if (gate.deliveries() !== seen) {\n seen = gate.deliveries();\n state = this.snapshot(name2);\n }\n }\n }\n }\n};\n\n// src/process/emscripten/longjmp.ts\nvar LONGJMP = Number.POSITIVE_INFINITY;\nfunction dynCallOf(ctx, sig, index3) {\n const ex = ctx.exports();\n const named = ex[`dynCall_${sig}`];\n if (typeof named === \"function\")\n return [`dynCall_${sig}`, named];\n const table = ex.__indirect_function_table;\n const fn = table?.get(index3);\n if (typeof fn !== \"function\")\n throw new WebAssembly.RuntimeError(\"null function or function signature mismatch\");\n return [`table:${index3}`, fn];\n}\nfunction invoke(ctx, sig) {\n const returnsI64 = sig.startsWith(\"j\");\n return async (index3, ...rest2) => {\n const ex = ctx.exports();\n const save = ex.emscripten_stack_get_current;\n const restore = ex._emscripten_stack_restore;\n const sp = save();\n try {\n const [name2, fn] = dynCallOf(ctx, sig, index3);\n const args = name2.startsWith(\"dynCall_\") ? [index3, ...rest2] : rest2;\n return await ctx.enter(name2, fn, args);\n } catch (e) {\n restore(sp);\n if (e !== e + 0) throw e;\n ex.setThrew(1, 0);\n return returnsI64 ? 0n : void 0;\n }\n };\n}\nfunction invokeImports(ctx, module) {\n const out = {};\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module !== \"env\" || !imp.name.startsWith(\"invoke_\")) continue;\n out[imp.name] = invoke(ctx, imp.name.slice(\"invoke_\".length));\n }\n return out;\n}\n\n// src/process/emscripten/mmap.ts\nvar PROT_WRITE = 2;\nvar MAP_PRIVATE = 2;\nvar MAP_TYPE = 15;\nvar MAP_ALIGN = 65536;\nvar MAX_READ2 = 1024 * 1024;\nasync function readAt(ctx, fd, target, position) {\n const e = await ctx.host.fds.get(fd);\n let done = 0;\n while (done < target.length) {\n const want = Math.min(MAX_READ2, target.length - done);\n let got;\n if (e.type === \"file\") got = await e.file.pread(want, position + done);\n else got = await ctx.sys.pread?.(fd, want, position + done) ?? new Uint8Array(0);\n if (got.length === 0) break;\n target.set(got, done);\n done += got.length;\n }\n return done;\n}\nfunction mmapImport(ctx) {\n return {\n _mmap_js: negated(\n async (len, prot, flags, fd, offset, allocated, addr) => {\n const position = Number(offset);\n if (!Number.isSafeInteger(position)) return -EM.OVERFLOW;\n const e = await ctx.host.fds.get(fd);\n const kernelFile = e.type === \"kernel\" && await ctx.host.fds.kind(fd, e) === \"file\";\n if (e.type !== \"file\" && !kernelFile) throw new EmError(43);\n const shared = (flags & MAP_TYPE) !== MAP_PRIVATE && (prot & PROT_WRITE) !== 0;\n if (shared) throw new EmError(43);\n if (e.type === \"file\" && !e.file.readable) throw new EmError(2);\n if (len <= 0) return -EM.INVAL;\n const memalign = ctx.exports().emscripten_builtin_memalign;\n if (!memalign) return -EM.NOMEM;\n const data = new Uint8Array(len);\n const done = await readAt(ctx, fd, data, position);\n const size = Math.ceil(len / MAP_ALIGN) * MAP_ALIGN;\n const ptr = memalign(MAP_ALIGN, size);\n if (!ptr) return -EM.NOMEM;\n const target = ctx.mem.bytes(ptr, size);\n target.fill(0);\n target.set(data.subarray(0, done));\n const v = ctx.mem.view();\n v.setInt32(allocated, 1, true);\n v.setUint32(addr, ptr, true);\n return 0;\n }\n )\n };\n}\n\n// src/process/emscripten/proc.ts\nvar WNOHANG = 1;\nvar WUNTRACED = 2;\nvar WCONTINUED = 8;\nvar IDS2 = [\"ruid\", \"euid\", \"suid\", \"rgid\", \"egid\", \"sgid\"];\nfunction strings(ctx, ptr) {\n const out = [];\n if (!ptr) return out;\n const v = ctx.mem.view();\n for (let i = 0; ; i++) {\n const s = v.getUint32(ptr + i * 4, true);\n if (!s) break;\n out.push(ctx.mem.cString(s));\n }\n return out;\n}\nfunction envOf(ctx, ptr) {\n if (!ptr) return null;\n const env = {};\n for (const kv of strings(ctx, ptr)) {\n const eq = kv.indexOf(\"=\");\n if (eq > 0) env[kv.slice(0, eq)] = kv.slice(eq + 1);\n }\n return env;\n}\nasync function restartedCall(ctx, req) {\n for (; ; ) {\n try {\n return await ctx.call(req);\n } catch (e) {\n if (e.code !== \"EINTR\") throw e;\n }\n }\n}\nasync function slot(ctx, fd) {\n const e = fd >= 0 ? await ctx.host.fds.find(fd) : void 0;\n if (!e) return { none: true };\n if (e.type === \"kernel\") return { fd };\n if (e.type === \"dir\") return { dir: e.path };\n if (e.type === \"device\") return { device: e.device, ...e.access ? { access: e.access } : {} };\n return { none: true };\n}\nfunction inherited(ctx, actions) {\n const { fds } = ctx.host;\n const table = /* @__PURE__ */ new Map();\n for (const entry of fds.snapshot()) {\n const cloexec = fds.cloexec.has(entry.fd);\n if (entry.type === \"kernel\")\n table.set(entry.fd, { slot: { fd: entry.fd, kernel: entry.fd }, cloexec });\n else if (entry.type === \"device\") {\n const access3 = entry.access ? { access: entry.access } : {};\n table.set(entry.fd, { slot: { fd: entry.fd, device: entry.device, ...access3 }, cloexec });\n } else table.set(entry.fd, { slot: void 0, cloexec });\n }\n for (const [target, source] of actions) {\n if (target <= 2) continue;\n const from = source >= 0 ? table.get(source) : void 0;\n if (from?.slot) {\n const moved = \"kernel\" in from.slot ? { fd: target, kernel: from.slot.kernel } : { ...from.slot, fd: target };\n table.set(target, { slot: moved, cloexec: false });\n } else table.delete(target);\n }\n const out = [];\n for (const [fd, { slot: s, cloexec }] of table) {\n if (fd > 2 && !cloexec && s) out.push(s);\n }\n return out;\n}\nasync function kernelWait(ctx, pid, nohang, options = 0) {\n const req = {\n op: \"proc-wait\",\n pid,\n nohang,\n ...options & WUNTRACED ? { untraced: true } : {},\n ...options & WCONTINUED ? { continued: true } : {}\n };\n for (; ; ) {\n try {\n const waited = await ctx.call(req) ?? [0, 0];\n if (waited[0] > 0) ctx.host.o.fs.invalidate?.();\n return [waited[0], waited[1]];\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n if (errno === 27 && ctx.gate.restartable()) continue;\n return -errno;\n }\n }\n}\nasync function execWait(ctx, pid) {\n try {\n const r = await ctx.call({ op: \"proc-exec\", pid });\n ctx.host.o.fs.invalidate?.();\n return r ? r[1] : 0;\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n}\nasync function spawnChild(ctx, req) {\n const { fds } = ctx.host;\n try {\n await fds.flushAll();\n await fds.promoteFiles();\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n const stdio = [];\n for (let n = 0; n < 3; n++) stdio.push(await slot(ctx, req.stdio[n] ?? -1));\n const inherit = inherited(ctx, req.actions);\n const spawn = {\n op: \"proc-spawn\",\n file: req.file,\n argv: req.argv,\n env: req.env ?? ctx.init.env,\n cwd: req.cwd ?? ctx.cwd.path,\n ...req.cwd !== null ? { chdir: true } : {},\n stdio,\n ...inherit.length > 0 ? { inherit } : {},\n ...req.exec ? { exec: true } : {},\n restart: true\n };\n try {\n return await restartedCall(ctx, spawn);\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n } finally {\n ctx.host.o.fs.invalidate?.();\n }\n}\nfunction throughKernel(sig) {\n if (sig === 0) return false;\n const action = defaultAction(sig);\n return action === \"terminate\" || action === \"stop\";\n}\nasync function status(ctx, req) {\n try {\n await ctx.call(req);\n return 0;\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n}\nasync function numberOf(ctx, req) {\n try {\n const r = await ctx.call(req);\n return typeof r === \"number\" ? r : -EM.IO;\n } catch (e) {\n const errno = errnoOf(e);\n if (errno === void 0) throw e;\n return -errno;\n }\n}\nasync function terminal(ctx, fd) {\n return (await ctx.host.fds.find(fd))?.type === \"kernel\";\n}\nasync function jobs(ctx, op, a, b) {\n switch (op) {\n case 0:\n return await status(ctx, { op: \"proc-setpgid\", pid: a, pgid: b });\n case 1:\n return await numberOf(ctx, { op: \"proc-getpgid\", pid: a });\n case 2:\n return await numberOf(ctx, { op: \"proc-getsid\", pid: a });\n case 3:\n return await numberOf(ctx, { op: \"proc-setsid\" });\n case 4:\n return await terminal(ctx, a) ? await numberOf(ctx, { op: \"tty-pgrp-get\", fd: a }) : -EM.NOTTY;\n case 5:\n return await terminal(ctx, a) ? await status(ctx, { op: \"tty-pgrp-set\", fd: a, pgrp: b }) : -EM.NOTTY;\n }\n return -EM.NOSYS;\n}\nasync function credOf2(ctx) {\n return await ctx.call({ op: \"proc-cred\" });\n}\nfunction procImports(ctx, state) {\n const { mem } = ctx;\n const cred = ctx.host.sliccImports();\n return {\n slicc_spawn_capture_js: async (path, argv, envp, cwd, inFd, outFd, errFd, actions, nactions) => {\n const file = mem.cString(path);\n if (!file) return -EM.NOENT;\n const pairs = [];\n const v = mem.view();\n for (let i = 0; i < nactions; i++) {\n pairs.push([v.getInt32(actions + 8 * i, true), v.getInt32(actions + 8 * i + 4, true)]);\n }\n return await spawnChild(ctx, {\n file,\n argv: strings(ctx, argv),\n env: envOf(ctx, envp),\n cwd: cwd ? mem.cString(cwd) : null,\n stdio: [inFd === -2 ? 0 : inFd, outFd, errFd],\n actions: pairs,\n exec: false\n });\n },\n slicc_wait_js: async (pid, statusPtr, options) => {\n const r = await kernelWait(ctx, pid, (options & WNOHANG) !== 0, options);\n if (typeof r === \"number\") return r;\n if (statusPtr && r[0] > 0) mem.view().setInt32(statusPtr, r[1], true);\n return r[0];\n },\n slicc_exec_detach: () => 0,\n slicc_exec_wait_js: async (pid) => await execWait(ctx, pid),\n slicc_execve_js: async (path, argv, envp) => {\n const file = mem.cString(path);\n if (!file) return -EM.NOENT;\n const pid = await spawnChild(ctx, {\n file,\n argv: strings(ctx, argv),\n env: envOf(ctx, envp),\n cwd: null,\n stdio: [0, 1, 2],\n actions: [],\n exec: true\n });\n if (pid < 0) return pid;\n return await execWait(ctx, pid);\n },\n slicc_in_emulated_fork: () => 0,\n slicc_getpid_js: () => ctx.pid,\n slicc_getppid_js: async () => (await identify(ctx.transport, ctx.init)).ppid,\n slicc_default_getpid_js: () => ctx.pid | 0 || 42,\n slicc_default_getppid_js: () => ctx.ppid | 0 || 1,\n slicc_kill_js: async (pid, sig) => {\n if (pid === ctx.init.pid && !throughKernel(sig)) {\n if (sig !== 0) await state.raise(sig);\n return 0;\n }\n return await status(ctx, { op: \"proc-kill\", pid, sig });\n },\n slicc_pause_js: async () => await status(ctx, { op: \"sig-pause\" }),\n slicc_sig_inherited_js: async () => {\n try {\n const bits = await inheritedSignals(ctx.transport);\n state.seeded.bits |= bits;\n return bits | 0;\n } catch {\n return 0;\n }\n },\n slicc_jobs_js: async (op, a, b) => await jobs(ctx, op, a, b),\n slicc_cred_js: negated(async (out) => {\n const c = await credOf2(ctx);\n const v = mem.view();\n for (let i = 0; i < IDS2.length; i++) v.setUint32(out + i * 4, c[IDS2[i]] >>> 0, true);\n }),\n slicc_groups_js: negated(async (list, cap) => {\n const { groups } = await credOf2(ctx);\n if (cap === 0) return groups.length;\n if (cap < groups.length) return -EM.INVAL;\n const v = mem.view();\n for (let i = 0; i < groups.length; i++)\n v.setUint32(list + i * 4, groups[i] >>> 0, true);\n return groups.length;\n }),\n slicc_setcred_js: async (...ids) => {\n const set = cred.cred_set;\n const r = await set(...ids);\n return r === 0 ? 0 : -r;\n },\n slicc_setgroups_js: async (list, n) => {\n const set = cred.groups_set;\n const r = await set(list, n);\n return r === 0 ? 0 : -r;\n },\n slicc_sleep_ms: async (ms) => {\n await holdStopped(ctx);\n await sleepIn(ctx, ms);\n await afterStopped(ctx);\n }\n };\n}\n\n// src/process/emscripten/pthread.ts\nvar DEFAULT_STACK = 65536;\nasync function canBlock() {\n try {\n await atomicsWait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n return true;\n } catch {\n return false;\n }\n}\nasync function initMainThread(ctx, self) {\n const ex = ctx.exports();\n const blocks = await canBlock();\n const init = ex._emscripten_thread_init;\n if (typeof init === \"function\") {\n const args = [self, blocks ? 0 : 1, 1, blocks ? 1 : 0, DEFAULT_STACK, 0];\n await ctx.enter(\"_emscripten_thread_init\", init, args);\n }\n const tls = ex._emscripten_tls_init;\n if (typeof tls === \"function\") await ctx.enter(\"_emscripten_tls_init\", tls, []);\n}\nfunction pthreadImports(ctx) {\n const nothing = () => {\n };\n return {\n _emscripten_init_main_thread_js: async (self) => await initMainThread(ctx, self),\n __pthread_create_js: () => EM.AGAIN,\n _emscripten_thread_set_strongref: nothing,\n _emscripten_thread_mailbox_await: nothing,\n _emscripten_thread_cleanup: nothing,\n _emscripten_notify_mailbox_postmessage: nothing,\n _emscripten_receive_on_main_thread_js: () => 0,\n emscripten_check_blocking_allowed: nothing,\n emscripten_exit_with_live_runtime: async () => await ctx.exit(0)\n };\n}\n\n// src/process/emscripten/reentry.ts\nvar UNWINDING2 = 1;\nvar Reentry = class {\n stack = [];\n state = () => 0;\n stopUnwind = () => {\n };\n unwound;\n bind(exports) {\n const state = exports.asyncify_get_state;\n const stop = exports.asyncify_stop_unwind;\n if (typeof state === \"function\") this.state = state;\n if (typeof stop === \"function\") this.stopUnwind = stop;\n }\n async enter(name2, fn, args) {\n this.stack.push(name2);\n try {\n return await reentered(fn)(...args);\n } finally {\n this.stack.pop();\n if (this.stack.length === 0 && await this.state() === UNWINDING2) {\n await this.stopUnwind();\n this.unwound = name2;\n }\n }\n }\n};\n\n// src/process/emscripten/time.ts\nvar TZ_GROUPS = [\n [\n \"Europe/London Europe/Belfast Europe/Guernsey Europe/Isle_of_Man Europe/Jersey GB GB-Eire\",\n { \"0\": \"GMT\", d3600: \"BST\" }\n ],\n [\"Europe/Dublin Eire\", { \"0\": \"GMT\", d3600: \"IST\" }],\n [\n \"Europe/Lisbon Portugal Atlantic/Madeira Atlantic/Canary Atlantic/Faroe Atlantic/Faeroe WET\",\n { \"0\": \"WET\", d3600: \"WEST\" }\n ],\n [\n \"Europe/Amsterdam Europe/Andorra Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Budapest Europe/Busingen Europe/Copenhagen Europe/Gibraltar Europe/Ljubljana Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Monaco Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Rome Europe/San_Marino Europe/Sarajevo Europe/Skopje Europe/Stockholm Europe/Tirane Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Warsaw Europe/Zagreb Europe/Zurich Africa/Ceuta Africa/Algiers Africa/Tunis Arctic/Longyearbyen Atlantic/Jan_Mayen Poland CET MET\",\n { \"3600\": \"CET\", d7200: \"CEST\" }\n ],\n [\n \"Europe/Athens Europe/Bucharest Europe/Chisinau Europe/Helsinki Europe/Kiev Europe/Kyiv Europe/Mariehamn Europe/Riga Europe/Sofia Europe/Tallinn Europe/Tiraspol Europe/Uzhgorod Europe/Vilnius Europe/Zaporozhye Europe/Nicosia Europe/Kaliningrad Asia/Beirut Asia/Nicosia Africa/Cairo Egypt EET\",\n { \"7200\": \"EET\", d10800: \"EEST\" }\n ],\n [\"Europe/Moscow Europe/Simferopol Europe/Kirov Europe/Volgograd W-SU\", { \"10800\": \"MSK\" }],\n [\"Asia/Jerusalem Asia/Tel_Aviv Israel\", { \"7200\": \"IST\", d10800: \"IDT\" }],\n [\"Asia/Kolkata Asia/Calcutta\", { \"19800\": \"IST\" }],\n [\"Asia/Karachi\", { \"18000\": \"PKT\", d21600: \"PKST\", since: 31536e3 }],\n [\"Asia/Tokyo Japan\", { \"32400\": \"JST\", d36000: \"JDT\" }],\n [\"Asia/Seoul Asia/Pyongyang ROK\", { \"32400\": \"KST\", d36000: \"KDT\" }],\n [\n \"Asia/Shanghai Asia/Chongqing Asia/Chungking Asia/Harbin Asia/Taipei Asia/Macau Asia/Macao PRC ROC\",\n { \"28800\": \"CST\", d32400: \"CDT\" }\n ],\n [\"Asia/Manila\", { \"28800\": \"PST\", d32400: \"PDT\" }],\n [\"Asia/Hong_Kong Hongkong\", { \"28800\": \"HKT\", d32400: \"HKST\" }],\n [\"Asia/Jakarta Asia/Pontianak\", { \"25200\": \"WIB\" }],\n [\"Asia/Makassar Asia/Ujung_Pandang\", { \"28800\": \"WITA\" }],\n [\"Asia/Jayapura\", { \"32400\": \"WIT\" }],\n [\n \"Australia/Sydney Australia/Melbourne Australia/Hobart Australia/Canberra Australia/ACT Australia/NSW Australia/Victoria Australia/Tasmania Australia/Currie Australia/Brisbane Australia/Lindeman Australia/Queensland Antarctica/Macquarie\",\n { \"36000\": \"AEST\", d39600: \"AEDT\" }\n ],\n [\n \"Australia/Adelaide Australia/Broken_Hill Australia/South Australia/Yancowinna Australia/Darwin Australia/North\",\n { \"34200\": \"ACST\", d37800: \"ACDT\" }\n ],\n [\"Australia/Perth Australia/West\", { \"28800\": \"AWST\", d32400: \"AWDT\" }],\n [\n \"Pacific/Auckland Antarctica/McMurdo Antarctica/South_Pole NZ\",\n { \"43200\": \"NZST\", d46800: \"NZDT\" }\n ],\n [\"Pacific/Guam Pacific/Saipan\", { \"36000\": \"ChST\", since: 977493600 }],\n [\"Africa/Windhoek\", { \"7200\": \"CAT\", since: 637365600 }],\n [\"Asia/Gaza Asia/Hebron\", { \"7200\": \"EET\", d10800: \"EEST\", since: 820454400 }],\n [\"Pacific/Pago_Pago Pacific/Midway Pacific/Samoa US/Samoa\", { \"-39600\": \"SST\" }],\n [\"America/Adak America/Atka US/Aleutian\", { \"-36000\": \"HST\", \"d-32400\": \"HDT\" }],\n [\n \"America/Hermosillo America/Mazatlan America/Chihuahua America/Ciudad_Juarez America/Ojinaga America/Dawson America/Whitehorse Mexico/BajaSur Canada/Yukon\",\n { \"-25200\": \"MST\", \"d-21600\": \"MDT\", intl: 1 }\n ],\n [\"America/Havana Cuba\", { \"-18000\": \"CST\", \"d-14400\": \"CDT\" }],\n [\n \"Etc/GMT Etc/GMT0 Etc/GMT+0 Etc/GMT-0 Etc/Greenwich GMT GMT0 GMT+0 GMT-0 Greenwich\",\n { \"0\": \"GMT\" }\n ],\n [\"Antarctica/Troll\", { \"0\": \"+00\", d7200: \"+02\" }],\n [\"America/St_Johns Canada/Newfoundland\", { \"-12600\": \"NST\", \"d-9000\": \"NDT\" }],\n [\"Africa/Johannesburg Africa/Maseru Africa/Mbabane\", { \"7200\": \"SAST\" }],\n [\n \"Africa/Maputo Africa/Blantyre Africa/Bujumbura Africa/Gaborone Africa/Harare Africa/Kigali Africa/Lubumbashi Africa/Lusaka\",\n { \"7200\": \"CAT\" }\n ],\n [\"Africa/Juba Africa/Khartoum\", { \"7200\": \"CAT\", \"10800\": \"EAT\" }],\n [\n \"Africa/Nairobi Africa/Addis_Ababa Africa/Asmara Africa/Asmera Africa/Dar_es_Salaam Africa/Djibouti Africa/Kampala Africa/Mogadishu Indian/Antananarivo Indian/Comoro Indian/Mayotte\",\n { \"10800\": \"EAT\" }\n ],\n [\n \"Africa/Lagos Africa/Bangui Africa/Brazzaville Africa/Douala Africa/Kinshasa Africa/Libreville Africa/Luanda Africa/Malabo Africa/Niamey Africa/Porto-Novo Africa/Ndjamena\",\n { \"3600\": \"WAT\" }\n ]\n];\nvar tzTable;\nfunction zones() {\n if (tzTable) return tzTable;\n const table = /* @__PURE__ */ new Map();\n for (const [names2, labels] of TZ_GROUPS) {\n for (const zone of names2.split(\" \")) table.set(zone, labels);\n }\n tzTable = table;\n return table;\n}\nvar lows = /* @__PURE__ */ new Map();\nvar MONTH = 2629800;\nfunction tzIntl(zone, t) {\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n timeZoneName: \"short\"\n });\n const at = (s) => {\n const parts = {};\n for (const p of fmt.formatToParts(new Date(s * 1e3))) parts[p.type] = p.value;\n const wall = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n ) / 1e3;\n return { off: Math.round(wall - s), name: parts.timeZoneName ?? \"\" };\n };\n const now = at(t);\n const canon = fmt.resolvedOptions().timeZone;\n const names2 = zones().get(zone) ?? zones().get(canon);\n const key = `${zone}|${Math.floor(t / 86400)}`;\n let low = lows.get(key);\n if (!low) {\n low = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];\n for (let m = 1; m <= 12; m++) {\n low[0] = Math.min(low[0], at(t - m * MONTH).off);\n low[1] = Math.min(low[1], at(t + m * MONTH).off);\n }\n if (lows.size > 4096) lows.clear();\n lows.set(key, low);\n }\n const dst = now.off > low[0] && now.off > low[1] ? 1 : 0;\n const since = names2?.since;\n const fixed = names2 && !(typeof since === \"number\" && t < since) ? names2[`${dst ? \"d\" : \"\"}${now.off}`] : void 0;\n const fixedLabel = typeof fixed === \"string\" ? fixed : void 0;\n let label = fixedLabel && !names2?.intl ? fixedLabel : /^[A-Za-z]{3,5}$/.test(now.name) ? now.name : fixedLabel;\n if (!label) {\n const a = Math.abs(now.off);\n const hh = String(Math.floor(a / 3600)).padStart(2, \"0\");\n const mm = Math.floor(a / 60) % 60;\n label = `${now.off < 0 ? \"-\" : \"+\"}${hh}${mm ? String(mm).padStart(2, \"0\") : \"\"}`;\n }\n return { value: now.off * 2 + dst, label };\n}\nvar LEAP = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\nvar REGULAR = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];\nfunction leap(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nfunction yday(date) {\n const table = leap(date.getFullYear()) ? LEAP : REGULAR;\n return table[date.getMonth()] + date.getDate() - 1;\n}\nfunction i53(value2) {\n return value2 < -9007199254740992n || value2 > 9007199254740992n ? Number.NaN : Number(value2);\n}\nfunction zoneName(offset) {\n const sign = offset >= 0 ? \"-\" : \"+\";\n const abs = Math.abs(offset);\n return `UTC${sign}${String(Math.floor(abs / 60)).padStart(2, \"0\")}${String(abs % 60).padStart(2, \"0\")}`;\n}\nvar ALIASES = {\n A: \"%a\",\n B: \"%b\",\n c: \"%a %b %d %H:%M:%S %Y\",\n D: \"%m\\\\/%d\\\\/%y\",\n e: \"%d\",\n F: \"%Y-%m-%d\",\n h: \"%b\",\n R: \"%H\\\\:%M\",\n r: \"%I\\\\:%M\\\\:%S\\\\s%p\",\n T: \"%H\\\\:%M\\\\:%S\",\n x: \"%m\\\\/%d\\\\/(?:%y|%Y)\",\n X: \"%H\\\\:%M\\\\:%S\"\n};\nvar FIELDS = {\n a: \"(?:Sun(?:day)?)|(?:Mon(?:day)?)|(?:Tue(?:sday)?)|(?:Wed(?:nesday)?)|(?:Thu(?:rsday)?)|(?:Fri(?:day)?)|(?:Sat(?:urday)?)\",\n b: \"(?:Jan(?:uary)?)|(?:Feb(?:ruary)?)|(?:Mar(?:ch)?)|(?:Apr(?:il)?)|May|(?:Jun(?:e)?)|(?:Jul(?:y)?)|(?:Aug(?:ust)?)|(?:Sep(?:tember)?)|(?:Oct(?:ober)?)|(?:Nov(?:ember)?)|(?:Dec(?:ember)?)\",\n C: \"\\\\d\\\\d\",\n d: \"0[1-9]|[1-9](?!\\\\d)|1\\\\d|2\\\\d|30|31\",\n H: \"\\\\d(?!\\\\d)|[0,1]\\\\d|20|21|22|23\",\n I: \"\\\\d(?!\\\\d)|0\\\\d|10|11|12\",\n j: \"00[1-9]|0?[1-9](?!\\\\d)|0?[1-9]\\\\d(?!\\\\d)|[1,2]\\\\d\\\\d|3[0-6]\\\\d\",\n m: \"0[1-9]|[1-9](?!\\\\d)|10|11|12\",\n M: \"0\\\\d|\\\\d(?!\\\\d)|[1-5]\\\\d\",\n n: \" \",\n p: \"AM|am|PM|pm|A\\\\.M\\\\.|a\\\\.m\\\\.|P\\\\.M\\\\.|p\\\\.m\\\\.\",\n S: \"0\\\\d|\\\\d(?!\\\\d)|[1-5]\\\\d|60\",\n U: \"0\\\\d|\\\\d(?!\\\\d)|[1-4]\\\\d|50|51|52|53\",\n W: \"0\\\\d|\\\\d(?!\\\\d)|[1-4]\\\\d|50|51|52|53\",\n w: \"[0-6]\",\n y: \"\\\\d\\\\d\",\n Y: \"\\\\d\\\\d\\\\d\\\\d\",\n t: \" \",\n z: \"Z|(?:[\\\\+\\\\-]\\\\d\\\\d:?(?:\\\\d\\\\d)?)\"\n};\nvar ESCAPED = /[\\\\!@#$^&*()+=\\-[\\]/{}|:<>?,.]/g;\nvar MONTHS = [\"JAN\", \"FEB\", \"MAR\", \"APR\", \"MAY\", \"JUN\", \"JUL\", \"AUG\", \"SEP\", \"OCT\", \"NOV\", \"DEC\"];\nvar DAYS = [\"SUN\", \"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\"];\nfunction parsePattern(format) {\n const fields = [];\n const source = format.replace(ESCAPED, \"\\\\$&\").replace(/%(.)/g, (whole, c) => ALIASES[c] || whole).replace(/%(.)/g, (_, c) => {\n const field2 = FIELDS[c];\n if (!field2) return c;\n fields.push(c);\n return `(${field2})`;\n }).replace(/\\s+/g, \"\\\\s*\");\n return { pattern: new RegExp(`^${source}`, \"i\"), fields };\n}\nfunction within2(value2, min, max) {\n return Number.isNaN(value2) || value2 < min ? min : Math.min(value2, max);\n}\nfunction weekDate(year, week, day, first) {\n const lead = new Date(year, 0, 1).getDay();\n const before = lead === first ? 0 : 7 - lead + first;\n return new Date(year, 0, 1 + Math.max(0, before + day + 7 * (week - 1)));\n}\nfunction offsetOf2(zone) {\n if (zone.toLowerCase() === \"z\") return 0;\n const [, hours, minutes] = /^([-+]\\d\\d):?(\\d\\d)?/.exec(zone);\n const base = Number(hours) * 3600;\n return minutes ? base + (base > 0 ? 60 : -60) * Number(minutes) : base;\n}\nfunction yearOf(num, fallback) {\n const short = num(\"y\");\n if (num(\"Y\") !== void 0 || short === void 0) return num(\"Y\") ?? fallback;\n const century = num(\"C\");\n return short + (century !== void 0 ? century * 100 : short < 69 ? 2e3 : 1900);\n}\nfunction monthOf(num, name2, fallback) {\n const month = num(\"m\");\n if (month !== void 0) return month - 1;\n return name2 ? Math.max(0, MONTHS.indexOf(name2.slice(0, 3).toUpperCase())) : fallback;\n}\nfunction weekDay(num, name2, year) {\n const at = DAYS.indexOf(name2.slice(0, 3).toUpperCase());\n const sunday = num(\"U\");\n if (sunday !== void 0) return weekDate(year, sunday, at, 0);\n const monday = num(\"W\");\n return monday === void 0 ? void 0 : weekDate(year, monday, (at + 6) % 7, 1);\n}\nfunction dayOf(num, name2, at) {\n const day = num(\"d\");\n if (day !== void 0) return { month: at.month, day };\n const ofYear = num(\"j\");\n if (ofYear !== void 0) {\n const fits = ofYear <= (leap(at.year) ? 366 : 365);\n const december = (leap(at.year) ? LEAP : REGULAR)[11];\n return { month: at.month, day: fits ? ofYear - december : at.day };\n }\n const date = name2 ? weekDay(num, name2, at.year) : void 0;\n return date ? { month: date.getMonth(), day: date.getDate() } : at;\n}\nfunction hourOf(num, half, fallback) {\n const hour = num(\"I\");\n if (num(\"H\") !== void 0 || hour === void 0) return num(\"H\") ?? fallback;\n return hour + (half.toUpperCase().startsWith(\"P\") ? 12 : 0);\n}\nfunction strptime(ctx, buf, format, tm) {\n const { mem } = ctx;\n const i32 = (at) => mem.view().getInt32(at, true);\n const put = (at, value2) => mem.view().setInt32(at, value2, true);\n const { pattern, fields } = parsePattern(mem.cString(format));\n const found = pattern.exec(mem.cString(buf));\n if (!found) return 0;\n const got = (field2) => fields.includes(field2) && found[fields.indexOf(field2) + 1] || \"\";\n const num = (field2) => got(field2) ? Number(got(field2)) : void 0;\n const year = yearOf(num, within2(i32(tm + 20) + 1900, 1970, 9999));\n const month = monthOf(num, got(\"b\"), within2(i32(tm + 16), 0, 11));\n const on = dayOf(num, got(\"a\"), { year, month, day: within2(i32(tm + 12), 1, 31) });\n const hour = hourOf(num, got(\"p\"), within2(i32(tm + 8), 0, 23));\n const minute = num(\"M\") ?? within2(i32(tm + 4), 0, 59);\n const second = num(\"S\") ?? within2(i32(tm), 0, 59);\n const date = new Date(year, on.month, on.day, hour, minute, second, 0);\n put(tm, date.getSeconds());\n put(tm + 4, date.getMinutes());\n put(tm + 8, date.getHours());\n put(tm + 12, date.getDate());\n put(tm + 16, date.getMonth());\n put(tm + 20, date.getFullYear() - 1900);\n put(tm + 24, date.getDay());\n put(tm + 28, yday(date));\n put(tm + 32, 0);\n put(tm + 36, got(\"z\") ? offsetOf2(got(\"z\")) : 0);\n return buf + new TextEncoder().encode(found[0]).length;\n}\nfunction timeImports(ctx) {\n const { mem } = ctx;\n const i32 = (at) => mem.view().getInt32(at, true);\n const put = (at, value2) => mem.view().setInt32(at, value2, true);\n return {\n emscripten_date_now: () => {\n lookedOutside();\n return Date.now();\n },\n emscripten_get_now: () => {\n lookedOutside();\n return performance.now();\n },\n _tzset_js: (timezone, daylight, std, dst) => {\n const year = (/* @__PURE__ */ new Date()).getFullYear();\n const winter = new Date(year, 0, 1).getTimezoneOffset();\n const summer = new Date(year, 6, 1).getTimezoneOffset();\n mem.view().setUint32(timezone, Math.max(winter, summer) * 60, true);\n put(daylight, Number(winter !== summer));\n const winterName = zoneName(winter);\n const summerName = zoneName(summer);\n if (summer < winter) {\n putString(mem, std, winterName, 17);\n putString(mem, dst, summerName, 17);\n } else {\n putString(mem, dst, winterName, 17);\n putString(mem, std, summerName, 17);\n }\n },\n _localtime_js: (time, tm) => {\n const date = new Date(i53(time) * 1e3);\n put(tm, date.getSeconds());\n put(tm + 4, date.getMinutes());\n put(tm + 8, date.getHours());\n put(tm + 12, date.getDate());\n put(tm + 16, date.getMonth());\n put(tm + 20, date.getFullYear() - 1900);\n put(tm + 24, date.getDay());\n put(tm + 28, yday(date) | 0);\n put(tm + 36, -(date.getTimezoneOffset() * 60));\n const summer = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n const winter = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();\n const isDst = summer !== winter && date.getTimezoneOffset() === Math.min(winter, summer) ? 1 : 0;\n put(tm + 32, isDst);\n },\n _gmtime_js: (time, tm) => {\n const date = new Date(i53(time) * 1e3);\n put(tm, date.getUTCSeconds());\n put(tm + 4, date.getUTCMinutes());\n put(tm + 8, date.getUTCHours());\n put(tm + 12, date.getUTCDate());\n put(tm + 16, date.getUTCMonth());\n put(tm + 20, date.getUTCFullYear() - 1900);\n put(tm + 24, date.getUTCDay());\n const start2 = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);\n put(tm + 28, (date.getTime() - start2) / 864e5 | 0);\n },\n _mktime_js: (tm) => {\n const date = new Date(\n i32(tm + 20) + 1900,\n i32(tm + 16),\n i32(tm + 12),\n i32(tm + 8),\n i32(tm + 4),\n i32(tm),\n 0\n );\n const dst = i32(tm + 32);\n const guessed = date.getTimezoneOffset();\n const start2 = new Date(date.getFullYear(), 0, 1);\n const summer = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n const winter = start2.getTimezoneOffset();\n const dstOffset = Math.min(winter, summer);\n if (dst < 0) {\n put(tm + 32, Number(summer !== winter && dstOffset === guessed));\n } else if (dst > 0 !== (dstOffset === guessed)) {\n const nonDst = Math.max(winter, summer);\n const trueOffset = dst > 0 ? dstOffset : nonDst;\n date.setTime(date.getTime() + (trueOffset - guessed) * 6e4);\n }\n put(tm + 24, date.getDay());\n put(tm + 28, yday(date) | 0);\n put(tm, date.getSeconds());\n put(tm + 4, date.getMinutes());\n put(tm + 8, date.getHours());\n put(tm + 12, date.getDate());\n put(tm + 16, date.getMonth());\n put(tm + 20, date.getFullYear() - 1900);\n const ms = date.getTime();\n return BigInt(Number.isNaN(ms) ? -1 : Math.trunc(ms / 1e3));\n },\n _timegm_js: (tm) => {\n const time = Date.UTC(\n i32(tm + 20) + 1900,\n i32(tm + 16),\n i32(tm + 12),\n i32(tm + 8),\n i32(tm + 4),\n i32(tm),\n 0\n );\n const date = new Date(time);\n put(tm + 24, date.getUTCDay());\n const start2 = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);\n put(tm + 28, (date.getTime() - start2) / 864e5 | 0);\n return BigInt(Math.trunc(date.getTime() / 1e3));\n },\n strptime: (buf, format, tm) => strptime(ctx, buf, format, tm),\n slicc_tz_intl: (name2, t, abbr, abbrlen) => {\n try {\n const { value: value2, label } = tzIntl(mem.cString(name2), t);\n if (abbr) putString(mem, abbr, label, abbrlen);\n return value2;\n } catch {\n return 2147483647;\n }\n }\n };\n}\n\n// src/process/emscripten/runtime.ts\nvar NOT_RUNNABLE = 126;\nvar HEAP_MAX = 2147483648;\nfunction procTree2(call2, pid) {\n return new ProcTree(\n {\n procList: async () => await call2({ op: \"proc-list\" }),\n mountList: async () => await call2({ op: \"mount-list\" })\n },\n pid\n );\n}\nfunction ownersOf2(init) {\n return {\n ...init.owners ? { owners: true } : {},\n ...init.links ? { links: true } : {},\n ...init.changes ? { changes: init.changes } : {}\n };\n}\nvar O_NONBLOCK4 = 2048;\nvar O_APPEND4 = 1024;\nasync function stdioEntries(init, call2) {\n const fds = [];\n const cloexec = [];\n for (let fd = 0; fd < 3; fd++) {\n let info;\n try {\n info = await call2({ op: \"fd-info\", fd });\n } catch {\n info = void 0;\n }\n const dir = info?.meta?.dir;\n if (dir !== void 0) fds.push({ fd, type: \"dir\", path: dir });\n else fds.push({ fd, type: \"kernel\", nonblock: false, append: false });\n }\n for (const entry of init.fds ?? []) {\n if (entry.fd <= 2) continue;\n if (entry.device) {\n const access3 = entry.device.access ? { access: entry.device.access } : {};\n fds.push({ fd: entry.fd, type: \"device\", device: entry.device.device, ...access3 });\n } else {\n const flags = entry.flags ?? 0;\n fds.push({\n fd: entry.fd,\n type: \"kernel\",\n nonblock: (flags & O_NONBLOCK4) !== 0,\n append: (flags & O_APPEND4) !== 0\n });\n }\n if (entry.cloexec) cloexec.push(entry.fd);\n }\n return { fds, cloexec };\n}\nvar PROVIDED_ELSEWHERE = /* @__PURE__ */ new Set([\"memory\"]);\nfunction missingImports(module, imports) {\n const missing3 = [];\n for (const imp of WebAssembly.Module.imports(module)) {\n const ns = imports[imp.module];\n if (imp.kind === \"function\" && typeof ns?.[imp.name] === \"function\") continue;\n if (imp.kind !== \"function\" && PROVIDED_ELSEWHERE.has(imp.kind) && ns?.[imp.name]) continue;\n missing3.push(`${imp.module}.${imp.name}`);\n }\n return missing3;\n}\nfunction importsCred(module) {\n for (const imp of WebAssembly.Module.imports(module)) {\n if (imp.module === \"env\" && imp.name === \"slicc_cred_js\") return true;\n }\n return false;\n}\nvar EmRuntime = class {\n reentry = new Reentry();\n ex;\n up = false;\n exiting = false;\n seeded = { bits: 0 };\n fork;\n ctx;\n exports() {\n if (!this.ex) throw new Error(\"emscripten: no instance yet\");\n return this.ex;\n }\n bind(exports, imported) {\n const own = exports;\n this.ex = imported && !own.memory ? { ...own, memory: imported } : own;\n this.reentry.bind(exports);\n }\n async enter(name2, fn, args) {\n return await this.reentry.enter(name2, fn, args);\n }\n masks() {\n const mask = this.ex?.slicc_sig_mask;\n const sliccSigMask = (w) => this.up && mask ? mask(w) : -1;\n return signalMasks({ sliccSigMask }, this.seeded);\n }\n async raise(sig) {\n const fn = this.ex?.slicc_raise;\n if (this.up && typeof fn === \"function\") await this.enter(\"slicc_raise\", fn, [sig]);\n }\n async timer(which) {\n const fn = this.ex?._emscripten_timeout;\n if (!this.up || typeof fn !== \"function\") {\n await this.raise(SIG.ALRM);\n return;\n }\n await this.enter(\"_emscripten_timeout\", fn, [which, performance.now()]);\n }\n async exit(status2) {\n if (!this.exiting) {\n this.exiting = true;\n const atexit = this.ex?.__funcs_on_exit;\n const quit = this.ctx?.quit;\n if (quit) quit.atExit = true;\n if (typeof atexit === \"function\") await this.enter(\"__funcs_on_exit\", atexit, []);\n const flush = this.ex?.fflush;\n if (typeof flush === \"function\") await this.enter(\"fflush\", flush, [0]);\n if (this.ctx) await commitStdout(this.ctx);\n if (quit) quit.atExit = false;\n this.up = false;\n }\n throw new WasiExit(this.ctx?.quit.failed && status2 === 0 ? 1 : status2);\n }\n};\nasync function abort(ctx, what) {\n await ctx.say(`Aborted(${what})`);\n throw new WebAssembly.RuntimeError(`Aborted(${what}). Build with -sASSERTIONS for more info.`);\n}\nfunction resizeHeap(ctx, requested) {\n const memory = ctx.exports().memory;\n const old = memory.buffer.byteLength;\n const size = requested >>> 0;\n if (size > HEAP_MAX) return 0;\n for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {\n let over = old * (1 + 0.2 / cutDown);\n over = Math.min(over, size + 100663296);\n const next2 = Math.min(HEAP_MAX, Math.ceil(Math.max(size, over) / 65536) * 65536);\n const pages2 = (next2 - memory.buffer.byteLength + 65535) / 65536 | 0;\n try {\n memory.grow(pages2);\n publishMemory(ctx.init.sab, memory.buffer.byteLength);\n return 1;\n } catch {\n }\n }\n return 0;\n}\nfunction runtimeImports(ctx, rt) {\n const { mem } = ctx;\n const sighandler = invoke(ctx, \"vi\");\n return {\n exit: async (status2) => await rt.exit(status2),\n _abort_js: async () => await abort(ctx, \"\"),\n __assert_fail: async (cond, file, line, func) => await abort(\n ctx,\n `Assertion failed: ${mem.cString(cond)}, at: ${[\n file ? mem.cString(file) : \"unknown filename\",\n line,\n func ? mem.cString(func) : \"unknown function\"\n ].join(\",\")}`\n ),\n emscripten_resize_heap: (size) => resizeHeap(ctx, size),\n emscripten_get_heap_max: () => HEAP_MAX,\n _emscripten_runtime_keepalive_clear: () => {\n },\n _emscripten_get_progname: (str, len) => putString(mem, str, ctx.init.argv0 || \"./this.program\", len),\n _emscripten_throw_longjmp: () => {\n throw Number.POSITIVE_INFINITY;\n },\n __call_sighandler: async (fp, sig) => {\n const ex = ctx.exports();\n if (typeof ex.dynCall_vi === \"function\") return await sighandler(fp, sig);\n const fn = ex.__indirect_function_table?.get(fp);\n if (typeof fn !== \"function\") throw new WebAssembly.RuntimeError(\"null function\");\n await ctx.enter(`table:${fp}`, fn, [sig]);\n },\n _setitimer_js: async (which, ms) => {\n if (which !== 0) return 0;\n await ctx.call({ op: \"proc-alarm\", sig: SIG.ALRM, ms: ms ?? 0, repeat: false, timer: 0 });\n return 0;\n },\n slicc_webcrypto_random: (out, len) => {\n for (let at = 0; at < len; at += 65536) {\n crypto.getRandomValues(\n mem.bytes(out + at, Math.min(65536, len - at))\n );\n }\n return 0;\n },\n slicc_fork_js: () => {\n if (!rt.fork) return -1;\n if (!rt.fork.supported()) return rt.fork.failed(-EM.NOSYS);\n return rt.fork.forkImport();\n }\n };\n}\nfunction buildImports(ctx, rt, module) {\n const state = { listings: /* @__PURE__ */ new WeakMap() };\n const env = {\n ...fileImports(ctx, state),\n ...fdImports(ctx),\n ...procImports(ctx, { seeded: rt.seeded, raise: async (sig) => await rt.raise(sig) }),\n ...timeImports(ctx),\n ...netImports(ctx),\n ...mmapImport(ctx),\n ...dnsImports(ctx),\n ...pthreadImports(ctx),\n ...runtimeImports(ctx, rt),\n ...invokeImports(ctx, module)\n };\n const preview1 = wasiImports(ctx, state);\n if (ctx.init.env.SLICC_EMSCRIPTEN_TRACE === \"1\") {\n for (const table of [env, preview1]) {\n for (const [name2, fn] of Object.entries(table)) {\n if (typeof fn !== \"function\" || name2.startsWith(\"invoke_\")) continue;\n table[name2] = async (...args) => {\n const r = await fn(...args);\n await ctx.say(`[em] ${name2}(${args.map(String).join(\",\")}) = ${String(r)}`);\n return r;\n };\n }\n }\n }\n return {\n env,\n wasi_snapshot_preview1: preview1\n };\n}\nfunction argvOnStack(ctx, args) {\n const ex = ctx.exports();\n const alloc = ex._emscripten_stack_alloc;\n const argv = alloc((args.length + 1) * 4);\n const encoder6 = new TextEncoder();\n for (let i = 0; i < args.length; i++) {\n const bytes = encoder6.encode(args[i]);\n const at = alloc(bytes.length + 1);\n ctx.mem.bytes(at, bytes.length + 1).set(bytes);\n ctx.mem.bytes(at + bytes.length, 1)[0] = 0;\n ctx.mem.view().setUint32(argv + i * 4, at, true);\n }\n ctx.mem.view().setUint32(argv + args.length * 4, 0, true);\n return argv;\n}\nasync function runMain(ctx, rt) {\n const ex = ctx.exports();\n const args = [ctx.init.argv0, ...ctx.init.args];\n const name2 = typeof ex.main === \"function\" ? \"main\" : \"__main_argc_argv\";\n const main = ex[name2];\n if (typeof main !== \"function\") throw new Error(`${ctx.init.argv0}: exports no main`);\n const argv = argvOnStack(ctx, args);\n const ret = await ctx.enter(name2, main, [args.length, argv]);\n const settled = rt.fork ? await rt.fork.settle(ret) : ret;\n return await rt.exit(Number(settled ?? 0));\n}\nvar sabTransport2 = (sab, port, memory) => createSyncSabTransport(sab, port, memory ? { memory } : {});\nasync function runEmscriptenProcess(init, port, given = {}) {\n const rt = new EmRuntime();\n let memory;\n const transports = given.transport ?? sabTransport2;\n const gate = new SignalGate(\n transports(init.sab, port, () => memory?.buffer.byteLength ?? 0),\n new Int32Array(init.sab, 0, SAB_HEADER_I32),\n {\n masks: () => rt.masks(),\n raise: async (sig) => await rt.raise(sig),\n timer: async (which) => await rt.timer(which)\n }\n );\n const transport = gate.transport();\n const sys = kernelSys(transport);\n const call2 = async (req) => {\n const r = await transport.call(req, Number.POSITIVE_INFINITY, req.op);\n if (!r.ok) throw new SyscallError(r.errno);\n return r.kind === \"json\" ? r.json : r.kind === \"bytes\" ? r.bytes : void 0;\n };\n const encoder6 = new TextEncoder();\n const say = async (text) => void await sys.write(2, encoder6.encode(`${text}\n`));\n const id = await identify(transport, init);\n const fork = init.fork?.wasi;\n const raw = createSyncFsSabBridge(transport, { ...ownersOf2(init), direct: true });\n const host = await new WasiHost({\n args: [init.argv0, ...init.args],\n env: init.env,\n cwd: fork?.cwd ?? init.cwd,\n pid: id.pid,\n ppid: id.ppid,\n parent: async () => (await identify(transport, init)).ppid,\n kernel: { sys, call: call2 },\n fs: ptsBridge(\n sysfsBridge(\n procfsBridge(cachingBridge(raw), procTree2(call2, id.pid)),\n async () => await call2({ op: \"fd-dev-nodes\" })\n ),\n call2\n ),\n bare: true\n }).attach();\n if (fork) host.fds.restore(fork.fds, fork.cloexec);\n else {\n const { fds, cloexec } = await stdioEntries(init, call2);\n host.fds.restore(fds, cloexec);\n }\n wireSignals(host, gate);\n const cwd = new EmCwd(host, fork?.cwd ?? init.cwd, call2, init.held);\n const ctx = {\n init,\n host,\n mem: host.mem,\n sys,\n transport,\n gate,\n cwd,\n reentry: rt.reentry,\n pid: init.pid,\n ppid: id.ppid,\n credAbi: importsCred(init.program.module),\n statfs: async (path) => await raw.statfs?.(path) ?? null,\n quit: { atExit: false, failed: false },\n call: call2,\n exports: () => rt.exports(),\n enter: async (name2, fn, args) => await rt.enter(name2, fn, args),\n exit: async (status2) => await rt.exit(status2),\n say\n };\n rt.ctx = ctx;\n const { module } = init.program;\n const imports = buildImports(ctx, rt, module);\n const spec = init.program.memory;\n const imported = createImportedMemory(spec);\n if (spec && imported) (imports[spec.module] ??= {})[spec.name] = imported;\n const missing3 = missingImports(module, imports);\n if (missing3.length > 0) {\n await say(\n `${init.argv0}: cannot start: the kernel's Emscripten runtime does not provide ${missing3.join(\", \")}`\n );\n return NOT_RUNNABLE;\n }\n const instance = await WebAssembly.instantiate(module, suspendingImports(imports));\n rt.bind(instance.exports, imported);\n memory = rt.exports().memory;\n host.mem.bind(memory);\n publishMemory(init.sab, memory.buffer.byteLength);\n port.postMessage({ type: WASM_PROCESS_READY });\n rt.fork = new EmFork(ctx);\n try {\n rt.up = true;\n const ctors = instance.exports.__wasm_call_ctors;\n if (typeof ctors === \"function\") await rt.enter(\"__wasm_call_ctors\", ctors, []);\n if (init.fork) {\n if (!rt.fork.supported()) throw new EmError(EM.NOSYS);\n const ret = await rt.fork.child(init.fork);\n return await rt.exit(Number(ret ?? 0));\n }\n return await runMain(ctx, rt);\n } catch (e) {\n if (e instanceof WasiExit) return e.code;\n throw e;\n } finally {\n rt.up = false;\n try {\n await host.flushAll();\n } catch {\n }\n }\n}\n\n// src/async/futexes.ts\nvar FUTEX_WAIT = \"futex-wait\";\nfunction later(fn) {\n const immediate = globalThis.setImmediate;\n if (immediate) immediate(fn);\n else setTimeout(fn, 0);\n}\nvar FutexHub = class {\n sleepers = /* @__PURE__ */ new Map();\n threads = 1;\n sleep(index3) {\n let set = this.sleepers.get(index3);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this.sleepers.set(index3, set);\n }\n const own = set;\n let wake = () => {\n };\n const woken = new Promise((resolve) => {\n wake = resolve;\n });\n own.add(wake);\n const cancel = () => {\n own.delete(wake);\n if (own.size === 0 && this.sleepers.get(index3) === own) this.sleepers.delete(index3);\n };\n return { woken, cancel };\n }\n wake(index3, count = Number.POSITIVE_INFINITY) {\n const set = this.sleepers.get(index3);\n if (!set) return 0;\n let woken = 0;\n for (const wake of [...set]) {\n if (woken >= count) break;\n set.delete(wake);\n wake();\n woken++;\n }\n if (set.size === 0) this.sleepers.delete(index3);\n return woken;\n }\n};\nfunction asyncFutexes(hub, transport) {\n const timed = async (ms, woken) => {\n const timeoutMs2 = Math.max(1, Math.ceil(ms));\n const waited = transport.call(\n { op: \"fd-select\", read: [], write: [], timeoutMs: timeoutMs2 },\n Number.POSITIVE_INFINITY,\n FUTEX_WAIT\n );\n const first = await Promise.race([woken.then(() => void 0), waited]);\n if (first !== void 0) return !first.ok;\n transport.cancel();\n waited.catch(() => void 0);\n return true;\n };\n const futexes = {\n async wait(view, index3, expected, ms) {\n if (Atomics.load(view, index3) !== expected) return true;\n if (!(ms > 0)) return false;\n const sleep = hub.sleep(index3);\n try {\n if (Number.isFinite(ms)) {\n return await timed(ms, sleep.woken) || Atomics.load(view, index3) !== expected;\n }\n const watch = transport.watch();\n try {\n await Promise.race([sleep.woken, watch.changed]);\n } finally {\n watch.forget();\n }\n return true;\n } finally {\n sleep.cancel();\n }\n },\n notify: (view, index3, count) => hub.wake(index3, count) + atomicsNotify(view, index3, count),\n async pause() {\n if (hub.threads > 1) await new Promise((resolve) => later(resolve));\n }\n };\n return futexes;\n}\n\n// src/async/wire.ts\nvar ASYNC_SYSCALL = \"async-syscall\";\nvar ASYNC_MORE = \"async-more\";\nvar ASYNC_STAGE = \"async-stage\";\nvar ASYNC_WORDS = \"async-words\";\nvar ASYNC_MIRROR = \"async-mirror\";\nvar ASYNC_SNAPSHOT = \"async-snapshot\";\nvar ASYNC_SNAPSHOT_TAKEN = \"async-snapshot-taken\";\nvar ASYNC_CANCEL = \"async-cancel\";\nvar ASYNC_THREAD = \"async-thread\";\nfunction isThreadMsg(message) {\n const data = message;\n return data?.type === ASYNC_THREAD && typeof data.channel === \"number\";\n}\nfunction applyRuns(view, runs) {\n if (!runs) return;\n let at = 0;\n while (at + 1 < runs.length) {\n const start2 = runs[at];\n const count = runs[at + 1];\n at += 2;\n for (let k = 0; k < count && start2 + k < view.length; k++) {\n Atomics.store(view, start2 + k, runs[at + k]);\n }\n at += count;\n }\n}\n\n// src/async/transport.ts\nfunction snapshotted(asked, snapshots) {\n const fork = asked;\n const memory = fork.state?.memory;\n if (!snapshots || fork.op !== \"proc-fork\" || !(memory instanceof Uint8Array)) {\n return { req: asked };\n }\n if (memory.byteLength === 0) return { req: asked };\n const owned = memory.buffer instanceof ArrayBuffer ? memory : memory.slice();\n const snapshot = snapshots.keep(owned);\n const state = { ...fork.state, memory: new Uint8Array(0), snapshot };\n const req = { ...asked, state };\n return { req, token: snapshot.token };\n}\nvar CLOCK_BLOCKED = 0;\nvar CLOCK_IDLE = 1;\nfunction isAnswer(reply) {\n return typeof reply.status === \"number\";\n}\nfunction bodyOf(req) {\n const body = req.body;\n return body instanceof Uint8Array ? body : void 0;\n}\nfunction exactCopy(body) {\n const whole = body.byteOffset === 0 && body.byteLength === body.buffer.byteLength;\n if (whole && body.buffer instanceof ArrayBuffer) return { body, transfer: [] };\n const copy = body.slice();\n return { body: copy, transfer: [copy.buffer] };\n}\nfunction landing2(status2, total, sink) {\n if (!sink || status2 !== SAB_STATUS_BYTES || total > sink.length) return new Uint8Array(total);\n return new Uint8Array(sink.buffer, sink.byteOffset, total);\n}\nfunction mirrored(spec) {\n if (!spec) return void 0;\n const buffer = new ArrayBuffer(spec.bytes);\n applyRuns(new Int32Array(buffer), spec.runs);\n return buffer;\n}\nfunction withTimeout(work, ms, label) {\n if (!Number.isFinite(ms)) return work;\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(syncError(\"EIO\", label)), Math.max(0, ms));\n work.then(\n (value2) => {\n clearTimeout(timer);\n resolve(value2);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n }\n );\n });\n}\nvar Mirrors = class {\n buffer = new ArrayBuffer(SAB_HEADER_BYTES);\n header = new Int32Array(this.buffer, 0, SAB_HEADER_I32);\n clock = new BigInt64Array(this.buffer, SAB_CLOCK_OFFSET, SAB_CLOCK_I64);\n changes;\n cwds;\n changesView;\n cwdsView;\n applied = 0;\n early = /* @__PURE__ */ new Map();\n settled = /* @__PURE__ */ new Map();\n waiters = /* @__PURE__ */ new Set();\n watchers = /* @__PURE__ */ new Set();\n start(mirror) {\n this.header.set(mirror.header.subarray(0, SAB_HEADER_I32));\n Atomics.store(this.clock, CLOCK_BLOCKED, BigInt(mirror.clock[0]));\n Atomics.store(this.clock, CLOCK_IDLE, BigInt(mirror.clock[1]));\n this.changes = mirrored(mirror.changes);\n this.cwds = mirrored(mirror.cwds);\n this.changesView = this.changes ? new Int32Array(this.changes) : void 0;\n this.cwdsView = this.cwds ? new Int32Array(this.cwds) : void 0;\n }\n apply(m) {\n const { header } = this;\n if (m.signals) Atomics.or(header, SAB_I_SIGNALS, m.signals);\n if (m.timers) Atomics.or(header, SAB_I_TIMERS, m.timers);\n Atomics.store(header, SAB_I_KILLED, m.killed);\n Atomics.store(header, SAB_I_ASYNC, m.async);\n Atomics.store(header, SAB_I_STOP, m.stop);\n Atomics.store(this.clock, CLOCK_BLOCKED, BigInt(m.clock));\n if (this.changesView) applyRuns(this.changesView, m.changes);\n if (this.cwdsView) applyRuns(this.cwdsView, m.cwds);\n this.applied = m.seq;\n }\n accept(m) {\n if (m.seq <= this.applied) return Promise.resolve();\n this.early.set(m.seq, m);\n const done = new Promise((resolve) => {\n const list = this.settled.get(m.seq) ?? [];\n list.push(resolve);\n this.settled.set(m.seq, list);\n });\n let progressed = false;\n for (let next2 = this.early.get(this.applied + 1); next2; next2 = this.early.get(this.applied + 1)) {\n this.early.delete(next2.seq);\n this.apply(next2);\n progressed = true;\n for (const resolve of this.settled.get(next2.seq) ?? []) resolve();\n this.settled.delete(next2.seq);\n }\n if (progressed) this.wake();\n return done;\n }\n watch() {\n let watcher;\n const changed2 = new Promise((resolve, reject) => {\n watcher = { view: this.header, index: 0, value: 0, settle: () => resolve(), fail: reject };\n this.watchers.add(watcher);\n });\n return { changed: changed2, forget: () => void (watcher && this.watchers.delete(watcher)) };\n }\n wake() {\n for (const watcher of [...this.watchers]) watcher.settle(\"ok\");\n this.watchers.clear();\n for (const waiter of [...this.waiters]) {\n if (Atomics.load(waiter.view, waiter.index) === waiter.value) continue;\n this.waiters.delete(waiter);\n waiter.settle(\"ok\");\n }\n }\n notify(view, index3) {\n for (const waiter of [...this.waiters]) {\n if (waiter.view !== view || waiter.index !== index3) continue;\n this.waiters.delete(waiter);\n waiter.settle(\"ok\");\n }\n }\n failAll(err) {\n for (const watcher of [...this.watchers]) watcher.fail(err);\n this.watchers.clear();\n for (const waiter of [...this.waiters]) {\n this.waiters.delete(waiter);\n waiter.fail(err);\n }\n }\n words(n, memory) {\n const { header } = this;\n if (memory !== void 0 && memory > 0) {\n Atomics.store(header, SAB_I_MEMORY, Math.ceil(memory / 65536));\n }\n return {\n n,\n seen: this.applied,\n signals: Atomics.load(header, SAB_I_SIGNALS),\n timers: Atomics.load(header, SAB_I_TIMERS),\n blocked: [Atomics.load(header, SAB_I_BLOCKED), Atomics.load(header, SAB_I_BLOCKED_HI)],\n memory: Atomics.load(header, SAB_I_MEMORY),\n idle: Number(Atomics.load(this.clock, CLOCK_IDLE))\n };\n }\n wait(view, index3, value2, timeoutMs2) {\n return new Promise((resolve, reject) => {\n let timer;\n const waiter = {\n view,\n index: index3,\n value: value2,\n settle: (result) => {\n clearTimeout(timer);\n resolve(result);\n },\n fail: (err) => {\n clearTimeout(timer);\n reject(err);\n }\n };\n this.waiters.add(waiter);\n if (!Number.isFinite(timeoutMs2)) return;\n timer = setTimeout(\n () => {\n this.waiters.delete(waiter);\n resolve(\"timed-out\");\n },\n Math.max(0, timeoutMs2)\n );\n });\n }\n};\nvar Caller = class {\n link;\n max;\n stages = 0;\n constructor(link, max) {\n this.link = link;\n this.max = max;\n }\n async pull(part, out, from, label) {\n for (let offset = from; offset < out.length; ) {\n const reply = await this.link.call({ type: ASYNC_MORE, part, offset });\n const bytes = reply?.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.length === 0) throw syncError(\"EIO\", label);\n if (offset + bytes.length > out.length) throw syncError(\"EIO\", label);\n out.set(bytes, offset);\n offset += bytes.length;\n }\n }\n async snapshot(token, out) {\n for (let offset = 0; offset < out.length; ) {\n const reply = await this.link.call({\n type: ASYNC_SNAPSHOT,\n token,\n offset\n });\n const bytes = reply?.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.length === 0)\n throw syncError(\"EIO\", \"fork memory\");\n if (offset + bytes.length > out.length) throw syncError(\"EIO\", \"fork memory\");\n out.set(bytes, offset);\n offset += bytes.length;\n }\n }\n async stage(body) {\n const id = ++this.stages;\n for (let offset = 0; offset < body.length; offset += this.max) {\n const bytes = body.slice(offset, Math.min(body.length, offset + this.max));\n await this.link.call({ type: ASYNC_STAGE, stage: id, offset, total: body.length, bytes }, [\n bytes.buffer\n ]);\n }\n return id;\n }\n staging(asked) {\n const body = bodyOf(asked);\n return body && body.byteLength > this.max ? body : void 0;\n }\n async staged(asked, body, timeoutMs2, label) {\n const staged = await withTimeout(this.stage(body), timeoutMs2, label).catch(() => {\n throw syncError(\"EIO\", label);\n });\n const { body: _dropped, ...rest2 } = asked;\n return { req: rest2, transfer: [], staged };\n }\n exact(asked, given) {\n const body = bodyOf(asked);\n if (!body) return { req: asked, transfer: given };\n const exact = exactCopy(body);\n if (exact.body === body) return { req: asked, transfer: given };\n return {\n req: { ...asked, body: exact.body },\n transfer: [...given, ...exact.transfer]\n };\n }\n async answer(reply, timeoutMs2, label, sink) {\n const { status: status2, total, bytes } = reply;\n if (reply.part === void 0) {\n if (!sink || status2 !== SAB_STATUS_BYTES || bytes.length > sink.length) {\n return decodeSabResult(status2, bytes);\n }\n const out2 = landing2(status2, bytes.length, sink);\n out2.set(bytes);\n return decodeSabResult(status2, out2);\n }\n const out = landing2(status2, total, sink);\n out.set(bytes);\n await withTimeout(this.pull(reply.part, out, bytes.length, label), timeoutMs2, label).catch(\n (err) => {\n throw err.code === \"EIO\" ? err : syncError(\"EIO\", label);\n }\n );\n return decodeSabResult(status2, out);\n }\n};\nfunction createAsyncTransport(link, options = {}) {\n const mirrors = new Mirrors();\n const caller = new Caller(link, options.maxMessageBytes ?? Number.POSITIVE_INFINITY);\n const started2 = Promise.withResolvers();\n let words = 0;\n let lastCall = 0;\n let initialised = false;\n let closedBy;\n const current2 = () => mirrors.words(++words, options.memory?.());\n const begin = async (init) => {\n mirrors.start(init.mirror);\n if (options.maxMessageBytes === void 0 && init.maxMessageBytes !== void 0) {\n caller.max = init.maxMessageBytes;\n }\n if (init.type === WASM_THREAD_INIT) {\n started2.resolve(init);\n return;\n }\n const fork = init.fork;\n const ref = fork?.snapshot;\n if (fork && ref) {\n delete fork.snapshot;\n const local2 = options.snapshots?.take(ref.token);\n if (local2 && local2.byteLength === ref.total) {\n fork.memory = local2;\n link.post({ type: ASYNC_SNAPSHOT_TAKEN, token: ref.token });\n } else {\n const whole = new Uint8Array(ref.total);\n await caller.snapshot(ref.token, whole);\n fork.memory = whole;\n }\n }\n const memory = init.fork?.memory;\n if (memory && !(memory instanceof Uint8Array) && init.fork) {\n const whole = new Uint8Array(memory.total);\n await caller.pull(memory.part, whole, 0, \"fork memory\");\n init.fork.memory = whole;\n }\n started2.resolve(init);\n };\n link.onMessage((message) => {\n const data = message;\n if (!initialised && (data?.type === WASM_PROCESS_INIT || data?.type === WASM_THREAD_INIT)) {\n initialised = true;\n begin(data).catch((err) => started2.reject(err));\n } else if (initialised && data?.type === ASYNC_MIRROR && data.mirror) {\n void mirrors.accept(data.mirror);\n }\n });\n link.onClose((reason) => {\n closedBy = reason;\n if (!initialised) started2.reject(new Error(`the kernel link closed: ${reason}`));\n mirrors.failAll(syncError(\"EIO\", `kernel link closed: ${reason}`));\n });\n const send = (msg, transfer, ms, label) => {\n const answered = link.call(msg, transfer).then(async (value2) => {\n const reply = value2;\n if (!reply || !isAnswer(reply)) throw syncError(\"EIO\", label);\n await mirrors.accept(reply.mirror);\n return reply;\n });\n answered.catch(() => void 0);\n return withTimeout(answered, ms, label).catch((err) => {\n throw err.code === \"EIO\" ? err : syncError(\"EIO\", label);\n });\n };\n const issue = async (asked, given, ms, label) => {\n const words2 = current2();\n lastCall = words2.n;\n const body = caller.staging(asked);\n if (!body) {\n const { req: req2, transfer } = caller.exact(asked, given);\n return send({ type: ASYNC_SYSCALL, req: req2, words: words2 }, transfer, ms, label);\n }\n const { req, staged } = await caller.staged(asked, body, ms, label);\n return send({ type: ASYNC_SYSCALL, req, words: words2, staged }, [], ms, label);\n };\n return {\n init: started2.promise,\n buffer: mirrors.buffer,\n header: mirrors.header,\n clock: mirrors.clock,\n get changes() {\n return mirrors.changes;\n },\n get cwds() {\n return mirrors.cwds;\n },\n get closed() {\n return closedBy !== void 0;\n },\n async call(asked, askedMs, label, given = [], sink) {\n const timeoutMs2 = options.deadlines === false ? Number.POSITIVE_INFINITY : askedMs;\n if (closedBy !== void 0) throw syncError(\"EIO\", label);\n const { req, token } = snapshotted(asked, options.snapshots);\n const forget = () => {\n if (token !== void 0) options.snapshots?.release(token);\n };\n try {\n const reply = await issue(req, given, timeoutMs2, label);\n const result = await caller.answer(reply, timeoutMs2, label, sink);\n if (!result.ok) forget();\n return result;\n } catch (err) {\n forget();\n throw err;\n }\n },\n wait(view, index3, value2, timeoutMs2 = Number.POSITIVE_INFINITY) {\n if (Atomics.load(view, index3) !== value2) return Promise.resolve(\"not-equal\");\n if (closedBy !== void 0) {\n return Promise.reject(syncError(\"EIO\", `kernel link closed: ${closedBy}`));\n }\n return mirrors.wait(view, index3, value2, timeoutMs2);\n },\n notify: (view, index3) => mirrors.notify(view, index3),\n watch() {\n if (closedBy === void 0) return mirrors.watch();\n const changed2 = Promise.reject(syncError(\"EIO\", `kernel link closed: ${closedBy}`));\n return { changed: changed2, forget: () => {\n } };\n },\n cancel() {\n if (closedBy === void 0 && initialised && lastCall > 0) {\n link.post({ type: ASYNC_CANCEL, n: lastCall });\n }\n },\n publish() {\n if (closedBy === void 0 && initialised) {\n link.post({ type: ASYNC_WORDS, words: current2() });\n }\n },\n post(message, transfer) {\n if (closedBy === void 0) link.post(message, transfer);\n },\n onClose: (handler) => link.onClose(handler)\n };\n}\n\n// src/async/process-entry.ts\nvar NOT_RUNNABLE2 = 126;\nvar ASYNC_NO_JSPI = \"the async process host needs WebAssembly JSPI (Suspending, promising)\";\nvar ASYNC_NO_JS = \"the async process host runs no JavaScript programs\";\nvar ASYNC_NO_EMSCRIPTEN = \"the async process host runs Emscripten programs only on the kernel's personality (emscripten: 'kernel')\";\nvar ASYNC_NO_IMPORTS = \"the async process host loads no JavaScript imports modules\";\nvar ASYNC_LOST_THREAD = \"the async process host has no memory for this thread\";\nvar ASYNC_NO_CREATE = \"the imports module exports no createAsyncImports function, which the async process host calls\";\nfunction refusal(init, deps) {\n const program = init.program;\n if (program.abi === \"js\") return ASYNC_NO_JS;\n if (program.abi !== \"wasi\" && program.emscripten !== \"kernel\") return ASYNC_NO_EMSCRIPTEN;\n if (program.imports !== void 0 && !deps.imports) return ASYNC_NO_IMPORTS;\n if (!jspiAvailable()) return ASYNC_NO_JSPI;\n return void 0;\n}\nvar NotRunnable = class extends Error {\n};\nasync function importsOf(init, deps) {\n const source = init.program.imports;\n if (source === void 0 || !deps.imports) return void 0;\n const create = (await deps.imports(source)).createAsyncImports;\n if (typeof create !== \"function\") throw new NotRunnable(ASYNC_NO_CREATE);\n return create;\n}\nvar KernelGone = class extends Error {\n constructor() {\n super(\"the kernel link closed\");\n }\n};\nfunction guarded(transport) {\n const call2 = async (...args) => {\n if (transport.closed) throw new KernelGone();\n try {\n return await transport.call(...args);\n } catch (err) {\n if (transport.closed) throw new KernelGone();\n throw err;\n }\n };\n return { call: call2, publish: () => transport.publish() };\n}\nvar KERNEL_WAIT = \"kernel-wait\";\nfunction kernelWaiter(transport, kernel, mirrored2) {\n return async (view, index3, value2, timeout = Number.POSITIVE_INFINITY) => {\n if (Atomics.load(view, index3) !== value2) return \"not-equal\";\n if (timeout <= 0) return \"timed-out\";\n const forever = !Number.isFinite(timeout);\n if (forever && mirrored2) return transport.wait(view, index3, value2);\n const timeoutMs2 = forever ? -1 : Math.max(1, Math.ceil(timeout));\n await kernel.call({ op: \"fd-select\", read: [], write: [], timeoutMs: timeoutMs2 }, Infinity, KERNEL_WAIT);\n return forever || Atomics.load(view, index3) !== value2 ? \"ok\" : \"timed-out\";\n };\n}\nfunction waitsOn(waiter, buffer) {\n if (buffer) registerWaiter(buffer, waiter);\n}\nvar ProcessThreads = class {\n hub = new FutexHub();\n main;\n spawned = /* @__PURE__ */ new Map();\n outgoing(message) {\n const data = message;\n if (data?.type !== WASM_THREAD_SPAWN || !data.thread) return message;\n const { memory, ids, modules, ...shown } = data.thread;\n this.spawned.set(shown.tid, { memory, ids, ...modules ? { modules } : {} });\n registerWaiter(ids, localWaiter);\n return { ...data, thread: shown };\n }\n take(tid) {\n const local2 = this.spawned.get(tid);\n this.spawned.delete(tid);\n return local2;\n }\n};\nfunction channelEnd(root, channel, gone) {\n const posts = [];\n const early = [];\n const closes = [];\n let ended;\n const close = (reason) => {\n if (ended !== void 0) return;\n ended = reason;\n gone();\n for (const handler of closes.splice(0)) handler(reason);\n };\n const link = {\n post(message, transfer) {\n if (ended === void 0) root.post({ type: ASYNC_THREAD, channel, message }, transfer);\n },\n call(message, transfer) {\n if (ended !== void 0) return Promise.reject(new Error(`link closed: ${ended}`));\n return root.call({ type: ASYNC_THREAD, channel, message }, transfer);\n },\n onMessage(handler) {\n posts.push(handler);\n for (const message of early.splice(0)) handler(message);\n },\n onClose(handler) {\n const reason = ended;\n if (reason === void 0) closes.push(handler);\n else queueMicrotask(() => handler(reason));\n },\n close: () => close(\"the thread closed its link\")\n };\n return {\n link,\n deliver(message) {\n if (posts.length === 0) early.push(message);\n else for (const handler of posts) handler(message);\n },\n close\n };\n}\nfunction threadMux(root, opened) {\n const channels = /* @__PURE__ */ new Map();\n const posts = [];\n const early = [];\n root.onMessage((message) => {\n if (!isThreadMsg(message)) {\n if (posts.length === 0) early.push(message);\n else for (const handler of posts) handler(message);\n return;\n }\n const { channel } = message;\n let end = channels.get(channel);\n if (message.closed !== void 0) {\n end?.close(message.closed);\n return;\n }\n if (!end) {\n end = channelEnd(root, channel, () => channels.delete(channel));\n channels.set(channel, end);\n opened(end.link);\n }\n end.deliver(message.message);\n });\n root.onClose((reason) => {\n for (const end of [...channels.values()]) end.close(reason);\n });\n return {\n post: (message, transfer) => root.post(message, transfer),\n call: (message, transfer) => root.call(message, transfer),\n onMessage(handler) {\n posts.push(handler);\n for (const message of early.splice(0)) handler(message);\n },\n onClose: (handler) => root.onClose(handler),\n close: () => root.close()\n };\n}\nfunction localInit(init, transport, module) {\n const { mirror: _mirror, maxMessageBytes: _max, held, program, ...rest2 } = init;\n const { image: _image, ...known } = program;\n const cwds = transport.cwds;\n const changes = transport.changes;\n return {\n ...rest2,\n sab: transport.buffer,\n ...changes ? { changes } : {},\n ...held && cwds ? { held: { ...held, sab: cwds } } : {},\n program: { ...known, module }\n };\n}\nfunction threadInit(init, transport, module, local2, main) {\n const { thread, ...shown } = init;\n const process = localInit(shown, transport, module);\n return {\n ...process,\n type: WASM_THREAD_INIT,\n thread: { ...thread, ...local2 },\n signals: main.buffer\n };\n}\nfunction running(transport, threads) {\n const kernel = guarded(transport);\n const mirrored2 = kernelWaiter(transport, kernel, true);\n waitsOn(mirrored2, transport.buffer);\n waitsOn(mirrored2, transport.changes);\n waitsOn(mirrored2, transport.cwds);\n const port = {\n postMessage: (message, transfer) => transport.post(threads.outgoing(message), transfer)\n };\n return { transport, kernel, port };\n}\nasync function started(init, transport, deps, size, threads) {\n const create = await importsOf(init, deps);\n const module = await deps.module(init.program.image);\n const { kernel, port } = running(transport, threads);\n const local2 = localInit(init, transport, module);\n const transports = (_sab, _port, memory) => {\n size.memory = memory;\n return kernel;\n };\n if (local2.program.abi !== \"wasi\")\n return runEmscriptenProcess(local2, port, { transport: transports });\n return runWasiProcess(local2, port, {\n transport: transports,\n futexes: asyncFutexes(threads.hub, transport),\n ...create ? { imports: create } : {}\n });\n}\nasync function threadStarted(init, transport, deps, threads) {\n const local2 = threads.take(init.thread.tid);\n const main = threads.main;\n if (!local2 || !main) throw new Error(ASYNC_LOST_THREAD);\n const create = await importsOf(init, deps);\n const module = await deps.module(init.program.image);\n const { kernel, port } = running(transport, threads);\n threads.hub.threads++;\n try {\n await runWasiThread(threadInit(init, transport, module, local2, main), port, {\n transport: () => kernel,\n futexes: asyncFutexes(threads.hub, transport),\n ...create ? { imports: create } : {}\n });\n } finally {\n threads.hub.threads--;\n }\n}\nfunction failure(transport) {\n return (err, code2) => transport.post({\n type: WASM_PROCESS_ERROR,\n message: err instanceof Error ? rawStack(err) ?? err.message : String(err),\n ...code2 === void 0 ? {} : { code: code2 }\n });\n}\nfunction asyncProcessEntry(link, deps) {\n const size = { memory: void 0 };\n const threads = new ProcessThreads();\n const transportOf = (on) => createAsyncTransport(on, {\n ...deps.maxMessageBytes !== void 0 ? { maxMessageBytes: deps.maxMessageBytes } : {},\n ...deps.snapshots ? { snapshots: deps.snapshots } : {},\n ...deps.deadlines === false ? { deadlines: false } : {},\n memory: () => size.memory?.()\n });\n const thread = (on) => {\n const transport2 = transportOf(on);\n const failed3 = failure(transport2);\n transport2.init.then(\n (init) => {\n if (init.type !== WASM_THREAD_INIT) return failed3(ASYNC_LOST_THREAD);\n threadStarted(init, transport2, deps, threads).catch((err) => {\n if (!transport2.closed) failed3(err);\n });\n },\n () => void 0\n );\n };\n const transport = transportOf(threadMux(link, thread));\n threads.main = transport;\n const failed2 = failure(transport);\n transport.init.then(\n (init) => {\n const refused3 = refusal(init, deps);\n if (refused3) return failed2(refused3, NOT_RUNNABLE2);\n if (init.type === WASM_THREAD_INIT) return failed2(ASYNC_LOST_THREAD);\n started(init, transport, deps, size, threads).then(\n (code2) => transport.post({ type: WASM_PROCESS_EXIT, code: code2 }),\n (err) => {\n if (transport.closed) return;\n if (err instanceof NotRunnable) failed2(err.message, NOT_RUNNABLE2);\n else failed2(err);\n }\n );\n },\n () => void 0\n );\n}\nexport {\n ASYNC_LOST_THREAD,\n ASYNC_NO_CREATE,\n ASYNC_NO_EMSCRIPTEN,\n ASYNC_NO_IMPORTS,\n ASYNC_NO_JS,\n ASYNC_NO_JSPI,\n KERNEL_WAIT,\n KernelGone,\n ProcessThreads,\n asyncProcessEntry,\n kernelWaiter,\n threadMux,\n threadStarted\n};\n";