@mostra/react 0.10.0 → 0.12.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.
@@ -1 +1 @@
1
- {"version":3,"file":"mount-BCj41qky.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,SAAoC;CAC1F,IAAI,MAAM,UAAU,mBAAmB,OAAO,CAAC,GAAG,KAAK;CACvD,OAAO,CAAC,GAAG,MAAM,OAAO,OAAO,GAAG,GAAG,MAAM,QAAQ,SAA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MAAM,UAAU,MAAM,gBAAgB;CACtC,eAAe,SAAS,cAAc,QAAQ,IAAI,CAAC;CACnD,WAAW,SAAS,KAAK,SAAS,KAAK;AACzC"}
1
+ {"version":3,"file":"mount-DmfrLZvk.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,SAAoC;CAC1F,IAAI,MAAM,UAAU,mBAAmB,OAAO,CAAC,GAAG,KAAK;CACvD,OAAO,CAAC,GAAG,MAAM,OAAO,OAAO,GAAG,GAAG,MAAM,QAAQ,SAAS,CA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,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-BCj41qky.js";
2
+ import { i as reportPage, n as prepareArtifact, r as renderArtifact } from "./mount-DmfrLZvk.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.10.0",
3
+ "version": "0.12.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.10.0"
47
+ "@mostra/protocol": "0.12.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@mostra/tools": "0.0.0",
@@ -80,7 +80,7 @@
80
80
  "react-router",
81
81
  "react-hook-form"
82
82
  ],
83
- "limit": "54 kB"
83
+ "limit": "56 kB"
84
84
  },
85
85
  {
86
86
  "name": "@mostra/react whole entry, zod excluded",
@@ -93,7 +93,7 @@
93
93
  "react-hook-form",
94
94
  "zod"
95
95
  ],
96
- "limit": "31 kB"
96
+ "limit": "33 kB"
97
97
  }
98
98
  ],
99
99
  "peerDependencies": {
package/src/hooks.ts CHANGED
@@ -125,8 +125,18 @@ export interface FieldMeta<T> {
125
125
  readonly error?: string;
126
126
  /** Another writer changed the field since the viewer's edit: keep theirs or mine. */
127
127
  readonly conflict?: { readonly theirs: T; keepMine(): void; takeTheirs(): void };
128
- /** Who last wrote the field (artifact scope, D63). */
129
- readonly updatedBy?: { readonly kind: "viewer" | "agent" | "host"; readonly name?: string };
128
+ /**
129
+ * Who last wrote the field and when (artifact scope, D63, D168): a viewer by name and by their
130
+ * key on this artifact (the same `key` `useRespondents` and `usePresence` give), an agent or a
131
+ * host; `self` when it was this viewer.
132
+ */
133
+ readonly updatedBy?: {
134
+ readonly kind: "viewer" | "agent" | "host";
135
+ readonly name?: string;
136
+ readonly key?: string;
137
+ readonly self?: boolean;
138
+ readonly at?: string;
139
+ };
130
140
  }
131
141
 
132
142
  /** What a field's validator says of a value: now, or once its asynchronous check settles. */
@@ -157,9 +167,19 @@ function validationOf<T>(validate: FieldOptions<T>["validate"], value: T): Valid
157
167
  return { kind: "now", error: messageOf(result) };
158
168
  }
159
169
 
160
- function updatedByOf(actor: Actor | undefined): FieldMeta<unknown>["updatedBy"] {
170
+ function updatedByOf(
171
+ actor: Actor | undefined,
172
+ at: string | undefined,
173
+ viewerId: string | undefined,
174
+ ): FieldMeta<unknown>["updatedBy"] {
161
175
  if (!actor || actor.kind === "mostra") return undefined;
162
- return { kind: actor.kind, ...(actor.name !== undefined ? { name: actor.name } : {}) };
176
+ return {
177
+ kind: actor.kind,
178
+ ...(actor.name !== undefined ? { name: actor.name } : {}),
179
+ ...(actor.key !== undefined ? { key: actor.key } : {}),
180
+ ...(actor.kind === "viewer" && viewerId !== undefined ? { self: actor.id === viewerId } : {}),
181
+ ...(at !== undefined ? { at } : {}),
182
+ };
163
183
  }
164
184
 
165
185
  const warned = new Set<string>();
@@ -282,15 +302,15 @@ export function useField<T>(
282
302
  const conflict = store.conflict(key);
283
303
  const refusal = store.refusal(key);
284
304
  const save = store.save(key);
285
- const writer = updatedByOf(store.updatedBy(key));
286
- const writerKind = writer?.kind;
287
- const writerName = writer?.name;
305
+ const writer = updatedByOf(store.updatedBy(key), store.updatedAt(key), store.viewer()?.id);
306
+ // One string for the memo: a change of who, when or self re-renders the meta.
307
+ const writerText = writer === undefined ? undefined : JSON.stringify(writer);
288
308
  const meta = useMemo((): FieldMeta<T> => {
289
309
  const message = error ?? refusal?.message;
290
310
  const updatedBy =
291
- writerKind === undefined
311
+ writerText === undefined
292
312
  ? undefined
293
- : { kind: writerKind, ...(writerName !== undefined ? { name: writerName } : {}) };
313
+ : (JSON.parse(writerText) as NonNullable<FieldMeta<T>["updatedBy"]>);
294
314
  return {
295
315
  save,
296
316
  ...(message !== undefined ? { error: message } : {}),
@@ -305,7 +325,7 @@ export function useField<T>(
305
325
  : {}),
306
326
  ...(scope === "artifact" && updatedBy ? { updatedBy } : {}),
307
327
  };
308
- }, [save, error, refusal, conflict, writerKind, writerName, store, key, scope, first]);
328
+ }, [save, error, refusal, conflict, writerText, store, key, scope, first]);
309
329
  return [value, set, meta];
310
330
  }
311
331
 
@@ -501,6 +521,8 @@ export function useViewer(): {
501
521
  readonly id: string;
502
522
  readonly name?: string;
503
523
  readonly source: ViewerKind;
524
+ /** On a hosted link: `true` for a signed-in account, `false` for an anonymous viewer's name. */
525
+ readonly verified?: boolean;
504
526
  } {
505
527
  const { store } = useRuntime();
506
528
  useStoreVersion(store);
@@ -510,6 +532,7 @@ export function useViewer(): {
510
532
  id: viewer.id,
511
533
  ...(viewer.name !== undefined ? { name: viewer.name } : {}),
512
534
  source: viewer.kind,
535
+ ...(viewer.verified !== undefined ? { verified: viewer.verified } : {}),
513
536
  }
514
537
  : { id: "", source: "local" };
515
538
  }
package/src/index.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * `@mostra/react`: the client runtime artifact authors import (INTERFACES §2.3). Fields that behave
5
5
  * like `useState` with a stable ID and persist as the viewer works, the artifact channel's
6
6
  * submit, the shell's trusted Submit label, signals, review-set choices, the viewer and the
7
- * artifact, a Claude-compatible `window.storage`, and the manifest helper. `@mostra/react/form`
7
+ * artifact, expected respondents and presence, a Claude-compatible `window.storage`, and the
8
+ * manifest helper. `@mostra/react/form`
8
9
  * adapts react-hook-form; `@mostra/react/router` mounts `pages/` artifacts.
9
10
  *
10
11
  * ```tsx
@@ -66,6 +67,21 @@ export {
66
67
  } from "./server-reference.ts";
67
68
  export { connectShell, openLink, reportReady, type ShellConnection } from "./shell-bridge.ts";
68
69
  export type { ClaudeCompatibleStorage, StorageEntry } from "./storage.ts";
70
+ export {
71
+ type Peer,
72
+ type Presence,
73
+ type PresenceCursor,
74
+ type PresenceOptions,
75
+ type PresencePeer,
76
+ type PresenceSelection,
77
+ type RespondentForPage,
78
+ type RespondentStatus,
79
+ type Respondents,
80
+ type RosterCounts,
81
+ type TeamVisibility,
82
+ usePresence,
83
+ useRespondents,
84
+ } from "./team-hooks.ts";
69
85
 
70
86
  /**
71
87
  * Declares an artifact's manifest (INTERFACES §2.2, D51). Mostra reads the object statically
@@ -702,9 +702,11 @@ export class ServerClient {
702
702
  }
703
703
  if (!this.#merge(tracked, message.run))
704
704
  void this.attach({ runIds: [message.run.runId] }).catch(() => {});
705
- } else {
705
+ } else if (message.kind === "live") {
706
706
  void this.#applyLiveUpdate(message.live);
707
707
  }
708
+ // Other kinds (the roster and presence, D168) are the team client's; a kind a newer gateway
709
+ // adds is none of this client's either.
708
710
  }
709
711
 
710
712
  /** Keeps an update for a run the page will track once its start is answered. */
@@ -34,6 +34,7 @@ import {
34
34
  import { MostraError, targetUnavailable } from "./errors.ts";
35
35
  import type { Journal, JournalEntry, MutationEntry, PendingEntry } from "./journal.ts";
36
36
  import { ServerClient } from "./server-client.ts";
37
+ import { TeamClient } from "./team.ts";
37
38
  import { NetworkError, type Transport } from "./transport.ts";
38
39
 
39
40
  /** How long the page waits after the last edit before it saves (INTERFACES §2.3). */
@@ -61,6 +62,8 @@ interface ServerField {
61
62
  readonly revision: number;
62
63
  readonly deleted: boolean;
63
64
  readonly updatedBy?: Actor;
65
+ /** When it was written last (D168: attribution says who and when). */
66
+ readonly updatedAt?: string;
64
67
  }
65
68
 
66
69
  /** A conflict the viewer hasn't resolved: what the field holds now. */
@@ -265,6 +268,8 @@ export class Store {
265
268
  #stopStream: (() => void) | undefined;
266
269
  /** Plain calls, action runs and live sources (WP-08), over the same transport and view. */
267
270
  readonly server: ServerClient;
271
+ /** The roster and presence (WP-31, D168), over the same transport and view. */
272
+ readonly team: TeamClient;
268
273
 
269
274
  constructor(options: StoreOptions) {
270
275
  this.#options = options;
@@ -273,6 +278,11 @@ export class Store {
273
278
  ...(options.mode === "live" && options.view ? { viewId: options.view.viewId } : {}),
274
279
  ...(options.timers ? { timers: options.timers } : {}),
275
280
  });
281
+ this.team = new TeamClient({
282
+ ...(options.mode === "live" && options.transport ? { transport: options.transport } : {}),
283
+ ...(options.mode === "live" && options.view ? { viewId: options.view.viewId } : {}),
284
+ ...(options.timers ? { timers: options.timers } : {}),
285
+ });
276
286
  this.mode = options.mode;
277
287
  this.view = options.view;
278
288
  this.#viewer = options.viewer;
@@ -351,11 +361,16 @@ export class Store {
351
361
  this.#kickQueue();
352
362
  // Run and live updates sent while the stream was down are gone: read them again.
353
363
  this.server.resync();
364
+ this.team.resync();
354
365
  }
355
366
  this.#changed(this.#allKeys());
356
367
  }
357
368
  },
358
- onEphemeral: (message) => this.server.receive(message),
369
+ onEphemeral: (message) => {
370
+ if (message.kind === "respondents" || message.kind === "presence")
371
+ this.team.receive(message);
372
+ else this.server.receive(message);
373
+ },
359
374
  });
360
375
  if (typeof window !== "undefined") {
361
376
  window.addEventListener("online", () => this.#kickQueue());
@@ -366,6 +381,7 @@ export class Store {
366
381
  stop(): void {
367
382
  this.#stopStream?.();
368
383
  this.server.stop();
384
+ this.team.stop();
369
385
  this.#broadcast?.close();
370
386
  if (this.#debounce !== undefined) this.#timers.clearTimeout(this.#debounce);
371
387
  if (this.#retry !== undefined) this.#timers.clearTimeout(this.#retry);
@@ -412,6 +428,7 @@ export class Store {
412
428
  revision: Number(field.revision),
413
429
  deleted: false,
414
430
  ...(field.updatedBy ? { updatedBy: field.updatedBy } : {}),
431
+ updatedAt: field.updatedAt,
415
432
  });
416
433
  }
417
434
  return replace;
@@ -468,6 +485,7 @@ export class Store {
468
485
  revision,
469
486
  deleted: false,
470
487
  updatedBy: event.actor,
488
+ updatedAt: event.at,
471
489
  });
472
490
  } else {
473
491
  // The page still shows the old value: until the snapshot brings the new one, an
@@ -483,6 +501,7 @@ export class Store {
483
501
  revision,
484
502
  deleted: change.deleted === true,
485
503
  updatedBy: event.actor,
504
+ updatedAt: event.at,
486
505
  });
487
506
  }
488
507
  this.#seen[scope] = Math.max(this.#seen[scope], revision);
@@ -561,6 +580,11 @@ export class Store {
561
580
  return this.#server.get(key)?.updatedBy;
562
581
  }
563
582
 
583
+ /** When the field was written last, as the gateway or this page knows it. */
584
+ updatedAt(key: FieldKey): string | undefined {
585
+ return this.#server.get(key)?.updatedAt;
586
+ }
587
+
564
588
  /** Why the gateway refused the field's edit for good, if it did: its code and message. */
565
589
  refusal(key: FieldKey): { readonly code: string; readonly message: string } | undefined {
566
590
  return this.#refused.get(key);
@@ -1046,6 +1070,7 @@ export class Store {
1046
1070
  revision,
1047
1071
  deleted: op.delete === true,
1048
1072
  updatedBy: { kind: "viewer", ...(this.#viewer ? { id: this.#viewer.id } : {}) },
1073
+ updatedAt: new Date().toISOString(),
1049
1074
  });
1050
1075
  }
1051
1076
  applied.push({ id: op.id, value: mine });
@@ -1310,6 +1335,7 @@ export class Store {
1310
1335
  revision: data.revision,
1311
1336
  deleted: change.value === undefined,
1312
1337
  ...(current?.updatedBy ? { updatedBy: current.updatedBy } : {}),
1338
+ ...(current?.updatedAt !== undefined ? { updatedAt: current.updatedAt } : {}),
1313
1339
  });
1314
1340
  touched.push(key);
1315
1341
  }