@threadedstack/wmd-web 0.1.41 → 0.1.42

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.
package/README.md CHANGED
@@ -2699,6 +2699,13 @@ The words of `edge`:
2699
2699
  - WebKit (Safari, every browser on iOS): the default is NO frame (`FRAME_CAPS.webkit` is 0 in `src/edge/sbx/cap.js`, measured there: the browser ends a web
2700
2700
  process at 2048 MB, and a sandboxed frame took the page past it); node runs in the guest with the calm reason `node runs in the guest in this browser: ...`. A page that
2701
2701
  wants frames anyway says `edge: { frameCap: N }` (its own choice, 0 = none).
2702
+ - `edge: { fscache: false }`: the off switch of the kept file answers (FSC-1). By default a start of node or python keeps what the page told it about the
2703
+ container's tree for 250 ms at most (the listing of a folder it read, the stat of a name and its absence), so the many repeated probes of an import or a
2704
+ `require` are answered inside the runtime, with no trip to the page (`edge/browser/src/fscache.rs`). What it keeps is dropped by every call of the program that
2705
+ changes the tree (write, rename, remove, link, mode, time, a truncate) and for the rest of the start by any call that lets another process act (a child, a watcher,
2706
+ a call the runtime does not know). A write by a process the program has no call to learn of (the guest, another frame) is unseen for 250 ms at most. The same switch for
2707
+ one program is `WMD_FSCACHE=0` in its environment (a mask: 1 listings, 2 stats, 3 both); for a diagnosis the page word `edgeFscache=0`. The table
2708
+ `FSCACHE_OFF` of `src/edge/sbx/cap.js` names an engine that must run with it off (empty: it is on in Chromium, Firefox and WebKit).
2702
2709
  - The rest of the object (`watch`, `prepare`, `onLog`, `onBridge`, `settings`, `rt`) is for tests and advanced pages; it is handed to `edgeSetup`.
2703
2710
  - Node runs in the guest, with the reason counted in `edgePlanCounts.off`, when: the image has no node 24, the container says `WMD_EDGE=0`,
2704
2711
  a user that is not root, a read-only root, tmpfs mounts, the browser lacks SharedArrayBuffer or wasm exceptions, or there is no source (or no pins file).
package/RELEASE.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wmd-web",
3
3
  "version": "0.5.1",
4
- "commit": "f896db7a78550adb1b3292eb291af93045826254",
4
+ "commit": "15f927989729f00a9548e101562d256f1ab2538c",
5
5
  "previous": null,
6
6
  "decisions": [
7
7
  "D-388",
@@ -109,7 +109,7 @@
109
109
  "root": "edge-site",
110
110
  "files": {
111
111
  "edge-site/own/HASHES.txt": {
112
- "sha256": "3bbb4e688423ea97034a4225d7e1c67d7f8b5007f3ece109156a2f74396ec00a",
112
+ "sha256": "4d83edcb41399bb89eb7b1f89115886d739adac887bdde59a8d33e3a4602683a",
113
113
  "bytes": 359
114
114
  },
115
115
  "edge-site/own/NOTICES.txt": {
@@ -133,8 +133,8 @@
133
133
  "bytes": 75647
134
134
  },
135
135
  "edge-site/own/wmd_browser_bg.wasm": {
136
- "sha256": "5c6a28df432770c97e9b1c7bd77589bd31c063bb574d2a4c77768ef032f4ceee",
137
- "bytes": 6312756
136
+ "sha256": "1e3db7f2c5f4be0ee44e5f2c0205cf8ca11f906d9addd5512915fad4821661c2",
137
+ "bytes": 6334959
138
138
  },
139
139
  "edge-site/wasm/NOTICES.txt": {
140
140
  "sha256": "7ae1af355689c49eae0a3e1ca3ea85a7d0793100f6bd7f9dabc7916e191e0421",
@@ -155,14 +155,14 @@
155
155
  }
156
156
  },
157
157
  "files": {
158
- "README.md": "8f8305186a662662bc67f4b0eebb62900f21dbb432e7dfcdedce24bdba20f341",
159
- "edge-site/own/HASHES.txt": "3bbb4e688423ea97034a4225d7e1c67d7f8b5007f3ece109156a2f74396ec00a",
158
+ "README.md": "9155fdbf01fcd60f0fd89d854d985a26682683294de7404bf0197fd22aa8fdfb",
159
+ "edge-site/own/HASHES.txt": "4d83edcb41399bb89eb7b1f89115886d739adac887bdde59a8d33e3a4602683a",
160
160
  "edge-site/own/NOTICES.txt": "8ceca5406ee5833737bd5fa4a41d434bf5e4d26eff6da1e42c693176ee113101",
161
161
  "edge-site/own/acorn/LICENSE": "76a876cf886ff9be2a8b5e2e86514fed06223c8c9f0c1e9ee9606e93841e00b7",
162
162
  "edge-site/own/acorn/acorn.mjs": "5fb5f5d2613ed04b33892f2beba7400e4d6ba624512bc0e8dfb572243b2882f3",
163
163
  "edge-site/own/snippets/wasmer-napi-749f42b30f6a109f/inline0.js": "6b7322b9a8e1c49921d022621e3438a597630a14df26576a8359070e477fe5f7",
164
164
  "edge-site/own/wmd_browser.js": "b389b072096881ba39b22cd705d3a230af02acc5409c61fb4f997d1081c4df6f",
165
- "edge-site/own/wmd_browser_bg.wasm": "5c6a28df432770c97e9b1c7bd77589bd31c063bb574d2a4c77768ef032f4ceee",
165
+ "edge-site/own/wmd_browser_bg.wasm": "1e3db7f2c5f4be0ee44e5f2c0205cf8ca11f906d9addd5512915fad4821661c2",
166
166
  "edge-site/wasm/NOTICES.txt": "7ae1af355689c49eae0a3e1ca3ea85a7d0793100f6bd7f9dabc7916e191e0421",
167
167
  "edge-site/wasm/edgejs.wasm": "7131008ab38d52ff31b0d3059c6e105e8a448775408981956ce7aff792bfd98b",
168
168
  "edge-site/wasm/linux.cjs": "77bb31f2d92a36f8a76bb129187febd253ce79e1c1dc9d4bccc87474075fef3f",
@@ -195,7 +195,7 @@
195
195
  "src/edge/codes.js": "1bb32c060d4a960a2e3b384d9ff8583329861de6e2b515b0d901b503f8b8a4a7",
196
196
  "src/edge/ctl.js": "c9818c60588a534b7285ba8050580ae9c474aa79ee8a126bf0274c0eba4e7025",
197
197
  "src/edge/error-kind.js": "2d44c95ba69168a31959eb9a484ed1aecf5a316d9f4e0b6e30fb8c2fa1a723fb",
198
- "src/edge/frame-code.gen.js": "c17093d2ec20adcad4cbf0c22eae81988938ad4518824a874c91d3df2a949469",
198
+ "src/edge/frame-code.gen.js": "19093c0f58ad13605e6232eef8b5ca01bac2c12b80c9a6ee061b83fb9aab7343",
199
199
  "src/edge/frame.html": "64b608f5c0f6fbc58ed5adc64137c00982503fe96a0e3876b66c5e35b206c380",
200
200
  "src/edge/frame.js": "78bdf2fc985188de2485b0f9ec2ab61a996f61edc2fc4fec1f45adf14f18fb1e",
201
201
  "src/edge/fs-route.js": "2e901b1c15e93a57f0696c5e46a99f87df6bd6c5e1c24cdad3c69bfba2fee281",
@@ -204,7 +204,7 @@
204
204
  "src/edge/node-args.js": "43395591af875da507000b224efc762f70691f2147462ad3981a9ff31ce02385",
205
205
  "src/edge/node-guest-opts.js": "81711a8b2f506aab85c61459a41922d031675f4f90ed5be5363179d8b112df44",
206
206
  "src/edge/node-opts.js": "dcad2d3b72f25071b80517ce28de6426731ce7677978376924e48170ae930fe3",
207
- "src/edge/own/adapter.js": "1fffcba9ead71c440737f3cca2e7d32af9d2abd48b95760273de35719e8b9979",
207
+ "src/edge/own/adapter.js": "10a8c900f212455fce72b98694bb85c8cd26d97906f4ffa57e1132da624083bf",
208
208
  "src/edge/own/capi.js": "f9ba67bdb8e04b970d38cd4225728e2de3cb7db41201b318334dcd764c12c732",
209
209
  "src/edge/own/child-host.js": "2ae20c7631f713520bbb47ead48812ddc42fb83aea5f91da39f4c0c6a5fd1a28",
210
210
  "src/edge/own/exit-now.js": "88bc30e44853b496536b97ab1ac1b5e8adfaecb3d19352f2c0143a6fd72df51a",
@@ -212,7 +212,7 @@
212
212
  "src/edge/own/fs-own-route.js": "316f807b895ef1c7964ef830a68e5a6abc80f99339697a9846a8362336db78d3",
213
213
  "src/edge/own/fs-stats.js": "0516ee532301af7467015b6116bb9bc4fe95d3e42d4d30eae0a9a3291678bbb4",
214
214
  "src/edge/own/guest-spawner.js": "57c33f5924428f04782d1ddd4f3341631a853ef0538464082da9927d706d04a5",
215
- "src/edge/own/hub.js": "eafdda175590f5df0751f4d3babecc44454764d3600d2d5caa7c05d42644cf82",
215
+ "src/edge/own/hub.js": "64e96430d74b44f6bfd2a3ccbc413e6d15d823fbdfc8aaeb0f0701ce226f7769",
216
216
  "src/edge/own/loader.js": "d9c739edd626ee50364260eded1b77c734c0529a85661df94e7298344ec2c80a",
217
217
  "src/edge/own/marks.js": "b14473e8b84e0a88e88a2742f300070e440e7f263093b5f2cebbfe52e98476c4",
218
218
  "src/edge/own/memcap.js": "cb1806f8a4174d58a34546457ac7539ad39d44c6b009744b957c2f885ddef55a",
@@ -237,8 +237,8 @@
237
237
  "src/edge/python-plan.js": "1da9bf454fc1625b557f290d3b659db34ef2fedc07c7d2f99bc5028a4037dff6",
238
238
  "src/edge/python-source.js": "b946e1979014328db2c05c80dc904d68b1b188b2e07e550d044745a4fba4ee92",
239
239
  "src/edge/resolve.js": "be0d9c53374da79af72a1b4664919a1320d17f7500dc9f269414005b296ff7dc",
240
- "src/edge/runtime.js": "22371456ad6e02815d74fac0ba1bd5b1a795fea967a97a2ad2dc55f74e7240e6",
241
- "src/edge/sbx/cap.js": "bf20f7d5f1479c3802ceae462a3776b30f9c52a1c4ad998f89add7077b747aac",
240
+ "src/edge/runtime.js": "6fb8dfd61ef61396b6821023313644c9b862ceb2fb5fe28762720cbec7acef64",
241
+ "src/edge/sbx/cap.js": "4bceaf8838e413246e986fdc5fd69eb85a9ff5e05b4e6ffb007d2548ac153784",
242
242
  "src/edge/sbx/common.js": "116390056fac2302a68089fbcde3f4d0ed169bb7b42ed606db5923c717873776",
243
243
  "src/edge/sbx/doc.js": "0b3877068550015c351240195a5487e9492d0a81a3431486e8d874c7cda11d0e",
244
244
  "src/edge/sbx/files.js": "511c0ac6028b0d15d8295c2680614d4b61e3d2139deb66a7cc76812db809a00a",
@@ -253,7 +253,7 @@
253
253
  "src/edge/sems.js": "f5bd680e67b7ec3eeb16b2f7ac9207b16491001400b435ff5ee3a34f050d8ceb",
254
254
  "src/edge/service-host.js": "f77664be9e3a0cc1cc9b283c5aeda7d94c7a9d61b8cecda5b90822295d315df6",
255
255
  "src/edge/service-port.js": "6daff74e083d8d6e4d3ce950004bafb8632e78c9fbf626197a2c18453ac96eeb",
256
- "src/edge/setup.js": "23a2d06bc965cbdeaaa04237de7dcfd5aa524bfdf65f6eb72450db2d71a9d41f",
256
+ "src/edge/setup.js": "ddaa360a6f9f17cde84c30e738d0f0cf021792aa6d822712ab8fffa9aad24a8d",
257
257
  "src/edge/shim.js": "25efa4dddd3bbdd4a2967d99116e10c011a41aa0a4bdd7ce670fbf6d01735a76",
258
258
  "src/edge/site.js": "ff63be7c751678b773fd03e79e551e6fe6e85caa0444b6413b7bb940b8316979",
259
259
  "src/edge/spawn-guard.js": "666cc6cca0628f3c07093f08da277a1d6291eebb91c19abebf0d422f6197e401",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threadedstack/wmd-web",
3
- "version": "0.1.41",
3
+ "version": "0.1.42",
4
4
  "license": "MIT",
5
5
  "homepage": "https://github.com/threadedstack/wmd-releases",
6
6
  "repository": {
@@ -9,8 +9,8 @@
9
9
  },
10
10
  "description": "Browser host for wmd's guest vm.wasm (Web Workers + shared memory + WASI preview1)",
11
11
  "wmd": {
12
- "tag": "v0.1.41",
13
- "commit": "f896db7a78550adb1b3292eb291af93045826254",
12
+ "tag": "v0.1.42",
13
+ "commit": "15f927989729f00a9548e101562d256f1ab2538c",
14
14
  "web": "0.5.1"
15
15
  },
16
16
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  // GENERATED by scripts/build-frame-code.mjs (make edge-frame-code); never edited, never committed.
2
- // frame 93d986542ee0fe1a 8315; worker 2fc8f7b3efc13029 102240; ownWorker e31fb4869ca0889d 61503
2
+ // frame 93d986542ee0fe1a 8315; worker 1849ffec0f1d2f37 102758; ownWorker e31fb4869ca0889d 61503
3
3
  const FRAME = "// src/edge/error-kind.js\nvar ERROR_KINDS = new Set([\"runtime\"]);\nvar kindWord = (k) => typeof k === \"string\" && ERROR_KINDS.has(k) ? k : undefined;\n\n// src/edge/sbx/common.js\nvar STRATEGIES = [\"module\", \"boot\", \"data\"];\nvar b64 = (text) => {\n const bytes = new TextEncoder().encode(text);\n let s = \"\";\n for (let i = 0;i < bytes.length; i += 32768)\n s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));\n return btoa(s);\n};\nvar dataUrl = (text) => \"data:text/javascript;base64,\" + b64(text).replace(/\\//g, \"%2F\");\nvar blobUrl = (text) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\nvar bootSrc = (url) => `var q = []; var h = function (e) { q.push(e) }; self.addEventListener(\"message\", h);\n` + \"import(\" + JSON.stringify(url) + `).then(function () { self.removeEventListener(\"message\", h); for (var i = 0; i < q.length; i++) self.dispatchEvent(new MessageEvent(\"message\", { data: q[i].data, ports: q[i].ports })) },\n` + ` function (e) { postMessage({ type: \"done\", error: \"the frame's Worker code did not load: \" + String(e && e.message || e) }) })`;\nvar SCRIPT_LOADER = 'onmessage = e => { const d = e.data; if (d && typeof d.__wmdScript === \"string\") { onmessage = null; (0, eval)(d.__wmdScript + \"\\\\n//# sourceURL=wmd-worker.js\") } }';\nvar SCRIPT_PREFIX = \"wmd-script:\";\nfunction makeFactory(name) {\n if (name === \"data\") {\n const scripts = new Map;\n const loader = \"data:text/javascript,\" + encodeURIComponent(SCRIPT_LOADER);\n return {\n name,\n url: dataUrl,\n script: (t) => {\n const n = SCRIPT_PREFIX + scripts.size;\n scripts.set(n, t);\n return n;\n },\n make: (u, o) => {\n const t = scripts.get(u);\n if (t === undefined)\n return new Worker(u, { name: o && o.name, type: \"module\" });\n const w = new Worker(loader, { name: o && o.name, type: \"module\" });\n w.postMessage({ __wmdScript: '\"use strict\";' + t });\n return w;\n }\n };\n }\n if (name === \"boot\")\n return { name, url: blobUrl, make: (u, o) => new Worker(blobUrl(bootSrc(u)), { name: o && o.name }) };\n return { name: \"module\", url: blobUrl, make: (u, o) => new Worker(u, { name: o && o.name, type: \"module\" }) };\n}\nvar dec = new TextDecoder;\nasync function probeStrategy({ hint = \"\", timeoutMs = 1500, make = makeFactory } = {}) {\n const order = [...STRATEGIES.includes(hint) ? [hint] : [], ...STRATEGIES.filter((s) => s !== hint)];\n const first = STRATEGIES.includes(hint) ? await probeForms([hint], timeoutMs, make) : null;\n if (first && first.name)\n return first;\n const rest = await probeForms(first ? order.slice(1) : order, timeoutMs, make);\n return first ? { name: rest.name, tried: [...first.tried, ...rest.tried] } : rest;\n}\nasync function probeForms(order, timeoutMs, make) {\n const runs = order.map((name) => {\n const f = make(name);\n let w = null;\n const p = new Promise((resolve) => {\n const timer = setTimeout(() => resolve({ name, ok: false, why: `no answer in ${timeoutMs} ms` }), timeoutMs);\n const end = (r) => (clearTimeout(timer), resolve({ name, ...r }));\n try {\n const a = f.url(\"export const v = 7\");\n const b = f.url(`import { v } from ${JSON.stringify(a)}; postMessage(v)`);\n w = f.make(b, { name: \"wmd-probe\" });\n w.onmessage = (e) => end(e.data === 7 ? { ok: true } : { ok: false, why: \"a wrong answer\" });\n w.onerror = (e) => {\n e?.preventDefault?.();\n end({ ok: false, why: String(e && e.message || \"the Worker did not start\") });\n };\n } catch (e) {\n end({ ok: false, why: String(e && e.message || e).slice(0, 120) });\n }\n });\n return p.then((r) => (w && w.terminate(), r));\n });\n const tried = [];\n for (const run of runs) {\n const r = await run;\n tried.push(r);\n if (r.ok) {\n runs.forEach((x) => x.catch(() => {}));\n return { name: r.name, tried };\n }\n }\n return { name: null, tried };\n}\n\n// src/edge/sbx/frame.js\nfunction start({ port, worker, ownWorker, hint = \"\" }) {\n let w = null;\n let cur = 0;\n const live = new Set;\n globalThis.x5live = live;\n let kept = null;\n globalThis.x5kept = () => kept;\n let held = null;\n let mk = null;\n let workerUrl = \"\";\n const up = (msg) => port.postMessage(msg);\n const endWorker = (x) => {\n if (!x || !live.delete(x))\n return;\n x.onmessage = null;\n x.onerror = null;\n if (x === w)\n w = null, cur = 0;\n try {\n x.terminate();\n } catch {}\n };\n const endAll = () => {\n for (const x of [...live])\n endWorker(x);\n };\n const payload = () => {\n if (!held)\n throw new Error(\"the page handed in no files\");\n const files = { glue: held.glue, snippet: held.snippet, acorn: held.acorn, linux: held.linux, hashes: held.hashes, ...held.linuxpy ? { linuxpy: held.linuxpy } : {} };\n if (held.python)\n files.python = held.python;\n if (!(kept && kept.rtModule))\n files.wasm = held.wasm;\n if (!(kept && kept.prog))\n files.edgejs = held.edgejs;\n return { strategy: mk.name, ownWorker, files };\n };\n const spawn = () => {\n const x = mk.make(workerUrl, { name: \"wmd-edge\" });\n live.add(x);\n return x;\n };\n let prepW = null;\n let waiting = null;\n const prepDone = (r) => {\n if (!prepW)\n return;\n const p = prepW;\n prepW = null;\n endWorker(p);\n up({ x5prepared: r });\n if (waiting) {\n const d = waiting;\n waiting = null;\n begin(d);\n }\n };\n const prepare = (cfg) => {\n if (prepW || w || waiting || kept)\n return up({ x5prepared: { ok: !!kept, already: true } });\n const p = prepW = spawn();\n p.onmessage = ({ data: d }) => {\n if (d && d.type === \"keep\")\n return void (kept = d.keep);\n if (d && d.type === \"done\")\n prepDone({ ok: !!d.prepared && !d.error, ...d.error ? { error: String(d.error).slice(0, 300) } : {}, ...kindWord(d.errorKind) ? { errorKind: d.errorKind } : {}, ms: d.prepareMs });\n };\n p.onerror = (e) => prepDone({ ok: false, error: \"worker error: \" + e.message });\n try {\n p.postMessage({ cfg, ports: [], prepare: true, kept, tf: performance.timeOrigin + performance.now(), x5sbx: payload() });\n } catch (e) {\n prepDone({ ok: false, error: String(e && e.message || e).slice(0, 200), errorKind: \"runtime\" });\n }\n };\n function begin(data) {\n const run = data.run;\n cur = run;\n const mine = w = spawn();\n mine.onmessage = ({ data: d }) => {\n if (d && d.type === \"keep\")\n return void (kept = d.keep);\n up({ x5relay: d, x5run: run });\n if (d && d.type === \"done\")\n endWorker(mine);\n };\n mine.onerror = (e) => {\n up({ x5relay: { type: \"done\", error: \"worker error: \" + e.message }, x5run: run });\n endWorker(mine);\n };\n try {\n mine.postMessage({ cfg: data.cfg, ports: data.ports, tf: performance.timeOrigin + performance.now(), kept, x5sbx: payload() }, data.ports);\n } catch (e) {\n up({ x5relay: { type: \"done\", error: String(e && e.message || e).slice(0, 300), errorKind: \"runtime\" }, x5run: run });\n endWorker(mine);\n }\n }\n addEventListener(\"pagehide\", endAll);\n port.onmessage = ({ data }) => {\n if (!data)\n return;\n if (data.x5sbx === \"files\")\n return void (held = data.files);\n if (data.x5edge === \"ping\")\n return up(data.check !== undefined ? { x5pong: data.check } : \"x5-pong\");\n if (data.x5edge === \"stop\")\n return waiting = null, prepW = null, endAll();\n if (data.x5edge === \"prepare\")\n return prepare(data.cfg);\n if (data.x5edge === \"in\")\n return w && cur !== 0 && data.run === cur ? w.postMessage({ in: data.in }) : undefined;\n if (w || waiting || data.x5edge !== \"start\")\n return;\n if (prepW)\n return void (waiting = data);\n begin(data);\n };\n const evalOk = () => {\n try {\n return new Function(\"return 7\")() === 7;\n } catch {\n return false;\n }\n };\n probeStrategy({ hint }).then((r) => {\n mk = r.name ? makeFactory(r.name) : null;\n if (mk)\n workerUrl = mk.url(worker);\n up({ x5sbx: \"ready\", caps: { worker: r.name, tried: r.tried, eval: evalOk(), sab: typeof SharedArrayBuffer === \"function\", coi: globalThis.crossOriginIsolated === true } });\n });\n}\nexport {\n start as default\n};\n"
4
- const WORKER = "var __defProp = Object.defineProperty;\nvar __returnValue = (v) => v;\nfunction __exportSetter(name, newValue) {\n this[name] = __returnValue.bind(null, newValue);\n}\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, {\n get: all[name],\n enumerable: true,\n configurable: true,\n set: __exportSetter.bind(all, name)\n });\n};\nvar __esm = (fn, res, err) => () => {\n if (fn)\n try {\n res = fn(fn = 0);\n } catch (e) {\n err = [e];\n }\n if (err)\n throw err[0];\n return res;\n};\n\n// src/edge/own/exit-now.js\nfunction exitOfRun(data, waiting) {\n if (data.id != null)\n return data;\n const first = waiting.keys().next();\n return first.done ? null : { ...data, id: first.value };\n}\n\n// src/edge/own/payload-size.js\nfunction payloadBytes(v, depth = 0, seen = new Set) {\n if (!v || typeof v !== \"object\" || depth > 6 || seen.has(v))\n return 0;\n if (ArrayBuffer.isView(v))\n return v.byteLength;\n if (v instanceof ArrayBuffer || typeof SharedArrayBuffer !== \"undefined\" && v instanceof SharedArrayBuffer)\n return v.byteLength;\n seen.add(v);\n let n = 0;\n for (const k of Object.keys(v))\n n += payloadBytes(v[k], depth + 1, seen);\n return n;\n}\nvar BIG_SHARE;\nvar init_payload_size = __esm(() => {\n BIG_SHARE = 1 << 20;\n});\n\n// src/edge/own/pool.js\nclass WorkerPool {\n #create;\n #init;\n #onMessage;\n #onFailure;\n #spare;\n #max;\n #slots = new Map;\n #next = 1;\n #closed = false;\n #idleMs;\n #onRetire;\n created = 0;\n retired = 0;\n constructor({ create, init = () => {}, spare = 0, max = 256, idleMs = 0, onRetire = () => {}, onMessage = () => {}, onFailure = () => {} }) {\n this.#create = create;\n this.#init = init;\n this.#spare = spare;\n this.#max = max;\n this.#idleMs = idleMs;\n this.#onRetire = onRetire;\n this.#onMessage = onMessage;\n this.#onFailure = onFailure;\n }\n get live() {\n return this.#slots.size;\n }\n get starting() {\n return this.#count(\"starting\");\n }\n get idle() {\n return this.#count(\"idle\");\n }\n get busy() {\n return this.#count(\"busy\");\n }\n get workers() {\n return [...this.#slots.values()].map((s) => s.worker);\n }\n get closed() {\n return this.#closed;\n }\n #count(state) {\n let n = 0;\n for (const s of this.#slots.values())\n if (s.state === state)\n n++;\n return n;\n }\n #available() {\n let n = 0;\n for (const s of this.#slots.values())\n if (s.state === \"idle\" || s.state === \"starting\" && s.queue.length === 0)\n n++;\n return n;\n }\n warm(n = this.#spare) {\n if (this.#closed)\n throw new Error(\"pool closed\");\n while (this.#available() < n && this.#slots.size < this.#max)\n this.#start();\n }\n #start() {\n const worker = this.#create();\n const slot = { id: this.#next++, worker, state: \"starting\", queue: [], task: null };\n this.#slots.set(slot.id, slot);\n this.created++;\n worker.addEventListener(\"message\", (e) => this.#message(slot, e.data));\n worker.addEventListener(\"error\", (e) => this.#crash(slot, e));\n this.#init(worker, slot.id);\n return slot;\n }\n dispatch(task, transfer) {\n if (this.#closed)\n throw new Error(\"pool closed\");\n let slot;\n for (const s of this.#slots.values()) {\n if (s.state === \"idle\") {\n slot = s;\n break;\n }\n }\n if (!slot) {\n for (const s of this.#slots.values()) {\n if (s.state === \"starting\" && s.queue.length === 0) {\n slot = s;\n break;\n }\n }\n }\n if (!slot) {\n if (this.#slots.size >= this.#max)\n throw new RangeError(\"worker limit reached (\" + this.#max + \")\");\n slot = this.#start();\n }\n if (slot.state === \"idle\")\n this.#send(slot, task, transfer);\n else\n slot.queue.push({ task, transfer });\n if (this.#spare)\n this.warm();\n return slot.id;\n }\n #idle(slot) {\n clearTimeout(slot.timer);\n slot.timer = null;\n if (!this.#idleMs)\n return;\n slot.timer = setTimeout(() => {\n slot.timer = null;\n if (this.#closed || slot.state !== \"idle\" || !this.#slots.has(slot.id) || this.#available() <= this.#spare)\n return;\n this.#slots.delete(slot.id);\n this.retired++;\n try {\n slot.worker.terminate();\n } catch {}\n this.#onRetire(slot.id, slot.worker);\n }, this.#idleMs);\n }\n #send(slot, task, transfer) {\n clearTimeout(slot.timer);\n slot.timer = null;\n slot.state = \"busy\";\n slot.task = task;\n slot.worker.postMessage(task, transfer);\n }\n #message(slot, data) {\n if (this.#closed || !this.#slots.has(slot.id))\n return;\n const type = data && data.type;\n if (type === \"ready\") {\n if (slot.state !== \"starting\")\n return;\n slot.state = \"idle\";\n const next = slot.queue.shift();\n if (next)\n this.#send(slot, next.task, next.transfer);\n else\n this.#idle(slot);\n } else if (type === \"done\") {\n slot.state = \"idle\";\n slot.task = null;\n this.#idle(slot);\n } else if (type === \"crash\") {\n this.#crash(slot, { message: data.error });\n } else {\n this.#onMessage(slot.id, data);\n }\n }\n #crash(slot, e) {\n if (this.#closed || !this.#slots.has(slot.id))\n return;\n this.#slots.delete(slot.id);\n clearTimeout(slot.timer);\n try {\n slot.worker.terminate();\n } catch {}\n const lost = [];\n if (slot.task)\n lost.push(slot.task);\n for (const q of slot.queue)\n lost.push(q.task);\n this.#onFailure(slot.id, lost, new Error(String(e && e.message || e || \"worker error\")));\n }\n terminateAll() {\n this.#closed = true;\n for (const s of this.#slots.values()) {\n clearTimeout(s.timer);\n try {\n s.worker.terminate();\n } catch {}\n }\n this.#slots.clear();\n }\n}\n\n// src/edge/own/fs-bridge.js\nfunction encodeReply(res) {\n if (res && res.error)\n return { kind: 0, bytes: enc.encode(JSON.stringify({ e: res.error.code, m: res.error.message })) };\n const v = res ? res.value : null;\n if (v instanceof Uint8Array)\n return { kind: 1, bytes: v };\n return { kind: 0, bytes: enc.encode(JSON.stringify({ v: v === undefined ? null : v })) };\n}\nasync function serveFsCall(memory, slot, route, onDone) {\n const slotWords = () => new Int32Array(memory.buffer, slot, 9);\n const w = slotWords();\n const cap = w[3];\n const replyPtr = w[4];\n const inLen = w[6] + w[8];\n let outLen = 0;\n let method = \"\";\n let result;\n try {\n const bytes = new Uint8Array(memory.buffer);\n const req = JSON.parse(dec.decode(bytes.slice(w[5], w[5] + w[6])));\n method = req.m;\n const data = w[8] ? bytes.slice(w[7], w[7] + w[8]) : new Uint8Array(0);\n result = await route.handle(req.m, req.a, data);\n } catch (e) {\n result = { error: { code: \"EIO\", message: String(e && e.message || e) } };\n }\n let failed = null;\n try {\n const { kind, bytes } = encodeReply(result);\n const out = slotWords();\n outLen = bytes.length;\n if (bytes.length > cap) {\n Atomics.store(out, 2, bytes.length);\n Atomics.store(out, 0, 2);\n } else {\n new Uint8Array(memory.buffer, replyPtr, bytes.length).set(bytes);\n Atomics.store(out, 2, bytes.length);\n Atomics.store(out, 1, kind);\n Atomics.store(out, 0, 1);\n }\n } catch (e) {\n failed = e;\n const out = slotWords();\n const err = enc.encode(JSON.stringify({ e: \"EIO\", m: \"reply failed: \" + String(e && e.message || e).slice(0, 120) }));\n if (err.length <= cap) {\n new Uint8Array(memory.buffer, replyPtr, err.length).set(err);\n Atomics.store(out, 2, err.length);\n Atomics.store(out, 1, 0);\n Atomics.store(out, 0, 1);\n } else {\n Atomics.store(out, 2, err.length);\n Atomics.store(out, 0, 2);\n }\n }\n Atomics.notify(slotWords(), 0);\n if (onDone)\n onDone(method, inLen, outLen);\n if (failed)\n throw failed;\n return method;\n}\nvar enc, dec;\nvar init_fs_bridge = __esm(() => {\n enc = new TextEncoder;\n dec = new TextDecoder;\n});\n\n// src/edge/own/stdio-pipe.js\nclass StdinPipe {\n #mem;\n #addr;\n #cap;\n #off;\n #queue = [];\n #closing = false;\n #timer = null;\n #sleep;\n constructor(memory, info, { sleep = (fn, ms) => setTimeout(fn, ms) } = {}) {\n this.#mem = memory;\n this.#addr = info.addr;\n this.#cap = info.cap;\n this.#off = info.off;\n this.#sleep = sleep;\n }\n write(bytes) {\n if (this.#closing)\n throw new Error(\"stdin is closed\");\n if (bytes.length)\n this.#queue.push(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));\n this.#pump();\n }\n close() {\n this.#closing = true;\n this.#pump();\n }\n get pending() {\n return this.#queue.reduce((a, b) => a + b.length, 0);\n }\n #pump() {\n const words = new Int32Array(this.#mem.buffer, this.#addr, 3);\n const data = new Uint8Array(this.#mem.buffer);\n const base = this.#addr + this.#off;\n while (this.#queue.length) {\n const head = Atomics.load(words, 0) >>> 0;\n const tail = Atomics.load(words, 1) >>> 0;\n const free = this.#cap - (tail - head >>> 0);\n if (free <= 0)\n break;\n const chunk = this.#queue[0];\n const n = Math.min(free, chunk.length);\n const start = tail % this.#cap;\n const first = Math.min(n, this.#cap - start);\n data.set(chunk.subarray(0, first), base + start);\n if (n > first)\n data.set(chunk.subarray(first, n), base);\n Atomics.store(words, 1, tail + n | 0);\n if (n === chunk.length)\n this.#queue.shift();\n else\n this.#queue[0] = chunk.subarray(n);\n }\n if (this.#queue.length) {\n if (!this.#timer) {\n this.#timer = this.#sleep(() => {\n this.#timer = null;\n this.#pump();\n }, 5);\n }\n return;\n }\n if (this.#closing)\n Atomics.store(words, 2, 1);\n }\n}\nfunction setTtySize(memory, addr, cols, rows) {\n const w = new Int32Array(memory.buffer, addr, 4);\n Atomics.store(w, 0, cols | 0);\n Atomics.store(w, 1, rows | 0);\n Atomics.add(w, 3, 1);\n}\n\n// src/edge/own/memcap.js\nfunction readLeb(b, i) {\n let r = 0;\n let s = 0;\n for (;; ) {\n const x = b[i++];\n r += (x & 127) * 2 ** s;\n s += 7;\n if (!(x & 128))\n return [r, i];\n }\n}\nfunction writePadded(b, at, len, value) {\n for (let k = 0;k < len; k++) {\n const part = value % 128;\n value = Math.floor(value / 128);\n b[at + k] = part | (k < len - 1 ? 128 : 0);\n }\n}\nfunction capMemoryMax(wasm, maxPages) {\n const b = wasm instanceof Uint8Array ? wasm : new Uint8Array(wasm);\n let i = 8;\n while (i < b.length) {\n const id = b[i++];\n let size;\n [size, i] = readLeb(b, i);\n const end = i + size;\n if (id === 2) {\n let [count, j] = readLeb(b, i);\n for (let n = 0;n < count; n++) {\n let l;\n [l, j] = readLeb(b, j);\n j += l;\n [l, j] = readLeb(b, j);\n j += l;\n const kind = b[j++];\n if (kind === 0)\n [, j] = readLeb(b, j);\n else if (kind === 1) {\n j++;\n const [fl, k] = readLeb(b, j);\n j = k;\n [, j] = readLeb(b, j);\n if (fl & 1)\n [, j] = readLeb(b, j);\n } else if (kind === 2) {\n const r = capLimits(b, j, maxPages);\n if (r.done)\n return r;\n j = r.next;\n } else if (kind === 3)\n j += 2;\n else {\n j++;\n [, j] = readLeb(b, j);\n }\n }\n } else if (id === 5) {\n const [count, j0] = readLeb(b, i);\n let j = j0;\n for (let n = 0;n < count; n++) {\n const r = capLimits(b, j, maxPages);\n if (r.done)\n return r;\n j = r.next;\n }\n }\n i = end;\n }\n return { bytes: b, before: null, after: null };\n}\nfunction capLimits(b, j, maxPages) {\n const [flags, a] = readLeb(b, j);\n const [min, c] = readLeb(b, a);\n if (!(flags & 1))\n return { done: false, next: c };\n const [max, d] = readLeb(b, c);\n const len = d - c;\n const cap = Math.max(maxPages, min);\n if (max <= cap)\n return { done: true, bytes: b, before: max, after: max };\n if (cap >= 128 ** len)\n throw new Error(\"memory cap does not fit the number it replaces\");\n const out = b.slice();\n writePadded(out, c, len, cap);\n return { done: true, bytes: out, before: max, after: cap };\n}\nvar PAGE = 65536, pagesOfMiB = (mib) => Math.floor(mib * 1024 * 1024 / PAGE);\n\n// src/edge/own/loader.js\nvar hasJspi = () => typeof WebAssembly.promising === \"function\" && typeof WebAssembly.Suspending === \"function\";\n\n// src/edge/own/procfs.js\nfunction content(path, bytes) {\n const pages = Math.ceil(bytes / PAGE_SIZE);\n if (path === \"/proc/self/statm\")\n return enc2.encode(`${pages} ${pages} 0 0 0 ${pages} 0\n`);\n return enc2.encode(`1 (node) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 0 ${bytes} ${pages} 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0\n`);\n}\nfunction withProc(route, memoryBytes) {\n const open = new Map;\n let next = FIRST;\n const clean = (p) => String(p ?? \"\").replace(/\\/+$/, \"\") || \"/\";\n const handle = (method, args, data) => {\n if (method === \"ctl\") {\n let q = null;\n try {\n q = JSON.parse(String(args[0] ?? \"\"));\n } catch {}\n if (q && q.op === \"meminfo\")\n return { value: JSON.stringify({ rss: memoryBytes() }) };\n }\n if (method === \"stat\" || method === \"open\" || method === \"readdir\") {\n const p = clean(args[0]);\n if (p === \"/proc/self\" || p === \"/proc\") {\n if (method === \"stat\")\n return { value: statDir(p === \"/proc\" ? 5 : 6) };\n if (method === \"readdir\") {\n const names = p === \"/proc\" ? [[\"self\", \"d\"]] : [[\"stat\", \"f\"], [\"statm\", \"f\"]];\n return { value: { l: names.map(([n, k]) => ({ n, ...k === \"d\" ? statDir(6) : statOf(1, n === \"stat\" ? 3 : 4) })), d: true } };\n }\n }\n if (FILES.has(p)) {\n if (method === \"stat\")\n return { value: statOf(content(p, memoryBytes()).length, p.endsWith(\"m\") ? 4 : 3) };\n const f = args[1] || {};\n if (f.w || f.c || f.cn || f.t || f.a)\n return EROFS;\n const h = next++;\n open.set(h, { p, bytes: content(p, memoryBytes()) });\n return { value: { h } };\n }\n } else if ((method === \"read\" || method === \"fstat\" || method === \"close\" || method === \"write\" || method === \"ftruncate\") && Number(args[0]) >= FIRST) {\n const e = open.get(args[0]);\n if (method === \"close\") {\n open.delete(args[0]);\n return { value: null };\n }\n if (!e)\n return EBADF;\n if (method === \"read\")\n return { value: e.bytes.subarray(Number(args[1] ?? 0), Number(args[1] ?? 0) + Number(args[2] ?? 0)) };\n if (method === \"fstat\")\n return { value: statOf(e.bytes.length, e.p.endsWith(\"m\") ? 4 : 3) };\n return EROFS;\n }\n return route.handle(method, args, data);\n };\n return {\n handle,\n queueSignal: (...a) => route.queueSignal?.(...a),\n get children() {\n return route.children;\n },\n get route() {\n return route;\n }\n };\n}\nvar PAGE_SIZE = 65536, enc2, FIRST, FILES, EROFS, EBADF, statOf = (size, ino) => ({ k: \"f\", s: size, a: \"0\", m: \"0\", c: \"0\", i: ino, nl: 1, md: 33060, u: 0, g: 0, rd: 0 }), statDir = (ino) => ({ k: \"d\", s: 4096, a: \"0\", m: \"0\", c: \"0\", i: ino, nl: 2, md: 16749, u: 0, g: 0, rd: 0 });\nvar init_procfs = __esm(() => {\n enc2 = new TextEncoder;\n FIRST = 2 ** 40;\n FILES = new Set([\"/proc/self/stat\", \"/proc/self/statm\"]);\n EROFS = { error: { code: \"EROFS\", message: \"EROFS\" } };\n EBADF = { error: { code: \"EBADF\", message: \"EBADF\" } };\n});\n\n// src/edge/own/marks.js\nclass MarkBook {\n first = {};\n last = {};\n n = {};\n all = {};\n add(name, t) {\n if (typeof name !== \"string\" || typeof t !== \"number\")\n return;\n if (this.first[name] === undefined)\n this.first[name] = t;\n if (this.last[name] === undefined || t > this.last[name])\n this.last[name] = t;\n this.n[name] = (this.n[name] || 0) + 1;\n const a = this.all[name] ||= [];\n if (a.length < 64)\n a.push(t);\n }\n}\nfunction stagesOf(m) {\n const pick = (k) => Array.isArray(k) ? k.map((x) => m[x]).find((v) => typeof v === \"number\") : m[k];\n const out = {};\n for (const [name, a, b] of STAGES) {\n const x = pick(a);\n const y = pick(b);\n if (typeof x === \"number\" && typeof y === \"number\")\n out[name] = Math.round((y - x) * 10) / 10;\n }\n return out;\n}\nvar PROGRAM_BYTES, at = () => performance.timeOrigin + performance.now(), STAGES;\nvar init_marks = __esm(() => {\n PROGRAM_BYTES = 8 << 20;\n STAGES = [\n [\"fwLoad\", \"frame\", \"fw\"],\n [\"check\", \"load0\", \"checked\"],\n [\"rtCompile\", \"rtc0\", \"rtc1\"],\n [\"program\", \"start0\", \"program\"],\n [\"shim\", \"program\", \"shim\"],\n [\"boot\", \"shim\", \"booted\"],\n [\"toMain\", \"runPost\", \"runRecv\"],\n [\"compile\", \"compile0\", \"compile1\"],\n [\"toInst\", \"compile1\", \"inst0\"],\n [\"inst\", \"inst0\", \"inst1\"],\n [\"toOut\", \"inst1\", \"firstOut\"],\n [\"tail\", [\"firstOut\", \"inst1\"], \"exitRecv\"],\n [\"exitHop\", \"exitPost\", \"exitRecv\"],\n [\"run\", \"runPost\", \"exitRecv\"]\n ];\n});\n\n// src/edge/own/fs-stats.js\nfunction readFsStats(buffer, addr) {\n if (!buffer || !addr || addr % 8 !== 0 || addr + 80 > buffer.byteLength)\n return null;\n const w = new BigUint64Array(buffer, addr, 10);\n const v = (i) => Number(Atomics.load(w, i));\n return {\n n: v(0),\n us: v(1),\n stat: { n: v(2), us: v(3) },\n ctl: { n: v(4), us: v(5) },\n other: { n: v(6), us: v(7) },\n firstMs: v(8) ? v(8) / 1000 : null,\n lastMs: v(9) ? v(9) / 1000 : null\n };\n}\n\n// src/edge/own/hub.js\nfunction runOptionsJson({ fs, cwd, stdin, tty, children, exec, shim, net = false, jspi, argv0 }) {\n return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...argv0 ? { argv0 } : {} });\n}\n\nclass OwnRuntime {\n #opts;\n #create;\n #module = null;\n #memory = null;\n #main = null;\n #pool = null;\n #booted = null;\n #capi = `wmd-own-capi-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n #scopes = 0;\n #byScope = new Map;\n #big = new Map;\n #bigHeld = new Map;\n #wants = new Map;\n #runs = new Map;\n #nextRun = 1;\n #dead = false;\n #outsSeen = 0;\n #capiN = { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 };\n #capiHeld = new Map;\n #countWait = new Map;\n #countSeq = 0;\n #held = [];\n #glue;\n #stdin = null;\n #ttyAddr = 0;\n static async start(opts) {\n const rt = new OwnRuntime(opts);\n await rt.#boot();\n return rt;\n }\n constructor(opts) {\n this.#opts = { spare: 2, max: 128, stack: 4 * 1024 * 1024, memoryMaxMiB: 1024, onOut: () => {}, onLog: () => {}, ...opts };\n this.#create = this.#opts.create || ((url, o) => new Worker(url, o));\n const base = typeof location === \"undefined\" ? undefined : location.href;\n this.#glue = new URL(this.#opts.glueUrl, base).href;\n if (this.#opts.marks)\n this.#marks = new MarkBook;\n }\n #routeCache = null;\n #marks = null;\n #calls = null;\n get marks() {\n if (!this.#marks)\n return null;\n const fs = this.#fsStat && this.#memory ? readFsStats(this.#memory.buffer, this.#fsStat) : null;\n const first = { ...this.#marks.first };\n for (const [k, v] of Object.entries(this.#marks.last))\n if (this.#marks.n[k] > 1)\n first[k + \"Last\"] = v;\n if (fs && fs.firstMs)\n first.fsFirst = fs.firstMs;\n if (fs && fs.lastMs)\n first.fsLast = fs.lastMs;\n return { first, n: { ...this.#marks.n }, series: Object.fromEntries(Object.entries(this.#marks.all).filter(([k, v]) => v.length > 1).map(([k, v]) => [k, [...v]])), fs, memMiB: this.#memory ? Math.round(this.#memory.buffer.byteLength / 1048576) : null, ...this.#calls ? { calls: this.#calls } : {} };\n }\n #fsT = globalThis.__wmdFsTime ? new Map : null;\n #timed(t0) {\n const tr = performance.timeOrigin + performance.now();\n return (method, inB, outB) => {\n const td = performance.timeOrigin + performance.now();\n const m = this.#fsT.get(method) || { n: 0, serveMs: 0, waitMs: 0, postMs: 0, inB: 0, outB: 0 };\n m.n++;\n m.serveMs += td - tr;\n if (typeof t0 === \"number\") {\n m.waitMs += td - t0;\n m.postMs += tr - t0;\n }\n m.inB += inB;\n m.outB += outB;\n this.#fsT.set(method, m);\n };\n }\n get fsTiming() {\n return this.#fsT ? Object.fromEntries(this.#fsT) : null;\n }\n #note(text) {\n try {\n const r = this.#opts.fsRoute && this.#opts.fsRoute.handle && this.#opts.fsRoute.handle(\"note\", [String(text).slice(0, 160)], new Uint8Array(0));\n if (r && typeof r.catch === \"function\")\n r.catch(() => {});\n } catch {}\n }\n #route() {\n if (!this.#opts.fsRoute)\n return NO_ROUTE;\n return this.#routeCache ||= withProc(this.#opts.fsRoute, () => this.#memory.buffer.byteLength);\n }\n async#boot() {\n const { wasmUrl, workerUrl, stack } = this.#opts;\n try {\n this.#module = this.#opts.module || await WebAssembly.compileStreaming(fetch(wasmUrl));\n } catch (e) {\n const err = new Error(`the runtime's wasm did not load (${wasmUrl}): ${String(e && e.message || e)}`);\n err.runtimeFiles = true;\n throw err;\n }\n this.#main = this.#create(workerUrl, { type: \"module\", name: \"wmd-own-main\" });\n this.#main.addEventListener(\"message\", (e) => this.#fromWorker(e.data));\n this.#main.addEventListener(\"error\", (e) => this.#fatal(new Error(\"runtime main worker: \" + (e.message || \"error\"))));\n const ready = new Promise((resolve, reject) => this.#booted = { resolve, reject });\n this.#byScope.set(this.#scopes + 1, this.#main);\n this.#main.postMessage({ type: \"init\", role: \"main\", capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}, fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, glue: this.#glue, ...this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}, module: this.#module, stack });\n const up = await ready;\n this.#memory = up.memory;\n this.#stdin = new StdinPipe(this.#memory, up.stdin);\n this.#ttyAddr = up.tty;\n this.#pool = new WorkerPool({\n create: () => this.#create(workerUrl, { type: \"module\", name: \"wmd-own-thread\" }),\n init: (w) => (this.#byScope.set(this.#scopes + 1, w), w.postMessage({ type: \"init\", role: \"thread\", capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}, fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, trace: this.#opts.trace | 0, glue: this.#glue, ...this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}, module: this.#module, memory: this.#memory, stack })),\n spare: this.#opts.spare,\n max: this.#opts.max,\n idleMs: this.#opts.poolIdleMs | 0,\n onRetire: (_id, w) => {\n for (const [k, v] of this.#byScope)\n if (v === w)\n this.#byScope.delete(k);\n },\n onMessage: (_id, data) => this.#fromWorker(data),\n onFailure: (_id, tasks, err) => {\n this.#note(\"thread ended: \" + String(err && err.message || err).slice(0, 140));\n for (const t of tasks)\n this.#refuse(t.ack, err);\n }\n });\n this.#pool.warm();\n }\n run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = \"null\", tty = {}, children = false, exec, shim = false, net = false, argv0 }) {\n if (this.#dead)\n return Promise.reject(new Error(\"runtime terminated\"));\n const id = this.#nextRun++;\n let buf = null;\n if (ready) {\n this.memoryCap = ready.cap;\n } else {\n buf = program instanceof ArrayBuffer ? program.slice(0) : program.buffer.slice(program.byteOffset, program.byteOffset + program.byteLength);\n if (this.#opts.memoryMaxMiB) {\n const cap = capMemoryMax(new Uint8Array(buf), pagesOfMiB(this.#opts.memoryMaxMiB));\n this.memoryCap = { before: cap.before, after: cap.after };\n if (cap.bytes.buffer !== buf)\n buf = cap.bytes.buffer;\n }\n }\n return new Promise((resolve, reject) => {\n this.#runs.set(id, { resolve, reject });\n const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0 });\n if (tty.cols || tty.rows)\n setTtySize(this.#memory, this.#ttyAddr, tty.cols || 80, tty.rows || 24);\n this.#calls = null;\n if (ready)\n this.#main.postMessage({ type: \"run\", id, program: ready.bytes, module: ready.module, hash: ready.hash, args, env, node, opts });\n else\n this.#main.postMessage({ type: \"run\", id, program: buf, args, env, node, opts }, [buf]);\n });\n }\n static async prepare(program, { memoryMaxMiB = 1024, compile = (b) => WebAssembly.compile(b), digest = (b) => crypto.subtle.digest(\"SHA-256\", b) } = {}) {\n let bytes = program instanceof Uint8Array ? program : new Uint8Array(program);\n let cap = { before: null, after: null };\n if (memoryMaxMiB) {\n const c = capMemoryMax(bytes, pagesOfMiB(memoryMaxMiB));\n cap = { before: c.before, after: c.after };\n bytes = c.bytes;\n }\n const plain = typeof SharedArrayBuffer === \"function\" && bytes.buffer instanceof SharedArrayBuffer ? bytes.slice() : bytes;\n const [hash, module] = await Promise.all([digest(plain), compile(plain)]);\n if (typeof SharedArrayBuffer === \"function\" && !(bytes.buffer instanceof SharedArrayBuffer)) {\n try {\n const shared = new Uint8Array(new SharedArrayBuffer(bytes.length));\n shared.set(bytes);\n bytes = shared;\n } catch {}\n }\n return { bytes, hash: new Uint8Array(hash), module, cap, memoryMaxMiB };\n }\n writeStdin(bytes) {\n this.#stdin.write(bytes);\n }\n closeStdin() {\n this.#stdin.close();\n }\n resize(cols, rows) {\n setTtySize(this.#memory, this.#ttyAddr, cols, rows);\n }\n get memoryBytes() {\n return this.#memory ? this.#memory.buffer.byteLength : 0;\n }\n collectCounts(ms = 400) {\n if (this.#dead)\n return Promise.resolve([]);\n const ws = [this.#main, ...this.#pool ? this.#pool.workers : []].filter(Boolean);\n const seq = ++this.#countSeq;\n return new Promise((resolve) => {\n const w = { got: [], want: ws.length };\n const end = () => {\n this.#countWait.delete(seq);\n resolve(w.got);\n };\n w.end = end;\n this.#countWait.set(seq, w);\n const t = setTimeout(end, ms);\n w.clear = () => clearTimeout(t);\n for (const x of ws) {\n try {\n x.postMessage({ type: \"counts\", seq });\n } catch {\n w.want--;\n }\n }\n if (w.got.length >= w.want)\n w.clear(), end();\n });\n }\n #forged = 0;\n get forged() {\n return this.#forged;\n }\n get capiStats() {\n return { ...this.#capiN };\n }\n #capiHold(k, data) {\n const have = this.#big.get(k);\n const e = have ? (have.data = data, have) : { data, size: payloadBytes((data.msg || {}).envelope), sent: new Set };\n if (!have) {\n this.#big.set(k, e);\n const c = this.#capiN;\n c.messages++;\n c.bytes += e.size;\n c.maxMessage = Math.max(c.maxMessage, e.size);\n c.heldBytes += e.size * 2;\n this.#bigHeld.set(k, e.size * 2);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n }\n const asks = this.#wants.get(k);\n if (asks) {\n this.#wants.delete(k);\n for (const sc of asks)\n this.#capiServe(k, e, sc);\n }\n }\n #capiWant(k, scope) {\n const e = this.#big.get(k);\n if (e)\n return this.#capiServe(k, e, scope);\n const asks = this.#wants.get(k) || new Set;\n asks.add(scope);\n this.#wants.set(k, asks);\n if (this.#wants.size > 4096)\n this.#wants.delete(this.#wants.keys().next().value);\n }\n #capiServe(k, e, scope) {\n const w = this.#byScope.get(scope);\n if (!w || e.sent.has(scope))\n return;\n e.sent.add(scope);\n const c = this.#capiN;\n c.copies++;\n c.copyBytes += e.size;\n c.maxRecipients = Math.max(c.maxRecipients, e.sent.size);\n c.heldBytes += e.size;\n this.#bigHeld.set(k, (this.#bigHeld.get(k) || 0) + e.size);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n try {\n w.postMessage(e.data);\n } catch {}\n }\n #countCapi(data) {\n const c = this.#capiN;\n const m = data.msg || {};\n const to = [this.#main, ...this.#pool ? this.#pool.workers : []].filter(Boolean).length;\n const size = payloadBytes(m.envelope);\n const k = `${m.registry}:${m.handle}`;\n if (m.t === \"share\") {\n c.messages++;\n c.bytes += size;\n c.copies += to;\n c.copyBytes += size * to;\n c.maxMessage = Math.max(c.maxMessage, size);\n c.maxRecipients = Math.max(c.maxRecipients, to);\n const held = size * (to + 1);\n c.heldBytes += held - (this.#capiHeld.get(k) || 0);\n this.#capiHeld.set(k, held);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n } else if (m.t === \"delete\" && this.#capiHeld.has(k)) {\n c.heldBytes -= this.#capiHeld.get(k);\n this.#capiHeld.delete(k);\n }\n if (m.t === \"delete\" && this.#bigHeld.has(k)) {\n c.heldBytes -= this.#bigHeld.get(k);\n this.#bigHeld.delete(k);\n }\n }\n #fsStat = 0;\n #sigWake = 0;\n #sigFlags = [];\n get workerCount() {\n return this.#dead ? 0 : 1 + (this.#pool ? this.#pool.live : 0);\n }\n get pool() {\n return this.#pool;\n }\n signal(n) {\n if (n === 9)\n return this.terminate();\n this.#opts.fsRoute?.queueSignal?.(0, n);\n if (this.#sigWake && this.#memory) {\n const w = new Int32Array(this.#memory.buffer);\n Atomics.add(w, this.#sigWake >> 2, 1);\n Atomics.notify(w, this.#sigWake >> 2);\n }\n }\n terminate() {\n this.#dead = true;\n if (this.#main)\n this.#main.terminate();\n if (this.#pool)\n this.#pool.terminateAll();\n this.#fatal(new Error(\"runtime terminated\"));\n }\n #fromWorker(data) {\n switch (data && data.type) {\n case \"ready\":\n if (this.#booted)\n this.#booted.resolve(data);\n this.#booted = null;\n break;\n case \"out\":\n this.#outsSeen++;\n this.#opts.onOut(data.fd, data.data);\n this.#release();\n break;\n case \"spawn\":\n this.#spawn(data);\n break;\n case \"mark\":\n if (this.#marks)\n this.#marks.add(data.name, data.t);\n break;\n case \"calls\":\n if (this.#marks && (!this.#calls || sumCalls(data.totals) >= sumCalls(this.#calls.totals)))\n this.#calls = { seen: data.seen, wrapped: data.wrapped, ring: data.ring, totals: data.totals, inst: data.inst };\n break;\n case \"counts\": {\n const w = this.#countWait.get(data.seq);\n if (w) {\n w.got.push({ role: data.role, c: data.c });\n if (w.got.length >= w.want)\n w.clear(), w.end();\n }\n break;\n }\n case \"capi\": {\n const m = data.msg || {};\n const k = `${m.registry}:${m.handle}`;\n if (m.t === \"want\")\n return this.#capiWant(k, m.from);\n if (m.t === \"share\" && payloadBytes(m.envelope) >= BIG_SHARE)\n return this.#capiHold(k, data);\n if (m.t === \"share\")\n this.#wants.delete(k);\n if (m.t === \"delete\") {\n this.#big.delete(k);\n this.#wants.delete(k);\n }\n this.#countCapi(data);\n for (const w of [this.#main, ...this.#pool ? this.#pool.workers : []])\n if (w)\n w.postMessage(data);\n break;\n }\n case \"fs\":\n serveFsCall(this.#memory, data.slot, this.#route(), this.#fsT ? this.#timed(data.t0) : undefined).then((m) => {\n if (m === \"peek\")\n this.#note(\"hub: peek answered\");\n }).catch((e) => {\n this.#note(\"fs call failed: \" + String(e && e.message || e).slice(0, 120));\n this.#opts.onLog({ type: \"log\", text: \"fs call failed: \" + (e && e.message) });\n });\n break;\n case \"fsstat\":\n if (Number.isInteger(data.addr))\n this.#fsStat = data.addr;\n break;\n case \"sigflag\":\n if (data.wake)\n this.#sigWake = data.wake;\n if (data.buffer && data.buffer.byteLength >= data.addr + 4 && data.addr % 4 === 0)\n this.#sigFlags.push({ words: new Int32Array(data.buffer), at: data.addr >> 2, bits: data.bits | 0 });\n break;\n case \"sigraise\":\n for (const f of this.#sigFlags)\n Atomics.or(f.words, f.at, f.bits);\n break;\n case \"note\": {\n this.#note(String(data.text));\n break;\n }\n case \"exit\":\n case \"run-error\": {\n const end = exitOfRun(data, this.#runs);\n if (end)\n this.#held.push(end);\n this.#release();\n break;\n }\n case \"fatal\":\n this.#fatal(new Error(data.error));\n break;\n default:\n this.#forged++;\n }\n }\n #release() {\n const ready = this.#held.filter((d) => this.#outsSeen >= (d.outs || 0));\n if (!ready.length)\n return;\n this.#held = this.#held.filter((d) => !ready.includes(d));\n for (const d of ready) {\n const run = this.#runs.get(d.id);\n this.#runs.delete(d.id);\n if (!run)\n continue;\n if (d.type === \"exit\")\n run.resolve({ code: d.code });\n else\n run.reject(new Error(d.error));\n }\n }\n #spawn(data) {\n if (this.#marks)\n this.#marks.add(\"spawnReq\", performance.timeOrigin + performance.now());\n if (this.#opts.debug)\n console.log(\"[hub] spawn request, ack\", data.ack, \"pool\", JSON.stringify({ live: this.#pool.live, idle: this.#pool.idle, busy: this.#pool.busy, starting: this.#pool.starting }));\n try {\n this.#pool.dispatch({ type: \"task\", msg: data.msg, ack: data.ack });\n } catch (err) {\n this.#refuse(data.ack, err);\n }\n }\n #refuse(ack, err) {\n this.#opts.onLog({ type: \"log\", text: \"spawn refused: \" + (err && err.message) });\n if (!ack || !this.#memory)\n return;\n const words = new Int32Array(this.#memory.buffer);\n Atomics.compareExchange(words, ack >> 2, 0, 2);\n Atomics.notify(words, ack >> 2);\n }\n #fatal(err) {\n if (this.#booted)\n this.#booted.reject(err);\n this.#booted = null;\n for (const run of this.#runs.values())\n run.reject(err);\n this.#runs.clear();\n }\n}\nvar NO_ROUTE, sumCalls = (t) => Object.values(t || {}).reduce((s, v) => s + (parseInt(v, 10) || 0), 0);\nvar init_hub = __esm(() => {\n init_payload_size();\n init_fs_bridge();\n init_procfs();\n init_marks();\n NO_ROUTE = { handle: () => ({ error: { code: \"ENOSYS\", message: \"this runtime has no file route\" } }) };\n});\n\n// src/edge/own/wasm-counters.js\nfunction installWasmCounters(g) {\n if (g.__wmdWasmCounters)\n return g.__wmdWasmCounters;\n const W = g.WebAssembly;\n const c = {\n compile: { calls: 0, bytes: 0, ms: 0 },\n stream: { calls: 0, bytes: 0, ms: 0 },\n instantiate: { calls: 0, bytes: 0, ms: 0 },\n module: { calls: 0, bytes: 0, ms: 0, maxMs: 0 },\n memory: { made: 0, shared: 0, madeBytes: 0 },\n fetched: {}\n };\n const refs = [];\n const kinds = [];\n const wrapAsync = (name, slot, bytesOf) => {\n const orig = W[name];\n if (typeof orig !== \"function\")\n return;\n W[name] = function(...a) {\n c[slot].calls++;\n c[slot].bytes += bytesOf ? bytesOf(a[0]) : 0;\n const t0 = performance.now();\n const p = orig.apply(this, a);\n return p && typeof p.then === \"function\" ? p.finally(() => c[slot].ms += performance.now() - t0) : p;\n };\n };\n wrapAsync(\"compile\", \"compile\", sizeOf);\n wrapAsync(\"instantiate\", \"instantiate\", sizeOf);\n const streamBytes = (r) => {\n try {\n return Number(r && r.headers && r.headers.get && r.headers.get(\"content-length\")) || 0;\n } catch {\n return 0;\n }\n };\n wrapAsync(\"compileStreaming\", \"stream\", null);\n wrapAsync(\"instantiateStreaming\", \"stream\", null);\n if (W.Module) {\n W.Module = new Proxy(W.Module, {\n construct(target, args) {\n const t0 = performance.now();\n const m = Reflect.construct(target, args);\n const ms = performance.now() - t0;\n c.module.calls++;\n c.module.bytes += sizeOf(args[0]);\n c.module.ms += ms;\n c.module.maxMs = Math.max(c.module.maxMs, ms);\n return m;\n }\n });\n }\n if (W.Memory) {\n W.Memory = new Proxy(W.Memory, {\n construct(target, args) {\n const d = args[0] || {};\n const m = Reflect.construct(target, args);\n c.memory.made++;\n if (d.shared)\n c.memory.shared++;\n refs.push(new WeakRef(m));\n kinds.push({ ref: new WeakRef(m), initial: d.initial | 0, maximum: d.maximum, shared: !!d.shared });\n return m;\n }\n });\n }\n const R = g.Response && g.Response.prototype;\n if (R && R.arrayBuffer) {\n const orig = R.arrayBuffer;\n R.arrayBuffer = async function() {\n const b = await orig.call(this);\n const k = kind(this.url);\n const f = c.fetched[k] ||= { calls: 0, bytes: 0 };\n f.calls++;\n f.bytes += b.byteLength;\n return b;\n };\n }\n const api = {\n kinds() {\n return kinds.map((k) => {\n const m = k.ref.deref();\n return { initial: k.initial, maximum: k.maximum, shared: k.shared, pages: m ? m.buffer.byteLength / 65536 : null };\n });\n },\n snapshot() {\n let live = 0;\n let liveBytes = 0;\n for (let i = refs.length - 1;i >= 0; i--) {\n const m = refs[i].deref();\n if (!m)\n continue;\n live++;\n try {\n liveBytes += m.buffer.byteLength;\n } catch {}\n }\n return JSON.parse(JSON.stringify({ ...c, memory: { ...c.memory, live, liveBytes }, kinds: api.kinds() }));\n }\n };\n g.__wmdWasmCounters = api;\n return api;\n}\nfunction addCounts(a, b) {\n const out = JSON.parse(JSON.stringify(a || {}));\n const walk = (dst, src) => {\n for (const [k, v] of Object.entries(src || {})) {\n if (v && typeof v === \"object\")\n walk(dst[k] ||= {}, v);\n else\n dst[k] = (Number(dst[k]) || 0) + (Number(v) || 0);\n }\n };\n walk(out, b);\n return out;\n}\nvar kind = (url) => {\n const u = String(url || \"\");\n if (/edgejs\\.wasm/.test(u))\n return \"program\";\n if (/wmd_browser_bg\\.wasm/.test(u))\n return \"runtime\";\n if (/wmd_browser\\.js/.test(u))\n return \"glue\";\n if (/HASHES\\.txt/.test(u))\n return \"hashes\";\n if (/linux\\.cjs/.test(u))\n return \"shim\";\n return \"other\";\n}, sizeOf = (src) => {\n try {\n if (src && typeof src.byteLength === \"number\")\n return src.byteLength;\n if (src && src.buffer && typeof src.buffer.byteLength === \"number\")\n return src.buffer.byteLength;\n } catch {}\n return 0;\n};\n\n// src/edge/own/node-globals.js\nvar NODE_GLOBALS;\nvar init_node_globals = __esm(() => {\n NODE_GLOBALS = Object.freeze([\n \"AbortController\",\n \"AbortSignal\",\n \"AggregateError\",\n \"Array\",\n \"ArrayBuffer\",\n \"AsyncDisposableStack\",\n \"Atomics\",\n \"BigInt\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Blob\",\n \"Boolean\",\n \"BroadcastChannel\",\n \"Buffer\",\n \"ByteLengthQueuingStrategy\",\n \"CloseEvent\",\n \"CompressionStream\",\n \"CountQueuingStrategy\",\n \"Crypto\",\n \"CryptoKey\",\n \"CustomEvent\",\n \"DOMException\",\n \"DataView\",\n \"Date\",\n \"DecompressionStream\",\n \"DisposableStack\",\n \"Error\",\n \"EvalError\",\n \"Event\",\n \"EventTarget\",\n \"File\",\n \"FinalizationRegistry\",\n \"Float16Array\",\n \"Float32Array\",\n \"Float64Array\",\n \"FormData\",\n \"Function\",\n \"Headers\",\n \"Infinity\",\n \"Int16Array\",\n \"Int32Array\",\n \"Int8Array\",\n \"Intl\",\n \"Iterator\",\n \"JSON\",\n \"Map\",\n \"Math\",\n \"MessageChannel\",\n \"MessageEvent\",\n \"MessagePort\",\n \"NaN\",\n \"Navigator\",\n \"Number\",\n \"Object\",\n \"Performance\",\n \"PerformanceEntry\",\n \"PerformanceMark\",\n \"PerformanceMeasure\",\n \"PerformanceObserver\",\n \"PerformanceObserverEntryList\",\n \"PerformanceResourceTiming\",\n \"Promise\",\n \"Proxy\",\n \"RangeError\",\n \"ReadableByteStreamController\",\n \"ReadableStream\",\n \"ReadableStreamBYOBReader\",\n \"ReadableStreamBYOBRequest\",\n \"ReadableStreamDefaultController\",\n \"ReadableStreamDefaultReader\",\n \"ReferenceError\",\n \"Reflect\",\n \"RegExp\",\n \"Request\",\n \"Response\",\n \"Set\",\n \"SharedArrayBuffer\",\n \"String\",\n \"SubtleCrypto\",\n \"SuppressedError\",\n \"Symbol\",\n \"SyntaxError\",\n \"TextDecoder\",\n \"TextDecoderStream\",\n \"TextEncoder\",\n \"TextEncoderStream\",\n \"TransformStream\",\n \"TransformStreamDefaultController\",\n \"TypeError\",\n \"URIError\",\n \"URL\",\n \"URLPattern\",\n \"URLSearchParams\",\n \"Uint16Array\",\n \"Uint32Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"WeakMap\",\n \"WeakRef\",\n \"WeakSet\",\n \"WebAssembly\",\n \"WebSocket\",\n \"WritableStream\",\n \"WritableStreamDefaultController\",\n \"WritableStreamDefaultWriter\",\n \"atob\",\n \"btoa\",\n \"clearImmediate\",\n \"clearInterval\",\n \"clearTimeout\",\n \"console\",\n \"crypto\",\n \"decodeURI\",\n \"decodeURIComponent\",\n \"encodeURI\",\n \"encodeURIComponent\",\n \"escape\",\n \"eval\",\n \"fetch\",\n \"global\",\n \"globalThis\",\n \"isFinite\",\n \"isNaN\",\n \"navigator\",\n \"parseFloat\",\n \"parseInt\",\n \"performance\",\n \"process\",\n \"queueMicrotask\",\n \"setImmediate\",\n \"setInterval\",\n \"setTimeout\",\n \"structuredClone\",\n \"undefined\",\n \"unescape\"\n ]);\n});\n\n// src/edge/shim.js\nfunction nodeVersionJs(v) {\n if (typeof v !== \"string\" || !NODE_VERSION.test(v))\n return \"\";\n return `\n;(() => {\n const version = ${JSON.stringify(v)};\n const hide = (o, k, value) => Object.defineProperty(o, k, { value, writable: false, enumerable: true, configurable: true });\n hide(process, 'version', version);\n if (process.versions) hide(process.versions, 'node', version.slice(1));\n})();\n`;\n}\nfunction withoutSymlinkOverride(links) {\n const a = links.indexOf(SYMLINK_FROM);\n const b = links.indexOf(SYMLINK_TO);\n if (a < 0 || b < a || links.split(PROMISE_SYMLINK).length !== 2)\n throw new Error(\"shim.js: the symlink block of BROWSER_LINKS moved; withoutSymlinkOverride needs a change\");\n const middle = links.slice(a, b);\n const at = middle.indexOf(\" if (fs.promises) {\");\n return links.slice(0, a) + middle.slice(at).replace(PROMISE_SYMLINK, \"\") + links.slice(b);\n}\nfunction shimSource(src, settings, { symlinks = true } = {}) {\n for (const [name, text] of [[\"settings marker\", SETTINGS_MARKER], [\"__wmdCtl take\", TAKE], [\"ctlError\", LINKS_MARKER], [\"signal table\", SIG_TABLE_FROM], [\"signal emit\", SIG_EMIT_FROM]]) {\n const n = src.split(text).length - 1;\n if (n !== 1)\n throw new Error(`linux.cjs: the ${name} is there ${n} times, not once; the browser shim needs a change`);\n }\n return src.replace(SETTINGS_MARKER, () => JSON.stringify(settings)).replace(TAKE, () => TAKE_HERE).replace(SIG_TABLE_FROM, () => SIG_TABLE_TO).replace(SIG_EMIT_FROM, () => SIG_EMIT_TO).replace(LINKS_MARKER, () => (symlinks ? BROWSER_LINKS : withoutSymlinkOverride(BROWSER_LINKS)) + LINKS_MARKER) + nodeVersionJs(settings && settings.nodeVersion);\n}\nvar SETTINGS_MARKER = \"/*__WMD_EDGE_CONFIG__*/{}\", TAKE = `const hostCtl = globalThis.__wmdCtl;\n delete globalThis.__wmdCtl;`, TAKE_HERE = `const realGlobal = Function('return this')();\n const hostCtl = globalThis.__wmdCtl || realGlobal.__wmdCtl;\n delete globalThis.__wmdCtl;\n delete realGlobal.__wmdCtl;`, LINKS_MARKER = \" function ctlError(r, syscall, p) {\", BROWSER_LINKS = ` {\n const pathOf = p => (typeof p === 'string' ? p : Buffer.isBuffer(p) ? p.toString() : null);\n const viaCtl = (op, p, key) => {\n const s = pathOf(p);\n if (s === null) return null;\n try { const r = ctl({ op, path: require('path').resolve(s) }); return r.err ? null : r[key]; } catch (_) { return null; }\n };\n const origRealpathSync = fs.realpathSync;\n const realpathSync = function realpathSync(p, o) {\n const r = viaCtl('realpath', p, 'path');\n if (r === null) return origRealpathSync.apply(fs, arguments);\n return o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r;\n };\n realpathSync.native = realpathSync;\n fs.realpathSync = realpathSync;\n const realpath = function realpath(p, o, cb) {\n if (typeof o === 'function') { cb = o; o = undefined; }\n let r;\n try { r = realpathSync(p, o); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null, r);\n };\n realpath.native = realpath;\n fs.realpath = realpath;\n const origReadlinkSync = fs.readlinkSync;\n const readlinkSync = function readlinkSync(p, o) {\n const r = viaCtl('readlink', p, 'target');\n return r === null ? origReadlinkSync.apply(fs, arguments) : (o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r);\n };\n fs.readlinkSync = readlinkSync;\n const origReadlink = fs.readlink;\n fs.readlink = function readlink(p, o, cb) {\n if (typeof o === 'function') { cb = o; o = undefined; }\n if (viaCtl('readlink', p, 'target') === null) return origReadlink.apply(fs, arguments);\n let r;\n try { r = readlinkSync(p, o); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null, r);\n };\n // The mount has no symlink call either; a link is made by the control request (npm's node_modules/.bin links).\n const symlinkSync = function symlinkSync(target, path) {\n const s = pathOf(path);\n if (s === null) return origSymlinkSync.apply(fs, arguments);\n const full = require('path').resolve(s);\n const r = ctl({ op: 'symlink', path: full, target: String(pathOf(target) === null ? target : pathOf(target)) });\n if (r.err) throw ctlError(r, 'symlink', s);\n };\n const origSymlinkSync = fs.symlinkSync;\n fs.symlinkSync = symlinkSync;\n fs.symlink = function symlink(target, path, type, cb) {\n if (typeof type === 'function') cb = type;\n try { symlinkSync(target, path); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null);\n };\n if (fs.promises) {\n fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n fs.promises.realpath = async function realpath(p, o) { return realpathSync(p, o); };\n const origP = fs.promises.readlink;\n fs.promises.readlink = async function readlink(p, o) { return viaCtl('readlink', p, 'target') === null ? origP.apply(fs.promises, arguments) : readlinkSync(p, o); };\n }\n // The page's run has pipes for stdio (the stub sent a terminal's run to the guest's own node), but the SDK's pipes look like a\n // character device to node, so process.stdout.isTTY is true and npm would draw progress. The guest's node says undefined.\n for (const name of ['stdin', 'stdout', 'stderr']) {\n const d = Object.getOwnPropertyDescriptor(process, name);\n if (!d || !d.get) continue;\n Object.defineProperty(process, name, {\n configurable: true,\n enumerable: d.enumerable,\n get() {\n const st = d.get.call(process);\n if (st && st.isTTY) { try { delete st.isTTY; } catch (_) {} if (st.isTTY) { try { Object.defineProperty(st, 'isTTY', { value: undefined, configurable: true }); } catch (_) {} } }\n return st;\n },\n });\n }\n }\n`, NODE_VERSION, SYMLINK_FROM = \" // The mount has no symlink call either; a link is made by the control request\", SYMLINK_TO = \" // The page's run has pipes for stdio\", PROMISE_SYMLINK = ` fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n`, SIG_TABLE_FROM = \" const SIG_NAMES = { 1: 'SIGHUP', 2: 'SIGINT', 3: 'SIGQUIT', 15: 'SIGTERM' };\", SIG_NAMES_LINUX, SIG_IGNORED_LINUX, SIG_TABLE_TO, SIG_EMIT_FROM = ` if (process.listenerCount(name) > 0) {\n process.emit(name, name);\n } else {`, SIG_EMIT_TO = ` if (process.listenerCount(name) > 0) {\n // tell the page that a handler takes it: the program is not stuck and is not cut off after the grace period (fix7)\n try { ctl({ op: 'signal_taken', n: sig, handled: true }); } catch (_) {}\n process.emit(name, name, sig);\n } else if (SIG_IGNORED.has(sig)) {\n // the default action of this signal leaves the program running\n } else {\n // the default action ends the program: the page learns it, so that the stub dies of the signal as node in the guest does (R4)\n try { ctl({ op: 'signal_taken', n: sig, handled: false }); } catch (_) {}`;\nvar init_shim = __esm(() => {\n NODE_VERSION = /^v\\d+\\.\\d+\\.\\d+$/;\n SIG_NAMES_LINUX = {\n 1: \"SIGHUP\",\n 2: \"SIGINT\",\n 3: \"SIGQUIT\",\n 4: \"SIGILL\",\n 5: \"SIGTRAP\",\n 6: \"SIGABRT\",\n 7: \"SIGBUS\",\n 8: \"SIGFPE\",\n 10: \"SIGUSR1\",\n 11: \"SIGSEGV\",\n 12: \"SIGUSR2\",\n 13: \"SIGPIPE\",\n 14: \"SIGALRM\",\n 15: \"SIGTERM\",\n 16: \"SIGSTKFLT\",\n 17: \"SIGCHLD\",\n 18: \"SIGCONT\",\n 19: \"SIGSTOP\",\n 20: \"SIGTSTP\",\n 21: \"SIGTTIN\",\n 22: \"SIGTTOU\",\n 23: \"SIGURG\",\n 24: \"SIGXCPU\",\n 25: \"SIGXFSZ\",\n 26: \"SIGVTALRM\",\n 27: \"SIGPROF\",\n 28: \"SIGWINCH\",\n 29: \"SIGIO\",\n 30: \"SIGPWR\",\n 31: \"SIGSYS\"\n };\n SIG_IGNORED_LINUX = [10, 13, 17, 18, 19, 20, 21, 22, 23, 28];\n SIG_TABLE_TO = ` const SIG_NAMES = ${JSON.stringify(SIG_NAMES_LINUX)};\n const SIG_IGNORED = new Set(${JSON.stringify(SIG_IGNORED_LINUX)});`;\n});\n\n// src/edge/tz.js\nfunction utcClock(g) {\n const RealDate = g.Date;\n const proto = RealDate.prototype;\n const realOffset = proto.getTimezoneOffset;\n const DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n const p2 = (n) => String(n).padStart(2, \"0\");\n const pairs = [[\"FullYear\"], [\"Month\"], [\"Date\"], [\"Day\"], [\"Hours\"], [\"Minutes\"], [\"Seconds\"], [\"Milliseconds\"]];\n const def = (name, fn) => Object.defineProperty(proto, name, { value: fn, writable: true, configurable: true, enumerable: false });\n for (const [n] of pairs) {\n def(\"get\" + n, function() {\n return this[\"getUTC\" + n]();\n });\n if (n !== \"Day\")\n def(\"set\" + n, function(...a) {\n return this[\"setUTC\" + n](...a);\n });\n }\n def(\"getYear\", function() {\n return this.getUTCFullYear() - 1900;\n });\n def(\"setYear\", function(y) {\n return this.setUTCFullYear(y >= 0 && y <= 99 ? 1900 + y : y);\n });\n def(\"getTimezoneOffset\", function() {\n return Number.isNaN(this.getTime()) ? NaN : 0;\n });\n const year = (y) => y >= 0 ? String(y).padStart(4, \"0\") : \"-\" + String(-y).padStart(4, \"0\");\n const dateText = (d) => `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${p2(d.getUTCDate())} ${year(d.getUTCFullYear())}`;\n const timeText = (d) => `${p2(d.getUTCHours())}:${p2(d.getUTCMinutes())}:${p2(d.getUTCSeconds())} GMT+0000 (Coordinated Universal Time)`;\n const valid = (d, f) => Number.isNaN(d.getTime()) ? \"Invalid Date\" : f(d);\n def(\"toString\", function() {\n return valid(this, (d) => dateText(d) + \" \" + timeText(d));\n });\n def(\"toDateString\", function() {\n return valid(this, dateText);\n });\n def(\"toTimeString\", function() {\n return valid(this, timeText);\n });\n for (const name of [\"toLocaleString\", \"toLocaleDateString\", \"toLocaleTimeString\"]) {\n const orig = proto[name];\n def(name, function(loc, opt) {\n return orig.call(this, loc, { timeZone: \"UTC\", ...opt });\n });\n }\n const isoDate = /^(?:\\+\\d{6}|-(?!000000)\\d{6}|\\d{4})(?:-\\d\\d(?:-\\d\\d)?)?$/;\n const isoLocalTime = /^(?:[+-]\\d{6}|\\d{4})-\\d\\d-\\d\\dT\\d\\d:\\d\\d(?::\\d\\d(?:\\.\\d+)?)?$/i;\n const hasZone = /(\\dZ|\\b(?:GMT|UTC|UT|[ECMP][SD]T|Z)\\b|(?:\\b(?:GMT|UTC|UT)|\\d:\\d\\d(?::\\d\\d(?:\\.\\d+)?)?\\s*|\\s)[+-]\\d{1,2}(?::?\\d{2})?)\\s*(\\([^)]*\\))?\\s*$/i;\n const zonedInside = /\\b(?:GMT|UTC|UT)\\b|\\b[ECMP][SD]T\\b|\\dZ\\b|\\s[+-]\\d{2}:?\\d{2}\\b/i;\n const dayBefore = (t) => realOffset.call(new RealDate(t - 86400000));\n const parse = (v) => {\n const s = String(v);\n const t = RealDate.parse(s);\n if (isoDate.test(s) || hasZone.test(s))\n return t;\n const off = Number.isNaN(t) || zonedInside.test(s) ? 0 : realOffset.call(new RealDate(t));\n const iso = isoLocalTime.test(s);\n for (const tail of iso ? [\"Z\"] : [\" GMT\", \"Z\"]) {\n const u = RealDate.parse(s + tail);\n if (!Number.isNaN(u) && (iso || u !== t || off === 0 || dayBefore(t) === 0))\n return u;\n }\n if (Number.isNaN(t))\n return NaN;\n if (!zonedInside.test(s) && !s.includes(\":\") && t % 86400000 === 0 && realOffset.call(new RealDate(t)) !== 0)\n return t;\n const offT = realOffset.call(new RealDate(t));\n let c = t - offT * 60000;\n const offB = dayBefore(t);\n if (offB !== offT) {\n const d = new RealDate(c);\n if (!new RegExp(\"(^|\\\\D)0?\" + d.getUTCHours() + \":\" + p2(d.getUTCMinutes()) + \"(\\\\D|$)\").test(s))\n c = t - offB * 60000;\n }\n return new RealDate(c).getTime();\n };\n const D = new Proxy(RealDate, {\n construct(t, a, nt) {\n if (a.length >= 2)\n return Reflect.construct(t, [RealDate.UTC(...a)], nt);\n if (a.length === 1 && typeof a[0] === \"string\")\n return Reflect.construct(t, [parse(a[0])], nt);\n return Reflect.construct(t, a, nt);\n },\n apply: () => new D().toString(),\n get: (t, k, r) => k === \"parse\" ? parse : Reflect.get(t, k, t)\n });\n Object.defineProperty(proto, \"constructor\", { value: D, writable: true, configurable: true, enumerable: false });\n g.Date = D;\n const DTF = g.Intl.DateTimeFormat;\n g.Intl.DateTimeFormat = new Proxy(DTF, {\n construct: (t, [loc, opt], nt) => Reflect.construct(t, [loc, { timeZone: \"UTC\", ...opt }], nt),\n apply: (t, th, [loc, opt]) => t(loc, { timeZone: \"UTC\", ...opt })\n });\n}\nfunction withUtcClock(src) {\n const head = \"'use strict';\";\n if (src.split(head).length !== 2 || !src.startsWith(head))\n throw new Error(\"linux.cjs: 'use strict' is not the first statement, once; the browser's clock needs a change\");\n return head + `\n(${utcClock})(globalThis);` + src.slice(head.length);\n}\nvar UTC_NAME_LIST, UTC_NAMES;\nvar init_tz = __esm(() => {\n UTC_NAME_LIST = [\"\", \"UTC\", \"UTC0\", \"Etc/UTC\", \"GMT\", \"GMT0\", \"Etc/GMT\", \"Etc/GMT0\", \"Etc/Universal\", \"Etc/Zulu\", \"Universal\", \"Zulu\", \"Z\", \":UTC\"];\n UTC_NAMES = new Set(UTC_NAME_LIST);\n});\n\n// src/edge/own/shim-post.js\nfunction ownShimPost(process, realGlobal, g, utcClock2, utcNames = [], req = null, sigNames = null, sigIgnored = null) {\n process.memoryUsage.rss = function rss() {\n return process.memoryUsage().rss;\n };\n {\n const engineMemory = process.memoryUsage;\n const memoryUsage = function memoryUsage() {\n const m = engineMemory.apply(process, arguments);\n const js = realGlobal && realGlobal.performance && realGlobal.performance.memory;\n if (m && js && js.usedJSHeapSize > 0) {\n m.heapUsed = js.usedJSHeapSize;\n m.heapTotal = js.totalJSHeapSize || js.usedJSHeapSize;\n m.rss = (m.rss || 0) + m.heapTotal;\n }\n return m;\n };\n memoryUsage.rss = function rss() {\n return process.memoryUsage().rss;\n };\n process.memoryUsage = memoryUsage;\n }\n try {\n const st = realGlobal && realGlobal[Symbol.for(\"wasmer.napi.serdes.state\")];\n const B = g && g.Buffer;\n if (st && typeof B === \"function\")\n st.bufferOf = (u8) => B.from(u8.buffer, u8.byteOffset, u8.byteLength);\n } catch {}\n if (sigNames && typeof process.kill === \"function\") {\n const nativeKill = process.kill;\n const byName = {};\n for (const n of Object.keys(sigNames))\n byName[sigNames[n]] = Number(n);\n byName.SIGKILL = 9;\n const ignored = new Set(sigIgnored || []);\n const later = (f) => typeof g.setImmediate === \"function\" ? g.setImmediate(f) : setTimeout(f, 0);\n process.kill = function kill(pid, sig) {\n const mine = pid === process.pid || pid === 0 || pid === \"0\" || String(pid) === String(process.pid) || String(pid) === \"-\" + process.pid;\n if (!mine)\n return nativeKill.apply(process, arguments);\n if (sig === 0 || sig === \"0\")\n return true;\n const num = sig === undefined ? 15 : typeof sig === \"number\" ? sig : byName[sig];\n const name = num === 9 ? \"SIGKILL\" : sigNames[num];\n if (!name)\n return nativeKill.apply(process, arguments);\n if (num !== 9 && process.listenerCount(name) > 0) {\n later(() => process.emit(name, name, num));\n return true;\n }\n if (num !== 9 && (ignored.has(num) || num === 10))\n return true;\n process.reallyExit(128 + num);\n return true;\n };\n }\n {\n let state = 0;\n const mainThread = () => {\n try {\n const wt = typeof req === \"function\" ? req(\"worker_threads\") : null;\n return !wt || wt.isMainThread !== false;\n } catch {\n return true;\n }\n };\n for (const name of [\"exit\", \"reallyExit\"]) {\n const native = process[name];\n if (typeof native !== \"function\")\n continue;\n process[name] = function() {\n if (state === 2)\n return;\n const outer = state === 0;\n state = 1;\n let ret;\n try {\n ret = native.apply(process, arguments);\n } finally {\n if (outer)\n state = 2;\n }\n const now = realGlobal && realGlobal.__wmdExitNow;\n if (typeof now === \"function\" && mainThread())\n now(name === \"reallyExit\" ? arguments[0] : process.exitCode, process.pid);\n return ret;\n };\n }\n }\n if (realGlobal && typeof realGlobal.addEventListener === \"function\") {\n realGlobal.addEventListener(\"unhandledrejection\", (ev) => {\n ev.preventDefault();\n const reason = ev.reason;\n if (process.emit(\"unhandledRejection\", reason, ev.promise))\n return;\n if (process.listenerCount(\"uncaughtException\") > 0) {\n process.emit(\"uncaughtException\", reason, \"unhandledRejection\");\n return;\n }\n const text = reason instanceof Error ? String(reason.stack || reason) : `[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"${String(reason)}\".] { code: 'ERR_UNHANDLED_REJECTION' }`;\n process.stderr.write(text + `\n`);\n process.exit(1);\n });\n }\n const fs = typeof req === \"function\" ? req(\"fs\") : null;\n if (fs && typeof fs.renameSync === \"function\") {\n const isDir = (p) => {\n try {\n return fs.lstatSync(p).isDirectory();\n } catch {\n return false;\n }\n };\n const fixed = (e, from, to) => {\n if (!e || e.code !== \"EINVAL\" || !isDir(to) || isDir(from))\n return e;\n const x = new Error(`EISDIR: illegal operation on a directory, rename '${from}' -> '${to}'`);\n return Object.assign(x, { errno: -21, code: \"EISDIR\", syscall: \"rename\", path: String(from), dest: String(to) });\n };\n const moveLink = (from, to) => {\n let text;\n try {\n if (!fs.lstatSync(from).isSymbolicLink())\n return false;\n text = fs.readlinkSync(from);\n let there = null;\n try {\n there = fs.lstatSync(to);\n } catch {}\n if (there && there.isDirectory())\n return false;\n if (there)\n fs.unlinkSync(to);\n fs.symlinkSync(text, to);\n fs.unlinkSync(from);\n return true;\n } catch {\n return false;\n }\n };\n const isLink = (p) => {\n try {\n return fs.lstatSync(p).isSymbolicLink();\n } catch {\n return false;\n }\n };\n const renameSync = fs.renameSync;\n fs.renameSync = function(from, to) {\n if (isLink(from) && moveLink(from, to))\n return;\n try {\n return renameSync.call(fs, from, to);\n } catch (e) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return;\n throw fixed(e, from, to);\n }\n };\n const rename = fs.rename;\n fs.rename = function(from, to, cb) {\n if (typeof cb !== \"function\")\n return rename.call(fs, from, to, cb);\n if (isLink(from) && moveLink(from, to))\n return void queueMicrotask(() => cb(null));\n return rename.call(fs, from, to, function(e, ...a) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return cb(null);\n cb(e ? fixed(e, from, to) : e, ...a);\n });\n };\n if (fs.promises && typeof fs.promises.rename === \"function\") {\n const prename = fs.promises.rename;\n fs.promises.rename = async function(from, to) {\n if (isLink(from) && moveLink(from, to))\n return;\n try {\n return await prename.call(fs.promises, from, to);\n } catch (e) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return;\n throw fixed(e, from, to);\n }\n };\n }\n }\n const tz = process.env && process.env.TZ;\n if (typeof utcClock2 === \"function\" && utcNames.includes(String(tz == null ? \"\" : tz).trim()))\n utcClock2(g);\n}\nvar SHIM_POST;\nvar init_shim_post = __esm(() => {\n init_tz();\n init_shim();\n SHIM_POST = `\n;(${ownShimPost.toString()})(process, Function('return this')(), globalThis, ${utcClock.toString()}, ${JSON.stringify(UTC_NAME_LIST)}, typeof require === 'function' ? require : null, ${JSON.stringify(SIG_NAMES_LINUX)}, ${JSON.stringify(SIG_IGNORED_LINUX)});\n`;\n});\n\n// src/edge/own/adapter.js\nvar exports_adapter = {};\n__export(exports_adapter, {\n exit: () => exit,\n keep: () => keep,\n load: () => load,\n name: () => name,\n prepare: () => prepare,\n release: () => release,\n setDeps: () => setDeps,\n signal: () => signal,\n start: () => start,\n stats: () => stats,\n teardown: () => teardown\n});\nfunction runtimeFile(text) {\n const e = new Error(text);\n e.runtimeFiles = true;\n return e;\n}\nasync function fetchOk(url) {\n let r;\n try {\n r = await deps.fetch(url);\n } catch (e) {\n throw runtimeFile(`${absUrl(url)} could not be fetched: ${whyOf(e)}`);\n }\n if (r.ok === false) {\n const e = new Error(`${r.url || url} answered ${r.status}${r.statusText ? \" \" + r.statusText : \"\"}`);\n e.runtimeFiles = true;\n throw e;\n }\n return r;\n}\nasync function readFile(url, as) {\n const r = await fetchOk(url);\n try {\n return as === \"text\" ? await r.text() : new Uint8Array(await r.arrayBuffer());\n } catch (e) {\n throw runtimeFile(`${r.url || absUrl(url)} could not be read: ${whyOf(e)}`);\n }\n}\nfunction setDeps(d) {\n deps = { ...deps, ...d };\n}\n\nclass Pipe {\n #chunks = [];\n #waiters = [];\n #done = false;\n bytes = 0;\n late = 0;\n taken = 0;\n push(b) {\n if (!b.length)\n return;\n this.bytes += b.length;\n if (this.#done)\n this.late += b.length;\n if (this.#waiters.length)\n this.#waiters.shift()(b);\n else\n this.#chunks.push(b);\n }\n end() {\n this.#done = true;\n for (const w of this.#waiters.splice(0))\n w(null);\n }\n async read(n) {\n if (this.#chunks.length)\n return this.#take(n);\n if (this.#done)\n return null;\n const b = await new Promise((r) => this.#waiters.push(r));\n if (b === null)\n return null;\n this.#chunks.unshift(b);\n return this.#take(n);\n }\n #take(n) {\n const c = this.#chunks[0];\n if (c.length <= n) {\n this.taken += c.length;\n return this.#chunks.shift();\n }\n this.#chunks[0] = c.subarray(n);\n this.taken += n;\n return c.subarray(0, n);\n }\n}\nfunction portRoute(p) {\n let next = 1;\n const pending = new Map;\n p.onmessage = (e) => {\n const m = e.data;\n const w = m && pending.get(m.id);\n if (!w)\n return;\n pending.delete(m.id);\n w(m.reply);\n };\n const route = {\n queueSignal: (id, n) => {\n route.handle(\"sigq\", [id, n], new Uint8Array(0));\n },\n handle: (method, args, data) => new Promise((resolve) => {\n const id = next++;\n pending.set(id, resolve);\n p.postMessage(globalThis.__wmdFsTime ? { own: \"fs\", id, method, args, data, t0: performance.timeOrigin + performance.now() } : { own: \"fs\", id, method, args, data });\n }),\n close: () => {\n try {\n p.postMessage({ own: \"bye\" });\n } catch {}\n for (const w of pending.values())\n w({ error: { code: \"EIO\", message: \"the file route closed\" } });\n pending.clear();\n }\n };\n return route;\n}\nasync function checkFiles(own, files) {\n const base = own.wasmUrl.replace(/[^/?#]*([?#].*)?$/, \"\");\n let text = null;\n try {\n const r = await deps.fetch(own.hashesUrl || base + \"HASHES.txt\");\n if (r.ok !== false)\n text = await r.text();\n } catch {}\n if (text === null) {\n files.missing++;\n return {};\n }\n const want = new Map;\n for (const line of String(text).split(`\n`)) {\n const [hash, size, name2] = line.trim().split(/\\s+/);\n if (name2 && /^[0-9a-f]{64}$/.test(hash))\n want.set(name2, { hash, size: Number(size) });\n }\n const out = {};\n for (const [key, name2] of [[\"wasmUrl\", \"wmd_browser_bg.wasm\"], [\"glueUrl\", \"wmd_browser.js\"]]) {\n const w = want.get(name2);\n if (!w) {\n files.unlisted++;\n continue;\n }\n const bytes = await readFile(own[key], \"bytes\");\n files.checked++;\n if (bytes.length !== w.size || await sha256(bytes) !== w.hash) {\n files.mismatch++;\n throw runtimeFile(`the runtime's files do not match HASHES.txt: ${name2} at ${absUrl(own[key])} (size ${bytes.length}, listed ${w.size}); not run`);\n }\n files.ok++;\n if (key === \"wasmUrl\") {\n mark(\"rtc0\");\n try {\n out.module = await deps.compile(bytes);\n } catch (e) {\n throw runtimeFile(`${absUrl(own[key])} did not compile as WebAssembly: ${whyOf(e)}`);\n }\n mark(\"rtc1\");\n }\n }\n return out;\n}\nfunction keep() {\n const k = state && state.keep;\n return k && (k.rtModule || k.prog) ? { ...k, texts: { ...k.texts } } : null;\n}\nasync function runtimeModule(own) {\n const k = state.kept;\n if (k && k.rtModule) {\n state.module = k.rtModule;\n state.files.kept = 1;\n state.keep.rtModule = k.rtModule;\n mark(\"checked\");\n return;\n }\n const tc = performance.now();\n const ok = await checkFiles(own, state.files);\n state.stages.check = performance.now() - tc;\n mark(\"checked\");\n state.module = ok.module;\n if (state.keep && ok.module)\n state.keep.rtModule = ok.module;\n}\nasync function programOf(module, memoryMaxMiB) {\n const s = state;\n let ready = s.kept && s.kept.prog && s.kept.prog.url === module ? s.kept.prog : null;\n let program = null;\n if (ready) {\n s.stages.keptProgram = 1;\n } else {\n program = await readFile(module, \"bytes\");\n if (s.keep && deps.OwnRuntime.prepare) {\n try {\n ready = { ...await deps.OwnRuntime.prepare(program, memoryMaxMiB ? { memoryMaxMiB } : undefined), url: module };\n } catch (e) {\n throw runtimeFile(`${absUrl(module)} is not a node program the runtime can compile: ${whyOf(e)}`);\n }\n program = null;\n }\n }\n if (s.keep && ready)\n s.keep.prog = ready;\n return { program, ready };\n}\nasync function linuxText(src) {\n const s = state;\n let raw = s.keep && s.keep.texts[src];\n if (typeof raw !== \"string\") {\n raw = await readFile(src, \"text\");\n try {\n shimSource(raw, {}, { symlinks: false });\n } catch (e) {\n throw runtimeFile(`${absUrl(src)} is not the settings file: ${whyOf(e)}`);\n }\n }\n if (s.keep)\n s.keep.texts[src] = raw;\n return raw;\n}\nfunction newState(own, kept, more) {\n const k = keptFor(own, kept);\n state = { own, out: new Pipe, err: new Pipe, t0: performance.now(), signals: [], files: { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 }, module: undefined, stages: {}, marks: own.marks ? { ...globalThis.__wmdFwMarks || {} } : null, ...more };\n state.kept = k;\n state.keep = own.keepMods !== false ? { wasmUrl: own.wasmUrl, glueUrl: own.glueUrl, rtModule: null, prog: null, texts: { ...k ? k.texts : {} } } : null;\n mark(\"load0\");\n}\nasync function load({ cfg, ports, log, onWorkerError, kept = null }) {\n const own = cfg.own || {};\n if (!own.wasmUrl || !own.glueUrl || !own.workerUrl)\n throw new Error(\"rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl\");\n if (own.fsTime)\n globalThis.__wmdFsTime = true;\n port = ports[0];\n route = portRoute(port);\n newState(own, kept, { log, onWorkerError });\n await runtimeModule(own);\n return {};\n}\nasync function prepare({ cfg, kept = null }) {\n const own = cfg.own || {};\n if (!own.wasmUrl || !own.glueUrl || !own.workerUrl)\n throw new Error(\"rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl\");\n if (own.keepMods === false)\n return { kept: false };\n newState(own, kept, {});\n await runtimeModule(own);\n await programOf(cfg.edgeWasm || \"/wasm/edgejs.wasm\", cfg.memoryMaxMiB);\n if (cfg.linux)\n await linuxText(cfg.linuxSrc || \"/wasm/linux.cjs\");\n return { kept: true, stages: { ...state.stages }, files: { ...state.files } };\n}\nasync function pythonShimText(src, linux) {\n const s = state;\n let raw = s.keep && s.keep.texts[src];\n if (typeof raw !== \"string\")\n raw = await readFile(src, \"text\");\n if (s.keep)\n s.keep.texts[src] = raw;\n const marker = '_cfg = {\"execPath\": \"\", \"arch\": \"\", \"hostname\": \"\", \"cpus\": 0, \"uid\": 0, \"gid\": 0} #__WMD_EDGE_CONFIG__#';\n if (!raw.includes(marker))\n throw runtimeFile(`${absUrl(src)} is not the python settings file`);\n const cfg = { execPath: linux.execPath, arch: linux.arch || \"arm64\", hostname: linux.hostname || \"wmd-web\", cpus: linux.cpus || 1, uid: linux.uid | 0, gid: linux.gid | 0 };\n return raw.replace(marker, () => `_cfg = (lambda true, false, null: ${JSON.stringify(cfg)})(True, False, None)`);\n}\nasync function start({ module, argv, env, cwd, files = {}, linux, linuxSrc, stdin = \"closed\", python }) {\n const s = state;\n let tm = performance.now();\n const lap = (name2) => {\n const now = performance.now();\n s.stages[name2] = now - tm;\n tm = now;\n };\n mark(\"start0\");\n const { program, ready } = await programOf(module, python && python.maxMiB);\n lap(\"program\");\n mark(\"program\");\n let args = argv;\n const shim = { ...files };\n if (python) {\n shim[\"startup.py\"] = await pythonShimText(linuxSrc || \"/wasm/linux.py\", linux || {});\n } else if (linux) {\n const text = shimSource(await linuxText(linuxSrc || \"/wasm/linux.cjs\"), linux, { symlinks: false }) + SHIM_POST;\n shim[\"linux.cjs\"] = text;\n args = [\"--require\", SHIM_PATH, ...argv];\n }\n await route.handle(\"shim\", [shim], new Uint8Array(0));\n lap(\"shim\");\n mark(\"shim\");\n if (globalThis.__wmdFsTime)\n await route.handle(\"timing\", [\"on\"], new Uint8Array(0));\n rt = await deps.OwnRuntime.start({\n wasmUrl: s.own.wasmUrl,\n ...s.module ? { module: s.module } : {},\n glueUrl: s.own.glueUrl,\n workerUrl: s.own.workerUrl,\n fsRoute: route,\n ...python && python.maxMiB ? { memoryMaxMiB: python.maxMiB } : {},\n marks: s.own.marks === 2 ? 2 : !!s.marks,\n onOut: (fd, b) => {\n if (s.stages.firstOut === undefined && b.length && s.runT0)\n s.stages.firstOut = performance.now() - s.runT0, mark(\"firstOut\");\n (fd === 2 ? s.err : s.out).push(b);\n },\n onLog: (d) => s.log?.(typeof d === \"string\" ? d : JSON.stringify(d)),\n stack: s.own.stack,\n ...s.own.trace ? { trace: s.own.trace | 0 } : {},\n nodeGlobals: NODE_GLOBALS\n });\n lap(\"boot\");\n mark(\"booted\");\n s.runT0 = performance.now();\n mark(\"runPost\");\n const envList = Object.entries({ HOME: \"/root\", ...env || {} }).map(([k, v]) => `${k}=${v}`);\n runP = rt.run({ program, ...ready ? { ready } : {}, args, env: envList, node: !python, cwd, stdin: stdin === \"pipe\" ? \"pipe\" : \"null\", tty: {}, children: s.own.children !== false, net: s.own.net !== false, exec: linux && linux.execPath, shim: !!linux && !python, ...python ? { argv0: python.argv0 } : {} }).then((r) => (r.code & ~127) === 16384 ? { exitCode: 128 + (r.code & 127), reason: \"exit\", signal: r.code & 127 } : { exitCode: r.code, reason: \"exit\" }, (e) => ({ exitCode: 1, reason: \"error: \" + String(e && e.message || e) })).then((r) => (mark(\"exitRecv\"), s.stages.run = performance.now() - s.runT0, s.out.end(), s.err.end(), r));\n return {\n readStdout: (n) => s.out.read(n),\n readStderr: (n) => s.err.read(n),\n writeStdin: async (bytes) => rt.writeStdin(bytes),\n closeStdin: async () => rt.closeStdin()\n };\n}\nasync function signal(proc, n) {\n if (n === 9)\n return rt?.terminate();\n return rt?.signal ? rt.signal(n) : undefined;\n}\nasync function exit() {\n const r = await runP;\n if (globalThis.__wmdFsTime && rt) {\n try {\n const t = (await route.handle(\"timing\", [\"read\"], new Uint8Array(0))).value;\n for (const [side, v] of [[\"hub\", rt.fsTiming], [\"route\", t]]) {\n const j = JSON.stringify(v);\n for (let i = 0;i < j.length; i += 140)\n await route.handle(\"note\", [`FSTAT ${side} ${i / 140} ` + j.slice(i, i + 140)], new Uint8Array(0));\n }\n } catch {}\n }\n return r;\n}\nasync function teardown() {\n rt?.terminate();\n}\nfunction release() {\n rt?.terminate();\n route?.close?.();\n return rt ? 1 : 0;\n}\nasync function stats() {\n let wasm = null;\n try {\n const mine = globalThis.__wmdWasmCounters ? globalThis.__wmdWasmCounters.snapshot() : null;\n let theirs = [];\n if (rt && state && state.own.counts) {\n const tc = performance.now();\n theirs = await rt.collectCounts(400);\n state.stages.counts = performance.now() - tc;\n }\n let sum = mine;\n for (const t of theirs)\n sum = addCounts(sum, t.c);\n if (sum)\n wasm = { ...sum, workers: theirs.length };\n if (wasm)\n wasm.kinds = [...globalThis.__wmdWasmCounters?.kinds?.() || [], ...theirs.flatMap((t) => t.c && t.c.kinds || [])];\n } catch {}\n let marks = null;\n if (state && state.marks) {\n const rm = rt && rt.marks || { first: {}, n: {} };\n const all = { ...rm.first, ...state.marks };\n for (const [k, v] of Object.entries(stagesOf(all)))\n state.stages[\"m.\" + k] = v;\n const base = state.marks.frame ?? state.marks.load0;\n marks = { t: Object.fromEntries(Object.entries(all).map(([k, v]) => [k, Math.round((v - base) * 10) / 10])), n: { ...rm.n }, ...rm.fs ? { fs: rm.fs } : {}, ...rm.series && Object.keys(rm.series).length ? { series: Object.fromEntries(Object.entries(rm.series).map(([k, v]) => [k, v.map((x) => Math.round((x - base) * 10) / 10)])) } : {}, ...rm.memMiB ? { memMiB: rm.memMiB } : {}, ...rm.calls ? { calls: rm.calls } : {} };\n }\n return {\n ...marks ? { marks } : {},\n service: null,\n frameRtt: null,\n ...wasm ? { wasm } : {},\n ...rt?.capiStats ? { capi: rt.capiStats } : {},\n ...rt && rt.forged ? { forged: rt.forged } : {},\n ...state ? { files: { ...state.files }, stages: { ...state.stages }, pipes: { out: state.out.bytes, err: state.err.bytes, lateOut: state.out.late, lateErr: state.err.late, unreadOut: state.out.bytes - state.out.taken, unreadErr: state.err.bytes - state.err.taken } } : {}\n };\n}\nvar name = \"own\", absUrl = (url) => {\n try {\n return new URL(url, globalThis.location && globalThis.location.href).href;\n } catch {\n return url;\n }\n}, whyOf = (e) => String(e && e.message || e).split(`\n`)[0], SHIM_PATH = \"/.wmd-edge/linux.cjs\", deps, rt = null, port = null, route = null, runP = null, state = null, mark = (name2) => {\n if (state && state.marks && state.marks[name2] === undefined)\n state.marks[name2] = at();\n}, sha256 = async (u8) => Array.from(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", u8)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\"), keptFor = (own, kept) => own.keepMods !== false && kept && kept.wasmUrl === own.wasmUrl && kept.glueUrl === own.glueUrl ? kept : null;\nvar init_adapter = __esm(() => {\n init_marks();\n init_hub();\n init_node_globals();\n init_shim();\n init_shim_post();\n deps = { OwnRuntime, fetch: (...a) => fetch(...a), compile: (b) => WebAssembly.compile(b) };\n});\n\n// src/edge/hist.js\nclass Hist {\n constructor() {\n this.n = 0;\n this.sumUs = 0;\n this.maxUs = 0;\n this.neg = 0;\n this.b = new Array(LOG2_BUCKETS).fill(0);\n }\n add(us) {\n if (us < 0) {\n this.neg++;\n us = 0;\n }\n this.n++;\n this.sumUs += us;\n if (us > this.maxUs)\n this.maxUs = us;\n const b = us < 1 ? 0 : Math.min(LOG2_BUCKETS - 1, Math.floor(Math.log2(us)) + 1);\n this.b[b]++;\n }\n quantileUs(q) {\n if (!this.n)\n return 0;\n const want = Math.ceil(this.n * q);\n let c = 0;\n for (let i = 0;i < this.b.length; i++) {\n c += this.b[i];\n if (c >= want)\n return i === 0 ? 1 : 2 ** i;\n }\n return this.maxUs;\n }\n summary() {\n return {\n n: this.n,\n meanUs: this.n ? +(this.sumUs / this.n).toFixed(1) : 0,\n maxUs: +this.maxUs.toFixed(1),\n neg: this.neg,\n p50Us: this.quantileUs(0.5),\n p90Us: this.quantileUs(0.9),\n p99Us: this.quantileUs(0.99),\n buckets: this.b.slice()\n };\n }\n}\nvar LOG2_BUCKETS = 24;\n\n// src/edge/sdk/forward.js\nclass Forwarder {\n constructor(port, respond) {\n this.port = port;\n this.respond = respond;\n this.pending = new Map;\n this.next = 1;\n this.rtt = {};\n this.stat = new Map;\n port.onmessage = ({ data: m }) => this.#reply(m);\n }\n send(m) {\n const id = this.next++;\n const t0 = performance.now();\n this.pending.set(id, { request: m, t0, method: m.method });\n this.port.postMessage({ id, mount: m.mount, method: m.method, args: m.args, t0: performance.timeOrigin + t0 });\n }\n #reply(m) {\n if (m.stats !== undefined || m.reset || m.plan) {\n const r = this.stat.get(m.id);\n this.stat.delete(m.id);\n if (r)\n r(m);\n return;\n }\n const p = this.pending.get(m.id);\n if (!p)\n return;\n this.pending.delete(m.id);\n (this.rtt[p.method] ||= new Hist).add((performance.now() - p.t0) * 1000);\n this.respond(p.request, m.res);\n }\n stats() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, (m) => res(m.stats));\n this.port.postMessage({ id, op: \"stats\" });\n });\n }\n plan() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, (m) => res(m.plan));\n this.port.postMessage({ id, op: \"plan\" });\n });\n }\n reset() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, () => res());\n this.port.postMessage({ id, op: \"reset\" });\n this.rtt = {};\n });\n }\n rttSummary() {\n return Object.fromEntries(Object.entries(this.rtt).map(([k, h]) => [k, h.summary()]));\n }\n}\nvar init_forward = () => {};\n\n// src/edge/workers.js\nfunction workerRegistry() {\n const made = new Set;\n return {\n track(w) {\n made.add(w);\n return w;\n },\n release() {\n const n = made.size;\n for (const w of [...made]) {\n made.delete(w);\n try {\n w.terminate();\n } catch {}\n }\n return n;\n },\n size: () => made.size\n };\n}\n\n// src/edge/spawn-guard.js\nfunction newSpawnMark() {\n const b = crypto.getRandomValues(new Uint8Array(6));\n return `${SPAWN_MARK.slice(0, -2)} [${Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\")}]: `;\n}\nfunction markScanner(mark) {\n let carry = \"\";\n let line = null;\n let done = false;\n return {\n push(text) {\n if (done)\n return;\n if (line === null) {\n const all = carry + text;\n const at = all.indexOf(mark);\n if (at < 0) {\n carry = all.slice(Math.max(0, all.length - (mark.length - 1)));\n return;\n }\n line = all.slice(at + mark.length);\n carry = \"\";\n } else\n line += text;\n const nl = line.indexOf(`\n`);\n if (nl < 0)\n return;\n done = true;\n return line.slice(0, nl);\n },\n finish: () => !done && line !== null ? (done = true, line) : undefined\n };\n}\nfunction spawnGuard(req, proc, mark, code) {\n const cp = req(\"child_process\");\n const fs = req(\"fs\");\n let refused = false;\n const refuse = (name, cmd) => {\n if (refused)\n throw new Error(\"spawn refused\");\n refused = true;\n const c = String(cmd == null ? \"\" : cmd).replace(/\\s+/g, \" \").slice(0, 200);\n const text = `${mark}${c}\nwmd: this program started a process (${name}), which node cannot do in the browser frame. It ends here. The next run of this program goes to the guest.\n`;\n try {\n fs.writeSync(2, text);\n } catch {}\n proc.exit(code);\n throw new Error(\"spawn refused: \" + c);\n };\n for (const name of [\"spawn\", \"spawnSync\", \"exec\", \"execSync\", \"execFile\", \"execFileSync\", \"fork\"]) {\n if (typeof cp[name] === \"function\")\n cp[name] = function(cmd) {\n return refuse(name, cmd);\n };\n }\n}\nfunction withSpawnGuard(src, mark = SPAWN_MARK) {\n return src + `\n;(${spawnGuard})(require, process, ${JSON.stringify(mark)}, ${SPAWN_EXIT});\n`;\n}\nvar SPAWN_MARK = \"wmd: spawn refused: \", SPAWN_EXIT = 126;\n\n// src/edge/sdk/adapter.js\nvar exports_adapter2 = {};\n__export(exports_adapter2, {\n exit: () => exit2,\n liveWorkers: () => liveWorkers,\n load: () => load2,\n name: () => name2,\n release: () => release2,\n signal: () => signal2,\n start: () => start2,\n stats: () => stats2,\n teardown: () => teardown2\n});\nfunction wrapWorkers(onWorkerError) {\n if (RealWorker)\n return;\n RealWorker = globalThis.Worker;\n globalThis.Worker = class extends RealWorker {\n constructor(...a) {\n super(...a);\n workers.track(this);\n this.addEventListener(\"message\", (e) => {\n const m = e.data;\n if (m && m.type === HOST_FS_MESSAGE && m.response && fwd) {\n e.stopImmediatePropagation();\n fwd.send(m);\n }\n });\n this.addEventListener(\"error\", (e) => onWorkerError?.(String(e && e.message || \"a Worker failed to load or crashed\")));\n }\n };\n}\nasync function load2({ cfg, ports, log, onWorkerError }) {\n baseUrl = cfg.rtBase || \"/sdk/\";\n wrapWorkers(onWorkerError);\n const t0 = performance.now();\n const hf = await import(baseUrl + \"dist/host-filesystem.js\");\n fwd = new Forwarder(ports[0], hf.respondToHostFileSystem);\n relay = workers.track(new RealWorker(\"/edge/sdk/relay.js\", { type: \"module\" }));\n relay.addEventListener(\"error\", (e) => onWorkerError?.(\"the relay Worker failed: \" + String(e && e.message || \"\")));\n await new Promise((r) => {\n relay.onmessage = () => r();\n relay.postMessage({ port: ports[1] }, [ports[1]]);\n });\n hf.installHostFileSystemWorkerBridge((msg) => (relay.postMessage(msg), true));\n const plan = await fwd.plan();\n if (plan.oversize.length)\n return { fallback: { reason: \"listing-too-large\", oversize: plan.oversize.slice(0, 20) } };\n const { Wasmer } = await import(baseUrl + \"dist/index.js\");\n wasmer = new Wasmer({ cache: \"memory\", parallelism: cfg.parallelism || 2 });\n core = await wasmer.getCore();\n log(\"sdk loaded after \" + (performance.now() - t0).toFixed(0) + \" ms\");\n return {};\n}\nasync function start2({ module, argv, env, cwd, mounts, files = {}, linux, linuxSrc, stdin = \"closed\", timeoutMs, parallelism, spawnMark }) {\n const edge = new Uint8Array(await (await fetch(module)).arrayBuffer());\n const fileBytes = Object.fromEntries(Object.entries(files).map(([p, t]) => [p, enc3.encode(t)]));\n let args = argv;\n if (linux) {\n const shim = \"/.wmd-edge/linux.cjs\";\n const src = await (await fetch(linuxSrc || \"/wasm/linux.cjs\")).text();\n const text = shimSource(src, linux);\n fileBytes[shim] = enc3.encode(withSpawnGuard(linux.utc ? withUtcClock(text) : text, spawnMark));\n args = [\"--require\", shim, ...args];\n }\n pkg = await core.createPackage({ modules: { node: edge }, commands: { node: { module: \"node\" } }, files: fileBytes });\n const b = core.sandbox();\n b.package(pkg);\n b.env(\"HOME\", \"/root\");\n for (const [k, v] of Object.entries(env || {}))\n b.env(k, v);\n b.network(\"disabled\");\n for (const [path, id, ro] of mounts)\n b.mountHost(path, id, ro);\n sb = await b.start();\n await fwd.reset();\n const cmd = sb.commandPackage(pkg);\n cmd.args(args);\n if (cwd)\n cmd.currentDir(cwd);\n cmd.timeoutMs(timeoutMs || 2147483647);\n cmd.stdinMode(stdin);\n cmd.stdoutMode(\"pipe\");\n cmd.stderrMode(\"pipe\");\n const pr = await cmd.spawn();\n return {\n pr,\n readStdout: (n) => pr.readStdout(n),\n readStderr: (n) => pr.readStderr(n),\n writeStdin: (bytes) => pr.writeStdin(bytes),\n closeStdin: () => pr.closeStdin()\n };\n}\nasync function signal2(proc, n) {\n if (n === 9)\n return proc.pr.kill();\n return proc.pr.terminate(2000);\n}\nasync function exit2(proc) {\n const w = await proc.pr.wait();\n return { exitCode: w.exitCode, reason: w.reason };\n}\nasync function teardown2() {\n try {\n await sb?.close();\n } finally {\n await wasmer?.close();\n }\n}\nfunction release2() {\n return workers.release();\n}\nasync function stats2() {\n return { service: fwd ? await fwd.stats() : null, frameRtt: fwd ? fwd.rttSummary() : null };\n}\nvar name2 = \"sdk\", HOST_FS_MESSAGE = \"wasmer-filesystem-rpc\", enc3, fwd = null, relay = null, wasmer = null, sb = null, pkg = null, core = null, baseUrl = \"/sdk/\", RealWorker = null, workers, liveWorkers = () => workers.size();\nvar init_adapter2 = __esm(() => {\n init_forward();\n init_shim();\n init_tz();\n enc3 = new TextEncoder;\n workers = workerRegistry();\n});\n\n// src/edge/sbx/worker-entry.js\ninit_hub();\ninit_adapter();\n\n// src/edge/runtime.js\nvar LOADERS = {\n own: () => Promise.resolve().then(() => (init_adapter(), exports_adapter)),\n sdk: null\n};\nvar RT_DEFAULT = \"own\";\nvar RT_NAMES = () => Object.keys(LOADERS);\nfunction handSdk(base) {\n if (typeof base !== \"string\" || !base.startsWith(\"/\") || !base.endsWith(\"/\"))\n throw new Error(\"sdkBase must be a path that starts and ends with '/'\");\n LOADERS.sdk = () => Promise.resolve().then(() => (init_adapter2(), exports_adapter2));\n return { rtBase: base };\n}\nfunction unavailable(rt) {\n if (!Object.hasOwn(LOADERS, rt))\n return `rt=${rt}: no such runtime (rt=${RT_NAMES().join(\"|\")})`;\n if (!LOADERS[rt])\n return rt === \"sdk\" ? \"rt=sdk: no SDK was handed in (the page option sdkBase), it is not in this build, node runs in the guest\" : `rt=${rt}: the runtime is not in this build, node runs in the guest`;\n return \"\";\n}\nasync function loadAdapter(rt, cfg = null) {\n if (rt === \"sdk\" && !LOADERS.sdk && cfg && typeof cfg.rtBase === \"string\") {\n try {\n handSdk(cfg.rtBase);\n } catch {}\n }\n const why = unavailable(rt);\n if (why)\n throw new Error(why);\n return LOADERS[rt]();\n}\n\n// src/edge/error-kind.js\nvar errorKindOf = (e, loading) => loading || e && e.runtimeFiles === true ? \"runtime\" : undefined;\nvar ERROR_KINDS = new Set([\"runtime\"]);\n\n// src/edge/worker.js\ninstallWasmCounters(globalThis);\nvar log = (text) => postMessage({ type: \"log\", text });\nvar errorText = (e) => {\n const stack = e && e.stack ? String(e.stack) : \"\";\n const msg = e && e.message !== undefined ? `${e.name || \"Error\"}: ${e.message}` : \"\";\n if (!msg)\n return stack || String(e);\n return stack.startsWith(msg) ? stack : stack ? msg + `\n` + stack : msg;\n};\nvar dec2 = new TextDecoder;\nvar enc4 = new TextEncoder;\nvar adapter = null;\nvar finished = false;\nvar done = (d) => {\n if (finished)\n return;\n finished = true;\n postMessage({ type: \"done\", ...d });\n};\nvar proc = null;\nvar early = [];\nasync function input(m) {\n if (!proc)\n return early.push(m);\n if (m.stdin)\n await proc.writeStdin(m.stdin);\n else if (m.stdinEnd)\n await proc.closeStdin();\n else if (m.signal)\n await adapter.signal(proc, m.signal);\n}\nonmessage = async ({ data: { cfg, ports, in: inp, tf, kept, prepare } }) => {\n if (inp)\n return input(inp);\n if (prepare) {\n try {\n const t0 = performance.now();\n adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg);\n const r = adapter.prepare ? await adapter.prepare({ cfg, kept }) : { kept: false };\n const k = adapter.keep ? adapter.keep() : null;\n if (k)\n postMessage({ type: \"keep\", keep: k });\n return done({ prepared: !!k, prepareMs: Math.round(performance.now() - t0), ...r.stages ? { stages: r.stages } : {} });\n } catch (e) {\n const kind = errorKindOf(e, false);\n return done({ error: String(e && e.message || e).slice(0, 300), ...kind ? { errorKind: kind } : {} });\n }\n }\n if (typeof tf === \"number\")\n globalThis.__wmdFwMarks = { frame: tf, fw: performance.timeOrigin + performance.now() };\n const res = {};\n let loading = true;\n try {\n const t0 = performance.now();\n adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg);\n const loaded = await adapter.load({\n cfg,\n ports,\n kept,\n log,\n onWorkerError: (why) => done({ error: \"the runtime lost a Worker: \" + why })\n });\n loading = false;\n if (loaded.fallback)\n return done({ fallback: true, ...loaded.fallback });\n const spawnMark = newSpawnMark();\n proc = await adapter.start({\n spawnMark,\n module: cfg.edgeWasm,\n argv: cfg.args,\n env: cfg.env,\n cwd: cfg.cwd,\n mounts: cfg.mounts,\n files: cfg.files,\n linux: cfg.linux,\n linuxSrc: cfg.linuxSrc,\n python: cfg.python,\n stdin: cfg.stdin || \"closed\",\n timeoutMs: cfg.timeoutMs,\n parallelism: cfg.parallelism\n });\n res.setupMs = performance.now() - t0;\n const k = adapter.keep ? adapter.keep() : null;\n if (k)\n postMessage({ type: \"keep\", keep: k });\n log(\"process started after \" + res.setupMs.toFixed(0) + \" ms\");\n const t1 = performance.now();\n postMessage({ type: \"step\", name: \"ready\", ms: res.setupMs });\n for (const m of early.splice(0))\n await input(m);\n const outs = [];\n const errs = [];\n let spawnRefused;\n const scanner = markScanner(spawnMark);\n const sdec = new TextDecoder;\n const sent = res.outBytes = { stdout: 0, stderr: 0 };\n const pump = async (read, into, kind) => {\n for (let n = 0;n < 1e6; n++) {\n const b = await read(65536);\n if (b == null)\n return;\n if (!b.length)\n continue;\n sent[kind] += b.length;\n if (kind === \"stderr\" && spawnRefused === undefined)\n spawnRefused = scanner.push(sdec.decode(b, { stream: true }));\n if (cfg.stream) {\n const c = b.slice();\n postMessage({ type: \"out\", kind, bytes: c }, [c.buffer]);\n } else\n into.push(b);\n }\n };\n if (cfg.stdinBytes)\n await proc.writeStdin(enc4.encode(cfg.stdinBytes));\n if (cfg.stdinBytes && cfg.stdin === \"pipe\")\n await proc.closeStdin();\n await Promise.all([pump(proc.readStdout, outs, \"stdout\"), pump(proc.readStderr, errs, \"stderr\")]);\n const w = await adapter.exit(proc);\n const join = (chunks) => {\n const all = new Uint8Array(chunks.reduce((a, c) => a + c.length, 0));\n let at = 0;\n for (const c of chunks)\n all.set(c, at), at += c.length;\n return all;\n };\n if (spawnRefused === undefined)\n spawnRefused = scanner.finish();\n res.runMs = performance.now() - t1;\n res.exitCode = w.exitCode;\n if (spawnRefused !== undefined && w.exitCode === SPAWN_EXIT)\n res.spawnRefused = spawnRefused;\n res.reason = w.reason;\n res.stdout = dec2.decode(join(outs)).slice(-8000);\n res.stderr = dec2.decode(join(errs)).slice(-8000);\n Object.assign(res, await adapter.stats());\n } catch (e) {\n res.error = errorText(e);\n const kind = errorKindOf(e, loading);\n if (kind)\n res.errorKind = kind;\n }\n done(res);\n};\n\n// src/edge/sbx/common.js\nvar b64 = (text) => {\n const bytes = new TextEncoder().encode(text);\n let s = \"\";\n for (let i = 0;i < bytes.length; i += 32768)\n s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));\n return btoa(s);\n};\nvar dataUrl = (text) => \"data:text/javascript;base64,\" + b64(text).replace(/\\//g, \"%2F\");\nvar blobUrl = (text) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\nvar bootSrc = (url) => `var q = []; var h = function (e) { q.push(e) }; self.addEventListener(\"message\", h);\n` + \"import(\" + JSON.stringify(url) + `).then(function () { self.removeEventListener(\"message\", h); for (var i = 0; i < q.length; i++) self.dispatchEvent(new MessageEvent(\"message\", { data: q[i].data, ports: q[i].ports })) },\n` + ` function (e) { postMessage({ type: \"done\", error: \"the frame's Worker code did not load: \" + String(e && e.message || e) }) })`;\nvar SCRIPT_LOADER = 'onmessage = e => { const d = e.data; if (d && typeof d.__wmdScript === \"string\") { onmessage = null; (0, eval)(d.__wmdScript + \"\\\\n//# sourceURL=wmd-worker.js\") } }';\nvar SCRIPT_PREFIX = \"wmd-script:\";\nfunction makeFactory(name) {\n if (name === \"data\") {\n const scripts = new Map;\n const loader = \"data:text/javascript,\" + encodeURIComponent(SCRIPT_LOADER);\n return {\n name,\n url: dataUrl,\n script: (t) => {\n const n = SCRIPT_PREFIX + scripts.size;\n scripts.set(n, t);\n return n;\n },\n make: (u, o) => {\n const t = scripts.get(u);\n if (t === undefined)\n return new Worker(u, { name: o && o.name, type: \"module\" });\n const w = new Worker(loader, { name: o && o.name, type: \"module\" });\n w.postMessage({ __wmdScript: '\"use strict\";' + t });\n return w;\n }\n };\n }\n if (name === \"boot\")\n return { name, url: blobUrl, make: (u, o) => new Worker(blobUrl(bootSrc(u)), { name: o && o.name }) };\n return { name: \"module\", url: blobUrl, make: (u, o) => new Worker(u, { name: o && o.name, type: \"module\" }) };\n}\nfunction moduleToScript(src) {\n const names = [];\n let body = src.replace(/^export\\s+((?:async\\s+)?function\\s*\\*?\\s*([\\w$]+)|(?:class|const|let|var)\\s+([\\w$]+))/gm, (m, rest, fn, other) => (names.push(fn || other), rest));\n const lists = [];\n body = body.replace(/^export\\s*\\{([^}]*)\\}\\s*;?[ \\t]*$/gm, (m, l) => (lists.push(...asObject(l)), \"\"));\n if (lists.includes(null) || /^\\s*(import|export)\\b/m.test(body) || /^await\\b/m.test(body) || !names.length && !lists.length)\n return null;\n body = body.replace(/import\\.meta\\.url/g, '\"about:blank\"');\n return `(() => {\n'use strict';\n${body}\nreturn { ${[...names, ...lists].join(\", \")} }\n})()`;\n}\nvar ACORN_RE = /(from\\s*)(['\"])\\.\\.\\/\\.\\.\\/acorn\\/acorn\\.mjs\\2/g;\nvar SNIPPET_RE = /(from\\s*)(['\"])\\.\\/snippets\\/[^'\"]+\\/inline0\\.js\\2/g;\nvar SNIPPET_IMPORT_RE = /import\\s*(?:\\*\\s*as\\s+(\\w+)|\\{([^}]*)\\})\\s*from\\s*(['\"])\\.\\/snippets\\/[^'\"]+\\/inline0\\.js\\3/g;\nvar SNIPPET_NS = \"__wmdSnippet\";\nvar dec3 = new TextDecoder;\nvar text = (v) => typeof v === \"string\" ? v : dec3.decode(v);\nvar ACORN_EXPORT_RE = /^export\\s*\\{([^}]*)\\}\\s*;?\\s*$/m;\nvar ACORN_IMPORT_RE = /^import\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])\\.\\.\\/\\.\\.\\/acorn\\/acorn\\.mjs\\2\\s*;?[ \\t]*$/m;\nvar asObject = (list) => list.split(\",\").map((x) => x.trim()).filter(Boolean).map((x) => {\n const m = /^([\\w$]+)\\s+as\\s+([\\w$]+)$/.exec(x);\n return m ? `${m[2]}: ${m[1]}` : /^[\\w$]+$/.test(x) ? x : null;\n});\nfunction acornExpr(src) {\n const m = ACORN_EXPORT_RE.exec(src);\n const rest = m && src.replace(ACORN_EXPORT_RE, \"\");\n if (!m || /^(import|export)\\b/m.test(rest))\n return null;\n const names = asObject(m[1]);\n return names.includes(null) ? null : `(() => {\n'use strict';\n${rest}\nreturn { ${names.join(\", \")} }\n})()`;\n}\nfunction snippetExpr(src, acornSrc) {\n const im = ACORN_IMPORT_RE.exec(src);\n const ac = im && acornExpr(acornSrc);\n if (!ac)\n return null;\n const pairs = im[1].split(\",\").map((x) => x.trim()).filter(Boolean).map((x) => {\n const k = /^([\\w$]+)\\s+as\\s+([\\w$]+)$/.exec(x);\n return k ? `${k[1]}: ${k[2]}` : /^[\\w$]+$/.test(x) ? x : null;\n });\n if (!pairs.length || pairs.includes(null))\n return null;\n let body = src.replace(ACORN_IMPORT_RE, `const { ${pairs.join(\", \")} } = __wmdAcorn;`);\n const names = [];\n body = body.replace(/^export\\s+((?:async\\s+)?function\\s*\\*?\\s*(\\w+)|(?:const|let|var|class)\\s+([\\w$]+))/gm, (m, rest, fn, other) => (names.push(fn || other), rest));\n if (/^(import|export)\\b/m.test(body) || !names.length)\n return null;\n return `(() => {\n'use strict';\nconst __wmdAcorn = ${ac};\n${body}\nreturn { ${names.join(\", \")} }\n})()`;\n}\nfunction urlsFor(factory, { glue, snippet, acorn, ownWorker }) {\n const expr = snippetExpr(text(snippet), text(acorn));\n let nested = null;\n if (!expr) {\n const acornU = factory.url(text(acorn));\n nested = factory.url(text(snippet).replace(ACORN_RE, (m, a, q) => a + q + acornU + q));\n }\n let first = true;\n const named = text(glue).replace(SNIPPET_IMPORT_RE, (m, star, braces, q) => {\n const head = first ? expr ? `const ${SNIPPET_NS} = ${expr}; ` : `import * as ${SNIPPET_NS} from ${q}${nested}${q}; ` : \"\";\n first = false;\n return head + (star ? `const ${star} = ${SNIPPET_NS}` : `const {${braces.replace(/\\s+as\\s+/g, \": \")}} = ${SNIPPET_NS}`);\n });\n const script = factory.script && expr ? moduleToScript(named) : null;\n if (script)\n return { glue: SCRIPT_PREFIX + \"glue\", glueScript: script, worker: factory.script(text(ownWorker)) };\n return { glue: factory.url(expr ? named : named.replace(SNIPPET_RE, (m, a, q) => a + q + nested + q)), worker: factory.url(text(ownWorker)) };\n}\n\n// src/edge/sbx/sha256.js\nvar K = new Int32Array([\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n]);\nfunction sha2562(data) {\n const n = data.length;\n const total = n + 9 + 63 >> 6 << 6;\n const tail = new Uint8Array(total - (n - n % 64));\n tail.set(data.subarray(n - n % 64));\n tail[n % 64] = 128;\n const dv = new DataView(tail.buffer);\n dv.setUint32(tail.length - 8, Math.floor(n / 536870912), false);\n dv.setUint32(tail.length - 4, n << 3 >>> 0, false);\n const h = new Int32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);\n const w = new Int32Array(64);\n const block = (b, o) => {\n for (let i = 0;i < 16; i++)\n w[i] = b[o + 4 * i] << 24 | b[o + 4 * i + 1] << 16 | b[o + 4 * i + 2] << 8 | b[o + 4 * i + 3];\n for (let i = 16;i < 64; i++) {\n const a = w[i - 15];\n const c = w[i - 2];\n const s0 = (a >>> 7 | a << 25) ^ (a >>> 18 | a << 14) ^ a >>> 3;\n const s1 = (c >>> 17 | c << 15) ^ (c >>> 19 | c << 13) ^ c >>> 10;\n w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;\n }\n let a = h[0], b1 = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];\n for (let i = 0;i < 64; i++) {\n const t1 = hh + ((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) + K[i] + w[i] | 0;\n const t2 = ((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + (a & b1 ^ a & c ^ b1 & c) | 0;\n hh = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b1;\n b1 = a;\n a = t1 + t2 | 0;\n }\n h[0] = h[0] + a | 0;\n h[1] = h[1] + b1 | 0;\n h[2] = h[2] + c | 0;\n h[3] = h[3] + d | 0;\n h[4] = h[4] + e | 0;\n h[5] = h[5] + f | 0;\n h[6] = h[6] + g | 0;\n h[7] = h[7] + hh | 0;\n };\n const whole = n - n % 64;\n for (let o = 0;o < whole; o += 64)\n block(data, o);\n for (let o = 0;o < tail.length; o += 64)\n block(tail, o);\n const out = new Uint8Array(32);\n const ov = new DataView(out.buffer);\n for (let i = 0;i < 8; i++)\n ov.setInt32(4 * i, h[i], false);\n return out;\n}\nfunction installDigestFallback(g = globalThis) {\n if (g.crypto && g.crypto.subtle)\n return false;\n const digest = async (alg, data) => {\n if (String(alg && alg.name ? alg.name : alg).toUpperCase() !== \"SHA-256\")\n throw new Error(\"only SHA-256 is available here\");\n const u = data instanceof ArrayBuffer || typeof SharedArrayBuffer === \"function\" && data instanceof SharedArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return sha2562(u).buffer;\n };\n const subtle = { digest };\n try {\n Object.defineProperty(g.crypto, \"subtle\", { value: subtle, configurable: true });\n } catch {\n return false;\n }\n return true;\n}\n\n// src/edge/sbx/worker-entry.js\ninstallDigestFallback(globalThis);\nvar real = globalThis.onmessage;\nvar dec4 = new TextDecoder;\nglobalThis.onmessage = (e) => {\n const d = e && e.data;\n if (d && d.x5sbx)\n setup(d.x5sbx);\n return real.call(globalThis, e);\n};\nfunction setup({ strategy, ownWorker, files }) {\n const mk = makeFactory(strategy);\n const urls = urlsFor(mk, { glue: files.glue, snippet: files.snippet, acorn: files.acorn, ownWorker });\n const name = (u) => String(u).replace(/^sbx:/, \"\");\n setDeps({\n fetch: async (u) => {\n const b = files[{ \"wmd_browser_bg.wasm\": \"wasm\", \"wmd_browser.js\": \"glue\", \"edgejs.wasm\": \"edgejs\", \"linux.cjs\": \"linux\", \"HASHES.txt\": \"hashes\", \"python-3.12.wasm\": \"python\", \"linux.py\": \"linuxpy\" }[name(u)]];\n if (!b)\n return { ok: false, status: 404, statusText: \"not handed in\", url: String(u) };\n return { ok: true, status: 200, url: String(u), arrayBuffer: async () => b, text: async () => dec4.decode(b) };\n },\n OwnRuntime: {\n start: (o) => OwnRuntime.start({ ...o, glueUrl: urls.glue, workerUrl: urls.worker, ...urls.glueScript ? { glueScript: urls.glueScript } : {}, create: mk.make, ...strategy === \"data\" && o.poolIdleMs === undefined ? { poolIdleMs: 1500 } : {} }),\n prepare: (...a) => OwnRuntime.prepare(...a)\n }\n });\n}\n"
4
+ const WORKER = "var __defProp = Object.defineProperty;\nvar __returnValue = (v) => v;\nfunction __exportSetter(name, newValue) {\n this[name] = __returnValue.bind(null, newValue);\n}\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, {\n get: all[name],\n enumerable: true,\n configurable: true,\n set: __exportSetter.bind(all, name)\n });\n};\nvar __esm = (fn, res, err) => () => {\n if (fn)\n try {\n res = fn(fn = 0);\n } catch (e) {\n err = [e];\n }\n if (err)\n throw err[0];\n return res;\n};\n\n// src/edge/own/exit-now.js\nfunction exitOfRun(data, waiting) {\n if (data.id != null)\n return data;\n const first = waiting.keys().next();\n return first.done ? null : { ...data, id: first.value };\n}\n\n// src/edge/own/payload-size.js\nfunction payloadBytes(v, depth = 0, seen = new Set) {\n if (!v || typeof v !== \"object\" || depth > 6 || seen.has(v))\n return 0;\n if (ArrayBuffer.isView(v))\n return v.byteLength;\n if (v instanceof ArrayBuffer || typeof SharedArrayBuffer !== \"undefined\" && v instanceof SharedArrayBuffer)\n return v.byteLength;\n seen.add(v);\n let n = 0;\n for (const k of Object.keys(v))\n n += payloadBytes(v[k], depth + 1, seen);\n return n;\n}\nvar BIG_SHARE;\nvar init_payload_size = __esm(() => {\n BIG_SHARE = 1 << 20;\n});\n\n// src/edge/own/pool.js\nclass WorkerPool {\n #create;\n #init;\n #onMessage;\n #onFailure;\n #spare;\n #max;\n #slots = new Map;\n #next = 1;\n #closed = false;\n #idleMs;\n #onRetire;\n created = 0;\n retired = 0;\n constructor({ create, init = () => {}, spare = 0, max = 256, idleMs = 0, onRetire = () => {}, onMessage = () => {}, onFailure = () => {} }) {\n this.#create = create;\n this.#init = init;\n this.#spare = spare;\n this.#max = max;\n this.#idleMs = idleMs;\n this.#onRetire = onRetire;\n this.#onMessage = onMessage;\n this.#onFailure = onFailure;\n }\n get live() {\n return this.#slots.size;\n }\n get starting() {\n return this.#count(\"starting\");\n }\n get idle() {\n return this.#count(\"idle\");\n }\n get busy() {\n return this.#count(\"busy\");\n }\n get workers() {\n return [...this.#slots.values()].map((s) => s.worker);\n }\n get closed() {\n return this.#closed;\n }\n #count(state) {\n let n = 0;\n for (const s of this.#slots.values())\n if (s.state === state)\n n++;\n return n;\n }\n #available() {\n let n = 0;\n for (const s of this.#slots.values())\n if (s.state === \"idle\" || s.state === \"starting\" && s.queue.length === 0)\n n++;\n return n;\n }\n warm(n = this.#spare) {\n if (this.#closed)\n throw new Error(\"pool closed\");\n while (this.#available() < n && this.#slots.size < this.#max)\n this.#start();\n }\n #start() {\n const worker = this.#create();\n const slot = { id: this.#next++, worker, state: \"starting\", queue: [], task: null };\n this.#slots.set(slot.id, slot);\n this.created++;\n worker.addEventListener(\"message\", (e) => this.#message(slot, e.data));\n worker.addEventListener(\"error\", (e) => this.#crash(slot, e));\n this.#init(worker, slot.id);\n return slot;\n }\n dispatch(task, transfer) {\n if (this.#closed)\n throw new Error(\"pool closed\");\n let slot;\n for (const s of this.#slots.values()) {\n if (s.state === \"idle\") {\n slot = s;\n break;\n }\n }\n if (!slot) {\n for (const s of this.#slots.values()) {\n if (s.state === \"starting\" && s.queue.length === 0) {\n slot = s;\n break;\n }\n }\n }\n if (!slot) {\n if (this.#slots.size >= this.#max)\n throw new RangeError(\"worker limit reached (\" + this.#max + \")\");\n slot = this.#start();\n }\n if (slot.state === \"idle\")\n this.#send(slot, task, transfer);\n else\n slot.queue.push({ task, transfer });\n if (this.#spare)\n this.warm();\n return slot.id;\n }\n #idle(slot) {\n clearTimeout(slot.timer);\n slot.timer = null;\n if (!this.#idleMs)\n return;\n slot.timer = setTimeout(() => {\n slot.timer = null;\n if (this.#closed || slot.state !== \"idle\" || !this.#slots.has(slot.id) || this.#available() <= this.#spare)\n return;\n this.#slots.delete(slot.id);\n this.retired++;\n try {\n slot.worker.terminate();\n } catch {}\n this.#onRetire(slot.id, slot.worker);\n }, this.#idleMs);\n }\n #send(slot, task, transfer) {\n clearTimeout(slot.timer);\n slot.timer = null;\n slot.state = \"busy\";\n slot.task = task;\n slot.worker.postMessage(task, transfer);\n }\n #message(slot, data) {\n if (this.#closed || !this.#slots.has(slot.id))\n return;\n const type = data && data.type;\n if (type === \"ready\") {\n if (slot.state !== \"starting\")\n return;\n slot.state = \"idle\";\n const next = slot.queue.shift();\n if (next)\n this.#send(slot, next.task, next.transfer);\n else\n this.#idle(slot);\n } else if (type === \"done\") {\n slot.state = \"idle\";\n slot.task = null;\n this.#idle(slot);\n } else if (type === \"crash\") {\n this.#crash(slot, { message: data.error });\n } else {\n this.#onMessage(slot.id, data);\n }\n }\n #crash(slot, e) {\n if (this.#closed || !this.#slots.has(slot.id))\n return;\n this.#slots.delete(slot.id);\n clearTimeout(slot.timer);\n try {\n slot.worker.terminate();\n } catch {}\n const lost = [];\n if (slot.task)\n lost.push(slot.task);\n for (const q of slot.queue)\n lost.push(q.task);\n this.#onFailure(slot.id, lost, new Error(String(e && e.message || e || \"worker error\")));\n }\n terminateAll() {\n this.#closed = true;\n for (const s of this.#slots.values()) {\n clearTimeout(s.timer);\n try {\n s.worker.terminate();\n } catch {}\n }\n this.#slots.clear();\n }\n}\n\n// src/edge/own/fs-bridge.js\nfunction encodeReply(res) {\n if (res && res.error)\n return { kind: 0, bytes: enc.encode(JSON.stringify({ e: res.error.code, m: res.error.message })) };\n const v = res ? res.value : null;\n if (v instanceof Uint8Array)\n return { kind: 1, bytes: v };\n return { kind: 0, bytes: enc.encode(JSON.stringify({ v: v === undefined ? null : v })) };\n}\nasync function serveFsCall(memory, slot, route, onDone) {\n const slotWords = () => new Int32Array(memory.buffer, slot, 9);\n const w = slotWords();\n const cap = w[3];\n const replyPtr = w[4];\n const inLen = w[6] + w[8];\n let outLen = 0;\n let method = \"\";\n let result;\n try {\n const bytes = new Uint8Array(memory.buffer);\n const req = JSON.parse(dec.decode(bytes.slice(w[5], w[5] + w[6])));\n method = req.m;\n const data = w[8] ? bytes.slice(w[7], w[7] + w[8]) : new Uint8Array(0);\n result = await route.handle(req.m, req.a, data);\n } catch (e) {\n result = { error: { code: \"EIO\", message: String(e && e.message || e) } };\n }\n let failed = null;\n try {\n const { kind, bytes } = encodeReply(result);\n const out = slotWords();\n outLen = bytes.length;\n if (bytes.length > cap) {\n Atomics.store(out, 2, bytes.length);\n Atomics.store(out, 0, 2);\n } else {\n new Uint8Array(memory.buffer, replyPtr, bytes.length).set(bytes);\n Atomics.store(out, 2, bytes.length);\n Atomics.store(out, 1, kind);\n Atomics.store(out, 0, 1);\n }\n } catch (e) {\n failed = e;\n const out = slotWords();\n const err = enc.encode(JSON.stringify({ e: \"EIO\", m: \"reply failed: \" + String(e && e.message || e).slice(0, 120) }));\n if (err.length <= cap) {\n new Uint8Array(memory.buffer, replyPtr, err.length).set(err);\n Atomics.store(out, 2, err.length);\n Atomics.store(out, 1, 0);\n Atomics.store(out, 0, 1);\n } else {\n Atomics.store(out, 2, err.length);\n Atomics.store(out, 0, 2);\n }\n }\n Atomics.notify(slotWords(), 0);\n if (onDone)\n onDone(method, inLen, outLen);\n if (failed)\n throw failed;\n return method;\n}\nvar enc, dec;\nvar init_fs_bridge = __esm(() => {\n enc = new TextEncoder;\n dec = new TextDecoder;\n});\n\n// src/edge/own/stdio-pipe.js\nclass StdinPipe {\n #mem;\n #addr;\n #cap;\n #off;\n #queue = [];\n #closing = false;\n #timer = null;\n #sleep;\n constructor(memory, info, { sleep = (fn, ms) => setTimeout(fn, ms) } = {}) {\n this.#mem = memory;\n this.#addr = info.addr;\n this.#cap = info.cap;\n this.#off = info.off;\n this.#sleep = sleep;\n }\n write(bytes) {\n if (this.#closing)\n throw new Error(\"stdin is closed\");\n if (bytes.length)\n this.#queue.push(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));\n this.#pump();\n }\n close() {\n this.#closing = true;\n this.#pump();\n }\n get pending() {\n return this.#queue.reduce((a, b) => a + b.length, 0);\n }\n #pump() {\n const words = new Int32Array(this.#mem.buffer, this.#addr, 3);\n const data = new Uint8Array(this.#mem.buffer);\n const base = this.#addr + this.#off;\n while (this.#queue.length) {\n const head = Atomics.load(words, 0) >>> 0;\n const tail = Atomics.load(words, 1) >>> 0;\n const free = this.#cap - (tail - head >>> 0);\n if (free <= 0)\n break;\n const chunk = this.#queue[0];\n const n = Math.min(free, chunk.length);\n const start = tail % this.#cap;\n const first = Math.min(n, this.#cap - start);\n data.set(chunk.subarray(0, first), base + start);\n if (n > first)\n data.set(chunk.subarray(first, n), base);\n Atomics.store(words, 1, tail + n | 0);\n if (n === chunk.length)\n this.#queue.shift();\n else\n this.#queue[0] = chunk.subarray(n);\n }\n if (this.#queue.length) {\n if (!this.#timer) {\n this.#timer = this.#sleep(() => {\n this.#timer = null;\n this.#pump();\n }, 5);\n }\n return;\n }\n if (this.#closing)\n Atomics.store(words, 2, 1);\n }\n}\nfunction setTtySize(memory, addr, cols, rows) {\n const w = new Int32Array(memory.buffer, addr, 4);\n Atomics.store(w, 0, cols | 0);\n Atomics.store(w, 1, rows | 0);\n Atomics.add(w, 3, 1);\n}\n\n// src/edge/own/memcap.js\nfunction readLeb(b, i) {\n let r = 0;\n let s = 0;\n for (;; ) {\n const x = b[i++];\n r += (x & 127) * 2 ** s;\n s += 7;\n if (!(x & 128))\n return [r, i];\n }\n}\nfunction writePadded(b, at, len, value) {\n for (let k = 0;k < len; k++) {\n const part = value % 128;\n value = Math.floor(value / 128);\n b[at + k] = part | (k < len - 1 ? 128 : 0);\n }\n}\nfunction capMemoryMax(wasm, maxPages) {\n const b = wasm instanceof Uint8Array ? wasm : new Uint8Array(wasm);\n let i = 8;\n while (i < b.length) {\n const id = b[i++];\n let size;\n [size, i] = readLeb(b, i);\n const end = i + size;\n if (id === 2) {\n let [count, j] = readLeb(b, i);\n for (let n = 0;n < count; n++) {\n let l;\n [l, j] = readLeb(b, j);\n j += l;\n [l, j] = readLeb(b, j);\n j += l;\n const kind = b[j++];\n if (kind === 0)\n [, j] = readLeb(b, j);\n else if (kind === 1) {\n j++;\n const [fl, k] = readLeb(b, j);\n j = k;\n [, j] = readLeb(b, j);\n if (fl & 1)\n [, j] = readLeb(b, j);\n } else if (kind === 2) {\n const r = capLimits(b, j, maxPages);\n if (r.done)\n return r;\n j = r.next;\n } else if (kind === 3)\n j += 2;\n else {\n j++;\n [, j] = readLeb(b, j);\n }\n }\n } else if (id === 5) {\n const [count, j0] = readLeb(b, i);\n let j = j0;\n for (let n = 0;n < count; n++) {\n const r = capLimits(b, j, maxPages);\n if (r.done)\n return r;\n j = r.next;\n }\n }\n i = end;\n }\n return { bytes: b, before: null, after: null };\n}\nfunction capLimits(b, j, maxPages) {\n const [flags, a] = readLeb(b, j);\n const [min, c] = readLeb(b, a);\n if (!(flags & 1))\n return { done: false, next: c };\n const [max, d] = readLeb(b, c);\n const len = d - c;\n const cap = Math.max(maxPages, min);\n if (max <= cap)\n return { done: true, bytes: b, before: max, after: max };\n if (cap >= 128 ** len)\n throw new Error(\"memory cap does not fit the number it replaces\");\n const out = b.slice();\n writePadded(out, c, len, cap);\n return { done: true, bytes: out, before: max, after: cap };\n}\nvar PAGE = 65536, pagesOfMiB = (mib) => Math.floor(mib * 1024 * 1024 / PAGE);\n\n// src/edge/own/loader.js\nvar hasJspi = () => typeof WebAssembly.promising === \"function\" && typeof WebAssembly.Suspending === \"function\";\n\n// src/edge/own/procfs.js\nfunction content(path, bytes) {\n const pages = Math.ceil(bytes / PAGE_SIZE);\n if (path === \"/proc/self/statm\")\n return enc2.encode(`${pages} ${pages} 0 0 0 ${pages} 0\n`);\n return enc2.encode(`1 (node) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 0 ${bytes} ${pages} 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0\n`);\n}\nfunction withProc(route, memoryBytes) {\n const open = new Map;\n let next = FIRST;\n const clean = (p) => String(p ?? \"\").replace(/\\/+$/, \"\") || \"/\";\n const handle = (method, args, data) => {\n if (method === \"ctl\") {\n let q = null;\n try {\n q = JSON.parse(String(args[0] ?? \"\"));\n } catch {}\n if (q && q.op === \"meminfo\")\n return { value: JSON.stringify({ rss: memoryBytes() }) };\n }\n if (method === \"stat\" || method === \"open\" || method === \"readdir\") {\n const p = clean(args[0]);\n if (p === \"/proc/self\" || p === \"/proc\") {\n if (method === \"stat\")\n return { value: statDir(p === \"/proc\" ? 5 : 6) };\n if (method === \"readdir\") {\n const names = p === \"/proc\" ? [[\"self\", \"d\"]] : [[\"stat\", \"f\"], [\"statm\", \"f\"]];\n return { value: { l: names.map(([n, k]) => ({ n, ...k === \"d\" ? statDir(6) : statOf(1, n === \"stat\" ? 3 : 4) })), d: true } };\n }\n }\n if (FILES.has(p)) {\n if (method === \"stat\")\n return { value: statOf(content(p, memoryBytes()).length, p.endsWith(\"m\") ? 4 : 3) };\n const f = args[1] || {};\n if (f.w || f.c || f.cn || f.t || f.a)\n return EROFS;\n const h = next++;\n open.set(h, { p, bytes: content(p, memoryBytes()) });\n return { value: { h } };\n }\n } else if ((method === \"read\" || method === \"fstat\" || method === \"close\" || method === \"write\" || method === \"ftruncate\") && Number(args[0]) >= FIRST) {\n const e = open.get(args[0]);\n if (method === \"close\") {\n open.delete(args[0]);\n return { value: null };\n }\n if (!e)\n return EBADF;\n if (method === \"read\")\n return { value: e.bytes.subarray(Number(args[1] ?? 0), Number(args[1] ?? 0) + Number(args[2] ?? 0)) };\n if (method === \"fstat\")\n return { value: statOf(e.bytes.length, e.p.endsWith(\"m\") ? 4 : 3) };\n return EROFS;\n }\n return route.handle(method, args, data);\n };\n return {\n handle,\n queueSignal: (...a) => route.queueSignal?.(...a),\n get children() {\n return route.children;\n },\n get route() {\n return route;\n }\n };\n}\nvar PAGE_SIZE = 65536, enc2, FIRST, FILES, EROFS, EBADF, statOf = (size, ino) => ({ k: \"f\", s: size, a: \"0\", m: \"0\", c: \"0\", i: ino, nl: 1, md: 33060, u: 0, g: 0, rd: 0 }), statDir = (ino) => ({ k: \"d\", s: 4096, a: \"0\", m: \"0\", c: \"0\", i: ino, nl: 2, md: 16749, u: 0, g: 0, rd: 0 });\nvar init_procfs = __esm(() => {\n enc2 = new TextEncoder;\n FIRST = 2 ** 40;\n FILES = new Set([\"/proc/self/stat\", \"/proc/self/statm\"]);\n EROFS = { error: { code: \"EROFS\", message: \"EROFS\" } };\n EBADF = { error: { code: \"EBADF\", message: \"EBADF\" } };\n});\n\n// src/edge/own/marks.js\nclass MarkBook {\n first = {};\n last = {};\n n = {};\n all = {};\n add(name, t) {\n if (typeof name !== \"string\" || typeof t !== \"number\")\n return;\n if (this.first[name] === undefined)\n this.first[name] = t;\n if (this.last[name] === undefined || t > this.last[name])\n this.last[name] = t;\n this.n[name] = (this.n[name] || 0) + 1;\n const a = this.all[name] ||= [];\n if (a.length < 64)\n a.push(t);\n }\n}\nfunction stagesOf(m) {\n const pick = (k) => Array.isArray(k) ? k.map((x) => m[x]).find((v) => typeof v === \"number\") : m[k];\n const out = {};\n for (const [name, a, b] of STAGES) {\n const x = pick(a);\n const y = pick(b);\n if (typeof x === \"number\" && typeof y === \"number\")\n out[name] = Math.round((y - x) * 10) / 10;\n }\n return out;\n}\nvar PROGRAM_BYTES, at = () => performance.timeOrigin + performance.now(), STAGES;\nvar init_marks = __esm(() => {\n PROGRAM_BYTES = 8 << 20;\n STAGES = [\n [\"fwLoad\", \"frame\", \"fw\"],\n [\"check\", \"load0\", \"checked\"],\n [\"rtCompile\", \"rtc0\", \"rtc1\"],\n [\"program\", \"start0\", \"program\"],\n [\"shim\", \"program\", \"shim\"],\n [\"boot\", \"shim\", \"booted\"],\n [\"toMain\", \"runPost\", \"runRecv\"],\n [\"compile\", \"compile0\", \"compile1\"],\n [\"toInst\", \"compile1\", \"inst0\"],\n [\"inst\", \"inst0\", \"inst1\"],\n [\"toOut\", \"inst1\", \"firstOut\"],\n [\"tail\", [\"firstOut\", \"inst1\"], \"exitRecv\"],\n [\"exitHop\", \"exitPost\", \"exitRecv\"],\n [\"run\", \"runPost\", \"exitRecv\"]\n ];\n});\n\n// src/edge/own/fs-stats.js\nfunction readFsStats(buffer, addr) {\n if (!buffer || !addr || addr % 8 !== 0 || addr + 80 > buffer.byteLength)\n return null;\n const w = new BigUint64Array(buffer, addr, 10);\n const v = (i) => Number(Atomics.load(w, i));\n return {\n n: v(0),\n us: v(1),\n stat: { n: v(2), us: v(3) },\n ctl: { n: v(4), us: v(5) },\n other: { n: v(6), us: v(7) },\n firstMs: v(8) ? v(8) / 1000 : null,\n lastMs: v(9) ? v(9) / 1000 : null\n };\n}\n\n// src/edge/own/hub.js\nfunction runOptionsJson({ fs, cwd, stdin, tty, children, exec, shim, net = false, jspi, argv0, fscache }) {\n return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...argv0 ? { argv0 } : {}, ...Number.isInteger(fscache) && fscache >= 0 ? { fscache } : {} });\n}\n\nclass OwnRuntime {\n #opts;\n #create;\n #module = null;\n #memory = null;\n #main = null;\n #pool = null;\n #booted = null;\n #capi = `wmd-own-capi-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n #scopes = 0;\n #byScope = new Map;\n #big = new Map;\n #bigHeld = new Map;\n #wants = new Map;\n #runs = new Map;\n #nextRun = 1;\n #dead = false;\n #outsSeen = 0;\n #capiN = { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 };\n #capiHeld = new Map;\n #countWait = new Map;\n #countSeq = 0;\n #held = [];\n #glue;\n #stdin = null;\n #ttyAddr = 0;\n static async start(opts) {\n const rt = new OwnRuntime(opts);\n await rt.#boot();\n return rt;\n }\n constructor(opts) {\n this.#opts = { spare: 2, max: 128, stack: 4 * 1024 * 1024, memoryMaxMiB: 1024, onOut: () => {}, onLog: () => {}, ...opts };\n this.#create = this.#opts.create || ((url, o) => new Worker(url, o));\n const base = typeof location === \"undefined\" ? undefined : location.href;\n this.#glue = new URL(this.#opts.glueUrl, base).href;\n if (this.#opts.marks)\n this.#marks = new MarkBook;\n }\n #routeCache = null;\n #marks = null;\n #calls = null;\n get marks() {\n if (!this.#marks)\n return null;\n const fs = this.#fsStat && this.#memory ? readFsStats(this.#memory.buffer, this.#fsStat) : null;\n const first = { ...this.#marks.first };\n for (const [k, v] of Object.entries(this.#marks.last))\n if (this.#marks.n[k] > 1)\n first[k + \"Last\"] = v;\n if (fs && fs.firstMs)\n first.fsFirst = fs.firstMs;\n if (fs && fs.lastMs)\n first.fsLast = fs.lastMs;\n return { first, n: { ...this.#marks.n }, series: Object.fromEntries(Object.entries(this.#marks.all).filter(([k, v]) => v.length > 1).map(([k, v]) => [k, [...v]])), fs, memMiB: this.#memory ? Math.round(this.#memory.buffer.byteLength / 1048576) : null, ...this.#calls ? { calls: this.#calls } : {} };\n }\n #fsT = globalThis.__wmdFsTime ? new Map : null;\n #timed(t0) {\n const tr = performance.timeOrigin + performance.now();\n return (method, inB, outB) => {\n const td = performance.timeOrigin + performance.now();\n const m = this.#fsT.get(method) || { n: 0, serveMs: 0, waitMs: 0, postMs: 0, inB: 0, outB: 0 };\n m.n++;\n m.serveMs += td - tr;\n if (typeof t0 === \"number\") {\n m.waitMs += td - t0;\n m.postMs += tr - t0;\n }\n m.inB += inB;\n m.outB += outB;\n this.#fsT.set(method, m);\n };\n }\n get fsTiming() {\n return this.#fsT ? Object.fromEntries(this.#fsT) : null;\n }\n #note(text) {\n try {\n const r = this.#opts.fsRoute && this.#opts.fsRoute.handle && this.#opts.fsRoute.handle(\"note\", [String(text).slice(0, 160)], new Uint8Array(0));\n if (r && typeof r.catch === \"function\")\n r.catch(() => {});\n } catch {}\n }\n #route() {\n if (!this.#opts.fsRoute)\n return NO_ROUTE;\n return this.#routeCache ||= withProc(this.#opts.fsRoute, () => this.#memory.buffer.byteLength);\n }\n async#boot() {\n const { wasmUrl, workerUrl, stack } = this.#opts;\n try {\n this.#module = this.#opts.module || await WebAssembly.compileStreaming(fetch(wasmUrl));\n } catch (e) {\n const err = new Error(`the runtime's wasm did not load (${wasmUrl}): ${String(e && e.message || e)}`);\n err.runtimeFiles = true;\n throw err;\n }\n this.#main = this.#create(workerUrl, { type: \"module\", name: \"wmd-own-main\" });\n this.#main.addEventListener(\"message\", (e) => this.#fromWorker(e.data));\n this.#main.addEventListener(\"error\", (e) => this.#fatal(new Error(\"runtime main worker: \" + (e.message || \"error\"))));\n const ready = new Promise((resolve, reject) => this.#booted = { resolve, reject });\n this.#byScope.set(this.#scopes + 1, this.#main);\n this.#main.postMessage({ type: \"init\", role: \"main\", capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}, fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, glue: this.#glue, ...this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}, module: this.#module, stack });\n const up = await ready;\n this.#memory = up.memory;\n this.#stdin = new StdinPipe(this.#memory, up.stdin);\n this.#ttyAddr = up.tty;\n this.#pool = new WorkerPool({\n create: () => this.#create(workerUrl, { type: \"module\", name: \"wmd-own-thread\" }),\n init: (w) => (this.#byScope.set(this.#scopes + 1, w), w.postMessage({ type: \"init\", role: \"thread\", capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}, fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, trace: this.#opts.trace | 0, glue: this.#glue, ...this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}, module: this.#module, memory: this.#memory, stack })),\n spare: this.#opts.spare,\n max: this.#opts.max,\n idleMs: this.#opts.poolIdleMs | 0,\n onRetire: (_id, w) => {\n for (const [k, v] of this.#byScope)\n if (v === w)\n this.#byScope.delete(k);\n },\n onMessage: (_id, data) => this.#fromWorker(data),\n onFailure: (_id, tasks, err) => {\n this.#note(\"thread ended: \" + String(err && err.message || err).slice(0, 140));\n for (const t of tasks)\n this.#refuse(t.ack, err);\n }\n });\n this.#pool.warm();\n }\n run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = \"null\", tty = {}, children = false, exec, shim = false, net = false, argv0, fscache }) {\n if (this.#dead)\n return Promise.reject(new Error(\"runtime terminated\"));\n const id = this.#nextRun++;\n let buf = null;\n if (ready) {\n this.memoryCap = ready.cap;\n } else {\n buf = program instanceof ArrayBuffer ? program.slice(0) : program.buffer.slice(program.byteOffset, program.byteOffset + program.byteLength);\n if (this.#opts.memoryMaxMiB) {\n const cap = capMemoryMax(new Uint8Array(buf), pagesOfMiB(this.#opts.memoryMaxMiB));\n this.memoryCap = { before: cap.before, after: cap.after };\n if (cap.bytes.buffer !== buf)\n buf = cap.bytes.buffer;\n }\n }\n return new Promise((resolve, reject) => {\n this.#runs.set(id, { resolve, reject });\n const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0, fscache });\n if (tty.cols || tty.rows)\n setTtySize(this.#memory, this.#ttyAddr, tty.cols || 80, tty.rows || 24);\n this.#calls = null;\n if (ready)\n this.#main.postMessage({ type: \"run\", id, program: ready.bytes, module: ready.module, hash: ready.hash, args, env, node, opts });\n else\n this.#main.postMessage({ type: \"run\", id, program: buf, args, env, node, opts }, [buf]);\n });\n }\n static async prepare(program, { memoryMaxMiB = 1024, compile = (b) => WebAssembly.compile(b), digest = (b) => crypto.subtle.digest(\"SHA-256\", b) } = {}) {\n let bytes = program instanceof Uint8Array ? program : new Uint8Array(program);\n let cap = { before: null, after: null };\n if (memoryMaxMiB) {\n const c = capMemoryMax(bytes, pagesOfMiB(memoryMaxMiB));\n cap = { before: c.before, after: c.after };\n bytes = c.bytes;\n }\n const plain = typeof SharedArrayBuffer === \"function\" && bytes.buffer instanceof SharedArrayBuffer ? bytes.slice() : bytes;\n const [hash, module] = await Promise.all([digest(plain), compile(plain)]);\n if (typeof SharedArrayBuffer === \"function\" && !(bytes.buffer instanceof SharedArrayBuffer)) {\n try {\n const shared = new Uint8Array(new SharedArrayBuffer(bytes.length));\n shared.set(bytes);\n bytes = shared;\n } catch {}\n }\n return { bytes, hash: new Uint8Array(hash), module, cap, memoryMaxMiB };\n }\n writeStdin(bytes) {\n this.#stdin.write(bytes);\n }\n closeStdin() {\n this.#stdin.close();\n }\n resize(cols, rows) {\n setTtySize(this.#memory, this.#ttyAddr, cols, rows);\n }\n get memoryBytes() {\n return this.#memory ? this.#memory.buffer.byteLength : 0;\n }\n collectCounts(ms = 400) {\n if (this.#dead)\n return Promise.resolve([]);\n const ws = [this.#main, ...this.#pool ? this.#pool.workers : []].filter(Boolean);\n const seq = ++this.#countSeq;\n return new Promise((resolve) => {\n const w = { got: [], want: ws.length };\n const end = () => {\n this.#countWait.delete(seq);\n resolve(w.got);\n };\n w.end = end;\n this.#countWait.set(seq, w);\n const t = setTimeout(end, ms);\n w.clear = () => clearTimeout(t);\n for (const x of ws) {\n try {\n x.postMessage({ type: \"counts\", seq });\n } catch {\n w.want--;\n }\n }\n if (w.got.length >= w.want)\n w.clear(), end();\n });\n }\n #forged = 0;\n get forged() {\n return this.#forged;\n }\n get capiStats() {\n return { ...this.#capiN };\n }\n #capiHold(k, data) {\n const have = this.#big.get(k);\n const e = have ? (have.data = data, have) : { data, size: payloadBytes((data.msg || {}).envelope), sent: new Set };\n if (!have) {\n this.#big.set(k, e);\n const c = this.#capiN;\n c.messages++;\n c.bytes += e.size;\n c.maxMessage = Math.max(c.maxMessage, e.size);\n c.heldBytes += e.size * 2;\n this.#bigHeld.set(k, e.size * 2);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n }\n const asks = this.#wants.get(k);\n if (asks) {\n this.#wants.delete(k);\n for (const sc of asks)\n this.#capiServe(k, e, sc);\n }\n }\n #capiWant(k, scope) {\n const e = this.#big.get(k);\n if (e)\n return this.#capiServe(k, e, scope);\n const asks = this.#wants.get(k) || new Set;\n asks.add(scope);\n this.#wants.set(k, asks);\n if (this.#wants.size > 4096)\n this.#wants.delete(this.#wants.keys().next().value);\n }\n #capiServe(k, e, scope) {\n const w = this.#byScope.get(scope);\n if (!w || e.sent.has(scope))\n return;\n e.sent.add(scope);\n const c = this.#capiN;\n c.copies++;\n c.copyBytes += e.size;\n c.maxRecipients = Math.max(c.maxRecipients, e.sent.size);\n c.heldBytes += e.size;\n this.#bigHeld.set(k, (this.#bigHeld.get(k) || 0) + e.size);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n try {\n w.postMessage(e.data);\n } catch {}\n }\n #countCapi(data) {\n const c = this.#capiN;\n const m = data.msg || {};\n const to = [this.#main, ...this.#pool ? this.#pool.workers : []].filter(Boolean).length;\n const size = payloadBytes(m.envelope);\n const k = `${m.registry}:${m.handle}`;\n if (m.t === \"share\") {\n c.messages++;\n c.bytes += size;\n c.copies += to;\n c.copyBytes += size * to;\n c.maxMessage = Math.max(c.maxMessage, size);\n c.maxRecipients = Math.max(c.maxRecipients, to);\n const held = size * (to + 1);\n c.heldBytes += held - (this.#capiHeld.get(k) || 0);\n this.#capiHeld.set(k, held);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n } else if (m.t === \"delete\" && this.#capiHeld.has(k)) {\n c.heldBytes -= this.#capiHeld.get(k);\n this.#capiHeld.delete(k);\n }\n if (m.t === \"delete\" && this.#bigHeld.has(k)) {\n c.heldBytes -= this.#bigHeld.get(k);\n this.#bigHeld.delete(k);\n }\n }\n #fsStat = 0;\n #sigWake = 0;\n #sigFlags = [];\n get workerCount() {\n return this.#dead ? 0 : 1 + (this.#pool ? this.#pool.live : 0);\n }\n get pool() {\n return this.#pool;\n }\n signal(n) {\n if (n === 9)\n return this.terminate();\n this.#opts.fsRoute?.queueSignal?.(0, n);\n if (this.#sigWake && this.#memory) {\n const w = new Int32Array(this.#memory.buffer);\n Atomics.add(w, this.#sigWake >> 2, 1);\n Atomics.notify(w, this.#sigWake >> 2);\n }\n }\n terminate() {\n this.#dead = true;\n if (this.#main)\n this.#main.terminate();\n if (this.#pool)\n this.#pool.terminateAll();\n this.#fatal(new Error(\"runtime terminated\"));\n }\n #fromWorker(data) {\n switch (data && data.type) {\n case \"ready\":\n if (this.#booted)\n this.#booted.resolve(data);\n this.#booted = null;\n break;\n case \"out\":\n this.#outsSeen++;\n this.#opts.onOut(data.fd, data.data);\n this.#release();\n break;\n case \"spawn\":\n this.#spawn(data);\n break;\n case \"mark\":\n if (this.#marks)\n this.#marks.add(data.name, data.t);\n break;\n case \"calls\":\n if (this.#marks && (!this.#calls || sumCalls(data.totals) >= sumCalls(this.#calls.totals)))\n this.#calls = { seen: data.seen, wrapped: data.wrapped, ring: data.ring, totals: data.totals, inst: data.inst };\n break;\n case \"counts\": {\n const w = this.#countWait.get(data.seq);\n if (w) {\n w.got.push({ role: data.role, c: data.c });\n if (w.got.length >= w.want)\n w.clear(), w.end();\n }\n break;\n }\n case \"capi\": {\n const m = data.msg || {};\n const k = `${m.registry}:${m.handle}`;\n if (m.t === \"want\")\n return this.#capiWant(k, m.from);\n if (m.t === \"share\" && payloadBytes(m.envelope) >= BIG_SHARE)\n return this.#capiHold(k, data);\n if (m.t === \"share\")\n this.#wants.delete(k);\n if (m.t === \"delete\") {\n this.#big.delete(k);\n this.#wants.delete(k);\n }\n this.#countCapi(data);\n for (const w of [this.#main, ...this.#pool ? this.#pool.workers : []])\n if (w)\n w.postMessage(data);\n break;\n }\n case \"fs\":\n serveFsCall(this.#memory, data.slot, this.#route(), this.#fsT ? this.#timed(data.t0) : undefined).then((m) => {\n if (m === \"peek\")\n this.#note(\"hub: peek answered\");\n }).catch((e) => {\n this.#note(\"fs call failed: \" + String(e && e.message || e).slice(0, 120));\n this.#opts.onLog({ type: \"log\", text: \"fs call failed: \" + (e && e.message) });\n });\n break;\n case \"fsstat\":\n if (Number.isInteger(data.addr))\n this.#fsStat = data.addr;\n break;\n case \"sigflag\":\n if (data.wake)\n this.#sigWake = data.wake;\n if (data.buffer && data.buffer.byteLength >= data.addr + 4 && data.addr % 4 === 0)\n this.#sigFlags.push({ words: new Int32Array(data.buffer), at: data.addr >> 2, bits: data.bits | 0 });\n break;\n case \"sigraise\":\n for (const f of this.#sigFlags)\n Atomics.or(f.words, f.at, f.bits);\n break;\n case \"note\": {\n this.#note(String(data.text));\n break;\n }\n case \"exit\":\n case \"run-error\": {\n const end = exitOfRun(data, this.#runs);\n if (end)\n this.#held.push(end);\n this.#release();\n break;\n }\n case \"fatal\":\n this.#fatal(new Error(data.error));\n break;\n default:\n this.#forged++;\n }\n }\n #release() {\n const ready = this.#held.filter((d) => this.#outsSeen >= (d.outs || 0));\n if (!ready.length)\n return;\n this.#held = this.#held.filter((d) => !ready.includes(d));\n for (const d of ready) {\n const run = this.#runs.get(d.id);\n this.#runs.delete(d.id);\n if (!run)\n continue;\n if (d.type === \"exit\")\n run.resolve({ code: d.code });\n else\n run.reject(new Error(d.error));\n }\n }\n #spawn(data) {\n if (this.#marks)\n this.#marks.add(\"spawnReq\", performance.timeOrigin + performance.now());\n if (this.#opts.debug)\n console.log(\"[hub] spawn request, ack\", data.ack, \"pool\", JSON.stringify({ live: this.#pool.live, idle: this.#pool.idle, busy: this.#pool.busy, starting: this.#pool.starting }));\n try {\n this.#pool.dispatch({ type: \"task\", msg: data.msg, ack: data.ack });\n } catch (err) {\n this.#refuse(data.ack, err);\n }\n }\n #refuse(ack, err) {\n this.#opts.onLog({ type: \"log\", text: \"spawn refused: \" + (err && err.message) });\n if (!ack || !this.#memory)\n return;\n const words = new Int32Array(this.#memory.buffer);\n Atomics.compareExchange(words, ack >> 2, 0, 2);\n Atomics.notify(words, ack >> 2);\n }\n #fatal(err) {\n if (this.#booted)\n this.#booted.reject(err);\n this.#booted = null;\n for (const run of this.#runs.values())\n run.reject(err);\n this.#runs.clear();\n }\n}\nvar NO_ROUTE, sumCalls = (t) => Object.values(t || {}).reduce((s, v) => s + (parseInt(v, 10) || 0), 0);\nvar init_hub = __esm(() => {\n init_payload_size();\n init_fs_bridge();\n init_procfs();\n init_marks();\n NO_ROUTE = { handle: () => ({ error: { code: \"ENOSYS\", message: \"this runtime has no file route\" } }) };\n});\n\n// src/edge/own/wasm-counters.js\nfunction installWasmCounters(g) {\n if (g.__wmdWasmCounters)\n return g.__wmdWasmCounters;\n const W = g.WebAssembly;\n const c = {\n compile: { calls: 0, bytes: 0, ms: 0 },\n stream: { calls: 0, bytes: 0, ms: 0 },\n instantiate: { calls: 0, bytes: 0, ms: 0 },\n module: { calls: 0, bytes: 0, ms: 0, maxMs: 0 },\n memory: { made: 0, shared: 0, madeBytes: 0 },\n fetched: {}\n };\n const refs = [];\n const kinds = [];\n const wrapAsync = (name, slot, bytesOf) => {\n const orig = W[name];\n if (typeof orig !== \"function\")\n return;\n W[name] = function(...a) {\n c[slot].calls++;\n c[slot].bytes += bytesOf ? bytesOf(a[0]) : 0;\n const t0 = performance.now();\n const p = orig.apply(this, a);\n return p && typeof p.then === \"function\" ? p.finally(() => c[slot].ms += performance.now() - t0) : p;\n };\n };\n wrapAsync(\"compile\", \"compile\", sizeOf);\n wrapAsync(\"instantiate\", \"instantiate\", sizeOf);\n const streamBytes = (r) => {\n try {\n return Number(r && r.headers && r.headers.get && r.headers.get(\"content-length\")) || 0;\n } catch {\n return 0;\n }\n };\n wrapAsync(\"compileStreaming\", \"stream\", null);\n wrapAsync(\"instantiateStreaming\", \"stream\", null);\n if (W.Module) {\n W.Module = new Proxy(W.Module, {\n construct(target, args) {\n const t0 = performance.now();\n const m = Reflect.construct(target, args);\n const ms = performance.now() - t0;\n c.module.calls++;\n c.module.bytes += sizeOf(args[0]);\n c.module.ms += ms;\n c.module.maxMs = Math.max(c.module.maxMs, ms);\n return m;\n }\n });\n }\n if (W.Memory) {\n W.Memory = new Proxy(W.Memory, {\n construct(target, args) {\n const d = args[0] || {};\n const m = Reflect.construct(target, args);\n c.memory.made++;\n if (d.shared)\n c.memory.shared++;\n refs.push(new WeakRef(m));\n kinds.push({ ref: new WeakRef(m), initial: d.initial | 0, maximum: d.maximum, shared: !!d.shared });\n return m;\n }\n });\n }\n const R = g.Response && g.Response.prototype;\n if (R && R.arrayBuffer) {\n const orig = R.arrayBuffer;\n R.arrayBuffer = async function() {\n const b = await orig.call(this);\n const k = kind(this.url);\n const f = c.fetched[k] ||= { calls: 0, bytes: 0 };\n f.calls++;\n f.bytes += b.byteLength;\n return b;\n };\n }\n const api = {\n kinds() {\n return kinds.map((k) => {\n const m = k.ref.deref();\n return { initial: k.initial, maximum: k.maximum, shared: k.shared, pages: m ? m.buffer.byteLength / 65536 : null };\n });\n },\n snapshot() {\n let live = 0;\n let liveBytes = 0;\n for (let i = refs.length - 1;i >= 0; i--) {\n const m = refs[i].deref();\n if (!m)\n continue;\n live++;\n try {\n liveBytes += m.buffer.byteLength;\n } catch {}\n }\n return JSON.parse(JSON.stringify({ ...c, memory: { ...c.memory, live, liveBytes }, kinds: api.kinds() }));\n }\n };\n g.__wmdWasmCounters = api;\n return api;\n}\nfunction addCounts(a, b) {\n const out = JSON.parse(JSON.stringify(a || {}));\n const walk = (dst, src) => {\n for (const [k, v] of Object.entries(src || {})) {\n if (v && typeof v === \"object\")\n walk(dst[k] ||= {}, v);\n else\n dst[k] = (Number(dst[k]) || 0) + (Number(v) || 0);\n }\n };\n walk(out, b);\n return out;\n}\nvar kind = (url) => {\n const u = String(url || \"\");\n if (/edgejs\\.wasm/.test(u))\n return \"program\";\n if (/wmd_browser_bg\\.wasm/.test(u))\n return \"runtime\";\n if (/wmd_browser\\.js/.test(u))\n return \"glue\";\n if (/HASHES\\.txt/.test(u))\n return \"hashes\";\n if (/linux\\.cjs/.test(u))\n return \"shim\";\n return \"other\";\n}, sizeOf = (src) => {\n try {\n if (src && typeof src.byteLength === \"number\")\n return src.byteLength;\n if (src && src.buffer && typeof src.buffer.byteLength === \"number\")\n return src.buffer.byteLength;\n } catch {}\n return 0;\n};\n\n// src/edge/own/node-globals.js\nvar NODE_GLOBALS;\nvar init_node_globals = __esm(() => {\n NODE_GLOBALS = Object.freeze([\n \"AbortController\",\n \"AbortSignal\",\n \"AggregateError\",\n \"Array\",\n \"ArrayBuffer\",\n \"AsyncDisposableStack\",\n \"Atomics\",\n \"BigInt\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Blob\",\n \"Boolean\",\n \"BroadcastChannel\",\n \"Buffer\",\n \"ByteLengthQueuingStrategy\",\n \"CloseEvent\",\n \"CompressionStream\",\n \"CountQueuingStrategy\",\n \"Crypto\",\n \"CryptoKey\",\n \"CustomEvent\",\n \"DOMException\",\n \"DataView\",\n \"Date\",\n \"DecompressionStream\",\n \"DisposableStack\",\n \"Error\",\n \"EvalError\",\n \"Event\",\n \"EventTarget\",\n \"File\",\n \"FinalizationRegistry\",\n \"Float16Array\",\n \"Float32Array\",\n \"Float64Array\",\n \"FormData\",\n \"Function\",\n \"Headers\",\n \"Infinity\",\n \"Int16Array\",\n \"Int32Array\",\n \"Int8Array\",\n \"Intl\",\n \"Iterator\",\n \"JSON\",\n \"Map\",\n \"Math\",\n \"MessageChannel\",\n \"MessageEvent\",\n \"MessagePort\",\n \"NaN\",\n \"Navigator\",\n \"Number\",\n \"Object\",\n \"Performance\",\n \"PerformanceEntry\",\n \"PerformanceMark\",\n \"PerformanceMeasure\",\n \"PerformanceObserver\",\n \"PerformanceObserverEntryList\",\n \"PerformanceResourceTiming\",\n \"Promise\",\n \"Proxy\",\n \"RangeError\",\n \"ReadableByteStreamController\",\n \"ReadableStream\",\n \"ReadableStreamBYOBReader\",\n \"ReadableStreamBYOBRequest\",\n \"ReadableStreamDefaultController\",\n \"ReadableStreamDefaultReader\",\n \"ReferenceError\",\n \"Reflect\",\n \"RegExp\",\n \"Request\",\n \"Response\",\n \"Set\",\n \"SharedArrayBuffer\",\n \"String\",\n \"SubtleCrypto\",\n \"SuppressedError\",\n \"Symbol\",\n \"SyntaxError\",\n \"TextDecoder\",\n \"TextDecoderStream\",\n \"TextEncoder\",\n \"TextEncoderStream\",\n \"TransformStream\",\n \"TransformStreamDefaultController\",\n \"TypeError\",\n \"URIError\",\n \"URL\",\n \"URLPattern\",\n \"URLSearchParams\",\n \"Uint16Array\",\n \"Uint32Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"WeakMap\",\n \"WeakRef\",\n \"WeakSet\",\n \"WebAssembly\",\n \"WebSocket\",\n \"WritableStream\",\n \"WritableStreamDefaultController\",\n \"WritableStreamDefaultWriter\",\n \"atob\",\n \"btoa\",\n \"clearImmediate\",\n \"clearInterval\",\n \"clearTimeout\",\n \"console\",\n \"crypto\",\n \"decodeURI\",\n \"decodeURIComponent\",\n \"encodeURI\",\n \"encodeURIComponent\",\n \"escape\",\n \"eval\",\n \"fetch\",\n \"global\",\n \"globalThis\",\n \"isFinite\",\n \"isNaN\",\n \"navigator\",\n \"parseFloat\",\n \"parseInt\",\n \"performance\",\n \"process\",\n \"queueMicrotask\",\n \"setImmediate\",\n \"setInterval\",\n \"setTimeout\",\n \"structuredClone\",\n \"undefined\",\n \"unescape\"\n ]);\n});\n\n// src/edge/shim.js\nfunction nodeVersionJs(v) {\n if (typeof v !== \"string\" || !NODE_VERSION.test(v))\n return \"\";\n return `\n;(() => {\n const version = ${JSON.stringify(v)};\n const hide = (o, k, value) => Object.defineProperty(o, k, { value, writable: false, enumerable: true, configurable: true });\n hide(process, 'version', version);\n if (process.versions) hide(process.versions, 'node', version.slice(1));\n})();\n`;\n}\nfunction withoutSymlinkOverride(links) {\n const a = links.indexOf(SYMLINK_FROM);\n const b = links.indexOf(SYMLINK_TO);\n if (a < 0 || b < a || links.split(PROMISE_SYMLINK).length !== 2)\n throw new Error(\"shim.js: the symlink block of BROWSER_LINKS moved; withoutSymlinkOverride needs a change\");\n const middle = links.slice(a, b);\n const at = middle.indexOf(\" if (fs.promises) {\");\n return links.slice(0, a) + middle.slice(at).replace(PROMISE_SYMLINK, \"\") + links.slice(b);\n}\nfunction shimSource(src, settings, { symlinks = true } = {}) {\n for (const [name, text] of [[\"settings marker\", SETTINGS_MARKER], [\"__wmdCtl take\", TAKE], [\"ctlError\", LINKS_MARKER], [\"signal table\", SIG_TABLE_FROM], [\"signal emit\", SIG_EMIT_FROM]]) {\n const n = src.split(text).length - 1;\n if (n !== 1)\n throw new Error(`linux.cjs: the ${name} is there ${n} times, not once; the browser shim needs a change`);\n }\n return src.replace(SETTINGS_MARKER, () => JSON.stringify(settings)).replace(TAKE, () => TAKE_HERE).replace(SIG_TABLE_FROM, () => SIG_TABLE_TO).replace(SIG_EMIT_FROM, () => SIG_EMIT_TO).replace(LINKS_MARKER, () => (symlinks ? BROWSER_LINKS : withoutSymlinkOverride(BROWSER_LINKS)) + LINKS_MARKER) + nodeVersionJs(settings && settings.nodeVersion);\n}\nvar SETTINGS_MARKER = \"/*__WMD_EDGE_CONFIG__*/{}\", TAKE = `const hostCtl = globalThis.__wmdCtl;\n delete globalThis.__wmdCtl;`, TAKE_HERE = `const realGlobal = Function('return this')();\n const hostCtl = globalThis.__wmdCtl || realGlobal.__wmdCtl;\n delete globalThis.__wmdCtl;\n delete realGlobal.__wmdCtl;`, LINKS_MARKER = \" function ctlError(r, syscall, p) {\", BROWSER_LINKS = ` {\n const pathOf = p => (typeof p === 'string' ? p : Buffer.isBuffer(p) ? p.toString() : null);\n const viaCtl = (op, p, key) => {\n const s = pathOf(p);\n if (s === null) return null;\n try { const r = ctl({ op, path: require('path').resolve(s) }); return r.err ? null : r[key]; } catch (_) { return null; }\n };\n const origRealpathSync = fs.realpathSync;\n const realpathSync = function realpathSync(p, o) {\n const r = viaCtl('realpath', p, 'path');\n if (r === null) return origRealpathSync.apply(fs, arguments);\n return o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r;\n };\n realpathSync.native = realpathSync;\n fs.realpathSync = realpathSync;\n const realpath = function realpath(p, o, cb) {\n if (typeof o === 'function') { cb = o; o = undefined; }\n let r;\n try { r = realpathSync(p, o); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null, r);\n };\n realpath.native = realpath;\n fs.realpath = realpath;\n const origReadlinkSync = fs.readlinkSync;\n const readlinkSync = function readlinkSync(p, o) {\n const r = viaCtl('readlink', p, 'target');\n return r === null ? origReadlinkSync.apply(fs, arguments) : (o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r);\n };\n fs.readlinkSync = readlinkSync;\n const origReadlink = fs.readlink;\n fs.readlink = function readlink(p, o, cb) {\n if (typeof o === 'function') { cb = o; o = undefined; }\n if (viaCtl('readlink', p, 'target') === null) return origReadlink.apply(fs, arguments);\n let r;\n try { r = readlinkSync(p, o); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null, r);\n };\n // The mount has no symlink call either; a link is made by the control request (npm's node_modules/.bin links).\n const symlinkSync = function symlinkSync(target, path) {\n const s = pathOf(path);\n if (s === null) return origSymlinkSync.apply(fs, arguments);\n const full = require('path').resolve(s);\n const r = ctl({ op: 'symlink', path: full, target: String(pathOf(target) === null ? target : pathOf(target)) });\n if (r.err) throw ctlError(r, 'symlink', s);\n };\n const origSymlinkSync = fs.symlinkSync;\n fs.symlinkSync = symlinkSync;\n fs.symlink = function symlink(target, path, type, cb) {\n if (typeof type === 'function') cb = type;\n try { symlinkSync(target, path); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null);\n };\n if (fs.promises) {\n fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n fs.promises.realpath = async function realpath(p, o) { return realpathSync(p, o); };\n const origP = fs.promises.readlink;\n fs.promises.readlink = async function readlink(p, o) { return viaCtl('readlink', p, 'target') === null ? origP.apply(fs.promises, arguments) : readlinkSync(p, o); };\n }\n // The page's run has pipes for stdio (the stub sent a terminal's run to the guest's own node), but the SDK's pipes look like a\n // character device to node, so process.stdout.isTTY is true and npm would draw progress. The guest's node says undefined.\n for (const name of ['stdin', 'stdout', 'stderr']) {\n const d = Object.getOwnPropertyDescriptor(process, name);\n if (!d || !d.get) continue;\n Object.defineProperty(process, name, {\n configurable: true,\n enumerable: d.enumerable,\n get() {\n const st = d.get.call(process);\n if (st && st.isTTY) { try { delete st.isTTY; } catch (_) {} if (st.isTTY) { try { Object.defineProperty(st, 'isTTY', { value: undefined, configurable: true }); } catch (_) {} } }\n return st;\n },\n });\n }\n }\n`, NODE_VERSION, SYMLINK_FROM = \" // The mount has no symlink call either; a link is made by the control request\", SYMLINK_TO = \" // The page's run has pipes for stdio\", PROMISE_SYMLINK = ` fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n`, SIG_TABLE_FROM = \" const SIG_NAMES = { 1: 'SIGHUP', 2: 'SIGINT', 3: 'SIGQUIT', 15: 'SIGTERM' };\", SIG_NAMES_LINUX, SIG_IGNORED_LINUX, SIG_TABLE_TO, SIG_EMIT_FROM = ` if (process.listenerCount(name) > 0) {\n process.emit(name, name);\n } else {`, SIG_EMIT_TO = ` if (process.listenerCount(name) > 0) {\n // tell the page that a handler takes it: the program is not stuck and is not cut off after the grace period (fix7)\n try { ctl({ op: 'signal_taken', n: sig, handled: true }); } catch (_) {}\n process.emit(name, name, sig);\n } else if (SIG_IGNORED.has(sig)) {\n // the default action of this signal leaves the program running\n } else {\n // the default action ends the program: the page learns it, so that the stub dies of the signal as node in the guest does (R4)\n try { ctl({ op: 'signal_taken', n: sig, handled: false }); } catch (_) {}`;\nvar init_shim = __esm(() => {\n NODE_VERSION = /^v\\d+\\.\\d+\\.\\d+$/;\n SIG_NAMES_LINUX = {\n 1: \"SIGHUP\",\n 2: \"SIGINT\",\n 3: \"SIGQUIT\",\n 4: \"SIGILL\",\n 5: \"SIGTRAP\",\n 6: \"SIGABRT\",\n 7: \"SIGBUS\",\n 8: \"SIGFPE\",\n 10: \"SIGUSR1\",\n 11: \"SIGSEGV\",\n 12: \"SIGUSR2\",\n 13: \"SIGPIPE\",\n 14: \"SIGALRM\",\n 15: \"SIGTERM\",\n 16: \"SIGSTKFLT\",\n 17: \"SIGCHLD\",\n 18: \"SIGCONT\",\n 19: \"SIGSTOP\",\n 20: \"SIGTSTP\",\n 21: \"SIGTTIN\",\n 22: \"SIGTTOU\",\n 23: \"SIGURG\",\n 24: \"SIGXCPU\",\n 25: \"SIGXFSZ\",\n 26: \"SIGVTALRM\",\n 27: \"SIGPROF\",\n 28: \"SIGWINCH\",\n 29: \"SIGIO\",\n 30: \"SIGPWR\",\n 31: \"SIGSYS\"\n };\n SIG_IGNORED_LINUX = [10, 13, 17, 18, 19, 20, 21, 22, 23, 28];\n SIG_TABLE_TO = ` const SIG_NAMES = ${JSON.stringify(SIG_NAMES_LINUX)};\n const SIG_IGNORED = new Set(${JSON.stringify(SIG_IGNORED_LINUX)});`;\n});\n\n// src/edge/tz.js\nfunction utcClock(g) {\n const RealDate = g.Date;\n const proto = RealDate.prototype;\n const realOffset = proto.getTimezoneOffset;\n const DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n const p2 = (n) => String(n).padStart(2, \"0\");\n const pairs = [[\"FullYear\"], [\"Month\"], [\"Date\"], [\"Day\"], [\"Hours\"], [\"Minutes\"], [\"Seconds\"], [\"Milliseconds\"]];\n const def = (name, fn) => Object.defineProperty(proto, name, { value: fn, writable: true, configurable: true, enumerable: false });\n for (const [n] of pairs) {\n def(\"get\" + n, function() {\n return this[\"getUTC\" + n]();\n });\n if (n !== \"Day\")\n def(\"set\" + n, function(...a) {\n return this[\"setUTC\" + n](...a);\n });\n }\n def(\"getYear\", function() {\n return this.getUTCFullYear() - 1900;\n });\n def(\"setYear\", function(y) {\n return this.setUTCFullYear(y >= 0 && y <= 99 ? 1900 + y : y);\n });\n def(\"getTimezoneOffset\", function() {\n return Number.isNaN(this.getTime()) ? NaN : 0;\n });\n const year = (y) => y >= 0 ? String(y).padStart(4, \"0\") : \"-\" + String(-y).padStart(4, \"0\");\n const dateText = (d) => `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${p2(d.getUTCDate())} ${year(d.getUTCFullYear())}`;\n const timeText = (d) => `${p2(d.getUTCHours())}:${p2(d.getUTCMinutes())}:${p2(d.getUTCSeconds())} GMT+0000 (Coordinated Universal Time)`;\n const valid = (d, f) => Number.isNaN(d.getTime()) ? \"Invalid Date\" : f(d);\n def(\"toString\", function() {\n return valid(this, (d) => dateText(d) + \" \" + timeText(d));\n });\n def(\"toDateString\", function() {\n return valid(this, dateText);\n });\n def(\"toTimeString\", function() {\n return valid(this, timeText);\n });\n for (const name of [\"toLocaleString\", \"toLocaleDateString\", \"toLocaleTimeString\"]) {\n const orig = proto[name];\n def(name, function(loc, opt) {\n return orig.call(this, loc, { timeZone: \"UTC\", ...opt });\n });\n }\n const isoDate = /^(?:\\+\\d{6}|-(?!000000)\\d{6}|\\d{4})(?:-\\d\\d(?:-\\d\\d)?)?$/;\n const isoLocalTime = /^(?:[+-]\\d{6}|\\d{4})-\\d\\d-\\d\\dT\\d\\d:\\d\\d(?::\\d\\d(?:\\.\\d+)?)?$/i;\n const hasZone = /(\\dZ|\\b(?:GMT|UTC|UT|[ECMP][SD]T|Z)\\b|(?:\\b(?:GMT|UTC|UT)|\\d:\\d\\d(?::\\d\\d(?:\\.\\d+)?)?\\s*|\\s)[+-]\\d{1,2}(?::?\\d{2})?)\\s*(\\([^)]*\\))?\\s*$/i;\n const zonedInside = /\\b(?:GMT|UTC|UT)\\b|\\b[ECMP][SD]T\\b|\\dZ\\b|\\s[+-]\\d{2}:?\\d{2}\\b/i;\n const dayBefore = (t) => realOffset.call(new RealDate(t - 86400000));\n const parse = (v) => {\n const s = String(v);\n const t = RealDate.parse(s);\n if (isoDate.test(s) || hasZone.test(s))\n return t;\n const off = Number.isNaN(t) || zonedInside.test(s) ? 0 : realOffset.call(new RealDate(t));\n const iso = isoLocalTime.test(s);\n for (const tail of iso ? [\"Z\"] : [\" GMT\", \"Z\"]) {\n const u = RealDate.parse(s + tail);\n if (!Number.isNaN(u) && (iso || u !== t || off === 0 || dayBefore(t) === 0))\n return u;\n }\n if (Number.isNaN(t))\n return NaN;\n if (!zonedInside.test(s) && !s.includes(\":\") && t % 86400000 === 0 && realOffset.call(new RealDate(t)) !== 0)\n return t;\n const offT = realOffset.call(new RealDate(t));\n let c = t - offT * 60000;\n const offB = dayBefore(t);\n if (offB !== offT) {\n const d = new RealDate(c);\n if (!new RegExp(\"(^|\\\\D)0?\" + d.getUTCHours() + \":\" + p2(d.getUTCMinutes()) + \"(\\\\D|$)\").test(s))\n c = t - offB * 60000;\n }\n return new RealDate(c).getTime();\n };\n const D = new Proxy(RealDate, {\n construct(t, a, nt) {\n if (a.length >= 2)\n return Reflect.construct(t, [RealDate.UTC(...a)], nt);\n if (a.length === 1 && typeof a[0] === \"string\")\n return Reflect.construct(t, [parse(a[0])], nt);\n return Reflect.construct(t, a, nt);\n },\n apply: () => new D().toString(),\n get: (t, k, r) => k === \"parse\" ? parse : Reflect.get(t, k, t)\n });\n Object.defineProperty(proto, \"constructor\", { value: D, writable: true, configurable: true, enumerable: false });\n g.Date = D;\n const DTF = g.Intl.DateTimeFormat;\n g.Intl.DateTimeFormat = new Proxy(DTF, {\n construct: (t, [loc, opt], nt) => Reflect.construct(t, [loc, { timeZone: \"UTC\", ...opt }], nt),\n apply: (t, th, [loc, opt]) => t(loc, { timeZone: \"UTC\", ...opt })\n });\n}\nfunction withUtcClock(src) {\n const head = \"'use strict';\";\n if (src.split(head).length !== 2 || !src.startsWith(head))\n throw new Error(\"linux.cjs: 'use strict' is not the first statement, once; the browser's clock needs a change\");\n return head + `\n(${utcClock})(globalThis);` + src.slice(head.length);\n}\nvar UTC_NAME_LIST, UTC_NAMES;\nvar init_tz = __esm(() => {\n UTC_NAME_LIST = [\"\", \"UTC\", \"UTC0\", \"Etc/UTC\", \"GMT\", \"GMT0\", \"Etc/GMT\", \"Etc/GMT0\", \"Etc/Universal\", \"Etc/Zulu\", \"Universal\", \"Zulu\", \"Z\", \":UTC\"];\n UTC_NAMES = new Set(UTC_NAME_LIST);\n});\n\n// src/edge/own/shim-post.js\nfunction ownShimPost(process, realGlobal, g, utcClock2, utcNames = [], req = null, sigNames = null, sigIgnored = null) {\n process.memoryUsage.rss = function rss() {\n return process.memoryUsage().rss;\n };\n {\n const engineMemory = process.memoryUsage;\n const memoryUsage = function memoryUsage() {\n const m = engineMemory.apply(process, arguments);\n const js = realGlobal && realGlobal.performance && realGlobal.performance.memory;\n if (m && js && js.usedJSHeapSize > 0) {\n m.heapUsed = js.usedJSHeapSize;\n m.heapTotal = js.totalJSHeapSize || js.usedJSHeapSize;\n m.rss = (m.rss || 0) + m.heapTotal;\n }\n return m;\n };\n memoryUsage.rss = function rss() {\n return process.memoryUsage().rss;\n };\n process.memoryUsage = memoryUsage;\n }\n try {\n const st = realGlobal && realGlobal[Symbol.for(\"wasmer.napi.serdes.state\")];\n const B = g && g.Buffer;\n if (st && typeof B === \"function\")\n st.bufferOf = (u8) => B.from(u8.buffer, u8.byteOffset, u8.byteLength);\n } catch {}\n if (sigNames && typeof process.kill === \"function\") {\n const nativeKill = process.kill;\n const byName = {};\n for (const n of Object.keys(sigNames))\n byName[sigNames[n]] = Number(n);\n byName.SIGKILL = 9;\n const ignored = new Set(sigIgnored || []);\n const later = (f) => typeof g.setImmediate === \"function\" ? g.setImmediate(f) : setTimeout(f, 0);\n process.kill = function kill(pid, sig) {\n const mine = pid === process.pid || pid === 0 || pid === \"0\" || String(pid) === String(process.pid) || String(pid) === \"-\" + process.pid;\n if (!mine)\n return nativeKill.apply(process, arguments);\n if (sig === 0 || sig === \"0\")\n return true;\n const num = sig === undefined ? 15 : typeof sig === \"number\" ? sig : byName[sig];\n const name = num === 9 ? \"SIGKILL\" : sigNames[num];\n if (!name)\n return nativeKill.apply(process, arguments);\n if (num !== 9 && process.listenerCount(name) > 0) {\n later(() => process.emit(name, name, num));\n return true;\n }\n if (num !== 9 && (ignored.has(num) || num === 10))\n return true;\n process.reallyExit(128 + num);\n return true;\n };\n }\n {\n let state = 0;\n const mainThread = () => {\n try {\n const wt = typeof req === \"function\" ? req(\"worker_threads\") : null;\n return !wt || wt.isMainThread !== false;\n } catch {\n return true;\n }\n };\n for (const name of [\"exit\", \"reallyExit\"]) {\n const native = process[name];\n if (typeof native !== \"function\")\n continue;\n process[name] = function() {\n if (state === 2)\n return;\n const outer = state === 0;\n state = 1;\n let ret;\n try {\n ret = native.apply(process, arguments);\n } finally {\n if (outer)\n state = 2;\n }\n const now = realGlobal && realGlobal.__wmdExitNow;\n if (typeof now === \"function\" && mainThread())\n now(name === \"reallyExit\" ? arguments[0] : process.exitCode, process.pid);\n return ret;\n };\n }\n }\n if (realGlobal && typeof realGlobal.addEventListener === \"function\") {\n realGlobal.addEventListener(\"unhandledrejection\", (ev) => {\n ev.preventDefault();\n const reason = ev.reason;\n if (process.emit(\"unhandledRejection\", reason, ev.promise))\n return;\n if (process.listenerCount(\"uncaughtException\") > 0) {\n process.emit(\"uncaughtException\", reason, \"unhandledRejection\");\n return;\n }\n const text = reason instanceof Error ? String(reason.stack || reason) : `[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"${String(reason)}\".] { code: 'ERR_UNHANDLED_REJECTION' }`;\n process.stderr.write(text + `\n`);\n process.exit(1);\n });\n }\n const fs = typeof req === \"function\" ? req(\"fs\") : null;\n if (fs && typeof fs.renameSync === \"function\") {\n const isDir = (p) => {\n try {\n return fs.lstatSync(p).isDirectory();\n } catch {\n return false;\n }\n };\n const fixed = (e, from, to) => {\n if (!e || e.code !== \"EINVAL\" || !isDir(to) || isDir(from))\n return e;\n const x = new Error(`EISDIR: illegal operation on a directory, rename '${from}' -> '${to}'`);\n return Object.assign(x, { errno: -21, code: \"EISDIR\", syscall: \"rename\", path: String(from), dest: String(to) });\n };\n const moveLink = (from, to) => {\n let text;\n try {\n if (!fs.lstatSync(from).isSymbolicLink())\n return false;\n text = fs.readlinkSync(from);\n let there = null;\n try {\n there = fs.lstatSync(to);\n } catch {}\n if (there && there.isDirectory())\n return false;\n if (there)\n fs.unlinkSync(to);\n fs.symlinkSync(text, to);\n fs.unlinkSync(from);\n return true;\n } catch {\n return false;\n }\n };\n const isLink = (p) => {\n try {\n return fs.lstatSync(p).isSymbolicLink();\n } catch {\n return false;\n }\n };\n const renameSync = fs.renameSync;\n fs.renameSync = function(from, to) {\n if (isLink(from) && moveLink(from, to))\n return;\n try {\n return renameSync.call(fs, from, to);\n } catch (e) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return;\n throw fixed(e, from, to);\n }\n };\n const rename = fs.rename;\n fs.rename = function(from, to, cb) {\n if (typeof cb !== \"function\")\n return rename.call(fs, from, to, cb);\n if (isLink(from) && moveLink(from, to))\n return void queueMicrotask(() => cb(null));\n return rename.call(fs, from, to, function(e, ...a) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return cb(null);\n cb(e ? fixed(e, from, to) : e, ...a);\n });\n };\n if (fs.promises && typeof fs.promises.rename === \"function\") {\n const prename = fs.promises.rename;\n fs.promises.rename = async function(from, to) {\n if (isLink(from) && moveLink(from, to))\n return;\n try {\n return await prename.call(fs.promises, from, to);\n } catch (e) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return;\n throw fixed(e, from, to);\n }\n };\n }\n }\n const tz = process.env && process.env.TZ;\n if (typeof utcClock2 === \"function\" && utcNames.includes(String(tz == null ? \"\" : tz).trim()))\n utcClock2(g);\n}\nvar SHIM_POST;\nvar init_shim_post = __esm(() => {\n init_tz();\n init_shim();\n SHIM_POST = `\n;(${ownShimPost.toString()})(process, Function('return this')(), globalThis, ${utcClock.toString()}, ${JSON.stringify(UTC_NAME_LIST)}, typeof require === 'function' ? require : null, ${JSON.stringify(SIG_NAMES_LINUX)}, ${JSON.stringify(SIG_IGNORED_LINUX)});\n`;\n});\n\n// src/edge/own/adapter.js\nvar exports_adapter = {};\n__export(exports_adapter, {\n exit: () => exit,\n fsCacheOf: () => fsCacheOf,\n fscacheRunOption: () => fscacheRunOption,\n keep: () => keep,\n load: () => load,\n name: () => name,\n prepare: () => prepare,\n release: () => release,\n setDeps: () => setDeps,\n signal: () => signal,\n start: () => start,\n stats: () => stats,\n teardown: () => teardown\n});\nfunction fsCacheOf(env) {\n const v = env && env.WMD_FSCACHE;\n return typeof v === \"string\" && /^[0-7]$/.test(v) ? Number(v) : undefined;\n}\nfunction fscacheRunOption(own, env) {\n if (own && own.fscache === false)\n return 0;\n return fsCacheOf(env);\n}\nfunction runtimeFile(text) {\n const e = new Error(text);\n e.runtimeFiles = true;\n return e;\n}\nasync function fetchOk(url) {\n let r;\n try {\n r = await deps.fetch(url);\n } catch (e) {\n throw runtimeFile(`${absUrl(url)} could not be fetched: ${whyOf(e)}`);\n }\n if (r.ok === false) {\n const e = new Error(`${r.url || url} answered ${r.status}${r.statusText ? \" \" + r.statusText : \"\"}`);\n e.runtimeFiles = true;\n throw e;\n }\n return r;\n}\nasync function readFile(url, as) {\n const r = await fetchOk(url);\n try {\n return as === \"text\" ? await r.text() : new Uint8Array(await r.arrayBuffer());\n } catch (e) {\n throw runtimeFile(`${r.url || absUrl(url)} could not be read: ${whyOf(e)}`);\n }\n}\nfunction setDeps(d) {\n deps = { ...deps, ...d };\n}\n\nclass Pipe {\n #chunks = [];\n #waiters = [];\n #done = false;\n bytes = 0;\n late = 0;\n taken = 0;\n push(b) {\n if (!b.length)\n return;\n this.bytes += b.length;\n if (this.#done)\n this.late += b.length;\n if (this.#waiters.length)\n this.#waiters.shift()(b);\n else\n this.#chunks.push(b);\n }\n end() {\n this.#done = true;\n for (const w of this.#waiters.splice(0))\n w(null);\n }\n async read(n) {\n if (this.#chunks.length)\n return this.#take(n);\n if (this.#done)\n return null;\n const b = await new Promise((r) => this.#waiters.push(r));\n if (b === null)\n return null;\n this.#chunks.unshift(b);\n return this.#take(n);\n }\n #take(n) {\n const c = this.#chunks[0];\n if (c.length <= n) {\n this.taken += c.length;\n return this.#chunks.shift();\n }\n this.#chunks[0] = c.subarray(n);\n this.taken += n;\n return c.subarray(0, n);\n }\n}\nfunction portRoute(p) {\n let next = 1;\n const pending = new Map;\n p.onmessage = (e) => {\n const m = e.data;\n const w = m && pending.get(m.id);\n if (!w)\n return;\n pending.delete(m.id);\n w(m.reply);\n };\n const route = {\n queueSignal: (id, n) => {\n route.handle(\"sigq\", [id, n], new Uint8Array(0));\n },\n handle: (method, args, data) => new Promise((resolve) => {\n const id = next++;\n pending.set(id, resolve);\n p.postMessage(globalThis.__wmdFsTime ? { own: \"fs\", id, method, args, data, t0: performance.timeOrigin + performance.now() } : { own: \"fs\", id, method, args, data });\n }),\n close: () => {\n try {\n p.postMessage({ own: \"bye\" });\n } catch {}\n for (const w of pending.values())\n w({ error: { code: \"EIO\", message: \"the file route closed\" } });\n pending.clear();\n }\n };\n return route;\n}\nasync function checkFiles(own, files) {\n const base = own.wasmUrl.replace(/[^/?#]*([?#].*)?$/, \"\");\n let text = null;\n try {\n const r = await deps.fetch(own.hashesUrl || base + \"HASHES.txt\");\n if (r.ok !== false)\n text = await r.text();\n } catch {}\n if (text === null) {\n files.missing++;\n return {};\n }\n const want = new Map;\n for (const line of String(text).split(`\n`)) {\n const [hash, size, name2] = line.trim().split(/\\s+/);\n if (name2 && /^[0-9a-f]{64}$/.test(hash))\n want.set(name2, { hash, size: Number(size) });\n }\n const out = {};\n for (const [key, name2] of [[\"wasmUrl\", \"wmd_browser_bg.wasm\"], [\"glueUrl\", \"wmd_browser.js\"]]) {\n const w = want.get(name2);\n if (!w) {\n files.unlisted++;\n continue;\n }\n const bytes = await readFile(own[key], \"bytes\");\n files.checked++;\n if (bytes.length !== w.size || await sha256(bytes) !== w.hash) {\n files.mismatch++;\n throw runtimeFile(`the runtime's files do not match HASHES.txt: ${name2} at ${absUrl(own[key])} (size ${bytes.length}, listed ${w.size}); not run`);\n }\n files.ok++;\n if (key === \"wasmUrl\") {\n mark(\"rtc0\");\n try {\n out.module = await deps.compile(bytes);\n } catch (e) {\n throw runtimeFile(`${absUrl(own[key])} did not compile as WebAssembly: ${whyOf(e)}`);\n }\n mark(\"rtc1\");\n }\n }\n return out;\n}\nfunction keep() {\n const k = state && state.keep;\n return k && (k.rtModule || k.prog) ? { ...k, texts: { ...k.texts } } : null;\n}\nasync function runtimeModule(own) {\n const k = state.kept;\n if (k && k.rtModule) {\n state.module = k.rtModule;\n state.files.kept = 1;\n state.keep.rtModule = k.rtModule;\n mark(\"checked\");\n return;\n }\n const tc = performance.now();\n const ok = await checkFiles(own, state.files);\n state.stages.check = performance.now() - tc;\n mark(\"checked\");\n state.module = ok.module;\n if (state.keep && ok.module)\n state.keep.rtModule = ok.module;\n}\nasync function programOf(module, memoryMaxMiB) {\n const s = state;\n let ready = s.kept && s.kept.prog && s.kept.prog.url === module ? s.kept.prog : null;\n let program = null;\n if (ready) {\n s.stages.keptProgram = 1;\n } else {\n program = await readFile(module, \"bytes\");\n if (s.keep && deps.OwnRuntime.prepare) {\n try {\n ready = { ...await deps.OwnRuntime.prepare(program, memoryMaxMiB ? { memoryMaxMiB } : undefined), url: module };\n } catch (e) {\n throw runtimeFile(`${absUrl(module)} is not a node program the runtime can compile: ${whyOf(e)}`);\n }\n program = null;\n }\n }\n if (s.keep && ready)\n s.keep.prog = ready;\n return { program, ready };\n}\nasync function linuxText(src) {\n const s = state;\n let raw = s.keep && s.keep.texts[src];\n if (typeof raw !== \"string\") {\n raw = await readFile(src, \"text\");\n try {\n shimSource(raw, {}, { symlinks: false });\n } catch (e) {\n throw runtimeFile(`${absUrl(src)} is not the settings file: ${whyOf(e)}`);\n }\n }\n if (s.keep)\n s.keep.texts[src] = raw;\n return raw;\n}\nfunction newState(own, kept, more) {\n const k = keptFor(own, kept);\n state = { own, out: new Pipe, err: new Pipe, t0: performance.now(), signals: [], files: { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 }, module: undefined, stages: {}, marks: own.marks ? { ...globalThis.__wmdFwMarks || {} } : null, ...more };\n state.kept = k;\n state.keep = own.keepMods !== false ? { wasmUrl: own.wasmUrl, glueUrl: own.glueUrl, rtModule: null, prog: null, texts: { ...k ? k.texts : {} } } : null;\n mark(\"load0\");\n}\nasync function load({ cfg, ports, log, onWorkerError, kept = null }) {\n const own = cfg.own || {};\n if (!own.wasmUrl || !own.glueUrl || !own.workerUrl)\n throw new Error(\"rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl\");\n if (own.fsTime)\n globalThis.__wmdFsTime = true;\n port = ports[0];\n route = portRoute(port);\n newState(own, kept, { log, onWorkerError });\n await runtimeModule(own);\n return {};\n}\nasync function prepare({ cfg, kept = null }) {\n const own = cfg.own || {};\n if (!own.wasmUrl || !own.glueUrl || !own.workerUrl)\n throw new Error(\"rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl\");\n if (own.keepMods === false)\n return { kept: false };\n newState(own, kept, {});\n await runtimeModule(own);\n await programOf(cfg.edgeWasm || \"/wasm/edgejs.wasm\", cfg.memoryMaxMiB);\n if (cfg.linux)\n await linuxText(cfg.linuxSrc || \"/wasm/linux.cjs\");\n return { kept: true, stages: { ...state.stages }, files: { ...state.files } };\n}\nasync function pythonShimText(src, linux) {\n const s = state;\n let raw = s.keep && s.keep.texts[src];\n if (typeof raw !== \"string\")\n raw = await readFile(src, \"text\");\n if (s.keep)\n s.keep.texts[src] = raw;\n const marker = '_cfg = {\"execPath\": \"\", \"arch\": \"\", \"hostname\": \"\", \"cpus\": 0, \"uid\": 0, \"gid\": 0} #__WMD_EDGE_CONFIG__#';\n if (!raw.includes(marker))\n throw runtimeFile(`${absUrl(src)} is not the python settings file`);\n const cfg = { execPath: linux.execPath, arch: linux.arch || \"arm64\", hostname: linux.hostname || \"wmd-web\", cpus: linux.cpus || 1, uid: linux.uid | 0, gid: linux.gid | 0 };\n return raw.replace(marker, () => `_cfg = (lambda true, false, null: ${JSON.stringify(cfg)})(True, False, None)`);\n}\nasync function start({ module, argv, env, cwd, files = {}, linux, linuxSrc, stdin = \"closed\", python }) {\n const s = state;\n let tm = performance.now();\n const lap = (name2) => {\n const now = performance.now();\n s.stages[name2] = now - tm;\n tm = now;\n };\n mark(\"start0\");\n const { program, ready } = await programOf(module, python && python.maxMiB);\n lap(\"program\");\n mark(\"program\");\n let args = argv;\n const shim = { ...files };\n if (python) {\n shim[\"startup.py\"] = await pythonShimText(linuxSrc || \"/wasm/linux.py\", linux || {});\n } else if (linux) {\n const text = shimSource(await linuxText(linuxSrc || \"/wasm/linux.cjs\"), linux, { symlinks: false }) + SHIM_POST;\n shim[\"linux.cjs\"] = text;\n args = [\"--require\", SHIM_PATH, ...argv];\n }\n await route.handle(\"shim\", [shim], new Uint8Array(0));\n lap(\"shim\");\n mark(\"shim\");\n if (globalThis.__wmdFsTime)\n await route.handle(\"timing\", [\"on\"], new Uint8Array(0));\n rt = await deps.OwnRuntime.start({\n wasmUrl: s.own.wasmUrl,\n ...s.module ? { module: s.module } : {},\n glueUrl: s.own.glueUrl,\n workerUrl: s.own.workerUrl,\n fsRoute: route,\n ...python && python.maxMiB ? { memoryMaxMiB: python.maxMiB } : {},\n marks: s.own.marks === 2 ? 2 : !!s.marks,\n onOut: (fd, b) => {\n if (s.stages.firstOut === undefined && b.length && s.runT0)\n s.stages.firstOut = performance.now() - s.runT0, mark(\"firstOut\");\n (fd === 2 ? s.err : s.out).push(b);\n },\n onLog: (d) => s.log?.(typeof d === \"string\" ? d : JSON.stringify(d)),\n stack: s.own.stack,\n ...s.own.trace ? { trace: s.own.trace | 0 } : {},\n nodeGlobals: NODE_GLOBALS\n });\n lap(\"boot\");\n mark(\"booted\");\n s.runT0 = performance.now();\n mark(\"runPost\");\n const envList = Object.entries({ HOME: \"/root\", ...env || {} }).map(([k, v]) => `${k}=${v}`);\n runP = rt.run({ program, ...ready ? { ready } : {}, args, env: envList, node: !python, cwd, stdin: stdin === \"pipe\" ? \"pipe\" : \"null\", tty: {}, children: s.own.children !== false, net: s.own.net !== false, exec: linux && linux.execPath, shim: !!linux && !python, ...python ? { argv0: python.argv0 } : {}, ...fscacheRunOption(s.own, env) !== undefined ? { fscache: fscacheRunOption(s.own, env) } : {} }).then((r) => (r.code & ~127) === 16384 ? { exitCode: 128 + (r.code & 127), reason: \"exit\", signal: r.code & 127 } : { exitCode: r.code, reason: \"exit\" }, (e) => ({ exitCode: 1, reason: \"error: \" + String(e && e.message || e) })).then((r) => (mark(\"exitRecv\"), s.stages.run = performance.now() - s.runT0, s.out.end(), s.err.end(), r));\n return {\n readStdout: (n) => s.out.read(n),\n readStderr: (n) => s.err.read(n),\n writeStdin: async (bytes) => rt.writeStdin(bytes),\n closeStdin: async () => rt.closeStdin()\n };\n}\nasync function signal(proc, n) {\n if (n === 9)\n return rt?.terminate();\n return rt?.signal ? rt.signal(n) : undefined;\n}\nasync function exit() {\n const r = await runP;\n if (globalThis.__wmdFsTime && rt) {\n try {\n const t = (await route.handle(\"timing\", [\"read\"], new Uint8Array(0))).value;\n for (const [side, v] of [[\"hub\", rt.fsTiming], [\"route\", t]]) {\n const j = JSON.stringify(v);\n for (let i = 0;i < j.length; i += 140)\n await route.handle(\"note\", [`FSTAT ${side} ${i / 140} ` + j.slice(i, i + 140)], new Uint8Array(0));\n }\n } catch {}\n }\n return r;\n}\nasync function teardown() {\n rt?.terminate();\n}\nfunction release() {\n rt?.terminate();\n route?.close?.();\n return rt ? 1 : 0;\n}\nasync function stats() {\n let wasm = null;\n try {\n const mine = globalThis.__wmdWasmCounters ? globalThis.__wmdWasmCounters.snapshot() : null;\n let theirs = [];\n if (rt && state && state.own.counts) {\n const tc = performance.now();\n theirs = await rt.collectCounts(400);\n state.stages.counts = performance.now() - tc;\n }\n let sum = mine;\n for (const t of theirs)\n sum = addCounts(sum, t.c);\n if (sum)\n wasm = { ...sum, workers: theirs.length };\n if (wasm)\n wasm.kinds = [...globalThis.__wmdWasmCounters?.kinds?.() || [], ...theirs.flatMap((t) => t.c && t.c.kinds || [])];\n } catch {}\n let marks = null;\n if (state && state.marks) {\n const rm = rt && rt.marks || { first: {}, n: {} };\n const all = { ...rm.first, ...state.marks };\n for (const [k, v] of Object.entries(stagesOf(all)))\n state.stages[\"m.\" + k] = v;\n const base = state.marks.frame ?? state.marks.load0;\n marks = { t: Object.fromEntries(Object.entries(all).map(([k, v]) => [k, Math.round((v - base) * 10) / 10])), n: { ...rm.n }, ...rm.fs ? { fs: rm.fs } : {}, ...rm.series && Object.keys(rm.series).length ? { series: Object.fromEntries(Object.entries(rm.series).map(([k, v]) => [k, v.map((x) => Math.round((x - base) * 10) / 10)])) } : {}, ...rm.memMiB ? { memMiB: rm.memMiB } : {}, ...rm.calls ? { calls: rm.calls } : {} };\n }\n return {\n ...marks ? { marks } : {},\n service: null,\n frameRtt: null,\n ...wasm ? { wasm } : {},\n ...rt?.capiStats ? { capi: rt.capiStats } : {},\n ...rt && rt.forged ? { forged: rt.forged } : {},\n ...state ? { files: { ...state.files }, stages: { ...state.stages }, pipes: { out: state.out.bytes, err: state.err.bytes, lateOut: state.out.late, lateErr: state.err.late, unreadOut: state.out.bytes - state.out.taken, unreadErr: state.err.bytes - state.err.taken } } : {}\n };\n}\nvar name = \"own\", absUrl = (url) => {\n try {\n return new URL(url, globalThis.location && globalThis.location.href).href;\n } catch {\n return url;\n }\n}, whyOf = (e) => String(e && e.message || e).split(`\n`)[0], SHIM_PATH = \"/.wmd-edge/linux.cjs\", deps, rt = null, port = null, route = null, runP = null, state = null, mark = (name2) => {\n if (state && state.marks && state.marks[name2] === undefined)\n state.marks[name2] = at();\n}, sha256 = async (u8) => Array.from(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", u8)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\"), keptFor = (own, kept) => own.keepMods !== false && kept && kept.wasmUrl === own.wasmUrl && kept.glueUrl === own.glueUrl ? kept : null;\nvar init_adapter = __esm(() => {\n init_marks();\n init_hub();\n init_node_globals();\n init_shim();\n init_shim_post();\n deps = { OwnRuntime, fetch: (...a) => fetch(...a), compile: (b) => WebAssembly.compile(b) };\n});\n\n// src/edge/hist.js\nclass Hist {\n constructor() {\n this.n = 0;\n this.sumUs = 0;\n this.maxUs = 0;\n this.neg = 0;\n this.b = new Array(LOG2_BUCKETS).fill(0);\n }\n add(us) {\n if (us < 0) {\n this.neg++;\n us = 0;\n }\n this.n++;\n this.sumUs += us;\n if (us > this.maxUs)\n this.maxUs = us;\n const b = us < 1 ? 0 : Math.min(LOG2_BUCKETS - 1, Math.floor(Math.log2(us)) + 1);\n this.b[b]++;\n }\n quantileUs(q) {\n if (!this.n)\n return 0;\n const want = Math.ceil(this.n * q);\n let c = 0;\n for (let i = 0;i < this.b.length; i++) {\n c += this.b[i];\n if (c >= want)\n return i === 0 ? 1 : 2 ** i;\n }\n return this.maxUs;\n }\n summary() {\n return {\n n: this.n,\n meanUs: this.n ? +(this.sumUs / this.n).toFixed(1) : 0,\n maxUs: +this.maxUs.toFixed(1),\n neg: this.neg,\n p50Us: this.quantileUs(0.5),\n p90Us: this.quantileUs(0.9),\n p99Us: this.quantileUs(0.99),\n buckets: this.b.slice()\n };\n }\n}\nvar LOG2_BUCKETS = 24;\n\n// src/edge/sdk/forward.js\nclass Forwarder {\n constructor(port, respond) {\n this.port = port;\n this.respond = respond;\n this.pending = new Map;\n this.next = 1;\n this.rtt = {};\n this.stat = new Map;\n port.onmessage = ({ data: m }) => this.#reply(m);\n }\n send(m) {\n const id = this.next++;\n const t0 = performance.now();\n this.pending.set(id, { request: m, t0, method: m.method });\n this.port.postMessage({ id, mount: m.mount, method: m.method, args: m.args, t0: performance.timeOrigin + t0 });\n }\n #reply(m) {\n if (m.stats !== undefined || m.reset || m.plan) {\n const r = this.stat.get(m.id);\n this.stat.delete(m.id);\n if (r)\n r(m);\n return;\n }\n const p = this.pending.get(m.id);\n if (!p)\n return;\n this.pending.delete(m.id);\n (this.rtt[p.method] ||= new Hist).add((performance.now() - p.t0) * 1000);\n this.respond(p.request, m.res);\n }\n stats() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, (m) => res(m.stats));\n this.port.postMessage({ id, op: \"stats\" });\n });\n }\n plan() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, (m) => res(m.plan));\n this.port.postMessage({ id, op: \"plan\" });\n });\n }\n reset() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, () => res());\n this.port.postMessage({ id, op: \"reset\" });\n this.rtt = {};\n });\n }\n rttSummary() {\n return Object.fromEntries(Object.entries(this.rtt).map(([k, h]) => [k, h.summary()]));\n }\n}\nvar init_forward = () => {};\n\n// src/edge/workers.js\nfunction workerRegistry() {\n const made = new Set;\n return {\n track(w) {\n made.add(w);\n return w;\n },\n release() {\n const n = made.size;\n for (const w of [...made]) {\n made.delete(w);\n try {\n w.terminate();\n } catch {}\n }\n return n;\n },\n size: () => made.size\n };\n}\n\n// src/edge/spawn-guard.js\nfunction newSpawnMark() {\n const b = crypto.getRandomValues(new Uint8Array(6));\n return `${SPAWN_MARK.slice(0, -2)} [${Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\")}]: `;\n}\nfunction markScanner(mark) {\n let carry = \"\";\n let line = null;\n let done = false;\n return {\n push(text) {\n if (done)\n return;\n if (line === null) {\n const all = carry + text;\n const at = all.indexOf(mark);\n if (at < 0) {\n carry = all.slice(Math.max(0, all.length - (mark.length - 1)));\n return;\n }\n line = all.slice(at + mark.length);\n carry = \"\";\n } else\n line += text;\n const nl = line.indexOf(`\n`);\n if (nl < 0)\n return;\n done = true;\n return line.slice(0, nl);\n },\n finish: () => !done && line !== null ? (done = true, line) : undefined\n };\n}\nfunction spawnGuard(req, proc, mark, code) {\n const cp = req(\"child_process\");\n const fs = req(\"fs\");\n let refused = false;\n const refuse = (name, cmd) => {\n if (refused)\n throw new Error(\"spawn refused\");\n refused = true;\n const c = String(cmd == null ? \"\" : cmd).replace(/\\s+/g, \" \").slice(0, 200);\n const text = `${mark}${c}\nwmd: this program started a process (${name}), which node cannot do in the browser frame. It ends here. The next run of this program goes to the guest.\n`;\n try {\n fs.writeSync(2, text);\n } catch {}\n proc.exit(code);\n throw new Error(\"spawn refused: \" + c);\n };\n for (const name of [\"spawn\", \"spawnSync\", \"exec\", \"execSync\", \"execFile\", \"execFileSync\", \"fork\"]) {\n if (typeof cp[name] === \"function\")\n cp[name] = function(cmd) {\n return refuse(name, cmd);\n };\n }\n}\nfunction withSpawnGuard(src, mark = SPAWN_MARK) {\n return src + `\n;(${spawnGuard})(require, process, ${JSON.stringify(mark)}, ${SPAWN_EXIT});\n`;\n}\nvar SPAWN_MARK = \"wmd: spawn refused: \", SPAWN_EXIT = 126;\n\n// src/edge/sdk/adapter.js\nvar exports_adapter2 = {};\n__export(exports_adapter2, {\n exit: () => exit2,\n liveWorkers: () => liveWorkers,\n load: () => load2,\n name: () => name2,\n release: () => release2,\n signal: () => signal2,\n start: () => start2,\n stats: () => stats2,\n teardown: () => teardown2\n});\nfunction wrapWorkers(onWorkerError) {\n if (RealWorker)\n return;\n RealWorker = globalThis.Worker;\n globalThis.Worker = class extends RealWorker {\n constructor(...a) {\n super(...a);\n workers.track(this);\n this.addEventListener(\"message\", (e) => {\n const m = e.data;\n if (m && m.type === HOST_FS_MESSAGE && m.response && fwd) {\n e.stopImmediatePropagation();\n fwd.send(m);\n }\n });\n this.addEventListener(\"error\", (e) => onWorkerError?.(String(e && e.message || \"a Worker failed to load or crashed\")));\n }\n };\n}\nasync function load2({ cfg, ports, log, onWorkerError }) {\n baseUrl = cfg.rtBase || \"/sdk/\";\n wrapWorkers(onWorkerError);\n const t0 = performance.now();\n const hf = await import(baseUrl + \"dist/host-filesystem.js\");\n fwd = new Forwarder(ports[0], hf.respondToHostFileSystem);\n relay = workers.track(new RealWorker(\"/edge/sdk/relay.js\", { type: \"module\" }));\n relay.addEventListener(\"error\", (e) => onWorkerError?.(\"the relay Worker failed: \" + String(e && e.message || \"\")));\n await new Promise((r) => {\n relay.onmessage = () => r();\n relay.postMessage({ port: ports[1] }, [ports[1]]);\n });\n hf.installHostFileSystemWorkerBridge((msg) => (relay.postMessage(msg), true));\n const plan = await fwd.plan();\n if (plan.oversize.length)\n return { fallback: { reason: \"listing-too-large\", oversize: plan.oversize.slice(0, 20) } };\n const { Wasmer } = await import(baseUrl + \"dist/index.js\");\n wasmer = new Wasmer({ cache: \"memory\", parallelism: cfg.parallelism || 2 });\n core = await wasmer.getCore();\n log(\"sdk loaded after \" + (performance.now() - t0).toFixed(0) + \" ms\");\n return {};\n}\nasync function start2({ module, argv, env, cwd, mounts, files = {}, linux, linuxSrc, stdin = \"closed\", timeoutMs, parallelism, spawnMark }) {\n const edge = new Uint8Array(await (await fetch(module)).arrayBuffer());\n const fileBytes = Object.fromEntries(Object.entries(files).map(([p, t]) => [p, enc3.encode(t)]));\n let args = argv;\n if (linux) {\n const shim = \"/.wmd-edge/linux.cjs\";\n const src = await (await fetch(linuxSrc || \"/wasm/linux.cjs\")).text();\n const text = shimSource(src, linux);\n fileBytes[shim] = enc3.encode(withSpawnGuard(linux.utc ? withUtcClock(text) : text, spawnMark));\n args = [\"--require\", shim, ...args];\n }\n pkg = await core.createPackage({ modules: { node: edge }, commands: { node: { module: \"node\" } }, files: fileBytes });\n const b = core.sandbox();\n b.package(pkg);\n b.env(\"HOME\", \"/root\");\n for (const [k, v] of Object.entries(env || {}))\n b.env(k, v);\n b.network(\"disabled\");\n for (const [path, id, ro] of mounts)\n b.mountHost(path, id, ro);\n sb = await b.start();\n await fwd.reset();\n const cmd = sb.commandPackage(pkg);\n cmd.args(args);\n if (cwd)\n cmd.currentDir(cwd);\n cmd.timeoutMs(timeoutMs || 2147483647);\n cmd.stdinMode(stdin);\n cmd.stdoutMode(\"pipe\");\n cmd.stderrMode(\"pipe\");\n const pr = await cmd.spawn();\n return {\n pr,\n readStdout: (n) => pr.readStdout(n),\n readStderr: (n) => pr.readStderr(n),\n writeStdin: (bytes) => pr.writeStdin(bytes),\n closeStdin: () => pr.closeStdin()\n };\n}\nasync function signal2(proc, n) {\n if (n === 9)\n return proc.pr.kill();\n return proc.pr.terminate(2000);\n}\nasync function exit2(proc) {\n const w = await proc.pr.wait();\n return { exitCode: w.exitCode, reason: w.reason };\n}\nasync function teardown2() {\n try {\n await sb?.close();\n } finally {\n await wasmer?.close();\n }\n}\nfunction release2() {\n return workers.release();\n}\nasync function stats2() {\n return { service: fwd ? await fwd.stats() : null, frameRtt: fwd ? fwd.rttSummary() : null };\n}\nvar name2 = \"sdk\", HOST_FS_MESSAGE = \"wasmer-filesystem-rpc\", enc3, fwd = null, relay = null, wasmer = null, sb = null, pkg = null, core = null, baseUrl = \"/sdk/\", RealWorker = null, workers, liveWorkers = () => workers.size();\nvar init_adapter2 = __esm(() => {\n init_forward();\n init_shim();\n init_tz();\n enc3 = new TextEncoder;\n workers = workerRegistry();\n});\n\n// src/edge/sbx/worker-entry.js\ninit_hub();\ninit_adapter();\n\n// src/edge/runtime.js\nvar LOADERS = {\n own: () => Promise.resolve().then(() => (init_adapter(), exports_adapter)),\n sdk: null\n};\nvar RT_DEFAULT = \"own\";\nvar RT_NAMES = () => Object.keys(LOADERS);\nfunction handSdk(base) {\n if (typeof base !== \"string\" || !base.startsWith(\"/\") || !base.endsWith(\"/\"))\n throw new Error(\"sdkBase must be a path that starts and ends with '/'\");\n LOADERS.sdk = () => Promise.resolve().then(() => (init_adapter2(), exports_adapter2));\n return { rtBase: base };\n}\nfunction unavailable(rt) {\n if (!Object.hasOwn(LOADERS, rt))\n return `rt=${rt}: no such runtime (rt=${RT_NAMES().join(\"|\")})`;\n if (!LOADERS[rt])\n return rt === \"sdk\" ? \"rt=sdk: no SDK was handed in (the page option sdkBase), it is not in this build, node runs in the guest\" : `rt=${rt}: the runtime is not in this build, node runs in the guest`;\n return \"\";\n}\nasync function loadAdapter(rt, cfg = null) {\n if (rt === \"sdk\" && !LOADERS.sdk && cfg && typeof cfg.rtBase === \"string\") {\n try {\n handSdk(cfg.rtBase);\n } catch {}\n }\n const why = unavailable(rt);\n if (why)\n throw new Error(why);\n return LOADERS[rt]();\n}\n\n// src/edge/error-kind.js\nvar errorKindOf = (e, loading) => loading || e && e.runtimeFiles === true ? \"runtime\" : undefined;\nvar ERROR_KINDS = new Set([\"runtime\"]);\n\n// src/edge/worker.js\ninstallWasmCounters(globalThis);\nvar log = (text) => postMessage({ type: \"log\", text });\nvar errorText = (e) => {\n const stack = e && e.stack ? String(e.stack) : \"\";\n const msg = e && e.message !== undefined ? `${e.name || \"Error\"}: ${e.message}` : \"\";\n if (!msg)\n return stack || String(e);\n return stack.startsWith(msg) ? stack : stack ? msg + `\n` + stack : msg;\n};\nvar dec2 = new TextDecoder;\nvar enc4 = new TextEncoder;\nvar adapter = null;\nvar finished = false;\nvar done = (d) => {\n if (finished)\n return;\n finished = true;\n postMessage({ type: \"done\", ...d });\n};\nvar proc = null;\nvar early = [];\nasync function input(m) {\n if (!proc)\n return early.push(m);\n if (m.stdin)\n await proc.writeStdin(m.stdin);\n else if (m.stdinEnd)\n await proc.closeStdin();\n else if (m.signal)\n await adapter.signal(proc, m.signal);\n}\nonmessage = async ({ data: { cfg, ports, in: inp, tf, kept, prepare } }) => {\n if (inp)\n return input(inp);\n if (prepare) {\n try {\n const t0 = performance.now();\n adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg);\n const r = adapter.prepare ? await adapter.prepare({ cfg, kept }) : { kept: false };\n const k = adapter.keep ? adapter.keep() : null;\n if (k)\n postMessage({ type: \"keep\", keep: k });\n return done({ prepared: !!k, prepareMs: Math.round(performance.now() - t0), ...r.stages ? { stages: r.stages } : {} });\n } catch (e) {\n const kind = errorKindOf(e, false);\n return done({ error: String(e && e.message || e).slice(0, 300), ...kind ? { errorKind: kind } : {} });\n }\n }\n if (typeof tf === \"number\")\n globalThis.__wmdFwMarks = { frame: tf, fw: performance.timeOrigin + performance.now() };\n const res = {};\n let loading = true;\n try {\n const t0 = performance.now();\n adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg);\n const loaded = await adapter.load({\n cfg,\n ports,\n kept,\n log,\n onWorkerError: (why) => done({ error: \"the runtime lost a Worker: \" + why })\n });\n loading = false;\n if (loaded.fallback)\n return done({ fallback: true, ...loaded.fallback });\n const spawnMark = newSpawnMark();\n proc = await adapter.start({\n spawnMark,\n module: cfg.edgeWasm,\n argv: cfg.args,\n env: cfg.env,\n cwd: cfg.cwd,\n mounts: cfg.mounts,\n files: cfg.files,\n linux: cfg.linux,\n linuxSrc: cfg.linuxSrc,\n python: cfg.python,\n stdin: cfg.stdin || \"closed\",\n timeoutMs: cfg.timeoutMs,\n parallelism: cfg.parallelism\n });\n res.setupMs = performance.now() - t0;\n const k = adapter.keep ? adapter.keep() : null;\n if (k)\n postMessage({ type: \"keep\", keep: k });\n log(\"process started after \" + res.setupMs.toFixed(0) + \" ms\");\n const t1 = performance.now();\n postMessage({ type: \"step\", name: \"ready\", ms: res.setupMs });\n for (const m of early.splice(0))\n await input(m);\n const outs = [];\n const errs = [];\n let spawnRefused;\n const scanner = markScanner(spawnMark);\n const sdec = new TextDecoder;\n const sent = res.outBytes = { stdout: 0, stderr: 0 };\n const pump = async (read, into, kind) => {\n for (let n = 0;n < 1e6; n++) {\n const b = await read(65536);\n if (b == null)\n return;\n if (!b.length)\n continue;\n sent[kind] += b.length;\n if (kind === \"stderr\" && spawnRefused === undefined)\n spawnRefused = scanner.push(sdec.decode(b, { stream: true }));\n if (cfg.stream) {\n const c = b.slice();\n postMessage({ type: \"out\", kind, bytes: c }, [c.buffer]);\n } else\n into.push(b);\n }\n };\n if (cfg.stdinBytes)\n await proc.writeStdin(enc4.encode(cfg.stdinBytes));\n if (cfg.stdinBytes && cfg.stdin === \"pipe\")\n await proc.closeStdin();\n await Promise.all([pump(proc.readStdout, outs, \"stdout\"), pump(proc.readStderr, errs, \"stderr\")]);\n const w = await adapter.exit(proc);\n const join = (chunks) => {\n const all = new Uint8Array(chunks.reduce((a, c) => a + c.length, 0));\n let at = 0;\n for (const c of chunks)\n all.set(c, at), at += c.length;\n return all;\n };\n if (spawnRefused === undefined)\n spawnRefused = scanner.finish();\n res.runMs = performance.now() - t1;\n res.exitCode = w.exitCode;\n if (spawnRefused !== undefined && w.exitCode === SPAWN_EXIT)\n res.spawnRefused = spawnRefused;\n res.reason = w.reason;\n res.stdout = dec2.decode(join(outs)).slice(-8000);\n res.stderr = dec2.decode(join(errs)).slice(-8000);\n Object.assign(res, await adapter.stats());\n } catch (e) {\n res.error = errorText(e);\n const kind = errorKindOf(e, loading);\n if (kind)\n res.errorKind = kind;\n }\n done(res);\n};\n\n// src/edge/sbx/common.js\nvar b64 = (text) => {\n const bytes = new TextEncoder().encode(text);\n let s = \"\";\n for (let i = 0;i < bytes.length; i += 32768)\n s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));\n return btoa(s);\n};\nvar dataUrl = (text) => \"data:text/javascript;base64,\" + b64(text).replace(/\\//g, \"%2F\");\nvar blobUrl = (text) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\nvar bootSrc = (url) => `var q = []; var h = function (e) { q.push(e) }; self.addEventListener(\"message\", h);\n` + \"import(\" + JSON.stringify(url) + `).then(function () { self.removeEventListener(\"message\", h); for (var i = 0; i < q.length; i++) self.dispatchEvent(new MessageEvent(\"message\", { data: q[i].data, ports: q[i].ports })) },\n` + ` function (e) { postMessage({ type: \"done\", error: \"the frame's Worker code did not load: \" + String(e && e.message || e) }) })`;\nvar SCRIPT_LOADER = 'onmessage = e => { const d = e.data; if (d && typeof d.__wmdScript === \"string\") { onmessage = null; (0, eval)(d.__wmdScript + \"\\\\n//# sourceURL=wmd-worker.js\") } }';\nvar SCRIPT_PREFIX = \"wmd-script:\";\nfunction makeFactory(name) {\n if (name === \"data\") {\n const scripts = new Map;\n const loader = \"data:text/javascript,\" + encodeURIComponent(SCRIPT_LOADER);\n return {\n name,\n url: dataUrl,\n script: (t) => {\n const n = SCRIPT_PREFIX + scripts.size;\n scripts.set(n, t);\n return n;\n },\n make: (u, o) => {\n const t = scripts.get(u);\n if (t === undefined)\n return new Worker(u, { name: o && o.name, type: \"module\" });\n const w = new Worker(loader, { name: o && o.name, type: \"module\" });\n w.postMessage({ __wmdScript: '\"use strict\";' + t });\n return w;\n }\n };\n }\n if (name === \"boot\")\n return { name, url: blobUrl, make: (u, o) => new Worker(blobUrl(bootSrc(u)), { name: o && o.name }) };\n return { name: \"module\", url: blobUrl, make: (u, o) => new Worker(u, { name: o && o.name, type: \"module\" }) };\n}\nfunction moduleToScript(src) {\n const names = [];\n let body = src.replace(/^export\\s+((?:async\\s+)?function\\s*\\*?\\s*([\\w$]+)|(?:class|const|let|var)\\s+([\\w$]+))/gm, (m, rest, fn, other) => (names.push(fn || other), rest));\n const lists = [];\n body = body.replace(/^export\\s*\\{([^}]*)\\}\\s*;?[ \\t]*$/gm, (m, l) => (lists.push(...asObject(l)), \"\"));\n if (lists.includes(null) || /^\\s*(import|export)\\b/m.test(body) || /^await\\b/m.test(body) || !names.length && !lists.length)\n return null;\n body = body.replace(/import\\.meta\\.url/g, '\"about:blank\"');\n return `(() => {\n'use strict';\n${body}\nreturn { ${[...names, ...lists].join(\", \")} }\n})()`;\n}\nvar ACORN_RE = /(from\\s*)(['\"])\\.\\.\\/\\.\\.\\/acorn\\/acorn\\.mjs\\2/g;\nvar SNIPPET_RE = /(from\\s*)(['\"])\\.\\/snippets\\/[^'\"]+\\/inline0\\.js\\2/g;\nvar SNIPPET_IMPORT_RE = /import\\s*(?:\\*\\s*as\\s+(\\w+)|\\{([^}]*)\\})\\s*from\\s*(['\"])\\.\\/snippets\\/[^'\"]+\\/inline0\\.js\\3/g;\nvar SNIPPET_NS = \"__wmdSnippet\";\nvar dec3 = new TextDecoder;\nvar text = (v) => typeof v === \"string\" ? v : dec3.decode(v);\nvar ACORN_EXPORT_RE = /^export\\s*\\{([^}]*)\\}\\s*;?\\s*$/m;\nvar ACORN_IMPORT_RE = /^import\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])\\.\\.\\/\\.\\.\\/acorn\\/acorn\\.mjs\\2\\s*;?[ \\t]*$/m;\nvar asObject = (list) => list.split(\",\").map((x) => x.trim()).filter(Boolean).map((x) => {\n const m = /^([\\w$]+)\\s+as\\s+([\\w$]+)$/.exec(x);\n return m ? `${m[2]}: ${m[1]}` : /^[\\w$]+$/.test(x) ? x : null;\n});\nfunction acornExpr(src) {\n const m = ACORN_EXPORT_RE.exec(src);\n const rest = m && src.replace(ACORN_EXPORT_RE, \"\");\n if (!m || /^(import|export)\\b/m.test(rest))\n return null;\n const names = asObject(m[1]);\n return names.includes(null) ? null : `(() => {\n'use strict';\n${rest}\nreturn { ${names.join(\", \")} }\n})()`;\n}\nfunction snippetExpr(src, acornSrc) {\n const im = ACORN_IMPORT_RE.exec(src);\n const ac = im && acornExpr(acornSrc);\n if (!ac)\n return null;\n const pairs = im[1].split(\",\").map((x) => x.trim()).filter(Boolean).map((x) => {\n const k = /^([\\w$]+)\\s+as\\s+([\\w$]+)$/.exec(x);\n return k ? `${k[1]}: ${k[2]}` : /^[\\w$]+$/.test(x) ? x : null;\n });\n if (!pairs.length || pairs.includes(null))\n return null;\n let body = src.replace(ACORN_IMPORT_RE, `const { ${pairs.join(\", \")} } = __wmdAcorn;`);\n const names = [];\n body = body.replace(/^export\\s+((?:async\\s+)?function\\s*\\*?\\s*(\\w+)|(?:const|let|var|class)\\s+([\\w$]+))/gm, (m, rest, fn, other) => (names.push(fn || other), rest));\n if (/^(import|export)\\b/m.test(body) || !names.length)\n return null;\n return `(() => {\n'use strict';\nconst __wmdAcorn = ${ac};\n${body}\nreturn { ${names.join(\", \")} }\n})()`;\n}\nfunction urlsFor(factory, { glue, snippet, acorn, ownWorker }) {\n const expr = snippetExpr(text(snippet), text(acorn));\n let nested = null;\n if (!expr) {\n const acornU = factory.url(text(acorn));\n nested = factory.url(text(snippet).replace(ACORN_RE, (m, a, q) => a + q + acornU + q));\n }\n let first = true;\n const named = text(glue).replace(SNIPPET_IMPORT_RE, (m, star, braces, q) => {\n const head = first ? expr ? `const ${SNIPPET_NS} = ${expr}; ` : `import * as ${SNIPPET_NS} from ${q}${nested}${q}; ` : \"\";\n first = false;\n return head + (star ? `const ${star} = ${SNIPPET_NS}` : `const {${braces.replace(/\\s+as\\s+/g, \": \")}} = ${SNIPPET_NS}`);\n });\n const script = factory.script && expr ? moduleToScript(named) : null;\n if (script)\n return { glue: SCRIPT_PREFIX + \"glue\", glueScript: script, worker: factory.script(text(ownWorker)) };\n return { glue: factory.url(expr ? named : named.replace(SNIPPET_RE, (m, a, q) => a + q + nested + q)), worker: factory.url(text(ownWorker)) };\n}\n\n// src/edge/sbx/sha256.js\nvar K = new Int32Array([\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n]);\nfunction sha2562(data) {\n const n = data.length;\n const total = n + 9 + 63 >> 6 << 6;\n const tail = new Uint8Array(total - (n - n % 64));\n tail.set(data.subarray(n - n % 64));\n tail[n % 64] = 128;\n const dv = new DataView(tail.buffer);\n dv.setUint32(tail.length - 8, Math.floor(n / 536870912), false);\n dv.setUint32(tail.length - 4, n << 3 >>> 0, false);\n const h = new Int32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);\n const w = new Int32Array(64);\n const block = (b, o) => {\n for (let i = 0;i < 16; i++)\n w[i] = b[o + 4 * i] << 24 | b[o + 4 * i + 1] << 16 | b[o + 4 * i + 2] << 8 | b[o + 4 * i + 3];\n for (let i = 16;i < 64; i++) {\n const a = w[i - 15];\n const c = w[i - 2];\n const s0 = (a >>> 7 | a << 25) ^ (a >>> 18 | a << 14) ^ a >>> 3;\n const s1 = (c >>> 17 | c << 15) ^ (c >>> 19 | c << 13) ^ c >>> 10;\n w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;\n }\n let a = h[0], b1 = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];\n for (let i = 0;i < 64; i++) {\n const t1 = hh + ((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) + K[i] + w[i] | 0;\n const t2 = ((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + (a & b1 ^ a & c ^ b1 & c) | 0;\n hh = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b1;\n b1 = a;\n a = t1 + t2 | 0;\n }\n h[0] = h[0] + a | 0;\n h[1] = h[1] + b1 | 0;\n h[2] = h[2] + c | 0;\n h[3] = h[3] + d | 0;\n h[4] = h[4] + e | 0;\n h[5] = h[5] + f | 0;\n h[6] = h[6] + g | 0;\n h[7] = h[7] + hh | 0;\n };\n const whole = n - n % 64;\n for (let o = 0;o < whole; o += 64)\n block(data, o);\n for (let o = 0;o < tail.length; o += 64)\n block(tail, o);\n const out = new Uint8Array(32);\n const ov = new DataView(out.buffer);\n for (let i = 0;i < 8; i++)\n ov.setInt32(4 * i, h[i], false);\n return out;\n}\nfunction installDigestFallback(g = globalThis) {\n if (g.crypto && g.crypto.subtle)\n return false;\n const digest = async (alg, data) => {\n if (String(alg && alg.name ? alg.name : alg).toUpperCase() !== \"SHA-256\")\n throw new Error(\"only SHA-256 is available here\");\n const u = data instanceof ArrayBuffer || typeof SharedArrayBuffer === \"function\" && data instanceof SharedArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return sha2562(u).buffer;\n };\n const subtle = { digest };\n try {\n Object.defineProperty(g.crypto, \"subtle\", { value: subtle, configurable: true });\n } catch {\n return false;\n }\n return true;\n}\n\n// src/edge/sbx/worker-entry.js\ninstallDigestFallback(globalThis);\nvar real = globalThis.onmessage;\nvar dec4 = new TextDecoder;\nglobalThis.onmessage = (e) => {\n const d = e && e.data;\n if (d && d.x5sbx)\n setup(d.x5sbx);\n return real.call(globalThis, e);\n};\nfunction setup({ strategy, ownWorker, files }) {\n const mk = makeFactory(strategy);\n const urls = urlsFor(mk, { glue: files.glue, snippet: files.snippet, acorn: files.acorn, ownWorker });\n const name = (u) => String(u).replace(/^sbx:/, \"\");\n setDeps({\n fetch: async (u) => {\n const b = files[{ \"wmd_browser_bg.wasm\": \"wasm\", \"wmd_browser.js\": \"glue\", \"edgejs.wasm\": \"edgejs\", \"linux.cjs\": \"linux\", \"HASHES.txt\": \"hashes\", \"python-3.12.wasm\": \"python\", \"linux.py\": \"linuxpy\" }[name(u)]];\n if (!b)\n return { ok: false, status: 404, statusText: \"not handed in\", url: String(u) };\n return { ok: true, status: 200, url: String(u), arrayBuffer: async () => b, text: async () => dec4.decode(b) };\n },\n OwnRuntime: {\n start: (o) => OwnRuntime.start({ ...o, glueUrl: urls.glue, workerUrl: urls.worker, ...urls.glueScript ? { glueScript: urls.glueScript } : {}, create: mk.make, ...strategy === \"data\" && o.poolIdleMs === undefined ? { poolIdleMs: 1500 } : {} }),\n prepare: (...a) => OwnRuntime.prepare(...a)\n }\n });\n}\n"
5
5
  const OWNWORKER = "// src/edge/own/loader.js\nfunction checkInit(m) {\n if (!m || m.type !== \"init\")\n throw new Error(\"not an init message\");\n if (typeof m.glue !== \"string\" || !m.glue)\n throw new Error(\"init: glue URL missing\");\n if (!m.module)\n throw new Error(\"init: compiled module missing\");\n if (m.role !== \"main\" && m.role !== \"thread\")\n throw new Error(`init: role must be main or thread, got ${m.role}`);\n if (m.role === \"thread\" && !m.memory)\n throw new Error(\"init: a thread Worker needs the shared memory\");\n return m;\n}\nvar hasJspi = () => typeof WebAssembly.promising === \"function\" && typeof WebAssembly.Suspending === \"function\";\nfunction makeTurn(now = () => performance.now(), channel = () => new MessageChannel, timer = setTimeout) {\n let last = 0;\n let idle = 0;\n let ch = null;\n return () => {\n const t = now();\n idle = t - last > 50 ? 0 : idle + 1;\n last = t;\n if (idle < 100) {\n ch ||= channel();\n return new Promise((r) => {\n ch.port1.onmessage = () => r();\n ch.port2.postMessage(0);\n });\n }\n return new Promise((r) => timer(r, 2));\n };\n}\nfunction suspendingImports(turn, run) {\n const wrap = (imports) => {\n for (const ns of Object.values(imports || {})) {\n for (const k of Object.keys(ns || {})) {\n if (k.includes(\"wmdTurn\"))\n ns[k] = new WebAssembly.Suspending(turn);\n }\n }\n return imports;\n };\n const inst = WebAssembly.instantiate;\n const Inst = WebAssembly.Instance;\n WebAssembly.instantiate = (src, imports, ...rest) => inst.call(WebAssembly, src, wrap(imports), ...rest);\n WebAssembly.Instance = new Proxy(Inst, { construct: (T, [mod, imports], nt) => Reflect.construct(T, [mod, wrap(imports)], nt) });\n return run().finally(() => {\n WebAssembly.instantiate = inst;\n WebAssembly.Instance = Inst;\n });\n}\nasync function loadRuntime({ glue, glueScript, module, memory, stack, debug = false, importer = (u) => import(u), jspi = hasJspi(), role = \"main\" }) {\n const g = glueScript ? (0, eval)(glueScript + `\n//# sourceURL=wmd-glue.js`) : await importer(glue);\n const init = () => g.default({ module_or_path: module, memory, thread_stack_size: stack });\n const turning = jspi && role === \"thread\";\n const wasm = turning ? await suspendingImports(makeTurn(), init) : await init();\n g.wmd_init();\n g.wmd_set_debug(!!debug);\n if (turning)\n g.wmd_enable_turn();\n return { glue: g, memory: memory || wasm.memory, exports: wasm, turning };\n}\n\n// src/edge/own/serdes-codec.js\nvar LIMIT = 1024 * 1024;\nvar T = { UNDEF: 0, NULL: 1, FALSE: 2, TRUE: 3, NUM: 4, BIGINT: 5, STR: 6, DATE: 7, REGEXP: 8, ARRAY: 9, OBJECT: 10, MAP: 11, SET: 12, ABUF: 13, HOLE: 14, VIEW: 15, ERROR: 16, REF: 17 };\nvar VIEWS = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, DataView];\nvar ERRORS = [\"Error\", \"EvalError\", \"RangeError\", \"ReferenceError\", \"SyntaxError\", \"TypeError\", \"URIError\"];\n\nclass Unsupported extends Error {\n}\nfunction encode(value) {\n const out = [];\n let size = 0;\n const refs = new Map;\n const u8 = (n) => {\n out.push(Uint8Array.of(n));\n size += 1;\n };\n const u32 = (n) => {\n const b = new Uint8Array(4);\n new DataView(b.buffer).setUint32(0, n, true);\n out.push(b);\n size += 4;\n };\n const f64 = (n) => {\n const b = new Uint8Array(8);\n new DataView(b.buffer).setFloat64(0, n, true);\n out.push(b);\n size += 8;\n };\n const bytes = (b) => {\n if ((size += b.length) > LIMIT)\n throw new Unsupported;\n out.push(b);\n };\n const str = (s) => {\n u32(s.length);\n const b = new Uint8Array(s.length * 2);\n const dv = new DataView(b.buffer);\n for (let i = 0;i < s.length; i++)\n dv.setUint16(i * 2, s.charCodeAt(i), true);\n bytes(b);\n };\n const walk = (v) => {\n if (size > LIMIT)\n throw new Unsupported;\n switch (typeof v) {\n case \"undefined\":\n return u8(T.UNDEF);\n case \"boolean\":\n return u8(v ? T.TRUE : T.FALSE);\n case \"number\":\n u8(T.NUM);\n return f64(v);\n case \"bigint\":\n u8(T.BIGINT);\n return str(v.toString());\n case \"string\":\n u8(T.STR);\n return str(v);\n case \"object\":\n break;\n default:\n throw new Unsupported;\n }\n if (v === null)\n return u8(T.NULL);\n if (refs.has(v)) {\n u8(T.REF);\n return u32(refs.get(v));\n }\n const proto = Object.getPrototypeOf(v);\n const remember = () => refs.set(v, refs.size);\n if (v instanceof Date && proto === Date.prototype) {\n remember();\n u8(T.DATE);\n return f64(v.getTime());\n }\n if (v instanceof RegExp && proto === RegExp.prototype) {\n remember();\n u8(T.REGEXP);\n str(v.source);\n return str(v.flags);\n }\n if (v instanceof ArrayBuffer && proto === ArrayBuffer.prototype) {\n remember();\n u8(T.ABUF);\n u32(v.byteLength);\n return bytes(new Uint8Array(v).slice());\n }\n if (ArrayBuffer.isView(v)) {\n const kind = VIEWS.findIndex((C) => v instanceof C);\n if (kind < 0)\n throw new Unsupported;\n remember();\n u8(T.VIEW);\n u8(kind);\n u32(v.byteLength);\n return bytes(new Uint8Array(v.buffer, v.byteOffset, v.byteLength).slice());\n }\n if (v instanceof Error) {\n const name = ERRORS.includes(v.name) && proto === globalThis[v.name].prototype ? v.name : null;\n if (!name)\n throw new Unsupported;\n remember();\n u8(T.ERROR);\n str(name);\n str(String(v.message));\n str(typeof v.stack === \"string\" ? v.stack : \"\");\n if (\"cause\" in v) {\n u8(1);\n return walk(v.cause);\n }\n return u8(0);\n }\n if (Array.isArray(v) && proto === Array.prototype) {\n remember();\n u8(T.ARRAY);\n u32(v.length);\n for (let i = 0;i < v.length; i++) {\n if (i in v)\n walk(v[i]);\n else\n u8(T.HOLE);\n }\n return;\n }\n if (v instanceof Map && proto === Map.prototype) {\n remember();\n u8(T.MAP);\n u32(v.size);\n for (const [k, x] of v) {\n walk(k);\n walk(x);\n }\n return;\n }\n if (v instanceof Set && proto === Set.prototype) {\n remember();\n u8(T.SET);\n u32(v.size);\n for (const x of v)\n walk(x);\n return;\n }\n if (proto === Object.prototype || proto === null) {\n remember();\n u8(T.OBJECT);\n const keys = Object.keys(v);\n u32(keys.length);\n for (const k of keys) {\n str(k);\n walk(v[k]);\n }\n return;\n }\n throw new Unsupported;\n };\n try {\n walk(value);\n } catch (e) {\n if (e instanceof Unsupported)\n return null;\n throw e;\n }\n const all = new Uint8Array(size);\n let at = 0;\n for (const b of out) {\n all.set(b, at);\n at += b.length;\n }\n return all;\n}\nfunction decode(buf) {\n const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n let at = 0;\n const need = (n) => {\n if (n < 0 || at + n > buf.length)\n throw new RangeError(\"serdes codec: unexpected end of buffer\");\n };\n const u8 = () => {\n need(1);\n return buf[at++];\n };\n const u32 = () => {\n need(4);\n const n = dv.getUint32(at, true);\n at += 4;\n return n;\n };\n const f64 = () => {\n need(8);\n const n = dv.getFloat64(at, true);\n at += 8;\n return n;\n };\n const str = () => {\n const n = u32();\n need(n * 2);\n let s = \"\";\n for (let i = 0;i < n; i += 4096) {\n const part = [];\n for (let j = i;j < Math.min(n, i + 4096); j++)\n part.push(dv.getUint16(at + j * 2, true));\n s += String.fromCharCode(...part);\n }\n at += n * 2;\n return s;\n };\n const refs = [];\n const read = () => {\n const t = u8();\n switch (t) {\n case T.UNDEF:\n return;\n case T.NULL:\n return null;\n case T.FALSE:\n return false;\n case T.TRUE:\n return true;\n case T.NUM:\n return f64();\n case T.BIGINT:\n return BigInt(str());\n case T.STR:\n return str();\n case T.REF: {\n const i = u32();\n if (i >= refs.length)\n throw new RangeError(\"serdes codec: bad reference\");\n return refs[i];\n }\n case T.DATE: {\n const d = new Date(f64());\n refs.push(d);\n return d;\n }\n case T.REGEXP: {\n const r = new RegExp(str(), str());\n refs.push(r);\n return r;\n }\n case T.ABUF: {\n const n = u32();\n need(n);\n const ab = buf.slice(at, at + n).buffer;\n at += n;\n refs.push(ab);\n return ab;\n }\n case T.VIEW: {\n const C = VIEWS[u8()];\n const n = u32();\n if (!C)\n throw new RangeError(\"serdes codec: bad view\");\n need(n);\n const ab = buf.slice(at, at + n).buffer;\n at += n;\n const view = C === DataView ? new DataView(ab) : new C(ab);\n refs.push(view);\n return view;\n }\n case T.ERROR: {\n const name = str();\n if (!ERRORS.includes(name))\n throw new RangeError(\"serdes codec: bad error\");\n const e = new globalThis[name](str());\n const stack = str();\n refs.push(e);\n Object.defineProperty(e, \"stack\", { value: stack, writable: true, configurable: true, enumerable: false });\n if (u8())\n Object.defineProperty(e, \"cause\", { value: read(), writable: true, configurable: true, enumerable: false });\n return e;\n }\n case T.ARRAY: {\n const n = u32();\n const a = [];\n refs.push(a);\n a.length = n;\n for (let i = 0;i < n; i++) {\n if (buf[at] === T.HOLE) {\n at++;\n continue;\n }\n a[i] = read();\n }\n return a;\n }\n case T.MAP: {\n const n = u32();\n const m = new Map;\n refs.push(m);\n for (let i = 0;i < n; i++) {\n const k = read();\n m.set(k, read());\n }\n return m;\n }\n case T.SET: {\n const n = u32();\n const s = new Set;\n refs.push(s);\n for (let i = 0;i < n; i++)\n s.add(read());\n return s;\n }\n case T.OBJECT: {\n const n = u32();\n const o = {};\n refs.push(o);\n for (let i = 0;i < n; i++) {\n const k = str();\n Object.defineProperty(o, k, { value: read(), writable: true, configurable: true, enumerable: true });\n }\n return o;\n }\n default:\n throw new RangeError(`serdes codec: unknown tag ${t}`);\n }\n };\n return read();\n}\n\n// src/edge/own/v8-serdes.js\nvar T2 = {\n PAD: 0,\n VERIFY: 63,\n UNDEF: 95,\n NULL: 48,\n TRUE: 84,\n FALSE: 70,\n INT32: 73,\n UINT32: 85,\n DOUBLE: 78,\n BIGINT: 90,\n UTF8: 83,\n ONE_BYTE: 34,\n TWO_BYTE: 99,\n REF: 94,\n OBJECT: 111,\n END_OBJECT: 123,\n DENSE: 65,\n END_DENSE: 36,\n SPARSE: 97,\n END_SPARSE: 64,\n DATE: 68,\n TRUE_OBJ: 121,\n FALSE_OBJ: 120,\n NUM_OBJ: 110,\n BIGINT_OBJ: 122,\n STR_OBJ: 115,\n REGEXP: 82,\n MAP: 59,\n END_MAP: 58,\n SET: 39,\n END_SET: 44,\n ABUF: 66,\n RESIZABLE_ABUF: 126,\n TRANSFERRED_ABUF: 116,\n SHARED_ABUF: 117,\n VIEW: 86,\n HOST: 92,\n ERROR: 114,\n HOLE: 45\n};\nvar ERR = { EVAL: 69, RANGE: 82, REFERENCE: 70, SYNTAX: 83, TYPE: 84, URI: 85, MESSAGE: 109, CAUSE: 99, STACK: 115, END: 46 };\nvar ERROR_NAMES = { EvalError: ERR.EVAL, RangeError: ERR.RANGE, ReferenceError: ERR.REFERENCE, SyntaxError: ERR.SYNTAX, TypeError: ERR.TYPE, URIError: ERR.URI };\nvar VIEW_TAGS = [\n [\"Int8Array\", 98],\n [\"Uint8Array\", 66],\n [\"Uint8ClampedArray\", 67],\n [\"Int16Array\", 119],\n [\"Uint16Array\", 87],\n [\"Int32Array\", 100],\n [\"Uint32Array\", 68],\n [\"Float16Array\", 104],\n [\"Float32Array\", 102],\n [\"Float64Array\", 70],\n [\"BigInt64Array\", 113],\n [\"BigUint64Array\", 81],\n [\"DataView\", 63]\n];\nvar VERSION = 15;\nvar FLAG_BITS = [[\"g\", 1], [\"i\", 2], [\"m\", 4], [\"y\", 8], [\"u\", 16], [\"s\", 32], [\"l\", 64], [\"d\", 128], [\"v\", 256]];\nvar MAX_INDEX = 4294967294;\nvar VIEW_LENGTH_TRACKING = 1;\nvar VIEW_BACKED_BY_RAB = 2;\nvar VERSION_ERROR = \"Unable to deserialize cloned data due to invalid or unsupported version.\";\nvar MIN_VERSION = 13;\nvar viewByteLength = (v) => {\n try {\n if (typeof v.at === \"function\")\n v.at(0);\n return v.byteLength;\n } catch {\n return -1;\n }\n};\nvar tracksLength = (v, ab) => {\n const before = viewByteLength(v);\n if (before < 0)\n return false;\n const size = ab.byteLength;\n const per = v.BYTES_PER_ELEMENT || 1;\n try {\n if (size + per <= ab.maxByteLength) {\n ab.resize(size + per);\n const grew = viewByteLength(v) !== before;\n ab.resize(size);\n return grew;\n }\n if (size - per >= v.byteOffset) {\n const kept = new Uint8Array(ab).slice(size - per);\n ab.resize(size - per);\n const after = viewByteLength(v);\n ab.resize(size);\n new Uint8Array(ab).set(kept, size - per);\n return before >= per && after === before - per;\n }\n } catch {}\n return false;\n};\nvar own = (o, k) => Object.getOwnPropertyDescriptor(o, k);\nvar tagOf = (o) => Object.prototype.toString.call(o);\nvar brand = (f) => (o) => {\n try {\n f(o);\n return true;\n } catch {\n return false;\n }\n};\nvar isDate = brand((o) => Date.prototype.getTime.call(o));\nvar isMap = brand((o) => own(Map.prototype, \"size\").get.call(o));\nvar isSet = brand((o) => own(Set.prototype, \"size\").get.call(o));\nvar isArrayBuffer = brand((o) => own(ArrayBuffer.prototype, \"byteLength\").get.call(o));\nvar isSharedArrayBuffer = typeof SharedArrayBuffer === \"function\" ? brand((o) => own(SharedArrayBuffer.prototype, \"byteLength\").get.call(o)) : () => false;\nvar isRegExp = brand((o) => {\n if (o === RegExp.prototype)\n throw 0;\n own(RegExp.prototype, \"source\").get.call(o);\n});\nvar isBoolObj = brand((o) => Boolean.prototype.valueOf.call(o));\nvar isNumObj = brand((o) => Number.prototype.valueOf.call(o));\nvar isStrObj = brand((o) => String.prototype.valueOf.call(o));\nvar isBigObj = brand((o) => BigInt.prototype.valueOf.call(o));\nvar NOT_CLONABLE = new Set([\"[object Promise]\", \"[object WeakMap]\", \"[object WeakSet]\", \"[object WeakRef]\", \"[object FinalizationRegistry]\", \"[object Generator]\", \"[object AsyncGenerator]\", \"[object Iterator]\"]);\nvar isIndexKey = (k) => {\n if (k.length === 0 || k.length > 10)\n return false;\n const c = k.charCodeAt(0);\n if (c < 48 || c > 57 || c === 48 && k.length > 1)\n return false;\n for (let i = 1;i < k.length; i++) {\n const d = k.charCodeAt(i);\n if (d < 48 || d > 57)\n return false;\n }\n return Number(k) <= MAX_INDEX;\n};\nvar isInt32 = (n) => n === (n | 0) && !(n === 0 && 1 / n < 0);\n\nclass Writer {\n constructor() {\n this.buf = new Uint8Array(256);\n this.len = 0;\n this.dv = new DataView(this.buf.buffer);\n }\n need(n) {\n if (this.len + n <= this.buf.length)\n return;\n let cap = this.buf.length * 2;\n while (cap < this.len + n)\n cap *= 2;\n const b = new Uint8Array(cap);\n b.set(this.buf.subarray(0, this.len));\n this.buf = b;\n this.dv = new DataView(b.buffer);\n }\n byte(x) {\n this.need(1);\n this.buf[this.len++] = x;\n }\n varint(n) {\n this.need(10);\n if (n <= 4294967295) {\n n >>>= 0;\n do {\n let b = n & 127;\n n >>>= 7;\n if (n)\n b |= 128;\n this.buf[this.len++] = b;\n } while (n);\n return;\n }\n let big = BigInt(n);\n do {\n let b = Number(big & 0x7fn);\n big >>= 7n;\n if (big)\n b |= 128;\n this.buf[this.len++] = b;\n } while (big);\n }\n varintBig(big) {\n this.need(10);\n do {\n let b = Number(big & 0x7fn);\n big >>= 7n;\n if (big)\n b |= 128;\n this.buf[this.len++] = b;\n } while (big);\n }\n f64(n) {\n this.need(8);\n this.dv.setFloat64(this.len, n, true);\n this.len += 8;\n }\n bytes(u8) {\n this.need(u8.length);\n this.buf.set(u8, this.len);\n this.len += u8.length;\n }\n out() {\n return this.buf.slice(0, this.len);\n }\n}\nvar varintSize = (n) => {\n let c = 1;\n while (n >= 128) {\n n = Math.floor(n / 128);\n c++;\n }\n return c;\n};\nfunction makeSerdesBinding({ bufferOf = null } = {}) {\n\n class Serializer {\n constructor() {\n this._w = new Writer;\n this._ids = new Map;\n this._next = 0;\n this._hostViews = false;\n this._transfer = new Map;\n }\n writeHeader() {\n this._w.byte(255);\n this._w.varint(VERSION);\n }\n writeValue(value) {\n this._write(value);\n return true;\n }\n releaseBuffer() {\n const out = this._w.out();\n this._w = new Writer;\n return bufferOf ? bufferOf(out) : out;\n }\n transferArrayBuffer(id, ab) {\n this._transfer.set(ab, Number(id) >>> 0);\n }\n writeUint32(n) {\n this._w.varint(Number(n) >>> 0);\n }\n writeUint64(hi, lo) {\n this._w.varintBig(BigInt(Number(hi) >>> 0) << 32n | BigInt(Number(lo) >>> 0));\n }\n writeDouble(n) {\n this._w.f64(Number(n));\n }\n writeRawBytes(src) {\n this._w.bytes(rawBytes(src));\n }\n _setTreatArrayBufferViewsAsHostObjects(on) {\n this._hostViews = Boolean(on);\n }\n _fail(text) {\n const E = this._getDataCloneError || Error;\n throw new E(text);\n }\n _describe(v) {\n try {\n if (typeof v === \"function\" || typeof v === \"symbol\")\n return String(v);\n const c = v && v.constructor && v.constructor.name;\n return `#<${c || \"Object\"}>`;\n } catch {\n return \"#<Object>\";\n }\n }\n _string(s) {\n const w = this._w;\n const n = s.length;\n let one = true;\n for (let i = 0;i < n; i++) {\n if (s.charCodeAt(i) > 255) {\n one = false;\n break;\n }\n }\n if (one) {\n w.byte(T2.ONE_BYTE);\n w.varint(n);\n w.need(n);\n for (let i = 0;i < n; i++)\n w.buf[w.len++] = s.charCodeAt(i);\n return;\n }\n const bytes = n * 2;\n if (w.len + 1 + varintSize(bytes) & 1)\n w.byte(T2.PAD);\n w.byte(T2.TWO_BYTE);\n w.varint(bytes);\n w.need(bytes);\n for (let i = 0;i < n; i++) {\n const c = s.charCodeAt(i);\n w.buf[w.len++] = c & 255;\n w.buf[w.len++] = c >> 8;\n }\n }\n _bigintBody(v) {\n const w = this._w;\n const neg = v < 0n;\n let mag = neg ? -v : v;\n const digits = [];\n while (mag > 0n) {\n digits.push(mag & 0xffffffffffffffffn);\n mag >>= 64n;\n }\n w.varint(digits.length * 8 * 2 + (neg ? 1 : 0));\n for (const d of digits) {\n w.need(8);\n w.dv.setBigUint64(w.len, d, true);\n w.len += 8;\n }\n }\n _number(n) {\n const w = this._w;\n if (isInt32(n)) {\n w.byte(T2.INT32);\n w.varint((n << 1 ^ n >> 31) >>> 0);\n } else {\n w.byte(T2.DOUBLE);\n w.f64(n);\n }\n }\n _key(k) {\n if (isIndexKey(k))\n this._number(Number(k));\n else\n this._string(k);\n }\n _props(o, keys) {\n let n = 0;\n for (const k of keys) {\n if (!Object.prototype.propertyIsEnumerable.call(o, k))\n continue;\n this._key(k);\n this._write(o[k]);\n n++;\n }\n return n;\n }\n _write(v) {\n const w = this._w;\n switch (typeof v) {\n case \"undefined\":\n return w.byte(T2.UNDEF);\n case \"boolean\":\n return w.byte(v ? T2.TRUE : T2.FALSE);\n case \"number\":\n return this._number(v);\n case \"bigint\":\n w.byte(T2.BIGINT);\n return this._bigintBody(v);\n case \"string\":\n return this._string(v);\n case \"object\":\n if (v === null)\n return w.byte(T2.NULL);\n return this._receiver(v);\n default:\n return this._fail(`${this._describe(v)} could not be cloned.`);\n }\n }\n _receiver(o) {\n const w = this._w;\n const seen = this._ids.get(o);\n if (seen !== undefined) {\n w.byte(T2.REF);\n return w.varint(seen);\n }\n if (!this._hostViews && !Array.isArray(o) && ArrayBuffer.isView(o))\n return this._view(o);\n this._ids.set(o, this._next++);\n if (Array.isArray(o))\n return this._array(o);\n if (isDate(o)) {\n w.byte(T2.DATE);\n return w.f64(Date.prototype.getTime.call(o));\n }\n if (isBoolObj(o))\n return w.byte(Boolean.prototype.valueOf.call(o) ? T2.TRUE_OBJ : T2.FALSE_OBJ);\n if (isNumObj(o)) {\n w.byte(T2.NUM_OBJ);\n return w.f64(Number.prototype.valueOf.call(o));\n }\n if (isStrObj(o)) {\n w.byte(T2.STR_OBJ);\n return this._string(String.prototype.valueOf.call(o));\n }\n if (isBigObj(o)) {\n w.byte(T2.BIGINT_OBJ);\n return this._bigintBody(BigInt.prototype.valueOf.call(o));\n }\n if (isRegExp(o)) {\n w.byte(T2.REGEXP);\n this._string(own(RegExp.prototype, \"source\").get.call(o));\n const flags = own(RegExp.prototype, \"flags\").get.call(o);\n let bits = 0;\n for (const [c, b] of FLAG_BITS)\n if (flags.includes(c))\n bits |= b;\n return w.varint(bits);\n }\n if (isMap(o)) {\n w.byte(T2.MAP);\n const entries = Array.from(Map.prototype.entries.call(o));\n for (const [k, x] of entries) {\n this._write(k);\n this._write(x);\n }\n w.byte(T2.END_MAP);\n return w.varint(entries.length * 2);\n }\n if (isSet(o)) {\n w.byte(T2.SET);\n const items = Array.from(Set.prototype.values.call(o));\n for (const x of items)\n this._write(x);\n w.byte(T2.END_SET);\n return w.varint(items.length);\n }\n if (isArrayBuffer(o))\n return this._arrayBuffer(o);\n if (isSharedArrayBuffer(o)) {\n if (typeof this._getSharedArrayBufferId !== \"function\")\n return this._fail(`${this._describe(o)} could not be cloned.`);\n w.byte(T2.SHARED_ABUF);\n return w.varint(Number(this._getSharedArrayBufferId(o)) >>> 0);\n }\n if (ArrayBuffer.isView(o))\n return this._view(o);\n if (typeof o === \"function\")\n return this._fail(`${String(o)} could not be cloned.`);\n const tag = tagOf(o);\n if (tag === \"[object Error]\")\n return this._error(o);\n if (NOT_CLONABLE.has(tag))\n return this._fail(`${this._describe(o)} could not be cloned.`);\n w.byte(T2.OBJECT);\n const n = this._props(o, Object.keys(o));\n w.byte(T2.END_OBJECT);\n return w.varint(n);\n }\n _array(a) {\n const w = this._w;\n const len = a.length;\n let packed = true;\n for (let i = 0;i < len; i++) {\n if (!(i in a)) {\n packed = false;\n break;\n }\n }\n if (!packed) {\n w.byte(T2.SPARSE);\n w.varint(len);\n const n = this._props(a, Object.keys(a));\n w.byte(T2.END_SPARSE);\n w.varint(n);\n return w.varint(len);\n }\n w.byte(T2.DENSE);\n w.varint(len);\n let doubles = len > 0;\n let fractional = false;\n for (let i = 0;i < len && doubles; i++) {\n const x = a[i];\n if (typeof x !== \"number\")\n doubles = false;\n else if (!isInt32(x))\n fractional = true;\n }\n doubles = doubles && fractional;\n for (let i = 0;i < len; i++) {\n if (doubles) {\n w.byte(T2.DOUBLE);\n w.f64(a[i]);\n } else\n this._write(a[i]);\n }\n const keys = Object.keys(a);\n const named = keys.length > len ? keys.slice(len) : [];\n const n = this._props(a, named);\n w.byte(T2.END_DENSE);\n w.varint(n);\n return w.varint(len);\n }\n _arrayBuffer(ab) {\n const w = this._w;\n const moved = this._transfer.get(ab);\n if (moved !== undefined) {\n w.byte(T2.TRANSFERRED_ABUF);\n return w.varint(moved);\n }\n const bytes = new Uint8Array(ab);\n if (ab.resizable) {\n w.byte(T2.RESIZABLE_ABUF);\n w.varint(ab.byteLength);\n w.varint(ab.maxByteLength);\n } else {\n w.byte(T2.ABUF);\n w.varint(ab.byteLength);\n }\n return w.bytes(bytes);\n }\n _view(v) {\n const w = this._w;\n if (this._hostViews) {\n if (typeof this._writeHostObject !== \"function\")\n return this._fail(`${this._describe(v)} could not be cloned.`);\n w.byte(T2.HOST);\n return this._writeHostObject(v);\n }\n const kind = VIEW_TAGS.findIndex(([name]) => typeof globalThis[name] === \"function\" && v instanceof globalThis[name]);\n const k = kind >= 0 ? kind : VIEW_TAGS.findIndex(([name]) => name !== \"DataView\" && tagOf(v) === `[object ${name}]`);\n const idx = k >= 0 ? k : tagOf(v) === \"[object DataView]\" ? VIEW_TAGS.length - 1 : -1;\n if (idx < 0)\n return this._fail(`${this._describe(v)} could not be cloned.`);\n let flags = 0;\n let length = v.byteLength;\n if (v.buffer.resizable === true) {\n flags = VIEW_BACKED_BY_RAB;\n if (tracksLength(v, v.buffer)) {\n flags |= VIEW_LENGTH_TRACKING;\n length = 0;\n }\n }\n if (!this._ids.has(v.buffer)) {\n this._ids.set(v.buffer, this._next++);\n this._arrayBuffer(v.buffer);\n } else {\n w.byte(T2.REF);\n w.varint(this._ids.get(v.buffer));\n }\n this._ids.set(v, this._next++);\n w.byte(T2.VIEW);\n w.byte(VIEW_TAGS[idx][1]);\n w.varint(v.byteOffset);\n w.varint(length);\n return w.varint(flags);\n }\n _error(e) {\n const w = this._w;\n w.byte(T2.ERROR);\n let name = \"\";\n try {\n name = String(e.name);\n } catch {\n name = \"\";\n }\n if (Object.hasOwn(ERROR_NAMES, name))\n w.byte(ERROR_NAMES[name]);\n const m = own(e, \"message\");\n if (m && \"value\" in m) {\n w.byte(ERR.MESSAGE);\n this._string(String(m.value));\n }\n let stack;\n try {\n stack = e.stack;\n } catch {\n stack = undefined;\n }\n if (typeof stack === \"string\") {\n w.byte(ERR.STACK);\n this._string(stack);\n }\n const c = own(e, \"cause\");\n if (c && \"value\" in c) {\n w.byte(ERR.CAUSE);\n this._write(c.value);\n }\n return w.byte(ERR.END);\n }\n }\n\n class Deserializer {\n constructor(value) {\n this.buffer = value;\n this.bytes = rawBytes(value);\n this.offset = 0;\n this._version = 0;\n this._objects = [];\n this._transfer = new Map;\n this._dv = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);\n }\n readHeader() {\n let version = 0;\n if (this.bytes[this.offset] === 255) {\n this.offset++;\n try {\n version = this._varint32();\n } catch (e) {\n throw e && e.__serdes ? new Error(VERSION_ERROR) : e;\n }\n this._version = version;\n if (version > VERSION)\n throw new Error(VERSION_ERROR);\n }\n if (version < MIN_VERSION)\n throw new Error(VERSION_ERROR);\n return true;\n }\n readValue() {\n try {\n return this._read();\n } catch (e) {\n if (e && e.__serdes)\n throw new Error(\"Unable to deserialize cloned data.\");\n throw e;\n }\n }\n getWireFormatVersion() {\n return this._version;\n }\n transferArrayBuffer(id, ab) {\n this._transfer.set(Number(id) >>> 0, ab);\n }\n _called(text, f) {\n try {\n return f();\n } catch (e) {\n throw e && e.__serdes ? new Error(text) : e;\n }\n }\n readUint32() {\n return this._called(\"ReadUint32() failed\", () => this._varint32());\n }\n readUint64() {\n return this._called(\"ReadUint64() failed\", () => {\n const big = this._varintBig();\n return [Number(big >> 32n) >>> 0, Number(big & 0xffffffffn)];\n });\n }\n readDouble() {\n return this._called(\"ReadDouble() failed\", () => {\n this._need(8);\n const n = this._dv.getFloat64(this.offset, true);\n this.offset += 8;\n return n;\n });\n }\n _readRawBytes(length) {\n const n = Number(length) >>> 0;\n return this._called(\"ReadRawBytes() failed\", () => {\n this._need(n);\n const at = this.offset;\n this.offset += n;\n return at;\n });\n }\n _bad() {\n const e = new Error(\"bad\");\n e.__serdes = true;\n return e;\n }\n _need(n) {\n if (n < 0 || this.offset + n > this.bytes.length)\n throw this._bad();\n }\n _byte() {\n this._need(1);\n return this.bytes[this.offset++];\n }\n _varint32() {\n let n = 0;\n for (let i = 0;; i++) {\n this._need(1);\n const b = this.bytes[this.offset];\n if (i === 5)\n return n >>> 0;\n this.offset++;\n n |= (b & 127) << 7 * i;\n if (!(b & 128))\n return n >>> 0;\n }\n }\n _varint() {\n let n = 0;\n let scale = 1;\n for (let i = 0;; i++) {\n const b = this._byte();\n n += (b & 127) * scale;\n if (!(b & 128))\n return n;\n scale *= 128;\n if (i > 8)\n throw this._bad();\n }\n }\n _varintBig() {\n let n = 0n;\n let shift = 0n;\n for (;; ) {\n const b = this._byte();\n n |= BigInt(b & 127) << shift;\n if (!(b & 128))\n return n;\n shift += 7n;\n if (shift > 70n)\n throw this._bad();\n }\n }\n _peek() {\n return this.offset < this.bytes.length ? this.bytes[this.offset] : -1;\n }\n _skipPadding() {\n while (this._peek() === T2.PAD)\n this.offset++;\n }\n _stringBody(tag) {\n if (tag === T2.ONE_BYTE) {\n const n = this._varint();\n this._need(n);\n let s = \"\";\n for (let i = 0;i < n; i += 8192)\n s += String.fromCharCode.apply(null, this.bytes.subarray(this.offset + i, this.offset + Math.min(n, i + 8192)));\n this.offset += n;\n return s;\n }\n if (tag === T2.TWO_BYTE) {\n const n = this._varint();\n if (n & 1)\n throw this._bad();\n this._need(n);\n let s = \"\";\n const units = n / 2;\n for (let i = 0;i < units; i += 4096) {\n const part = [];\n for (let j = i;j < Math.min(units, i + 4096); j++)\n part.push(this.bytes[this.offset + j * 2] | this.bytes[this.offset + j * 2 + 1] << 8);\n s += String.fromCharCode.apply(null, part);\n }\n this.offset += n;\n return s;\n }\n if (tag === T2.UTF8) {\n const n = this._varint();\n this._need(n);\n const s = new TextDecoder().decode(this.bytes.subarray(this.offset, this.offset + n));\n this.offset += n;\n return s;\n }\n throw this._bad();\n }\n _readString() {\n this._skipPadding();\n return this._stringBody(this._byte());\n }\n _bigintBody() {\n const bits = this._varint();\n const neg = bits & 1;\n const n = Math.floor(bits / 2);\n if (neg && n === 0)\n throw this._bad();\n this._need(n);\n const tail = n % 8;\n let v = 0n;\n for (let i = n - 1;i >= n - tail; i--)\n v = v << 8n | BigInt(this.bytes[this.offset + i]);\n for (let i = (n - tail) / 8 - 1;i >= 0; i--)\n v = v << 64n | this._dv.getBigUint64(this.offset + i * 8, true);\n this.offset += n;\n return neg ? -v : v;\n }\n _add(o) {\n this._objects.push(o);\n return o;\n }\n _setKey(o, k, v) {\n if (Object.hasOwn(o, k))\n throw this._bad();\n if (k === \"__proto__\")\n Object.defineProperty(o, k, { value: v, writable: true, enumerable: true, configurable: true });\n else\n o[k] = v;\n }\n _props(o, endTag) {\n let n = 0;\n for (;; ) {\n this._skipPadding();\n if (this._peek() === endTag) {\n this.offset++;\n return n;\n }\n const k = this._read();\n if (typeof k !== \"string\" && typeof k !== \"number\")\n throw this._bad();\n this._setKey(o, k, this._read());\n n++;\n }\n }\n _read() {\n this._skipPadding();\n const t = this._byte();\n switch (t) {\n case T2.VERIFY:\n this._varint32();\n return this._read();\n case T2.UNDEF:\n return;\n case T2.NULL:\n return null;\n case T2.TRUE:\n return true;\n case T2.FALSE:\n return false;\n case T2.INT32: {\n const z = this._varint();\n return z >>> 1 ^ -(z & 1);\n }\n case T2.UINT32:\n return this._varint();\n case T2.DOUBLE: {\n this._need(8);\n const n = this._dv.getFloat64(this.offset, true);\n this.offset += 8;\n return n;\n }\n case T2.BIGINT:\n return this._bigintBody();\n case T2.ONE_BYTE:\n case T2.TWO_BYTE:\n case T2.UTF8:\n return this._stringBody(t);\n case T2.REF: {\n const id = this._varint();\n if (id >= this._objects.length)\n throw this._bad();\n const o = this._objects[id];\n return o instanceof ArrayBuffer ? this._maybeView(o) : o;\n }\n case T2.OBJECT: {\n const o = this._add({});\n const n = this._props(o, T2.END_OBJECT);\n if (this._varint() !== n)\n throw this._bad();\n return o;\n }\n case T2.DENSE: {\n const len = this._varint();\n if (len > this.bytes.length - this.offset)\n throw this._bad();\n const a = this._add(new Array(len));\n for (let i = 0;i < len; i++) {\n if (this._peek() === T2.HOLE) {\n this.offset++;\n continue;\n }\n a[i] = this._read();\n }\n const n = this._props(a, T2.END_DENSE);\n if (this._varint() !== n)\n throw this._bad();\n if (this._varint() !== len)\n throw this._bad();\n return a;\n }\n case T2.SPARSE: {\n const len = this._varint();\n const a = this._add([]);\n a.length = len;\n const n = this._props(a, T2.END_SPARSE);\n if (this._varint() !== n)\n throw this._bad();\n if (this._varint() !== len)\n throw this._bad();\n return a;\n }\n case T2.DATE: {\n this._need(8);\n const d = this._add(new Date(this._dv.getFloat64(this.offset, true)));\n this.offset += 8;\n return d;\n }\n case T2.TRUE_OBJ:\n return this._add(Object(true));\n case T2.FALSE_OBJ:\n return this._add(Object(false));\n case T2.NUM_OBJ: {\n this._need(8);\n const n = this._add(Object(this._dv.getFloat64(this.offset, true)));\n this.offset += 8;\n return n;\n }\n case T2.BIGINT_OBJ:\n return this._add(Object(this._bigintBody()));\n case T2.STR_OBJ:\n return this._add(Object(this._readString()));\n case T2.REGEXP: {\n const source = this._readString();\n const bits = this._varint32();\n if (bits & ~447 || bits & 16 && bits & 256)\n throw this._bad();\n let flags = \"\";\n for (const [c, b] of FLAG_BITS)\n if (bits & b)\n flags += c;\n return this._add(new RegExp(source, flags));\n }\n case T2.MAP: {\n const m = this._add(new Map);\n let n = 0;\n for (;; ) {\n this._skipPadding();\n if (this._peek() === T2.END_MAP) {\n this.offset++;\n break;\n }\n const k = this._read();\n m.set(k, this._read());\n n += 2;\n }\n if (this._varint() !== n)\n throw this._bad();\n return m;\n }\n case T2.SET: {\n const s = this._add(new Set);\n let n = 0;\n for (;; ) {\n this._skipPadding();\n if (this._peek() === T2.END_SET) {\n this.offset++;\n break;\n }\n s.add(this._read());\n n++;\n }\n if (this._varint() !== n)\n throw this._bad();\n return s;\n }\n case T2.ABUF:\n case T2.RESIZABLE_ABUF: {\n const len = this._varint();\n const max = t === T2.RESIZABLE_ABUF ? this._varint() : len;\n this._need(len);\n const ab = t === T2.RESIZABLE_ABUF ? new ArrayBuffer(len, { maxByteLength: max }) : new ArrayBuffer(len);\n new Uint8Array(ab).set(this.bytes.subarray(this.offset, this.offset + len));\n this.offset += len;\n this._add(ab);\n return this._maybeView(ab);\n }\n case T2.TRANSFERRED_ABUF: {\n const ab = this._transfer.get(this._varint());\n if (!ab)\n throw this._bad();\n this._add(ab);\n return this._maybeView(ab);\n }\n case T2.HOST: {\n if (typeof this._readHostObject !== \"function\")\n throw this._bad();\n const at = this._objects.length;\n this._objects.push(undefined);\n const o = this._readHostObject();\n this._objects[at] = o;\n return o;\n }\n case T2.ERROR:\n return this._readError();\n default:\n throw this._bad();\n }\n }\n _maybeView(ab) {\n if (this._peek() !== T2.VIEW)\n return ab;\n this.offset++;\n const sub = this._byte();\n const k = VIEW_TAGS.findIndex((x) => x[1] === sub);\n if (k < 0)\n throw this._bad();\n const offset = this._varint();\n const length = this._varint();\n const flags = this._version >= 14 ? this._varint() >>> 0 : 0;\n const tracking = (flags & VIEW_LENGTH_TRACKING) !== 0;\n const rab = (flags & VIEW_BACKED_BY_RAB) !== 0;\n if ((tracking || rab) && ab.resizable !== true)\n throw this._bad();\n if (ab.resizable === true && !rab)\n throw this._bad();\n const C = globalThis[VIEW_TAGS[k][0]];\n if (typeof C !== \"function\")\n throw this._bad();\n const per = C === DataView ? 1 : C.BYTES_PER_ELEMENT || 1;\n if (offset % per || length % per)\n throw this._bad();\n let v;\n try {\n if (C === DataView)\n v = tracking ? new DataView(ab, offset) : new DataView(ab, offset, length);\n else\n v = tracking ? new C(ab, offset) : new C(ab, offset, length / (C.BYTES_PER_ELEMENT || 1));\n } catch {\n throw this._bad();\n }\n return this._add(v);\n }\n _readError() {\n const at = this._objects.length;\n this._objects.push(undefined);\n let Ctor = Error;\n let message;\n let stack;\n let hasCause = false;\n let cause;\n for (;; ) {\n const t = this._byte();\n if (t === ERR.END)\n break;\n if (t === ERR.EVAL)\n Ctor = EvalError;\n else if (t === ERR.RANGE)\n Ctor = RangeError;\n else if (t === ERR.REFERENCE)\n Ctor = ReferenceError;\n else if (t === ERR.SYNTAX)\n Ctor = SyntaxError;\n else if (t === ERR.TYPE)\n Ctor = TypeError;\n else if (t === ERR.URI)\n Ctor = URIError;\n else if (t === ERR.MESSAGE)\n message = this._readString();\n else if (t === ERR.STACK)\n stack = this._readString();\n else if (t === ERR.CAUSE) {\n hasCause = true;\n cause = this._read();\n } else\n throw this._bad();\n }\n const e = message === undefined ? new Ctor : new Ctor(message);\n this._objects[at] = e;\n if (hasCause)\n Object.defineProperty(e, \"cause\", { value: cause, writable: true, enumerable: false, configurable: true });\n if (stack !== undefined)\n Object.defineProperty(e, \"stack\", { value: stack, writable: true, enumerable: false, configurable: true });\n return e;\n }\n }\n return { Serializer, Deserializer };\n}\nfunction rawBytes(value) {\n if (value instanceof ArrayBuffer || typeof SharedArrayBuffer === \"function\" && value instanceof SharedArrayBuffer)\n return new Uint8Array(value);\n if (ArrayBuffer.isView(value))\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n throw new TypeError(\"buffer must be an ArrayBuffer or an ArrayBuffer view\");\n}\n\n// src/edge/own/payload-size.js\nvar BIG_SHARE = 1 << 20;\nfunction payloadBytes(v, depth = 0, seen = new Set) {\n if (!v || typeof v !== \"object\" || depth > 6 || seen.has(v))\n return 0;\n if (ArrayBuffer.isView(v))\n return v.byteLength;\n if (v instanceof ArrayBuffer || typeof SharedArrayBuffer !== \"undefined\" && v instanceof SharedArrayBuffer)\n return v.byteLength;\n seen.add(v);\n let n = 0;\n for (const k of Object.keys(v))\n n += payloadBytes(v[k], depth + 1, seen);\n return n;\n}\n\n// src/edge/own/capi.js\nvar GONE_LIMIT = 4096;\nvar key = (registry, handle) => `${registry}:${handle}`;\nfunction installCapi(g, { channel, scope, BroadcastChannel: BC = g.BroadcastChannel, relay = null, log = null }) {\n if (!Number.isInteger(scope) || scope < 0 || scope > 4095)\n throw new Error(`capi: scope ${scope} is not below 4096`);\n const table = new Map;\n const waiting = new Map;\n const gone = new Map;\n const markGone = (k, who) => {\n gone.delete(k);\n gone.set(k, who);\n if (gone.size > GONE_LIMIT)\n for (const old of gone.keys()) {\n gone.delete(old);\n if (gone.size <= GONE_LIMIT)\n break;\n }\n };\n const mine = new Map;\n const bc = !relay && channel && BC ? new BC(channel) : null;\n const open = !!(bc || relay);\n const send = (msg) => relay ? relay({ ...msg, from: scope }) : bc.postMessage(msg);\n const put = (k, envelope) => {\n table.set(k, envelope);\n const ws = waiting.get(k);\n if (ws) {\n waiting.delete(k);\n for (const w of ws)\n w.resolve(undefined);\n }\n };\n const receive = (d) => {\n if (!d || d.from === scope)\n return;\n if (log)\n log(`got ${d.t} ${d.handle}`);\n if (d.t === \"share\") {\n if (!gone.has(key(d.registry, d.handle)))\n put(key(d.registry, d.handle), d.envelope);\n else if (log)\n log(`late copy of ${d.handle} dropped (deleted ${gone.get(key(d.registry, d.handle))})`);\n } else if (d.t === \"delete\") {\n table.delete(key(d.registry, d.handle));\n mine.delete(key(d.registry, d.handle));\n markGone(key(d.registry, d.handle), \"from \" + d.from);\n } else if (d.t === \"hello\") {\n if (log)\n log(`hello: sending again ${[...mine.values()].map((m) => m.handle).join(\",\") || \"nothing\"}`);\n for (const [, m] of mine)\n if (payloadBytes(m.envelope) < BIG_SHARE)\n send({ t: \"share\", registry: m.registry, handle: m.handle, envelope: m.envelope });\n }\n };\n if (bc) {\n bc.onmessage = (e) => receive(e.data);\n bc.onmessageerror = () => {\n if (log)\n log(\"a message from another Worker could not be read here (messageerror)\");\n };\n }\n if (open)\n send({ t: \"hello\" });\n g.__wasmerCapiShare = (registry, handle, envelope) => {\n if (log)\n log(`share ${handle} ${typeof envelope?.value} ${String(Object.prototype.toString.call(envelope?.value))}`);\n try {\n if (open)\n send({ t: \"share\", registry, handle, envelope });\n } catch (e) {\n if (log) {\n let what = \"\";\n try {\n const v = envelope && envelope.value;\n what = v && typeof v === \"object\" ? Object.keys(v).map((k) => `${k}:${typeof v[k]}`).join(\",\") : typeof v;\n } catch (e2) {\n what = \"unreadable \" + String(e2);\n }\n log(`share ${handle} could not be copied: ${String(e && e.name || \"\")} ${String(e && e.message || e).slice(0, 200)} (${what})`);\n }\n throw e;\n }\n mine.set(key(registry, handle), { registry, handle, envelope });\n put(key(registry, handle), envelope);\n };\n g.__wasmerCapiObtain = (registry, handle) => {\n if (log)\n log(`obtain ${handle} ${table.has(key(registry, handle))}`);\n return table.get(key(registry, handle));\n };\n g.__wasmerCapiWait = (registry, handle) => {\n const k = key(registry, handle);\n if (log)\n log(`wait ${registry}:${handle} ${table.has(k)}`);\n if (table.has(k))\n return Promise.resolve(undefined);\n if (open)\n send({ t: \"want\", registry, handle });\n return new Promise((resolve, reject) => {\n const list = waiting.get(k) || [];\n list.push({ resolve, reject });\n waiting.set(k, list);\n });\n };\n g.__wasmerCapiDelete = (registry, handle) => {\n if (log)\n log(`delete ${handle}`);\n table.delete(key(registry, handle));\n mine.delete(key(registry, handle));\n markGone(key(registry, handle), \"here\");\n if (open)\n send({ t: \"delete\", registry, handle });\n };\n g.__wasmerCapiInfo = (registry, handle) => ({ inTable: table.has(key(registry, handle)), mine: mine.has(key(registry, handle)), gone: gone.get(key(registry, handle)) || null, tableSize: table.size });\n g.__wasmerCapiMessageScope = () => scope;\n return {\n receive,\n close() {\n if (bc)\n bc.close();\n for (const ws of waiting.values())\n for (const w of ws)\n w.reject(new Error(\"capi: closed\"));\n waiting.clear();\n },\n table,\n goneLimit: GONE_LIMIT,\n goneSize: () => gone.size\n };\n}\nfunction installSerdesState(g, { scope, note = null }) {\n let next = scope * 2 ** 20 + 1;\n const say = (ev, id, extra = \"\") => note && note(`SERDES ${Math.round(performance.timeOrigin + performance.now()) % 1e7} s${scope} ${ev} ${id} w${Math.floor(id / 2 ** 20)}${extra}`);\n const seen = new Set;\n const state = {\n get next() {\n return next;\n },\n set next(v) {\n next = v;\n },\n codec: {\n encode: (value) => {\n const bytes = encode(value);\n if (note)\n say(bytes ? \"inline\" : \"byid\", 0, ` ${bytes ? bytes.length : 0}`);\n return bytes;\n },\n decode\n },\n values: {\n set: (id, value) => {\n say(\"share\", id);\n return g.__wasmerCapiShare(1397051972, id, { value });\n },\n has: (id) => {\n const hit = g.__wasmerCapiObtain(1397051972, id) !== undefined;\n if (note) {\n if (hit)\n say(\"has\", id, seen.has(id) ? \" AGAIN\" : \"\");\n else {\n const i = g.__wasmerCapiInfo ? g.__wasmerCapiInfo(1397051972, id) : {};\n say(\"MISS\", id, ` ${seen.has(id) ? \"read-before-here\" : i.gone ? \"deleted-\" + i.gone.replace(\" \", \"-\") : i.mine ? \"mine-not-in-table\" : \"never-arrived\"} table=${i.tableSize}`);\n }\n seen.add(id);\n }\n return hit;\n },\n get: (id) => g.__wasmerCapiObtain(1397051972, id)?.value,\n delete: (id) => {\n say(\"delete\", id);\n return g.__wasmerCapiDelete(1397051972, id);\n }\n },\n binding: () => makeSerdesBinding({ bufferOf: (u8) => state.bufferOf ? state.bufferOf(u8) : u8 }),\n bufferOf: null\n };\n g[Symbol.for(\"wasmer.napi.serdes.state\")] = state;\n}\n\n// src/edge/own/wasm-counters.js\nvar kind = (url) => {\n const u = String(url || \"\");\n if (/edgejs\\.wasm/.test(u))\n return \"program\";\n if (/wmd_browser_bg\\.wasm/.test(u))\n return \"runtime\";\n if (/wmd_browser\\.js/.test(u))\n return \"glue\";\n if (/HASHES\\.txt/.test(u))\n return \"hashes\";\n if (/linux\\.cjs/.test(u))\n return \"shim\";\n return \"other\";\n};\nvar sizeOf = (src) => {\n try {\n if (src && typeof src.byteLength === \"number\")\n return src.byteLength;\n if (src && src.buffer && typeof src.buffer.byteLength === \"number\")\n return src.buffer.byteLength;\n } catch {}\n return 0;\n};\nfunction installWasmCounters(g) {\n if (g.__wmdWasmCounters)\n return g.__wmdWasmCounters;\n const W = g.WebAssembly;\n const c = {\n compile: { calls: 0, bytes: 0, ms: 0 },\n stream: { calls: 0, bytes: 0, ms: 0 },\n instantiate: { calls: 0, bytes: 0, ms: 0 },\n module: { calls: 0, bytes: 0, ms: 0, maxMs: 0 },\n memory: { made: 0, shared: 0, madeBytes: 0 },\n fetched: {}\n };\n const refs = [];\n const kinds = [];\n const wrapAsync = (name, slot, bytesOf) => {\n const orig = W[name];\n if (typeof orig !== \"function\")\n return;\n W[name] = function(...a) {\n c[slot].calls++;\n c[slot].bytes += bytesOf ? bytesOf(a[0]) : 0;\n const t0 = performance.now();\n const p = orig.apply(this, a);\n return p && typeof p.then === \"function\" ? p.finally(() => c[slot].ms += performance.now() - t0) : p;\n };\n };\n wrapAsync(\"compile\", \"compile\", sizeOf);\n wrapAsync(\"instantiate\", \"instantiate\", sizeOf);\n const streamBytes = (r) => {\n try {\n return Number(r && r.headers && r.headers.get && r.headers.get(\"content-length\")) || 0;\n } catch {\n return 0;\n }\n };\n wrapAsync(\"compileStreaming\", \"stream\", null);\n wrapAsync(\"instantiateStreaming\", \"stream\", null);\n if (W.Module) {\n W.Module = new Proxy(W.Module, {\n construct(target, args) {\n const t0 = performance.now();\n const m = Reflect.construct(target, args);\n const ms = performance.now() - t0;\n c.module.calls++;\n c.module.bytes += sizeOf(args[0]);\n c.module.ms += ms;\n c.module.maxMs = Math.max(c.module.maxMs, ms);\n return m;\n }\n });\n }\n if (W.Memory) {\n W.Memory = new Proxy(W.Memory, {\n construct(target, args) {\n const d = args[0] || {};\n const m = Reflect.construct(target, args);\n c.memory.made++;\n if (d.shared)\n c.memory.shared++;\n refs.push(new WeakRef(m));\n kinds.push({ ref: new WeakRef(m), initial: d.initial | 0, maximum: d.maximum, shared: !!d.shared });\n return m;\n }\n });\n }\n const R = g.Response && g.Response.prototype;\n if (R && R.arrayBuffer) {\n const orig = R.arrayBuffer;\n R.arrayBuffer = async function() {\n const b = await orig.call(this);\n const k = kind(this.url);\n const f = c.fetched[k] ||= { calls: 0, bytes: 0 };\n f.calls++;\n f.bytes += b.byteLength;\n return b;\n };\n }\n const api = {\n kinds() {\n return kinds.map((k) => {\n const m = k.ref.deref();\n return { initial: k.initial, maximum: k.maximum, shared: k.shared, pages: m ? m.buffer.byteLength / 65536 : null };\n });\n },\n snapshot() {\n let live = 0;\n let liveBytes = 0;\n for (let i = refs.length - 1;i >= 0; i--) {\n const m = refs[i].deref();\n if (!m)\n continue;\n live++;\n try {\n liveBytes += m.buffer.byteLength;\n } catch {}\n }\n return JSON.parse(JSON.stringify({ ...c, memory: { ...c.memory, live, liveBytes }, kinds: api.kinds() }));\n }\n };\n g.__wmdWasmCounters = api;\n return api;\n}\n\n// src/edge/own/stack-fix.js\nvar NAMES = [\"Error\", \"TypeError\", \"RangeError\", \"SyntaxError\", \"ReferenceError\", \"EvalError\", \"URIError\"];\nfunction withHeader(e) {\n try {\n const s = e.stack;\n if (typeof s !== \"string\")\n return e;\n const name = String(e.name);\n if (s.startsWith(name))\n return e;\n const head = e.message ? `${name}: ${e.message}` : name;\n Object.defineProperty(e, \"stack\", { value: `${head}\n${s}`, writable: true, configurable: true, enumerable: false });\n } catch {}\n return e;\n}\nfunction installStackHeader(g) {\n const probe = new g.Error(\"wmd-probe\").stack;\n if (typeof probe === \"string\" && probe.startsWith(\"Error: wmd-probe\"))\n return false;\n for (const n of NAMES) {\n const C = g[n];\n if (typeof C !== \"function\")\n continue;\n g[n] = new Proxy(C, {\n construct: (target, args, newTarget) => withHeader(Reflect.construct(target, args, newTarget === g[n] ? target : newTarget)),\n apply: (target, thisArg, args) => withHeader(Reflect.apply(target, thisArg, args))\n });\n }\n return true;\n}\n\n// src/edge/own/marks.js\nvar PROGRAM_BYTES = 8 << 20;\nvar at = () => performance.timeOrigin + performance.now();\nvar sizeOf2 = (b) => b && typeof b.byteLength === \"number\" ? b.byteLength : 0;\nvar isProgram = (imports) => !!(imports && (imports.wasix_32v1 || imports.wasix_64v1 || imports.wasi_snapshot_preview1 || imports.wasi_unstable));\nvar CALL_RING = 400;\nvar PUSH_EVERY = 64;\nvar WASIX = [\"wasix_32v1\", \"wasix_64v1\", \"wasi_snapshot_preview1\", \"wasi_unstable\"];\n\nclass CallLog {\n ring = [];\n totals = {};\n n = 0;\n t0 = performance.now();\n post = null;\n wrap(name, f) {\n const log = this;\n return function(...a) {\n const t = performance.now();\n try {\n return f.apply(this, a);\n } finally {\n const us = (performance.now() - t) * 1000;\n const e = log.totals[name] ||= [0, 0];\n e[0]++;\n e[1] += us;\n if (log.ring.length < CALL_RING)\n log.ring.push([name, Math.round((t - log.t0) * 1000) / 1000, Math.round(us)]);\n if (log.post && (++log.n % PUSH_EVERY === 0 || log.ring.length === CALL_RING))\n log.post(log.snapshot());\n }\n };\n }\n wrapImports(imports) {\n const out = { ...imports };\n this.wrapped = {};\n for (const ns of WASIX) {\n if (!imports[ns])\n continue;\n this.wrapped[ns] = Object.keys(imports[ns]).length;\n out[ns] = Object.fromEntries(Object.entries(imports[ns]).map(([k, v]) => [k, typeof v === \"function\" ? this.wrap(k, v) : v]));\n }\n return out;\n }\n reset() {\n this.ring = [];\n this.totals = {};\n this.n = 0;\n this.taken = false;\n }\n snapshot() {\n return { inst: (this.g && this.g.__wmdInst ? this.g.__wmdInst : []).map((p) => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`), seen: this.seen || 0, taken: !!this.taken, wrapped: this.wrapped || null, ring: this.ring.map((r) => r.join(\" \")), totals: Object.fromEntries(Object.entries(this.totals).map(([k, v]) => [k, `${v[0]} ${Math.round(v[1])}`])) };\n }\n}\nfunction installMarks(g, post, opts = {}) {\n const W = g.WebAssembly;\n if (!W || W.__wmdMarks)\n return W && W.__wmdMarks;\n const calls = opts.calls ? new CallLog : null;\n if (calls && opts.postCalls)\n calls.post = opts.postCalls;\n if (calls)\n g.__wmdInst = [], calls.g = g;\n const Mod = W.Module;\n const Inst = W.Instance;\n W.Module = new Proxy(Mod, {\n construct(T, a, nt) {\n const big = sizeOf2(a[0]) >= PROGRAM_BYTES;\n const t0 = at();\n const m = Reflect.construct(T, a, nt);\n if (big)\n post(\"compile0\", t0), post(\"compile1\", at());\n return m;\n }\n });\n W.Instance = new Proxy(Inst, {\n construct(T, a, nt) {\n const prog = isProgram(a[1]);\n const t0 = at();\n if (prog && calls)\n calls.seen = (calls.seen || 0) + 1;\n let args = a;\n if (prog && calls && !calls.taken)\n calls.taken = true, args = [a[0], calls.wrapImports(a[1]), ...a.slice(2)];\n const i = Reflect.construct(T, args, nt);\n if (prog && calls && args !== a)\n calls.t0 = performance.now();\n if (prog)\n post(\"inst0\", t0), post(\"inst1\", at());\n return i;\n }\n });\n const compile = W.compile;\n W.compile = function(b, ...rest) {\n const big = sizeOf2(b) >= PROGRAM_BYTES;\n const t0 = at();\n const p = compile.call(this, b, ...rest);\n if (big)\n post(\"acompile0\", t0), p.then(() => post(\"acompile1\", at()), () => {});\n return p;\n };\n W.__wmdMarks = calls || true;\n return calls;\n}\n\n// src/edge/own/exit-now.js\nfunction makeExitNow({ runId, post, outs, cleanup = () => {}, endProcess = () => false, park }) {\n let posted = false;\n const status = (code) => {\n const n = Number(code);\n return Number.isFinite(n) ? Math.trunc(n) & 255 : 0;\n };\n return function exitNow(code, pid = 1) {\n if (pid !== 1) {\n let ended = false;\n try {\n ended = endProcess(pid, status(code)) === true;\n } catch {}\n if (ended)\n park();\n return;\n }\n if (!posted) {\n posted = true;\n try {\n cleanup();\n } catch {}\n post({ type: \"exit\", id: runId(), code: status(code), outs: outs() });\n }\n park();\n };\n}\nfunction parkForever() {\n const cell = new Int32Array(new SharedArrayBuffer(4));\n for (;; )\n Atomics.wait(cell, 0, 0);\n}\n\n// src/edge/own/worker.js\ninstallStackHeader(globalThis);\nvar glue = null;\nvar exports = null;\nvar turning = false;\nvar debug = false;\nvar role = \"\";\nvar capi = null;\nvar counters = null;\nvar marks = false;\nvar calls = null;\nvar runId = 0;\nvar text = (err) => String(err && err.stack || err);\nself.addEventListener(\"message\", async (e) => {\n const m = e.data;\n try {\n if (m.type === \"init\") {\n checkInit(m);\n debug = !!m.debug;\n if (debug)\n console.log(`[w] performance.memory ${typeof performance.memory} used ${performance.memory && performance.memory.usedJSHeapSize}`);\n role = m.role;\n counters = installWasmCounters(globalThis);\n if (m.marks)\n marks = true, calls = installMarks(globalThis, (name, t) => self.postMessage({ type: \"mark\", name, t }), { calls: m.marks === 2, postCalls: (snap) => self.postMessage({ type: \"calls\", ...snap }) }) || null;\n if (calls && typeof calls.snapshot !== \"function\")\n calls = null;\n if (marks)\n self.postMessage({ type: \"mark\", name: m.role === \"main\" ? \"mInit0\" : \"tInit0\", t: at() });\n if (m.fsTime) {\n const post = self.postMessage.bind(self);\n self.postMessage = (msg, t) => post(msg && msg.type === \"fs\" ? { ...msg, t0: performance.timeOrigin + performance.now() } : msg, t);\n }\n if (Array.isArray(m.nodeGlobals))\n globalThis.__wmdNodeGlobals = m.nodeGlobals;\n if (m.capi)\n capi = installCapi(globalThis, { channel: m.capi, scope: m.scope % 4096, relay: (msg) => self.postMessage({ type: \"capi\", msg }), log: m.debug ? (t) => console.log(`[capi s${m.scope}] ${t}`) : null });\n if (capi)\n installSerdesState(globalThis, { scope: m.scope % 4096, note: m.fsTime ? (text) => self.postMessage({ type: \"note\", text }) : null });\n const r = await loadRuntime({ ...m, role: m.role });\n glue = r.glue;\n exports = r.exports;\n turning = r.turning;\n if (marks)\n self.postMessage({ type: \"mark\", name: m.role === \"main\" ? \"mReady\" : \"tReady\", t: at() });\n glue.wmd_set_trace(m.trace | 0);\n globalThis.__wmdExitNow = makeExitNow({ runId: () => role === \"main\" ? runId : undefined, post: (msg) => self.postMessage(msg), outs: () => glue.wmd_out_count(), endProcess: (pid, code) => typeof glue.wmd_exit_process === \"function\" ? glue.wmd_exit_process(pid, code) : false, park: parkForever });\n if (m.calltrace)\n glue.wmd_set_calltrace(true);\n if (m.napifixOff)\n glue.wmd_set_napifix_off(true);\n globalThis.__wmdCtl = (_pid, json) => glue.wmd_ctl(json);\n self.postMessage({\n type: \"ready\",\n memory: r.memory,\n stdin: { addr: glue.wmd_stdin_addr(), cap: glue.wmd_stdin_cap(), off: glue.wmd_stdin_offset() },\n tty: glue.wmd_tty_addr()\n });\n } else if (m.type === \"counts\") {\n self.postMessage({ type: \"counts\", seq: m.seq, role, c: counters ? counters.snapshot() : null });\n } else if (m.type === \"capi\") {\n if (capi)\n capi.receive(m.msg);\n } else if (m.type === \"task\") {\n try {\n if (debug)\n console.log(\"[w thread] task start\");\n if (marks)\n self.postMessage({ type: \"mark\", name: \"task0\", t: at() });\n if (calls)\n calls.reset();\n if (turning) {\n const ptr = glue.wmd_thread_prepare(m.msg);\n await WebAssembly.promising(exports.wmd_job_main)(ptr);\n } else {\n glue.wmd_thread_entry(m.msg);\n }\n } catch (err) {\n self.postMessage({ type: \"crash\", error: text(err) });\n return;\n }\n if (calls && calls.taken)\n self.postMessage({ type: \"calls\", ...calls.snapshot() });\n if (debug)\n console.log(\"[w thread] task done\");\n self.postMessage({ type: \"done\" });\n } else if (m.type === \"run\") {\n runId = m.id;\n try {\n if (debug)\n console.log(\"[w main] run start\");\n if (marks)\n self.postMessage({ type: \"mark\", name: \"runRecv\", t: at() });\n if (calls)\n calls.reset();\n const run = m.node ? glue.wmd_run_node : glue.wmd_run;\n if (!run)\n throw new Error(\"this build has no N-API support (build edge/browser with --features napi)\");\n let code;\n if (m.module && !m.node && glue.wmd_run_ready) {\n code = glue.wmd_run_ready(m.module, m.hash, m.program, m.args || [], m.env || [], m.opts || \"\");\n } else if (m.module && m.node && glue.wmd_run_node_ready) {\n code = glue.wmd_run_node_ready(m.module, m.hash, m.program, m.args || [], m.env || [], m.opts || \"\");\n } else {\n code = run(new Uint8Array(m.program), m.args || [], m.env || [], m.opts || \"\");\n }\n if (calls)\n self.postMessage({ type: \"calls\", ...calls.snapshot() });\n if (marks)\n self.postMessage({ type: \"mark\", name: \"exitPost\", t: at() });\n self.postMessage({ type: \"exit\", id: m.id, code, outs: glue.wmd_out_count() });\n } catch (err) {\n self.postMessage({ type: \"run-error\", id: m.id, error: text(err), outs: glue.wmd_out_count() });\n }\n }\n } catch (err) {\n self.postMessage({ type: \"fatal\", error: text(err) });\n }\n});\n"
6
6
  export const FRAME_CODE = { frame: FRAME, worker: WORKER, ownWorker: OWNWORKER }
@@ -41,6 +41,21 @@ const absUrl = (url) => {
41
41
  return url
42
42
  }
43
43
  }
44
+ /** X25 gate 2e: what a start keeps of the tree (edge/browser/src/fscache.rs), chosen by the program's environment WMD_FSCACHE: a mask 0..7 (1 listings, 2 stats); anything else is no choice. */
45
+ export function fsCacheOf(env) {
46
+ const v = env && env.WMD_FSCACHE
47
+ return typeof v === 'string' && /^[0-7]$/.test(v) ? Number(v) : undefined
48
+ }
49
+
50
+ /**
51
+ * FSC-1: the run option `fscache` for a start: the page's off (the frame's config `own.fscache === false`) wins and sends 0; else the program's own WMD_FSCACHE (fsCacheOf);
52
+ * else nothing, and the runtime's default (on) holds.
53
+ */
54
+ export function fscacheRunOption(own, env) {
55
+ if (own && own.fscache === false) return 0
56
+ return fsCacheOf(env)
57
+ }
58
+
44
59
  const whyOf = (e) => String((e && e.message) || e).split('\n')[0]
45
60
  function runtimeFile(text) {
46
61
  const e = new Error(text)
@@ -378,7 +393,7 @@ export async function start({ module, argv, env, cwd, files = {}, linux, linuxSr
378
393
  mark('runPost')
379
394
  const envList = Object.entries({ HOME: '/root', ...(env || {}) }).map(([k, v]) => `${k}=${v}`)
380
395
  runP = rt
381
- .run({ program, ...(ready ? { ready } : {}), args, env: envList, node: !python, cwd, stdin: stdin === 'pipe' ? 'pipe' : 'null', tty: {}, children: s.own.children !== false, net: s.own.net !== false, exec: linux && linux.execPath, shim: !!linux && !python, ...(python ? { argv0: python.argv0 } : {}) })
396
+ .run({ program, ...(ready ? { ready } : {}), args, env: envList, node: !python, cwd, stdin: stdin === 'pipe' ? 'pipe' : 'null', tty: {}, children: s.own.children !== false, net: s.own.net !== false, exec: linux && linux.execPath, shim: !!linux && !python, ...(python ? { argv0: python.argv0 } : {}), ...(fscacheRunOption(s.own, env) !== undefined ? { fscache: fscacheRunOption(s.own, env) } : {}) })
382
397
  .then(
383
398
  // a program the default action of a signal ended: the runtime's code records the signal (wmd_signal.rs `signaled`, 0x4000 + n), the exit is 128 + n
384
399
  r => ((r.code & ~0x7f) === 0x4000 ? { exitCode: 128 + (r.code & 0x7f), reason: 'exit', signal: r.code & 0x7f } : { exitCode: r.code, reason: 'exit' }),
@@ -30,8 +30,9 @@ export { payloadBytes }
30
30
  * The options JSON a `run` message carries to the runtime (edge/browser/src/lib.rs `RunOpts`). `net` is true only when the caller asked: a runtime
31
31
  * that gets no `net` has no network (every socket call is ENOTSUP, as before X5 net).
32
32
  */
33
- export function runOptionsJson({ fs, cwd, stdin, tty, children, exec, shim, net = false, jspi, argv0 }) {
34
- return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...(argv0 ? { argv0 } : {}) })
33
+ export function runOptionsJson({ fs, cwd, stdin, tty, children, exec, shim, net = false, jspi, argv0, fscache }) {
34
+ // fscache (X25 gate 2e): what the start keeps of the tree, a bit mask (1 listings, 2 stats); absent = the runtime's default
35
+ return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...(argv0 ? { argv0 } : {}), ...(Number.isInteger(fscache) && fscache >= 0 ? { fscache } : {}) })
35
36
  }
36
37
 
37
38
  const sumCalls = (t) => Object.values(t || {}).reduce((s, v) => s + (parseInt(v, 10) || 0), 0)
@@ -184,7 +185,7 @@ export class OwnRuntime {
184
185
  // The file system is the page's file route (option fsRoute of start()): the program's root is that route's tree.
185
186
  // ready X5 default1 round 2 (B2.1): the program made ready by OwnRuntime.prepare (capped bytes, their sha256 and the compiled module): node only;
186
187
  // the runtime compiles and hashes nothing and the bytes are not copied here (a kept frame hands the same ones to each start)
187
- run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = 'null', tty = {}, children = false, exec, shim = false, net = false, argv0 }) {
188
+ run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = 'null', tty = {}, children = false, exec, shim = false, net = false, argv0, fscache }) {
188
189
  if (this.#dead) return Promise.reject(new Error('runtime terminated'))
189
190
  const id = this.#nextRun++
190
191
  let buf = null
@@ -201,7 +202,7 @@ export class OwnRuntime {
201
202
  }
202
203
  return new Promise((resolve, reject) => {
203
204
  this.#runs.set(id, { resolve, reject })
204
- const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0 })
205
+ const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0, fscache })
205
206
  if (tty.cols || tty.rows) setTtySize(this.#memory, this.#ttyAddr, tty.cols || 80, tty.rows || 24)
206
207
  this.#calls = null // the run's ring is the biggest one of its Workers (worker.js posts one per task)
207
208
  if (ready) this.#main.postMessage({ type: 'run', id, program: ready.bytes, module: ready.module, hash: ready.hash, args, env, node, opts })
@@ -2,9 +2,9 @@
2
2
  // The files of node in the sandboxed frame: the path under a source (the option edge: { sources } of bootWmd), the role the frame gives the file, its
3
3
  // sha256 and its size. The page accepts a file only when it has exactly this sha256 and size. The notice files travel with the rest.
4
4
  // EDGE_PACKAGE is the package that holds these files, for the {name} {version} {file} of a registry source's url (null: none named).
5
- export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.41' }
5
+ export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.42' }
6
6
  export const EDGE_PINS = [
7
- { path: 'wmd_browser_bg.wasm', role: 'wasm', sha256: '5c6a28df432770c97e9b1c7bd77589bd31c063bb574d2a4c77768ef032f4ceee', size: 6312756 },
7
+ { path: 'wmd_browser_bg.wasm', role: 'wasm', sha256: '1e3db7f2c5f4be0ee44e5f2c0205cf8ca11f906d9addd5512915fad4821661c2', size: 6334959 },
8
8
  { path: 'wmd_browser.js', role: 'glue', sha256: 'b389b072096881ba39b22cd705d3a230af02acc5409c61fb4f997d1081c4df6f', size: 75647 },
9
9
  { path: 'snippets/wasmer-napi-749f42b30f6a109f/inline0.js', role: 'snippet', sha256: '6b7322b9a8e1c49921d022621e3438a597630a14df26576a8359070e477fe5f7', size: 38363 },
10
10
  { path: 'acorn/acorn.mjs', role: 'acorn', sha256: '5fb5f5d2613ed04b33892f2beba7400e4d6ba624512bc0e8dfb572243b2882f3', size: 207423 },
@@ -51,7 +51,9 @@ export function pageRuntime(get) {
51
51
  const trace = Math.min(2, Math.max(0, Number(get('edgeTrace')) | 0))
52
52
  // X5 net: edgeNet=0 turns the frame's network off (every socket call is ENOTSUP again): for the A/B of its cost and for a diagnosis
53
53
  const noNet = get('edgeNet') === '0'
54
- return { rt: parseRt(get('rt')), handIn: base || fsTime || counts || marks || noKeep || trace || noNet ? { ...(base ? handSdk(base) : {}), fsTime, ...(counts ? { counts } : {}), ...(marks ? { marks } : {}), ...(noKeep ? { keepMods: false } : {}), ...(trace ? { trace } : {}), ...(noNet ? { net: false } : {}) } : null }
54
+ // FSC-1: edgeFscache=0 turns the kept file answers off (for the A/B of their cost and for a diagnosis); on otherwise
55
+ const noFsc = get('edgeFscache') === '0'
56
+ return { rt: parseRt(get('rt')), handIn: base || fsTime || counts || marks || noKeep || trace || noNet || noFsc ? { ...(base ? handSdk(base) : {}), fsTime, ...(counts ? { counts } : {}), ...(marks ? { marks } : {}), ...(noKeep ? { keepMods: false } : {}), ...(trace ? { trace } : {}), ...(noNet ? { net: false } : {}), ...(noFsc ? { fscache: false } : {}) } : null }
55
57
  }
56
58
 
57
59
  /** The page option rt as a runtime name: '' or absent is the default; anything else is returned as given (unavailable() then refuses it). */
@@ -72,7 +74,7 @@ export function unavailable(rt) {
72
74
  */
73
75
  export function runtimeConfig(rt, handIn = null) {
74
76
  // handIn.sbx: the frame the library makes itself has no site to load from: the files are handed in as bytes, under these names (src/edge/sbx/worker-entry.js)
75
- if (rt === 'own') return { own: { ...(handIn && handIn.sbx ? { wasmUrl: 'sbx:wmd_browser_bg.wasm', glueUrl: 'sbx:wmd_browser.js', workerUrl: 'sbx:own-worker.js' } : { wasmUrl: '/own/wmd_browser_bg.wasm', glueUrl: '/own/wmd_browser.js', workerUrl: '/edge/own/worker.js' }), ...(handIn && handIn.fsTime ? { fsTime: true } : {}), ...(handIn && handIn.counts ? { counts: true } : {}), ...(handIn && handIn.marks ? { marks: handIn.marks } : {}), ...(handIn && handIn.keepMods === false ? { keepMods: false } : {}), ...(handIn && handIn.trace ? { trace: handIn.trace } : {}), ...(handIn && handIn.net === false ? { net: false } : {}) } }
77
+ if (rt === 'own') return { own: { ...(handIn && handIn.sbx ? { wasmUrl: 'sbx:wmd_browser_bg.wasm', glueUrl: 'sbx:wmd_browser.js', workerUrl: 'sbx:own-worker.js' } : { wasmUrl: '/own/wmd_browser_bg.wasm', glueUrl: '/own/wmd_browser.js', workerUrl: '/edge/own/worker.js' }), ...(handIn && handIn.fsTime ? { fsTime: true } : {}), ...(handIn && handIn.counts ? { counts: true } : {}), ...(handIn && handIn.marks ? { marks: handIn.marks } : {}), ...(handIn && handIn.keepMods === false ? { keepMods: false } : {}), ...(handIn && handIn.trace ? { trace: handIn.trace } : {}), ...(handIn && handIn.net === false ? { net: false } : {}), ...(handIn && handIn.fscache === false ? { fscache: false } : {}) } }
76
78
  if (rt === 'sdk' && handIn && handIn.rtBase) return { rtBase: handIn.rtBase }
77
79
  return {}
78
80
  }
@@ -26,6 +26,18 @@ export function frameCapOf(ua = globalThis.navigator?.userAgent || '', own) {
26
26
  return FRAME_CAPS[engineOf(ua)] // undefined: no bound
27
27
  }
28
28
 
29
+ /**
30
+ * FSC-1: the engines whose frames do NOT keep file answers (edge/browser/src/fscache.rs), as {engine: true}. Empty: the equality proof of the six programs passed in
31
+ * Chromium, Firefox and WebKit (docs/research/browser-speed-2026-11/fsc/fsc.md). A browser that fails it is named here and runs with the kept answers off, the others stay on.
32
+ */
33
+ export const FSCACHE_OFF = {}
34
+
35
+ /** Whether a start keeps file answers: the page's own choice (option edge.fscache, a boolean) first, else the engine table. */
36
+ export function fscacheOnOf(ua = globalThis.navigator?.userAgent || '', own) {
37
+ if (typeof own === 'boolean') return own
38
+ return !FSCACHE_OFF[engineOf(ua)]
39
+ }
40
+
29
41
  /** The reason of a start that went to the guest because the page has its frames: a calm one, not a failure. */
30
42
  export const FRAME_CAP_WHY = n => n === 0 ? 'node runs in the guest in this browser: its frames of node cost more memory than the browser allows a page' : `this page already has ${n} frame${n === 1 ? '' : 's'} of node alive, the most this browser holds: this one runs in the guest`
31
43
 
package/src/edge/setup.js CHANGED
@@ -22,7 +22,7 @@ import { SANDBOX } from './sbx/common.js'
22
22
  import { filesGate } from './sbx/gate.js'
23
23
  import { pythonModuleFor } from './python-module.js'
24
24
  import { pythonCapMiB } from './python-plan.js'
25
- import { FRAME_CAP_WHY, frameCapOf, hintOf } from './sbx/cap.js'
25
+ import { FRAME_CAP_WHY, fscacheOnOf, frameCapOf, hintOf } from './sbx/cap.js'
26
26
 
27
27
  // The Worker form the first sandboxed frame of this page found (src/edge/sbx/common.js probeStrategy); the page's later frames try it first.
28
28
  let wmHint = ''
@@ -82,6 +82,7 @@ const idleOf = g => (typeof g.requestIdleCallback === 'function' ? f => g.reques
82
82
  * @param {string} [o.rt] the runtime (src/edge/runtime.js, 'own'); [o.handIn] what the caller hands it
83
83
  * @param {object} [o.watch] the frame watch's limits (src/edge/page.js runEdge); keepFrame defaults to true
84
84
  * @param {boolean} [o.shareSite] true: this container may live on one frame site with others that say the same (they are not kept apart)
85
+ * @param {boolean} [o.fscache] false: no start keeps file answers (default on in every browser, src/edge/sbx/cap.js FSCACHE_OFF; a browser that fails the equality proof is off there only)
85
86
  * @param {number} [o.frameCap] the most frames of node this page has alive at once (default by browser, src/edge/sbx/cap.js); a start that needs a new one over it runs in the guest
86
87
  * @param {boolean} [o.prepare] false: no frame is made before the first node command (default true, with keepFrame)
87
88
  * @param {function} [o.onLog] (id, record) of each run, and the site's events ({type: 'site', ...})
@@ -89,7 +90,7 @@ const idleOf = g => (typeof g.requestIdleCallback === 'function' ? f => g.reques
89
90
  * @param {{on: number, off: object}} counts the plan's decisions, counted (src/boot.js edgePlanCounts)
90
91
  */
91
92
  export function edgeSetupIn(o, counts) {
92
- const { origin: siteOrigin, sources, base, pinned = null, fetchFiles: fetchFilesOpt, fetchOpts = {}, filesWaitMs, filesRetryMs, filesProgressMs, frameCap: frameCapOpt, python: pythonAsk, imagePython, pythonMaxMiB, fetchPython: fetchPythonOpt, ramMiB = 0, main = [], memoryMB = 0, swapMB = 0, env = [], user = '', readonlyRoot = false, hasTmpfs = false, p9port = 564, root = 'rootfs', settings = {}, rt = RT_DEFAULT, handIn = null, watch = {}, prepare = true, shareSite = false, edgeWasm = '/wasm/edgejs.wasm', onLog = () => {}, onBridge = () => {}, doc = globalThis.document, win = globalThis } = o
93
+ const { origin: siteOrigin, sources, base, pinned = null, fetchFiles: fetchFilesOpt, fetchOpts = {}, filesWaitMs, filesRetryMs, filesProgressMs, frameCap: frameCapOpt, fscache: fscacheOpt, python: pythonAsk, imagePython, pythonMaxMiB, fetchPython: fetchPythonOpt, ramMiB = 0, main = [], memoryMB = 0, swapMB = 0, env = [], user = '', readonlyRoot = false, hasTmpfs = false, p9port = 564, root = 'rootfs', settings = {}, rt = RT_DEFAULT, handIn = null, watch = {}, prepare = true, shareSite = false, edgeWasm = '/wasm/edgejs.wasm', onLog = () => {}, onBridge = () => {}, doc = globalThis.document, win = globalThis } = o
93
94
  const sandbox = !siteOrigin
94
95
  const origin = sandbox ? SANDBOX : siteOrigin
95
96
  // X25: python in the frame follows the switch of node (`edge`) and has its own, `python: false`; the page's plan for the image's python is planPython
@@ -122,6 +123,8 @@ export function edgeSetupIn(o, counts) {
122
123
  }
123
124
  counts.on++
124
125
  const keepFrame = watch.keepFrame !== false
126
+ // FSC-1: the page's option, else the engine's table: off says so in the frame's config (own.fscache === false), on says nothing (the runtime's default)
127
+ const fscHand = fscacheOnOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? '', fscacheOpt) ? {} : { fscache: false }
125
128
  // the sandboxed frame: the page fetches and checks the files (src/edge/sbx/files.js) and hands them in; the frame's code is generated text (frame-code.gen.js)
126
129
  let codeP = null
127
130
  let hookP = null // the test hook's one fetch (a result with an error is not kept)
@@ -204,7 +207,7 @@ export function edgeSetupIn(o, counts) {
204
207
  python: pyPlan.use ? { path: pyPlan.python, version: pyPlan.version, maxMiB: capMiB } : null,
205
208
  settings: { arch: 'arm64', hostname: 'wmd-web', cpus: 1, ...settings, execPath: plan.node },
206
209
  rt,
207
- handIn: sandbox ? { ...handIn, sbx: true } : handIn,
210
+ handIn: sandbox ? { ...handIn, sbx: true, ...fscHand } : handIn,
208
211
  edgeWasm: sandbox ? 'sbx:edgejs.wasm' : edgeWasm,
209
212
  nodeVersion: nodeVersion(env), // the image's node version: the frame's node reports it (check5 F5)
210
213
  watch: { ...watch, keepFrame },
@@ -256,7 +259,7 @@ export function edgeSetupIn(o, counts) {
256
259
  if (sandbox) gate.begin() // the files come while the frame is made (a node start finds them in, or waits at most FILES_WAIT_MS)
257
260
  const { prepareEdge } = await import('./page.js')
258
261
  if (sandbox) await sbx.loadCode()
259
- const cfg = { rt, ...runtimeConfig(rt, sandbox ? { ...handIn, sbx: true } : handIn), edgeWasm: prepWasm, ...(sandbox ? { linuxSrc: 'sbx:linux.cjs' } : {}), linux: {}, ...(pyPlan.use && prepWasm !== nodeWasm ? { memoryMaxMiB: capMiB } : {}) }
262
+ const cfg = { rt, ...runtimeConfig(rt, sandbox ? { ...handIn, sbx: true, ...fscHand } : handIn), edgeWasm: prepWasm, ...(sandbox ? { linuxSrc: 'sbx:linux.cjs' } : {}), linux: {}, ...(pyPlan.use && prepWasm !== nodeWasm ? { memoryMaxMiB: capMiB } : {}) }
260
263
  p.started = Math.round(performance.now())
261
264
  const r = await prepareEdge({ origin, cfg, doc, win, owner, ...(sandbox ? { sbx } : {}) })
262
265
  Object.assign(p, r, { ended: Math.round(performance.now()) })
package/wmdpack.wasm CHANGED
Binary file