@mostra/react 0.6.1 → 0.7.0
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.
- package/dist/form.js +1 -1
- package/dist/{hooks-Dh_l8KqJ.js → hooks-BUQOrPQg.js} +53 -6
- package/dist/hooks-BUQOrPQg.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{mount-Bpg0M5ln.js → mount-BN4Ra0tK.js} +55 -3
- package/dist/mount-BN4Ra0tK.js.map +1 -0
- package/dist/router.js +1 -1
- package/package.json +2 -2
- package/src/runtime/boot.ts +7 -0
- package/src/runtime/service-worker.ts +55 -0
- package/src/runtime/transport.ts +73 -8
- package/src/shell-bridge.ts +8 -0
- package/dist/hooks-Dh_l8KqJ.js.map +0 -1
- package/dist/mount-Bpg0M5ln.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as MemoryJournal, d as connectShell, f as listenShell, g as fieldKey, h as Store, m as reportReady, t as RuntimeProvider, u as builtVersion, v as HttpTransport, x as MostraError, y as IndexedDbJournal } from "./hooks-
|
|
1
|
+
import { b as MemoryJournal, d as connectShell, f as listenShell, g as fieldKey, h as Store, m as reportReady, t as RuntimeProvider, u as builtVersion, v as HttpTransport, x as MostraError, y as IndexedDbJournal } from "./hooks-BUQOrPQg.js";
|
|
2
2
|
import { BRIDGE_FIELDS_MAX, BRIDGE_TEXT_MAX, VERIFY_PROBE, VERIFY_REPORT, isFieldId, mostraFieldFocus, mostraFields, mostraFlush, mostraPage, mostraVersionAvailable, readViewContext } from "@mostra/protocol";
|
|
3
3
|
import { createElement } from "react";
|
|
4
4
|
import { createRoot } from "react-dom/client";
|
|
@@ -26,6 +26,53 @@ function blockersForShell(blockers) {
|
|
|
26
26
|
});
|
|
27
27
|
}
|
|
28
28
|
//#endregion
|
|
29
|
+
//#region src/runtime/service-worker.ts
|
|
30
|
+
/**
|
|
31
|
+
* The frame's service worker in worker mode (D70, D158 item 5): where the shell and the artifact
|
|
32
|
+
* are two sites, Mostra's own service worker at `/` signs every request of the frame with its
|
|
33
|
+
* session. An artifact's own worker can't run there: its script is fetched without the session
|
|
34
|
+
* (a browser adds nothing to that request), and a page it controlled would send requests no
|
|
35
|
+
* worker signs, so the page would lose its session. The client runtime refuses such a
|
|
36
|
+
* registration with a diagnostic the page can see, rather than letting it fail obscurely or end
|
|
37
|
+
* the session. On a tailnet, Funnel or local link (cookie mode) the artifact registers its own
|
|
38
|
+
* workers as usual.
|
|
39
|
+
*/
|
|
40
|
+
/** Mostra's worker, which the gateway serves on every worker-mode artifact origin. */
|
|
41
|
+
const MOSTRA_WORKER = "/_mostra/sw.js";
|
|
42
|
+
/** Whether this page runs under Mostra's worker-mode service worker. */
|
|
43
|
+
function workerModeFrame() {
|
|
44
|
+
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) return false;
|
|
45
|
+
const controller = navigator.serviceWorker.controller;
|
|
46
|
+
if (!controller) return false;
|
|
47
|
+
try {
|
|
48
|
+
return new URL(controller.scriptURL).pathname === MOSTRA_WORKER;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
let guarded = false;
|
|
54
|
+
/**
|
|
55
|
+
* In a worker-mode frame, refuses an artifact's own service worker with
|
|
56
|
+
* `MOSTRA_HYGIENE_FRAME_SESSION` (rejecting the registration's promise and saying so on the
|
|
57
|
+
* console), instead of letting it fail without its session or end the page's. Installed once,
|
|
58
|
+
* before artifact code runs; a no-op anywhere else.
|
|
59
|
+
*/
|
|
60
|
+
function guardFrameServiceWorker() {
|
|
61
|
+
if (guarded || !workerModeFrame()) return;
|
|
62
|
+
guarded = true;
|
|
63
|
+
const container = navigator.serviceWorker;
|
|
64
|
+
const register = container.register.bind(container);
|
|
65
|
+
const guard = (scriptURL, options) => {
|
|
66
|
+
const script = new URL(String(scriptURL), location.href);
|
|
67
|
+
if (script.origin === location.origin && script.pathname === MOSTRA_WORKER) return register(scriptURL, options);
|
|
68
|
+
const scope = new URL(options?.scope ?? "./", script);
|
|
69
|
+
const error = new MostraError("MOSTRA_HYGIENE_FRAME_SESSION", `This page opened through a link whose frame runs on Mostra's own service worker (a public Cloudflare link), so ${script.pathname} can't be registered here (scope ${scope.pathname}): it would run without the page's session. On a tailnet, Funnel or local link the page registers its own service workers.`);
|
|
70
|
+
console.error(`[MOSTRA_HYGIENE_FRAME_SESSION] ${error.message}`);
|
|
71
|
+
return Promise.reject(error);
|
|
72
|
+
};
|
|
73
|
+
container.register = guard;
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
29
76
|
//#region src/runtime/verify-probe.ts
|
|
30
77
|
/**
|
|
31
78
|
* `verify`'s field probe (D138 item 3): in the `verify` target only, the page keeps a record of
|
|
@@ -89,6 +136,7 @@ function installVerifyProbe(store) {
|
|
|
89
136
|
* `visibilitychange`, `pagehide`) and the bridge (`mostra/fields`, `mostra/flush`,
|
|
90
137
|
* `mostra/field.focus`, `mostra/version.available`) to the store.
|
|
91
138
|
*/
|
|
139
|
+
guardFrameServiceWorker();
|
|
92
140
|
/** The delivery target the page was built or exported for: its `mostra-target` meta tag (D111). */
|
|
93
141
|
function deliveryTarget() {
|
|
94
142
|
if (typeof document === "undefined") return "live";
|
|
@@ -215,7 +263,11 @@ async function startRuntime() {
|
|
|
215
263
|
const journal = await IndexedDbJournal.open() ?? new MemoryJournal();
|
|
216
264
|
const store = new Store({
|
|
217
265
|
mode: "live",
|
|
218
|
-
transport: new HttpTransport(view.viewId, {
|
|
266
|
+
transport: new HttpTransport(view.viewId, {
|
|
267
|
+
...shell.session.csrf !== "" ? { csrf: shell.session.csrf } : {},
|
|
268
|
+
...shell.session.mode === "worker" ? { tickets: true } : {},
|
|
269
|
+
...shell.session.streams ? {} : { streams: false }
|
|
270
|
+
}),
|
|
219
271
|
journal,
|
|
220
272
|
view,
|
|
221
273
|
scopes: shell.session.scopes,
|
|
@@ -513,4 +565,4 @@ async function mountArtifact(options) {
|
|
|
513
565
|
//#endregion
|
|
514
566
|
export { createServerReference as a, reportPage as i, prepareArtifact as n, setServerCallback as o, renderArtifact as r, mountArtifact as t };
|
|
515
567
|
|
|
516
|
-
//# sourceMappingURL=mount-
|
|
568
|
+
//# sourceMappingURL=mount-BN4Ra0tK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mount-BN4Ra0tK.js","names":[],"sources":["../src/runtime/bridge-limits.ts","../src/runtime/service-worker.ts","../src/runtime/verify-probe.ts","../src/runtime/boot.ts","../src/server-reference.ts","../src/storage.ts","../src/mount.ts"],"sourcesContent":["/**\n * What the page sends the shell, fitted to the bridge's limits (Claude review finding 11): a long\n * label or validation message is shortened, and a page with more fields than one message lists\n * sends those that matter first. A report the bridge refuses would leave the shell's rail and its\n * blocker list stale, and a refused flush answer would stop every trusted Submit.\n */\nimport { BRIDGE_FIELDS_MAX, BRIDGE_TEXT_MAX, type SubmitBlocker } from \"@mostra/protocol\";\n\n/** Text shortened to what the bridge carries. */\nexport function clip(text: string): string {\n return text.length <= BRIDGE_TEXT_MAX ? text : `${text.slice(0, BRIDGE_TEXT_MAX - 1)}…`;\n}\n\n/** At most {@link BRIDGE_FIELDS_MAX} items, those that matter first, in their order otherwise. */\nexport function firstThatMatter<T>(items: readonly T[], matters: (item: T) => boolean): T[] {\n if (items.length <= BRIDGE_FIELDS_MAX) return [...items];\n return [...items.filter(matters), ...items.filter((item) => !matters(item))].slice(\n 0,\n BRIDGE_FIELDS_MAX,\n );\n}\n\n/** Blockers as the bridge carries them: labels shortened, at most {@link BRIDGE_FIELDS_MAX}. */\nexport function blockersForShell(blockers: readonly SubmitBlocker[]): SubmitBlocker[] {\n return blockers\n .slice(0, BRIDGE_FIELDS_MAX)\n .map((blocker) =>\n blocker.label === undefined ? blocker : { ...blocker, label: clip(blocker.label) },\n );\n}\n","/**\n * The frame's service worker in worker mode (D70, D158 item 5): where the shell and the artifact\n * are two sites, Mostra's own service worker at `/` signs every request of the frame with its\n * session. An artifact's own worker can't run there: its script is fetched without the session\n * (a browser adds nothing to that request), and a page it controlled would send requests no\n * worker signs, so the page would lose its session. The client runtime refuses such a\n * registration with a diagnostic the page can see, rather than letting it fail obscurely or end\n * the session. On a tailnet, Funnel or local link (cookie mode) the artifact registers its own\n * workers as usual.\n */\nimport { MostraError } from \"./errors.ts\";\n\n/** Mostra's worker, which the gateway serves on every worker-mode artifact origin. */\nconst MOSTRA_WORKER = \"/_mostra/sw.js\";\n\n/** Whether this page runs under Mostra's worker-mode service worker. */\nexport function workerModeFrame(): boolean {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return false;\n const controller = navigator.serviceWorker.controller;\n if (!controller) return false;\n try {\n return new URL(controller.scriptURL).pathname === MOSTRA_WORKER;\n } catch {\n return false;\n }\n}\n\nlet guarded = false;\n\n/**\n * In a worker-mode frame, refuses an artifact's own service worker with\n * `MOSTRA_HYGIENE_FRAME_SESSION` (rejecting the registration's promise and saying so on the\n * console), instead of letting it fail without its session or end the page's. Installed once,\n * before artifact code runs; a no-op anywhere else.\n */\nexport function guardFrameServiceWorker(): void {\n if (guarded || !workerModeFrame()) return;\n guarded = true;\n const container = navigator.serviceWorker;\n const register = container.register.bind(container);\n const guard: typeof container.register = (scriptURL, options) => {\n const script = new URL(String(scriptURL), location.href);\n if (script.origin === location.origin && script.pathname === MOSTRA_WORKER) {\n return register(scriptURL, options);\n }\n const scope = new URL(options?.scope ?? \"./\", script);\n const error = new MostraError(\n \"MOSTRA_HYGIENE_FRAME_SESSION\",\n `This page opened through a link whose frame runs on Mostra's own service worker (a public Cloudflare link), so ${script.pathname} can't be registered here (scope ${scope.pathname}): it would run without the page's session. On a tailnet, Funnel or local link the page registers its own service workers.`,\n );\n console.error(`[MOSTRA_HYGIENE_FRAME_SESSION] ${error.message}`);\n return Promise.reject(error);\n };\n container.register = guard;\n}\n","\"use client\";\n\n/**\n * `verify`'s field probe (D138 item 3): in the `verify` target only, the page keeps a record of\n * every field it mounts (the hook, the scope and the type of the initial value) and how much\n * server work it waits on, and publishes both on `globalThis[VERIFY_PROBE]`, where the verify\n * runner reads them. Viewers' pages never install it.\n */\nimport { type ProbedField, VERIFY_PROBE } from \"@mostra/protocol\";\nimport type { Registration, Store } from \"./store.ts\";\n\n/** `typeof`, with arrays and `null` named as such. */\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\ninterface Entry {\n readonly first: { readonly hook: string; readonly scope: string; readonly initialType: string };\n mounts: number;\n readonly conflicts: Set<string>;\n}\n\n/** Records the store's field mounts on `globalThis[VERIFY_PROBE]`. */\nexport function installVerifyProbe(store: Store): void {\n const entries = new Map<string, Entry>();\n store.observeMounts((registration: Registration, mounted: boolean) => {\n const shape = {\n hook: registration.hook ?? \"useField\",\n scope: registration.scope,\n initialType: typeName(registration.initial),\n };\n let entry = entries.get(registration.id);\n if (!entry) {\n entry = { first: shape, mounts: 0, conflicts: new Set() };\n entries.set(registration.id, entry);\n }\n if (mounted) {\n entry.mounts += 1;\n if (shape.hook !== entry.first.hook)\n entry.conflicts.add(`${entry.first.hook} and ${shape.hook}`);\n if (shape.scope !== entry.first.scope)\n entry.conflicts.add(`scopes ${entry.first.scope} and ${shape.scope}`);\n if (shape.initialType !== entry.first.initialType)\n entry.conflicts.add(\n `initial values of types ${entry.first.initialType} and ${shape.initialType}`,\n );\n } else entry.mounts = Math.max(0, entry.mounts - 1);\n });\n const fields = (): ProbedField[] =>\n [...entries].map(([id, entry]) => ({\n id,\n scope: entry.first.scope as ProbedField[\"scope\"],\n hook: entry.first.hook,\n initialType: entry.first.initialType,\n mounts: entry.mounts,\n conflicts: [...entry.conflicts],\n }));\n // `pending`: the server work the page waits on (calls, runs, first live values), which the\n // runner's quiescence wait includes (Opus review finding 1).\n const pending = (): number => store.server.pending();\n Object.defineProperty(globalThis, VERIFY_PROBE, {\n value: { fields, pending },\n configurable: true,\n });\n}\n","/**\n * Starts the client runtime for the page (D111): reads the delivery target, connects to the shell\n * and the gateway in live mode, opens the journal, and wires the page's lifecycle (blur,\n * `visibilitychange`, `pagehide`) and the bridge (`mostra/fields`, `mostra/flush`,\n * `mostra/field.focus`, `mostra/version.available`) to the store.\n */\nimport {\n type DeliveryTarget,\n type FieldsParams,\n type FlushResult,\n mostraFieldFocus,\n mostraFields,\n mostraFlush,\n mostraVersionAvailable,\n readViewContext,\n type VersionAvailableParams,\n type ViewContext,\n} from \"@mostra/protocol\";\nimport { builtVersion, connectShell, listenShell, type ShellConnection } from \"../shell-bridge.ts\";\nimport { blockersForShell, clip, firstThatMatter } from \"./bridge-limits.ts\";\nimport { IndexedDbJournal, type Journal, MemoryJournal } from \"./journal.ts\";\nimport { guardFrameServiceWorker } from \"./service-worker.ts\";\nimport { Store } from \"./store.ts\";\nimport { HttpTransport } from \"./transport.ts\";\nimport { installVerifyProbe } from \"./verify-probe.ts\";\n\n// Before any artifact code runs: the generated entry imports the runtime first (D70).\nguardFrameServiceWorker();\n\n/** The page's runtime: its store, where it runs, and its shell connection. */\nexport interface Runtime {\n readonly store: Store;\n /** The delivery target the page was built or exported for (D111): it chooses the history. */\n readonly target: DeliveryTarget;\n /**\n * Where the page runs, as `useArtifact` reports it: the target, except that a live page opened\n * outside Mostra's shell has no server features and reports `static`.\n */\n readonly mode: DeliveryTarget;\n /** The shell connection, inside Mostra's shell. */\n readonly shell: ShellConnection | undefined;\n}\n\n/** The delivery target the page was built or exported for: its `mostra-target` meta tag (D111). */\nexport function deliveryTarget(): DeliveryTarget {\n if (typeof document === \"undefined\") return \"live\";\n const content = document\n .querySelector('meta[name=\"mostra-target\"]')\n ?.getAttribute(\"content\")\n ?.trim();\n return content === \"static\" || content === \"mcp-app\" || content === \"verify\" ? content : \"live\";\n}\n\n/** A random ID for this tab. */\nfunction tabId(): string {\n const bytes = new Uint8Array(12);\n globalThis.crypto.getRandomValues(bytes);\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\ninterface Locks {\n request(name: string, callback: () => Promise<unknown>): Promise<unknown>;\n request(\n name: string,\n options: { mode?: \"exclusive\" | \"shared\" },\n callback: () => Promise<unknown>,\n ): Promise<unknown>;\n query(): Promise<{ held?: { name?: string }[] }>;\n}\n\nfunction locks(): Locks | undefined {\n const navigatorLocks = (globalThis.navigator as { locks?: Locks } | undefined)?.locks;\n return navigatorLocks;\n}\n\nconst TAB_LOCK = \"mostra-tab:\";\n\n/** How long a tab waits for other tabs to say they are open, where Web Locks are missing. */\nconst PRESENCE_WAIT_MS = 300;\n\n/**\n * Where Web Locks are missing (they need a secure context, and an artifact served over plain\n * HTTP on a LAN address isn't one), open tabs answer a roll call on a BroadcastChannel, which\n * works everywhere: a tab that doesn't answer within {@link PRESENCE_WAIT_MS} is gone.\n */\nfunction rollCall(\n tab: string,\n): ((tabs: readonly string[]) => Promise<ReadonlySet<string>>) | undefined {\n if (typeof BroadcastChannel === \"undefined\") return undefined;\n const channel = new BroadcastChannel(\"mostra-tabs\");\n channel.onmessage = (event: MessageEvent<{ who?: true; here?: string }>) => {\n if (event.data?.who) channel.postMessage({ here: tab });\n };\n return (tabs) =>\n new Promise((resolve) => {\n const open = new Set<string>();\n const listen = new BroadcastChannel(\"mostra-tabs\");\n listen.onmessage = (event: MessageEvent<{ here?: string }>) => {\n if (typeof event.data?.here === \"string\") open.add(event.data.here);\n };\n listen.postMessage({ who: true });\n setTimeout(() => {\n listen.close();\n resolve(new Set(tabs.filter((other) => !open.has(other))));\n }, PRESENCE_WAIT_MS);\n });\n}\n\n/**\n * Holds this tab's lock for as long as the page lives, so other pages know its journal entries\n * belong to an open tab (Web Locks). Returns which of some tabs hold no lock: they are gone.\n */\nfunction tabPresence(tab: string): (tabs: readonly string[]) => Promise<ReadonlySet<string>> {\n const api = locks();\n if (!api) return rollCall(tab) ?? (async (tabs) => new Set(tabs));\n void api.request(`${TAB_LOCK}${tab}`, () => new Promise<never>(() => undefined));\n return async (tabs) => {\n const held = new Set(\n ((await api.query()).held ?? [])\n .map((lock) => lock.name)\n .filter((name): name is string => name?.startsWith(TAB_LOCK) === true)\n .map((name) => name.slice(TAB_LOCK.length)),\n );\n return new Set(tabs.filter((other) => !held.has(other)));\n };\n}\n\n/** Runs `fn` while no other page of the artifact adopts journal entries. */\nfunction exclusive<T>(fn: () => Promise<T>): Promise<T> {\n const api = locks();\n if (!api) return fn();\n return api.request(\"mostra-journal\", fn) as Promise<T>;\n}\n\n/** The longest pause between two attempts at the shell's handshake. */\nconst SHELL_RETRY_MAX_MS = 8_000;\n\n/**\n * The shell's connection for a framed page. A page inside a frame is inside Mostra's shell (its\n * origin is framed by the shell only): if the handshake fails (the daemon restarting during the\n * frame's load, a slow shell), it tries again rather than run on its own, where its answers\n * would stay in this browser while the shell said \"Saved\" (FAILURE_MODEL §1 rule 4; Claude review\n * finding 4). A page opened on its own has no shell and runs locally.\n */\nasync function framedShell(): Promise<ShellConnection | undefined> {\n if (typeof window === \"undefined\" || window.parent === window) return undefined;\n for (let attempt = 0; ; attempt += 1) {\n const shell = await connectShell();\n if (shell) return shell;\n if (attempt === 1)\n console.warn(\"Mostra: waiting for the shell; the page connects when it can.\");\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(500 * 2 ** attempt, SHELL_RETRY_MAX_MS)),\n );\n }\n}\n\n/**\n * Starts the runtime: live behind the gateway inside Mostra's shell, local otherwise (a static\n * export, an MCP App until its transport arrives, a page opened on its own).\n */\nexport async function startRuntime(): Promise<Runtime> {\n const target = deliveryTarget();\n const tab = tabId();\n const shell = target === \"live\" || target === \"verify\" ? await framedShell() : undefined;\n // Read the tolerant way: a later shell may send values this page doesn't know (Claude review\n // finding 5), which never cost it its view.\n const view: ViewContext | undefined = shell?.host.mostra\n ? readViewContext(shell.host.mostra)\n : undefined;\n const built = builtVersion();\n if (shell && view && built !== undefined && built !== view.version.id) {\n // This page is another version than the view the shell opened: another tab moved the frame\n // session on (D98 item 5). Nothing it shows may be saved as this view, nor kept: the shell,\n // told the page's version in `ui/initialize`, loads the frame again at its own version.\n const scratch = new Map<string, string>();\n const store = new Store({\n mode: \"local\",\n journal: new MemoryJournal(),\n tab,\n local: {\n getItem: (key) => scratch.get(key) ?? null,\n setItem: (key, value) => void scratch.set(key, value),\n removeItem: (key) => void scratch.delete(key),\n },\n });\n store.start();\n return { store, target, mode: view.target, shell };\n }\n if (!shell || !view) {\n const store = new Store({ mode: \"local\", journal: new MemoryJournal(), tab });\n store.start();\n return { store, target, mode: target === \"live\" ? \"static\" : target, shell: undefined };\n }\n const journal: Journal = (await IndexedDbJournal.open()) ?? new MemoryJournal();\n const store = new Store({\n mode: \"live\",\n transport: new HttpTransport(view.viewId, {\n ...(shell.session.csrf !== \"\" ? { csrf: shell.session.csrf } : {}),\n // Worker mode opens streams and polls with tickets, past the service worker (D70).\n ...(shell.session.mode === \"worker\" ? { tickets: true } : {}),\n ...(shell.session.streams ? {} : { streams: false }),\n }),\n journal,\n view,\n scopes: shell.session.scopes,\n ...(shell.session.viewer ? { viewer: shell.session.viewer } : {}),\n tab,\n goneTabs: tabPresence(tab),\n exclusive,\n channel: (name) =>\n typeof BroadcastChannel === \"undefined\" ? undefined : new BroadcastChannel(name),\n });\n // A verify run reads which fields the page mounts (D138); a viewer's page never records them.\n if (target === \"verify\") installVerifyProbe(store);\n store.start();\n wireLifecycle(store);\n wireShell(store, shell);\n return { store, target, mode: view.target, shell };\n}\n\n/** Saves on blur, and when the page is hidden or closed (IN-02). */\nfunction wireLifecycle(store: Store): void {\n if (typeof document === \"undefined\") return;\n document.addEventListener(\"focusout\", () => void store.flush(), true);\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") void store.flush({ keepalive: true });\n });\n window.addEventListener(\"pagehide\", () => void store.flush({ keepalive: true }));\n}\n\n/** Focuses the element a field is bound to, when the viewer picks it in the shell. */\nfunction focusField(id: string): void {\n const escaped = typeof CSS !== \"undefined\" && CSS.escape ? CSS.escape(id) : id;\n const element = document.querySelector<HTMLElement>(\n `[data-mostra-field=\"${escaped}\"], [name=\"${escaped}\"], #${escaped}`,\n );\n element?.scrollIntoView({ block: \"center\" });\n element?.focus();\n}\n\n/** Reports fields and save state to the shell, and answers its requests. */\nfunction wireShell(store: Store, shell: ShellConnection): void {\n let last = \"\";\n let scheduled = false;\n const report = (): void => {\n scheduled = false;\n const fields = store.registrations().map((registration) => ({\n id: registration.id,\n scope: registration.scope,\n ...(registration.label !== undefined ? { label: clip(registration.label) } : {}),\n ...(registration.required !== undefined ? { required: registration.required } : {}),\n ...(registration.sensitive !== undefined ? { sensitive: registration.sensitive } : {}),\n ...(registration.error !== undefined ? { error: clip(registration.error) } : {}),\n ...(store.conflict(`${registration.scope}:${registration.id}`) ? { conflict: true } : {}),\n }));\n const params: FieldsParams = {\n fields: firstThatMatter(fields, (field) =>\n Boolean(field.required || field.error !== undefined || field.conflict),\n ),\n save: store.pageSave(),\n unsaved: store.unsaved(),\n };\n const text = JSON.stringify(params);\n if (text === last) return;\n last = text;\n try {\n shell.bridge.notify(mostraFields, params);\n } catch (error) {\n // Never silently: the shell's rail would keep its last state (Claude review finding 11).\n console.error(\"Mostra: the page's fields couldn't be reported to the shell.\", error);\n }\n };\n store.subscribe(() => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(report);\n });\n report();\n listenShell({\n request: async (message, params) => {\n if (message !== mostraFlush) return undefined;\n const reason = (params as { reason: \"submit\" | \"switch\" }).reason;\n if (reason === \"submit\") {\n const prepared = await store.prepareSubmit();\n const result: FlushResult = {\n revision: String(prepared.revision),\n unsaved: prepared.unsaved,\n blockers: blockersForShell(prepared.blockers),\n };\n return result;\n }\n const flushed = await store.flush();\n const result: FlushResult = {\n revision: String(flushed.revision),\n unsaved: flushed.unsaved,\n blockers: blockersForShell(store.blockers()),\n };\n return result;\n },\n notification: (message, params) => {\n if (message === mostraFieldFocus) focusField((params as { id: string }).id);\n if (message === mostraVersionAvailable) {\n // The page may show its own notice; the shell's trusted banner always appears (§5).\n window.dispatchEvent(\n new CustomEvent<VersionAvailableParams>(\"mostra:version-available\", {\n detail: params as VersionAvailableParams,\n }),\n );\n }\n },\n });\n}\n","\"use client\";\n\n/**\n * The client side of `\"use server\"` functions (D19 seam 2, D54). The builder compiles every export\n * of a `\"use server\"` module in client code into a server reference: a function that carries the\n * server function's ID and hands the call to the page's runtime, as React's own server references\n * hand theirs to the callback `setServerCallback` installs. The runtime calls Mostra (a plain\n * call: no record, the result streamed back); where there is no Mostra server, such as a static\n * export, the call rejects with `MOSTRA_TARGET_UNAVAILABLE`.\n */\n\n/** A `\"use server\"` function as client code sees it. */\nexport interface ServerReference<A extends unknown[] = unknown[], R = unknown> {\n /** Calls the server function with `args`; resolves with its result. */\n (...args: A): Promise<R>;\n /** The server function's ID: its module path, `#` and its export name (`actions.ts#sendReply`). */\n readonly mostraServerFunctionId: string;\n}\n\n/** How the page's runtime calls a server function. */\nexport type CallServer = (id: string, args: unknown[]) => Promise<unknown>;\n\nconst unavailable: CallServer = async (id) => {\n const error = new Error(\n `The server function ${id} can't run here: this delivery target has no Mostra server. Open the artifact through its Mostra link to use it.`,\n ) as Error & { code: string };\n error.code = \"MOSTRA_TARGET_UNAVAILABLE\";\n throw error;\n};\n\nlet callServer: CallServer = unavailable;\n\n/**\n * Installs how server references call the server: the runtime does it when the page starts (a\n * live page calls Mostra; a static export keeps the default, which rejects). Returns the function\n * that restores the previous one.\n */\nexport function setServerCallback(callback: CallServer): () => void {\n const previous = callServer;\n callServer = callback;\n return () => {\n callServer = previous;\n };\n}\n\n/**\n * Creates the client stub of one server function. The builder emits these calls; artifact code\n * imports the server module as usual and never calls this itself.\n */\nexport function createServerReference(id: string): ServerReference {\n const reference = (...args: unknown[]): Promise<unknown> => callServer(id, args);\n Object.defineProperty(reference, \"mostraServerFunctionId\", { value: id, enumerable: true });\n return reference as unknown as ServerReference;\n}\n","\"use client\";\n\n/**\n * `window.storage`, compatible with Claude artifacts' persistent storage (D53, D112): agents that\n * learned `await window.storage.get(key)` keep working, and their values become Mostra fields.\n * Personal keys are the viewer's draft fields `storage.<key>`, carried over between versions and\n * delivered with the submission; `shared: true` keys are artifact state, every viewer's (D63).\n *\n * Differences from Claude's, by design (D112): a value is any JSON value up to 1 MiB (Mostra's\n * field limit; a larger one rejects with `MOSTRA_FIELD_TOO_LARGE`, never truncated), a missing key\n * resolves `null`, and two writers of one key end with the last write (a write that keeps meeting\n * another writer's change is refused with `MOSTRA_FIELD_CONFLICT`, never reported saved).\n */\nimport { isFieldId } from \"@mostra/protocol\";\nimport { MostraError } from \"./runtime/errors.ts\";\nimport { fieldKey, type Store } from \"./runtime/store.ts\";\n\n/** What `get` and `set` resolve with. */\nexport interface StorageEntry {\n /** The key. */\n readonly key: string;\n /** Its value: any JSON value. */\n readonly value: unknown;\n /** Whether it is shared by every viewer (artifact state) or the viewer's own. */\n readonly shared: boolean;\n}\n\n/** The storage API of Claude artifacts, backed by Mostra fields (D53). */\nexport interface ClaudeCompatibleStorage {\n /** The value of `key`, or `null` when it has none. */\n get(key: string, shared?: boolean): Promise<StorageEntry | null>;\n /** Stores `value` under `key`; resolves once Mostra saved it. */\n set(key: string, value: unknown, shared?: boolean): Promise<StorageEntry>;\n /** Removes `key`; resolves once Mostra saved that. */\n delete(\n key: string,\n shared?: boolean,\n ): Promise<{ readonly key: string; readonly deleted: true; readonly shared: boolean }>;\n /** The keys stored, those starting with `prefix` when it is given. */\n list(\n prefix?: string,\n shared?: boolean,\n ): Promise<{ readonly keys: string[]; readonly prefix?: string; readonly shared: boolean }>;\n}\n\nconst PREFIX = \"storage.\";\n\n/**\n * How many times a write over another writer's change is tried (last write wins, D112) before it\n * is refused with `MOSTRA_FIELD_CONFLICT`.\n */\nconst ATTEMPTS = 6;\n\nfunction fieldIdOf(key: unknown): string {\n if (typeof key !== \"string\" || !isFieldId(`${PREFIX}${key}`)) {\n throw new MostraError(\n \"MOSTRA_FIELD_ID_INVALID\",\n `${JSON.stringify(key)} can't be a storage key: use 1 to 248 characters without control characters or empty dot-separated parts.`,\n );\n }\n return `${PREFIX}${key}`;\n}\n\n/** Creates the `window.storage` of a page's store. */\nexport function createStorage(store: Store): ClaudeCompatibleStorage {\n const write = async (key: string, value: unknown, shared: boolean): Promise<void> => {\n const id = fieldIdOf(key);\n const scope = shared ? \"artifact\" : \"viewer\";\n await store.whenReady();\n if (value !== undefined) {\n const text = JSON.stringify(value);\n if (text === undefined) {\n throw new MostraError(\"MOSTRA_HOST_INVALID_PARAMS\", `The value of ${key} isn't JSON.`);\n }\n }\n store.set(scope, id, value, {\n immediate: true,\n ...(value === undefined ? { delete: true } : {}),\n });\n const k = fieldKey(scope, id);\n // Settled: saved, refused or in conflict. Offline, the write waits in the journal and the\n // promise with it: it resolves when Mostra has the value, never before (GPT review finding 10).\n const settled = (): Promise<void> =>\n new Promise((resolve) => {\n const done = (): boolean =>\n store.refusal(k) !== undefined ||\n store.conflict(k) !== undefined ||\n store.save(k) === \"saved\" ||\n store.save(k) === \"readonly\";\n if (done()) {\n resolve();\n return;\n }\n const stop = store.subscribe(() => {\n if (!done()) return;\n stop();\n resolve();\n });\n });\n for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {\n await store.flush();\n await settled();\n const refused = store.refusal(k);\n if (refused !== undefined) {\n store.takeTheirs(k);\n throw new MostraError(refused.code, refused.message);\n }\n if (!store.conflict(k)) return;\n if (attempt === ATTEMPTS - 1) break;\n // Another writer got in between: written again over theirs, after a short, growing pause.\n await new Promise((resolve) => setTimeout(resolve, 20 * 2 ** attempt * (1 + Math.random())));\n store.keepMine(k);\n }\n // Another writer kept changing it: the write is refused, never reported saved, and the field\n // keeps their value (Claude review finding 9).\n store.takeTheirs(k);\n throw new MostraError(\n \"MOSTRA_FIELD_CONFLICT\",\n `${key} kept changing under another writer, so this write wasn't saved.`,\n );\n };\n return {\n async get(key, shared = false) {\n const id = fieldIdOf(key);\n await store.whenReady();\n const value = store.value(fieldKey(shared ? \"artifact\" : \"viewer\", id), undefined);\n return value === undefined ? null : { key, value, shared };\n },\n async set(key, value, shared = false) {\n await write(key, value, shared);\n return { key, value, shared };\n },\n async delete(key, shared = false) {\n await write(key, undefined, shared);\n return { key, deleted: true as const, shared };\n },\n async list(prefix, shared = false) {\n await store.whenReady();\n const keys = store\n .ids(shared ? \"artifact\" : \"viewer\")\n .filter((id) => id.startsWith(PREFIX))\n .map((id) => id.slice(PREFIX.length))\n .filter((key) => prefix === undefined || key.startsWith(prefix));\n return { keys, ...(prefix !== undefined ? { prefix } : {}), shared };\n },\n };\n}\n\ndeclare global {\n interface Window {\n /** Claude-compatible persistent storage, backed by Mostra fields (D53). */\n storage: ClaudeCompatibleStorage;\n }\n}\n\n/** Installs `window.storage` for the page's store. */\nexport function installStorage(store: Store): void {\n if (typeof window === \"undefined\") return;\n Object.defineProperty(window, \"storage\", {\n value: createStorage(store),\n configurable: true,\n enumerable: false,\n writable: true,\n });\n}\n","\"use client\";\n\n/**\n * Mounting an artifact (D57, D111): the generated client entry hands the page to\n * {@link mountArtifact}, or its `pages/` routes to `mountRoutes` from `@mostra/react/router`. The\n * client runtime starts first, so the page renders with the viewer's saved answers rather than\n * flashing its defaults; after a short wait it renders anyway and catches up when the gateway\n * answers.\n */\nimport { mostraPage, VERIFY_REPORT } from \"@mostra/protocol\";\nimport { type ComponentType, createElement, type ReactNode } from \"react\";\nimport { createRoot, type RootOptions } from \"react-dom/client\";\nimport { type ArtifactMode, RuntimeProvider } from \"./hooks.ts\";\nimport { type Runtime, startRuntime } from \"./runtime/boot.ts\";\nimport { setServerCallback } from \"./server-reference.ts\";\nimport { reportReady } from \"./shell-bridge.ts\";\nimport { installStorage } from \"./storage.ts\";\n\n/** How long the first render waits for the viewer's saved answers. */\nconst FIRST_RENDER_WAIT_MS = 3_000;\n\n/** Starts the runtime, installs `window.storage`, and resolves once the page can render. */\nexport async function prepareArtifact(): Promise<Runtime> {\n const runtime = await startRuntime();\n installStorage(runtime.store);\n // Server references call through this page's runtime in live mode (D54); elsewhere (a static\n // export, a page opened outside its shell) they keep refusing with `MOSTRA_TARGET_UNAVAILABLE`,\n // naming the function.\n if (runtime.store.mode === \"live\") {\n setServerCallback((id, args) => runtime.store.server.call(id, args));\n }\n await runtime.store.whenReady(FIRST_RENDER_WAIT_MS);\n return runtime;\n}\n\n/**\n * The root's error handlers: in the `verify` target, an error a boundary caught goes to verify's\n * recorder with its `cause` chain (React's default logs it with `console.error`, which verify\n * couldn't tell apart from the page's own logging); everywhere else, React's defaults.\n */\nfunction rootOptions(mode: string): RootOptions | undefined {\n if (mode !== \"verify\") return undefined;\n const report = (globalThis as unknown as Record<string, unknown>)[VERIFY_REPORT];\n if (typeof report !== \"function\") return undefined;\n return { onCaughtError: (error: unknown) => (report as (error: unknown) => void)(error) };\n}\n\n/** Renders `node` inside the runtime into `#root`, and reports `mostra/ready`. */\nexport function renderArtifact(runtime: Runtime, node: ReactNode): void {\n const root = document.getElementById(\"root\");\n if (!root) throw new Error(\"The page has no #root element.\");\n createRoot(root, rootOptions(runtime.mode)).render(\n createElement(\n RuntimeProvider,\n { store: runtime.store, mode: runtime.mode as ArtifactMode },\n node,\n ),\n );\n reportReady();\n}\n\n/** Tells the shell which page the viewer is on (D57), so comments record it. */\nexport function reportPage(runtime: Runtime, path: string, title?: string): void {\n runtime.shell?.bridge.notify(mostraPage, {\n path,\n ...(title !== undefined && title !== \"\" ? { title } : {}),\n });\n}\n\n/**\n * Mounts a single-page artifact: the generated entry calls it with the entry's default export.\n * Artifact code doesn't need to.\n */\nexport async function mountArtifact(options: { readonly page: ComponentType }): Promise<void> {\n const runtime = await prepareArtifact();\n renderArtifact(runtime, createElement(options.page));\n reportPage(runtime, \"/\", document.title);\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,KAAK,MAAsB;CACzC,OAAO,KAAK,UAAU,kBAAkB,OAAO,GAAG,KAAK,MAAM,GAAG,kBAAkB,CAAC,EAAE;AACvF;;AAGA,SAAgB,gBAAmB,OAAqB,SA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,YAAY;EACvC;EACA,GAAI,UAAU,KAAA,KAAa,UAAU,KAAK,EAAE,MAAM,IAAI,CAAC;CACzD,CAAC;AACH;;;;;AAMA,eAAsB,cAAc,SAA0D;CAC5F,MAAM,UAAU,MAAM,gBAAgB;CACtC,eAAe,SAAS,cAAc,QAAQ,IAAI,CAAC;CACnD,WAAW,SAAS,KAAK,SAAS,KAAK;AACzC"}
|
package/dist/router.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { i as reportPage, n as prepareArtifact, r as renderArtifact } from "./mount-
|
|
2
|
+
import { i as reportPage, n as prepareArtifact, r as renderArtifact } from "./mount-BN4Ra0tK.js";
|
|
3
3
|
import { createElement } from "react";
|
|
4
4
|
import { Outlet, createBrowserRouter, createHashRouter, createMemoryRouter } from "react-router";
|
|
5
5
|
import { RouterProvider } from "react-router/dom";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mostra/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Mostra client runtime for artifact authors: fields, submit, signals, choices, window.storage, routing and the shell bridge.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "The Mostra Authors",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"provenance": true
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@mostra/protocol": "0.
|
|
47
|
+
"@mostra/protocol": "0.7.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
50
|
"@mostra/tools": "0.0.0",
|
package/src/runtime/boot.ts
CHANGED
|
@@ -19,10 +19,14 @@ import {
|
|
|
19
19
|
import { builtVersion, connectShell, listenShell, type ShellConnection } from "../shell-bridge.ts";
|
|
20
20
|
import { blockersForShell, clip, firstThatMatter } from "./bridge-limits.ts";
|
|
21
21
|
import { IndexedDbJournal, type Journal, MemoryJournal } from "./journal.ts";
|
|
22
|
+
import { guardFrameServiceWorker } from "./service-worker.ts";
|
|
22
23
|
import { Store } from "./store.ts";
|
|
23
24
|
import { HttpTransport } from "./transport.ts";
|
|
24
25
|
import { installVerifyProbe } from "./verify-probe.ts";
|
|
25
26
|
|
|
27
|
+
// Before any artifact code runs: the generated entry imports the runtime first (D70).
|
|
28
|
+
guardFrameServiceWorker();
|
|
29
|
+
|
|
26
30
|
/** The page's runtime: its store, where it runs, and its shell connection. */
|
|
27
31
|
export interface Runtime {
|
|
28
32
|
readonly store: Store;
|
|
@@ -193,6 +197,9 @@ export async function startRuntime(): Promise<Runtime> {
|
|
|
193
197
|
mode: "live",
|
|
194
198
|
transport: new HttpTransport(view.viewId, {
|
|
195
199
|
...(shell.session.csrf !== "" ? { csrf: shell.session.csrf } : {}),
|
|
200
|
+
// Worker mode opens streams and polls with tickets, past the service worker (D70).
|
|
201
|
+
...(shell.session.mode === "worker" ? { tickets: true } : {}),
|
|
202
|
+
...(shell.session.streams ? {} : { streams: false }),
|
|
196
203
|
}),
|
|
197
204
|
journal,
|
|
198
205
|
view,
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The frame's service worker in worker mode (D70, D158 item 5): where the shell and the artifact
|
|
3
|
+
* are two sites, Mostra's own service worker at `/` signs every request of the frame with its
|
|
4
|
+
* session. An artifact's own worker can't run there: its script is fetched without the session
|
|
5
|
+
* (a browser adds nothing to that request), and a page it controlled would send requests no
|
|
6
|
+
* worker signs, so the page would lose its session. The client runtime refuses such a
|
|
7
|
+
* registration with a diagnostic the page can see, rather than letting it fail obscurely or end
|
|
8
|
+
* the session. On a tailnet, Funnel or local link (cookie mode) the artifact registers its own
|
|
9
|
+
* workers as usual.
|
|
10
|
+
*/
|
|
11
|
+
import { MostraError } from "./errors.ts";
|
|
12
|
+
|
|
13
|
+
/** Mostra's worker, which the gateway serves on every worker-mode artifact origin. */
|
|
14
|
+
const MOSTRA_WORKER = "/_mostra/sw.js";
|
|
15
|
+
|
|
16
|
+
/** Whether this page runs under Mostra's worker-mode service worker. */
|
|
17
|
+
export function workerModeFrame(): boolean {
|
|
18
|
+
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) return false;
|
|
19
|
+
const controller = navigator.serviceWorker.controller;
|
|
20
|
+
if (!controller) return false;
|
|
21
|
+
try {
|
|
22
|
+
return new URL(controller.scriptURL).pathname === MOSTRA_WORKER;
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let guarded = false;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* In a worker-mode frame, refuses an artifact's own service worker with
|
|
32
|
+
* `MOSTRA_HYGIENE_FRAME_SESSION` (rejecting the registration's promise and saying so on the
|
|
33
|
+
* console), instead of letting it fail without its session or end the page's. Installed once,
|
|
34
|
+
* before artifact code runs; a no-op anywhere else.
|
|
35
|
+
*/
|
|
36
|
+
export function guardFrameServiceWorker(): void {
|
|
37
|
+
if (guarded || !workerModeFrame()) return;
|
|
38
|
+
guarded = true;
|
|
39
|
+
const container = navigator.serviceWorker;
|
|
40
|
+
const register = container.register.bind(container);
|
|
41
|
+
const guard: typeof container.register = (scriptURL, options) => {
|
|
42
|
+
const script = new URL(String(scriptURL), location.href);
|
|
43
|
+
if (script.origin === location.origin && script.pathname === MOSTRA_WORKER) {
|
|
44
|
+
return register(scriptURL, options);
|
|
45
|
+
}
|
|
46
|
+
const scope = new URL(options?.scope ?? "./", script);
|
|
47
|
+
const error = new MostraError(
|
|
48
|
+
"MOSTRA_HYGIENE_FRAME_SESSION",
|
|
49
|
+
`This page opened through a link whose frame runs on Mostra's own service worker (a public Cloudflare link), so ${script.pathname} can't be registered here (scope ${scope.pathname}): it would run without the page's session. On a tailnet, Funnel or local link the page registers its own service workers.`,
|
|
50
|
+
);
|
|
51
|
+
console.error(`[MOSTRA_HYGIENE_FRAME_SESSION] ${error.message}`);
|
|
52
|
+
return Promise.reject(error);
|
|
53
|
+
};
|
|
54
|
+
container.register = guard;
|
|
55
|
+
}
|
package/src/runtime/transport.ts
CHANGED
|
@@ -80,6 +80,13 @@ export const KEEPALIVE_BODY_MAX: number = 64 * 1024 - 1024;
|
|
|
80
80
|
/** After this many stream failures in a row, the client long-polls instead (FAILURE_MODEL §8). */
|
|
81
81
|
const STREAM_FAILURES_BEFORE_POLL = 2;
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* How long a stream may stay silent after it opens before the page long-polls instead: the
|
|
85
|
+
* gateway's first message (`ready`) comes at once, so silence means something holds the stream
|
|
86
|
+
* back (a buffering proxy or tunnel, or a browser that stalled it, WP-13).
|
|
87
|
+
*/
|
|
88
|
+
export const STREAM_FIRST_MESSAGE_MS = 6_000;
|
|
89
|
+
|
|
83
90
|
/**
|
|
84
91
|
* The browser protocol over HTTP, on the artifact's origin. The CSRF token comes from
|
|
85
92
|
* `/_mostra/session`, once; a refusal is a {@link MostraError} with the gateway's diagnostic, and
|
|
@@ -88,18 +95,42 @@ const STREAM_FAILURES_BEFORE_POLL = 2;
|
|
|
88
95
|
export class HttpTransport implements Transport {
|
|
89
96
|
readonly #viewId: string;
|
|
90
97
|
readonly #base: string;
|
|
98
|
+
readonly #tickets: boolean;
|
|
99
|
+
readonly #streams: boolean;
|
|
91
100
|
#csrf: Promise<string> | undefined;
|
|
92
101
|
|
|
93
102
|
/**
|
|
94
103
|
* `csrf` is the session's token when the caller already read it (the bridge does): a save made
|
|
95
104
|
* as the page closes must not wait for a request the closing page would cancel (IN-02).
|
|
96
105
|
*/
|
|
97
|
-
constructor(
|
|
106
|
+
constructor(
|
|
107
|
+
viewId: string,
|
|
108
|
+
options: {
|
|
109
|
+
readonly csrf?: string;
|
|
110
|
+
readonly base?: string;
|
|
111
|
+
/**
|
|
112
|
+
* Worker mode (D70): every stream and poll opens with a single-use ticket, so it bypasses
|
|
113
|
+
* the service worker, which can't carry an endless response in Firefox.
|
|
114
|
+
*/
|
|
115
|
+
readonly tickets?: boolean;
|
|
116
|
+
/** `false` where event streams don't pass: the page long-polls from the start (D47). */
|
|
117
|
+
readonly streams?: boolean;
|
|
118
|
+
} = {},
|
|
119
|
+
) {
|
|
98
120
|
this.#viewId = viewId;
|
|
99
121
|
this.#base = options.base ?? `/_mostra/v/${BROWSER_PROTOCOL_REVISION}`;
|
|
122
|
+
this.#tickets = options.tickets === true;
|
|
123
|
+
this.#streams = options.streams !== false;
|
|
100
124
|
if (options.csrf) this.#csrf = Promise.resolve(options.csrf);
|
|
101
125
|
}
|
|
102
126
|
|
|
127
|
+
/** `&ticket=…` for a stream or poll in worker mode, else nothing. */
|
|
128
|
+
async #ticketQuery(): Promise<string> {
|
|
129
|
+
if (!this.#tickets) return "";
|
|
130
|
+
const { ticket } = (await this.#post("/ticket", { purpose: "stream" })) as { ticket: string };
|
|
131
|
+
return `&ticket=${encodeURIComponent(ticket)}`;
|
|
132
|
+
}
|
|
133
|
+
|
|
103
134
|
#token(): Promise<string> {
|
|
104
135
|
this.#csrf ??= (async () => {
|
|
105
136
|
const session = (await this.#request("/_mostra/session", { method: "GET" })) as {
|
|
@@ -264,9 +295,11 @@ export class HttpTransport implements Transport {
|
|
|
264
295
|
let backoff = 1_000;
|
|
265
296
|
while (!closed) {
|
|
266
297
|
try {
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
|
|
298
|
+
const ticket = await this.#ticketQuery();
|
|
299
|
+
const result = (await this.#request(
|
|
300
|
+
`${this.#base}/events/poll?${query()}&wait=25${ticket}`,
|
|
301
|
+
{ method: "GET" },
|
|
302
|
+
)) as PollResult;
|
|
270
303
|
backoff = 1_000;
|
|
271
304
|
handlers.onStatus("live");
|
|
272
305
|
if (result.snapshot) handlers.onSnapshot(result.snapshot);
|
|
@@ -287,13 +320,39 @@ export class HttpTransport implements Transport {
|
|
|
287
320
|
}
|
|
288
321
|
};
|
|
289
322
|
|
|
290
|
-
const open = (): void => {
|
|
323
|
+
const open = async (): Promise<void> => {
|
|
291
324
|
if (closed) return;
|
|
292
|
-
if (typeof EventSource === "undefined") {
|
|
325
|
+
if (typeof EventSource === "undefined" || !this.#streams) {
|
|
293
326
|
void poll();
|
|
294
327
|
return;
|
|
295
328
|
}
|
|
296
|
-
|
|
329
|
+
let ticket = "";
|
|
330
|
+
try {
|
|
331
|
+
ticket = await this.#ticketQuery();
|
|
332
|
+
} catch {
|
|
333
|
+
// No ticket, no stream: the page long-polls, which asks for its own tickets.
|
|
334
|
+
void poll();
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (closed) return;
|
|
338
|
+
const opened = new EventSource(`${this.#base}/events?${query()}${ticket}`);
|
|
339
|
+
source = opened;
|
|
340
|
+
// Silence after opening is a stream held back: poll at once, on the same cursor.
|
|
341
|
+
let heard = false;
|
|
342
|
+
const silent = setTimeout(() => {
|
|
343
|
+
if (heard || closed || source !== opened) return;
|
|
344
|
+
opened.close();
|
|
345
|
+
source = undefined;
|
|
346
|
+
handlers.onStatus("offline");
|
|
347
|
+
if (!polling) void poll();
|
|
348
|
+
}, STREAM_FIRST_MESSAGE_MS);
|
|
349
|
+
const hear = (): void => {
|
|
350
|
+
heard = true;
|
|
351
|
+
clearTimeout(silent);
|
|
352
|
+
};
|
|
353
|
+
opened.addEventListener("ready", hear);
|
|
354
|
+
opened.addEventListener("snapshot", hear);
|
|
355
|
+
opened.addEventListener("mostra", hear);
|
|
297
356
|
source.addEventListener("open", () => {
|
|
298
357
|
failures = 0;
|
|
299
358
|
handlers.onStatus("live");
|
|
@@ -329,10 +388,16 @@ export class HttpTransport implements Transport {
|
|
|
329
388
|
source?.close();
|
|
330
389
|
source = undefined;
|
|
331
390
|
if (!polling) void poll();
|
|
391
|
+
} else if (this.#tickets) {
|
|
392
|
+
// A ticket opens one connection: EventSource's own reconnect would present it again,
|
|
393
|
+
// so a ticketed stream reconnects itself, with a new ticket.
|
|
394
|
+
source?.close();
|
|
395
|
+
source = undefined;
|
|
396
|
+
retry = setTimeout(() => void open(), 1_000);
|
|
332
397
|
}
|
|
333
398
|
});
|
|
334
399
|
};
|
|
335
|
-
open();
|
|
400
|
+
void open();
|
|
336
401
|
return () => {
|
|
337
402
|
closed = true;
|
|
338
403
|
source?.close();
|
package/src/shell-bridge.ts
CHANGED
|
@@ -54,6 +54,10 @@ export interface ShellConnection {
|
|
|
54
54
|
readonly csrf: string;
|
|
55
55
|
readonly scopes: readonly string[];
|
|
56
56
|
readonly viewer?: Viewer;
|
|
57
|
+
/** `worker` when the frame authenticates through Mostra's service worker (D70, WP-13). */
|
|
58
|
+
readonly mode: "cookie" | "worker";
|
|
59
|
+
/** `false` where event streams don't pass (a Cloudflare quick tunnel): the page long-polls. */
|
|
60
|
+
readonly streams: boolean;
|
|
57
61
|
};
|
|
58
62
|
}
|
|
59
63
|
|
|
@@ -62,6 +66,8 @@ interface FrameSession {
|
|
|
62
66
|
readonly csrf?: unknown;
|
|
63
67
|
readonly scopes?: unknown;
|
|
64
68
|
readonly viewer?: unknown;
|
|
69
|
+
readonly mode?: unknown;
|
|
70
|
+
readonly streams?: unknown;
|
|
65
71
|
}
|
|
66
72
|
|
|
67
73
|
/** Hears what the shell sends: requests answered by the first handler that returns a value. */
|
|
@@ -147,6 +153,8 @@ export function connectShell(): Promise<ShellConnection | undefined> {
|
|
|
147
153
|
? session.scopes.filter((scope): scope is string => typeof scope === "string")
|
|
148
154
|
: [],
|
|
149
155
|
...(isViewer(session.viewer) ? { viewer: session.viewer } : {}),
|
|
156
|
+
mode: session.mode === "worker" ? ("worker" as const) : ("cookie" as const),
|
|
157
|
+
streams: session.streams !== false,
|
|
150
158
|
},
|
|
151
159
|
};
|
|
152
160
|
})().then(
|