@mostra/react 0.0.0-stage → 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks-Dh_l8KqJ.js","names":[],"sources":["../src/runtime/errors.ts","../src/runtime/journal.ts","../src/runtime/transport.ts","../src/runtime/server-client.ts","../src/runtime/store.ts","../src/shell-bridge.ts","../src/hooks.ts"],"sourcesContent":["/**\n * Errors the client runtime throws: each carries the stable diagnostic code an artifact can switch\n * on (INTERFACES §13), and the diagnostic itself when the gateway sent one.\n */\n\n/** A diagnostic as the gateway sends it; only the fields the runtime reads. */\nexport interface DiagnosticLike {\n /** The stable diagnostic code, such as `MOSTRA_FIELD_TOO_LARGE`. */\n readonly code: string;\n /** What is wrong. */\n readonly message: string;\n /** What to do about it. */\n readonly hint?: string;\n /** The code's documentation page. */\n readonly docs?: string;\n}\n\n/** An error with a Mostra diagnostic code, such as `MOSTRA_SUBMIT_CHANNEL_DENIED`. */\nexport class MostraError extends Error {\n /** The stable diagnostic code. */\n readonly code: string;\n /** The HTTP status the gateway answered with, when the error came from it. */\n readonly status: number | undefined;\n /** The diagnostic, when the gateway sent one. */\n readonly diagnostic: DiagnosticLike | undefined;\n /** Extra data the refusal carried, such as the existing submission of `MOSTRA_SUBMIT_ALREADY`. */\n readonly body: Readonly<Record<string, unknown>> | undefined;\n\n constructor(\n code: string,\n message: string,\n options: {\n readonly status?: number;\n readonly diagnostic?: DiagnosticLike;\n readonly body?: Readonly<Record<string, unknown>>;\n } = {},\n ) {\n super(message);\n this.name = \"MostraError\";\n this.code = code;\n this.status = options.status;\n this.diagnostic = options.diagnostic;\n this.body = options.body;\n }\n}\n\n/** `MOSTRA_TARGET_UNAVAILABLE`: what the delivery target can't do (a static export, D111). */\nexport function targetUnavailable(what: string): MostraError {\n return new MostraError(\n \"MOSTRA_TARGET_UNAVAILABLE\",\n `${what} needs the artifact's Mostra link; this copy of the page has no Mostra server.`,\n );\n}\n","/**\n * The offline journal (D22, IN-02, IN-04): every edit the gateway hasn't confirmed, kept in the\n * artifact origin's IndexedDB so a closed tab, a crash or a lost connection loses nothing. Two\n * kinds of entry: a field's pending edit (not sent yet; its newest value wins), and a mutation that\n * was sent or is about to be, kept with its mutation ID so a replay is idempotent. Every entry\n * names its viewer and the tab that wrote it: a page replays only its own viewer's entries, and\n * adopts another tab's only once that tab is gone, so two open tabs never overwrite each other's\n * unsent edits. Where IndexedDB can't be used the journal lives in memory and says so.\n */\nimport type { FieldOp } from \"@mostra/protocol\";\n\n/** A field's edit, not sent yet. */\nexport interface PendingEntry {\n readonly kind: \"pending\";\n readonly viewerId: string;\n /** The tab that made the edit. */\n readonly tab: string;\n readonly viewId: string;\n readonly scope: \"viewer\" | \"artifact\";\n readonly op: FieldOp;\n /**\n * The revision the edit was based on: the field was unchanged since it (D22). `null` while an\n * earlier mutation of the same field is in flight; its answer sets it.\n */\n readonly base: number | null;\n /** When the edit was made (ms since the epoch). */\n readonly at: number;\n}\n\n/** A mutation, sent or about to be, replayed with its own ID. */\nexport interface MutationEntry {\n readonly kind: \"mutation\";\n readonly viewerId: string;\n readonly tab: string;\n readonly viewId: string;\n readonly scope: \"viewer\" | \"artifact\";\n readonly mutationId: string;\n readonly baseRevision: number;\n readonly ops: readonly FieldOp[];\n /** Its place in the journal: mutations replay in this order. */\n readonly seq: number;\n}\n\n/** One entry. */\nexport type JournalEntry = PendingEntry | MutationEntry;\n\n/** A viewer's entries, mutations in journal order. */\nexport interface JournalContents {\n readonly pending: PendingEntry[];\n readonly mutations: MutationEntry[];\n}\n\n/** The journal's storage. */\nexport interface Journal {\n /** Whether entries survive the page (IndexedDB), or live only in memory. */\n readonly durable: boolean;\n /** Every entry of a viewer, mutations in order. */\n load(viewerId: string): Promise<JournalContents>;\n /** Records a pending edit, replacing the same tab's earlier one for the field. */\n putPending(entry: PendingEntry): Promise<void>;\n /** Turns pending edits into a mutation in one transaction. */\n promote(mutation: MutationEntry, consumed: readonly PendingEntry[]): Promise<void>;\n /** Forgets a mutation the gateway answered. */\n remove(mutationId: string): Promise<void>;\n /** Forgets a field's pending edit (taken back, or refused for good). */\n dropPending(entry: PendingEntry): Promise<void>;\n /** Moves entries of a tab that is gone to `tab`, in one transaction. */\n adopt(entries: readonly JournalEntry[], tab: string): Promise<void>;\n}\n\n/** The key of a pending edit: one per viewer, tab, scope and field. */\nexport const pendingKey = (\n entry: Pick<PendingEntry, \"viewerId\" | \"tab\" | \"scope\" | \"op\">,\n): string => `p\\u0000${entry.viewerId}\\u0000${entry.tab}\\u0000${entry.scope}\\u0000${entry.op.id}`;\n\nconst mutationKey = (mutationId: string): string => `m\\u0000${mutationId}`;\n\nconst keyOf = (entry: JournalEntry): string =>\n entry.kind === \"pending\" ? pendingKey(entry) : mutationKey(entry.mutationId);\n\nfunction split(entries: readonly JournalEntry[], viewerId: string): JournalContents {\n const mine = entries.filter((entry) => entry.viewerId === viewerId);\n return {\n pending: mine.filter((entry): entry is PendingEntry => entry.kind === \"pending\"),\n mutations: mine\n .filter((entry): entry is MutationEntry => entry.kind === \"mutation\")\n .sort((a, b) => a.seq - b.seq),\n };\n}\n\n/** The journal in memory: for targets without IndexedDB, and for tests. */\nexport class MemoryJournal implements Journal {\n readonly durable: boolean = false;\n readonly #entries = new Map<string, JournalEntry>();\n\n async load(viewerId: string): Promise<JournalContents> {\n return split([...this.#entries.values()], viewerId);\n }\n\n async putPending(entry: PendingEntry): Promise<void> {\n this.#entries.set(pendingKey(entry), entry);\n }\n\n async promote(mutation: MutationEntry, consumed: readonly PendingEntry[]): Promise<void> {\n for (const entry of consumed) this.#entries.delete(pendingKey(entry));\n this.#entries.set(mutationKey(mutation.mutationId), mutation);\n }\n\n async remove(mutationId: string): Promise<void> {\n this.#entries.delete(mutationKey(mutationId));\n }\n\n async dropPending(entry: PendingEntry): Promise<void> {\n this.#entries.delete(pendingKey(entry));\n }\n\n async adopt(entries: readonly JournalEntry[], tab: string): Promise<void> {\n for (const entry of entries) {\n this.#entries.delete(keyOf(entry));\n const moved = { ...entry, tab };\n const key = keyOf(moved);\n // A tab's own newer edit of the same field wins over an adopted one.\n if (!this.#entries.has(key)) this.#entries.set(key, moved);\n }\n }\n}\n\nconst DB_NAME = \"mostra\";\nconst STORE = \"journal\";\n\nfunction request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nfunction done(transaction: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error);\n transaction.onabort = () => reject(transaction.error ?? new Error(\"The transaction aborted.\"));\n });\n}\n\n/**\n * The journal in the artifact origin's IndexedDB: one database per origin, so per artifact (D38).\n * Each write starts its transaction at once, so an edit made just before the page closes is in it.\n */\nexport class IndexedDbJournal implements Journal {\n readonly durable: boolean = true;\n readonly #db: IDBDatabase;\n\n private constructor(db: IDBDatabase) {\n this.#db = db;\n }\n\n /** Opens the journal; `undefined` where IndexedDB can't be used (a private mode, a sandbox). */\n static async open(): Promise<IndexedDbJournal | undefined> {\n if (typeof indexedDB === \"undefined\") return undefined;\n try {\n const open = indexedDB.open(DB_NAME, 1);\n open.onupgradeneeded = () => {\n if (!open.result.objectStoreNames.contains(STORE)) open.result.createObjectStore(STORE);\n };\n return new IndexedDbJournal(await request(open));\n } catch {\n return undefined;\n }\n }\n\n #write(change: (store: IDBObjectStore) => void): Promise<void> {\n const transaction = this.#db.transaction(STORE, \"readwrite\");\n change(transaction.objectStore(STORE));\n return done(transaction);\n }\n\n async load(viewerId: string): Promise<JournalContents> {\n const all = (await request(\n this.#db.transaction(STORE, \"readonly\").objectStore(STORE).getAll(),\n )) as JournalEntry[];\n return split(all, viewerId);\n }\n\n putPending(entry: PendingEntry): Promise<void> {\n return this.#write((store) => store.put(entry, pendingKey(entry)));\n }\n\n promote(mutation: MutationEntry, consumed: readonly PendingEntry[]): Promise<void> {\n return this.#write((store) => {\n for (const entry of consumed) store.delete(pendingKey(entry));\n store.put(mutation, mutationKey(mutation.mutationId));\n });\n }\n\n remove(mutationId: string): Promise<void> {\n return this.#write((store) => store.delete(mutationKey(mutationId)));\n }\n\n dropPending(entry: PendingEntry): Promise<void> {\n return this.#write((store) => store.delete(pendingKey(entry)));\n }\n\n async adopt(entries: readonly JournalEntry[], tab: string): Promise<void> {\n const transaction = this.#db.transaction(STORE, \"readwrite\");\n const store = transaction.objectStore(STORE);\n for (const entry of entries) {\n store.delete(keyOf(entry));\n const moved = { ...entry, tab };\n // `add` fails on an existing key: a tab's own newer edit wins over an adopted one.\n const added = store.add(moved, keyOf(moved));\n added.onerror = (event) => {\n event.preventDefault();\n event.stopPropagation();\n };\n }\n await done(transaction);\n }\n}\n","/**\n * How the client runtime reaches Mostra (INTERFACES §4): the browser protocol over the artifact's\n * own origin, with its session cookie and CSRF token. A delivery target without a gateway (a\n * static export, an MCP App before its transport, D111) gets another implementation of the same\n * interface, so hooks never know which they talk to.\n */\nimport {\n BROWSER_PROTOCOL_REVISION,\n type CallLine,\n type CallRequest,\n type EphemeralMessage,\n type EventRecord,\n type FieldsRequest,\n type LiveRequest,\n type LiveState,\n type LiveUpdate,\n type MutationResult,\n type PollResult,\n type RunAttachRequest,\n type RunDelta,\n type RunRequest,\n type RunState,\n type SignalRequest,\n type StreamSnapshot,\n type SubmissionSummary,\n type SubmitRequest,\n} from \"@mostra/protocol\";\nimport { type DiagnosticLike, MostraError } from \"./errors.ts\";\n\n/** The connection to the gateway failed before it answered: the page is offline. */\nexport class NetworkError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** What a subscription hears. */\nexport interface StreamHandlers {\n /** Where the page stands, first, and again after a compacted cursor. */\n onSnapshot(snapshot: StreamSnapshot): void;\n /** Durable events after the last cursor, in order. */\n onEvents(events: readonly EventRecord[]): void;\n /** The stream's health: `live` while connected, `offline` while it retries, `revoked` at the end. */\n onStatus(status: \"live\" | \"offline\" | \"revoked\"): void;\n /** Run and live updates (WP-08): lossy, never events, so a page reads again what it missed. */\n onEphemeral?(message: EphemeralMessage): void;\n}\n\n/** The client runtime's way to Mostra. */\nexport interface Transport {\n /** Where the page stands: its viewer, draft, the artifact state and their cursor. */\n snapshot(): Promise<StreamSnapshot>;\n /** One mutation (`fields`); `keepalive` lets it outlive the page (`pagehide`). */\n mutate(\n request: FieldsRequest,\n options?: { readonly keepalive?: boolean },\n ): Promise<MutationResult>;\n /** A submit through the artifact channel. */\n submit(request: SubmitRequest): Promise<SubmissionSummary>;\n /** A signal. */\n signal(request: SignalRequest): Promise<{ readonly cursor: string }>;\n /** Hears the page's events after `cursor`; returns the function that stops. */\n subscribe(cursor: string | undefined, handlers: StreamHandlers): () => void;\n /** A plain server-function call (D54): its result's lines as they come. */\n call?(fnId: string, request: CallRequest, signal?: AbortSignal): AsyncIterable<CallLine>;\n /** Starts or joins an action run (AC-02, AC-03). */\n startRun?(request: RunRequest): Promise<RunState>;\n /** Reads runs and follows them for a minute. */\n attachRuns?(request: RunAttachRequest): Promise<{ readonly runs: readonly RunState[] }>;\n /** Cancels a run (AC-04). */\n cancelRun?(runId: string, viewId: string): Promise<RunState>;\n /** Reads live sources and keeps them produced for a minute (D56). */\n live?(request: LiveRequest): Promise<{ readonly sources: readonly LiveState[] }>;\n}\n\n/** The longest body `fetch` sends with `keepalive` (the Fetch standard's 64 KiB budget). */\nexport const KEEPALIVE_BODY_MAX: number = 64 * 1024 - 1024;\n\n/** After this many stream failures in a row, the client long-polls instead (FAILURE_MODEL §8). */\nconst STREAM_FAILURES_BEFORE_POLL = 2;\n\n/**\n * The browser protocol over HTTP, on the artifact's origin. The CSRF token comes from\n * `/_mostra/session`, once; a refusal is a {@link MostraError} with the gateway's diagnostic, and\n * an unreachable gateway a {@link NetworkError}.\n */\nexport class HttpTransport implements Transport {\n readonly #viewId: string;\n readonly #base: string;\n #csrf: Promise<string> | undefined;\n\n /**\n * `csrf` is the session's token when the caller already read it (the bridge does): a save made\n * as the page closes must not wait for a request the closing page would cancel (IN-02).\n */\n constructor(viewId: string, options: { readonly csrf?: string; readonly base?: string } = {}) {\n this.#viewId = viewId;\n this.#base = options.base ?? `/_mostra/v/${BROWSER_PROTOCOL_REVISION}`;\n if (options.csrf) this.#csrf = Promise.resolve(options.csrf);\n }\n\n #token(): Promise<string> {\n this.#csrf ??= (async () => {\n const session = (await this.#request(\"/_mostra/session\", { method: \"GET\" })) as {\n csrf: string;\n };\n return session.csrf;\n })().catch((error: unknown) => {\n this.#csrf = undefined;\n throw error;\n });\n return this.#csrf;\n }\n\n async #request(path: string, init: RequestInit): Promise<unknown> {\n let response: Response;\n try {\n response = await fetch(path, { credentials: \"same-origin\", cache: \"no-store\", ...init });\n } catch (error) {\n throw new NetworkError((error as Error).message);\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = undefined;\n }\n if (!response.ok) {\n const diagnostic = (body ?? {}) as Partial<DiagnosticLike> & Record<string, unknown>;\n // A proxy or a restarting gateway answers without a diagnostic: that is a network failure.\n if (typeof diagnostic.code !== \"string\") {\n throw new NetworkError(`The gateway answered ${response.status}.`);\n }\n throw new MostraError(diagnostic.code, diagnostic.message ?? diagnostic.code, {\n status: response.status,\n diagnostic: diagnostic as DiagnosticLike,\n body: diagnostic,\n });\n }\n return body;\n }\n\n async #post(path: string, body: unknown, keepalive = false): Promise<unknown> {\n const text = JSON.stringify(body);\n const csrf = await this.#token();\n return this.#request(`${this.#base}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-mostra-csrf\": csrf },\n body: text,\n keepalive: keepalive && text.length < KEEPALIVE_BODY_MAX,\n });\n }\n\n async snapshot(): Promise<StreamSnapshot> {\n const result = (await this.#request(`${this.#base}/events/poll?view=${this.#viewId}&wait=0`, {\n method: \"GET\",\n })) as PollResult;\n if (!result.snapshot) throw new NetworkError(\"The gateway sent no snapshot.\");\n return result.snapshot;\n }\n\n mutate(\n request: FieldsRequest,\n options?: { readonly keepalive?: boolean },\n ): Promise<MutationResult> {\n return this.#post(\"/fields\", request, options?.keepalive === true) as Promise<MutationResult>;\n }\n\n submit(request: SubmitRequest): Promise<SubmissionSummary> {\n return this.#post(\"/submit\", request) as Promise<SubmissionSummary>;\n }\n\n signal(request: SignalRequest): Promise<{ readonly cursor: string }> {\n return this.#post(\"/signal\", request) as Promise<{ cursor: string }>;\n }\n\n async *call(fnId: string, request: CallRequest, signal?: AbortSignal): AsyncIterable<CallLine> {\n const csrf = await this.#token();\n let response: Response;\n try {\n response = await fetch(`${this.#base}/call/${encodeURIComponent(fnId)}`, {\n method: \"POST\",\n credentials: \"same-origin\",\n cache: \"no-store\",\n headers: { \"content-type\": \"application/json\", \"x-mostra-csrf\": csrf },\n body: JSON.stringify(request),\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n throw new NetworkError((error as Error).message);\n }\n if (!response.ok || !response.body) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = undefined;\n }\n const diagnostic = (body ?? {}) as Partial<DiagnosticLike>;\n if (typeof diagnostic.code !== \"string\") {\n throw new NetworkError(`The gateway answered ${response.status}.`);\n }\n throw new MostraError(diagnostic.code, diagnostic.message ?? diagnostic.code, {\n status: response.status,\n diagnostic: diagnostic as DiagnosticLike,\n });\n }\n // NDJSON: one line per batch, then the end.\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n let buffer = \"\";\n try {\n for (;;) {\n let chunk: ReadableStreamReadResult<string>;\n try {\n chunk = await reader.read();\n } catch (error) {\n throw new NetworkError((error as Error).message);\n }\n if (chunk.done) break;\n buffer += chunk.value;\n let newline = buffer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n if (line.trim() !== \"\") yield JSON.parse(line) as CallLine;\n newline = buffer.indexOf(\"\\n\");\n }\n }\n } finally {\n reader.releaseLock();\n }\n if (buffer.trim() !== \"\") yield JSON.parse(buffer) as CallLine;\n }\n\n startRun(request: RunRequest): Promise<RunState> {\n return this.#post(\"/runs\", request) as Promise<RunState>;\n }\n\n attachRuns(request: RunAttachRequest): Promise<{ readonly runs: readonly RunState[] }> {\n return this.#post(\"/runs/attach\", request) as Promise<{ runs: RunState[] }>;\n }\n\n cancelRun(runId: string, viewId: string): Promise<RunState> {\n return this.#post(`/runs/${encodeURIComponent(runId)}/cancel`, { viewId }) as Promise<RunState>;\n }\n\n live(request: LiveRequest): Promise<{ readonly sources: readonly LiveState[] }> {\n return this.#post(\"/live\", request) as Promise<{ sources: LiveState[] }>;\n }\n\n subscribe(cursor: string | undefined, handlers: StreamHandlers): () => void {\n let closed = false;\n let last = cursor;\n let source: EventSource | undefined;\n let failures = 0;\n let polling = false;\n let retry: ReturnType<typeof setTimeout> | undefined;\n const query = (): string =>\n `view=${this.#viewId}${last === undefined ? \"\" : `&cursor=${last}`}`;\n\n const poll = async (): Promise<void> => {\n polling = true;\n let backoff = 1_000;\n while (!closed) {\n try {\n const result = (await this.#request(`${this.#base}/events/poll?${query()}&wait=25`, {\n method: \"GET\",\n })) as PollResult;\n backoff = 1_000;\n handlers.onStatus(\"live\");\n if (result.snapshot) handlers.onSnapshot(result.snapshot);\n if (result.events.length > 0) handlers.onEvents(result.events);\n for (const message of result.ephemeral ?? []) handlers.onEphemeral?.(message);\n last = result.cursor;\n } catch (error) {\n if (error instanceof MostraError && error.code === \"MOSTRA_HYGIENE_TOKEN_REVOKED\") {\n handlers.onStatus(\"revoked\");\n return;\n }\n handlers.onStatus(\"offline\");\n await new Promise((resolve) => {\n retry = setTimeout(resolve, backoff);\n });\n backoff = Math.min(backoff * 2, 30_000);\n }\n }\n };\n\n const open = (): void => {\n if (closed) return;\n if (typeof EventSource === \"undefined\") {\n void poll();\n return;\n }\n source = new EventSource(`${this.#base}/events?${query()}`);\n source.addEventListener(\"open\", () => {\n failures = 0;\n handlers.onStatus(\"live\");\n });\n source.addEventListener(\"snapshot\", (event) => {\n failures = 0;\n const snapshot = JSON.parse((event as MessageEvent<string>).data) as StreamSnapshot;\n last = snapshot.cursor;\n handlers.onSnapshot(snapshot);\n });\n source.addEventListener(\"mostra\", (event) => {\n failures = 0;\n const record = JSON.parse((event as MessageEvent<string>).data) as EventRecord;\n last = record.cursor;\n handlers.onEvents([record]);\n });\n // Run and live updates carry no `id`, so they never move the stream's cursor.\n source.addEventListener(\"run\", (event) => {\n const run = JSON.parse((event as MessageEvent<string>).data) as RunDelta;\n handlers.onEphemeral?.({ kind: \"run\", run });\n });\n source.addEventListener(\"live\", (event) => {\n const live = JSON.parse((event as MessageEvent<string>).data) as LiveUpdate;\n handlers.onEphemeral?.({ kind: \"live\", live });\n });\n source.addEventListener(\"error\", () => {\n if (closed) return;\n failures += 1;\n handlers.onStatus(\"offline\");\n // A refused stream (revoked link, gateway gone) is CLOSED; a dropped one reconnects by\n // itself. Either way, after two failures in a row the page long-polls on the same cursor.\n if (source?.readyState === EventSource.CLOSED || failures >= STREAM_FAILURES_BEFORE_POLL) {\n source?.close();\n source = undefined;\n if (!polling) void poll();\n }\n });\n };\n open();\n return () => {\n closed = true;\n source?.close();\n if (retry !== undefined) clearTimeout(retry);\n };\n }\n}\n","/**\n * The page's server side (D54, D56; WP-08): plain calls to `\"use server\"` functions, durable action\n * runs, and live sources, over the store's transport. Runs and sources are tracked per page: one\n * record per run and per source however many hooks show it, fed by the stream's ephemeral\n * messages and read again whenever a message may have been missed (a gap, a reconnect, a renewal),\n * so what a page shows always converges on what the server holds.\n */\nimport {\n type AnyFunction,\n type Batches,\n type CallLine,\n deserializeAll,\n type EphemeralMessage,\n type Frame,\n isFinalRunStatus,\n type LiveState,\n type LiveUpdate,\n RemoteError,\n type RunDelta,\n type RunProgress,\n type RunState,\n type RunStatus,\n serializeAll,\n ValueReader,\n type WireError,\n} from \"@mostra/protocol\";\nimport { MostraError, targetUnavailable } from \"./errors.ts\";\nimport { NetworkError, type Transport } from \"./transport.ts\";\n\n/** How often a page renews its interest in the runs and sources it shows (the lease is a minute). */\nexport const RENEW_MS = 20_000;\n\n/** How many times a run's start is retried after the network failed, with the same client key. */\nconst START_ATTEMPTS = 6;\n/** How many runs' early updates a page keeps, and how many updates of each (see `#keepEarly`). */\nconst EARLY_RUNS = 64;\nconst EARLY_DELTAS_PER_RUN = 32;\n\n/** The function ID a server reference carries, or `undefined` for any other function. */\nexport function serverFunctionId(fn: unknown): string | undefined {\n const id = (fn as { mostraServerFunctionId?: unknown } | null | undefined)\n ?.mostraServerFunctionId;\n return typeof id === \"string\" ? id : undefined;\n}\n\n/** A random client key: a run's request idempotency (a retried POST joins its own run). */\nfunction clientKey(): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** The error a failed or cancelled run, or call, rejects with. */\nfunction failure(error: WireError | undefined, fallback: string): MostraError {\n return new MostraError(error?.code ?? fallback, error?.message ?? \"The action failed.\");\n}\n\n/** What a page knows of one run. */\nexport interface RunView {\n readonly runId: string;\n readonly fnId: string;\n readonly key?: string;\n readonly status: RunStatus;\n readonly reason?: string;\n readonly progress?: RunProgress;\n readonly log: readonly string[];\n readonly error?: WireError;\n readonly finishedAt?: string;\n /** The result, once it succeeded (an async iterable result: the iterable). */\n readonly data?: unknown;\n /** Items an async iterable result yielded so far. */\n readonly partial: readonly unknown[];\n}\n\ninterface TrackedRun {\n view: RunView;\n batches: Frame[][];\n reader: ValueReader;\n rootDecoded: boolean;\n settled: Promise<unknown>;\n resolve(value: unknown): void;\n reject(error: unknown): void;\n}\n\n/** What a page knows of one live source. */\nexport interface LiveView {\n readonly key: string;\n readonly loading: boolean;\n readonly data?: unknown;\n readonly revision?: string;\n readonly at?: string;\n readonly error?: WireError;\n /** Append mode: the values kept, oldest first, at most the largest window asked for. */\n readonly ring: readonly unknown[];\n}\n\ninterface TrackedLive {\n view: LiveView;\n watchers: Map<number, number | undefined>;\n /** Revision numbers decoded or decoding, so an older value never replaces a newer one. */\n newest: number;\n ringRevisions: number[];\n /**\n * Every read and update of this source applies in the order it arrived, one at a time: values\n * decode asynchronously, and two in flight must never land out of order.\n */\n applying: Promise<void>;\n /** The newest value in latest mode still waiting its turn; a newer one replaces it. */\n pending?: LiveUpdate;\n}\n\n/** Options for {@link ServerClient}. */\nexport interface ServerClientOptions {\n readonly transport?: Transport;\n /** The page's view (D104), in live mode. */\n readonly viewId?: string;\n readonly timers?: {\n setTimeout(fn: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n };\n}\n\n/** Plain calls, action runs and live sources for one page. */\nexport class ServerClient {\n readonly #options: ServerClientOptions;\n readonly #runs = new Map<string, TrackedRun>();\n readonly #live = new Map<string, TrackedLive>();\n readonly #listeners = new Set<() => void>();\n #version = 0;\n #nextWatcher = 1;\n #renewTimer: unknown;\n #liveFlush: Promise<void> | undefined;\n #liveRefresh = new Set<string>();\n #notifyScheduled = false;\n /** Plain calls whose value hasn't arrived yet. */\n #callsInFlight = 0;\n /**\n * Updates for runs the page doesn't track yet: a fast run's end can arrive on the stream before\n * the answer that starts it, and is applied when that answer is (bounded, oldest dropped).\n */\n readonly #early = new Map<string, RunDelta[]>();\n\n constructor(options: ServerClientOptions) {\n this.#options = options;\n }\n\n // ── Subscription ───────────────────────────────────────────────────────────────────────\n\n /** Calls `listener` after every change; returns the function that stops. */\n subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n };\n\n /** A number that changes with every change, for `useSyncExternalStore`. */\n version = (): number => this.#version;\n\n /**\n * Server work the page is waiting on: plain calls whose value hasn't arrived, runs that haven't\n * ended, and live sources a component shows that have no first value yet. `verify`'s field\n * probe reads it, so the runner judges the page once what it loads at mount has arrived (Opus\n * review finding 1).\n */\n pending(): number {\n let count = this.#callsInFlight;\n for (const tracked of this.#runs.values())\n if (!isFinalRunStatus(tracked.view.status)) count += 1;\n for (const tracked of this.#live.values())\n if (tracked.view.loading && tracked.watchers.size > 0) count += 1;\n return count;\n }\n\n /**\n * Notes a change. Listeners hear about it once per animation frame (FAILURE_MODEL §6), or in a\n * microtask where a page has no frames to draw (a hidden tab, outside a browser), so a source\n * producing hundreds of values a second renders at most once a frame.\n */\n #changed(): void {\n this.#version += 1;\n if (this.#notifyScheduled) return;\n this.#notifyScheduled = true;\n const notify = (): void => {\n this.#notifyScheduled = false;\n for (const listener of [...this.#listeners]) listener();\n };\n const visible =\n typeof document === \"undefined\" ? false : document.visibilityState === \"visible\";\n if (visible && typeof requestAnimationFrame === \"function\") requestAnimationFrame(notify);\n else queueMicrotask(notify);\n }\n\n #transport(what: string): Transport & Required<Pick<Transport, \"call\">> {\n const transport = this.#options.transport;\n if (!transport?.call || this.#options.viewId === undefined) throw targetUnavailable(what);\n return transport as Transport & Required<Pick<Transport, \"call\">>;\n }\n\n get #viewId(): string {\n return this.#options.viewId ?? \"\";\n }\n\n // ── Plain calls (D54) ──────────────────────────────────────────────────────────────────\n\n /**\n * Calls a server function: no record, the result as soon as its first batch arrives (an async\n * iterable result keeps yielding as later batches come).\n */\n async call(fnId: string, args: readonly unknown[]): Promise<unknown> {\n const transport = this.#transport(`Calling the server function ${fnId}`);\n const batches = await serializeAll([...args], {\n mode: \"argument\",\n serverFunctionId: (fn: AnyFunction) => serverFunctionId(fn),\n });\n const reader = new ValueReader({ serverFunction: (id) => this.reference(id) });\n const lines = transport\n .call(fnId, { viewId: this.#viewId, args: batches })\n [Symbol.asyncIterator]();\n let ended: Extract<CallLine, { end: unknown }>[\"end\"] | undefined;\n const pump = async (): Promise<void> => {\n for (;;) {\n const next = await lines.next();\n if (next.done) break;\n const line = next.value;\n if (\"batch\" in line) reader.push(line.batch);\n else ended = line.end;\n }\n if (ended?.status === \"failed\") throw failure(ended.error, \"MOSTRA_ACTION_THREW\");\n if (!ended) throw new NetworkError(\"The call's answer ended early.\");\n };\n const pumped = pump();\n // The value as soon as it exists; a failure before it rejects the call.\n this.#callsInFlight += 1;\n try {\n const root = await Promise.race([reader.root, pumped.then(() => reader.root)]);\n pumped.catch((error: unknown) => reader.fail(error));\n return root;\n } finally {\n this.#callsInFlight -= 1;\n }\n }\n\n /** The client stub of a server function a result refers to. */\n reference(id: string): AnyFunction {\n const fn = ((...args: unknown[]) => this.call(id, args)) as AnyFunction;\n Object.defineProperty(fn, \"mostraServerFunctionId\", { value: id, enumerable: true });\n return fn;\n }\n\n // ── Action runs (D24, D54) ─────────────────────────────────────────────────────────────\n\n /** What the page knows of a run. */\n run(runId: string): RunView | undefined {\n return this.#runs.get(runId)?.view;\n }\n\n /**\n * Starts a run, or joins the one its key names (AC-03). The request carries a client key, so a\n * retry after a dropped answer joins the run it started instead of starting another.\n */\n async startRun(fnId: string, args: readonly unknown[], key?: string): Promise<RunView> {\n const transport = this.#transport(\"Running actions\");\n const batches: Batches = await serializeAll([...args], {\n mode: \"argument\",\n serverFunctionId: (fn: AnyFunction) => serverFunctionId(fn),\n });\n const ck = clientKey();\n let delay = 500;\n for (let attempt = 1; ; attempt++) {\n try {\n const state = await (transport.startRun as NonNullable<Transport[\"startRun\"]>)({\n viewId: this.#viewId,\n fnId,\n args: batches,\n ...(key !== undefined ? { key } : {}),\n clientKey: ck,\n });\n return this.#track(state);\n } catch (error) {\n if (!(error instanceof NetworkError) || attempt >= START_ATTEMPTS) throw error;\n await new Promise((resolve) => this.#setTimeout(() => resolve(undefined), delay));\n delay = Math.min(delay * 2, 8_000);\n }\n }\n }\n\n /** Finds runs by ID, or by function and key (a reloaded page re-attaching, AC-02). */\n async attach(input: {\n readonly runIds?: readonly string[];\n readonly keyed?: readonly { readonly fnId: string; readonly key: string }[];\n }): Promise<RunView[]> {\n const transport = this.#transport(\"Running actions\");\n // What the page holds of each run already isn't sent again (Opus review 14).\n const held = (input.runIds ?? []).flatMap((runId) => {\n const tracked = this.#runs.get(runId);\n return tracked && (tracked.view.log.length > 0 || tracked.batches.length > 0)\n ? [{ runId, log: tracked.view.log.length, batches: tracked.batches.length }]\n : [];\n });\n const { runs } = await (transport.attachRuns as NonNullable<Transport[\"attachRuns\"]>)({\n viewId: this.#viewId,\n ...(input.runIds && input.runIds.length > 0 ? { runIds: input.runIds } : {}),\n ...(input.keyed && input.keyed.length > 0 ? { keyed: input.keyed } : {}),\n ...(held.length > 0 ? { held } : {}),\n });\n return runs.map((state) => this.#track(state));\n }\n\n /** Cancels a run (AC-04): its `abortSignal` fires on the server. */\n async cancel(runId: string): Promise<void> {\n const transport = this.#transport(\"Cancelling actions\");\n const state = await (transport.cancelRun as NonNullable<Transport[\"cancelRun\"]>)(\n runId,\n this.#viewId,\n );\n this.#track(state);\n }\n\n /** Resolves with the run's result once it succeeded; rejects when it failed or was cancelled. */\n settled(runId: string): Promise<unknown> {\n const tracked = this.#runs.get(runId);\n if (!tracked) return Promise.reject(new MostraError(\"MOSTRA_ACTION_RUN_NOT_FOUND\", runId));\n return tracked.settled;\n }\n\n #newRun(state: RunState): TrackedRun {\n let resolve!: (value: unknown) => void;\n let reject!: (error: unknown) => void;\n const settled = new Promise<unknown>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n settled.catch(() => {});\n return {\n view: {\n runId: state.runId,\n fnId: state.fnId,\n ...(state.key !== undefined ? { key: state.key } : {}),\n status: state.status,\n log: [],\n partial: [],\n },\n batches: [],\n reader: new ValueReader({ serverFunction: (id) => this.reference(id) }),\n rootDecoded: false,\n settled,\n resolve,\n reject,\n };\n }\n\n /** Merges a full run state: the server's account wins. */\n #track(state: RunState): RunView {\n let tracked = this.#runs.get(state.runId);\n if (!tracked) {\n tracked = this.#newRun(state);\n this.#runs.set(state.runId, tracked);\n }\n this.#merge(tracked, {\n runId: state.runId,\n status: state.status,\n ...(state.reason !== undefined ? { reason: state.reason } : {}),\n ...(state.progress ? { progress: state.progress } : {}),\n logFrom: state.logFrom ?? 0,\n log: state.log,\n batchFrom: state.batchFrom ?? 0,\n batches: state.batches,\n ...(state.error ? { error: state.error } : {}),\n ...(state.finishedAt ? { finishedAt: state.finishedAt } : {}),\n });\n // What the stream said of it before this answer arrived (a fast run's end).\n const early = this.#early.get(state.runId);\n if (early) {\n this.#early.delete(state.runId);\n const current = tracked;\n if (!early.every((delta) => this.#merge(current, delta)))\n void this.attach({ runIds: [state.runId] }).catch(() => {});\n }\n this.#renewSoon();\n return tracked.view;\n }\n\n /** Applies a run delta; returns `false` when it skipped something the page doesn't have. */\n #merge(tracked: TrackedRun, delta: RunDelta): boolean {\n const view = tracked.view;\n if (delta.logFrom > view.log.length || delta.batchFrom > tracked.batches.length) return false;\n // A final state is final: a late \"running\" never takes it back.\n if (isFinalRunStatus(view.status) && !isFinalRunStatus(delta.status)) return true;\n const log = [...view.log, ...delta.log.slice(view.log.length - delta.logFrom)];\n const fresh = delta.batches.slice(tracked.batches.length - delta.batchFrom);\n for (const batch of fresh) {\n tracked.batches.push([...batch]);\n try {\n tracked.reader.push(batch);\n } catch (error) {\n tracked.reader.fail(error);\n }\n }\n tracked.view = {\n ...view,\n status: delta.status,\n ...(delta.reason !== undefined ? { reason: delta.reason } : {}),\n ...(delta.progress ? { progress: delta.progress } : {}),\n log,\n ...(delta.error ? { error: delta.error } : {}),\n ...(delta.finishedAt ? { finishedAt: delta.finishedAt } : {}),\n };\n if (fresh.length > 0 && !tracked.rootDecoded) this.#decodeRoot(tracked);\n if (isFinalRunStatus(delta.status)) this.#settle(tracked);\n this.#changed();\n return true;\n }\n\n #decodeRoot(tracked: TrackedRun): void {\n tracked.rootDecoded = true;\n void tracked.reader.root.then(\n (root) => {\n tracked.view = { ...tracked.view, data: root };\n this.#changed();\n // An async iterable result: its items as they come, for `partial`.\n if (root !== null && typeof root === \"object\" && Symbol.asyncIterator in root) {\n void (async () => {\n try {\n for await (const item of root as AsyncIterable<unknown>) {\n tracked.view = { ...tracked.view, partial: [...tracked.view.partial, item] };\n this.#changed();\n }\n } catch {\n // The run's own state says what went wrong.\n }\n })();\n }\n },\n () => {},\n );\n }\n\n /** Settles the run's promise once it reached a final state. */\n #settle(tracked: TrackedRun): void {\n const { status, error } = tracked.view;\n if (status === \"succeeded\") {\n if (tracked.batches.length === 0) {\n tracked.resolve(undefined);\n return;\n }\n if (!tracked.rootDecoded) this.#decodeRoot(tracked);\n tracked.reader.root.then(tracked.resolve, tracked.reject);\n // Every batch is in: whatever they never settled won't be.\n queueMicrotask(() => {\n if (!tracked.reader.complete) {\n tracked.reader.fail(new RemoteError({ message: \"The result ended early.\" }));\n }\n });\n return;\n }\n const ended =\n status === \"cancelled\"\n ? (error ?? { code: \"MOSTRA_ACTION_CANCELLED\", message: \"The run was cancelled.\" })\n : error;\n tracked.reader.fail(new RemoteError(ended ?? { message: \"The action failed.\" }));\n tracked.reject(\n failure(ended, status === \"cancelled\" ? \"MOSTRA_ACTION_CANCELLED\" : \"MOSTRA_ACTION_THREW\"),\n );\n }\n\n // ── Live sources (D56) ─────────────────────────────────────────────────────────────────\n\n /** What the page knows of a live source. */\n liveView(key: string): LiveView | undefined {\n return this.#live.get(key)?.view;\n }\n\n /**\n * Shows a live source: reads it now and keeps it produced while the page shows it. Returns the\n * function that stops showing it.\n */\n watchLive(key: string, window?: number): () => void {\n let tracked = this.#live.get(key);\n if (!tracked) {\n tracked = {\n view: { key, loading: true, ring: [] },\n watchers: new Map(),\n newest: 0,\n ringRevisions: [],\n applying: Promise.resolve(),\n };\n this.#live.set(key, tracked);\n }\n const id = this.#nextWatcher++;\n tracked.watchers.set(id, window);\n this.#flushLive();\n return () => {\n tracked.watchers.delete(id);\n };\n }\n\n /** Asks the source's producer to load again now (`useLive`'s `refresh()`). */\n refreshLive(key: string): void {\n this.#liveRefresh.add(key);\n this.#flushLive();\n }\n\n #windowOf(tracked: TrackedLive): number | undefined {\n let largest: number | undefined;\n for (const window of tracked.watchers.values()) {\n if (window !== undefined) largest = Math.max(largest ?? 0, window);\n }\n return largest;\n }\n\n /** Reads every shown source in one request, coalesced within a tick. */\n #flushLive(): void {\n if (this.#liveFlush) return;\n this.#liveFlush = Promise.resolve().then(async () => {\n this.#liveFlush = undefined;\n const shown = [...this.#live.values()].filter((tracked) => tracked.watchers.size > 0);\n if (shown.length === 0) return;\n const refresh = this.#liveRefresh;\n this.#liveRefresh = new Set();\n let transport: Transport;\n try {\n transport = this.#transport(\"Live data\");\n } catch (error) {\n for (const tracked of shown) {\n const diagnostic = error as MostraError;\n tracked.view = {\n ...tracked.view,\n loading: false,\n error: { message: diagnostic.message, code: diagnostic.code },\n };\n }\n this.#changed();\n return;\n }\n try {\n const { sources } = await (transport.live as NonNullable<Transport[\"live\"]>)({\n viewId: this.#viewId,\n keys: shown.map((tracked) => {\n const window = this.#windowOf(tracked);\n return {\n key: tracked.view.key,\n ...(window !== undefined ? { window } : {}),\n ...(refresh.has(tracked.view.key) ? { refresh: true } : {}),\n };\n }),\n });\n for (const source of sources) await this.#applyLiveState(source);\n } catch (error) {\n for (const tracked of shown) {\n if (tracked.view.revision !== undefined) continue;\n tracked.view = {\n ...tracked.view,\n ...(error instanceof MostraError\n ? { loading: false, error: { message: error.message, code: error.code } }\n : {}),\n };\n }\n this.#changed();\n }\n this.#renewSoon();\n });\n }\n\n /** Applies `apply` to a source after everything that arrived for it before. */\n #inOrder(key: string, apply: (tracked: TrackedLive) => Promise<void>): Promise<void> {\n const tracked = this.#live.get(key);\n if (!tracked) return Promise.resolve();\n const next = tracked.applying.then(() => apply(tracked)).catch(() => {});\n tracked.applying = next;\n return next;\n }\n\n #applyLiveState(state: LiveState): Promise<void> {\n return this.#inOrder(state.key, (tracked) => this.#applyLiveStateNow(tracked, state));\n }\n\n #applyLiveUpdate(update: LiveUpdate): Promise<void> {\n const tracked = this.#live.get(update.key);\n if (!tracked) return Promise.resolve();\n // In latest mode only the newest value shows: one still waiting its turn is replaced, never\n // decoded (Opus review 12). Append mode keeps every value for its ring.\n if (update.value !== undefined && this.#windowOf(tracked) === undefined) {\n const waiting = tracked.pending;\n // Never for an older one arriving late.\n if (!waiting || Number(update.revision ?? 0) > Number(waiting.revision ?? 0)) {\n tracked.pending = update;\n }\n if (waiting) return tracked.applying;\n return this.#inOrder(update.key, async (current) => {\n const next = current.pending;\n delete current.pending;\n if (next) await this.#applyLiveUpdateNow(current, next);\n });\n }\n return this.#inOrder(update.key, (current) => this.#applyLiveUpdateNow(current, update));\n }\n\n async #applyLiveStateNow(tracked: TrackedLive, state: LiveState): Promise<void> {\n const revision = Number(state.revision ?? 0);\n if (state.ring) {\n const values = await Promise.all(state.ring.map((entry) => decode(entry.value)));\n const revisions = state.ring.map((entry) => Number(entry.revision));\n // A read answered after newer updates arrived keeps them: the ring only moves forward.\n const last = revisions.at(-1) ?? 0;\n const kept = tracked.ringRevisions.flatMap((held, index) =>\n held > last ? [{ revision: held, value: tracked.view.ring[index] }] : [],\n );\n const window = this.#windowOf(tracked);\n const merged = [...values, ...kept.map((entry) => entry.value)];\n const mergedRevisions = [...revisions, ...kept.map((entry) => entry.revision)];\n tracked.ringRevisions =\n window === undefined ? mergedRevisions : mergedRevisions.slice(-window);\n tracked.view = {\n ...tracked.view,\n ring: window === undefined ? merged : merged.slice(-window),\n };\n }\n if (state.value && revision >= tracked.newest) {\n tracked.newest = revision;\n const data = await decode(state.value);\n if (revision < tracked.newest) return;\n tracked.view = {\n ...tracked.view,\n data,\n ...(state.revision !== undefined ? { revision: state.revision } : {}),\n ...(state.at !== undefined ? { at: state.at } : {}),\n };\n }\n tracked.view = {\n ...tracked.view,\n loading: false,\n ...(state.error ? { error: state.error } : {}),\n };\n if (!state.error && tracked.view.error) {\n const { error: _cleared, ...rest } = tracked.view;\n tracked.view = rest;\n }\n this.#changed();\n }\n\n async #applyLiveUpdateNow(tracked: TrackedLive, update: LiveUpdate): Promise<void> {\n if (update.error && !update.value) {\n tracked.view = { ...tracked.view, loading: false, error: update.error };\n this.#changed();\n return;\n }\n const revision = Number(update.revision ?? 0);\n if (!update.value || revision <= tracked.newest) return;\n // A value skipped (a dropped message): read the source again, ring included.\n const skipped =\n tracked.newest > 0 && revision > tracked.newest + 1 && this.#windowOf(tracked) !== undefined;\n tracked.newest = revision;\n const data = await decode(update.value);\n const window = this.#windowOf(tracked);\n const ring =\n window === undefined ? tracked.view.ring : [...tracked.view.ring, data].slice(-window);\n if (window !== undefined)\n tracked.ringRevisions = [...tracked.ringRevisions, revision].slice(-window);\n const { error: _cleared, ...rest } = tracked.view;\n tracked.view = {\n ...rest,\n loading: false,\n data,\n ring,\n revision: String(revision),\n ...(update.at !== undefined ? { at: update.at } : {}),\n };\n this.#changed();\n if (skipped) this.#flushLive();\n }\n\n // ── The stream ─────────────────────────────────────────────────────────────────────────\n\n /** One ephemeral message from the page's stream. */\n receive(message: EphemeralMessage): void {\n if (message.kind === \"run\") {\n const tracked = this.#runs.get(message.run.runId);\n if (!tracked) {\n this.#keepEarly(message.run);\n return;\n }\n if (!this.#merge(tracked, message.run))\n void this.attach({ runIds: [message.run.runId] }).catch(() => {});\n } else {\n void this.#applyLiveUpdate(message.live);\n }\n }\n\n /** Keeps an update for a run the page will track once its start is answered. */\n #keepEarly(delta: RunDelta): void {\n const kept = this.#early.get(delta.runId);\n if (kept) {\n if (kept.length < EARLY_DELTAS_PER_RUN) kept.push(delta);\n return;\n }\n if (this.#early.size >= EARLY_RUNS) {\n const oldest = this.#early.keys().next().value;\n if (oldest !== undefined) this.#early.delete(oldest);\n }\n this.#early.set(delta.runId, [delta]);\n }\n\n /** The stream came back after a gap: read again what may have been missed. */\n resync(): void {\n const open = [...this.#runs.values()].filter(\n (tracked) => !isFinalRunStatus(tracked.view.status),\n );\n if (open.length > 0) {\n void this.attach({ runIds: open.map((tracked) => tracked.view.runId) }).catch(() => {});\n }\n this.#flushLive();\n }\n\n /** Renews interest in open runs and shown sources before their lease ends. */\n #renewSoon(): void {\n if (this.#renewTimer !== undefined) return;\n this.#renewTimer = this.#setTimeout(() => {\n this.#renewTimer = undefined;\n const open = [...this.#runs.values()].filter(\n (tracked) => !isFinalRunStatus(tracked.view.status),\n );\n const shown = [...this.#live.values()].some((tracked) => tracked.watchers.size > 0);\n if (open.length > 0 || shown) {\n this.resync();\n this.#renewSoon();\n }\n }, RENEW_MS);\n }\n\n #setTimeout(fn: () => void, ms: number): unknown {\n return this.#options.timers ? this.#options.timers.setTimeout(fn, ms) : setTimeout(fn, ms);\n }\n\n /** Stops renewing (the page is going away, or a test ends). */\n stop(): void {\n if (this.#renewTimer === undefined) return;\n if (this.#options.timers) this.#options.timers.clearTimeout(this.#renewTimer);\n else clearTimeout(this.#renewTimer as ReturnType<typeof setTimeout>);\n this.#renewTimer = undefined;\n }\n}\n\n/** A serialized live value, read back. */\nfunction decode(value: Batches): Promise<unknown> {\n return deserializeAll(value);\n}\n","/**\n * The client runtime's store (INTERFACES §2.3; D22, D52, D110; IN-01 to IN-04): one per page. It\n * holds what the gateway says each field is, the viewer's edits it hasn't confirmed, and the\n * mounted fields, and hooks read it through `useSyncExternalStore`.\n *\n * - **Edits** show at once, are journaled in IndexedDB at once, and are sent after a short\n * debounce, or at once on blur, when the page is hidden or closed, and before a submit (IN-02).\n * - **Bases.** Each edit remembers the revision the field had when the viewer made it, so the\n * gateway turns an edit made over a change the viewer never saw into a conflict, never a silent\n * overwrite (D22). The page's own answers move a field's revision; another writer's change moves\n * it only when the event stream delivers it, in order.\n * - **Conflicts** keep both values: the viewer's (mine) stays shown until they keep it or take\n * theirs (FAILURE_MODEL §5).\n * - **Offline**, mutations stay in the journal with their IDs and replay in order (IN-04); a tab\n * that closed with unsent edits leaves them for the next page of the artifact to adopt.\n * - **Tabs** converge through the event stream; a BroadcastChannel only shortens the delay.\n */\nimport {\n type Actor,\n type EventRecord,\n type FieldConflict,\n type FieldOp,\n type FieldScope,\n isFieldId,\n MutationId,\n type MutationResult,\n SIGNAL_NAME_PATTERN,\n type StreamSnapshot,\n type SubmissionSummary,\n type SubmitBlocker,\n type ViewContext,\n type Viewer,\n} from \"@mostra/protocol\";\nimport { MostraError, targetUnavailable } from \"./errors.ts\";\nimport type { Journal, JournalEntry, MutationEntry, PendingEntry } from \"./journal.ts\";\nimport { ServerClient } from \"./server-client.ts\";\nimport { NetworkError, type Transport } from \"./transport.ts\";\n\n/** How long the page waits after the last edit before it saves (INTERFACES §2.3). */\nexport const SAVE_DEBOUNCE_MS = 400;\n\n/** How long a submit waits for the event stream to reach the page's own last save. */\nconst CATCH_UP_MS = 5_000;\n\n/** How soon waiting saves try again once the event stream shows the gateway answers. */\nconst RETRY_SOON_MS = 250;\n\n/** The most ops one mutation carries (the browser protocol's limit). */\nconst OPS_PER_MUTATION = 1000;\n\n/** A field's key in the store: its scope and ID. */\nexport type FieldKey = `${FieldScope}:${string}`;\n\n/** A field's key. */\nexport const fieldKey = (scope: FieldScope, id: string): FieldKey => `${scope}:${id}`;\n\n/** What the gateway says a field holds. */\ninterface ServerField {\n readonly value: unknown;\n /** The revision that last wrote it. */\n readonly revision: number;\n readonly deleted: boolean;\n readonly updatedBy?: Actor;\n}\n\n/** A conflict the viewer hasn't resolved: what the field holds now. */\nexport interface OpenConflict {\n readonly theirs: unknown;\n readonly deleted: boolean;\n /** The revision that wrote theirs: keeping mine writes over it. */\n readonly revision: number;\n readonly updatedBy?: Actor;\n}\n\n/** A mounted field, as `useField` declares it. */\nexport interface Registration {\n readonly id: string;\n readonly scope: FieldScope;\n readonly initial: unknown;\n readonly label?: string;\n readonly required?: boolean;\n readonly sensitive?: boolean;\n /** The validation message of its current value, if any. */\n readonly error?: string;\n /** The hook that named it, for `verify`'s field-ID checks (D138): `useField` unless stated. */\n readonly hook?: string;\n}\n\n/** The page's save state (D47): what the shell's rail and `FieldMeta.save` show. */\nexport type PageSave = \"saved\" | \"saving\" | \"offline\" | \"conflict\";\n\n/** Where the runtime runs and what it may do. */\nexport type RuntimeMode =\n /** Behind Mostra's gateway in a shell's frame: everything works. */\n | \"live\"\n /** No gateway (a static export, a page opened outside its shell): values stay in this browser. */\n | \"local\";\n\n/** The submission state `useSubmit` reports (INTERFACES §2.3). */\nexport type SubmitState =\n | \"open\"\n | \"submitting\"\n | \"submitted\"\n | \"delivered\"\n | \"pending-delivery\"\n | \"undeliverable\"\n | \"closed\";\n\n/** Options for {@link Store}. */\nexport interface StoreOptions {\n readonly mode: RuntimeMode;\n /** The browser protocol, in live mode. */\n readonly transport?: Transport;\n /** The journal of unconfirmed edits. */\n readonly journal: Journal;\n /** The view this page is, in live mode (D104). */\n readonly view?: ViewContext;\n /** The link's scopes (D97): without `draft` the page saves nothing. */\n readonly scopes?: readonly string[];\n /**\n * The viewer the page acts as, from its frame session, before the first snapshot: an edit made\n * before it arrives is journaled like any other (Claude review finding 4).\n */\n readonly viewer?: Viewer;\n /** This tab's ID, unique per page load. */\n readonly tab: string;\n /** The tabs whose journal entries this page may adopt: those no longer open. */\n readonly goneTabs?: (tabs: readonly string[]) => Promise<ReadonlySet<string>>;\n /** Runs `fn` while no other page of the artifact adopts journal entries (Web Locks). */\n readonly exclusive?: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Where `local` mode keeps values; `localStorage` by default. */\n readonly local?: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\">;\n /** The same-browser latency path (D22); never a source of truth. */\n readonly channel?: (name: string) => BroadcastChannel | undefined;\n /** Timers, replaceable in tests. */\n readonly timers?: {\n setTimeout(fn: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n };\n}\n\n/** What a flush ends with: the draft revision every save reached, and whether some still wait. */\nexport interface FlushOutcome {\n readonly revision: number;\n readonly unsaved: boolean;\n}\n\n/** How many early delivery events a page keeps. */\nconst EARLY_DELIVERIES_MAX = 64;\n\nconst DELIVERY_SEVERITY = { delivered: 0, pending: 1, rejected: 2, undeliverable: 3 } as const;\n\n/**\n * One submission's two accounts merged: each delivery as its latest change says, so an answer\n * built before newer events never takes the state back (Claude review finding 8).\n */\nfunction mergedSubmission(\n known: SubmissionSummary | undefined,\n next: SubmissionSummary,\n): SubmissionSummary {\n if (known?.id !== next.id || known.deliveries === undefined) return next;\n const newer = new Map((next.deliveries ?? []).map((delivery) => [delivery.deliveryId, delivery]));\n for (const delivery of known.deliveries) {\n const other = newer.get(delivery.deliveryId);\n if (other === undefined || delivery.updatedAt > other.updatedAt) {\n newer.set(delivery.deliveryId, delivery);\n }\n }\n const deliveries = [...newer.values()];\n let worst: SubmissionSummary[\"delivery\"] = \"delivered\";\n for (const delivery of deliveries) {\n if (DELIVERY_SEVERITY[delivery.state] > DELIVERY_SEVERITY[worst]) worst = delivery.state;\n }\n return { ...next, deliveries, delivery: deliveries.length > 0 ? worst : next.delivery };\n}\n\n/** Deep equality for JSON values. */\nfunction same(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keysA = Object.keys(a as object);\n const keysB = Object.keys(b as object);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((key) =>\n same((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\n/** Whether a required field's value counts as missing. */\nexport function isEmpty(value: unknown): boolean {\n return (\n value === undefined ||\n value === null ||\n (typeof value === \"string\" && value.trim() === \"\") ||\n (Array.isArray(value) && value.length === 0)\n );\n}\n\nconst keyParts = (key: FieldKey): { scope: FieldScope; id: string } => {\n const at = key.indexOf(\":\");\n return { scope: key.slice(0, at) as FieldScope, id: key.slice(at + 1) };\n};\n\n/** The runtime's store of one page. */\nexport class Store {\n readonly mode: RuntimeMode;\n readonly view: ViewContext | undefined;\n readonly #options: StoreOptions;\n readonly #timers: NonNullable<StoreOptions[\"timers\"]>;\n\n // What the gateway says.\n readonly #server = new Map<FieldKey, ServerField>();\n /** The revision the event stream reached, per document: every change up to it was seen. */\n readonly #seen: Record<FieldScope, number> = { viewer: 0, artifact: 0 };\n #epoch = 1;\n #viewer: Viewer | undefined;\n /** Whether the first snapshot arrived. */\n #loaded = false;\n /** Delivery events for a submission not known yet (the stream may beat the submit's answer). */\n #earlyDeliveries: EventRecord[] = [];\n #submission: SubmissionSummary | undefined;\n /** Whether a submission closed the viewer's draft (`once`, D106). */\n #closed = false;\n\n // What the page holds that the gateway hasn't confirmed.\n readonly #pending = new Map<FieldKey, PendingEntry>();\n readonly #inflight = new Map<string, MutationEntry>();\n /** The value each in-flight mutation sends, per field. */\n readonly #sending = new Map<FieldKey, { readonly value: unknown; readonly mutationId: string }>();\n readonly #conflicts = new Map<FieldKey, OpenConflict>();\n /** Edits the gateway refused for good (too large, invalid): kept, shown with the reason. */\n readonly #refused = new Map<FieldKey, { readonly code: string; readonly message: string }>();\n /** Mutations waiting for the network, in order. */\n readonly #queue: MutationEntry[] = [];\n\n // Mounted fields.\n readonly #registrations = new Map<FieldKey, { registration: Registration; count: number }>();\n /** Who hears each mount and unmount: `verify`'s field probe (D138). */\n readonly #mountObservers = new Set<(registration: Registration, mounted: boolean) => void>();\n\n #ready = false;\n #readyWaiters: (() => void)[] = [];\n #online = true;\n #revoked = false;\n #debounce: unknown;\n #retry: unknown;\n #retryMs = 1_000;\n #sendingQueue = false;\n #seq = 0;\n #version = 0;\n readonly #listeners = new Set<() => void>();\n readonly #keyVersions = new Map<FieldKey, number>();\n #broadcast: BroadcastChannel | undefined;\n #submitState: SubmitState = \"open\";\n #catchUp: (() => void)[] = [];\n /**\n * Fields another writer changed whose new value the page hasn't got (a sensitive value isn't in\n * events, D52): an edit of one is based on what the page last had, so it conflicts instead of\n * overwriting, and a submit waits until a snapshot brings the value.\n */\n readonly #unknown = new Set<FieldKey>();\n #resyncing: Promise<void> | undefined;\n readonly #beforeSubmit = new Set<() => Promise<void>>();\n #stopStream: (() => void) | undefined;\n /** Plain calls, action runs and live sources (WP-08), over the same transport and view. */\n readonly server: ServerClient;\n\n constructor(options: StoreOptions) {\n this.#options = options;\n this.server = new ServerClient({\n ...(options.mode === \"live\" && options.transport ? { transport: options.transport } : {}),\n ...(options.mode === \"live\" && options.view ? { viewId: options.view.viewId } : {}),\n ...(options.timers ? { timers: options.timers } : {}),\n });\n this.mode = options.mode;\n this.view = options.view;\n this.#viewer = options.viewer;\n this.#timers = options.timers ?? {\n setTimeout: (fn, ms) => setTimeout(fn, ms),\n clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n if (options.view?.policy.policy === \"none\") this.#submitState = \"closed\";\n }\n\n // ── Subscription ───────────────────────────────────────────────────────────────────────\n\n /** Calls `listener` after every change; returns the function that stops. */\n subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n };\n\n /** A number that changes with every change, for `useSyncExternalStore`. */\n version = (): number => this.#version;\n\n /** A number that changes whenever the field's value or meta may have. */\n keyVersion(key: FieldKey): number {\n return this.#keyVersions.get(key) ?? 0;\n }\n\n #changed(keys: Iterable<FieldKey> = []): void {\n this.#version += 1;\n for (const key of keys) this.#keyVersions.set(key, (this.#keyVersions.get(key) ?? 0) + 1);\n for (const listener of [...this.#listeners]) listener();\n }\n\n // ── Start ──────────────────────────────────────────────────────────────────────────────\n\n /** Whether the first snapshot arrived (or, in local mode, at once). */\n get ready(): boolean {\n return this.#ready;\n }\n\n /** Resolves once the store is ready, or after `timeoutMs`. */\n whenReady(timeoutMs: number = Number.POSITIVE_INFINITY): Promise<void> {\n if (this.#ready) return Promise.resolve();\n return new Promise((resolve) => {\n this.#readyWaiters.push(resolve);\n if (Number.isFinite(timeoutMs)) this.#timers.setTimeout(resolve, timeoutMs);\n });\n }\n\n #markReady(): void {\n if (this.#ready) return;\n this.#ready = true;\n for (const resolve of this.#readyWaiters.splice(0)) resolve();\n this.#changed(this.#allKeys());\n }\n\n #allKeys(): FieldKey[] {\n return [...new Set([...this.#server.keys(), ...this.#registrations.keys()])];\n }\n\n /** Starts: subscribes to the event stream (live) or reads this browser's values (local). */\n start(): void {\n if (this.mode === \"local\") {\n this.#markReady();\n return;\n }\n const transport = this.#transport();\n this.#stopStream = transport.subscribe(undefined, {\n onSnapshot: (snapshot) => this.#applySnapshot(snapshot),\n onEvents: (events) => this.#applyEvents(events),\n onStatus: (status) => {\n if (status === \"revoked\") this.#revoked = true;\n const online = status === \"live\";\n if (online !== this.#online) {\n this.#online = online;\n if (online) {\n this.#kickQueue();\n // Run and live updates sent while the stream was down are gone: read them again.\n this.server.resync();\n }\n this.#changed(this.#allKeys());\n }\n },\n onEphemeral: (message) => this.server.receive(message),\n });\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"online\", () => this.#kickQueue());\n }\n }\n\n /** Stops the stream and timers (the page is going away, or a test ends). */\n stop(): void {\n this.#stopStream?.();\n this.server.stop();\n this.#broadcast?.close();\n if (this.#debounce !== undefined) this.#timers.clearTimeout(this.#debounce);\n if (this.#retry !== undefined) this.#timers.clearTimeout(this.#retry);\n }\n\n #transport(): Transport {\n const transport = this.#options.transport;\n if (!transport) throw targetUnavailable(\"Saving\");\n return transport;\n }\n\n // ── What the gateway says ──────────────────────────────────────────────────────────────\n\n #applySnapshot(snapshot: StreamSnapshot): void {\n this.#gatewayHeard();\n const first = !this.#loaded;\n this.#loaded = true;\n this.#viewer = snapshot.viewer;\n const touched = new Set<FieldKey>(this.#allKeys());\n // A snapshot replaces a document the page knows no newer revision of. One that is older than\n // events already applied (a resync answered after the stream moved on) only adds what it\n // knows newer, field by field: the stream's cursor is past those events, so they would never\n // come again (GPT review finding 11).\n const load = (scope: FieldScope, document: StreamSnapshot[\"draft\"]): boolean => {\n const revision = Number(document.revision);\n const replace = first || revision >= this.#seen[scope];\n if (replace) {\n for (const key of [...this.#server.keys()]) {\n if (keyParts(key).scope === scope) this.#server.delete(key);\n }\n for (const key of [...this.#unknown]) {\n if (keyParts(key).scope === scope) this.#unknown.delete(key);\n }\n this.#seen[scope] = revision;\n }\n for (const [id, field] of Object.entries(document.fields)) {\n const key = fieldKey(scope, id);\n const current = this.#server.get(key);\n if (!replace && current && current.revision >= Number(field.revision)) continue;\n touched.add(key);\n this.#unknown.delete(key);\n this.#server.set(key, {\n value: field.value,\n revision: Number(field.revision),\n deleted: false,\n ...(field.updatedBy ? { updatedBy: field.updatedBy } : {}),\n });\n }\n return replace;\n };\n if (load(\"viewer\", snapshot.draft)) this.#epoch = snapshot.draft.epoch;\n load(\"artifact\", snapshot.state);\n if (snapshot.submission) this.#adoptSubmission(snapshot.submission, true);\n this.#resolveCatchUp();\n this.#changed(touched);\n if (first) {\n this.#openChannel();\n void this.#recoverJournal().finally(() => {\n this.#markReady();\n // Edits made before the first snapshot waited for it (Claude review finding 4).\n if (this.#pending.size > 0) this.#schedule();\n });\n }\n }\n\n #applyEvents(events: readonly EventRecord[]): void {\n this.#gatewayHeard();\n const touched = new Set<FieldKey>();\n let resync = false;\n for (const event of events) {\n const ownMutation =\n event.causation?.[\"mutationId\"] !== undefined &&\n (this.#inflight.has(event.causation[\"mutationId\"]) ||\n [...this.#sending.values()].some(\n (s) => s.mutationId === event.causation?.[\"mutationId\"],\n ));\n if (event.type === \"draft.changed\" || event.type === \"state.changed\") {\n const scope: FieldScope = event.type === \"draft.changed\" ? \"viewer\" : \"artifact\";\n const payload = event.payload as {\n revision: string;\n epoch?: number;\n changes: { id: string; value?: unknown; deleted?: true; sensitive?: true }[];\n };\n const revision = Number(payload.revision);\n if (scope === \"viewer\" && payload.epoch !== undefined && payload.epoch > this.#epoch) {\n this.#epoch = payload.epoch;\n }\n for (const change of payload.changes) {\n const key = fieldKey(scope, change.id);\n touched.add(key);\n const current = this.#server.get(key);\n if (current && current.revision >= revision) continue;\n if (change.sensitive && !change.deleted) {\n // A sensitive value isn't in events (D52): the page's own value is known, another\n // writer's comes with a fresh snapshot.\n const mine = this.#sending.get(key);\n if (ownMutation && mine) {\n this.#server.set(key, {\n value: mine.value,\n revision,\n deleted: false,\n updatedBy: event.actor,\n });\n } else {\n // The page still shows the old value: until the snapshot brings the new one, an\n // edit conflicts and a submit waits (GPT review finding 4).\n this.#unknown.add(key);\n resync = true;\n }\n continue;\n }\n this.#unknown.delete(key);\n this.#server.set(key, {\n value: change.deleted ? undefined : change.value,\n revision,\n deleted: change.deleted === true,\n updatedBy: event.actor,\n });\n }\n this.#seen[scope] = Math.max(this.#seen[scope], revision);\n } else if (event.type === \"submission.created\") {\n const payload = event.payload as { submissionId: string; viewerId?: string };\n const own = payload.viewerId !== undefined && payload.viewerId === this.#viewer?.id;\n if (own && this.#submission?.id !== payload.submissionId) {\n // The viewer's own submission, made in another tab or by the shell's trusted Submit:\n // the snapshot carries it whole, with its deliveries.\n resync = true;\n } else if (!own && this.view?.policy.policy === \"once\") {\n // Under `once` for the whole artifact anyone's submission closes the draft (D106).\n if (this.view.policy.scope !== \"per-viewer\") {\n this.#closed = true;\n this.#submitState = \"closed\";\n for (const key of this.#allKeys()) touched.add(key);\n }\n }\n } else if (event.type.startsWith(\"submission.\")) {\n this.#deliveryEvent(event);\n }\n }\n this.#resolveCatchUp();\n if (resync) void this.#resync();\n if (touched.size > 0) this.#changed(touched);\n }\n\n /** Loads a fresh snapshot, once at a time; a failure leaves it to the next event or submit. */\n #resync(): Promise<void> {\n this.#resyncing ??= (async () => {\n try {\n this.#applySnapshot(await this.#transport().snapshot());\n } catch {\n // The next event, reconnect or submit asks again.\n } finally {\n this.#resyncing = undefined;\n }\n })();\n return this.#resyncing;\n }\n\n // ── Reading ────────────────────────────────────────────────────────────────────────────\n\n /** Whether the gateway holds a value for the field (deleted fields don't count). */\n stored(key: FieldKey): boolean {\n const server = this.#server.get(key);\n return server !== undefined && !server.deleted;\n }\n\n /** The field's value as the viewer sees it: their edit, else the gateway's, else `fallback`. */\n value(key: FieldKey, fallback: unknown): unknown {\n if (this.mode === \"local\") {\n const stored = this.#localRead(key);\n const pending = this.#pending.get(key);\n if (pending) return pending.op.delete ? fallback : pending.op.value;\n return stored === undefined ? fallback : stored;\n }\n const pending = this.#pending.get(key);\n if (pending) return pending.op.delete ? fallback : pending.op.value;\n const sending = this.#sending.get(key);\n if (sending) return sending.value === undefined ? fallback : sending.value;\n const server = this.#server.get(key);\n if (server && !server.deleted) return server.value;\n return fallback;\n }\n\n /** The field's open conflict, if any. */\n conflict(key: FieldKey): OpenConflict | undefined {\n return this.#conflicts.get(key);\n }\n\n /** Who last wrote the field (artifact state, D63). */\n updatedBy(key: FieldKey): Actor | undefined {\n return this.#server.get(key)?.updatedBy;\n }\n\n /** Why the gateway refused the field's edit for good, if it did: its code and message. */\n refusal(key: FieldKey): { readonly code: string; readonly message: string } | undefined {\n return this.#refused.get(key);\n }\n\n /** Whether the field takes edits: not a closed draft, not a view-only link. */\n writable(key: FieldKey): boolean {\n if (this.mode === \"local\") return true;\n const { scope } = keyParts(key);\n if (!this.#canSave()) return false;\n return scope === \"artifact\" || !this.#closed;\n }\n\n /** Whether the link may submit (D97): its `submit` scope. */\n canSubmit(): boolean {\n return this.#options.scopes === undefined || this.#options.scopes.includes(\"submit\");\n }\n\n #canSave(): boolean {\n return this.#options.scopes === undefined || this.#options.scopes.includes(\"draft\");\n }\n\n /** The field's save state (INTERFACES §2.3). */\n save(key: FieldKey): \"saved\" | \"saving\" | \"offline\" | \"conflict\" | \"readonly\" {\n if (this.mode === \"local\") return \"readonly\";\n if (this.#conflicts.has(key)) return \"conflict\";\n if (!this.writable(key)) return \"readonly\";\n if (this.#refused.has(key)) return \"offline\";\n const unsent = this.#pending.has(key) || this.#sending.has(key);\n if (!unsent) return \"saved\";\n return this.#online && !this.#revoked ? \"saving\" : \"offline\";\n }\n\n /** The page's save state, for the shell's rail. */\n pageSave(): PageSave {\n if (this.mode === \"local\") return \"saved\";\n if (this.#conflicts.size > 0) return \"conflict\";\n const unsent = this.#pending.size > 0 || this.#inflight.size > 0 || this.#queue.length > 0;\n if (!unsent && this.#refused.size === 0) return \"saved\";\n return this.#online && !this.#revoked && this.#refused.size === 0 ? \"saving\" : \"offline\";\n }\n\n /** Whether edits wait to be saved. */\n unsaved(): boolean {\n return (\n this.#pending.size > 0 ||\n this.#inflight.size > 0 ||\n this.#queue.length > 0 ||\n this.#refused.size > 0\n );\n }\n\n /** The viewer the page acts as, once known. */\n viewer(): Viewer | undefined {\n return this.#viewer;\n }\n\n /** Every field ID of a scope the viewer sees, with its value (for `window.storage.list`). */\n ids(scope: FieldScope): string[] {\n const ids = new Set<string>();\n if (this.mode === \"local\") {\n for (const id of this.#localIds(scope)) ids.add(id);\n }\n for (const [key, server] of this.#server) {\n if (!server.deleted && key.startsWith(`${scope}:`)) ids.add(keyParts(key).id);\n }\n for (const key of [...this.#pending.keys(), ...this.#sending.keys()]) {\n if (key.startsWith(`${scope}:`)) ids.add(keyParts(key).id);\n }\n return [...ids].filter((id) => this.value(fieldKey(scope, id), undefined) !== undefined).sort();\n }\n\n // ── Mounted fields ─────────────────────────────────────────────────────────────────────\n\n /** Registers a mounted field; returns the function that unregisters it. */\n register(registration: Registration): () => void {\n const key = fieldKey(registration.scope, registration.id);\n const existing = this.#registrations.get(key);\n if (existing) {\n existing.count += 1;\n existing.registration = { ...registration, initial: existing.registration.initial };\n } else this.#registrations.set(key, { registration, count: 1 });\n for (const observer of this.#mountObservers) observer(registration, true);\n this.#changed([key]);\n let released = false;\n return () => {\n const entry = this.#registrations.get(key);\n if (!entry) return;\n if (!released) {\n released = true;\n for (const observer of this.#mountObservers) observer(registration, false);\n }\n entry.count -= 1;\n if (entry.count <= 0) this.#registrations.delete(key);\n this.#changed([key]);\n };\n }\n\n /**\n * Hears every field mount and unmount, with the registration as the hook gave it; returns the\n * function that stops. `verify`'s field probe uses it (D138). @internal\n */\n observeMounts(observer: (registration: Registration, mounted: boolean) => void): () => void {\n this.#mountObservers.add(observer);\n return () => this.#mountObservers.delete(observer);\n }\n\n /**\n * Tells the mount observers about a field a hook reads and writes without registering it\n * (`useChoice`'s choice field): `verify`'s field probe hears it, and nothing else changes, so\n * no default is written for it (D110). Returns the function that announces its unmount.\n */\n announceMount(registration: Registration): () => void {\n if (this.#mountObservers.size === 0) return () => undefined;\n for (const observer of this.#mountObservers) observer(registration, true);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n for (const observer of this.#mountObservers) observer(registration, false);\n };\n }\n\n /** Updates a mounted field's options or validation message. */\n updateRegistration(registration: Registration): void {\n const key = fieldKey(registration.scope, registration.id);\n const entry = this.#registrations.get(key);\n if (!entry) return;\n const next = { ...registration, initial: entry.registration.initial };\n if (\n entry.registration.label === next.label &&\n entry.registration.required === next.required &&\n entry.registration.sensitive === next.sensitive &&\n entry.registration.error === next.error\n )\n return;\n entry.registration = next;\n this.#changed([key]);\n }\n\n /** Every mounted field. */\n registrations(): Registration[] {\n return [...this.#registrations.values()].map((entry) => entry.registration);\n }\n\n /** What blocks a submit now (INTERFACES §2.3): required, invalid and conflicting fields. */\n blockers(): SubmitBlocker[] {\n const blockers: SubmitBlocker[] = [];\n for (const [key, { registration }] of this.#registrations) {\n const label = registration.label !== undefined ? { label: registration.label } : {};\n if (this.#conflicts.has(key)) {\n blockers.push({ fieldId: registration.id, ...label, reason: \"conflict\" });\n } else if (registration.error !== undefined) {\n blockers.push({ fieldId: registration.id, ...label, reason: \"invalid\" });\n } else if (registration.required && isEmpty(this.value(key, registration.initial))) {\n blockers.push({ fieldId: registration.id, ...label, reason: \"required\" });\n }\n }\n return blockers.sort((a, b) => (a.fieldId < b.fieldId ? -1 : a.fieldId > b.fieldId ? 1 : 0));\n }\n\n // ── Editing ────────────────────────────────────────────────────────────────────────────\n\n /**\n * Sets a field: shown at once, journaled at once, sent after the debounce (`immediate` sends\n * now). Refused with `MOSTRA_FIELD_ID_INVALID` for an ID that isn't one; a closed draft or a\n * view-only link refuses with `MOSTRA_SUBMIT_ALREADY` or `MOSTRA_HYGIENE_SCOPE_DENIED`.\n */\n set(\n scope: FieldScope,\n id: string,\n value: unknown,\n options: {\n readonly label?: string;\n readonly required?: boolean;\n readonly sensitive?: boolean;\n readonly immediate?: boolean;\n readonly delete?: boolean;\n } = {},\n ): void {\n if (!isFieldId(id)) {\n throw new MostraError(\"MOSTRA_FIELD_ID_INVALID\", `${JSON.stringify(id)} isn't a field ID.`);\n }\n const key = fieldKey(scope, id);\n if (!this.writable(key)) {\n throw this.#closed && scope === \"viewer\"\n ? new MostraError(\"MOSTRA_SUBMIT_ALREADY\", \"This draft was submitted and takes no edits.\")\n : new MostraError(\"MOSTRA_HYGIENE_SCOPE_DENIED\", \"This link can't save answers.\");\n }\n if (value !== undefined) {\n try {\n JSON.stringify(value);\n } catch {\n throw new MostraError(\"MOSTRA_HOST_INVALID_PARAMS\", `The value of ${id} isn't JSON.`);\n }\n }\n // An edit keeps the field's label, `required` and `sensitive`: from this call, else the\n // earlier unsent edit, else the mounted field.\n const earlierOp = this.#pending.get(fieldKey(scope, id))?.op;\n const registered = this.#registrations.get(fieldKey(scope, id))?.registration;\n const label = options.label ?? earlierOp?.label ?? registered?.label;\n const required = options.required ?? earlierOp?.required ?? registered?.required;\n const sensitive = options.sensitive ?? earlierOp?.sensitive ?? registered?.sensitive;\n const op: FieldOp = {\n id,\n ...(options.delete || value === undefined ? { delete: true as const } : { value }),\n ...(label !== undefined ? { label } : {}),\n ...(required !== undefined ? { required } : {}),\n ...(sensitive !== undefined ? { sensitive } : {}),\n };\n if (this.mode === \"local\") {\n this.#localWrite(key, op.delete ? undefined : op.value);\n this.#changed([key]);\n return;\n }\n const earlier = this.#pending.get(key);\n const entry: PendingEntry = {\n kind: \"pending\",\n viewerId: this.#viewer?.id ?? \"\",\n tab: this.#options.tab,\n viewId: this.view?.viewId ?? \"\",\n scope,\n op,\n base: earlier ? earlier.base : this.#baseFor(key),\n at: Date.now(),\n };\n this.#refused.delete(key);\n this.#pending.set(key, entry);\n // A conflict stays open until the viewer resolves it; the edit waits with it.\n if (entry.viewerId !== \"\") void this.#options.journal.putPending(entry).catch(() => undefined);\n this.#changed([key]);\n if (options.immediate) void this.flush();\n else this.#schedule();\n }\n\n /** The base of a new edit: what the page has seen of the field (null while it is in flight). */\n #baseFor(key: FieldKey): number | null {\n if (this.#sending.has(key)) return null;\n // A value the page hasn't got: based on what it last had, so the write conflicts.\n if (this.#unknown.has(key)) return this.#server.get(key)?.revision ?? 0;\n const { scope } = keyParts(key);\n return Math.max(this.#server.get(key)?.revision ?? 0, this.#seen[scope]);\n }\n\n #schedule(): void {\n if (this.#debounce !== undefined) this.#timers.clearTimeout(this.#debounce);\n this.#debounce = this.#timers.setTimeout(() => {\n this.#debounce = undefined;\n void this.flush();\n }, SAVE_DEBOUNCE_MS);\n }\n\n /** Keeps the viewer's value of a conflicting field: written over theirs (FAILURE_MODEL §5). */\n keepMine(key: FieldKey): void {\n const conflict = this.#conflicts.get(key);\n const pending = this.#pending.get(key);\n if (!conflict || !pending) return;\n this.#conflicts.delete(key);\n const entry = { ...pending, base: conflict.revision, at: Date.now() };\n this.#pending.set(key, entry);\n void this.#options.journal.putPending(entry).catch(() => undefined);\n this.#changed([key]);\n void this.flush();\n }\n\n /** Takes the other writer's value of a conflicting field and drops the viewer's. */\n takeTheirs(key: FieldKey): void {\n const pending = this.#pending.get(key);\n this.#conflicts.delete(key);\n this.#refused.delete(key);\n this.#pending.delete(key);\n if (pending) void this.#options.journal.dropPending(pending).catch(() => undefined);\n this.#changed([key]);\n }\n\n // ── Saving ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Sends every edit now and waits for the answers. `keepalive` is for `pagehide`: the requests\n * outlive the page, and the journal keeps whatever they don't deliver (IN-02).\n */\n async flush(options: { readonly keepalive?: boolean } = {}): Promise<FlushOutcome> {\n // Nothing is sent before the first snapshot: an edit's base must be a revision the page saw.\n // It is journaled meanwhile and goes out once the snapshot arrives.\n if (this.mode === \"local\" || this.#viewer === undefined || !this.#loaded) {\n return { revision: this.#seen.viewer, unsaved: this.unsaved() };\n }\n if (this.#debounce !== undefined) {\n this.#timers.clearTimeout(this.#debounce);\n this.#debounce = undefined;\n }\n // Edits whose base waits for an earlier save stay until it answers; conflicts until resolved.\n const ready = [...this.#pending.entries()].filter(\n ([key, entry]) => entry.base !== null && !this.#conflicts.has(key) && !this.#refused.has(key),\n );\n const groups = new Map<string, PendingEntry[]>();\n for (const [, entry] of ready) {\n // Each edit goes out as the view it was made in (an adopted tab's may be another version's),\n // so its version and causation name what showed it (Claude review finding 12).\n const group = `${entry.scope}\\u0000${entry.base}\\u0000${entry.viewId}`;\n const list = groups.get(group) ?? [];\n list.push(entry);\n groups.set(group, list);\n }\n const created: MutationEntry[] = [];\n for (const entries of groups.values()) {\n for (let start = 0; start < entries.length; start += OPS_PER_MUTATION) {\n const chunk = entries.slice(start, start + OPS_PER_MUTATION);\n const first = chunk[0] as PendingEntry;\n const mutation: MutationEntry = {\n kind: \"mutation\",\n viewerId: this.#viewer.id,\n tab: this.#options.tab,\n viewId: first.viewId !== \"\" ? first.viewId : (this.view?.viewId ?? \"\"),\n scope: first.scope,\n mutationId: MutationId.create(),\n baseRevision: first.base as number,\n ops: chunk.map((entry) => entry.op),\n seq: Date.now() * 1000 + (this.#seq++ % 1000),\n };\n for (const entry of chunk) {\n const key = fieldKey(entry.scope, entry.op.id);\n this.#pending.delete(key);\n this.#sending.set(key, {\n value: entry.op.delete ? undefined : entry.op.value,\n mutationId: mutation.mutationId,\n });\n }\n void this.#options.journal.promote(mutation, chunk).catch(() => undefined);\n created.push(mutation);\n this.#queue.push(mutation);\n }\n }\n if (created.length > 0)\n this.#changed(created.flatMap((m) => m.ops.map((op) => fieldKey(m.scope, op.id))));\n await this.#drain(options.keepalive === true);\n return { revision: this.#ownRevision(), unsaved: this.unsaved() };\n }\n\n /** The draft revision the page's own saves reached. */\n #ownRevision(): number {\n let revision = this.#seen.viewer;\n for (const [key, server] of this.#server) {\n if (key.startsWith(\"viewer:\")) revision = Math.max(revision, server.revision);\n }\n return revision;\n }\n\n /** Sends queued mutations one at a time, in order, until the queue is empty or the page is offline. */\n async #drain(keepalive: boolean): Promise<void> {\n if (keepalive) {\n // The page is closing: every request goes out now, outliving it.\n // A hidden page may come back: each answered request leaves the queue (GPT review finding 9).\n for (const mutation of [...this.#queue]) {\n void this.#send(mutation, true)\n .then((outcome) => {\n if (outcome === \"done\") this.#dequeue(mutation);\n })\n .catch(() => undefined);\n }\n return;\n }\n if (this.#sendingQueue) {\n await new Promise<void>((resolve) => {\n const check = (): void => {\n if (!this.#sendingQueue) resolve();\n else this.#timers.setTimeout(check, 20);\n };\n check();\n });\n if (this.#queue.length === 0) return;\n }\n this.#sendingQueue = true;\n try {\n while (this.#queue.length > 0 && !this.#revoked) {\n const head = this.#queue[0] as MutationEntry;\n const outcome = await this.#send(head, false);\n if (outcome === \"retry\") {\n this.#scheduleRetry();\n return;\n }\n this.#dequeue(head);\n }\n this.#retryMs = 1_000;\n } finally {\n this.#sendingQueue = false;\n }\n }\n\n /** Removes an answered mutation from the queue; the page's save state changes only now. */\n #dequeue(mutation: MutationEntry): void {\n const index = this.#queue.indexOf(mutation);\n if (index === -1) return;\n this.#queue.splice(index, 1);\n this.#changed(mutation.ops.map((op) => fieldKey(mutation.scope, op.id)));\n }\n\n /**\n * The event stream just brought something, so the gateway is reachable: saves waiting out a\n * backoff after a network failure try again soon instead of after up to 30 s (FAILURE_MODEL\n * §5, \"on reconnect the journal replays\"). The backoff itself isn't reset, so a path that keeps\n * failing while the stream works (a proxy refusing POSTs) is tried at most once per message.\n */\n #gatewayHeard(): void {\n if (this.#retry === undefined) return;\n this.#timers.clearTimeout(this.#retry);\n this.#retry = this.#timers.setTimeout(() => {\n this.#retry = undefined;\n void this.#drain(false);\n }, RETRY_SOON_MS);\n }\n\n #scheduleRetry(): void {\n if (this.#retry !== undefined) return;\n this.#retry = this.#timers.setTimeout(() => {\n this.#retry = undefined;\n void this.#drain(false);\n }, this.#retryMs);\n this.#retryMs = Math.min(this.#retryMs * 2, 30_000);\n }\n\n #kickQueue(): void {\n if (this.#retry !== undefined) {\n this.#timers.clearTimeout(this.#retry);\n this.#retry = undefined;\n }\n this.#retryMs = 1_000;\n void this.flush();\n }\n\n /** Sends one mutation; `retry` when the network failed and it stays queued. */\n async #send(mutation: MutationEntry, keepalive: boolean): Promise<\"done\" | \"retry\"> {\n this.#inflight.set(mutation.mutationId, mutation);\n let result: MutationResult;\n try {\n result = await this.#transport().mutate(\n {\n mutationId: mutation.mutationId,\n scope: mutation.scope,\n baseRevision: String(mutation.baseRevision),\n viewId: mutation.viewId,\n ops: mutation.ops,\n },\n { keepalive },\n );\n } catch (error) {\n if (error instanceof NetworkError) {\n this.#online = false;\n this.#changed(mutation.ops.map((op) => fieldKey(mutation.scope, op.id)));\n return \"retry\";\n }\n return this.#refusedMutation(mutation, error);\n } finally {\n this.#inflight.delete(mutation.mutationId);\n }\n if (!this.#online) this.#online = true;\n this.#answered(mutation, result);\n return \"done\";\n }\n\n /** A mutation the gateway answered. */\n #answered(mutation: MutationEntry, result: MutationResult): void {\n const revision = Number(result.revision);\n const touched: FieldKey[] = [];\n const conflicts = new Map(result.conflicts.map((conflict) => [conflict.id, conflict]));\n const applied: { id: string; value: unknown }[] = [];\n for (const op of mutation.ops) {\n const key = fieldKey(mutation.scope, op.id);\n touched.push(key);\n const sending = this.#sending.get(key);\n const mine = op.delete ? undefined : op.value;\n if (sending?.mutationId === mutation.mutationId) this.#sending.delete(key);\n const conflict = conflicts.get(op.id);\n if (conflict) {\n this.#conflicted(key, op, conflict, mutation);\n continue;\n }\n if (result.applied.includes(op.id)) {\n const current = this.#server.get(key);\n if (!current || current.revision < revision) {\n this.#server.set(key, {\n value: mine,\n revision,\n deleted: op.delete === true,\n updatedBy: { kind: \"viewer\", ...(this.#viewer ? { id: this.#viewer.id } : {}) },\n });\n }\n applied.push({ id: op.id, value: mine });\n // A later edit of the field, made while this one was in flight, is based on it.\n const later = this.#pending.get(key);\n if (later && later.base === null) {\n const based = { ...later, base: revision };\n this.#pending.set(key, based);\n void this.#options.journal.putPending(based).catch(() => undefined);\n }\n }\n }\n void this.#options.journal.remove(mutation.mutationId).catch(() => undefined);\n if (applied.length > 0) {\n this.#broadcast?.postMessage({\n kind: \"applied\",\n scope: mutation.scope,\n revision,\n changes: applied,\n });\n }\n this.#resolveCatchUp();\n this.#changed(touched);\n // Edits that waited for this answer can go now.\n if ([...this.#pending.values()].some((entry) => entry.base !== null)) this.#schedule();\n }\n\n #conflicted(key: FieldKey, op: FieldOp, conflict: FieldConflict, mutation: MutationEntry): void {\n const theirs = conflict.deleted ? undefined : conflict.value;\n const mine = op.delete ? undefined : op.value;\n this.#unknown.delete(key);\n this.#server.set(key, {\n value: theirs,\n revision: Number(conflict.revision),\n deleted: conflict.deleted === true,\n ...(conflict.updatedBy ? { updatedBy: conflict.updatedBy } : {}),\n });\n const later = this.#pending.get(key);\n // The same value written twice (a replay of an edit that already landed) is no conflict.\n if (same(theirs, later ? (later.op.delete ? undefined : later.op.value) : mine)) {\n if (later) {\n this.#pending.delete(key);\n void this.#options.journal.dropPending(later).catch(() => undefined);\n }\n return;\n }\n // The viewer's value stays as a held edit, shown as theirs to keep or drop. It keeps the\n // base it was made on, so a page that replays it from the journal meets the same conflict\n // instead of writing over theirs; only `keepMine()` moves it to their revision (GPT review\n // finding 1).\n const held: PendingEntry =\n later !== undefined\n ? later.base === null\n ? { ...later, base: mutation.baseRevision }\n : later\n : {\n kind: \"pending\",\n viewerId: mutation.viewerId,\n tab: this.#options.tab,\n viewId: mutation.viewId,\n scope: mutation.scope,\n op,\n base: mutation.baseRevision,\n at: Date.now(),\n };\n this.#pending.set(key, held);\n void this.#options.journal.putPending(held).catch(() => undefined);\n this.#conflicts.set(key, {\n theirs,\n deleted: conflict.deleted === true,\n revision: Number(conflict.revision),\n ...(conflict.updatedBy ? { updatedBy: conflict.updatedBy } : {}),\n });\n }\n\n /** A mutation the gateway refused: dropped from the queue, its values handled per refusal. */\n async #refusedMutation(mutation: MutationEntry, error: unknown): Promise<\"done\" | \"retry\"> {\n const code = error instanceof MostraError ? error.code : \"MOSTRA_HOST_INTERNAL_ERROR\";\n const keys = mutation.ops.map((op) => fieldKey(mutation.scope, op.id));\n const forget = (): void => {\n for (const key of keys) {\n const sending = this.#sending.get(key);\n if (sending?.mutationId === mutation.mutationId) this.#sending.delete(key);\n }\n void this.#options.journal.remove(mutation.mutationId).catch(() => undefined);\n };\n switch (code) {\n case \"MOSTRA_HYGIENE_TOKEN_REVOKED\":\n // The link died: the journal keeps the edits for a working link (FAILURE_MODEL §8).\n this.#revoked = true;\n this.#changed(keys);\n return \"retry\";\n case \"MOSTRA_SUBMIT_VIEW_INVALID\":\n // A view another link opened (an adopted entry): replay it as this page's view.\n if (this.view && mutation.viewId !== this.view.viewId) {\n const moved = { ...mutation, viewId: this.view.viewId };\n this.#queue[0] = moved;\n void this.#options.journal.promote(moved, []).catch(() => undefined);\n return this.#send(moved, false);\n }\n break;\n case \"MOSTRA_SUBMIT_ALREADY\":\n // A `once` submission closed the draft; these edits can't land (D106).\n this.#closed = true;\n forget();\n this.#changed(this.#allKeys());\n return \"done\";\n case \"MOSTRA_HOME_DISK_FULL\":\n case \"MOSTRA_HOME_GONE\":\n case \"MOSTRA_HOST_INTERNAL_ERROR\":\n // The gateway's trouble, not the edit's: it waits and retries (FAILURE_MODEL §3).\n this.#online = false;\n this.#changed(keys);\n return \"retry\";\n default:\n break;\n }\n // Refused for good (too large, an invalid ID or value): the value stays on the page, not\n // truncated, with the reason, and isn't sent again until the viewer changes it.\n const message = error instanceof Error ? error.message : String(error);\n for (const op of mutation.ops) {\n const key = fieldKey(mutation.scope, op.id);\n if (!this.#pending.has(key)) {\n const held: PendingEntry = {\n kind: \"pending\",\n viewerId: mutation.viewerId,\n tab: this.#options.tab,\n viewId: mutation.viewId,\n scope: mutation.scope,\n op,\n base: mutation.baseRevision,\n at: Date.now(),\n };\n this.#pending.set(key, held);\n // Journaled before the mutation is forgotten: the next page still has the value (GPT\n // review finding 7).\n void this.#options.journal.putPending(held).catch(() => undefined);\n }\n this.#refused.set(key, { code, message });\n }\n forget();\n this.#changed(keys);\n return \"done\";\n }\n\n // ── The journal ────────────────────────────────────────────────────────────────────────\n\n /**\n * Replays what earlier pages left: this tab's entries (none on a fresh load) and those of tabs\n * that are gone, mutations first in their order, then pending edits (IN-02, IN-04).\n */\n #recoverJournal(): Promise<void> {\n const exclusive = this.#options.exclusive ?? (<T>(fn: () => Promise<T>) => fn());\n return exclusive(() => this.#adoptJournal()).catch(() => undefined);\n }\n\n async #adoptJournal(): Promise<void> {\n const viewerId = this.#viewer?.id;\n if (!viewerId) return;\n let contents: Awaited<ReturnType<Journal[\"load\"]>>;\n try {\n contents = await this.#options.journal.load(viewerId);\n } catch {\n return;\n }\n const tabs = [\n ...new Set([...contents.pending, ...contents.mutations].map((entry) => entry.tab)),\n ].filter((tab) => tab !== this.#options.tab);\n const gone = this.#options.goneTabs ? await this.#options.goneTabs(tabs) : new Set(tabs);\n const mutations = contents.mutations.filter((entry) => gone.has(entry.tab));\n // Edits of one field left by several closed tabs: the newest stays an edit, the older ones\n // become mutations of their own, sent first, so each is saved or meets the others as a\n // conflict; adopting them under this tab would otherwise keep only one (GPT review finding 6).\n const pending: PendingEntry[] = [];\n const newest = new Map<FieldKey, PendingEntry>();\n for (const entry of contents.pending\n .filter((candidate) => gone.has(candidate.tab))\n .sort((a, b) => a.at - b.at)) {\n const key = fieldKey(entry.scope, entry.op.id);\n const earlier = newest.get(key);\n if (earlier) {\n const promoted: MutationEntry = {\n kind: \"mutation\",\n viewerId: earlier.viewerId,\n tab: earlier.tab,\n viewId: earlier.viewId,\n scope: earlier.scope,\n mutationId: MutationId.create(),\n baseRevision:\n earlier.base ?? this.#server.get(key)?.revision ?? this.#seen[earlier.scope],\n ops: [earlier.op],\n seq: earlier.at * 1000,\n };\n try {\n await this.#options.journal.promote(promoted, [earlier]);\n } catch {\n return;\n }\n mutations.push(promoted);\n pending.splice(pending.indexOf(earlier), 1);\n }\n newest.set(key, entry);\n pending.push(entry);\n }\n const adopted: JournalEntry[] = [...mutations.sort((a, b) => a.seq - b.seq), ...pending];\n if (adopted.length === 0) return;\n try {\n await this.#options.journal.adopt(adopted, this.#options.tab);\n } catch {\n return;\n }\n const touched: FieldKey[] = [];\n for (const entry of adopted) {\n if (entry.kind !== \"mutation\") continue;\n const mutation = { ...entry, tab: this.#options.tab };\n for (const op of mutation.ops) {\n const key = fieldKey(mutation.scope, op.id);\n touched.push(key);\n this.#sending.set(key, {\n value: op.delete ? undefined : op.value,\n mutationId: mutation.mutationId,\n });\n }\n this.#queue.push(mutation);\n }\n for (const entry of adopted) {\n if (entry.kind !== \"pending\") continue;\n const key = fieldKey(entry.scope, entry.op.id);\n touched.push(key);\n if (this.#pending.has(key)) continue;\n const base = entry.base ?? (this.#sending.has(key) ? null : this.#baseFor(key));\n this.#pending.set(key, { ...entry, tab: this.#options.tab, base });\n }\n this.#changed(touched);\n void this.flush();\n }\n\n // ── Tabs ───────────────────────────────────────────────────────────────────────────────\n\n #openChannel(): void {\n const viewerId = this.#viewer?.id;\n const artifactId = this.view?.artifactId;\n if (!viewerId || !artifactId || !this.#options.channel) return;\n this.#broadcast = this.#options.channel(`mostra:${artifactId}:${viewerId}`);\n if (!this.#broadcast) return;\n this.#broadcast.onmessage = (event: MessageEvent) => {\n const data = event.data as {\n kind?: string;\n scope?: FieldScope;\n revision?: number;\n changes?: { id: string; value: unknown }[];\n };\n if (data.kind !== \"applied\" || !data.scope || typeof data.revision !== \"number\") return;\n const touched: FieldKey[] = [];\n for (const change of data.changes ?? []) {\n const key = fieldKey(data.scope, change.id);\n const current = this.#server.get(key);\n // Only ever newer: the event stream stays the source of truth (D22).\n if (current && current.revision >= data.revision) continue;\n this.#server.set(key, {\n value: change.value,\n revision: data.revision,\n deleted: change.value === undefined,\n ...(current?.updatedBy ? { updatedBy: current.updatedBy } : {}),\n });\n touched.push(key);\n }\n if (touched.length > 0) this.#changed(touched);\n };\n }\n\n // ── Submitting ─────────────────────────────────────────────────────────────────────────\n\n /** The submission state (INTERFACES §2.3). */\n submitState(): SubmitState {\n return this.#submitState;\n }\n\n /** The viewer's submission, once made or known. */\n submission(): SubmissionSummary | undefined {\n return this.#submission;\n }\n\n /** Whether a submission closed the viewer's draft. */\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Gets the draft ready for a submit (D110, IN-02): writes the initial values of mounted viewer\n * fields the gateway never stored, saves everything, waits until the event stream reached the\n * page's own last save, and reports what still blocks.\n */\n /**\n * Adds a check that runs before every submit, either channel's: an adapter whose library\n * validates on its own schedule (react-hook-form validates on submit by default) runs its\n * validation here and updates its registrations, so the blockers are current. Returns the\n * function that removes it.\n */\n beforeSubmit(check: () => Promise<void>): () => void {\n this.#beforeSubmit.add(check);\n return () => this.#beforeSubmit.delete(check);\n }\n\n async prepareSubmit(): Promise<{\n readonly revision: number;\n readonly unsaved: boolean;\n readonly blockers: SubmitBlocker[];\n }> {\n if (this.mode === \"local\") throw targetUnavailable(\"Submitting\");\n await this.whenReady(CATCH_UP_MS);\n // A check that fails can't stop the viewer's submit: it is the adapter's, and its own\n // errors stay visible on its fields.\n await Promise.allSettled([...this.#beforeSubmit].map((check) => check()));\n for (const [key, { registration }] of this.#registrations) {\n if (registration.scope !== \"viewer\" || !this.writable(key)) continue;\n if (this.stored(key) || this.#pending.has(key) || this.#sending.has(key)) continue;\n if (registration.initial === undefined) continue;\n this.set(\"viewer\", registration.id, registration.initial, {\n ...(registration.label !== undefined ? { label: registration.label } : {}),\n ...(registration.required !== undefined ? { required: registration.required } : {}),\n ...(registration.sensitive !== undefined ? { sensitive: registration.sensitive } : {}),\n });\n }\n const flushed = await this.flush();\n await this.#caughtUp(flushed.revision);\n // A value another writer changed that the page hasn't got: the page doesn't show what would\n // be submitted until a snapshot brings it.\n if (this.#unknown.size > 0) await this.#resync();\n if (this.#seen.viewer < flushed.revision) {\n // The page's own saves landed, but its stream hasn't shown everything up to them: another\n // writer may have changed a field in between. It names only what it has shown, which the\n // gateway refuses as moved, and fetches the rest, so the viewer sees it and submits again\n // (FAILURE_MODEL §4; Claude review finding 3).\n void this.#resync();\n return { revision: this.#seen.viewer, unsaved: this.unsaved(), blockers: this.blockers() };\n }\n return {\n revision: Math.max(this.#seen.viewer, flushed.revision),\n unsaved: this.unsaved() || this.#unknown.size > 0,\n blockers: this.blockers(),\n };\n }\n\n /** Waits until the event stream reached `revision` of the draft, or a while. */\n #caughtUp(revision: number): Promise<void> {\n if (this.#seen.viewer >= revision) return Promise.resolve();\n return new Promise((resolve) => {\n const check = (): void => {\n if (this.#seen.viewer >= revision) resolve();\n else this.#catchUp.push(check);\n };\n this.#catchUp.push(check);\n this.#timers.setTimeout(resolve, CATCH_UP_MS);\n });\n }\n\n #resolveCatchUp(): void {\n for (const check of this.#catchUp.splice(0)) check();\n }\n\n /**\n * Submits through the artifact channel (D40), where the view allows it: prepares the draft,\n * refuses with `MOSTRA_SUBMIT_BLOCKED` while a field blocks, and submits the revision the\n * viewer saw.\n */\n async submit(): Promise<SubmissionSummary> {\n if (this.mode === \"local\") throw targetUnavailable(\"Submitting\");\n const view = this.view;\n if (view && !view.submitChannels.includes(\"artifact\")) {\n throw new MostraError(\n \"MOSTRA_SUBMIT_CHANNEL_DENIED\",\n \"This host takes submissions from the shell's trusted Submit only.\",\n );\n }\n if (view?.policy.policy === \"none\") {\n throw new MostraError(\n \"MOSTRA_SUBMIT_POLICY_NONE\",\n \"This artifact's submission policy is none: it takes no submissions.\",\n );\n }\n if (!this.canSubmit()) {\n throw new MostraError(\n \"MOSTRA_HYGIENE_SCOPE_DENIED\",\n \"This link doesn't carry the submit scope.\",\n );\n }\n const previous = this.#submitState;\n this.#submitState = \"submitting\";\n this.#changed();\n try {\n const prepared = await this.prepareSubmit();\n if (prepared.blockers.length > 0) {\n throw new MostraError(\n \"MOSTRA_SUBMIT_BLOCKED\",\n `Not submitted: ${prepared.blockers.map((b) => b.label ?? b.fieldId).join(\", \")} ${prepared.blockers.length === 1 ? \"needs\" : \"need\"} attention.`,\n { body: { blockers: prepared.blockers } },\n );\n }\n if (prepared.unsaved) {\n throw new MostraError(\n \"MOSTRA_SUBMIT_BLOCKED\",\n \"Not submitted: some answers aren't saved yet. Try again when the page is back online.\",\n { body: { blockers: [] } },\n );\n }\n const submission = await this.#transport().submit({\n viewId: view?.viewId ?? \"\",\n expectedRevision: String(prepared.revision),\n channel: \"artifact\",\n });\n this.#adoptSubmission(submission, false);\n // The page sees the submission, and a closed draft, at once (IN-13).\n this.#changed(this.#allKeys());\n return submission;\n } catch (error) {\n if (error instanceof MostraError && error.code === \"MOSTRA_SUBMIT_ALREADY\") {\n const existing = error.body?.[\"submission\"] as SubmissionSummary | undefined;\n if (existing) this.#adoptSubmission(existing, false);\n else this.#submitState = \"closed\";\n } else {\n this.#submitState = previous === \"submitting\" ? \"open\" : previous;\n if (error instanceof MostraError && error.code === \"MOSTRA_SUBMIT_REVISION_MOVED\") {\n // The draft changed elsewhere: the page shows it before the viewer submits again.\n await this.#resync();\n }\n }\n this.#changed();\n throw error;\n }\n }\n\n /** Raises a signal for the host's attention (IN-09). */\n async signal(name: string, payload?: unknown): Promise<void> {\n if (this.mode === \"local\") throw targetUnavailable(\"Sending a signal\");\n if (!SIGNAL_NAME_PATTERN.test(name) || name === \"submit\") {\n throw new MostraError(\n \"MOSTRA_SUBMIT_SIGNAL_INVALID\",\n `${JSON.stringify(name)} isn't a signal name: use letters, digits, \".\", \"_\" and \"-\"; \"submit\" is the shell's.`,\n );\n }\n await this.#transport().signal({\n viewId: this.view?.viewId ?? \"\",\n name,\n ...(payload !== undefined ? { payload } : {}),\n });\n }\n\n /** Takes a submission the page made, or learned of, as the viewer's. */\n adoptSubmission(submission: SubmissionSummary): void {\n this.#adoptSubmission(submission, false);\n this.#changed();\n }\n\n #adoptSubmission(incoming: SubmissionSummary, fromSnapshot: boolean): void {\n const submission = mergedSubmission(this.#submission, incoming);\n this.#submission = submission;\n // Delivery events the stream brought before this submission was known (Claude review\n // finding 8): applied now, so the state never goes back.\n const early = this.#earlyDeliveries.filter(\n (event) => (event.payload as { submissionId?: string }).submissionId === submission.id,\n );\n this.#earlyDeliveries = this.#earlyDeliveries.filter((event) => !early.includes(event));\n const policy = this.view?.policy;\n // Under `epochs` the draft goes on to the next round; under `once` it is closed.\n if (policy?.policy !== \"epochs\" || submission.epoch === this.#epoch) {\n if (policy?.policy === \"once\" || policy === undefined) this.#closed = true;\n }\n if (policy?.policy === \"epochs\" && fromSnapshot && submission.epoch < this.#epoch) {\n this.#submitState = \"open\";\n return;\n }\n this.#submitState = deliveryState(submission);\n for (const event of early) this.#deliveryEvent(event);\n }\n\n #deliveryEvent(event: EventRecord): void {\n const submission = this.#submission;\n const payload = event.payload as {\n submissionId?: string;\n deliveryId?: string;\n owner?: string;\n reason?: string;\n };\n if (!submission || payload.submissionId !== submission.id) {\n this.#earlyDeliveries = [...this.#earlyDeliveries, event].slice(-EARLY_DELIVERIES_MAX);\n return;\n }\n const kind = event.type.slice(\"submission.\".length);\n const state =\n kind === \"delivered\"\n ? \"delivered\"\n : kind === \"rejected\"\n ? \"rejected\"\n : kind === \"undeliverable\"\n ? \"undeliverable\"\n : \"pending\";\n const deliveries = (submission.deliveries ?? []).map((delivery) =>\n delivery.deliveryId === payload.deliveryId\n ? {\n ...delivery,\n state,\n ...(kind === \"retrying\" ? { waiting: true as const } : {}),\n ...(payload.reason !== undefined && kind !== \"retrying\"\n ? { reason: payload.reason }\n : {}),\n updatedAt: event.at,\n }\n : delivery,\n ) as NonNullable<SubmissionSummary[\"deliveries\"]>;\n this.#submission = { ...submission, deliveries, delivery: worst(deliveries) };\n this.#submitState = deliveryState(this.#submission);\n this.#changed();\n }\n\n // ── Local mode ─────────────────────────────────────────────────────────────────────────\n\n #localStorage(): Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | undefined {\n if (this.#options.local) return this.#options.local;\n try {\n return typeof localStorage === \"undefined\" ? undefined : localStorage;\n } catch {\n return undefined;\n }\n }\n\n #localRead(key: FieldKey): unknown {\n const text = this.#localStorage()?.getItem(`mostra.field.${key}`);\n if (text === null || text === undefined) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n }\n\n #localWrite(key: FieldKey, value: unknown): void {\n const storage = this.#localStorage();\n try {\n if (value === undefined) storage?.removeItem(`mostra.field.${key}`);\n else storage?.setItem(`mostra.field.${key}`, JSON.stringify(value));\n } catch {\n // A full or refused localStorage keeps the value for this page only.\n this.#pending.set(key, {\n kind: \"pending\",\n viewerId: \"\",\n tab: this.#options.tab,\n viewId: \"\",\n scope: keyParts(key).scope,\n op:\n value === undefined\n ? { id: keyParts(key).id, delete: true }\n : { id: keyParts(key).id, value },\n base: 0,\n at: Date.now(),\n });\n }\n }\n\n #localIds(scope: FieldScope): string[] {\n const storage = this.#localStorage() as Storage | undefined;\n if (!storage || typeof storage.length !== \"number\") return [];\n const prefix = `mostra.field.${scope}:`;\n const ids: string[] = [];\n for (let index = 0; index < storage.length; index += 1) {\n const name = storage.key(index);\n if (name?.startsWith(prefix)) ids.push(name.slice(prefix.length));\n }\n return ids;\n }\n}\n\nconst SEVERITY = { delivered: 0, pending: 1, rejected: 2, undeliverable: 3 } as const;\n\nfunction worst(\n deliveries: NonNullable<SubmissionSummary[\"deliveries\"]>,\n): SubmissionSummary[\"delivery\"] {\n let result: SubmissionSummary[\"delivery\"] = \"delivered\";\n for (const delivery of deliveries) {\n if (SEVERITY[delivery.state] > SEVERITY[result]) result = delivery.state;\n }\n return result;\n}\n\n/** The submission's state as the viewer sees it (IN-13, D47). */\nexport function deliveryState(submission: SubmissionSummary): SubmitState {\n const deliveries = submission.deliveries ?? [];\n if (submission.delivery === \"undeliverable\" || submission.delivery === \"rejected\") {\n return \"undeliverable\";\n }\n if (submission.delivery === \"delivered\") return \"delivered\";\n return deliveries.some((delivery) => delivery.state === \"pending\" && delivery.waiting)\n ? \"pending-delivery\"\n : \"submitted\";\n}\n","\"use client\";\n\n/**\n * The artifact's end of the shell bridge (INTERFACES §5, SH-04). The client runtime starts it:\n * when the page runs inside Mostra's shell, it learns the shell's exact origin and its link's\n * scopes from its own session (`GET /_mostra/session`, readable only by this origin), introduces\n * itself with MCP Apps' `ui/initialize`, whose answer names the view this frame load is (D104),\n * and reports `mostra/ready` once the page has rendered. Messages from any other window or origin\n * are dropped. Outside a shell (a static export, the page opened on its own) it does nothing.\n */\nimport {\n type AnyBridgeMessage,\n type Bridge,\n connectBridge,\n MCP_APPS_PROTOCOL_VERSION,\n mostraReady,\n OPEN_LINK_SCHEMES,\n type UiInitializeResult,\n uiInitialize,\n uiInitialized,\n uiOpenLink,\n type Viewer,\n} from \"@mostra/protocol\";\n\n/**\n * The version this page's build belongs to: its `<meta name=\"mostra-version\">`, which Mostra's\n * builder writes (WP-07). `undefined` for a build that has none. @internal\n */\nexport function builtVersion(): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n const content = document.querySelector('meta[name=\"mostra-version\"]')?.getAttribute(\"content\");\n return content ? content : undefined;\n}\n\n/** `ui/initialize`'s `mostra` params: the page's version, when the build names it. */\nfunction versionParams(): { mostra?: { versionId: string } } {\n const versionId = builtVersion();\n return versionId === undefined ? {} : { mostra: { versionId } };\n}\n\n/** The shell connection of this page, once it is established. */\nexport interface ShellConnection {\n /** The shell's origin. */\n readonly shellOrigin: string;\n /** What the shell said about where the page is shown, and the view (`host.mostra`). */\n readonly host: UiInitializeResult;\n /** The bridge, for the client runtime's messages. */\n readonly bridge: Bridge;\n /**\n * The frame session's facts: its CSRF token, the link's scopes (D97, D98) and, from gateways\n * since WP-07, the viewer it acts as.\n */\n readonly session: {\n readonly csrf: string;\n readonly scopes: readonly string[];\n readonly viewer?: Viewer;\n };\n}\n\ninterface FrameSession {\n readonly shellOrigin?: unknown;\n readonly csrf?: unknown;\n readonly scopes?: unknown;\n readonly viewer?: unknown;\n}\n\n/** Hears what the shell sends: requests answered by the first handler that returns a value. */\nexport interface ShellListener {\n readonly request?: (message: AnyBridgeMessage, params: unknown) => unknown;\n readonly notification?: (message: AnyBridgeMessage, params: unknown) => void;\n}\n\nconst listeners = new Set<ShellListener>();\nlet connecting: Promise<ShellConnection | undefined> | undefined;\n\n/**\n * Listens to the shell's requests and notifications on this page's bridge; returns the function\n * that stops. The client runtime answers `mostra/flush` and hears `mostra/version.available`.\n */\nexport function listenShell(listener: ShellListener): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\n/**\n * Connects this page to the shell that frames it, once; later calls return the same connection.\n * Resolves `undefined` when the page isn't framed by a Mostra shell. The client runtime calls it;\n * artifact code doesn't need to.\n */\nexport function connectShell(): Promise<ShellConnection | undefined> {\n connecting ??= (async () => {\n if (typeof window === \"undefined\" || window.parent === window) return undefined;\n let session: FrameSession;\n try {\n const response = await fetch(\"/_mostra/session\", {\n credentials: \"same-origin\",\n cache: \"no-store\",\n signal: AbortSignal.timeout(HANDSHAKE_TIMEOUT_MS),\n });\n if (!response.ok) return undefined;\n session = (await response.json()) as FrameSession;\n } catch {\n return undefined;\n }\n if (typeof session.shellOrigin !== \"string\") return undefined;\n const shellOrigin = session.shellOrigin;\n const bridge = connectBridge({\n side: \"artifact\",\n receiver: window,\n peer: () => window.parent,\n peerOrigin: shellOrigin,\n onRequest: async (message, params) => {\n for (const listener of listeners) {\n const answer = await listener.request?.(message, params);\n if (answer !== undefined) return answer;\n }\n throw new Error(`The page doesn't answer ${message.method}.`);\n },\n onNotification: (message, params) => {\n for (const listener of listeners) listener.notification?.(message, params);\n },\n });\n let host: UiInitializeResult;\n try {\n host = await bridge.call(\n uiInitialize,\n {\n appInfo: { name: \"mostra-artifact\", version: \"0\" },\n appCapabilities: {},\n protocolVersion: MCP_APPS_PROTOCOL_VERSION,\n ...versionParams(),\n },\n { timeoutMs: HANDSHAKE_TIMEOUT_MS },\n );\n } catch (error) {\n bridge.close();\n throw error;\n }\n bridge.notify(uiInitialized, {});\n return {\n shellOrigin,\n host,\n bridge,\n session: {\n csrf: typeof session.csrf === \"string\" ? session.csrf : \"\",\n scopes: Array.isArray(session.scopes)\n ? session.scopes.filter((scope): scope is string => typeof scope === \"string\")\n : [],\n ...(isViewer(session.viewer) ? { viewer: session.viewer } : {}),\n },\n };\n })().then(\n (connection) => {\n // A framed page that didn't connect may try again (the daemon restarting during the\n // frame's load, a slow handshake): only a connection is kept (Claude review finding 4).\n if (connection === undefined) connecting = undefined;\n return connection;\n },\n () => {\n connecting = undefined;\n return undefined;\n },\n );\n return connecting;\n}\n\n/** Whether the session's `viewer` looks like a viewer (a light check: the gateway sends it). */\nfunction isViewer(value: unknown): value is Viewer {\n const viewer = value as { id?: unknown; kind?: unknown } | null | undefined;\n return typeof viewer?.id === \"string\" && typeof viewer.kind === \"string\";\n}\n\n/** How long one attempt at the shell's handshake may take. */\nconst HANDSHAKE_TIMEOUT_MS = 10_000;\n\n/**\n * Tells the shell the page has rendered (`mostra/ready`), after the next frame paints. The\n * client runtime calls it right after mounting the page.\n */\nexport function reportReady(): void {\n void connectShell().then((connection) => {\n if (!connection) return;\n requestAnimationFrame(() => connection.bridge.notify(mostraReady, {}));\n });\n}\n\n/**\n * Opens `url` for the viewer in a new tab. Inside Mostra's shell the frame can't navigate the\n * viewer's tab (D98 item 7), so the shell opens it (`ui/open-link`, MCP Apps); on a page of its\n * own, the browser does. Only `http:`, `https:`, `mailto:` and `tel:` URLs open. Resolves `true`\n * when the URL was handed to the browser.\n */\nexport async function openLink(url: string): Promise<boolean> {\n const connection = await connectShell();\n if (connection) {\n try {\n const result = await connection.bridge.call(uiOpenLink, { url });\n return result.isError !== true;\n } catch {\n return false;\n }\n }\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return false;\n }\n if (!OPEN_LINK_SCHEMES.includes(parsed.protocol)) return false;\n window.open(parsed.href, \"_blank\", \"noopener,noreferrer\");\n return true;\n}\n","\"use client\";\n\n/**\n * The client runtime's hooks (INTERFACES §2.3, D52, D53, D113): fields that behave like\n * `useState` with a stable ID, the artifact channel's submit, the shell's trusted Submit label,\n * signals, choices, the viewer and the artifact. Every hook works in every delivery target: where\n * there is no Mostra server (a static export), fields keep their values in this browser, and\n * submit and signals reject with `MOSTRA_TARGET_UNAVAILABLE`.\n */\nimport {\n type Actor,\n type ControlRequest,\n type FieldScope,\n mostraControlsRequest,\n type SubmissionSummary,\n type SubmitBlocker,\n} from \"@mostra/protocol\";\nimport {\n createContext,\n createElement,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { MostraError } from \"./runtime/errors.ts\";\nimport { MemoryJournal } from \"./runtime/journal.ts\";\nimport { type FieldKey, fieldKey, Store, type SubmitState } from \"./runtime/store.ts\";\nimport { connectShell } from \"./shell-bridge.ts\";\n\n/** Where the artifact runs (D111): Mostra's gateway, a static export, an MCP App, or `verify`. */\nexport type ArtifactMode = \"live\" | \"static\" | \"mcp-app\" | \"verify\";\n\ninterface RuntimeValue {\n readonly store: Store;\n readonly mode: ArtifactMode;\n}\n\nconst RuntimeContext = createContext<RuntimeValue | undefined>(undefined);\n\nlet fallback: RuntimeValue | undefined;\n\n/** The runtime of a tree rendered outside `mountArtifact` (a test, a component gallery): local. */\nfunction fallbackRuntime(): RuntimeValue {\n if (!fallback) {\n const store = new Store({ mode: \"local\", journal: new MemoryJournal(), tab: \"fallback\" });\n store.start();\n fallback = { store, mode: \"static\" };\n }\n return fallback;\n}\n\n/** Provides a runtime to a tree; `mountArtifact` renders the page inside it. */\nexport function RuntimeProvider(props: {\n readonly store: Store;\n readonly mode: ArtifactMode;\n readonly children?: ReactNode;\n}): ReactNode {\n const value = useMemo(\n () => ({ store: props.store, mode: props.mode }),\n [props.store, props.mode],\n );\n return createElement(RuntimeContext.Provider, { value }, props.children);\n}\n\nfunction useRuntime(): RuntimeValue {\n return useContext(RuntimeContext) ?? fallbackRuntime();\n}\n\n/** The page's store, for the package's own adapters (`@mostra/react/form`). @internal */\nexport function useStore(): Store {\n return useRuntime().store;\n}\n\n/** Re-renders on every change of the store; returns its version. */\nfunction useStoreVersion(store: Store): number {\n return useSyncExternalStore(store.subscribe, store.version, store.version);\n}\n\n// ── useField ────────────────────────────────────────────────────────────────────────────\n\n/**\n * A Standard Schema validator (`~standard`), such as a Zod 4 schema: what `validate` takes besides\n * a function.\n */\nexport interface StandardSchema<T> {\n /** The Standard Schema interface (version 1). */\n readonly \"~standard\": {\n /** Checks a value: issues when it is invalid. */\n validate(\n value: unknown,\n ): { readonly issues?: readonly { readonly message: string }[] } | Promise<unknown>;\n /** The type the schema accepts. */\n readonly types?: { readonly input: T; readonly output: T } | undefined;\n };\n}\n\n/** Options of {@link useField} (D52). */\nexport interface FieldOptions<T> {\n /** The label people see in results and the shell's list of missing answers. */\n readonly label?: string;\n /** A submit needs a value: the shell and `useSubmit` list it until it has one. */\n readonly required?: boolean;\n /** Kept in the submission, left out of events and logs. */\n readonly sensitive?: boolean;\n /** A Zod (or any Standard Schema) schema, or a function returning a message for a bad value. */\n readonly validate?: StandardSchema<T> | ((value: T) => string | undefined);\n /** `viewer` (default): the viewer's draft. `artifact`: shared state every viewer sees (D63). */\n readonly scope?: FieldScope;\n}\n\n/** What a field is doing (INTERFACES §2.3). */\nexport interface FieldMeta<T> {\n /**\n * `saved`; `saving`; `offline` (not saved yet: no connection, or the gateway refused it, with\n * `error`); `conflict` (another writer changed it: see `conflict`); `readonly` (submitted under\n * `once`, a view-only link, or a copy of the page without a Mostra server).\n */\n readonly save: \"saved\" | \"saving\" | \"offline\" | \"conflict\" | \"readonly\";\n /** The validation message for the current value, or why the gateway refused it. */\n readonly error?: string;\n /** Another writer changed the field since the viewer's edit: keep theirs or mine. */\n readonly conflict?: { readonly theirs: T; keepMine(): void; takeTheirs(): void };\n /** Who last wrote the field (artifact scope, D63). */\n readonly updatedBy?: { readonly kind: \"viewer\" | \"agent\" | \"host\"; readonly name?: string };\n}\n\n/** What a field's validator says of a value: now, or once its asynchronous check settles. */\ntype Validation =\n | { readonly kind: \"now\"; readonly error: string | undefined }\n | { readonly kind: \"later\"; readonly settled: Promise<string | undefined> };\n\n/** The message shown while an asynchronous check runs; it blocks a submit until it settles. */\nconst CHECKING = \"Checking this answer…\";\n\nfunction messageOf(result: unknown): string | undefined {\n const issues = (result as { issues?: readonly { message: string }[] } | undefined)?.issues;\n return issues && issues.length > 0 ? (issues[0]?.message ?? \"Invalid value.\") : undefined;\n}\n\nfunction validationOf<T>(validate: FieldOptions<T>[\"validate\"], value: T): Validation {\n if (validate === undefined) return { kind: \"now\", error: undefined };\n if (typeof validate === \"function\") return { kind: \"now\", error: validate(value) ?? undefined };\n const result = validate[\"~standard\"].validate(value);\n if (result instanceof Promise) {\n // A Standard Schema may check asynchronously (Zod's async refinements): the answer counts\n // only once the check settles (GPT review finding 14).\n return {\n kind: \"later\",\n settled: result.then(messageOf, () => \"This answer couldn't be checked.\"),\n };\n }\n return { kind: \"now\", error: messageOf(result) };\n}\n\nfunction updatedByOf(actor: Actor | undefined): FieldMeta<unknown>[\"updatedBy\"] {\n if (!actor || actor.kind === \"mostra\") return undefined;\n return { kind: actor.kind, ...(actor.name !== undefined ? { name: actor.name } : {}) };\n}\n\nconst warned = new Set<string>();\n\n/**\n * A persisted value with a stable field ID (D52). It behaves like `useState`: the value the viewer\n * sees, a setter, and what the field is doing. Edits save to Mostra as the viewer works, survive\n * reloads, closed tabs and other devices, reach other tabs, and carry over to newer versions by\n * ID. Dotted IDs (`reply.m1`) nest in results.\n *\n * ```tsx\n * const [layout, setLayout, meta] = useField(\"layout\", \"a\", { label: \"Layout\", required: true });\n * ```\n */\nexport function useField<T>(\n id: string,\n initial: T,\n // `NoInfer`: the type comes from `initial`, as `useState`'s does; a validator annotated\n // `(value: number)` must not narrow `useField(\"count\", 1)` to the literal type `1`.\n options: FieldOptions<NoInfer<T>> = {},\n): [T, (next: T | ((previous: T) => T)) => void, FieldMeta<T>] {\n const { store } = useRuntime();\n const scope = options.scope ?? \"viewer\";\n const key = fieldKey(scope, id);\n // The first render's initial value, as `useState` keeps it.\n const [first] = useState(() => initial);\n useSyncExternalStore(\n store.subscribe,\n () => store.keyVersion(key),\n () => store.keyVersion(key),\n );\n const value = store.value(key, first) as T;\n const { validate } = options;\n const validation = useMemo(() => validationOf(validate, value), [validate, value]);\n const [settled, setSettled] = useState<{ of: Validation; error: string | undefined }>();\n useEffect(() => {\n if (validation.kind !== \"later\") return;\n let current = true;\n void validation.settled.then((message) => {\n if (current) setSettled({ of: validation, error: message });\n });\n return () => {\n current = false;\n };\n }, [validation]);\n const error =\n validation.kind === \"now\"\n ? validation.error\n : settled?.of === validation\n ? settled.error\n : CHECKING;\n const { label, required, sensitive } = options;\n\n // Registered once per mount and ID; the next effect keeps its options current.\n // biome-ignore lint/correctness/useExhaustiveDependencies: options change through updateRegistration.\n useEffect(\n () =>\n store.register({\n id,\n scope,\n initial: first,\n ...(label !== undefined ? { label } : {}),\n ...(required !== undefined ? { required } : {}),\n ...(sensitive !== undefined ? { sensitive } : {}),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the next effect keeps the options current.\n [store, id, scope, first],\n );\n useEffect(() => {\n store.updateRegistration({\n id,\n scope,\n initial: first,\n ...(label !== undefined ? { label } : {}),\n ...(required !== undefined ? { required } : {}),\n ...(sensitive !== undefined ? { sensitive } : {}),\n ...(error !== undefined ? { error } : {}),\n });\n });\n // A submit waits for an asynchronous check of the value it would send, then counts its answer.\n useEffect(() => {\n if (validation.kind !== \"later\") return;\n return store.beforeSubmit(async () => {\n const message = await validation.settled;\n store.updateRegistration({\n id,\n scope,\n initial: first,\n ...(label !== undefined ? { label } : {}),\n ...(required !== undefined ? { required } : {}),\n ...(sensitive !== undefined ? { sensitive } : {}),\n ...(message !== undefined ? { error: message } : {}),\n });\n });\n }, [store, validation, id, scope, first, label, required, sensitive]);\n\n const set = useCallback(\n (next: T | ((previous: T) => T)) => {\n if (!store.writable(key)) {\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `Mostra: the field ${id} is read-only here (submitted, or a view-only link); the change was not kept.`,\n );\n }\n return;\n }\n const previous = store.value(key, first) as T;\n const resolved =\n typeof next === \"function\" ? (next as (previous: T) => T)(previous) : (next as T);\n store.set(scope, id, resolved, {\n ...(label !== undefined ? { label } : {}),\n ...(required !== undefined ? { required } : {}),\n ...(sensitive !== undefined ? { sensitive } : {}),\n });\n },\n [store, key, scope, id, label, required, sensitive, first],\n );\n\n const conflict = store.conflict(key);\n const refusal = store.refusal(key);\n const save = store.save(key);\n const writer = updatedByOf(store.updatedBy(key));\n const writerKind = writer?.kind;\n const writerName = writer?.name;\n const meta = useMemo((): FieldMeta<T> => {\n const message = error ?? refusal?.message;\n const updatedBy =\n writerKind === undefined\n ? undefined\n : { kind: writerKind, ...(writerName !== undefined ? { name: writerName } : {}) };\n return {\n save,\n ...(message !== undefined ? { error: message } : {}),\n ...(conflict\n ? {\n conflict: {\n theirs: (conflict.deleted ? first : conflict.theirs) as T,\n keepMine: () => store.keepMine(key),\n takeTheirs: () => store.takeTheirs(key),\n },\n }\n : {}),\n ...(scope === \"artifact\" && updatedBy ? { updatedBy } : {}),\n };\n }, [save, error, refusal, conflict, writerKind, writerName, store, key, scope, first]);\n return [value, set, meta];\n}\n\n// ── useSubmit ───────────────────────────────────────────────────────────────────────────\n\n/** What `useSubmit` returns (INTERFACES §2.3). */\nexport interface SubmitHandle {\n /**\n * Submits the viewer's draft through the artifact's own code (D40). Rejects with\n * `MOSTRA_SUBMIT_CHANNEL_DENIED` where the host takes the shell's trusted Submit only,\n * `MOSTRA_SUBMIT_BLOCKED` while a field blocks, `MOSTRA_SUBMIT_ALREADY` under a closed `once`.\n */\n submit(): Promise<SubmissionSummary>;\n /** Whether `submit()` can work here: the host allows the artifact channel and the draft is open. */\n readonly allowed: boolean;\n /** What blocks a submit now. */\n readonly blockers: readonly SubmitBlocker[];\n /** Where the submission stands (IN-13). */\n readonly state: SubmitState;\n /** The viewer's submission, once made. */\n readonly submission?: { readonly id: string; readonly at: string };\n}\n\n/** The artifact channel's submit, the blockers and the submission's state (D40, IN-13). */\nexport function useSubmit(): SubmitHandle {\n const { store } = useRuntime();\n const version = useStoreVersion(store);\n // biome-ignore lint/correctness/useExhaustiveDependencies: the version stands for the store's state.\n return useMemo((): SubmitHandle => {\n const view = store.view;\n const state = store.submitState();\n const submission = store.submission();\n const openState =\n state === \"open\" || (view?.policy.policy === \"epochs\" && state !== \"submitting\");\n const allowed =\n store.mode === \"live\" &&\n view !== undefined &&\n view.submitChannels.includes(\"artifact\") &&\n view.policy.policy !== \"none\" &&\n store.canSubmit() &&\n !store.closed &&\n openState;\n return {\n submit: () => store.submit(),\n allowed,\n blockers: store.blockers(),\n state,\n ...(submission ? { submission: { id: submission.id, at: submission.at } } : {}),\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `version` stands for the store's state.\n }, [store, version]);\n}\n\n/** Asks the shell for a trusted control while mounted, and withdraws it on unmount. */\nfunction useControl(request: ControlRequest | undefined, release: ControlRequest): void {\n const text = request === undefined ? undefined : JSON.stringify(request);\n const releaseText = JSON.stringify(release);\n useEffect(() => {\n if (text === undefined) return;\n let active = true;\n void connectShell().then((connection) => {\n if (!active || !connection) return;\n void connection.bridge\n .call(mostraControlsRequest, JSON.parse(text) as ControlRequest)\n .catch(() => undefined);\n });\n return () => {\n active = false;\n void connectShell().then((connection) => {\n void connection?.bridge\n .call(mostraControlsRequest, JSON.parse(releaseText) as ControlRequest)\n .catch(() => undefined);\n });\n };\n }, [text, releaseText]);\n}\n\n/**\n * Relabels the shell's trusted Submit while mounted, and asks the shell to confirm with `confirm`\n * first (D06, SH-02). The artifact asks; the shell renders the control in its own origin, where\n * the artifact can't reach it.\n */\nexport function useSubmitControl(options: {\n readonly label?: string;\n readonly confirm?: string;\n}): void {\n useControl(\n {\n control: \"submit\",\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(options.confirm !== undefined ? { confirm: options.confirm } : {}),\n },\n { control: \"release\", submit: true },\n );\n}\n\n// ── useSignal ───────────────────────────────────────────────────────────────────────────\n\n/** A named signal for the host's attention (IN-09), such as \"Ping the agent\". */\nexport function useSignal(name: string): { send(payload?: unknown): Promise<void> } {\n const { store } = useRuntime();\n return useMemo(\n () => ({ send: (payload?: unknown) => store.signal(name, payload) }),\n [store, name],\n );\n}\n\n// ── useChoice ───────────────────────────────────────────────────────────────────────────\n\n/** A review set's candidate, as the trusted Choose names it. */\nexport interface ChoiceCandidate {\n /** The candidate's ID: the choice's value. */\n readonly id: string;\n /** The name the trusted Choose shows (\"Choose Dense\"), and results label it with. */\n readonly label?: string;\n}\n\n/**\n * A review set's choice (D65, D113): the field `review.<reviewSetId>.choice`. With `candidates`,\n * the shell renders a trusted Choose for the candidate the page shows (`current`); `choose()`\n * chooses from inside the page where the host allows the artifact channel (D40), else rejects\n * with `MOSTRA_SUBMIT_CHANNEL_DENIED`.\n */\nexport function useChoice(\n reviewSetId: string,\n options?: { readonly candidates?: readonly ChoiceCandidate[]; readonly current?: string },\n): { readonly choice?: string; choose(candidateId: string): Promise<void> } {\n const { store } = useRuntime();\n const id = `review.${reviewSetId}.choice`;\n const key: FieldKey = fieldKey(\"viewer\", id);\n useSyncExternalStore(\n store.subscribe,\n () => store.keyVersion(key),\n () => store.keyVersion(key),\n );\n const choice = store.value(key, undefined);\n // verify's field probe hears the choice field too (GPT review finding 6); a viewer's page has\n // no probe, and this does nothing there.\n useEffect(\n () => store.announceMount({ id, scope: \"viewer\", initial: undefined, hook: \"useChoice\" }),\n [store, id],\n );\n const candidates = options?.candidates;\n useControl(\n candidates && candidates.length > 0\n ? {\n control: \"choose\",\n reviewSetId,\n candidates: candidates.map((candidate) => ({\n id: candidate.id,\n ...(candidate.label !== undefined ? { label: candidate.label } : {}),\n })),\n ...(options?.current !== undefined ? { current: options.current } : {}),\n }\n : undefined,\n { control: \"release\", reviewSetId },\n );\n const labels = useMemo(\n () => new Map((candidates ?? []).map((candidate) => [candidate.id, candidate.label])),\n [candidates],\n );\n const choose = useCallback(\n async (candidateId: string) => {\n const view = store.view;\n if (store.mode === \"live\" && view && !view.submitChannels.includes(\"artifact\")) {\n throw new MostraError(\n \"MOSTRA_SUBMIT_CHANNEL_DENIED\",\n \"This host takes choices from the shell's trusted Choose only.\",\n );\n }\n const label = labels.get(candidateId);\n store.set(\"viewer\", id, candidateId, {\n ...(label !== undefined ? { label } : {}),\n immediate: true,\n });\n await store.flush();\n },\n [store, id, labels],\n );\n return {\n ...(typeof choice === \"string\" ? { choice } : {}),\n choose,\n };\n}\n\n// ── useViewer and useArtifact ───────────────────────────────────────────────────────────\n\n/** Who the page acts as (D104): the home's local user, a tailnet user, or a link's person. */\nexport function useViewer(): {\n readonly id: string;\n readonly name?: string;\n readonly source: \"local\" | \"tailnet\" | \"token\" | \"host\";\n} {\n const { store } = useRuntime();\n useStoreVersion(store);\n const viewer = store.viewer();\n return viewer\n ? {\n id: viewer.id,\n ...(viewer.name !== undefined ? { name: viewer.name } : {}),\n source: viewer.kind,\n }\n : { id: \"\", source: \"local\" };\n}\n\n/** The artifact, the version and the view the page shows, and where it runs (D104, D111). */\nexport function useArtifact(): {\n readonly id: string;\n readonly versionId: string;\n readonly version: number;\n readonly viewId: string;\n readonly mode: ArtifactMode;\n} {\n const { store, mode } = useRuntime();\n const view = store.view;\n return {\n id: view?.artifactId ?? \"\",\n versionId: view?.version.id ?? \"\",\n version: view?.version.number ?? 0,\n viewId: view?.viewId ?? \"\",\n mode,\n };\n}\n"],"mappings":";;;;AAkBA,IAAa,cAAb,cAAiC,MAAM;;CAErC;;CAEA;;CAEA;;CAEA;CAEA,YACE,MACA,SACA,UAII,CAAC,GACL;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,aAAa,QAAQ;EAC1B,KAAK,OAAO,QAAQ;CACtB;AACF;;AAGA,SAAgB,kBAAkB,MAA2B;CAC3D,OAAO,IAAI,YACT,6BACA,GAAG,KAAK,+EACV;AACF;;;;ACmBA,MAAa,cACX,UACW,UAAU,MAAM,SAAS,QAAQ,MAAM,IAAI,QAAQ,MAAM,MAAM,QAAQ,MAAM,GAAG;AAE7F,MAAM,eAAe,eAA+B,UAAU;AAE9D,MAAM,SAAS,UACb,MAAM,SAAS,YAAY,WAAW,KAAK,IAAI,YAAY,MAAM,UAAU;AAE7E,SAAS,MAAM,SAAkC,UAAmC;CAClF,MAAM,OAAO,QAAQ,QAAQ,UAAU,MAAM,aAAa,QAAQ;CAClE,OAAO;EACL,SAAS,KAAK,QAAQ,UAAiC,MAAM,SAAS,SAAS;E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