@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,301 @@
1
+ // X5 part B: the file service route for container node outside the guest (switch edge=1).
2
+ //
3
+ // node runs in an isolated frame (src/edge/frame.js) on the runtime of the adapter in use (src/edge/runtime.js). The
4
+ // SDK adapter's runtime serves a path under a host mount by calling the embedder with (mount id, method, args) and
5
+ // waits for a reply (the SDK's experimental worker-to-native file protocol, pinned by src/edge/sdk/). This module answers those calls from the machine's
6
+ // own Overlay, the object the guest's 9P server reads and writes, so node and the guest see one
7
+ // tree. It is synchronous and transport-free: the channel service Worker (chan-service.js) takes
8
+ // requests off a MessagePort and calls handle(); tests call it directly.
9
+ //
10
+ // Methods the 0.19.1 SDK sends (measured in part A, docs/research/browser-speed-2026-11/x5/gate2a/
11
+ // hostfs3-*.json): stat(path), readDir(path), open(path, read, write, create, createNew, truncate,
12
+ // append), read(h, off, len), write(h, off, bytes), flush(h), close(h), fileStat(h), mkdir(path),
13
+ // remove(path), rename(from, to), setTimes(path, accessedNs, modifiedNs). Paths are relative to the
14
+ // mount. A metadata reply is {kind: 'file'|'directory', size, accessed, modified, created} with the
15
+ // times as decimal strings of nanoseconds; the SDK reads no mode, owner or link count from it.
16
+ // A reply is {value} or {error: {code, message}}.
17
+ //
18
+ // Names in the Overlay are byte strings (one char per byte); node's paths are UTF-16 strings, so
19
+ // they go through byteStr() on the way in and back through utf8() on the way out.
20
+
21
+ import {
22
+ EACCES, EBADF, EEXIST, EFBIG, EINVAL, EIO, EISDIR, ELOOP, ENAMETOOLONG, ENOENT, ENOSPC, ENOSYS, ENOTDIR, ENOTEMPTY, EPERM, EROFS, fail,
23
+ } from '../fs/errno.js'
24
+ import { CODES } from './codes.js'
25
+ import { resolveIn } from './resolve.js'
26
+ import { EdgeCtl } from './ctl.js'
27
+ import { Hist } from './hist.js'
28
+ import { S_IFDIR, S_IFLNK, S_IFMT, bytesOf, byteStr } from '../fs/pack.js'
29
+
30
+ const utf8 = s => new TextDecoder().decode(bytesOf(s))
31
+ const reply = value => ({ value })
32
+ const err = (code, message) => ({ error: { code, message: message || code } })
33
+
34
+ export { Hist, resolveIn }
35
+
36
+ /** What the SDK's bridge can carry in one reply: 512 KiB less its 8-byte header (the SDK adapter's bridge, pinned in src/edge/sdk/). */
37
+ export const REPLY_CAP = 512 * 1024 - 8
38
+
39
+ /** The methods this route answers (the SDK's own names). */
40
+ export const MAX_READ = REPLY_CAP
41
+ /** The most open handles one run (owner) may hold. */
42
+ export const MAX_HANDLES = 4096
43
+
44
+ export const METHODS = ['stat', 'readDir', 'open', 'read', 'write', 'flush', 'close', 'fileStat', 'mkdir', 'remove', 'rename', 'setTimes']
45
+ const KNOWN = new Set([...METHODS, 'ctl'])
46
+
47
+ /**
48
+ * What the Overlay's inode n looks like to the SDK. `kind` is 'directory' for a directory and 'file'
49
+ * for everything else (the SDK knows no other kind); times are decimal strings of nanoseconds, the
50
+ * only shape the SDK reads (a number, or milliseconds, is read wrongly or fails the start).
51
+ */
52
+ export function sdkStat(fs, n) {
53
+ return {
54
+ kind: (n.mode & S_IFMT) === S_IFDIR ? 'directory' : 'file',
55
+ size: fs.size(n),
56
+ accessed: String(n.atime),
57
+ modified: String(n.mtime),
58
+ created: String(n.ctime),
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Answers the SDK's file calls from an Overlay.
64
+ * @param {import('../fs/overlay.js').Overlay} fs
65
+ * @param {object} o
66
+ * @param {Object<string, {path: string, ro?: boolean}>} o.mounts mount id -> the container path it shows (relative to `root`)
67
+ * @param {string} [o.root] where the container's root is in the Overlay ('rootfs' under the guest's layout, '' for the Overlay's root)
68
+ */
69
+ export class EdgeFsRoute {
70
+ constructor(fs, { mounts, root = '' }) {
71
+ this.fs = fs
72
+ this.mounts = mounts
73
+ this.rootPath = root
74
+ this.handles = new Map() // h -> {n, ro, owner}
75
+ this.owned = new Map() // owner -> open handles it holds
76
+ this.next = 1
77
+ this.calls = {} // method -> {n, errors, workUs: Hist}
78
+ this.ctl = new EdgeCtl(fs, { root, mounts }) // linux.cjs's control requests (method 'ctl', mount 0), src/edge/ctl.js
79
+ }
80
+
81
+ #root() {
82
+ return this.rootPath ? this.fs.resolve(this.rootPath) : this.fs.root
83
+ }
84
+
85
+ // the inode `path` (a byte string, relative to the mount) leads to; `..` and absolute links stay inside the container root
86
+ #at(m, path, follow = true) {
87
+ const root = this.#root()
88
+ return resolveIn(this.fs, root, resolveIn(this.fs, root, root, byteStr(m.path), true), path, follow)
89
+ }
90
+
91
+ /** One request: {mount, method, args}. Returns the SDK's reply. */
92
+ handle(mount, method, args, owner = 0) {
93
+ const t0 = performance.now()
94
+ let res
95
+ try {
96
+ res = this.#serve(mount, method, Array.isArray(args) ? args : [args], owner)
97
+ } catch (e) {
98
+ res = e && e.errno !== undefined ? err(CODES[e.errno] || 'EIO', e.message) : err('EIO', String((e && e.message) || e))
99
+ }
100
+ const key = KNOWN.has(method) ? method : 'other' // a method name is the sender's: never an Object.prototype name as a key
101
+ const c = (this.calls[key] ||= { n: 0, errors: 0, errorCodes: {}, workUs: new Hist() })
102
+ c.n++
103
+ if (res.error) {
104
+ c.errors++
105
+ c.errorCodes[res.error.code] = (c.errorCodes[res.error.code] || 0) + 1
106
+ }
107
+ c.workUs.add((performance.now() - t0) * 1000)
108
+ return res
109
+ }
110
+
111
+ // a handle belongs to the run that opened it: another run's number is no handle
112
+ #h(h, owner) {
113
+ const e = this.handles.get(h)
114
+ if (!e || e.owner !== owner) fail(EBADF)
115
+ return e
116
+ }
117
+
118
+ #drop(h, e) {
119
+ this.handles.delete(h)
120
+ this.owned.set(e.owner, (this.owned.get(e.owner) || 1) - 1)
121
+ if (this.owned.get(e.owner) <= 0) this.owned.delete(e.owner)
122
+ this.fs.unref(e.n)
123
+ }
124
+
125
+ /** A run ended: its open handles are closed (the files' references go). Returns how many. */
126
+ releaseOwner(owner) {
127
+ let n = 0
128
+ for (const [h, e] of [...this.handles]) {
129
+ if (e.owner !== owner) continue
130
+ this.#drop(h, e)
131
+ n++
132
+ }
133
+ return n
134
+ }
135
+
136
+ #serve(mount, method, a, owner) {
137
+ const fs = this.fs
138
+ if (method === 'ctl') return reply(JSON.stringify(this.ctl.handle(String(a[0] ?? ''))))
139
+ // an own entry of the table only: 'constructor', '__proto__' and the like are no mounts
140
+ const m = (typeof mount === 'number' || typeof mount === 'string') && Object.hasOwn(this.mounts, mount) ? this.mounts[mount] : undefined
141
+ if (!m) return err('ENOENT', `no mount ${mount}`)
142
+ const rw = () => {
143
+ if (m.ro) fail(EROFS)
144
+ }
145
+ const path = () => byteStr(String(a[0] ?? ''))
146
+ switch (method) {
147
+ case 'stat':
148
+ return reply(sdkStat(fs, this.#at(m, path())))
149
+ case 'readDir': {
150
+ const dir = this.#at(m, path())
151
+ if (!dir.isDir()) fail(ENOTDIR)
152
+ const { names, nodes } = fs.listing(dir)
153
+ const out = new Array(names.length)
154
+ for (let i = 0; i < names.length; i++) {
155
+ let n = nodes[i]
156
+ if (n.type === S_IFLNK) {
157
+ try {
158
+ n = this.#at(m, byteStr(String(a[0] ?? '')) + '/' + names[i])
159
+ } catch (e) {
160
+ // a dangling link is listed as a file
161
+ }
162
+ }
163
+ out[i] = { name: utf8(names[i]), ...sdkStat(fs, n) }
164
+ }
165
+ // a listing the bridge cannot carry: refused here with its size, where the SDK would answer EIO with no reason
166
+ if (out.length > 1000) {
167
+ const bytes = new TextEncoder().encode(JSON.stringify({ value: out })).length
168
+ if (bytes > REPLY_CAP) return err('EIO', `directory has ${out.length} entries, its listing is ${bytes} bytes, over the bridge's cap of ${REPLY_CAP}`)
169
+ }
170
+ return reply(out)
171
+ }
172
+ case 'open': {
173
+ const create = !!(a[3] || a[4])
174
+ const trunc = !!a[5]
175
+ let n
176
+ try {
177
+ n = this.#at(m, path())
178
+ if (a[4] && create) fail(EEXIST)
179
+ } catch (e) {
180
+ if (e.errno !== ENOENT || !create) throw e
181
+ rw()
182
+ const parts = path().split('/').filter(s => s !== '')
183
+ const dir = this.#at(m, parts.slice(0, -1).join('/'))
184
+ n = fs.create(dir, parts.at(-1), 0o644, 0, 0)
185
+ }
186
+ if (trunc) rw()
187
+ if ((this.owned.get(owner) || 0) >= MAX_HANDLES) return err('EMFILE', `more than ${MAX_HANDLES} open files in one run`)
188
+ fs.open(n, { write: trunc, trunc })
189
+ fs.ref(n)
190
+ const h = this.next++
191
+ this.handles.set(h, { n, ro: !!m.ro, owner })
192
+ this.owned.set(owner, (this.owned.get(owner) || 0) + 1)
193
+ return reply(h)
194
+ }
195
+ case 'read': {
196
+ const { n } = this.#h(a[0], owner)
197
+ const off = Number(a[1] ?? 0)
198
+ const len = Number(a[2] ?? 0)
199
+ if (!Number.isFinite(off) || !Number.isFinite(len) || off < 0 || len < 0) fail(EINVAL)
200
+ // one reply carries at most what the bridge can (a short read is a read: the SDK asks for 64 KiB)
201
+ const got = fs.read(n, off, Math.min(len, MAX_READ))
202
+ const out = new Uint8Array(got.length)
203
+ out.set(got)
204
+ return reply(out)
205
+ }
206
+ case 'write': {
207
+ const h = this.#h(a[0], owner)
208
+ if (h.ro) fail(EROFS)
209
+ const b = a[2] instanceof Uint8Array ? a[2] : ArrayBuffer.isView(a[2]) ? new Uint8Array(a[2].buffer, a[2].byteOffset, a[2].byteLength) : Uint8Array.from(a[2] || [])
210
+ // as the guest's 9P server does (src/fs/9p/server.js Twrite): a non-finite offset is EFBIG; every other offset goes to the Overlay, which
211
+ // holds a write far out as a sparse file (a write at 2^40 makes a file of 1 TiB that holds only the chunk written: it is charged
212
+ // for the chunk, and refused with EFBIG past 2^52 or ENOSPC past maxUpperBytes). A negative or fractional offset cannot come
213
+ // over 9P (the wire has an unsigned integer) and is EINVAL here, as pwrite(2) has it (check4 F9).
214
+ const off = Number(a[1] ?? 0)
215
+ if (!Number.isFinite(off)) fail(EFBIG)
216
+ if (off < 0 || !Number.isInteger(off)) fail(EINVAL)
217
+ return reply(fs.write(h.n, off, b))
218
+ }
219
+ case 'flush':
220
+ this.#h(a[0], owner)
221
+ return reply(null)
222
+ case 'close': {
223
+ const h = this.handles.get(a[0])
224
+ if (h && h.owner === owner) this.#drop(a[0], h)
225
+ return reply(null)
226
+ }
227
+ case 'fileStat':
228
+ return reply(sdkStat(fs, this.#h(a[0], owner).n))
229
+ case 'mkdir': {
230
+ rw()
231
+ const parts = path().split('/').filter(s => s !== '')
232
+ if (parts.length === 0) fail(EEXIST)
233
+ const dir = this.#at(m, parts.slice(0, -1).join('/'))
234
+ fs.mkdir(dir, parts.at(-1), 0o755, 0, 0)
235
+ return reply(null)
236
+ }
237
+ case 'remove': {
238
+ rw()
239
+ const parts = path().split('/').filter(s => s !== '')
240
+ if (parts.length === 0) fail(EPERM)
241
+ const dir = this.#at(m, parts.slice(0, -1).join('/'))
242
+ const n = fs.lookup(dir, parts.at(-1))
243
+ fs.unlink(dir, parts.at(-1), n.isDir())
244
+ return reply(null)
245
+ }
246
+ case 'rename': {
247
+ rw()
248
+ const from = byteStr(String(a[0] ?? '')).split('/').filter(s => s !== '')
249
+ const to = byteStr(String(a[1] ?? '')).split('/').filter(s => s !== '')
250
+ if (!from.length || !to.length) fail(EINVAL)
251
+ const odir = this.#at(m, from.slice(0, -1).join('/'))
252
+ const ndir = this.#at(m, to.slice(0, -1).join('/'))
253
+ fs.rename(odir, from.at(-1), ndir, to.at(-1))
254
+ return reply(null)
255
+ }
256
+ case 'setTimes': {
257
+ rw()
258
+ const n = this.#at(m, path())
259
+ const s = {}
260
+ if (a[1] != null) s.atime = BigInt(a[1])
261
+ if (a[2] != null) s.mtime = BigInt(a[2])
262
+ fs.setattr(n, s)
263
+ return reply(null)
264
+ }
265
+ }
266
+ return err('ENOSYS', `edge fs: method ${method} is not served`)
267
+ }
268
+
269
+ /**
270
+ * The directories under the mounts whose listing would not fit one reply (what the page checks before it starts node:
271
+ * a program that lists one gets EIO, so the container runs in the guest instead). [{path (container path), entries, bytes}]
272
+ */
273
+ oversizeDirs() {
274
+ const out = []
275
+ const enc = new TextEncoder()
276
+ for (const m of Object.values(this.mounts)) {
277
+ const walk = (dir, path) => {
278
+ const { names, nodes } = this.fs.listing(dir)
279
+ if (names.length > 1000) {
280
+ const entries = names.map((n, i) => ({ name: utf8(n), ...sdkStat(this.fs, nodes[i]) }))
281
+ const bytes = enc.encode(JSON.stringify({ value: entries })).length
282
+ if (bytes > REPLY_CAP && !out.some(o => o.path === path)) out.push({ path, entries: names.length, bytes })
283
+ }
284
+ for (let i = 0; i < names.length; i++) if (nodes[i].isDir()) walk(nodes[i], (path === '/' ? '' : path) + '/' + utf8(names[i]))
285
+ }
286
+ try {
287
+ walk(this.#at(m, ''), '/' + m.path.replace(/^\/+|\/+$/g, ''))
288
+ } catch (e) {
289
+ // a mount whose directory is not there lists nothing
290
+ }
291
+ }
292
+ return out
293
+ }
294
+
295
+ /** Requests answered so far, by method. */
296
+ stats() {
297
+ const out = {}
298
+ for (const [k, c] of Object.entries(this.calls)) out[k] = { n: c.n, errors: c.errors, errorCodes: c.errorCodes, work: c.workUs.summary() }
299
+ return { methods: out, openHandles: this.handles.size }
300
+ }
301
+ }
@@ -0,0 +1,46 @@
1
+ // X5 part B: a histogram of durations, shared by the file route (service side) and the frame (sender side).
2
+
3
+ const LOG2_BUCKETS = 24 // 1 us .. about 8 s
4
+
5
+ /** A histogram of durations in microseconds, buckets of powers of two (bucket b: [2^(b-1), 2^b) us, bucket 0 under 1 us). */
6
+ export class Hist {
7
+ constructor() {
8
+ this.n = 0
9
+ this.sumUs = 0
10
+ this.maxUs = 0
11
+ this.neg = 0 // negative differences (clocks of two Workers disagree): counted, not binned
12
+ this.b = new Array(LOG2_BUCKETS).fill(0)
13
+ }
14
+
15
+ add(us) {
16
+ if (us < 0) {
17
+ this.neg++
18
+ us = 0
19
+ }
20
+ this.n++
21
+ this.sumUs += us
22
+ if (us > this.maxUs) this.maxUs = us
23
+ const b = us < 1 ? 0 : Math.min(LOG2_BUCKETS - 1, Math.floor(Math.log2(us)) + 1)
24
+ this.b[b]++
25
+ }
26
+
27
+ /** The value below which a fraction q of the samples lie, as the bucket's upper edge in us. */
28
+ quantileUs(q) {
29
+ if (!this.n) return 0
30
+ const want = Math.ceil(this.n * q)
31
+ let c = 0
32
+ for (let i = 0; i < this.b.length; i++) {
33
+ c += this.b[i]
34
+ if (c >= want) return i === 0 ? 1 : 2 ** i
35
+ }
36
+ return this.maxUs
37
+ }
38
+
39
+ summary() {
40
+ return {
41
+ n: this.n, meanUs: this.n ? +(this.sumUs / this.n).toFixed(1) : 0, maxUs: +this.maxUs.toFixed(1), neg: this.neg,
42
+ p50Us: this.quantileUs(0.5), p90Us: this.quantileUs(0.9), p99Us: this.quantileUs(0.99), buckets: this.b.slice(),
43
+ }
44
+ }
45
+ }
46
+
@@ -0,0 +1,106 @@
1
+ // X5 part B (edge=1 only): what the page and the channel service accept from the frame. The frame is less trusted than the page
2
+ // (a runtime, and what it runs, could be hostile), and an exception in the channel service ends the whole machine, so every field of
3
+ // every message is checked where it comes in and copied into a plain value. A message that does not pass ends its one run
4
+ // (exit 125, the reason on stderr: src/edge/page.js, service-host.js), never more.
5
+
6
+ export class BadMessage extends Error {}
7
+ const bad = text => {
8
+ throw new BadMessage(text)
9
+ }
10
+
11
+ export const KINDS_OUT = new Set(['stdout', 'stderr'])
12
+ const MAX_TEXT = 1 << 16 // a text field of a message, in characters
13
+ const MAX_DEPTH = 4
14
+ const MAX_KEYS = 200
15
+ const MAX_ITEMS = 1000
16
+
17
+ /** The most bytes one out message of the frame may carry (the frame writes in chunks far smaller; a larger one is not a program's write). */
18
+ export const MAX_OUT_BYTES = 8 << 20
19
+
20
+ /**
21
+ * A byte view that is exactly its bytes: the same Uint8Array when it already covers the whole of a plain ArrayBuffer (so that the caller may transfer
22
+ * its buffer), else a copy of the viewed bytes only, never the bytes of the buffer outside the view (check5 F7). More than MAX_OUT_BYTES is refused.
23
+ */
24
+ export function bytesView(b) {
25
+ if (ArrayBuffer.isView(b) && b.BYTES_PER_ELEMENT === 1) {
26
+ if (b.byteLength > MAX_OUT_BYTES) bad('bytes is larger than one write may be')
27
+ if (b instanceof Uint8Array && b.buffer instanceof ArrayBuffer && b.byteOffset === 0 && b.byteLength === b.buffer.byteLength) return b
28
+ return new Uint8Array(b.buffer, b.byteOffset, b.byteLength).slice() // a view of part of a buffer, a shared or a foreign buffer: copy the view's bytes
29
+ }
30
+ if (b instanceof ArrayBuffer) {
31
+ if (b.byteLength > MAX_OUT_BYTES) bad('bytes is larger than one write may be')
32
+ return new Uint8Array(b)
33
+ }
34
+ return bad('bytes is not a byte array')
35
+ }
36
+
37
+ /** A string field: a string, cut to max characters. */
38
+ export function text(s, what, max = MAX_TEXT) {
39
+ if (typeof s !== 'string') bad(`${what} is not a string`)
40
+ return s.length > max ? s.slice(0, max) : s
41
+ }
42
+
43
+ /** An exit code: a 32-bit integer (what process.exit takes), as the OS keeps it (0..255). Any other number is not an exit code (check5 F7). */
44
+ export function exitCodeOf(c) {
45
+ if (typeof c !== 'number' || !Number.isInteger(c) || c > 2147483647 || c < -2147483648) bad('exitCode is not a 32-bit integer')
46
+ return c & 255
47
+ }
48
+
49
+ /** A plain copy of data (the stats of a run): primitives, arrays and plain objects, cut by depth, number of keys and text length. */
50
+ export function plain(v, depth = 0) {
51
+ switch (typeof v) {
52
+ case 'string':
53
+ return v.length > MAX_TEXT ? v.slice(0, MAX_TEXT) : v
54
+ case 'number':
55
+ return Number.isFinite(v) ? v : null
56
+ case 'boolean':
57
+ return v
58
+ case 'undefined':
59
+ return undefined
60
+ case 'object':
61
+ break
62
+ default:
63
+ return undefined
64
+ }
65
+ if (v === null || depth >= MAX_DEPTH) return null
66
+ if (Array.isArray(v)) {
67
+ const n = Math.min(v.length, MAX_ITEMS)
68
+ const a = []
69
+ for (let i = 0; i < n; i++) a.push(plain(v[i], depth + 1) ?? null)
70
+ return a
71
+ }
72
+ if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) return null
73
+ const o = {}
74
+ let n = 0
75
+ for (const k of Object.keys(v)) {
76
+ if (k === '__proto__') continue
77
+ if (++n > MAX_KEYS) break
78
+ const x = plain(v[k], depth + 1)
79
+ if (x !== undefined) o[k] = x
80
+ }
81
+ return o
82
+ }
83
+
84
+ /**
85
+ * The page's look at a frame message (the x5relay field). Returns the message to use, a plain copy, or null for a type the page does not
86
+ * take (ignored). Throws BadMessage for a message of a taken type with a wrong field. Any other exception (a getter that throws) is the
87
+ * caller's to turn into the same end of the run.
88
+ */
89
+ export function cleanRelay(r) {
90
+ if (!r || typeof r !== 'object') return null
91
+ const type = r.type
92
+ if (type === 'log') return { type, text: text(r.text, 'log text') }
93
+ if (type === 'step') return { type, name: text(r.name, 'step name', 64), ms: typeof r.ms === 'number' && Number.isFinite(r.ms) ? r.ms : 0 }
94
+ if (type === 'out') {
95
+ if (!KINDS_OUT.has(r.kind)) bad('out kind is not stdout or stderr')
96
+ return { type, kind: r.kind, bytes: bytesView(r.bytes) }
97
+ }
98
+ if (type === 'done') {
99
+ const d = plain(r)
100
+ if (d.exitCode !== undefined) d.exitCode = exitCodeOf(d.exitCode)
101
+ for (const k of ['reason', 'error', 'spawnRefused', 'errorKind']) if (d[k] !== undefined && typeof d[k] !== 'string') bad(`done ${k} is not a string`)
102
+ if (d.fallback !== undefined && typeof d.fallback !== 'boolean') bad('done fallback is not a boolean')
103
+ return { ...d, type }
104
+ }
105
+ return null
106
+ }
@@ -0,0 +1,194 @@
1
+ // X5 part B (edge=1 only): what a `node` command line runs. Used by the plan (children: which program needs a process) and by the key under
2
+ // which a run that tried to start a process is remembered (service-host.js programKey). node's own options come first; an option that takes
3
+ // a separate value (`--env-file .env app.js`) is told from one that does not by a table built from `node --help` and `node --v8-options`
4
+ // (src/edge/node-opts.js, made by test/unit/data/gen-node-opts.mjs), so that the value is never taken for the program (check4 F6).
5
+ import { NODE_VALUE_OPTIONS } from './node-opts.js'
6
+
7
+ /** Options that show or check and never run the program: no process can start, so they get no key. */
8
+ const NO_RUN = new Set(['-v', '--version', '-h', '--help', '--v8-options', '--completion-bash', '-c', '--check'])
9
+ /** The ones among them that print the node build's own text (check5 F5). */
10
+ const OWN_TEXT = new Set(['-v', '--version', '-h', '--help', '--v8-options', '--completion-bash'])
11
+ /** The options whose value is code (the program is that code). */
12
+ const CODE = new Set(['-e', '--eval', '-p', '--print', '-pe', '-ep'])
13
+
14
+ /** The options that name a file or module that runs before the program. */
15
+ const PRELOAD = new Set(['-r', '--require', '--import', '--loader', '--experimental-loader'])
16
+
17
+ /**
18
+ * The words of the container's NODE_OPTIONS as node reads them: split at spaces, a double-quoted word keeps its spaces, a backslash takes the next
19
+ * character. Returns [] when the variable is not set. (node's own rule, src/node_options.cc ParseNodeOptionsEnvVar.)
20
+ */
21
+ export function nodeOptionsWords(env) {
22
+ let v = ''
23
+ for (const kv of env || []) if (typeof kv === 'string' && kv.startsWith('NODE_OPTIONS=')) v = kv.slice(13)
24
+ const out = []
25
+ let cur = ''
26
+ let quoted = false
27
+ let any = false
28
+ for (let i = 0; i < v.length; i++) {
29
+ const c = v[i]
30
+ if (c === '\\' && quoted && i + 1 < v.length) {
31
+ cur += v[++i]
32
+ any = true
33
+ } else if (c === '"') {
34
+ quoted = !quoted
35
+ any = true
36
+ } else if (c === ' ' && !quoted) {
37
+ if (any) out.push(cur)
38
+ cur = ''
39
+ any = false
40
+ } else {
41
+ cur += c
42
+ any = true
43
+ }
44
+ }
45
+ if (any) out.push(cur)
46
+ return out
47
+ }
48
+
49
+ /** Parses NODE_OPTIONS the way a command line is: the same fields (preloads, watch, ...), with no program. */
50
+ export function parseNodeOptions(env) {
51
+ const r = parseNodeArgs({ argv: ['node', ...nodeOptionsWords(env)] })
52
+ return r
53
+ }
54
+
55
+ const takesValue = name => NODE_VALUE_OPTIONS.has(name) || NODE_VALUE_OPTIONS.has(name.replace(/_/g, '-'))
56
+
57
+ /**
58
+ * Parses a node command line (hello.argv[0] is node).
59
+ * @returns {{prog: string, code: string, hasCode: boolean, stdin: boolean, noRun: boolean, rest: string[]}}
60
+ * options: the names of the options before the program (a value after `=` left off);
61
+ * prog: the program's file as typed ('' when there is none); code: the -e/-p code, all of it joined; stdin: the program comes from stdin;
62
+ * noRun: --version, --help and the like; printed: the option among them that prints the build's own text; run: the --run script; test, watch, sea: the option is on the line; rest: the arguments after the program.
63
+ */
64
+ export function parseNodeArgs(hello) {
65
+ const args = (hello.argv || []).slice(1).map(String)
66
+ const r = { prog: '', code: '', hasCode: false, stdin: false, noRun: false, printed: '', run: '', test: false, watch: false, sea: false, preloads: [], options: [], rest: [] }
67
+ let i = 0
68
+ for (; i < args.length; i++) {
69
+ const a = args[i]
70
+ if (a === '--') {
71
+ i++
72
+ break
73
+ }
74
+ if (a === '-') {
75
+ r.stdin = true
76
+ i++
77
+ break
78
+ }
79
+ if (!a.startsWith('-')) break
80
+ const eq = a.indexOf('=')
81
+ const name = eq > 0 ? a.slice(0, eq) : a
82
+ r.options.push(name) // every option before the program, as typed without its value (fix7 F5: which of them the frame cannot run as the guest does)
83
+ if (NO_RUN.has(name)) r.noRun = true
84
+ if (OWN_TEXT.has(name) && !r.printed) r.printed = name
85
+ if (name === '--run') r.run = eq > 0 ? a.slice(eq + 1) : (args[i + 1] ?? '') // a script of package.json, run in a shell: the value is the script, not the program
86
+ else if (name === '--test') r.test = true // the words after it are test files: node starts a child per file
87
+ else if (name === '--watch') r.watch = true // node starts a child that runs the program again at a change
88
+ else if (name === '--experimental-sea-config') r.sea = true // a build step that runs node's own binary
89
+ if (PRELOAD.has(name)) r.preloads.push(eq > 0 ? a.slice(eq + 1) : (args[i + 1] ?? '')) // code that runs before the program
90
+ if (CODE.has(name)) {
91
+ r.hasCode = true
92
+ r.code += (r.code ? '\n' : '') + (eq > 0 ? a.slice(eq + 1) : (args[++i] ?? ''))
93
+ continue
94
+ }
95
+ if (eq < 0 && takesValue(name)) i++
96
+ }
97
+ if (!r.stdin && i < args.length && !(r.hasCode && args[i].startsWith('-'))) {
98
+ // with -e or -p the rest are the code's arguments; without, the next word is the program
99
+ if (r.hasCode) r.rest = args.slice(i)
100
+ else {
101
+ r.prog = args[i]
102
+ r.rest = args.slice(i + 1)
103
+ }
104
+ } else if (r.stdin || r.hasCode) r.rest = args.slice(i)
105
+ if (!r.prog && !r.hasCode && !r.run && !r.test && !r.sea) r.stdin = true // no file, no code, no script: node reads its program from stdin
106
+ return r
107
+ }
108
+
109
+ /** An absolute path with . and .. and repeated slashes removed (text only, no link is followed). */
110
+ export function normPath(path, cwd) {
111
+ const parts = (path.startsWith('/') ? path : (cwd || '/') + '/' + path).split('/')
112
+ const out = []
113
+ for (const p of parts) {
114
+ if (!p || p === '.') continue
115
+ if (p === '..') out.pop()
116
+ else out.push(p)
117
+ }
118
+ return '/' + out.join('/')
119
+ }
120
+
121
+ /** A short hash of text (cyrb53), for the key of -e and -p code. */
122
+ export function hashText(s) {
123
+ let h1 = 0xdeadbeef
124
+ let h2 = 0x41c6ce57
125
+ for (let i = 0; i < s.length; i++) {
126
+ const c = s.charCodeAt(i)
127
+ h1 = Math.imul(h1 ^ c, 2654435761)
128
+ h2 = Math.imul(h2 ^ c, 1597334677)
129
+ }
130
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
131
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
132
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16)
133
+ }
134
+
135
+ export const NPM_NAME = /^(npm|npx)(-cli|-prefix)?(\.c?js)?$/
136
+ /** npm options (and npx's) with a separate value: `npm --prefix /app ci` has the command ci. */
137
+ const NPM_VALUE = new Set(['--prefix', '--workspace', '-w', '--registry', '--cache', '--userconfig', '--globalconfig', '--loglevel', '--tag', '--otp', '--omit', '--include', '--scope', '--location', '--install-strategy', '--before', '--package', '-p', '--call', '-c', '--node-options', '--cpu', '--os', '--libc'])
138
+ const NPM_RUN = new Set(['run', 'run-script', 'rum', 'urn', 'exec', 'x'])
139
+ /** npm's own names for one command (npm help npm: aliases), so that the key of `npm rum build` is the key of `npm run build`. */
140
+ const NPM_ALIAS = {
141
+ 'run-script': 'run', rum: 'run', urn: 'run', x: 'exec', ic: 'ci', 'clean-install': 'ci', cit: 'ci', 'clean-install-test': 'ci',
142
+ i: 'install', in: 'install', ins: 'install', inst: 'install', insta: 'install', instal: 'install', isnt: 'install', isnta: 'install', isntal: 'install', add: 'install',
143
+ }
144
+
145
+ /** The words of an npm command line (flags and their values left out) and the --prefix. */
146
+ function npmWords(rest) {
147
+ const words = []
148
+ let prefix = ''
149
+ for (let i = 0; i < rest.length; i++) {
150
+ const a = rest[i]
151
+ if (a === '--') {
152
+ words.push(...rest.slice(i + 1))
153
+ break
154
+ }
155
+ if (a.startsWith('-')) {
156
+ const eq = a.indexOf('=')
157
+ const name = eq > 0 ? a.slice(0, eq) : a
158
+ if (name === '--prefix') prefix = eq > 0 ? a.slice(eq + 1) : (rest[i + 1] ?? '')
159
+ if (eq < 0 && NPM_VALUE.has(name)) i++
160
+ continue
161
+ }
162
+ words.push(a)
163
+ }
164
+ return { words, prefix }
165
+ }
166
+
167
+ /**
168
+ * What a later run of the same program is called when an earlier one started a process in the frame, or null when no process can start
169
+ * (--version, --help, --check). The key names the program that runs:
170
+ * npm and npx: the project (cwd and --prefix), the sub-command and, for run and exec, the script or program;
171
+ * a file: its normalized place (`./a.js` and `a.js` are one), not its arguments;
172
+ * -e and -p: a hash of the code;
173
+ * stdin: one key for all (the code comes after the start, so it cannot be told apart then).
174
+ */
175
+ export function programKey(hello) {
176
+ const p = parseNodeArgs(hello)
177
+ if (p.noRun) return null
178
+ const cwd = hello.cwd || '/'
179
+ if (p.hasCode) return 'code:' + hashText(p.code) // -e and -p of the same code are one program
180
+ if (p.run) return `run:${normPath('.', cwd)}:${p.run}` // a script of the project's package.json: each is its own program
181
+ if (p.test) return `test:${normPath('.', cwd)}:${[p.prog, ...p.rest].filter(Boolean).map(w => (w.startsWith('-') ? w : normPath(w, cwd))).join(' ')}`
182
+ if (p.sea) return `sea:${normPath('.', cwd)}`
183
+ if (p.stdin) return 'stdin:'
184
+ const base = p.prog.split('/').pop()
185
+ if (NPM_NAME.test(base) || /\/node_modules\/npm\/bin\//.test(p.prog)) {
186
+ const { words, prefix } = npmWords(p.rest)
187
+ const sub = NPM_ALIAS[words[0]] || words[0] || ''
188
+ const names = sub === 'install' ? words.slice(1).join(',') : '' // npm install foo and npm install bar are two programs
189
+ const target = NPM_RUN.has(words[0]) || base.startsWith('npx') ? words[base.startsWith('npx') ? 0 : 1] || '' : ''
190
+ const name = base.startsWith('npx') ? 'npx' : 'npm'
191
+ return `${name}:${normPath(prefix || '.', cwd)}:${name === 'npx' ? '' : sub}${target ? ':' + target : ''}${names ? ':' + names : ''}`
192
+ }
193
+ return 'file:' + normPath(p.prog, cwd)
194
+ }