@threadedstack/wmd-web 0.1.30 → 0.1.32

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.
Files changed (62) hide show
  1. package/README.md +23 -2
  2. package/RELEASE.json +123 -16
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +47 -2
  8. package/src/edge/bridge.js +297 -0
  9. package/src/edge/codes.js +10 -0
  10. package/src/edge/ctl.js +199 -0
  11. package/src/edge/error-kind.js +4 -0
  12. package/src/edge/frame.html +4 -0
  13. package/src/edge/frame.js +48 -0
  14. package/src/edge/fs-route.js +301 -0
  15. package/src/edge/hist.js +46 -0
  16. package/src/edge/msg.js +106 -0
  17. package/src/edge/node-args.js +194 -0
  18. package/src/edge/node-guest-opts.js +108 -0
  19. package/src/edge/node-opts.js +82 -0
  20. package/src/edge/own/adapter.js +271 -0
  21. package/src/edge/own/capi.js +200 -0
  22. package/src/edge/own/child-host.js +196 -0
  23. package/src/edge/own/fs-bridge.js +71 -0
  24. package/src/edge/own/fs-own-route.js +356 -0
  25. package/src/edge/own/guest-spawner.js +235 -0
  26. package/src/edge/own/hub.js +430 -0
  27. package/src/edge/own/loader.js +81 -0
  28. package/src/edge/own/memcap.js +95 -0
  29. package/src/edge/own/payload-size.js +15 -0
  30. package/src/edge/own/pool.js +160 -0
  31. package/src/edge/own/procfs.js +84 -0
  32. package/src/edge/own/serdes-codec.js +317 -0
  33. package/src/edge/own/service-receiver.js +98 -0
  34. package/src/edge/own/shim-post.js +185 -0
  35. package/src/edge/own/stack-fix.js +36 -0
  36. package/src/edge/own/stdio-pipe.js +80 -0
  37. package/src/edge/own/v8-serdes.js +970 -0
  38. package/src/edge/own/wasm-counters.js +144 -0
  39. package/src/edge/own/worker.js +97 -0
  40. package/src/edge/page.js +162 -0
  41. package/src/edge/plan.js +65 -0
  42. package/src/edge/resolve.js +44 -0
  43. package/src/edge/runtime.js +94 -0
  44. package/src/edge/sdk/adapter.js +151 -0
  45. package/src/edge/sdk/forward.js +80 -0
  46. package/src/edge/sdk/napi-stub.js +50 -0
  47. package/src/edge/sdk/relay.js +17 -0
  48. package/src/edge/service-host.js +382 -0
  49. package/src/edge/service-port.js +245 -0
  50. package/src/edge/shim.js +161 -0
  51. package/src/edge/site.js +106 -0
  52. package/src/edge/spawn-guard.js +80 -0
  53. package/src/edge/tz.js +103 -0
  54. package/src/edge/worker.js +121 -0
  55. package/src/edge/workers.js +27 -0
  56. package/src/host/chan-service.js +75 -8
  57. package/src/host/chan-services.js +77 -3
  58. package/src/host/ctl.js +26 -5
  59. package/src/host/edge-go.js +7 -3
  60. package/src/host/edge-host.js +327 -0
  61. package/src/host/yamux.js +21 -8
  62. package/wmdpack.wasm +0 -0
@@ -0,0 +1,108 @@
1
+ // fix7 item 5 (F5): the node options the frame's node does not run as the image's node does. The frame's program is Edge.js's build, whose option
2
+ // parser knows part of node's options: an option it does not know ends the run with exit 9 and no text where node runs, and some it knows act
3
+ // differently (a check of the option's use that node makes at its start, a message on stderr, a debugger that listens). Every option in this table sends
4
+ // the run to the guest's own node, with the reason named in the page's fallback counters. The table was made from the sweep of node's own options
5
+ // (`web/test/fix5/machine.ts optsweep`, 181 options, edge against guest in Chromium): every option whose result differed is here or was fixed.
6
+ // `NODE_OPTIONS` of the container is read the same way.
7
+ import { parseNodeArgs, parseNodeOptions } from './node-args.js'
8
+
9
+ /** option -> why the frame cannot run it */
10
+ export const GUEST_OPTIONS = new Map([
11
+ ['--expose-gc', 'global.gc() needs the engine to collect garbage on request: the frame\'s engine (the browser\'s) cannot'],
12
+ ['--expose_gc', 'global.gc() needs the engine to collect garbage on request: the frame\'s engine (the browser\'s) cannot'],
13
+ ['--allow-fs-read', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model"],
14
+ ['--allow-fs-write', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model"],
15
+ ['--allow-addons', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
16
+ ['--allow-child-process', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
17
+ ['--allow-inspector', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
18
+ ['--allow-wasi', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
19
+ ['--allow-worker', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
20
+ ['--allow-openssl-store', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
21
+ ['--permission', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
22
+ ['--experimental-permission', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model (it prints a warning of its own where node prints none)"],
23
+ ['--allow-openssl-store', "the option is about OpenSSL (fips, secure heap, store): the frame's build has none of it and answers differently from node"],
24
+ ['--build-snapshot', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
25
+ ['--build-snapshot-config', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
26
+ ['--check', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
27
+ ['--cpu-prof-dir', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
28
+ ['--cpu-prof-interval', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
29
+ ['--cpu-prof-name', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
30
+ ['--debug-port', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
31
+ ['--disable-proto', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
32
+ ['--disable-sigusr1', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
33
+ ['--disable-wasm-trap-handler', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
34
+ ['--disallow-code-generation-from-strings', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
35
+ ['--enable-etw-stack-walking', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
36
+ ['--enable-fips', "the option is about OpenSSL (fips, secure heap, store): the frame's build has none of it and answers differently from node"],
37
+ ['--enable-fips-indicator-events', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
38
+ ['--enable-network-family-autoselection', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
39
+ ['--experimental-config-file', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
40
+ ['--experimental-default-config-file', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
41
+ ['--experimental-import-text', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
42
+ ['--experimental-package-map', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
43
+ ['--experimental-sea-config', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
44
+ ['--experimental-storage-inspection', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
45
+ ['--experimental-stream-iter', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
46
+ ['--experimental-test-tag-filter', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
47
+ ['--experimental-worker-inspection', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
48
+ ['--force-context-aware', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
49
+ ['--force-fips', "the option is about OpenSSL (fips, secure heap, store): the frame's build has none of it and answers differently from node"],
50
+ ['--force-node-api-uncaught-exceptions-policy', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
51
+ ['--frozen-intrinsics', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
52
+ ['--heap-prof-dir', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
53
+ ['--heap-prof-interval', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
54
+ ['--heap-prof-name', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
55
+ ['--heapsnapshot-near-heap-limit', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
56
+ ['--heapsnapshot-signal', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
57
+ ['--inspect', "node starts a debugger or inspector (a listener and a message on stderr) that the frame does not have"],
58
+ ['--inspect-brk', "node starts a debugger or inspector (a listener and a message on stderr) that the frame does not have"],
59
+ ['--inspect-publish-uid', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
60
+ ['--inspect-wait', "node starts a debugger or inspector (a listener and a message on stderr) that the frame does not have"],
61
+ ['--interpreted-frames-native-stack', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
62
+ ['--loader', "node starts its loader hooks in a thread of its own (AsyncLoaderHookWorker) that the frame's engine cannot run: it ends with a TypeError (reading 'status') where node runs the loader"],
63
+ ['--experimental-loader', "node starts its loader hooks in a thread of its own (AsyncLoaderHookWorker) that the frame's engine cannot run: it ends with a TypeError (reading 'status') where node runs the loader"],
64
+ ['--max-old-space-size-percentage', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
65
+ ['--network-family-autoselection-attempt-timeout', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
66
+ ['--no-extra-info-on-fatal-exception', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
67
+ ['--no-force-async-hooks-checks', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
68
+ ['--no-global-search-paths', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
69
+ ['--node-memory-debug', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
70
+ ['--permission-audit', "node's permission model reads the option at its start and makes its own checks and messages; the frame has no permission model"],
71
+ ['--prof-process', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
72
+ ['--report-exclude-env', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
73
+ ['--report-exclude-network', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
74
+ ['--run', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
75
+ ['--secure-heap', "the option is about OpenSSL (fips, secure heap, store): the frame's build has none of it and answers differently from node"],
76
+ ['--secure-heap-min', "the option is about OpenSSL (fips, secure heap, store): the frame's build has none of it and answers differently from node"],
77
+ ['--snapshot-blob', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
78
+ ['--test', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
79
+ ['--test-random-seed', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
80
+ ['--test-randomize', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
81
+ ['--tls-max-v1', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
82
+ ['--tls-min-v1', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
83
+ ['--trace-env', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
84
+ ['--trace-env-js-stack', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
85
+ ['--trace-env-native-stack', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
86
+ ['--trace-exit', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
87
+ ['--trace-promises', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
88
+ ['--trace-require-module', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
89
+ ['--trace-sync-io', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
90
+ ['--trace-uncaught', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
91
+ ['--track-heap-objects', "node prints trace text (to stderr or a file) for this option; the frame prints none or other text"],
92
+ ['--unhandled-rejections', "the frame's option parser does not know it (it ends the run with exit 9 and no text); the image's node runs it"],
93
+ ['--use-largepages', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
94
+ ['--watch', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
95
+ ['--watch-path', "node checks this option against others at its start and ends with exit 9 and its own message; the frame runs the program"],
96
+ ])
97
+
98
+ const norm = name => name.replace(/_/g, '-')
99
+
100
+ /** The first option of the command line or of the container's NODE_OPTIONS that the frame cannot run, as {name, why}, or null. */
101
+ export function guestOption(hello) {
102
+ const names = [...parseNodeArgs(hello).options, ...parseNodeOptions(hello.env).options]
103
+ for (const n of names) {
104
+ const why = GUEST_OPTIONS.get(n) ?? GUEST_OPTIONS.get(norm(n))
105
+ if (why) return { name: n, why }
106
+ }
107
+ return null
108
+ }
@@ -0,0 +1,82 @@
1
+ // Made by web/test/unit/data/gen-node-opts.mjs from `node --help` and `node --v8-options`. Do not edit by hand.
2
+ // The node options that take a separate value: `node --env-file .env app.js` runs app.js, `node --check app.js` has no value. 77 entries.
3
+ // Versions: v24.13.1 (host), v24.22.3 (the container of the npmci image, from its own node --help)
4
+ export const NODE_VALUE_OPTIONS = new Set([
5
+ '--allow-fs-read',
6
+ '--allow-fs-write',
7
+ '--build-snapshot-config',
8
+ '--conditions',
9
+ '--cpu-prof-dir',
10
+ '--cpu-prof-interval',
11
+ '--cpu-prof-name',
12
+ '--debug-port',
13
+ '--diagnostic-dir',
14
+ '--disable-proto',
15
+ '--disable-warning',
16
+ '--dns-result-order',
17
+ '--env-file',
18
+ '--env-file-if-exists',
19
+ '--eval',
20
+ '--experimental-config-file',
21
+ '--experimental-loader',
22
+ '--experimental-package-map',
23
+ '--experimental-sea-config',
24
+ '--experimental-test-isolation',
25
+ '--experimental-test-tag-filter',
26
+ '--heap-prof-dir',
27
+ '--heap-prof-interval',
28
+ '--heap-prof-name',
29
+ '--heapsnapshot-near-heap-limit',
30
+ '--heapsnapshot-signal',
31
+ '--icu-data-dir',
32
+ '--import',
33
+ '--input-type',
34
+ '--inspect-port',
35
+ '--inspect-publish-uid',
36
+ '--loader',
37
+ '--localstorage-file',
38
+ '--max-http-header-size',
39
+ '--max-old-space-size-percentage',
40
+ '--network-family-autoselection-attempt-timeout',
41
+ '--openssl-config',
42
+ '--redirect-warnings',
43
+ '--report-dir',
44
+ '--report-directory',
45
+ '--report-filename',
46
+ '--report-signal',
47
+ '--require',
48
+ '--run',
49
+ '--secure-heap',
50
+ '--secure-heap-min',
51
+ '--snapshot-blob',
52
+ '--test-concurrency',
53
+ '--test-coverage-branches',
54
+ '--test-coverage-exclude',
55
+ '--test-coverage-functions',
56
+ '--test-coverage-include',
57
+ '--test-coverage-lines',
58
+ '--test-global-setup',
59
+ '--test-isolation',
60
+ '--test-name-pattern',
61
+ '--test-random-seed',
62
+ '--test-reporter',
63
+ '--test-reporter-destination',
64
+ '--test-rerun-failures',
65
+ '--test-shard',
66
+ '--test-skip-pattern',
67
+ '--test-timeout',
68
+ '--title',
69
+ '--tls-cipher-list',
70
+ '--tls-keylog',
71
+ '--trace-event-categories',
72
+ '--trace-event-file-pattern',
73
+ '--trace-require-module',
74
+ '--unhandled-rejections',
75
+ '--use-largepages',
76
+ '--v8-pool-size',
77
+ '--watch-kill-signal',
78
+ '--watch-path',
79
+ '-C',
80
+ '-e',
81
+ '-r',
82
+ ])
@@ -0,0 +1,271 @@
1
+ // The own runtime behind the runtime seam of X5 part B (src/edge/runtime.js on branch speed-x5-fix3, read at commit 4728035f):
2
+ // the frame's worker (src/edge/worker.js) calls an adapter module with five things, and this module is one. Nothing else of
3
+ // the frame knows which runtime runs.
4
+ //
5
+ // load({cfg, ports, log, onWorkerError}) -> {fallback?} cfg.own = {wasmUrl, glueUrl, workerUrl} (URLs of the build output of
6
+ // edge/browser and of this folder's worker); ports[0] leads to the
7
+ // file route (see "the file route's port" below)
8
+ // start({module, argv, env, cwd, mounts, files, linux, linuxSrc, stdin, timeoutMs, parallelism}) -> proc
9
+ // proc {readStdout(n), readStderr(n), writeStdin(bytes), closeStdin()}; the readers give a Uint8Array, or null at the end
10
+ // signal(proc, n) exit(proc) -> {exitCode, reason} teardown() stats() -> {service, frameRtt} release()
11
+ //
12
+ // What differs from the SDK adapter: there is one root file system (the route's tree), so `mounts` is not used; the program's
13
+ // threads and children are the runtime's own Workers (hub.js), which `release()` ends.
14
+ //
15
+ // The file route's port. The hub asks `fsRoute.handle(method, args, data)` for every file call of the program; here that is a
16
+ // message on ports[0], {own: 'fs', id, method, args, data}, answered with {id, reply} where reply is {value} or {error: {code,
17
+ // message}} (a Uint8Array value for `read`). The side that owns the Overlay answers with `OwnFsRoute.handle` (fs-own-route.js).
18
+ // The receiving side is service-receiver.js. What is left to join with the channel service of the fix round: its port handler must
19
+ // pass `own` messages to it (src/edge/service-port.js knows only the SDK's `method` messages).
20
+ import { addCounts } from './wasm-counters.js'
21
+ import { OwnRuntime } from './hub.js'
22
+ import { shimSource } from '../shim.js'
23
+ import { SHIM_POST } from './shim-post.js'
24
+
25
+ export const name = 'own'
26
+
27
+ const SHIM_PATH = '/.wmd-edge/linux.cjs'
28
+ let deps = { OwnRuntime, fetch: (...a) => fetch(...a), compile: (b) => WebAssembly.compile(b) }
29
+ let rt = null
30
+ let port = null
31
+ let route = null
32
+ let runP = null
33
+ let state = null
34
+
35
+ /** Tests put fakes here. */
36
+ export function setDeps(d) {
37
+ deps = { ...deps, ...d }
38
+ }
39
+
40
+ class Pipe {
41
+ #chunks = []
42
+ #waiters = []
43
+ #done = false
44
+ /** fix7 (F1): bytes that came in, and bytes that came after end() (nobody reads those) */
45
+ bytes = 0
46
+ late = 0
47
+ taken = 0
48
+ push(b) {
49
+ // an empty write is nothing to deliver; a reader that stops at an empty chunk (worker.js pump) must not be stopped by one (fix7 F1)
50
+ if (!b.length) return
51
+ this.bytes += b.length
52
+ if (this.#done) this.late += b.length
53
+ if (this.#waiters.length) this.#waiters.shift()(b)
54
+ else this.#chunks.push(b)
55
+ }
56
+ end() {
57
+ this.#done = true
58
+ for (const w of this.#waiters.splice(0)) w(null)
59
+ }
60
+ // up to n bytes of the next chunk, or null at the end
61
+ async read(n) {
62
+ if (this.#chunks.length) return this.#take(n)
63
+ if (this.#done) return null
64
+ const b = await new Promise(r => this.#waiters.push(r))
65
+ if (b === null) return null
66
+ this.#chunks.unshift(b)
67
+ return this.#take(n)
68
+ }
69
+ #take(n) {
70
+ const c = this.#chunks[0]
71
+ if (c.length <= n) {
72
+ this.taken += c.length
73
+ return this.#chunks.shift()
74
+ }
75
+ this.#chunks[0] = c.subarray(n)
76
+ this.taken += n
77
+ return c.subarray(0, n)
78
+ }
79
+ }
80
+
81
+ function portRoute(p) {
82
+ let next = 1
83
+ const pending = new Map()
84
+ p.onmessage = e => {
85
+ const m = e.data
86
+ const w = m && pending.get(m.id)
87
+ if (!w) return
88
+ pending.delete(m.id)
89
+ w(m.reply)
90
+ }
91
+ const route = {
92
+ // hub.js `signal(n)` queues the signal here; the side that owns the file tree keeps the queue the program's shim polls
93
+ queueSignal: (id, n) => {
94
+ route.handle('sigq', [id, n], new Uint8Array(0))
95
+ },
96
+ handle: (method, args, data) =>
97
+ new Promise(resolve => {
98
+ const id = next++
99
+ pending.set(id, resolve)
100
+ p.postMessage(globalThis.__wmdFsTime ? { own: 'fs', id, method, args, data, t0: performance.timeOrigin + performance.now() } : { own: 'fs', id, method, args, data })
101
+ }),
102
+ close: () => {
103
+ // the receiving side ends the children the run started (service-receiver.js)
104
+ try {
105
+ p.postMessage({ own: 'bye' })
106
+ } catch {
107
+ // the port is gone
108
+ }
109
+ for (const w of pending.values()) w({ error: { code: 'EIO', message: 'the file route closed' } })
110
+ pending.clear()
111
+ },
112
+ }
113
+ return route
114
+ }
115
+
116
+ const sha256 = async (u8) => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', u8)), (b) => b.toString(16).padStart(2, '0')).join('')
117
+
118
+ // fix7 (F11): the files that run are the ones the build wrote. edge/browser/build.sh puts HASHES.txt (sha256, size, name) next to them; the wasm and the glue are
119
+ // fetched, hashed and compared before the first Worker starts. A file that differs is an error that names it (the page remembers a runtime that does not load and
120
+ // the program runs in the guest); a missing list or a file the list does not name is counted (stats().files) and the run goes on with what is there.
121
+ async function checkFiles(own, files) {
122
+ const base = own.wasmUrl.replace(/[^/?#]*([?#].*)?$/, '')
123
+ let text = null
124
+ try {
125
+ const r = await deps.fetch(own.hashesUrl || base + 'HASHES.txt')
126
+ if (r.ok !== false) text = await r.text()
127
+ } catch {
128
+ // no list
129
+ }
130
+ if (text === null) {
131
+ files.missing++
132
+ return {}
133
+ }
134
+ const want = new Map()
135
+ for (const line of String(text).split('\n')) {
136
+ const [hash, size, name] = line.trim().split(/\s+/)
137
+ if (name && /^[0-9a-f]{64}$/.test(hash)) want.set(name, { hash, size: Number(size) })
138
+ }
139
+ const out = {}
140
+ for (const [key, name] of [['wasmUrl', 'wmd_browser_bg.wasm'], ['glueUrl', 'wmd_browser.js']]) {
141
+ const w = want.get(name)
142
+ if (!w) {
143
+ files.unlisted++
144
+ continue
145
+ }
146
+ const bytes = new Uint8Array(await (await deps.fetch(own[key])).arrayBuffer())
147
+ files.checked++
148
+ if (bytes.length !== w.size || (await sha256(bytes)) !== w.hash) {
149
+ files.mismatch++
150
+ throw new Error(`the runtime's files do not match HASHES.txt: ${name} (size ${bytes.length}, listed ${w.size}); not run`)
151
+ }
152
+ files.ok++
153
+ if (key === 'wasmUrl') out.module = await deps.compile(bytes)
154
+ }
155
+ return out
156
+ }
157
+
158
+ export async function load({ cfg, ports, log, onWorkerError }) {
159
+ const own = cfg.own || {}
160
+ if (!own.wasmUrl || !own.glueUrl || !own.workerUrl) throw new Error('rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl')
161
+ if (own.fsTime) globalThis.__wmdFsTime = true // counters of the file calls (hub.js, fs-own-route.js): off unless the page option fsTime=1
162
+ port = ports[0]
163
+ route = portRoute(port)
164
+ state = { own, log, onWorkerError, out: new Pipe(), err: new Pipe(), t0: performance.now(), signals: [], files: { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 }, module: undefined, stages: {} }
165
+ const tc = performance.now()
166
+ const ok = await checkFiles(own, state.files)
167
+ state.stages.check = performance.now() - tc
168
+ state.module = ok.module
169
+ return {}
170
+ }
171
+
172
+ export async function start({ module, argv, env, cwd, files = {}, linux, linuxSrc, stdin = 'closed' }) {
173
+ const s = state
174
+ let tm = performance.now()
175
+ const lap = (name) => {
176
+ const now = performance.now()
177
+ s.stages[name] = now - tm
178
+ tm = now
179
+ }
180
+ const program = new Uint8Array(await (await deps.fetch(module)).arrayBuffer())
181
+ lap('program')
182
+ let args = argv
183
+ const shim = { ...files }
184
+ if (linux) {
185
+ const text = shimSource(await (await deps.fetch(linuxSrc || '/wasm/linux.cjs')).text(), linux, { symlinks: false }) + SHIM_POST
186
+ shim['linux.cjs'] = text
187
+ args = ['--require', SHIM_PATH, ...argv]
188
+ }
189
+ await route.handle('shim', [shim], new Uint8Array(0))
190
+ lap('shim')
191
+ if (globalThis.__wmdFsTime) await route.handle('timing', ['on'], new Uint8Array(0))
192
+ rt = await deps.OwnRuntime.start({
193
+ wasmUrl: s.own.wasmUrl,
194
+ ...(s.module ? { module: s.module } : {}),
195
+ glueUrl: s.own.glueUrl,
196
+ workerUrl: s.own.workerUrl,
197
+ fsRoute: route,
198
+ onOut: (fd, b) => {
199
+ if (s.stages.firstOut === undefined && b.length && s.runT0) s.stages.firstOut = performance.now() - s.runT0
200
+ ;(fd === 2 ? s.err : s.out).push(b)
201
+ },
202
+ onLog: d => s.log?.(typeof d === 'string' ? d : JSON.stringify(d)),
203
+ stack: s.own.stack,
204
+ })
205
+ lap('boot')
206
+ s.runT0 = performance.now()
207
+ const envList = Object.entries({ HOME: '/root', ...(env || {}) }).map(([k, v]) => `${k}=${v}`)
208
+ runP = rt
209
+ .run({ program, args, env: envList, node: true, cwd, stdin: stdin === 'pipe' ? 'pipe' : 'null', tty: {}, children: s.own.children !== false, exec: linux && linux.execPath, shim: !!linux })
210
+ .then(
211
+ r => ({ exitCode: r.code, reason: 'exit' }),
212
+ e => ({ exitCode: 1, reason: 'error: ' + String((e && e.message) || e) }),
213
+ )
214
+ .then(r => ((s.stages.run = performance.now() - s.runT0), s.out.end(), s.err.end(), r))
215
+ return {
216
+ readStdout: n => s.out.read(n),
217
+ readStderr: n => s.err.read(n),
218
+ writeStdin: async bytes => rt.writeStdin(bytes),
219
+ closeStdin: async () => rt.closeStdin(),
220
+ }
221
+ }
222
+
223
+ /** 9 ends the program at once; the others are for the runtime to deliver to the program (see hub.js `signal`). */
224
+ export async function signal(proc, n) {
225
+ if (n === 9) return rt?.terminate()
226
+ return rt?.signal ? rt.signal(n) : undefined
227
+ }
228
+
229
+ export async function exit() {
230
+ const r = await runP
231
+ if (globalThis.__wmdFsTime && rt) {
232
+ // the counters go into the route's ring as note lines (150 characters each) for the page to read: `FSTAT <hub|route> <json>`
233
+ try {
234
+ const t = (await route.handle('timing', ['read'], new Uint8Array(0))).value
235
+ for (const [side, v] of [['hub', rt.fsTiming], ['route', t]]) {
236
+ const j = JSON.stringify(v)
237
+ for (let i = 0; i < j.length; i += 140) await route.handle('note', [`FSTAT ${side} ${i / 140} ` + j.slice(i, i + 140)], new Uint8Array(0))
238
+ }
239
+ } catch {
240
+ // no counters then
241
+ }
242
+ }
243
+ return r
244
+ }
245
+
246
+ export async function teardown() {
247
+ rt?.terminate()
248
+ }
249
+
250
+ export function release() {
251
+ rt?.terminate()
252
+ route?.close?.()
253
+ return rt ? 1 : 0
254
+ }
255
+
256
+ export async function stats() {
257
+ // fix7 item 15: the WebAssembly objects of this start: this Worker's and each runtime Worker's, summed (`workers` is how many answered)
258
+ let wasm = null
259
+ try {
260
+ const mine = globalThis.__wmdWasmCounters ? globalThis.__wmdWasmCounters.snapshot() : null
261
+ const theirs = rt ? await rt.collectCounts(400) : []
262
+ let sum = mine
263
+ for (const t of theirs) sum = addCounts(sum, t.c)
264
+ if (sum) wasm = { ...sum, workers: theirs.length }
265
+ if (wasm) wasm.kinds = [...(globalThis.__wmdWasmCounters?.kinds?.() || []), ...theirs.flatMap((t) => (t.c && t.c.kinds) || [])]
266
+ } catch {
267
+ // no counters then
268
+ }
269
+ // fix7 (F1): what the runtime handed the pipes: a lost error text shows as bytes after the end or as a smaller count than the worker saw
270
+ return { service: null, frameRtt: null, ...(wasm ? { wasm } : {}), ...(rt?.capiStats ? { capi: rt.capiStats } : {}), ...(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 } } : {}) }
271
+ }