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);
}
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;
}
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(() => {});
}
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}`;
}
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);
}
export function importModule(url) {
return import(url);
}
export function busOf(handle) {
return Object.freeze({
call: (method, params) => handle.call(method, params ?? {}),
stream: (method, params, onItem) => handle.stream(method, params ?? {}, typeof onItem === "function" ? onItem : () => {}),
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();
},
});
}
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);
});
},
};
}
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);
}
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?.();
}
export function live(bus, spec) {
return bus.live(spec);
}
export function on(bus, topic, fn, opts) {
return bus.on(topic, fn, opts);
}
export function last(bus, topic) {
return bus.last(topic);
}
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}$/;
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, open: new Map() };
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.open.clear();
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);
}
}
const bare = (item) => {
if (item?.type === "data") return { type: "data", content: item.content };
const out = { type: String(item?.type ?? "failed") };
const kind = item?.kind ?? item?.error?.error_kind;
if (typeof kind === "string") out.kind = kind;
if (item?.message != null) out.message = String(item.message);
return out;
};
const FRAME_STREAMS_MAX = 16;
function open(b, d, onItem, refused) {
if (typeof d.id !== "string" || b.open.has(d.id)) return;
if (!b.member) return refused("the frame has no bridge: it was handed nothing yet");
if (b.open.size >= FRAME_STREAMS_MAX) return refused(`too_many_streams: a frame holds at most ${FRAME_STREAMS_MAX} calls and streams open at once`, "too_many_streams");
const params = d.params && typeof d.params === "object" && !Array.isArray(d.params) ? d.params : {};
try {
const s = b.member.stream(String(d.method), params, (item) => {
if (item?.type !== "data") b.open.delete(d.id);
onItem(bare(item));
});
b.open.set(d.id, s);
} catch (e) {
refused(String(e?.message ?? e));
}
}
function bridge(b, d) {
const answer = (a) => live(b) && post(b, { type: "plexus:answer", id: d.id, ...a });
const events = [];
open(b, d, (item) => {
if (item.type === "data") return void events.push(item.content);
const inBand = events.find((e) => e && (e.type === "error" || e.type === "refused"));
const words = inBand ? String(inBand.message ?? inBand.reason ?? inBand.type) : item.type === "done" ? null : item.type === "dropped" ? "disconnected" : item.message ?? item.type;
answer({ ok: words === null, events, message: words });
}, (message, kind) => answer({ ok: false, events: [], message, refused: true, ...(kind ? { kind } : {}) }));
}
function bridgeStream(b, d) {
const say = (item) => live(b) && post(b, { type: "plexus:item", id: d.id, item });
open(b, d, say, (message, kind) => say({ type: "refused", ...(kind ? { kind } : {}), message }));
}
function bridgeStop(b, d) {
const s = typeof d.id === "string" ? b.open.get(d.id) : null;
if (!s) return;
b.open.delete(d.id);
s.stop();
}
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:stream") bridgeStream(b, d);
else if (d.type === "plexus:stop") bridgeStop(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 });
}
},
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;
},
});
}
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);
}