@threadedstack/wmd-web 0.1.38 → 0.1.41

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 (68) hide show
  1. package/README.md +239 -2
  2. package/RELEASE.json +97 -53
  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 +321 -12
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/boot-setup.js +175 -0
  54. package/src/gowasm/make-pins-module.mjs +35 -0
  55. package/src/gowasm/pins-data.js +162 -0
  56. package/src/gowasm/setup.js +167 -0
  57. package/src/gowasm/twin-fetch.js +27 -0
  58. package/src/host/chan-service.js +33 -6
  59. package/src/host/chan-services.js +29 -4
  60. package/src/host/ckpt.js +78 -0
  61. package/src/host/csp-reason.js +64 -0
  62. package/src/host/ctl.js +30 -8
  63. package/src/host/edge-go.js +94 -4
  64. package/src/host/edge-host.js +58 -3
  65. package/src/host/gowasm-guard.js +11 -1
  66. package/src/host/gowasm-worker.js +90 -35
  67. package/src/host/pinned-fetch.js +436 -0
  68. package/wmdpack.wasm +0 -0
@@ -0,0 +1,275 @@
1
+ // X5 (item 3 of default1 round 2): node in the frame for a page that embeds the package. src/boot.js edgeSetup() decides the cases that need
2
+ // none of these modules (the switch off, no site) and loads this module for the rest; web/page/ckpt.js is one such page.
3
+ //
4
+ // const e = await edgeSetup({ origin, env }) (src/boot.js; the frame site's origin is the one thing a page must give)
5
+ // containerBundle({ ..., edgeNode: e.edgeNode }) undefined when node runs in the guest: the bundle is as without the switch
6
+ // bootWmd({ ..., edge: e.bootOption() }) one per boot (a restore's too); undefined when node runs in the guest
7
+ // e.prepare() after the boot: the frame is made and the runtime compiled when the page is idle
8
+ // e.close() the last booted machine ended (not one a restore replaces): the runs of every machine
9
+ // that got a boot option of this setup end, the kept frame goes; a node start of any of
10
+ // them that comes later is answered with the counted fallback (the stub runs node in the guest)
11
+ // e.use, e.reason the plan (src/edge/plan.js): node in the frame, or why it runs in the guest
12
+ // e.bridge(), e.site, e.prepared the current machine's bridge (its stats()), the site (src/edge/site.js), the prepare's result
13
+ //
14
+ // The site's origin must serve the frame's files with the headers of web/README.md "The frame's site", and the page's own server must serve
15
+ // /wasm/edgejs.wasm and allow the site in its frame-src. A site that does not answer is found by the frame's load (src/edge/page.js
16
+ // FRAME_LOAD_GRACE_MS): the run, and every later one while the site is down, gives the guest's node with the reason counted.
17
+ import { NODE_PATHS, nodeMajor, nodeVersion, planEdge, planPython, pythonSpecTools } from './plan.js'
18
+ import { bridgesPerMachine, edgeBridge } from './bridge.js'
19
+ import { RT_DEFAULT, runtimeConfig } from './runtime.js'
20
+ import { frameSite, iframeProbe } from './site.js'
21
+ import { SANDBOX } from './sbx/common.js'
22
+ import { filesGate } from './sbx/gate.js'
23
+ import { pythonModuleFor } from './python-module.js'
24
+ import { pythonCapMiB } from './python-plan.js'
25
+ import { FRAME_CAP_WHY, frameCapOf, hintOf } from './sbx/cap.js'
26
+
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
+ let wmHint = ''
29
+
30
+ /** What the browser needs for node in the frame: SharedArrayBuffer in a cross-origin isolated page, and wasm exceptions. */
31
+ export function edgeBrowserOk(g = globalThis) {
32
+ return typeof g.SharedArrayBuffer === 'function' && g.crossOriginIsolated === true && typeof g.WebAssembly?.Exception === 'function'
33
+ }
34
+
35
+ /** The reason of a setup that asked for a frame site another live container of the page already has (X5 check 2, F2). */
36
+ export const SITE_IN_USE = 'the frame site is in use'
37
+ /**
38
+ * X5 check 2, F2: a frame site has one live setup in a page. Two containers on one site are one browser origin: a program of one answers a
39
+ * BroadcastChannel message of the other and reads its storage, so the page keeps the rule "one origin per container" (D-582) itself. A setup
40
+ * holds its site from edgeSetupIn() (and again from a bootOption() after a close()) until close(). `share` (the option shareSite) lets
41
+ * containers that trust each other live on one site, and only when every one of them asked for it.
42
+ */
43
+ const sitesOf = new WeakMap() // page (its document) -> Map(origin -> {owners: Set, shared})
44
+ const NO_DOC = {}
45
+ const originKey = origin => {
46
+ try {
47
+ return new URL(origin).origin
48
+ } catch {
49
+ return String(origin)
50
+ }
51
+ }
52
+ function claimSite(doc, origin, owner, share) {
53
+ const page = doc || NO_DOC
54
+ const sites = sitesOf.get(page) || sitesOf.set(page, new Map()).get(page)
55
+ const key = originKey(origin)
56
+ const held = sites.get(key)
57
+ if (!held) return sites.set(key, { owners: new Set([owner]), shared: !!share }), true
58
+ if (held.owners.has(owner)) return true
59
+ if (!held.shared || !share) return false
60
+ return held.owners.add(owner), true
61
+ }
62
+ function releaseSite(doc, origin, owner) {
63
+ const sites = sitesOf.get(doc || NO_DOC)
64
+ const key = originKey(origin)
65
+ const held = sites?.get(key)
66
+ if (held?.owners.delete(owner) && !held.owners.size) sites.delete(key)
67
+ }
68
+
69
+ const idleOf = g => (typeof g.requestIdleCallback === 'function' ? f => g.requestIdleCallback(f, { timeout: 2000 }) : f => g.setTimeout(f, 0))
70
+
71
+ /**
72
+ * @param {object} o
73
+ * @param {string} [o.origin] the frame site's origin; none: the library makes the frame itself (a sandboxed frame) and the page fetches the files from o.base
74
+ * @param {object[]} [o.sources] the places the files of node come from when there is no origin, tried in order: {kind: 'tgz', url} | {kind: 'file', base} | {kind: 'url', url}
75
+ * @param {string|string[]} [o.base] the short form: one file base (or a list of them) is [{kind: 'file', base}]; with neither, the default of src/edge/base.js
76
+ * @param {{pins: object[], pkg: object|null}} [o.pinned] the pins of the files and the package they name (src/edge/pins.js loadEdgePins; boot.js edgeSetup loads it)
77
+ * @param {function} [o.fetchFiles] test hook: replaces the page's fetch of the files ({files, ...} or {error})
78
+ * @param {string[]} [o.env] the container's environment (its NODE_VERSION picks the node major; WMD_EDGE=0 turns it off)
79
+ * @param {string} [o.user] the container's user; [o.readonlyRoot], [o.hasTmpfs] as in planEdge
80
+ * @param {number} [o.p9port] the 9P service's port of the container's files (564) and [o.root] its `at` ('rootfs')
81
+ * @param {object} [o.settings] what linux.cjs reads (arch, hostname, cpus)
82
+ * @param {string} [o.rt] the runtime (src/edge/runtime.js, 'own'); [o.handIn] what the caller hands it
83
+ * @param {object} [o.watch] the frame watch's limits (src/edge/page.js runEdge); keepFrame defaults to true
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 {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
+ * @param {boolean} [o.prepare] false: no frame is made before the first node command (default true, with keepFrame)
87
+ * @param {function} [o.onLog] (id, record) of each run, and the site's events ({type: 'site', ...})
88
+ * @param {function} [o.onBridge] (bridge) when a machine's bridge is made
89
+ * @param {{on: number, off: object}} counts the plan's decisions, counted (src/boot.js edgePlanCounts)
90
+ */
91
+ 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 sandbox = !siteOrigin
94
+ const origin = sandbox ? SANDBOX : siteOrigin
95
+ // 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
96
+ // (src/edge/plan.js; `imagePython` is what the caller found in the image: src/edge/python-plan.js findPython and imagePythonVersion)
97
+ const common = { enabled: true, env, user, readonlyRoot, hasTmpfs, hasJspi: edgeBrowserOk(win), rt }
98
+ const nodePlan = planEdge({ ...common, nodePath: NODE_PATHS[0] })
99
+ const plan = nodePlan
100
+ const capMiB = pythonMaxMiB || pythonCapMiB({ memoryMB, swapMB, ramMiB }) // the python's memory cap follows the machine (page option pymax decides when given)
101
+ const pyPlan = imagePython ? planPython({ ...common, python: pythonAsk, imagePython, memoryMB, swapMB, ramMiB }) : { use: false, reason: 'no python asked for' }
102
+ const off = reason => {
103
+ counts.off[reason] = (counts.off[reason] || 0) + 1
104
+ return { use: false, reason, edgeNode: undefined, edgeTools: [], bootOption: () => undefined, prepare: () => null, close: () => {}, bridge: () => null, site: null, prepared: null }
105
+ }
106
+ if (!nodePlan.use && !pyPlan.use) {
107
+ // neither: the reason is the one of the runtime the image is for (a node image says node's; an image with no NODE_VERSION says python's)
108
+ return off(imagePython && !nodeMajor(env) ? pyPlan.reason : nodePlan.reason)
109
+ }
110
+ // a cap of none (a page's own `frameCap: 0`, src/edge/sbx/cap.js): node and python run in the guest, one calm reason, nothing fetched or made
111
+ if (sandbox && frameCapOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? '', frameCapOpt) === 0) return off(FRAME_CAP_WHY(0))
112
+ if (imagePython && !pyPlan.use && nodePlan.use && pythonAsk !== false) counts.off[`python: ${pyPlan.reason}`] = (counts.off[`python: ${pyPlan.reason}`] || 0) + 1
113
+ // the module the idle prepare compiles: node's when node is on (as before), else the image python's (python only for an image that has no node)
114
+ const mainIsPython = pyPlan.use && /^python/.test(String(main[0] || '').split('/').pop())
115
+ const pyMod = pyPlan.use ? pythonModuleFor(pyPlan.version) : null
116
+ const nodeWasm = sandbox ? 'sbx:edgejs.wasm' : edgeWasm
117
+ const prepWasm = nodePlan.use && !mainIsPython ? nodeWasm : sandbox ? `sbx:${pyMod.file}` : pyMod.url
118
+ const owner = {} // this setup's token: its kept frames, its users of the site and its hold of the site are its own (src/edge/page.js, P1)
119
+ if (!sandbox && !claimSite(doc, origin, owner, shareSite)) {
120
+ onLog(0, { type: 'site', inUse: true, origin })
121
+ return off(SITE_IN_USE)
122
+ }
123
+ counts.on++
124
+ const keepFrame = watch.keepFrame !== false
125
+ // 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
+ let codeP = null
127
+ let hookP = null // the test hook's one fetch (a result with an error is not kept)
128
+ const copyAll = f => Object.fromEntries(Object.entries(f).map(([k, v]) => [k, v.slice(0)]))
129
+ const sbx = !sandbox ? null : {
130
+ code: null,
131
+ loadCode: () => (codeP ||= import('./frame-code.gen.js').then(m => (sbx.code = m.FRAME_CODE))),
132
+ hint: () => wmHint || hintOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? ''), // what this page's first frame found, else the engine's usual form (an order: the probe still decides)
133
+ frameCap: frameCapOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? '', frameCapOpt), // the most frames this page has alive at once (src/edge/sbx/cap.js)
134
+ onCaps: c => void (c && c.worker && (wmHint = c.worker)),
135
+ // one fetch for the page's life (src/edge/sbx/files.js fetchEdgeFilesOnce): the prepare frame and the run frame ask for the same files, and every
136
+ // asker gets its own copy of the bytes (a frame takes its files by transfer, which empties what it was given). The gate (src/edge/sbx/gate.js)
137
+ // owns the download: it starts once, a node start waits for it at most FILES_WAIT_MS, and its events tell the page what it did.
138
+ files: async () => {
139
+ const r = await gate.join()
140
+ if (r.error) return r
141
+ const files = copyAll(r.files)
142
+ // python's module goes with them once it is in (a start that needs it waits for the gate below; a failed gate leaves python in the guest)
143
+ if (pyGate && pyGate.state() === 'ready') {
144
+ const pr = await pyGate.join()
145
+ if (!pr.error) Object.assign(files, copyAll(pr.files))
146
+ }
147
+ return { ...r, files }
148
+ },
149
+ }
150
+ const gate = !sandbox
151
+ ? null
152
+ : filesGate({
153
+ get: onProgress =>
154
+ fetchFilesOpt
155
+ ? (hookP ||= Promise.resolve().then(fetchFilesOpt).then(r => (r && r.error && (hookP = null), r), e => ((hookP = null), Promise.reject(e))))
156
+ : import('./sbx/files.js').then(m => m.fetchEdgeFilesOnce({ ...fetchOpts, sources, base, pins: pinned && pinned.pins, pkg: pinned && pinned.pkg, onProgress })),
157
+ onEvent: e => onLog(0, e),
158
+ ...(filesWaitMs !== undefined ? { waitMs: filesWaitMs } : {}),
159
+ ...(filesRetryMs !== undefined ? { retryMs: filesRetryMs } : {}),
160
+ ...(filesProgressMs !== undefined ? { progressMs: filesProgressMs } : {}),
161
+ })
162
+ // X25: python's module is a second package (@threadedstack/wmd-python, the pins of src/edge/python-pins.js), fetched by its own gate and handed to the frame
163
+ // with the other files. Only when the page's plan took the image's python; `python: false` makes no gate and no request.
164
+ const pyGate = !sandbox || !pyPlan.use
165
+ ? null
166
+ : filesGate({
167
+ get: () =>
168
+ fetchPythonOpt
169
+ ? Promise.resolve().then(fetchPythonOpt)
170
+ : import('./python-source.js').then(m => m.fetchPythonModule(pyPlan.version)).then(r => (r.error ? r : { files: { python: r.bytes }, source: r.source, reasons: r.reasons })),
171
+ onEvent: e => onLog(0, { ...e, python: true }),
172
+ ...(filesWaitMs !== undefined ? { waitMs: filesWaitMs } : {}),
173
+ ...(filesRetryMs !== undefined ? { retryMs: filesRetryMs } : {}),
174
+ ...(filesProgressMs !== undefined ? { progressMs: filesProgressMs } : {}),
175
+ })
176
+ const site = frameSite({ origin, probe: sandbox ? () => sbx.files().then(r => !r.error) : iframeProbe({ doc, win }), onEvent: e => onLog(0, e) })
177
+ // what a start waits for: node's files (the gate of item 12); and when the page planned python, python's module too. A start that is python's goes to the guest while
178
+ // python's module is loading or when its fetch failed; a start of node goes to the guest only while it is loading (a failed fetch leaves python in the guest).
179
+ const gateFor = async job => {
180
+ if (!sandbox) return null
181
+ const g = await gate.forStart()
182
+ if (g || !pyGate) return g
183
+ const isPython = !!(job && job.cfg && job.cfg.python)
184
+ const pg = await pyGate.forStart()
185
+ if (pg && (isPython || pyGate.state() === 'loading')) return { ...pg, reason: String(pg.reason).replace("node's files", "python's module") }
186
+ if (isPython) {
187
+ const r = await gate.join()
188
+ if (!r.error && !(r.files && r.files.linuxpy)) return { fallback: true, reason: "the pins of the frame's files have no linux.py (the shim of python)" }
189
+ }
190
+ return null
191
+ }
192
+ let current = null
193
+ const pers = new Set() // every boot option's bridges: close() reaches all of them (X5 fix3p P5)
194
+ // one bridge per machine (src/edge/bridge.js bridgesPerMachine), made when its first message comes; each boot option has its own (a second
195
+ // machine of the page, booted with its own options, keeps its own bridges), and the site is the page's: a restore keeps what it knows
196
+ const bootOption = () => {
197
+ const mine = bridgesPerMachine(machine => {
198
+ current = edgeBridge({
199
+ site,
200
+ vm: machine,
201
+ p9port,
202
+ origin,
203
+ ...(sandbox ? { linuxSrc: 'sbx:linux.cjs' } : {}),
204
+ python: pyPlan.use ? { path: pyPlan.python, version: pyPlan.version, maxMiB: capMiB } : null,
205
+ settings: { arch: 'arm64', hostname: 'wmd-web', cpus: 1, ...settings, execPath: plan.node },
206
+ rt,
207
+ handIn: sandbox ? { ...handIn, sbx: true } : handIn,
208
+ edgeWasm: sandbox ? 'sbx:edgejs.wasm' : edgeWasm,
209
+ nodeVersion: nodeVersion(env), // the image's node version: the frame's node reports it (check5 F5)
210
+ watch: { ...watch, keepFrame },
211
+ // a sandboxed frame needs the files first: a start that finds them still loading after FILES_WAIT_MS runs in the guest (the bridge answers a result with
212
+ // `fallback` so; it is no failure of the frame)
213
+ run: (...a) => gateFor(a[0]).then(g => g || Promise.all([import('./page.js'), sandbox ? sbx.loadCode() : null]).then(([{ runEdge }]) => runEdge({ ...a[0], owner, ...(sandbox ? { sbx } : {}) }, ...a.slice(1)))),
214
+ onLog,
215
+ doc,
216
+ owner,
217
+ })
218
+ onBridge(current)
219
+ return current
220
+ })
221
+ pers.add(mine)
222
+ // F2: a boot after close() takes the site again; when another container took it meanwhile this option only refuses (the guest runs node)
223
+ if (!sandbox && !claimSite(doc, origin, owner, shareSite)) mine.close()
224
+ return {
225
+ port: p9port,
226
+ root,
227
+ rt, // the runtime decides what the service looks at before a start (children, listing size: src/edge/runtime.js)
228
+ busy: () => mine.busy(),
229
+ onMessage: (m, machine) => mine.onMessage(m, machine),
230
+ }
231
+ }
232
+ const e = {
233
+ use: true,
234
+ reason: '',
235
+ edgeNode: nodePlan.use ? plan.node : undefined,
236
+ prepares: prepWasm, // the module the idle prepare compiles: node's, unless the image has no node or its main program is python
237
+ edgeTools: pyPlan.use ? pythonSpecTools(pyPlan.python) : [], // the stub over the image's python (containerBundle's edge.tools)
238
+ python: pyPlan.use ? { path: pyPlan.python, version: pyPlan.version } : undefined,
239
+ bootOption,
240
+ site,
241
+ bridge: () => current,
242
+ prepared: null,
243
+ pythonReady: () => (pyGate ? pyGate.begin() : Promise.resolve(null)), // python's module: the one download (the prepare starts it too); tests and the page's progress read it
244
+ files: sbx ? sbx.files : undefined, // the page's fetch of the files of node (shared by the frames of this page)
245
+ /**
246
+ * X5 default1 round 2 (B2.2): the frame of the site is made when the page is idle and fetches and compiles the runtime and node
247
+ * (src/edge/page.js prepareEdge), so that the first node command compiles nothing. Once per setup; none without kept frames. A frame
248
+ * whose page loads without the frame's script (nothing answers at the site) marks the site down: node commands then run in the guest at
249
+ * once, with the reason.
250
+ */
251
+ prepare() {
252
+ if (!prepare || !keepFrame || e.prepared) return e.prepared
253
+ const p = (e.prepared = { asked: Math.round(performance.now()) })
254
+ const go = async () => {
255
+ if (sandbox) pyGate?.begin() // python's module comes with them
256
+ 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
+ const { prepareEdge } = await import('./page.js')
258
+ 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 } : {}) }
260
+ p.started = Math.round(performance.now())
261
+ const r = await prepareEdge({ origin, cfg, doc, win, owner, ...(sandbox ? { sbx } : {}) })
262
+ Object.assign(p, r, { ended: Math.round(performance.now()) })
263
+ if (r.down) site.markDown(r.error)
264
+ else if (r.errorKind === 'runtime') site.markDown(r.error, { kind: 'runtime' }) // X5 fix2 F4: a file of the runtime, the program or the settings did not load
265
+ }
266
+ idleOf(win)(() => go().catch(err => (p.error = String((err && err.message) || err).slice(0, 200))))
267
+ return p
268
+ },
269
+ close() {
270
+ pers.forEach(per => per.close())
271
+ if (!sandbox) releaseSite(doc, origin, owner)
272
+ },
273
+ }
274
+ return e
275
+ }
package/src/edge/shim.js CHANGED
@@ -143,7 +143,9 @@ const SIG_EMIT_TO = ` if (process.listenerCount(name) > 0) {
143
143
  process.emit(name, name, sig);
144
144
  } else if (SIG_IGNORED.has(sig)) {
145
145
  // the default action of this signal leaves the program running
146
- } else {`
146
+ } else {
147
+ // 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)
148
+ try { ctl({ op: 'signal_taken', n: sig, handled: false }); } catch (_) {}`
147
149
 
148
150
  export function shimSource(src, settings, { symlinks = true } = {}) {
149
151
  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]]) {
@@ -0,0 +1,101 @@
1
+ // X5 fix3 R5: the watchers of the frame's fs.watch (linux.cjs's FSWatcher: watch_start, watch_poll_all, watch_stop). WASIX has no inotify and the page
2
+ // has no event from the machine's Overlay, so the page compares scans of it: the names below the watched directory (or the watched file) with the
3
+ // last scan, and reports what node's inotify watcher reports: `rename` for a name that came, went or is another inode now, `change` for a file whose
4
+ // size or mtime changed and for a regular file that was made (its first write or touch). The files of the guest and of the frame are the same Overlay, so a write by either shows. The scan runs at most every
5
+ // max(MIN_SCAN_MS, 5 times what the last scan cost) ms for each watcher (the shim asks every 10 ms), and a scan reads at most MAX_ENTRIES names.
6
+
7
+ import { S_IFDIR, S_IFMT, S_IFREG } from '../fs/pack.js'
8
+
9
+ export const MIN_SCAN_MS = 50
10
+ export const MAX_ENTRIES = 50_000
11
+ export const MAX_WATCHERS = 1024
12
+ const utf8 = b => new TextDecoder().decode(Uint8Array.from(b, c => c.charCodeAt(0)))
13
+
14
+ export class PathWatches {
15
+ /** @param {import('../fs/overlay.js').Overlay} fs @param {() => number} now milliseconds */
16
+ constructor(fs, now) {
17
+ this.fs = fs
18
+ this.now = now
19
+ this.list = new Map()
20
+ this.nextId = 0
21
+ }
22
+
23
+ /** Start watching a node (a directory or a file). Returns the id, or null when there are too many watchers. */
24
+ start(node, name, recursive) {
25
+ if (this.list.size >= MAX_WATCHERS) return null
26
+ const w = { id: ++this.nextId, node, name, recursive: !!recursive, isDir: this.#isDir(node), snap: null, last: 0, interval: MIN_SCAN_MS, gone: false }
27
+ this.#rescan(w)
28
+ this.list.set(w.id, w)
29
+ return w.id
30
+ }
31
+
32
+ stop(id) {
33
+ this.list.delete(Number(id))
34
+ }
35
+
36
+ /** The events of every watcher whose turn it is: [{id, eventType, filename}]. */
37
+ poll() {
38
+ const events = []
39
+ for (const w of this.list.values()) {
40
+ const t = this.now()
41
+ if (t - w.last < w.interval) continue
42
+ const before = w.snap
43
+ this.#rescan(w)
44
+ const oldInodes = new Set([...before.values()].map(v => v.split(':', 1)[0]))
45
+ for (const [name, sig] of w.snap) {
46
+ const old = before.get(name)
47
+ if (old === undefined) {
48
+ events.push({ id: w.id, eventType: 'rename', filename: name })
49
+ // a file made (not one moved in from another name) has been written or touched too: inotify's IN_MODIFY / IN_ATTRIB, which node reports as `change`
50
+ const [ino, type] = sig.split(':')
51
+ if (!oldInodes.has(ino) && Number(type) === S_IFREG) events.push({ id: w.id, eventType: 'change', filename: name })
52
+ } else if (old !== sig) events.push({ id: w.id, eventType: old.split(':', 2).join(':') !== sig.split(':', 2).join(':') ? 'rename' : 'change', filename: name })
53
+ }
54
+ for (const name of before.keys()) if (!w.snap.has(name)) events.push({ id: w.id, eventType: 'rename', filename: name })
55
+ }
56
+ return events
57
+ }
58
+
59
+ #isDir(n) {
60
+ return (this.fs.getattr(n).mode & S_IFMT) === S_IFDIR
61
+ }
62
+
63
+ // sig: "ino:type" for what makes a name another thing, then ":size:mtime" for a file
64
+ #sig(n) {
65
+ const a = this.fs.getattr(n)
66
+ const type = a.mode & S_IFMT
67
+ return type === S_IFDIR ? `${a.ino}:${type}` : `${a.ino}:${type}:${a.size}:${a.mtime}`
68
+ }
69
+
70
+ #rescan(w) {
71
+ const t0 = this.now()
72
+ const snap = new Map()
73
+ if (!w.isDir) {
74
+ // a file: its own name; a file with no name left is gone (one `rename`, then nothing)
75
+ const a = this.fs.getattr(w.node)
76
+ if (a.nlink > 0 && !w.gone) snap.set(w.name, this.#sig(w.node))
77
+ else w.gone = true
78
+ } else {
79
+ let budget = MAX_ENTRIES
80
+ const walk = (dir, prefix) => {
81
+ let l
82
+ try {
83
+ l = this.fs.listing(dir)
84
+ } catch {
85
+ return
86
+ }
87
+ for (let i = 0; i < l.names.length && budget > 0; i++, budget--) {
88
+ const name = prefix + utf8(l.names[i])
89
+ const n = l.nodes[i]
90
+ snap.set(name, this.#sig(n))
91
+ if (w.recursive && (this.fs.getattr(n).mode & S_IFMT) === S_IFDIR) walk(n, name + '/')
92
+ }
93
+ }
94
+ walk(w.node, '')
95
+ }
96
+ w.snap = snap
97
+ const t1 = this.now()
98
+ w.interval = Math.max(MIN_SCAN_MS, 5 * (t1 - t0))
99
+ w.last = t1
100
+ }
101
+ }
@@ -14,6 +14,14 @@ import { SPAWN_EXIT, markScanner, newSpawnMark } from './spawn-guard.js'
14
14
 
15
15
  installWasmCounters(globalThis) // fix7 item 15
16
16
  const log = text => postMessage({ type: 'log', text })
17
+ // X5 fix2 F4 (hold 1): the text of an error that ends a run. The page shows its first line (a fallback's reason). Chromium's stack starts with the message;
18
+ // Firefox's and Safari's list frames only, so the message goes first and the stack after it.
19
+ const errorText = e => {
20
+ const stack = e && e.stack ? String(e.stack) : ''
21
+ const msg = e && e.message !== undefined ? `${e.name || 'Error'}: ${e.message}` : ''
22
+ if (!msg) return stack || String(e)
23
+ return stack.startsWith(msg) ? stack : stack ? msg + '\n' + stack : msg
24
+ }
17
25
  const dec = new TextDecoder()
18
26
  const enc = new TextEncoder()
19
27
  let adapter = null
@@ -37,8 +45,24 @@ async function input(m) {
37
45
  else if (m.signal) await adapter.signal(proc, m.signal) // the page sends only the signals that end a program (src/edge/bridge.js)
38
46
  }
39
47
 
40
- onmessage = async ({ data: { cfg, ports, in: inp } }) => {
48
+ onmessage = async ({ data: { cfg, ports, in: inp, tf, kept, prepare } }) => {
41
49
  if (inp) return input(inp)
50
+ if (prepare) {
51
+ // X5 default1 round 2 (B2.2): no program runs; the adapter makes ready what the frame keeps for the starts to come (frame.js, page.js prepareEdge)
52
+ try {
53
+ const t0 = performance.now()
54
+ adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg)
55
+ const r = adapter.prepare ? await adapter.prepare({ cfg, kept }) : { kept: false }
56
+ const k = adapter.keep ? adapter.keep() : null
57
+ if (k) postMessage({ type: 'keep', keep: k })
58
+ return done({ prepared: !!k, prepareMs: Math.round(performance.now() - t0), ...(r.stages ? { stages: r.stages } : {}) })
59
+ } catch (e) {
60
+ const kind = errorKindOf(e, false) // X5 fix2 F4: a prepare that finds the runtime's files missing says so (the page marks the site down)
61
+ return done({ error: String((e && e.message) || e).slice(0, 300), ...(kind ? { errorKind: kind } : {}) })
62
+ }
63
+ }
64
+ // X5 default1 round 2 (B2.1): when the frame made this Worker and when its script ran (the adapter takes them with the option marks)
65
+ if (typeof tf === 'number') globalThis.__wmdFwMarks = { frame: tf, fw: performance.timeOrigin + performance.now() }
42
66
  const res = {}
43
67
  let loading = true // fix7 F12: an error while the runtime's files load is told to the page as such (it remembers it)
44
68
  try {
@@ -47,6 +71,7 @@ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
47
71
  const loaded = await adapter.load({
48
72
  cfg,
49
73
  ports,
74
+ kept, // X5 default1 round 2 (B2.1): what an earlier start of this frame left (frame.js); an adapter that keeps nothing ignores it
50
75
  log,
51
76
  onWorkerError: why => done({ error: 'the runtime lost a Worker: ' + why }),
52
77
  })
@@ -63,11 +88,15 @@ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
63
88
  files: cfg.files,
64
89
  linux: cfg.linux,
65
90
  linuxSrc: cfg.linuxSrc,
91
+ python: cfg.python, // X25 gate 1
66
92
  stdin: cfg.stdin || 'closed',
67
93
  timeoutMs: cfg.timeoutMs,
68
94
  parallelism: cfg.parallelism,
69
95
  })
70
96
  res.setupMs = performance.now() - t0
97
+ // X5 default1 round 2 (B2.1): the compiled modules and the program's bytes for the frame to keep (frame.js; never relayed to the page)
98
+ const k = adapter.keep ? adapter.keep() : null
99
+ if (k) postMessage({ type: 'keep', keep: k })
71
100
  log('process started after ' + res.setupMs.toFixed(0) + ' ms')
72
101
  const t1 = performance.now()
73
102
  postMessage({ type: 'step', name: 'ready', ms: res.setupMs }) // the process runs: the page may tell the guest it has started
@@ -113,7 +142,7 @@ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
113
142
  Object.assign(res, await adapter.stats())
114
143
  // no adapter.teardown(): the runtime's Workers end when the frame terminates this one (fix9, see done)
115
144
  } catch (e) {
116
- res.error = String((e && e.stack) || e)
145
+ res.error = errorText(e)
117
146
  const kind = errorKindOf(e, loading) // fix 11 (F-M): the runtime's wasm that is missing is found in start(), after load()
118
147
  if (kind) res.errorKind = kind
119
148
  }
@@ -0,0 +1,175 @@
1
+ // X6 default part 3, item 1: bootWmd does the twin's whole setup alone. Called first thing by bootWmd (src/boot.js) with its options; for each 9P
2
+ // service whose files hold bundle/config/config.json (what containerBundle returns, src/host/ctl.js) it adds the stub mounts to the spec text and sets
3
+ // the service's `gowasm` field with the mount destinations read from that spec. The consumer writes no twin line.
4
+ //
5
+ // What a consumer MAY pass, on bootWmd only:
6
+ // gowasm: false the twin is off; nothing is changed, nothing is said
7
+ // gowasm: { sources: [...] } the ordered sources of the twin's module (default GOWASM_SOURCES_DEFAULT; src/host/pinned-fetch.js)
8
+ // gowasm: { base: 'https://.../gowasm' } one file source: <base>/compile-<go release>.wasm (an app that serves its own copy)
9
+ // gowasm: { limits: {...} } beatLimitMs, readyLimitMs, runLimitMs, earlyReply, lateFallbackAt (tests)
10
+ // gowasm: { pins, packages } the pins and the package names (tests)
11
+ // gowasm: true as undefined, but a missing source list is said (one event) instead of silently off
12
+ // A service that already has its own `gowasm` field (a caller that calls gowasmSetup itself, the test page) is left as it is; a spec that already has
13
+ // the mounts (a caller that still passes `edge` to containerBundle) gets nothing added: adding twice changes nothing.
14
+ // The image decides: the channel service's Worker takes the stub mounts out of the spec for an image with no Go compile (GoEdge.pruneBundle) or when the
15
+ // twin's code cannot be loaded (noTwin), before the guest reads the spec; an image with a Go release that has no pin keeps the stubs, and its compiles go
16
+ // to the guest with one calm event (GoEdge, rule 'unpinned').
17
+ // A checkpoint: the service files are part of the boot key, so the spec text (with or without the twin's stub mounts) says which choice a checkpoint was taken with.
18
+ // A boot that restores takes the choice its checkpoint was taken with (chooseTwin, below), the way X24's RAM layout does (chooseLayout): a checkpoint taken
19
+ // without the twin restores into a boot that would have the twin on, and runs without it (one event, rule 'checkpoint'); a checkpoint taken with the twin keeps it,
20
+ // and one taken with the twin ALWAYS restores, also in a boot that has the twin off (gowasm: false, no source, a setup that is not usable): it keeps its own spec
21
+ // text (the guest has the stub mounts), the service's gowasm field says `off` (no Worker, nothing fetched), every compile runs in the guest, one event, rule
22
+ // 'checkpoint-twin'. A header with no boot description, or whose spec text is neither, changes nothing.
23
+ import { addEdgeToolMounts } from '../host/ctl.js'
24
+ import { bootKeyForChoice, sampleKey, specChoice } from '../host/ckpt.js'
25
+ import { GOWASM_SOURCES_DEFAULT, planOf } from './setup.js'
26
+
27
+ export { GOWASM_SOURCES_DEFAULT }
28
+ const CONFIG = 'bundle/config/config.json'
29
+ // the spec text does not depend on the sources, so a boot that does not use the twin still makes the text a checkpoint with the twin would hold
30
+ const TEXT_ONLY = [{ kind: 'file', base: 'https://twin.invalid/' }]
31
+ const textOf = raw => {
32
+ const d = raw && typeof raw === 'object' && !(raw instanceof Uint8Array) && 'data' in raw ? raw.data : raw
33
+ return typeof d === 'string' || d instanceof Uint8Array ? d : new Uint8Array(d)
34
+ }
35
+
36
+ /**
37
+ * @param {object} o bootWmd's options
38
+ * @returns {Promise<{o: object, events: object[], plain: object, twinOn: boolean, texts: {i: number, port: number, plain: string|Uint8Array, twin: string}[], off: string}>}
39
+ * o is the same object when nothing changes; events are {t: 'gowasm-off', why} (at most one). For chooseTwin: `plain` is the options as given, `twinOn` says
40
+ * whether `o` has the twin, `texts` holds, per 9P service the twin could change, its spec text without and with the twin (even when the twin is off for
41
+ * this boot: a checkpoint taken with it is told apart), and `off` says why it is off (empty when on).
42
+ */
43
+ export async function twinForBoot(o) {
44
+ const events = []
45
+ const res = (o2, extra = {}) => ({ o: o2, events, plain: o, twinOn: false, texts: [], off: '', offO: null, ...extra })
46
+ try {
47
+ const opt = o && o.gowasm
48
+ const given = opt && typeof opt === 'object' ? opt : {}
49
+ const sources = given.sources ?? (given.base ? [{ kind: 'file', base: given.base }] : GOWASM_SOURCES_DEFAULT)
50
+ const services = o && o.channels && Array.isArray(o.channels.services) ? o.channels.services : []
51
+ const mine = services.map((s, i) => [s, i]).filter(([s]) => s && (s.kind === '9p' || s.kind === 1) && s.files && typeof s.files === 'object' && !s.gowasm && s.files[CONFIG] !== undefined)
52
+ if (!mine.length) return res(o)
53
+ const consumerOff = opt === false || !sources
54
+ const plan = planOf({ sources: consumerOff ? TEXT_ONLY : sources, pins: given.pins, packages: given.packages, limits: given.limits || {} })
55
+ const consumerWhy = opt === false ? 'gowasm: false' : 'no source'
56
+ // the text of the spec with the stub mounts is decided by the tools alone, not by the sources or the limits: when this boot does not use the twin (the consumer's
57
+ // choice, or a setup that is not usable) it is made from the caller's pins and, when those are not usable, from the package's own, so a checkpoint taken with
58
+ // the twin can still be told apart and restored (part 6)
59
+ let textPlan = plan
60
+ if (plan.why) {
61
+ textPlan = planOf({ sources: TEXT_ONLY, pins: given.pins, packages: given.packages, limits: {} })
62
+ if (textPlan.why) textPlan = planOf({ sources: TEXT_ONLY, limits: {} })
63
+ }
64
+ /** The services with the twin's spec text (and a gowasm field made by `p`), the texts to tell, or null when a spec is not JSON. */
65
+ const build = (p, fieldOf) => {
66
+ const next = services.slice()
67
+ const texts = []
68
+ for (const [svc, i] of mine) {
69
+ const raw = svc.files[CONFIG]
70
+ let spec
71
+ try {
72
+ spec = JSON.parse(typeof raw === 'string' ? raw : new TextDecoder().decode(raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw))
73
+ } catch {
74
+ return { bad: "the bundle's config is not JSON" }
75
+ }
76
+ if (!spec || !Array.isArray(spec.mounts)) return { bad: "the bundle's config has no mounts" }
77
+ spec.mounts = addEdgeToolMounts(spec.mounts, p.edge.tools)
78
+ const text = JSON.stringify(spec, null, 2) + '\n'
79
+ const given0 = textOf(raw)
80
+ if (!(typeof given0 === 'string' && given0 === text)) texts.push({ i, port: svc.port, plain: given0, twin: text })
81
+ next[i] = { ...svc, files: { ...svc.files, [CONFIG]: typeof raw === 'string' && raw === text ? raw : text }, gowasm: fieldOf(p.service(spec.mounts.map(m => m.destination))) }
82
+ }
83
+ return { next, texts }
84
+ }
85
+ /** What a restore of a checkpoint taken with the twin gets when the twin is off for this boot: the twin's text (the stubs stay), a gowasm field that says off. */
86
+ const offOf = (why, built) => (built.next ? { ...o, channels: { ...o.channels, services: built.next.map((sv, i) => (sv !== services[i] ? { ...sv, gowasm: { ...sv.gowasm, modules: [], preload: [], sources: undefined, off: why } } : sv)) } } : null)
87
+ const goOff = (why, event) => {
88
+ if (event) events.push({ t: 'gowasm-off', why })
89
+ const built = textPlan.why ? { bad: textPlan.why } : build(textPlan, f => f)
90
+ return built.next ? res(o, { texts: built.texts, off: why, offO: offOf(why, built) }) : res(o, { off: why })
91
+ }
92
+ if (plan.why) return consumerOff ? goOff(consumerWhy, false) : goOff(`the twin's setup is not usable: ${plan.why}`, true)
93
+ const built = build(plan, f => f)
94
+ if (built.bad) return consumerOff ? goOff(consumerWhy, false) : (events.push({ t: 'gowasm-off', why: built.bad }), res(o, { off: built.bad }))
95
+ if (consumerOff) {
96
+ if (opt === undefined) return res(o, { texts: built.texts, off: 'no source', offO: offOf('no source', built) })
97
+ if (opt === false) return res(o, { texts: built.texts, off: 'gowasm: false', offO: offOf('gowasm: false', built) })
98
+ events.push({ t: 'gowasm-off', why: 'no source of the twin is named: no sources and no default, so none is asked for' })
99
+ return res(o, { texts: built.texts, off: 'no source', offO: offOf('no source', built) })
100
+ }
101
+ return res({ ...o, channels: { ...o.channels, services: built.next } }, { twinOn: true, texts: built.texts })
102
+ } catch (e) {
103
+ return { o, events: [{ t: 'gowasm-off', why: `the twin's setup failed: ${(e && e.message) || e}` }], plain: o, twinOn: false, texts: [], off: 'failed', offO: null }
104
+ }
105
+ }
106
+
107
+ /**
108
+ * X6 default part 4: a restore takes the twin choice its checkpoint was taken with. `v` is twinForBoot's result and `header` the checkpoint's (or a base
109
+ * snapshot's) header; the only thing read of it is which of the two spec texts the first 9P service's recorded key matches (specChoice). Returns
110
+ * {o, events}: `o` is v.o unless the checkpoint was taken without the twin and this boot would have it (then the options as given, no stub mount, no
111
+
112
+ * gowasm field, and one event {t: 'gowasm-off', rule: 'checkpoint', why}). A checkpoint that has the twin in a boot that has it off (gowasm: false, no source,
113
+ * an unusable setup) restores with its own spec text and a gowasm field that says `off` (part 6, see below). A header with no description, a text that
114
+ * is neither, or services that disagree change nothing: the usual check of the restore decides, as it did before. X5 would call the same two functions
115
+ * with its own mounts' texts (specChoice names the text; its setup function returns what twinForBoot returns).
116
+ */
117
+ export async function chooseTwin(v, header) {
118
+ const none = { o: v.o, events: [] }
119
+ if (!header || typeof header !== 'object' || !v.texts || !v.texts.length) return none
120
+ const rec = []
121
+ for (const t of v.texts) rec.push(await specChoice(header, t.i, t.port, CONFIG, { plain: t.plain, twin: t.twin }))
122
+ if (rec[0] === null || rec.some(r => r !== rec[0])) return none
123
+ if (rec[0] === 'plain') {
124
+ if (!v.twinOn) return none
125
+ return { o: v.plain, events: [{ t: 'gowasm-off', rule: 'checkpoint', why: 'the checkpoint was taken without the Go twin, so this machine runs without it (its compiles run in the guest)' }] }
126
+ }
127
+ if (v.twinOn) return none
128
+ // Part 6: a checkpoint taken with the twin always restores, whatever this boot's twin state. The twin is off for this boot (gowasm: false, no source, a setup
129
+ // that is not usable): the machine keeps the checkpoint's spec text (its guest has the stub mounts), no twin Worker is started, nothing of the twin is fetched,
130
+ // every compile runs in the guest (GoEdge started off answers each stub with the fallback), and one calm event says so. A spec that is not JSON has no
131
+ // twin text to make: the usual check of the restore decides and says what differs.
132
+ if (!v.offO) return none
133
+ const why = `the checkpoint was taken with the Go twin and the twin is off in this boot (${v.off || 'off'}): the machine keeps the twin's stub mounts and runs its compiles in the guest`
134
+ return { o: v.offO, events: [{ t: 'gowasm-off', rule: 'checkpoint-twin', why }], supersedes: true }
135
+ }
136
+
137
+ /**
138
+ * The events a boot says for its twin choice, once each: twinForBoot's own and chooseTwin's. When the checkpoint's choice supersedes (a checkpoint taken with the
139
+ * twin, a boot that has it off), the one event of the checkpoint's rule says it, with the reason, and the boot's own reason (an unusable setup) is in that text.
140
+ */
141
+ export function eventsOf(v, c) {
142
+ return c.supersedes ? c.events : [...v.events, ...c.events]
143
+ }
144
+
145
+ /**
146
+ * The sample keys of the spec text of each 9P service that has one that differs from what the boot description `desc` records ({serviceIndex: key}; empty
147
+ * when they all agree or there is no description): the services' texts after the twin choice against a boot key made before it (held assets, vm.restore()).
148
+ */
149
+ export async function specKeysDiffering(desc, services) {
150
+ const out = {}
151
+ if (!desc || !Array.isArray(desc.services) || !Array.isArray(services)) return out
152
+ for (let i = 0; i < services.length; i++) {
153
+ const raw = services[i] && services[i].files ? services[i].files[CONFIG] : undefined
154
+ if (raw === undefined) continue
155
+ const d = textOf(raw)
156
+ const key = await sampleKey(typeof d === 'string' ? new TextEncoder().encode(d) : d)
157
+ if (desc.services[i] && desc.services[i].bundle && desc.services[i].bundle[CONFIG] !== key) out[i] = key
158
+ }
159
+ return out
160
+ }
161
+
162
+ /**
163
+ * X6 fix 10 (F1): a base snapshot that is refused after the twin choice was made from its header (the late checks: fit, packs, a body that cannot be read) and
164
+ * whose boot falls back to a cold start takes the options' own twin choice back: `o` with the channels of `twin.o` (no checkpoint stub text, no `gowasm.off`),
165
+ * and, when a boot key was already made with the checkpoint's text (`bootDesc`), the key and description a cold boot of those options makes. One function for
166
+ * every refusal (boot.js baseRefused), so a refusal path added later cannot forget it. `layout` is {flat, maxPages} of the machine as it boots.
167
+ * @returns {Promise<{o: object, key: {key: string, desc: object}|null}>}
168
+ */
169
+ export async function putBackTwin(twin, o, bootDesc, layout) {
170
+ const back = { ...o, channels: twin.o.channels }
171
+ if (!bootDesc) return { o: back, key: null }
172
+ const keys = await specKeysDiffering(bootDesc, back.channels?.services)
173
+ if (!Object.keys(keys).length) return { o: back, key: null }
174
+ return { o: back, key: await bootKeyForChoice(bootDesc, layout, keys) }
175
+ }