plexus-ui-engine 0.2.3

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
// FRAME-12: the host's JS face — `host.js`, beside `engine.js` in every
// bundle. `engine.js` imports it (wasm-bindgen's raw_module "./host.js"), and
// a module may import it from its own version's folder (`../host.js`).
//
// It holds no state. Everything a component needs arrives through `mount`'s
// context — `mount(target, { props, bus })` — and every function here reads
// only what it is handed, so a module that imports the `host.js` of another
// version is still on the page's one bus: the bus is the one it was given.
//
//   bus.call(method, params)         → Promise of the answer, FRAME-37:
//                                       the call's data events carrying `ok`,
//                                       `events` (itself) and `message` — what
//                                       rhx's call(…, "fold") folds; `ok`
//                                       false on an in-band error or refused,
//                                       the service's refusal, or the socket
//                                       dropping ("disconnected"), never sent
//                                       again; rejected only before the
//                                       socket, when the component's `uses`
//                                       does not name it
//   bus.live(spec)                   → { subscribe(fn) → unsubscribe, get(),
//                                       update(patch) } of { rows, status },
//                                       shared by spec; `fn` is called before
//                                       `subscribe` returns. FRAME-20:
//                                       `fn(value, change)` — the change
//                                       `{ upsert, remove }`, or `{ replace:
//                                       rows }` when whole. FRAME-19: the spec
//                                       may carry `when` (false: nothing asked)
//                                       and `debounce_ms`; `update({ params?,
//                                       changes_params?, when? })` moves them,
//                                       the host's registry keeping the time
//   bus.markdown(text)               → the engine's sanitized render as HTML,
//                                       what rhx's {@html markdown(text)} draws
//   bus.emit(topic, data, opts?)     page-wide, bare string topics; `plexus.…`
//                                       is the host's; never heard by the emitter.
//                                       FRAME-53: `{ sticky: true }` keeps it as
//                                       the topic's last event (a later emit on
//                                       the topic, sticky or not, replaces it)
//   bus.on(topic, fn, opts?)         → unsubscribe. FRAME-53: `{ last: true }`
//                                       calls `fn` at once with the topic's kept
//                                       event, if any (`plexus.booted` is kept)
//   bus.last(topic)                  → the topic's kept event, or undefined
//   bus.navigate(route)
//   bus.keys({ "ctrl+k": fn, "j": { to: fn, label, in_inputs, only, in_controls } })
//                                    → unsubscribe. FRAME-36: the module's
//                                       shortcuts, handled by the host on the
//                                       window (capture phase): a match is
//                                       never the page's or the browser's;
//                                       `fn({ key, chord, target })`. They go
//                                       with the module's destroy too
//   bus.slots.set(layout, slot, component, version?) → Promise; held to `uses`
//   bus.frame(target, opts)          → COMPS-2: a sandboxed frame in `target`
//                                       (`frame` below; CONTRACT.md "Frames")
//   bus.props                        the props now

// FRAME-16: the page's boot, in parallel — what an entrypoint calls:
//
//   const { start } = await import(`/app/${version}/host.js`); start(version);
//
// The socket is made, and the version's manifest.json and components.json
// asked, before engine.js is imported and the wasm instantiated; all three
// are handed to the wasm (`boot_started`), which adopts the socket. Nothing
// is kept here: everything goes to the wasm.
//
// UI-19: each of the version's files is asked at its content URL
// (`/app/f/<sha256>.<ext>`, `fileUrl`) when the page was served with it.
export async function start(version) {
  const socket = new WebSocket(socketUrl());
  const text = (file) => fetch(fileUrl(`/app/${version}/${file}`)).then((r) => (r.ok ? r.text() : null), () => null);
  const manifest = text("manifest.json");
  const components = text("components.json");
  const engine = await import(new URL("./engine.js", import.meta.url).href);
  await engine.default({ module_or_path: fileUrl(`/app/${version}/engine.wasm`) });
  engine.boot_started(version, socket, manifest, components);
}

// UI-19: the page's files by their content — the import map the service
// stamps first in the entrypoint (`<script type="importmap"
// id="plexus-ui-files">`): each `/app/<version>/<path>` of the version the
// page was served for, to `/app/f/<sha256>.<ext>`. The browser resolves
// every module import through it; `fileUrl` is the same for a fetch (the
// manifest, components.json, the wasm, a component's tree, handlers and
// sheet). A URL it does not name (another version's, a page served without
// it) is asked as it is.
let files = null;
function filesMap() {
  if (files) return files;
  try {
    files = JSON.parse(document.getElementById("plexus-ui-files")?.textContent || "{}").imports || {};
  } catch {
    files = {};
  }
  return files;
}
export function fileUrl(url) {
  return filesMap()[url] ?? url;
}

// UI-19: the service worker (`/app/sw.js`, the service's) keeps every
// `/app/f/…` answer across versions — cache-first, they never change — and
// is told the content URLs this version names, so it drops the ones no
// recent version names. Registered once the page is drawn; nothing waits
// on it, and a page served without a files map registers nothing.
export function keepFiles(version) {
  const urls = [...new Set(Object.values(filesMap()).filter((u) => u.startsWith("/app/f/")))];
  if (!urls.length || !("serviceWorker" in navigator) || !globalThis.isSecureContext) return;
  navigator.serviceWorker
    .register("/app/sw.js", { scope: "/" })
    .then(() => navigator.serviceWorker.ready)
    .then((r) => r.active?.postMessage({ type: "plexus-ui:files", version, urls }))
    .catch(() => {});
}

// The page's socket, as the wasm names it: over https the origin's /ws,
// else the stamped port (plexus-ws-port, else menger-ws-port) on the
// page's host.
function socketUrl() {
  if (location.protocol === "https:") return `wss://${location.host}/ws`;
  const meta = (name) => document.querySelector(`meta[name="${name}"]`)?.getAttribute("content") ?? "";
  const digits = (p) => /^[0-9]+$/.test(p);
  const port = [meta("plexus-ws-port"), meta("menger-ws-port")].find(digits) ?? "4455";
  return `ws://${location.hostname}:${port}`;
}

// STUDIO-32: a page whose session has ended goes to the tenant's sign-in —
// the URL its `<meta name="plexus-login" content="…">` names — with `next`,
// where to come back to (the page's path, query and hash; the whole URL when
// the sign-in is on another origin), once. The wasm calls `signedOut()` when
// a call is answered plexus-core's -32001 "Authentication required", or the
// socket cannot be opened and the page itself now wants a sign-in
// (`sessionGone`). A page that names no sign-in keeps its refusals: "none".
//
// No loop: the send is kept in sessionStorage (this tab's), and the page that
// loads next takes it — a page that came back from the sign-in and is
// answered -32001 again before any call of it is answered says so (a console
// warning, and `plexus.signed_out { sent: false }` on the bus) instead of
// sending the person round again: "said". A call answered (`signedIn()`)
// ends that: the page is signed in, and a later sign-out sends it again.
// Several refusals at once send it once: "sent".
const SENT_KEY = "plexus-login:sent";
let sending = false;
let cameBack = (() => {
  try {
    const at = sessionStorage.getItem(SENT_KEY);
    sessionStorage.removeItem(SENT_KEY);
    return at != null;
  } catch {
    return false;
  }
})();

// The page's sign-in as a URL (http or https), or null when it names none.
export function loginUrl() {
  const named = document.querySelector('meta[name="plexus-login"]')?.getAttribute("content")?.trim();
  if (!named) return null;
  try {
    const url = new URL(named, location.href);
    return url.protocol === "https:" || url.protocol === "http:" ? url : null;
  } catch {
    return null;
  }
}

export function signedOut() {
  const url = loginUrl();
  if (!url) return "none";
  if (sending) return "sent";
  const shown = url.origin === location.origin ? url.pathname : url.href;
  if (cameBack) {
    console.warn(`signed out: this page came back from ${shown} still without a session, so it is not sent there again — sign in, then reload`);
    return "said";
  }
  const here = location.pathname + location.search + location.hash;
  url.searchParams.set("next", url.origin === location.origin ? here : location.href);
  try {
    sessionStorage.setItem(SENT_KEY, String(Date.now()));
  } catch {}
  sending = true;
  location.assign(url.href);
  return "sent";
}

// A call was answered: the page is signed in.
export function signedIn() {
  cameBack = false;
}

// STUDIO-32: whether the page itself now wants a sign-in — asked when the
// socket cannot be opened (a refused upgrade is only a failure to a page):
// the page's own URL, asked again without following a redirect, answers a
// redirect or a 401. A server that is down answers nothing: false, and the
// socket is tried again as ever.
export async function sessionGone() {
  if (!loginUrl()) return false;
  try {
    const r = await fetch(location.pathname + location.search, { redirect: "manual", cache: "no-store", credentials: "same-origin" });
    return r.type === "opaqueredirect" || r.status === 401;
  } catch {
    return false;
  }
}

// FRAME-50: `fn` in a task of its own, posted behind the tasks the page has
// queued — the boot's mount yields between its sections through it, so an
// answer that arrived meanwhile is handled before the next section mounts. A
// MessageChannel's message: setTimeout clamps a chain of them to 4 ms, and
// scheduler.yield()'s continuation runs before the queued tasks — the answers
// the yield is for.
const turns = [];
let channel = null;
export function yieldTask(fn) {
  if (!channel) {
    channel = new MessageChannel();
    channel.port1.onmessage = () => turns.shift()?.();
  }
  turns.push(fn);
  channel.port2.postMessage(null);
}

// Imports a module (the wasm cannot `import()`).
export function importModule(url) {
  return import(url);
}

// The bus object a module is handed, over the wasm's handle of its member.
export function busOf(handle) {
  return Object.freeze({
    call: (method, params) => handle.call(method, params ?? {}),
    live: (spec) => store(handle.live(spec), spec?.key),
    emit: (topic, data, opts) => handle.emit(topic, data ?? null, opts),
    on: (topic, fn, opts) => handle.on(topic, fn, opts),
    last: (topic) => handle.last(topic),
    navigate: (route) => handle.navigate(route),
    keys: (map) => handle.keys(map),
    markdown: (text) => handle.markdown(String(text ?? "")),
    slots: Object.freeze({ set: (layout, slot, component, version) => handle.slots_set(layout, slot, component, version ?? undefined) }),
    frame: (target, opts) => frame(handle, target, opts),
    get props() {
      return handle.props();
    },
  });
}

// FRAME-20: a `live` collection as a store, over the wasm's handle. The
// handle hands each subscriber the move — `{ status, message?, replace: rows }`
// (the first call, a resync, a switch: whole) or `{ status, message?,
// upsert: [rows], remove: [keys] }` (the fold's change by key) — and the
// store keeps the rows and applies it: an upserted row replaces the one of
// its key in place, or comes last; a removed key goes. Each move is a new
// value and a new array of the rows kept, the same objects but the ones the
// change named, so a keyed each touches only those. `fn(value, change)`:
// the value as ever, `{ rows, status }` (and `message`), and the change —
// `{ replace: rows }` or `{ upsert, remove }`.
function store(handle, key) {
  const keyOf = (row) => {
    const k = row?.[key];
    return typeof k === "string" ? k : JSON.stringify(k ?? null);
  };
  return {
    get: () => handle.get(),
    update: (patch) => handle.update(patch),
    subscribe(fn) {
      let rows = [];
      let at = new Map();
      return handle.subscribe((move) => {
        let change;
        if (move.replace) {
          rows = move.replace;
          at = new Map(rows.map((r, i) => [keyOf(r), i]));
          change = { replace: rows };
        } else {
          rows = rows.slice();
          if (move.remove.length) {
            const gone = new Set(move.remove);
            rows = rows.filter((r) => !gone.has(keyOf(r)));
            at = new Map(rows.map((r, i) => [keyOf(r), i]));
          }
          for (const r of move.upsert) {
            const k = keyOf(r);
            const i = at.get(k);
            if (i === undefined) {
              at.set(k, rows.length);
              rows.push(r);
            } else {
              rows[i] = r;
            }
          }
          change = { upsert: move.upsert, remove: move.remove };
        }
        const value = { rows, status: move.status };
        if (move.message !== undefined) value.message = move.message;
        fn(value, change);
      });
    },
  };
}

// FRAME-30: a component's sheet, adopted by the page — a constructed
// CSSStyleSheet in document.adoptedStyleSheets, keyed by the component and
// its sheet's sha256; synchronous, so the element is never drawn bare (no
// <link> to wait on). Each engine on the page adopts a key once and drops it
// when its last instance goes; the page counts them, so two engines (the
// studio drawing a tenant's components beside its own) never drop each
// other's.
const sheets = new Map();
export function adoptSheet(key, css) {
  const held = sheets.get(key);
  if (held) {
    held.n += 1;
    return;
  }
  const sheet = new CSSStyleSheet();
  sheet.replaceSync(css);
  sheets.set(key, { sheet, n: 1 });
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
}
export function dropSheet(key) {
  const held = sheets.get(key);
  if (!held || --held.n > 0) return;
  sheets.delete(key);
  document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== held.sheet);
}

// What the host calls: a module's `mount`, `update` and `destroy`.
export function mountModule(module, target, props, handle) {
  if (typeof module?.mount !== "function") throw new Error("the module exports no mount(target, { props, bus })");
  return module.mount(target, { props, bus: busOf(handle) }) ?? {};
}

export function updateModule(mounted, props) {
  mounted?.update?.(props);
}

export function destroyModule(mounted) {
  mounted?.destroy?.();
}

// Helpers for a module's own code (a hand-written esm/1 module's):
// each reads the bus it is handed, never one of its own.
export function live(bus, spec) {
  return bus.live(spec);
}

export function on(bus, topic, fn, opts) {
  return bus.on(topic, fn, opts);
}

// FRAME-53: the topic's kept event, or undefined.
export function last(bus, topic) {
  return bus.last(topic);
}

// ── COMPS-2: frames ────────────────────────────────────────────────────────
//
// bus.frame(target, opts) → { update(opts), tell(event), destroy(), state, height, frame }
//
// The one way a component draws someone else's UI: a page it was handed
// (`{ html }`), or a stored component (`{ component: { version, name },
// props }`) — someone else's rhx or module, drawn by the engine inside the
// frame, never in the page. CONTRACT.md "Frames" is the contract; in short:
//
// - the frame is `<iframe sandbox="allow-scripts …">` (never
//   allow-same-origin: an opaque origin) on the service's `/frame#<channel>`,
//   served under its own policy (no connection, no form submitted) — never a
//   srcdoc, which would inherit the page's;
// - the handshake: the frame says `plexus:boot` on its channel and is handed
//   its page (`plexus:doc`) or its component (`plexus:component`: the
//   version's manifest, components.json and engine.wasm, which it cannot
//   fetch) once it has a width; every message either way is taken only
//   from the other side's own window, carrying the frame's channel;
// - its height is the content's (`plexus:size`), set on the iframe, so it
//   never scrolls inside — `height` fixes it, `max` caps it; a page that
//   grows with its frame is held after a few steps;
// - the theme (`theme: true`): the page's tokens in the frame's head, and
//   again whenever the page's root or the system's scheme flips;
// - the bridge: a page's `plexus.call(method, params)` (and a framed
//   component's every call) is `plexus:call`, made here through a member of
//   the bus held to the frame's `uses` — a page's as `opts.uses` declares,
//   kept only where the framer's own `uses` names it too; a component's its
//   manifest entry's — over the page's one socket as the viewer, answered
//   `plexus:answer { ok, events, message }`; outside `uses`, refused in
//   words, nothing sent;
// - `update(opts)` loads the new page in a second frame behind the one on
//   screen, which it replaces once it says its height: nothing flashes;
// - COMPS-5: or an element (`{ element: { name, source }, props }`, profile
//   element/1 — menger v1's custom element), defined and drawn by the frame
//   document itself (`plexus:element`): its props its attributes, its
//   `body` its words; `tell(event)` hands an event to its `on("change")`.

const FRAME_ROUTE = "/frame";
const GROWS = 8;
const VERSION_NAME = /^[A-Za-z0-9_-]{1,128}$/;
const COMPONENT_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,127}$/;

// The page's theme as a frame's `:root`: every token the page's root holds,
// and its colour scheme.
export function themeCss() {
  const cs = getComputedStyle(document.documentElement);
  const out = [];
  for (let i = 0; i < cs.length; i++) if (cs[i].startsWith("--")) out.push(`${cs[i]}:${cs.getPropertyValue(cs[i]).trim()}`);
  return `:root{color-scheme:${cs.colorScheme || "normal"};${out.join(";")}}`;
}

function frameChannel() {
  return "f" + Array.from(crypto.getRandomValues(new Uint32Array(3)), (x) => x.toString(36)).join("");
}

function frameSpec(x) {
  const spec = { ...(x ?? {}) };
  if ([spec.html, spec.component, spec.element].filter((x) => x != null).length !== 1) throw new Error("bus.frame(target, opts): opts holds one of { html }, { component: { version, name } } or { element: { name, source } }");
  if (spec.element != null) {
    const { name, source } = spec.element;
    if (!/^[a-z][a-z0-9._]*-[a-z0-9._-]*$/.test(String(name)) || typeof source !== "string") throw new Error("bus.frame: an element is { name, source }, its name a custom element's");
  }
  if (spec.component != null) {
    const { version, name } = spec.component;
    if (!VERSION_NAME.test(String(version)) || !COMPONENT_NAME.test(String(name))) throw new Error("bus.frame: a component is { version, name }, each a plain name");
  }
  if (spec.uses != null && (!Array.isArray(spec.uses) || spec.uses.some((u) => typeof u !== "string"))) throw new Error("bus.frame: uses is a list of method names");
  return spec;
}

const sandboxOf = (spec) => ["allow-scripts", spec.forms !== false ? "allow-forms" : "", spec.popups ? "allow-popups allow-popups-to-escape-sandbox" : ""].filter(Boolean).join(" ");

function untilWide(el) {
  return new Promise((done) => {
    if (el.offsetWidth > 0) return done();
    const ro = new ResizeObserver(() => {
      if (el.offsetWidth > 0) {
        ro.disconnect();
        done();
      }
    });
    ro.observe(el);
  });
}

async function versionText(url, optional) {
  const r = await fetch(fileUrl(url));
  if (r.ok) return r.text();
  if (optional) return null;
  throw new Error(`${url}: ${r.status}`);
}

export function frame(handle, target, opts) {
  if (!target || typeof target.appendChild !== "function") throw new Error("bus.frame(target, opts): target is the element the frame is drawn in");
  let o = frameSpec(opts);
  const bufs = [];
  let shown = null;
  let seq = 0;
  let state = "loading";
  let height = null;
  let gone = false;
  let watching = null;

  const setState = (s, message) => {
    if (state === s) return;
    state = s;
    o.onstate?.(s, message ?? null);
  };
  const themeOf = () => (o.theme === true ? themeCss() : typeof o.theme === "string" ? o.theme : null);
  const post = (b, m, transfer) => b.iframe.contentWindow?.postMessage({ ...m, channel: b.channel }, "*", transfer ?? []);
  const live = (b) => !gone && bufs.includes(b);
  const clamp = (h) => Math.min(o.max ?? Infinity, Math.max(0, o.height ?? h));

  function place(b, front) {
    const s = b.iframe.style;
    b.iframe.dataset.buffer = front ? "shown" : "loading";
    s.position = front ? "" : "absolute";
    s.top = s.left = front ? "" : "0";
    s.visibility = front ? "" : "hidden";
    s.pointerEvents = front ? "" : "none";
  }

  function load() {
    const spec = o;
    const b = { id: ++seq, channel: frameChannel(), spec, h: null, grows: 0, sent: false, member: null };
    const f = document.createElement("iframe");
    f.setAttribute("sandbox", sandboxOf(spec));
    f.setAttribute("referrerpolicy", "no-referrer");
    f.setAttribute("title", spec.title || (spec.component ? spec.component.name : spec.element ? spec.element.name : "a page"));
    f.dataset.channel = b.channel;
    Object.assign(f.style, { display: "block", border: "0", maxWidth: "none", width: spec.width ? `${spec.width}px` : "100%", height: `${clamp(spec.start ?? 150)}px` });
    b.iframe = f;
    bufs.push(b);
    if (shown == null) shown = b.id;
    place(b, b.id === shown);
    target.appendChild(f);
    b.late = setTimeout(() => {
      if (!b.sent && b.id === shown) setState("failed", "the frame never said it was up");
    }, spec.timeout ?? 8000);
    f.src = `${spec.src ?? FRAME_ROUTE}#${b.channel}`;
  }

  function drop(b) {
    clearTimeout(b.late);
    b.iframe.remove();
    b.member?.leave();
    b.member?.free?.();
    b.member = null;
    bufs.splice(bufs.indexOf(b), 1);
  }

  async function give(b) {
    b.sent = true;
    clearTimeout(b.late);
    await untilWide(b.iframe);
    if (!live(b)) return;
    const css = themeOf();
    if (b.spec.element != null) {
      const { name, source } = b.spec.element;
      b.member = handle.framed(b.spec.title || name, b.spec.uses ?? [], true);
      post(b, { type: "plexus:element", name, source, props: b.spec.props ?? {}, css });
      return;
    }
    if (b.spec.html != null) {
      b.member = handle.framed(b.spec.title || "a framed page", b.spec.uses ?? [], true);
      post(b, { type: "plexus:doc", html: String(b.spec.html), css });
      return;
    }
    const { version, name } = b.spec.component;
    try {
      const [manifest, components, wasm] = await Promise.all([
        versionText(`/app/${version}/manifest.json`),
        versionText(`/app/${version}/components.json`, true),
        fetch(fileUrl(`/app/${version}/engine.wasm`)).then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(`/app/${version}/engine.wasm: ${r.status}`)))),
      ]);
      const entry = JSON.parse(manifest).components?.[name];
      if (!entry) throw new Error(`version ${version} has no component ${name}`);
      if (!live(b)) return;
      b.member = handle.framed(name, Array.isArray(entry.uses) ? entry.uses : [], false);
      post(b, { type: "plexus:component", version, name, props: b.spec.props ?? {}, manifest, components, wasm, css }, [wasm]);
    } catch (e) {
      if (b.id === shown) setState("failed", String(e?.message ?? e));
    }
  }

  function size(b, h) {
    if (!b.sent || !Number.isFinite(h)) return;
    h = Math.round(h);
    if (b.h != null && h > b.h) {
      if (++b.grows > GROWS) return;
    } else b.grows = 0;
    b.h = h;
    b.iframe.style.height = `${clamp(h)}px`;
    if (b.id !== shown && b === bufs[bufs.length - 1]) {
      for (const x of bufs.filter((x) => x !== b)) drop(x);
      shown = b.id;
      place(b, true);
    }
    if (b.id === shown) {
      height = clamp(h);
      setState("drawn");
      o.onsize?.(height);
    }
  }

  function bridge(b, d) {
    if (typeof d.id !== "string") return;
    const answer = (a) => live(b) && post(b, { type: "plexus:answer", id: d.id, ...a });
    if (!b.member) return answer({ ok: false, events: [], message: "the frame has no bridge: it was handed nothing yet" });
    const params = d.params && typeof d.params === "object" && !Array.isArray(d.params) ? d.params : {};
    let p;
    try {
      p = b.member.call(String(d.method), params);
    } catch (e) {
      p = Promise.reject(e);
    }
    Promise.resolve(p).then(
      (ev) => answer({ ok: !!ev.ok, events: Array.from(ev), message: ev.message ?? null }),
      (e) => answer({ ok: false, events: [], message: String(e?.message ?? e), refused: true }),
    );
  }

  const onMessage = (e) => {
    const b = bufs.find((x) => x.iframe.contentWindow === e.source);
    const d = e.data;
    if (!b || !d || typeof d !== "object" || d.channel !== b.channel) return;
    if (d.type === "plexus:boot" && !b.sent) give(b);
    else if (d.type === "plexus:size") size(b, d.height);
    else if (d.type === "plexus:call") bridge(b, d);
    else if (d.type === "plexus:failed" && b.id === shown) setState("failed", String(d.message ?? "the frame could not draw it"));
  };
  addEventListener("message", onMessage);

  function watchTheme() {
    if (o.theme !== true || watching) return;
    const send = () => {
      if (o.theme !== true) return;
      const css = themeCss();
      for (const b of bufs) if (b.sent) post(b, { type: "plexus:theme", css });
    };
    const mo = new MutationObserver(send);
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "class", "style"] });
    const mq = matchMedia("(prefers-color-scheme: dark)");
    mq.addEventListener("change", send);
    watching = () => {
      mo.disconnect();
      mq.removeEventListener("change", send);
    };
  }

  load();
  watchTheme();

  return Object.freeze({
    update(next = {}) {
      if (gone) return;
      const before = o;
      const merged = { ...o, ...next };
      for (const k of ["html", "component", "element"]) if (next[k] != null) for (const other of ["html", "component", "element"]) if (other !== k) delete merged[other];
      o = frameSpec(merged);
      const changed = (k) => k in next && JSON.stringify(next[k]) !== JSON.stringify(before[k]);
      if (["html", "component", "element", "props", "uses", "width", "forms", "popups", "src"].some(changed)) {
        for (const x of bufs.filter((x) => x.id !== shown)) drop(x);
        load();
      } else if ("height" in next || "max" in next) {
        const b = bufs.find((x) => x.id === shown);
        if (b?.h != null) {
          height = clamp(b.h);
          b.iframe.style.height = `${height}px`;
          o.onsize?.(height);
        }
      }
      if ("theme" in next) {
        watchTheme();
        const css = themeOf();
        if (css != null) for (const b of bufs) if (b.sent) post(b, { type: "plexus:theme", css });
      }
    },
    /** COMPS-5: `event` to an element's `on("change")` (every frame that has its own). */
    tell(event) {
      if (gone) return;
      for (const b of bufs) if (b.sent) post(b, { type: "plexus:change", event });
    },
    destroy() {
      if (gone) return;
      gone = true;
      removeEventListener("message", onMessage);
      watching?.();
      for (const b of [...bufs]) drop(b);
    },
    get state() {
      return state;
    },
    get height() {
      return height;
    },
    get frame() {
      return bufs.find((x) => x.id === shown)?.iframe ?? null;
    },
  });
}

// COMPS-2: inside a frame — the service's /frame document imports this
// version's host.js and calls it with what its parent handed over: the
// engine instantiated from the bytes given (the frame fetches nothing),
// then the component drawn by the engine's `boot_frame`.
export async function startFrame({ version, name, props, manifest, components, wasm, channel }) {
  const engine = await import(new URL("./engine.js", import.meta.url).href);
  await engine.default({ module_or_path: wasm });
  engine.boot_frame(version, name, JSON.stringify(props ?? {}), manifest, components ?? undefined, channel);
}