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 ?? {}),
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) }),
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);
}