@mostra/react 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ArtifactManifest, ArtifactManifest as ArtifactManifest$1, Bridge, DeliveryTarget, FieldScope, RunProgress, RunStatus, SubmissionSummary, SubmissionSummary as SubmissionSummary$1, SubmitBlocker, SubmitBlocker as SubmitBlocker$1, UiInitializeResult, Viewer } from "@mostra/protocol";
1
+ import { ArtifactManifest, ArtifactManifest as ArtifactManifest$1, Bridge, DeliveryTarget, FieldScope, RunProgress, RunStatus, SubmissionSummary, SubmissionSummary as SubmissionSummary$1, SubmitBlocker, SubmitBlocker as SubmitBlocker$1, TallyValue, TallyValue as TallyValue$1, UiInitializeResult, Viewer, ViewerKind } from "@mostra/protocol";
2
2
  import { ComponentType, ReactNode } from "react";
3
3
  //#region src/runtime/store.d.ts
4
4
  /** The submission state `useSubmit` reports (INTERFACES §2.3). */
@@ -128,11 +128,14 @@ export declare function useChoice(reviewSetId: string, options?: {
128
128
  readonly choice?: string;
129
129
  choose(candidateId: string): Promise<void>;
130
130
  };
131
- /** Who the page acts as (D104): the home's local user, a tailnet user, or a link's person. */
131
+ /**
132
+ * Who the page acts as (D104): the home's local user, a tailnet user, or a link's person; on a
133
+ * hosted link, a signed-in account or an anonymous visitor (D165 item 8).
134
+ */
132
135
  export declare function useViewer(): {
133
136
  readonly id: string;
134
137
  readonly name?: string;
135
- readonly source: "local" | "tailnet" | "token" | "host";
138
+ readonly source: ViewerKind;
136
139
  };
137
140
  /** The artifact, the version and the view the page shows, and where it runs (D104, D111). */
138
141
  export declare function useArtifact(): {
@@ -295,10 +298,18 @@ type LiveValuesOf<M> = { [K in keyof M as M[K] extends {
295
298
  } ? K : never]: M[K] extends {
296
299
  readonly __value?: infer T;
297
300
  } ? T : never; };
298
- /** A live source's key: one of `LiveSources`, or any string before the declaration exists. */
299
- type LiveKey = [keyof LiveSources] extends [never] ? string : keyof LiveSources & string;
300
- /** A live source's value type. */
301
- type LiveValue<K extends string> = K extends keyof LiveSources ? LiveSources[K] : unknown;
301
+ /**
302
+ * A tally's key, `$tally/<field>` (D165 item 12): the counts of a fixed-choice field the manifest's
303
+ * `tally` names, which Mostra keeps and pushes itself.
304
+ */
305
+ type TallyKey = `$tally/${string}`;
306
+ /**
307
+ * A live source's key: one of `LiveSources`, or any string before the declaration exists, or a
308
+ * tally's key.
309
+ */
310
+ type LiveKey = ([keyof LiveSources] extends [never] ? string : keyof LiveSources & string) | TallyKey;
311
+ /** A live source's value type; a tally's is `TallyValue`. */
312
+ type LiveValue<K extends string> = K extends TallyKey ? TallyValue$1 : K extends keyof LiveSources ? LiveSources[K] : unknown;
302
313
  /** What `useLive` shows (INTERFACES §2.3). */
303
314
  interface LiveResult<T> {
304
315
  /** The latest value; in append mode, the values kept, oldest first. */
@@ -313,6 +324,11 @@ interface LiveResult<T> {
313
324
  readonly revision?: string;
314
325
  /** When the value was produced. */
315
326
  readonly at?: string;
327
+ /**
328
+ * On a hosted page, `true` while the page's owner is offline, so its producer can't refresh the
329
+ * value: `data` is the last value, from `at` (D165 item 4).
330
+ */
331
+ readonly ownerOffline?: boolean;
316
332
  }
317
333
  /**
318
334
  * Reads a live source of `live.ts`, or one an agent or host pushes to (D56): the latest value, or
@@ -412,5 +428,5 @@ declare global {
412
428
  */
413
429
  export declare function defineArtifact<const M extends ArtifactManifest$1>(manifest: M): M;
414
430
  //#endregion
415
- export type { ActionHandle, ArtifactManifest, ArtifactMode, CallServer, ChoiceCandidate, ClaudeCompatibleStorage, DiagnosticLike, FieldMeta, FieldOptions, LiveKey, LiveResult, LiveSources, LiveValue, LiveValuesOf, ServerReference, ShellConnection, StandardSchema, StorageEntry, SubmissionSummary, SubmitBlocker, SubmitHandle, SubmitState };
431
+ export type { ActionHandle, ArtifactManifest, ArtifactMode, CallServer, ChoiceCandidate, ClaudeCompatibleStorage, DiagnosticLike, FieldMeta, FieldOptions, LiveKey, LiveResult, LiveSources, LiveValue, LiveValuesOf, ServerReference, ShellConnection, StandardSchema, StorageEntry, SubmissionSummary, SubmitBlocker, SubmitHandle, SubmitState, TallyKey, TallyValue };
416
432
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["SubmissionSummary","SubmitBlocker","ArtifactManifest"],"sources":["../src/runtime/store.ts","../src/hooks.ts","../src/shell-bridge.ts","../src/mount.ts","../src/runtime/errors.ts","../src/server-hooks.ts","../src/server-reference.ts","../src/storage.ts","../src/index.ts"],"mappings":";;;;KAmGY;;;;KCjEA;;;;;UAsDK,eAAe;;WAErB;;IAEP,SACE;eACY;iBAA6B;;QAAwB;;aAE1D;eAAmB,OAAO;eAAY,QAAQ;;;;;UAK1C,aAAa;;WAEnB;;WAEA;;WAEA;;WAEA,WAAW,eAAe,OAAO,OAAO;;WAExC,QAAQ;;;UAIF,UAAU;;;;;;WAMhB;;WAEA;;WAEA;aAAsB,QAAQ;IAAG;IAAkB;;;WAEnD;aAAuB;aAA4C;;;;;;;;;;;;;wBAgD9D,SAAS,GACvB,YACA,SAAS,GAGT,UAAS,aAAa,QAAQ,OAC5B,IAAI,MAAM,MAAM,UAAU,MAAM,aAAa,UAAU;;UAoI1C;;;;;;EAMf,UAAU,QAAQA;;WAET;;WAEA,mBAAmBC;;WAEnB,OAAO;;WAEP;aAAwB;aAAqB;;;;wBAIxC,aAAa;;;;;;wBA0Db,iBAAiB;WACtB;WACA;;;wBAeK,UAAU;EAAiB,KAAK,oBAAoB;;;UAWnD;;WAEN;;WAEA;;;;;;;;wBASK,UACd,qBACA;WAAqB,sBAAsB;WAA4B;;WAC3D;EAAiB,OAAO,sBAAsB;;;wBA8D5C;WACL;WACA;WACA;;;wBAeK;WACL;WACA;WACA;WACA;WACA,MAAM;;;;;UC7dA;;WAEN;;WAEA,MAAM;;WAEN,QAAQ;;;;;WAKR;aACE;aACA;aACA,SAAS;;aA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mBAAmB,QAAQ;;EAE5C,IAAI,aAAa,gBAAgB,mBAAmB,QAAQ;;EAE5D,OACE,aACA,mBACC;aAAmB;aAAsB;aAAwB;;;EAEpE,KACE,iBACA,mBACC;aAAmB;aAAyB;aAA0B;;;QA0G5D;YACH;;IAER,SAAS;;;;;;;;;;;;;;wBC/EG,qBAAqB,UAAUC,oBAAkB,UAAU,IAAI"}
1
+ {"version":3,"file":"index.d.ts","names":["SubmissionSummary","SubmitBlocker","TallyValue","ArtifactManifest"],"sources":["../src/runtime/store.ts","../src/hooks.ts","../src/shell-bridge.ts","../src/mount.ts","../src/runtime/errors.ts","../src/server-hooks.ts","../src/server-reference.ts","../src/storage.ts","../src/index.ts"],"mappings":";;;;KAmGY;;;;KChEA;;;;;UAsDK,eAAe;;WAErB;;IAEP,SACE;eACY;iBAA6B;;QAAwB;;aAE1D;eAAmB,OAAO;eAAY,QAAQ;;;;;UAK1C,aAAa;;WAEnB;;WAEA;;WAEA;;WAEA,WAAW,eAAe,OAAO,OAAO;;WAExC,QAAQ;;;UAIF,UAAU;;;;;;WAMhB;;WAEA;;WAEA;aAAsB,QAAQ;IAAG;IAAkB;;;WAEnD;aAAuB;aAA4C;;;;;;;;;;;;;wBAgD9D,SAAS,GACvB,YACA,SAAS,GAGT,UAAS,aAAa,QAAQ,OAC5B,IAAI,MAAM,MAAM,UAAU,MAAM,aAAa,UAAU;;UAoI1C;;;;;;EAMf,UAAU,QAAQA;;WAET;;WAEA,mBAAmBC;;WAEnB,OAAO;;WAEP;aAAwB;aAAqB;;;;wBAIxC,aAAa;;;;;;wBA0Db,iBAAiB;WACtB;WACA;;;wBAeK,UAAU;EAAiB,KAAK,oBAAoB;;;UAWnD;;WAEN;;WAEA;;;;;;;;wBASK,UACd,qBACA;WAAqB,sBAAsB;WAA4B;;WAC3D;EAAiB,OAAO,sBAAsB;;;;;;wBAiE5C;WACL;WACA;WACA,QAAQ;;;wBAeH;WACL;WACA;WACA;WACA;WACA,MAAM;;;;;UCj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;;;wBAiB1C,kBAAkB,UAAU;;;;;wBAY5B,sBAAsB,aAAa;;;;UC/BlC;;WAEN;;WAEA;;WAEA;;;UAIM;;EAEf,IAAI,aAAa,mBAAmB,QAAQ;;EAE5C,IAAI,aAAa,gBAAgB,mBAAmB,QAAQ;;EAE5D,OACE,aACA,mBACC;aAAmB;aAAsB;aAAwB;;;EAEpE,KACE,iBACA,mBACC;aAAmB;aAAyB;aAA0B;;;QA0G5D;YACH;;IAER,SAAS;;;;;;;;;;;;;;wBCzEG,qBAAqB,UAAUC,oBAAkB,UAAU,IAAI"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { _ as serverFunctionId, a as useSignal, c as useSubmitControl, d as connectShell, i as useField, l as useViewer, m as reportReady, n as useArtifact, o as useStore, p as openLink, r as useChoice, s as useSubmit, x as MostraError } from "./hooks-BHhOYg3U.js";
3
- import { a as createServerReference, o as setServerCallback, t as mountArtifact } from "./mount-DSuEcMdp.js";
2
+ import { _ as serverFunctionId, a as useSignal, c as useSubmitControl, d as connectShell, i as useField, l as useViewer, m as reportReady, n as useArtifact, o as useStore, p as openLink, r as useChoice, s as useSubmit, x as MostraError } from "./hooks-C0SVZDl4.js";
3
+ import { a as createServerReference, o as setServerCallback, t as mountArtifact } from "./mount-BCj41qky.js";
4
4
  import { isFinalRunStatus } from "@mostra/protocol";
5
5
  import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
6
  //#region src/server-hooks.ts
@@ -120,7 +120,7 @@ function useAction(fn, options) {
120
120
  }, [server, runId]);
121
121
  return useMemo(() => {
122
122
  const status = view?.status ?? "idle";
123
- const error = view?.error && (view.status === "failed" || view.status === "cancelled") ? {
123
+ const error = view?.error && (view.status === "failed" || view.status === "cancelled" || view.status === "unknown") ? {
124
124
  code: view.error.code ?? "MOSTRA_ACTION_THREW",
125
125
  message: view.error.message
126
126
  } : view?.status === "cancelled" ? {
@@ -170,7 +170,8 @@ function useLive(key, options) {
170
170
  ...view?.error ? { error: new MostraError(view.error.code ?? "MOSTRA_LIVE_SOURCE_FAILED", view.error.message) } : {},
171
171
  refresh,
172
172
  ...view?.revision !== void 0 ? { revision: view.revision } : {},
173
- ...view?.at !== void 0 ? { at: view.at } : {}
173
+ ...view?.at !== void 0 ? { at: view.at } : {},
174
+ ...view?.ownerOffline ? { ownerOffline: true } : {}
174
175
  };
175
176
  }, [
176
177
  view,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/server-hooks.ts","../src/index.ts"],"sourcesContent":["\"use client\";\n\n/**\n * Server functions and live data in the page (INTERFACES §2.3, D54, D56): `useAction` turns calls\n * of a `\"use server\"` function into durable action runs, and `useLive` reads a live source. Both\n * share the page's runtime, its view and its event stream, so a run started in one tab or before a\n * reload is followed the same way, and every component showing one source shares one value.\n */\nimport { isFinalRunStatus, type RunProgress, type RunStatus } from \"@mostra/protocol\";\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { useStore } from \"./hooks.ts\";\nimport { MostraError } from \"./runtime/errors.ts\";\nimport { serverFunctionId } from \"./runtime/server-client.ts\";\n\n// ── useAction ─────────────────────────────────────────────────────────────────────────────\n\n/** What `useAction` shows of its run (INTERFACES §2.3). */\nexport interface ActionHandle<A extends unknown[], R> {\n /**\n * Runs the action: a durable run (D24) whose result this resolves with, or whose failure it\n * rejects with as a `MostraError`. While this hook's run is in flight, another call joins it; with\n * a `key`, every call anywhere joins the one run of that key, so it happens at most once.\n */\n run(...args: A): Promise<R>;\n /**\n * `idle` before any run, then the run's state. `waiting` is reserved for a run waiting for its\n * owner's instance (a hosted artifact, WP-28).\n */\n readonly status: \"idle\" | RunStatus;\n /** Whether a run is starting or in flight. */\n readonly isPending: boolean;\n /** The result, once the run succeeded. */\n readonly data?: R;\n /** Why the run failed, was cancelled or couldn't start. */\n readonly error?: { readonly code: string; readonly message: string };\n /** The run's latest progress (`progress()` in the action). */\n readonly progress?: RunProgress;\n /** The run's log lines (`log()` and the console in the action), capped at 1 MB. */\n readonly log: readonly string[];\n /** For an action that returns an async iterable: the items it yielded so far. */\n readonly partial: readonly (R extends AsyncIterable<infer T> ? T : unknown)[];\n /** Cancels the run: the action's `abortSignal` fires (AC-04). */\n cancel(): void;\n /** The run's `run_` ID, once it has one. */\n readonly runId?: string;\n}\n\nconst NO_LOG: readonly string[] = [];\n\n/** What `useAction` knows of one function and key. */\ninterface IdentityState {\n readonly runId?: string | undefined;\n readonly starting: boolean;\n readonly startError?: { code: string; message: string } | undefined;\n}\n\nconst IDLE: IdentityState = { starting: false };\nconst NO_STATES: ReadonlyMap<string, IdentityState> = new Map();\n\n/**\n * Runs a `\"use server\"` function as durable action runs (D24, D54): each call is recorded before\n * it runs, streams progress, log lines and partial results, survives the tab closing, and is\n * found again after a reload. Without a `key`, a call while this hook's run is in flight joins it,\n * so a double click runs once; with a `key`, the run of that key happens at most once across\n * clicks, tabs, reloads and devices, and a page that opens later shows it.\n *\n * ```tsx\n * const send = useAction(sendReply, { key: `send.${message.id}` });\n * <button disabled={send.isPending || send.status === \"succeeded\"} onClick={() => send.run(message.id, reply)}>\n * {send.status === \"succeeded\" ? \"Sent\" : (send.progress?.message ?? \"Send\")}\n * </button>\n * ```\n */\nexport function useAction<A extends unknown[], R>(\n fn: (...args: A) => Promise<R>,\n options?: { readonly key?: string },\n): ActionHandle<A, Awaited<R>> {\n const store = useStore();\n const server = store.server;\n const fnId = serverFunctionId(fn);\n const key = options?.key;\n // Everything the hook knows belongs to one function and key: a component that changes either\n // shows the new one's run, never the old one's, and a late answer for the old one lands under\n // the old identity, where the hook no longer looks.\n const identity = `${fnId ?? \"\"}\\u0000${key ?? \"\"}`;\n const [states, setStates] = useState<ReadonlyMap<string, IdentityState>>(NO_STATES);\n const current = states.get(identity) ?? IDLE;\n const { runId, starting, startError } = current;\n const update = useCallback((of: string, patch: Partial<IdentityState>): void => {\n setStates((previous) => {\n const next = new Map(previous);\n next.set(of, { ...(previous.get(of) ?? IDLE), ...patch });\n return next;\n });\n }, []);\n const inFlight = useRef(new Map<string, Promise<unknown>>());\n useSyncExternalStore(server.subscribe, server.version, server.version);\n\n // A keyed run started earlier, in another tab or before a reload, is shown again (AC-02).\n useEffect(() => {\n if (key === undefined || fnId === undefined || store.mode !== \"live\") return;\n let active = true;\n server.attach({ keyed: [{ fnId, key }] }).then(\n (runs) => {\n const [found] = runs;\n if (active && found) update(identity, { runId: found.runId });\n },\n () => {},\n );\n return () => {\n active = false;\n };\n }, [server, store.mode, fnId, key, identity, update]);\n\n const view = runId === undefined ? undefined : server.run(runId);\n\n const run = useCallback(\n (...args: A): Promise<Awaited<R>> => {\n if (fnId === undefined) {\n return Promise.reject(\n new TypeError(\n 'useAction needs a server function: import it from a module that starts with \"use server\".',\n ),\n );\n }\n // One run in flight per hook instance and function and key (D54): a second click joins it.\n const joined = inFlight.current.get(identity);\n if (joined) return joined as Promise<Awaited<R>>;\n update(identity, { starting: true, startError: undefined });\n const started = (async () => {\n let state: Awaited<ReturnType<typeof server.startRun>>;\n try {\n state = await server.startRun(fnId, args, key);\n } catch (error) {\n // The run never started (a refused link, a parked worker, the network): say why.\n update(identity, {\n starting: false,\n startError:\n error instanceof MostraError\n ? { code: error.code, message: error.message }\n : { code: \"MOSTRA_ACTION_THREW\", message: (error as Error).message },\n });\n throw error;\n }\n update(identity, { starting: false, runId: state.runId });\n return server.settled(state.runId);\n })();\n inFlight.current.set(identity, started);\n const settle = (): void => {\n if (inFlight.current.get(identity) === started) inFlight.current.delete(identity);\n };\n started.then(settle, settle);\n return started as Promise<Awaited<R>>;\n },\n [server, fnId, key, identity, update],\n );\n\n const cancel = useCallback(() => {\n if (runId === undefined) return;\n const current = server.run(runId);\n if (current && !isFinalRunStatus(current.status)) void server.cancel(runId).catch(() => {});\n }, [server, runId]);\n\n return useMemo(() => {\n const status: ActionHandle<A, Awaited<R>>[\"status\"] = view?.status ?? \"idle\";\n const error =\n view?.error && (view.status === \"failed\" || view.status === \"cancelled\")\n ? { code: view.error.code ?? \"MOSTRA_ACTION_THREW\", message: view.error.message }\n : view?.status === \"cancelled\"\n ? { code: \"MOSTRA_ACTION_CANCELLED\", message: \"The run was cancelled.\" }\n : startError;\n return {\n run,\n cancel,\n status,\n isPending: starting || status === \"queued\" || status === \"running\" || status === \"waiting\",\n ...(view?.status === \"succeeded\" && view.data !== undefined\n ? { data: view.data as Awaited<R> }\n : {}),\n ...(error ? { error } : {}),\n ...(view?.progress ? { progress: view.progress } : {}),\n log: view?.log ?? NO_LOG,\n partial: (view?.partial ?? []) as ActionHandle<A, Awaited<R>>[\"partial\"],\n ...(runId !== undefined ? { runId } : {}),\n };\n }, [run, cancel, view, starting, startError, runId]);\n}\n\n// ── useLive ───────────────────────────────────────────────────────────────────────────────\n\n/**\n * The live sources of the artifact, by key, with their value types. A generated declaration\n * (`mostra-env.d.ts`, written by `mostra new`) fills it from `live.ts`:\n *\n * ```ts\n * declare module \"@mostra/react\" {\n * interface LiveSources extends LiveValuesOf<typeof import(\"./live\")> {}\n * }\n * ```\n */\n// biome-ignore lint/suspicious/noEmptyInterface: augmented by each artifact's declaration.\nexport interface LiveSources {}\n\n/** The value types of a `live.ts` module's sources, by export name (D56). */\nexport type LiveValuesOf<M> = {\n [K in keyof M as M[K] extends { readonly \"~mostra.live\": unknown } ? K : never]: M[K] extends {\n readonly __value?: infer T;\n }\n ? T\n : never;\n};\n\n/** A live source's key: one of `LiveSources`, or any string before the declaration exists. */\nexport type LiveKey = [keyof LiveSources] extends [never] ? string : keyof LiveSources & string;\n\n/** A live source's value type. */\nexport type LiveValue<K extends string> = K extends keyof LiveSources ? LiveSources[K] : unknown;\n\n/** What `useLive` shows (INTERFACES §2.3). */\nexport interface LiveResult<T> {\n /** The latest value; in append mode, the values kept, oldest first. */\n readonly data: T | undefined;\n /** Whether no value has arrived yet. */\n readonly isLoading: boolean;\n /** The producer's last failure; the last good value stays in `data` (FAILURE_MODEL §6). */\n readonly error?: Error;\n /** Asks the producer to load again now. */\n refresh(): void;\n /** The value's revision, which only grows. */\n readonly revision?: string;\n /** When the value was produced. */\n readonly at?: string;\n}\n\n/** How long append mode keeps values without a `window`. */\nconst DEFAULT_WINDOW = 1024;\n\n/**\n * Reads a live source of `live.ts`, or one an agent or host pushes to (D56): the latest value, or\n * in append mode the recent values for a high-rate chart. The value is shared by every component\n * that shows it and updates without a reload; nothing of it is a durable event (D63).\n *\n * ```tsx\n * const { data, isLoading, error } = useLive(\"inbox\");\n * const { data: points } = useLive(\"cpu\", { mode: \"append\", window: 600 });\n * ```\n */\nexport function useLive<K extends LiveKey>(\n key: K,\n options: { readonly mode: \"append\"; readonly window?: number },\n): LiveResult<LiveValue<K>[]>;\n/** Reads a live source's latest value (D56). See the first signature. */\nexport function useLive<K extends LiveKey>(\n key: K,\n options?: { readonly mode?: \"latest\"; readonly window?: number },\n): LiveResult<LiveValue<K>>;\nexport function useLive<K extends LiveKey>(\n key: K,\n options?: { readonly mode?: \"latest\" | \"append\"; readonly window?: number },\n): LiveResult<unknown> {\n const store = useStore();\n const server = store.server;\n const append = options?.mode === \"append\";\n const window = append ? (options?.window ?? DEFAULT_WINDOW) : undefined;\n useSyncExternalStore(server.subscribe, server.version, server.version);\n useEffect(() => server.watchLive(key, window), [server, key, window]);\n const view = server.liveView(key);\n const refresh = useCallback(() => server.refreshLive(key), [server, key]);\n return useMemo(() => {\n const data = append\n ? view?.ring.length\n ? view.ring.slice(-(window ?? 0))\n : undefined\n : view?.data;\n return {\n data,\n isLoading: data === undefined && (view?.loading ?? true),\n ...(view?.error\n ? {\n error: new MostraError(\n view.error.code ?? \"MOSTRA_LIVE_SOURCE_FAILED\",\n view.error.message,\n ),\n }\n : {}),\n refresh,\n ...(view?.revision !== undefined ? { revision: view.revision } : {}),\n ...(view?.at !== undefined ? { at: view.at } : {}),\n };\n }, [view, append, window, refresh]);\n}\n","\"use client\";\n\n/**\n * `@mostra/react`: the client runtime artifact authors import (INTERFACES §2.3). Fields that behave\n * like `useState` with a stable ID and persist as the viewer works, the artifact channel's\n * submit, the shell's trusted Submit label, signals, review-set choices, the viewer and the\n * artifact, a Claude-compatible `window.storage`, and the manifest helper. `@mostra/react/form`\n * adapts react-hook-form; `@mostra/react/router` mounts `pages/` artifacts.\n *\n * ```tsx\n * import { defineArtifact, useField, useSubmitControl } from \"@mostra/react\";\n *\n * export const artifact = defineArtifact({ title: \"Sidebar options\", family: \"review\" });\n *\n * export default function Page() {\n * const [layout, setLayout] = useField(\"layout\", \"left\", { label: \"Layout\", required: true });\n * useSubmitControl({ label: \"Send my choice\" });\n * return <select value={layout} onChange={(e) => setLayout(e.target.value)}>…</select>;\n * }\n * ```\n *\n * @packageDocumentation\n */\nimport type { ArtifactManifest } from \"@mostra/protocol\";\n\nexport type { ArtifactManifest, SubmissionSummary, SubmitBlocker } from \"@mostra/protocol\";\nexport {\n type ArtifactMode,\n type ChoiceCandidate,\n type FieldMeta,\n type FieldOptions,\n type StandardSchema,\n type SubmitHandle,\n useArtifact,\n useChoice,\n useField,\n useSignal,\n useSubmit,\n useSubmitControl,\n useViewer,\n} from \"./hooks.ts\";\nexport { mountArtifact } from \"./mount.ts\";\nexport { type DiagnosticLike, MostraError } from \"./runtime/errors.ts\";\nexport type { SubmitState } from \"./runtime/store.ts\";\nexport {\n type ActionHandle,\n type LiveKey,\n type LiveResult,\n type LiveSources,\n type LiveValue,\n type LiveValuesOf,\n useAction,\n useLive,\n} from \"./server-hooks.ts\";\nexport {\n type CallServer,\n createServerReference,\n type ServerReference,\n setServerCallback,\n} from \"./server-reference.ts\";\nexport { connectShell, openLink, reportReady, type ShellConnection } from \"./shell-bridge.ts\";\nexport type { ClaudeCompatibleStorage, StorageEntry } from \"./storage.ts\";\n\n/**\n * Declares an artifact's manifest (INTERFACES §2.2, D51). Mostra reads the object statically\n * without running the page, so write every value as a literal: strings, numbers, booleans, arrays\n * and objects. At run time it returns its argument unchanged.\n *\n * ```ts\n * export const artifact = defineArtifact({ title: \"Q3 plan\", family: \"proposal\" });\n * ```\n */\nexport function defineArtifact<const M extends ArtifactManifest>(manifest: M): M {\n return manifest;\n}\n"],"mappings":";;;;;;;;;;;;AA+CA,MAAM,SAA4B,CAAC;AASnC,MAAM,OAAsB,EAAE,UAAU,MAAM;AAC9C,MAAM,4BAAgD,IAAI,IAAI;;;;;;;;;;;;;;;AAgB9D,SAAgB,UACd,IACA,SAC6B;CAC7B,MAAM,QAAQ,SAAS;CACvB,MAAM,SAAS,MAAM;CACrB,MAAM,OAAO,iBAAiB,EAAE;CAChC,MAAM,MAAM,SAAS;CAIrB,MAAM,WAAW,GAAG,QAAQ,GAAG,QAAQ,OAAO;CAC9C,MAAM,CAAC,QAAQ,aAAa,SAA6C,SAAS;CAElF,MAAM,EAAE,OAAO,UAAU,eADT,OAAO,IAAI,QAAQ,KAAK;CAExC,MAAM,SAAS,aAAa,IAAY,UAAwC;EAC9E,WAAW,aAAa;GACtB,MAAM,OAAO,IAAI,IAAI,QAAQ;GAC7B,KAAK,IAAI,IAAI;IAAE,GAAI,SAAS,IAAI,EAAE,KAAK;IAAO,GAAG;GAAM,CAAC;GACxD,OAAO;EACT,CAAC;CACH,GAAG,CAAC,CAAC;CACL,MAAM,WAAW,uBAAO,IAAI,IAA8B,CAAC;CAC3D,qBAAqB,OAAO,WAAW,OAAO,SAAS,OAAO,OAAO;CAGrE,gBAAgB;EACd,IAAI,QAAQ,KAAA,KAAa,SAAS,KAAA,KAAa,MAAM,SAAS,QAAQ;EACtE,IAAI,SAAS;EACb,OAAO,OAAO,EAAE,OAAO,CAAC;GAAE;GAAM;EAAI,CAAC,EAAE,CAAC,CAAC,CAAC,MACvC,SAAS;GACR,MAAM,CAAC,SAAS;GAChB,IAAI,UAAU,OAAO,OAAO,UAAU,EAAE,OAAO,MAAM,MAAM,CAAC;EAC9D,SACM,CAAC,CACT;EACA,aAAa;GACX,SAAS;EACX;CACF,GAAG;EAAC;EAAQ,MAAM;EAAM;EAAM;EAAK;EAAU;CA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,GAAI,MAAM,QACN,EACE,OAAO,IAAI,YACT,KAAK,MAAM,QAAQ,6BACnB,KAAK,MAAM,OACb,EACF,IACA,CAAC;GACL;GACA,GAAI,MAAM,aAAa,KAAA,IAAY,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;GAClE,GAAI,MAAM,OAAO,KAAA,IAAY,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;EAClD;CACF,GAAG;EAAC;EAAM;EAAQ;EAAQ;CAAO,CAAC;AACpC;;;;;;;;;;;;AC1NA,SAAgB,eAAiD,UAAgB;CAC/E,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/server-hooks.ts","../src/index.ts"],"sourcesContent":["\"use client\";\n\n/**\n * Server functions and live data in the page (INTERFACES §2.3, D54, D56): `useAction` turns calls\n * of a `\"use server\"` function into durable action runs, and `useLive` reads a live source. Both\n * share the page's runtime, its view and its event stream, so a run started in one tab or before a\n * reload is followed the same way, and every component showing one source shares one value.\n */\nimport {\n isFinalRunStatus,\n type RunProgress,\n type RunStatus,\n type TallyValue,\n} from \"@mostra/protocol\";\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { useStore } from \"./hooks.ts\";\nimport { MostraError } from \"./runtime/errors.ts\";\nimport { serverFunctionId } from \"./runtime/server-client.ts\";\n\n// ── useAction ─────────────────────────────────────────────────────────────────────────────\n\n/** What `useAction` shows of its run (INTERFACES §2.3). */\nexport interface ActionHandle<A extends unknown[], R> {\n /**\n * Runs the action: a durable run (D24) whose result this resolves with, or whose failure it\n * rejects with as a `MostraError`. While this hook's run is in flight, another call joins it; with\n * a `key`, every call anywhere joins the one run of that key, so it happens at most once.\n */\n run(...args: A): Promise<R>;\n /**\n * `idle` before any run, then the run's state. `waiting` is reserved for a run waiting for its\n * owner's instance (a hosted artifact, WP-28).\n */\n readonly status: \"idle\" | RunStatus;\n /** Whether a run is starting or in flight. */\n readonly isPending: boolean;\n /** The result, once the run succeeded. */\n readonly data?: R;\n /** Why the run failed, was cancelled or couldn't start. */\n readonly error?: { readonly code: string; readonly message: string };\n /** The run's latest progress (`progress()` in the action). */\n readonly progress?: RunProgress;\n /** The run's log lines (`log()` and the console in the action), capped at 1 MB. */\n readonly log: readonly string[];\n /** For an action that returns an async iterable: the items it yielded so far. */\n readonly partial: readonly (R extends AsyncIterable<infer T> ? T : unknown)[];\n /** Cancels the run: the action's `abortSignal` fires (AC-04). */\n cancel(): void;\n /** The run's `run_` ID, once it has one. */\n readonly runId?: string;\n}\n\nconst NO_LOG: readonly string[] = [];\n\n/** What `useAction` knows of one function and key. */\ninterface IdentityState {\n readonly runId?: string | undefined;\n readonly starting: boolean;\n readonly startError?: { code: string; message: string } | undefined;\n}\n\nconst IDLE: IdentityState = { starting: false };\nconst NO_STATES: ReadonlyMap<string, IdentityState> = new Map();\n\n/**\n * Runs a `\"use server\"` function as durable action runs (D24, D54): each call is recorded before\n * it runs, streams progress, log lines and partial results, survives the tab closing, and is\n * found again after a reload. Without a `key`, a call while this hook's run is in flight joins it,\n * so a double click runs once; with a `key`, the run of that key happens at most once across\n * clicks, tabs, reloads and devices, and a page that opens later shows it.\n *\n * ```tsx\n * const send = useAction(sendReply, { key: `send.${message.id}` });\n * <button disabled={send.isPending || send.status === \"succeeded\"} onClick={() => send.run(message.id, reply)}>\n * {send.status === \"succeeded\" ? \"Sent\" : (send.progress?.message ?? \"Send\")}\n * </button>\n * ```\n */\nexport function useAction<A extends unknown[], R>(\n fn: (...args: A) => Promise<R>,\n options?: { readonly key?: string },\n): ActionHandle<A, Awaited<R>> {\n const store = useStore();\n const server = store.server;\n const fnId = serverFunctionId(fn);\n const key = options?.key;\n // Everything the hook knows belongs to one function and key: a component that changes either\n // shows the new one's run, never the old one's, and a late answer for the old one lands under\n // the old identity, where the hook no longer looks.\n const identity = `${fnId ?? \"\"}\\u0000${key ?? \"\"}`;\n const [states, setStates] = useState<ReadonlyMap<string, IdentityState>>(NO_STATES);\n const current = states.get(identity) ?? IDLE;\n const { runId, starting, startError } = current;\n const update = useCallback((of: string, patch: Partial<IdentityState>): void => {\n setStates((previous) => {\n const next = new Map(previous);\n next.set(of, { ...(previous.get(of) ?? IDLE), ...patch });\n return next;\n });\n }, []);\n const inFlight = useRef(new Map<string, Promise<unknown>>());\n useSyncExternalStore(server.subscribe, server.version, server.version);\n\n // A keyed run started earlier, in another tab or before a reload, is shown again (AC-02).\n useEffect(() => {\n if (key === undefined || fnId === undefined || store.mode !== \"live\") return;\n let active = true;\n server.attach({ keyed: [{ fnId, key }] }).then(\n (runs) => {\n const [found] = runs;\n if (active && found) update(identity, { runId: found.runId });\n },\n () => {},\n );\n return () => {\n active = false;\n };\n }, [server, store.mode, fnId, key, identity, update]);\n\n const view = runId === undefined ? undefined : server.run(runId);\n\n const run = useCallback(\n (...args: A): Promise<Awaited<R>> => {\n if (fnId === undefined) {\n return Promise.reject(\n new TypeError(\n 'useAction needs a server function: import it from a module that starts with \"use server\".',\n ),\n );\n }\n // One run in flight per hook instance and function and key (D54): a second click joins it.\n const joined = inFlight.current.get(identity);\n if (joined) return joined as Promise<Awaited<R>>;\n update(identity, { starting: true, startError: undefined });\n const started = (async () => {\n let state: Awaited<ReturnType<typeof server.startRun>>;\n try {\n state = await server.startRun(fnId, args, key);\n } catch (error) {\n // The run never started (a refused link, a parked worker, the network): say why.\n update(identity, {\n starting: false,\n startError:\n error instanceof MostraError\n ? { code: error.code, message: error.message }\n : { code: \"MOSTRA_ACTION_THREW\", message: (error as Error).message },\n });\n throw error;\n }\n update(identity, { starting: false, runId: state.runId });\n return server.settled(state.runId);\n })();\n inFlight.current.set(identity, started);\n const settle = (): void => {\n if (inFlight.current.get(identity) === started) inFlight.current.delete(identity);\n };\n started.then(settle, settle);\n return started as Promise<Awaited<R>>;\n },\n [server, fnId, key, identity, update],\n );\n\n const cancel = useCallback(() => {\n if (runId === undefined) return;\n const current = server.run(runId);\n if (current && !isFinalRunStatus(current.status)) void server.cancel(runId).catch(() => {});\n }, [server, runId]);\n\n return useMemo(() => {\n const status: ActionHandle<A, Awaited<R>>[\"status\"] = view?.status ?? \"idle\";\n const error =\n view?.error &&\n (view.status === \"failed\" || view.status === \"cancelled\" || view.status === \"unknown\")\n ? { code: view.error.code ?? \"MOSTRA_ACTION_THREW\", message: view.error.message }\n : view?.status === \"cancelled\"\n ? { code: \"MOSTRA_ACTION_CANCELLED\", message: \"The run was cancelled.\" }\n : startError;\n return {\n run,\n cancel,\n status,\n isPending: starting || status === \"queued\" || status === \"running\" || status === \"waiting\",\n ...(view?.status === \"succeeded\" && view.data !== undefined\n ? { data: view.data as Awaited<R> }\n : {}),\n ...(error ? { error } : {}),\n ...(view?.progress ? { progress: view.progress } : {}),\n log: view?.log ?? NO_LOG,\n partial: (view?.partial ?? []) as ActionHandle<A, Awaited<R>>[\"partial\"],\n ...(runId !== undefined ? { runId } : {}),\n };\n }, [run, cancel, view, starting, startError, runId]);\n}\n\n// ── useLive ───────────────────────────────────────────────────────────────────────────────\n\n/**\n * The live sources of the artifact, by key, with their value types. A generated declaration\n * (`mostra-env.d.ts`, written by `mostra new`) fills it from `live.ts`:\n *\n * ```ts\n * declare module \"@mostra/react\" {\n * interface LiveSources extends LiveValuesOf<typeof import(\"./live\")> {}\n * }\n * ```\n */\n// biome-ignore lint/suspicious/noEmptyInterface: augmented by each artifact's declaration.\nexport interface LiveSources {}\n\n/** The value types of a `live.ts` module's sources, by export name (D56). */\nexport type LiveValuesOf<M> = {\n [K in keyof M as M[K] extends { readonly \"~mostra.live\": unknown } ? K : never]: M[K] extends {\n readonly __value?: infer T;\n }\n ? T\n : never;\n};\n\n/**\n * A tally's key, `$tally/<field>` (D165 item 12): the counts of a fixed-choice field the manifest's\n * `tally` names, which Mostra keeps and pushes itself.\n */\nexport type TallyKey = `$tally/${string}`;\n\n/**\n * A live source's key: one of `LiveSources`, or any string before the declaration exists, or a\n * tally's key.\n */\nexport type LiveKey =\n | ([keyof LiveSources] extends [never] ? string : keyof LiveSources & string)\n | TallyKey;\n\n/** A live source's value type; a tally's is `TallyValue`. */\nexport type LiveValue<K extends string> = K extends TallyKey\n ? TallyValue\n : K extends keyof LiveSources\n ? LiveSources[K]\n : unknown;\n\n/** What `useLive` shows (INTERFACES §2.3). */\nexport interface LiveResult<T> {\n /** The latest value; in append mode, the values kept, oldest first. */\n readonly data: T | undefined;\n /** Whether no value has arrived yet. */\n readonly isLoading: boolean;\n /** The producer's last failure; the last good value stays in `data` (FAILURE_MODEL §6). */\n readonly error?: Error;\n /** Asks the producer to load again now. */\n refresh(): void;\n /** The value's revision, which only grows. */\n readonly revision?: string;\n /** When the value was produced. */\n readonly at?: string;\n /**\n * On a hosted page, `true` while the page's owner is offline, so its producer can't refresh the\n * value: `data` is the last value, from `at` (D165 item 4).\n */\n readonly ownerOffline?: boolean;\n}\n\n/** How long append mode keeps values without a `window`. */\nconst DEFAULT_WINDOW = 1024;\n\n/**\n * Reads a live source of `live.ts`, or one an agent or host pushes to (D56): the latest value, or\n * in append mode the recent values for a high-rate chart. The value is shared by every component\n * that shows it and updates without a reload; nothing of it is a durable event (D63).\n *\n * ```tsx\n * const { data, isLoading, error } = useLive(\"inbox\");\n * const { data: points } = useLive(\"cpu\", { mode: \"append\", window: 600 });\n * ```\n */\nexport function useLive<K extends LiveKey>(\n key: K,\n options: { readonly mode: \"append\"; readonly window?: number },\n): LiveResult<LiveValue<K>[]>;\n/** Reads a live source's latest value (D56). See the first signature. */\nexport function useLive<K extends LiveKey>(\n key: K,\n options?: { readonly mode?: \"latest\"; readonly window?: number },\n): LiveResult<LiveValue<K>>;\nexport function useLive<K extends LiveKey>(\n key: K,\n options?: { readonly mode?: \"latest\" | \"append\"; readonly window?: number },\n): LiveResult<unknown> {\n const store = useStore();\n const server = store.server;\n const append = options?.mode === \"append\";\n const window = append ? (options?.window ?? DEFAULT_WINDOW) : undefined;\n useSyncExternalStore(server.subscribe, server.version, server.version);\n useEffect(() => server.watchLive(key, window), [server, key, window]);\n const view = server.liveView(key);\n const refresh = useCallback(() => server.refreshLive(key), [server, key]);\n return useMemo(() => {\n const data = append\n ? view?.ring.length\n ? view.ring.slice(-(window ?? 0))\n : undefined\n : view?.data;\n return {\n data,\n isLoading: data === undefined && (view?.loading ?? true),\n ...(view?.error\n ? {\n error: new MostraError(\n view.error.code ?? \"MOSTRA_LIVE_SOURCE_FAILED\",\n view.error.message,\n ),\n }\n : {}),\n refresh,\n ...(view?.revision !== undefined ? { revision: view.revision } : {}),\n ...(view?.at !== undefined ? { at: view.at } : {}),\n ...(view?.ownerOffline ? { ownerOffline: true } : {}),\n };\n }, [view, append, window, refresh]);\n}\n","\"use client\";\n\n/**\n * `@mostra/react`: the client runtime artifact authors import (INTERFACES §2.3). Fields that behave\n * like `useState` with a stable ID and persist as the viewer works, the artifact channel's\n * submit, the shell's trusted Submit label, signals, review-set choices, the viewer and the\n * artifact, a Claude-compatible `window.storage`, and the manifest helper. `@mostra/react/form`\n * adapts react-hook-form; `@mostra/react/router` mounts `pages/` artifacts.\n *\n * ```tsx\n * import { defineArtifact, useField, useSubmitControl } from \"@mostra/react\";\n *\n * export const artifact = defineArtifact({ title: \"Sidebar options\", family: \"review\" });\n *\n * export default function Page() {\n * const [layout, setLayout] = useField(\"layout\", \"left\", { label: \"Layout\", required: true });\n * useSubmitControl({ label: \"Send my choice\" });\n * return <select value={layout} onChange={(e) => setLayout(e.target.value)}>…</select>;\n * }\n * ```\n *\n * @packageDocumentation\n */\nimport type { ArtifactManifest } from \"@mostra/protocol\";\n\nexport type {\n ArtifactManifest,\n SubmissionSummary,\n SubmitBlocker,\n TallyValue,\n} from \"@mostra/protocol\";\nexport {\n type ArtifactMode,\n type ChoiceCandidate,\n type FieldMeta,\n type FieldOptions,\n type StandardSchema,\n type SubmitHandle,\n useArtifact,\n useChoice,\n useField,\n useSignal,\n useSubmit,\n useSubmitControl,\n useViewer,\n} from \"./hooks.ts\";\nexport { mountArtifact } from \"./mount.ts\";\nexport { type DiagnosticLike, MostraError } from \"./runtime/errors.ts\";\nexport type { SubmitState } from \"./runtime/store.ts\";\nexport {\n type ActionHandle,\n type LiveKey,\n type LiveResult,\n type LiveSources,\n type LiveValue,\n type LiveValuesOf,\n type TallyKey,\n useAction,\n useLive,\n} from \"./server-hooks.ts\";\nexport {\n type CallServer,\n createServerReference,\n type ServerReference,\n setServerCallback,\n} from \"./server-reference.ts\";\nexport { connectShell, openLink, reportReady, type ShellConnection } from \"./shell-bridge.ts\";\nexport type { ClaudeCompatibleStorage, StorageEntry } from \"./storage.ts\";\n\n/**\n * Declares an artifact's manifest (INTERFACES §2.2, D51). Mostra reads the object statically\n * without running the page, so write every value as a literal: strings, numbers, booleans, arrays\n * and objects. At run time it returns its argument unchanged.\n *\n * ```ts\n * export const artifact = defineArtifact({ title: \"Q3 plan\", family: \"proposal\" });\n * ```\n */\nexport function defineArtifact<const M extends ArtifactManifest>(manifest: M): M {\n return manifest;\n}\n"],"mappings":";;;;;;;;;;;;AAoDA,MAAM,SAA4B,CAAC;AASnC,MAAM,OAAsB,EAAE,UAAU,MAAM;AAC9C,MAAM,4BAAgD,IAAI,IAAI;;;;;;;;;;;;;;;AAgB9D,SAAgB,UACd,IACA,SAC6B;CAC7B,MAAM,QAAQ,SAAS;CACvB,MAAM,SAAS,MAAM;CACrB,MAAM,OAAO,iBAAiB,EAAE;CAChC,MAAM,MAAM,SAAS;CAIrB,MAAM,WAAW,GAAG,QAAQ,GAAG,QAAQ,OAAO;CAC9C,MAAM,CAAC,QAAQ,aAAa,SAA6C,SAAS;CAElF,MAAM,EAAE,OAAO,UAAU,eADT,OAAO,IAAI,QAAQ,KAAK;CAExC,MAAM,SAAS,aAAa,IAAY,UAAwC;EAC9E,WAAW,aAAa;GACtB,MAAM,OAAO,IAAI,IAAI,QAAQ;GAC7B,KAAK,IAAI,IAAI;IAAE,GAAI,SAAS,IAAI,EAAE,KAAK;IAAO,GAAG;GAAM,CAAC;GACxD,OAAO;EACT,CAAC;CACH,GAAG,CAAC,CAAC;CACL,MAAM,W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AM,SAAS,SAAS,SAAS;CACjC,MAAM,SAAS,SAAU,SAAS,UAAU,iBAAkB,KAAA;CAC9D,qBAAqB,OAAO,WAAW,OAAO,SAAS,OAAO,OAAO;CACrE,gBAAgB,OAAO,UAAU,KAAK,MAAM,GAAG;EAAC;EAAQ;EAAK;CAAM,CAAC;CACpE,MAAM,OAAO,OAAO,SAAS,GAAG;CAChC,MAAM,UAAU,kBAAkB,OAAO,YAAY,GAAG,GAAG,CAAC,QAAQ,GAAG,CAAC;CACxE,OAAO,cAAc;EACnB,MAAM,OAAO,SACT,MAAM,KAAK,SACT,KAAK,KAAK,MAAM,EAAE,UAAU,EAAE,IAC9B,KAAA,IACF,MAAM;EACV,OAAO;GACL;GACA,WAAW,SAAS,KAAA,MAAc,MAAM,WAAW;GACnD,GAAI,MAAM,QACN,EACE,OAAO,IAAI,YACT,KAAK,MAAM,QAAQ,6BACnB,KAAK,MAAM,OACb,EACF,IACA,CAAC;GACL;GACA,GAAI,MAAM,aAAa,KAAA,IAAY,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;GAClE,GAAI,MAAM,OAAO,KAAA,IAAY,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;GAChD,GAAI,MAAM,eAAe,EAAE,cAAc,KAAK,IAAI,CAAC;EACrD;CACF,GAAG;EAAC;EAAM;EAAQ;EAAQ;CAAO,CAAC;AACpC;;;;;;;;;;;;AC/OA,SAAgB,eAAiD,UAAgB;CAC/E,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { b as MemoryJournal, d as connectShell, f as listenShell, g as fieldKey, h as Store, m as reportReady, t as RuntimeProvider, u as builtVersion, v as HttpTransport, x as MostraError, y as IndexedDbJournal } from "./hooks-BHhOYg3U.js";
1
+ import { b as MemoryJournal, d as connectShell, f as listenShell, g as fieldKey, h as Store, m as reportReady, t as RuntimeProvider, u as builtVersion, v as HttpTransport, x as MostraError, y as IndexedDbJournal } from "./hooks-C0SVZDl4.js";
2
2
  import { BRIDGE_FIELDS_MAX, BRIDGE_TEXT_MAX, VERIFY_PROBE, VERIFY_REPORT, isFieldId, mostraFieldFocus, mostraFields, mostraFlush, mostraPage, mostraVersionAvailable, readViewContext } from "@mostra/protocol";
3
3
  import { createElement } from "react";
4
4
  import { createRoot } from "react-dom/client";
@@ -565,4 +565,4 @@ async function mountArtifact(options) {
565
565
  //#endregion
566
566
  export { createServerReference as a, reportPage as i, prepareArtifact as n, setServerCallback as o, renderArtifact as r, mountArtifact as t };
567
567
 
568
- //# sourceMappingURL=mount-DSuEcMdp.js.map
568
+ //# sourceMappingURL=mount-BCj41qky.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mount-DSuEcMdp.js","names":[],"sources":["../src/runtime/bridge-limits.ts","../src/runtime/service-worker.ts","../src/runtime/verify-probe.ts","../src/runtime/boot.ts","../src/server-reference.ts","../src/storage.ts","../src/mount.ts"],"sourcesContent":["/**\n * What the page sends the shell, fitted to the bridge's limits (Claude review finding 11): a long\n * label or validation message is shortened, and a page with more fields than one message lists\n * sends those that matter first. A report the bridge refuses would leave the shell's rail and its\n * blocker list stale, and a refused flush answer would stop every trusted Submit.\n */\nimport { BRIDGE_FIELDS_MAX, BRIDGE_TEXT_MAX, type SubmitBlocker } from \"@mostra/protocol\";\n\n/** Text shortened to what the bridge carries. */\nexport function clip(text: string): string {\n return text.length <= BRIDGE_TEXT_MAX ? text : `${text.slice(0, BRIDGE_TEXT_MAX - 1)}…`;\n}\n\n/** At most {@link BRIDGE_FIELDS_MAX} items, those that matter first, in their order otherwise. */\nexport function firstThatMatter<T>(items: readonly T[], matters: (item: T) => boolean): T[] {\n if (items.length <= BRIDGE_FIELDS_MAX) return [...items];\n return [...items.filter(matters), ...items.filter((item) => !matters(item))].slice(\n 0,\n BRIDGE_FIELDS_MAX,\n );\n}\n\n/** Blockers as the bridge carries them: labels shortened, at most {@link BRIDGE_FIELDS_MAX}. */\nexport function blockersForShell(blockers: readonly SubmitBlocker[]): SubmitBlocker[] {\n return blockers\n .slice(0, BRIDGE_FIELDS_MAX)\n .map((blocker) =>\n blocker.label === undefined ? blocker : { ...blocker, label: clip(blocker.label) },\n );\n}\n","/**\n * The frame's service worker in worker mode (D70, D158 item 5): where the shell and the artifact\n * are two sites, Mostra's own service worker at `/` signs every request of the frame with its\n * session. An artifact's own worker can't run there: its script is fetched without the session\n * (a browser adds nothing to that request), and a page it controlled would send requests no\n * worker signs, so the page would lose its session. The client runtime refuses such a\n * registration with a diagnostic the page can see, rather than letting it fail obscurely or end\n * the session. On a tailnet, Funnel or local link (cookie mode) the artifact registers its own\n * workers as usual.\n */\nimport { MostraError } from \"./errors.ts\";\n\n/** Mostra's worker, which the gateway serves on every worker-mode artifact origin. */\nconst MOSTRA_WORKER = \"/_mostra/sw.js\";\n\n/** Whether this page runs under Mostra's worker-mode service worker. */\nexport function workerModeFrame(): boolean {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return false;\n const controller = navigator.serviceWorker.controller;\n if (!controller) return false;\n try {\n return new URL(controller.scriptURL).pathname === MOSTRA_WORKER;\n } catch {\n return false;\n }\n}\n\nlet guarded = false;\n\n/**\n * In a worker-mode frame, refuses an artifact's own service worker with\n * `MOSTRA_HYGIENE_FRAME_SESSION` (rejecting the registration's promise and saying so on the\n * console), instead of letting it fail without its session or end the page's. Installed once,\n * before artifact code runs; a no-op anywhere else.\n */\nexport function guardFrameServiceWorker(): void {\n if (guarded || !workerModeFrame()) return;\n guarded = true;\n const container = navigator.serviceWorker;\n const register = container.register.bind(container);\n const guard: typeof container.register = (scriptURL, options) => {\n const script = new URL(String(scriptURL), location.href);\n if (script.origin === location.origin && script.pathname === MOSTRA_WORKER) {\n return register(scriptURL, options);\n }\n const scope = new URL(options?.scope ?? \"./\", script);\n const error = new MostraError(\n \"MOSTRA_HYGIENE_FRAME_SESSION\",\n `This page opened through a link whose frame runs on Mostra's own service worker (a public Cloudflare link), so ${script.pathname} can't be registered here (scope ${scope.pathname}): it would run without the page's session. On a tailnet, Funnel or local link the page registers its own service workers.`,\n );\n console.error(`[MOSTRA_HYGIENE_FRAME_SESSION] ${error.message}`);\n return Promise.reject(error);\n };\n container.register = guard;\n}\n","\"use client\";\n\n/**\n * `verify`'s field probe (D138 item 3): in the `verify` target only, the page keeps a record of\n * every field it mounts (the hook, the scope and the type of the initial value) and how much\n * server work it waits on, and publishes both on `globalThis[VERIFY_PROBE]`, where the verify\n * runner reads them. Viewers' pages never install it.\n */\nimport { type ProbedField, VERIFY_PROBE } from \"@mostra/protocol\";\nimport type { Registration, Store } from \"./store.ts\";\n\n/** `typeof`, with arrays and `null` named as such. */\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\ninterface Entry {\n readonly first: { readonly hook: string; readonly scope: string; readonly initialType: string };\n mounts: number;\n readonly conflicts: Set<string>;\n}\n\n/** Records the store's field mounts on `globalThis[VERIFY_PROBE]`. */\nexport function installVerifyProbe(store: Store): void {\n const entries = new Map<string, Entry>();\n store.observeMounts((registration: Registration, mounted: boolean) => {\n const shape = {\n hook: registration.hook ?? \"useField\",\n scope: registration.scope,\n initialType: typeName(registration.initial),\n };\n let entry = entries.get(registration.id);\n if (!entry) {\n entry = { first: shape, mounts: 0, conflicts: new Set() };\n entries.set(registration.id, entry);\n }\n if (mounted) {\n entry.mounts += 1;\n if (shape.hook !== entry.first.hook)\n entry.conflicts.add(`${entry.first.hook} and ${shape.hook}`);\n if (shape.scope !== entry.first.scope)\n entry.conflicts.add(`scopes ${entry.first.scope} and ${shape.scope}`);\n if (shape.initialType !== entry.first.initialType)\n entry.conflicts.add(\n `initial values of types ${entry.first.initialType} and ${shape.initialType}`,\n );\n } else entry.mounts = Math.max(0, entry.mounts - 1);\n });\n const fields = (): ProbedField[] =>\n [...entries].map(([id, entry]) => ({\n id,\n scope: entry.first.scope as ProbedField[\"scope\"],\n hook: entry.first.hook,\n initialType: entry.first.initialType,\n mounts: entry.mounts,\n conflicts: [...entry.conflicts],\n }));\n // `pending`: the server work the page waits on (calls, runs, first live values), which the\n // runner's quiescence wait includes (Opus review finding 1).\n const pending = (): number => store.server.pending();\n Object.defineProperty(globalThis, VERIFY_PROBE, {\n value: { fields, pending },\n configurable: true,\n });\n}\n","/**\n * Starts the client runtime for the page (D111): reads the delivery target, connects to the shell\n * and the gateway in live mode, opens the journal, and wires the page's lifecycle (blur,\n * `visibilitychange`, `pagehide`) and the bridge (`mostra/fields`, `mostra/flush`,\n * `mostra/field.focus`, `mostra/version.available`) to the store.\n */\nimport {\n type DeliveryTarget,\n type FieldsParams,\n type FlushResult,\n mostraFieldFocus,\n mostraFields,\n mostraFlush,\n mostraVersionAvailable,\n readViewContext,\n type VersionAvailableParams,\n type ViewContext,\n} from \"@mostra/protocol\";\nimport { builtVersion, connectShell, listenShell, type ShellConnection } from \"../shell-bridge.ts\";\nimport { blockersForShell, clip, firstThatMatter } from \"./bridge-limits.ts\";\nimport { IndexedDbJournal, type Journal, MemoryJournal } from \"./journal.ts\";\nimport { guardFrameServiceWorker } from \"./service-worker.ts\";\nimport { Store } from \"./store.ts\";\nimport { HttpTransport } from \"./transport.ts\";\nimport { installVerifyProbe } from \"./verify-probe.ts\";\n\n// Before any artifact code runs: the generated entry imports the runtime first (D70).\nguardFrameServiceWorker();\n\n/** The page's runtime: its store, where it runs, and its shell connection. */\nexport interface Runtime {\n readonly store: Store;\n /** The delivery target the page was built or exported for (D111): it chooses the history. */\n readonly target: DeliveryTarget;\n /**\n * Where the page runs, as `useArtifact` reports it: the target, except that a live page opened\n * outside Mostra's shell has no server features and reports `static`.\n */\n readonly mode: DeliveryTarget;\n /** The shell connection, inside Mostra's shell. */\n readonly shell: ShellConnection | undefined;\n}\n\n/** The delivery target the page was built or exported for: its `mostra-target` meta tag (D111). */\nexport function deliveryTarget(): DeliveryTarget {\n if (typeof document === \"undefined\") return \"live\";\n const content = document\n .querySelector('meta[name=\"mostra-target\"]')\n ?.getAttribute(\"content\")\n ?.trim();\n return content === \"static\" || content === \"mcp-app\" || content === \"verify\" ? content : \"live\";\n}\n\n/** A random ID for this tab. */\nfunction tabId(): string {\n const bytes = new Uint8Array(12);\n globalThis.crypto.getRandomValues(bytes);\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\ninterface Locks {\n request(name: string, callback: () => Promise<unknown>): Promise<unknown>;\n request(\n name: string,\n options: { mode?: \"exclusive\" | \"shared\" },\n callback: () => Promise<unknown>,\n ): Promise<unknown>;\n query(): Promise<{ held?: { name?: string }[] }>;\n}\n\nfunction locks(): Locks | undefined {\n const navigatorLocks = (globalThis.navigator as { locks?: Locks } | undefined)?.locks;\n return navigatorLocks;\n}\n\nconst TAB_LOCK = \"mostra-tab:\";\n\n/** How long a tab waits for other tabs to say they are open, where Web Locks are missing. */\nconst PRESENCE_WAIT_MS = 300;\n\n/**\n * Where Web Locks are missing (they need a secure context, and an artifact served over plain\n * HTTP on a LAN address isn't one), open tabs answer a roll call on a BroadcastChannel, which\n * works everywhere: a tab that doesn't answer within {@link PRESENCE_WAIT_MS} is gone.\n */\nfunction rollCall(\n tab: string,\n): ((tabs: readonly string[]) => Promise<ReadonlySet<string>>) | undefined {\n if (typeof BroadcastChannel === \"undefined\") return undefined;\n const channel = new BroadcastChannel(\"mostra-tabs\");\n channel.onmessage = (event: MessageEvent<{ who?: true; here?: string }>) => {\n if (event.data?.who) channel.postMessage({ here: tab });\n };\n return (tabs) =>\n new Promise((resolve) => {\n const open = new Set<string>();\n const listen = new BroadcastChannel(\"mostra-tabs\");\n listen.onmessage = (event: MessageEvent<{ here?: string }>) => {\n if (typeof event.data?.here === \"string\") open.add(event.data.here);\n };\n listen.postMessage({ who: true });\n setTimeout(() => {\n listen.close();\n resolve(new Set(tabs.filter((other) => !open.has(other))));\n }, PRESENCE_WAIT_MS);\n });\n}\n\n/**\n * Holds this tab's lock for as long as the page lives, so other pages know its journal entries\n * belong to an open tab (Web Locks). Returns which of some tabs hold no lock: they are gone.\n */\nfunction tabPresence(tab: string): (tabs: readonly string[]) => Promise<ReadonlySet<string>> {\n const api = locks();\n if (!api) return rollCall(tab) ?? (async (tabs) => new Set(tabs));\n void api.request(`${TAB_LOCK}${tab}`, () => new Promise<never>(() => undefined));\n return async (tabs) => {\n const held = new Set(\n ((await api.query()).held ?? [])\n .map((lock) => lock.name)\n .filter((name): name is string => name?.startsWith(TAB_LOCK) === true)\n .map((name) => name.slice(TAB_LOCK.length)),\n );\n return new Set(tabs.filter((other) => !held.has(other)));\n };\n}\n\n/** Runs `fn` while no other page of the artifact adopts journal entries. */\nfunction exclusive<T>(fn: () => Promise<T>): Promise<T> {\n const api = locks();\n if (!api) return fn();\n return api.request(\"mostra-journal\", fn) as Promise<T>;\n}\n\n/** The longest pause between two attempts at the shell's handshake. */\nconst SHELL_RETRY_MAX_MS = 8_000;\n\n/**\n * The shell's connection for a framed page. A page inside a frame is inside Mostra's shell (its\n * origin is framed by the shell only): if the handshake fails (the daemon restarting during the\n * frame's load, a slow shell), it tries again rather than run on its own, where its answers\n * would stay in this browser while the shell said \"Saved\" (FAILURE_MODEL §1 rule 4; Claude review\n * finding 4). A page opened on its own has no shell and runs locally.\n */\nasync function framedShell(): Promise<ShellConnection | undefined> {\n if (typeof window === \"undefined\" || window.parent === window) return undefined;\n for (let attempt = 0; ; attempt += 1) {\n const shell = await connectShell();\n if (shell) return shell;\n if (attempt === 1)\n console.warn(\"Mostra: waiting for the shell; the page connects when it can.\");\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(500 * 2 ** attempt, SHELL_RETRY_MAX_MS)),\n );\n }\n}\n\n/**\n * Starts the runtime: live behind the gateway inside Mostra's shell, local otherwise (a static\n * export, an MCP App until its transport arrives, a page opened on its own).\n */\nexport async function startRuntime(): Promise<Runtime> {\n const target = deliveryTarget();\n const tab = tabId();\n const shell = target === \"live\" || target === \"verify\" ? await framedShell() : undefined;\n // Read the tolerant way: a later shell may send values this page doesn't know (Claude review\n // finding 5), which never cost it its view.\n const view: ViewContext | undefined = shell?.host.mostra\n ? readViewContext(shell.host.mostra)\n : undefined;\n const built = builtVersion();\n if (shell && view && built !== undefined && built !== view.version.id) {\n // This page is another version than the view the shell opened: another tab moved the frame\n // session on (D98 item 5). Nothing it shows may be saved as this view, nor kept: the shell,\n // told the page's version in `ui/initialize`, loads the frame again at its own version.\n const scratch = new Map<string, string>();\n const store = new Store({\n mode: \"local\",\n journal: new MemoryJournal(),\n tab,\n local: {\n getItem: (key) => scratch.get(key) ?? null,\n setItem: (key, value) => void scratch.set(key, value),\n removeItem: (key) => void scratch.delete(key),\n },\n });\n store.start();\n return { store, target, mode: view.target, shell };\n }\n if (!shell || !view) {\n const store = new Store({ mode: \"local\", journal: new MemoryJournal(), tab });\n store.start();\n return { store, target, mode: target === \"live\" ? \"static\" : target, shell: undefined };\n }\n const journal: Journal = (await IndexedDbJournal.open()) ?? new MemoryJournal();\n const store = new Store({\n mode: \"live\",\n transport: new HttpTransport(view.viewId, {\n ...(shell.session.csrf !== \"\" ? { csrf: shell.session.csrf } : {}),\n // Worker mode opens streams and polls with tickets, past the service worker (D70).\n ...(shell.session.mode === \"worker\" ? { tickets: true } : {}),\n ...(shell.session.streams ? {} : { streams: false }),\n }),\n journal,\n view,\n scopes: shell.session.scopes,\n ...(shell.session.viewer ? { viewer: shell.session.viewer } : {}),\n tab,\n goneTabs: tabPresence(tab),\n exclusive,\n channel: (name) =>\n typeof BroadcastChannel === \"undefined\" ? undefined : new BroadcastChannel(name),\n });\n // A verify run reads which fields the page mounts (D138); a viewer's page never records them.\n if (target === \"verify\") installVerifyProbe(store);\n store.start();\n wireLifecycle(store);\n wireShell(store, shell);\n return { store, target, mode: view.target, shell };\n}\n\n/** Saves on blur, and when the page is hidden or closed (IN-02). */\nfunction wireLifecycle(store: Store): void {\n if (typeof document === \"undefined\") return;\n document.addEventListener(\"focusout\", () => void store.flush(), true);\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") void store.flush({ keepalive: true });\n });\n window.addEventListener(\"pagehide\", () => void store.flush({ keepalive: true }));\n}\n\n/** Focuses the element a field is bound to, when the viewer picks it in the shell. */\nfunction focusField(id: string): void {\n const escaped = typeof CSS !== \"undefined\" && CSS.escape ? CSS.escape(id) : id;\n const element = document.querySelector<HTMLElement>(\n `[data-mostra-field=\"${escaped}\"], [name=\"${escaped}\"], #${escaped}`,\n );\n element?.scrollIntoView({ block: \"center\" });\n element?.focus();\n}\n\n/** Reports fields and save state to the shell, and answers its requests. */\nfunction wireShell(store: Store, shell: ShellConnection): void {\n let last = \"\";\n let scheduled = false;\n const report = (): void => {\n scheduled = false;\n const fields = store.registrations().map((registration) => ({\n id: registration.id,\n scope: registration.scope,\n ...(registration.label !== undefined ? { label: clip(registration.label) } : {}),\n ...(registration.required !== undefined ? { required: registration.required } : {}),\n ...(registration.sensitive !== undefined ? { sensitive: registration.sensitive } : {}),\n ...(registration.error !== undefined ? { error: clip(registration.error) } : {}),\n ...(store.conflict(`${registration.scope}:${registration.id}`) ? { conflict: true } : {}),\n }));\n const params: FieldsParams = {\n fields: firstThatMatter(fields, (field) =>\n Boolean(field.required || field.error !== undefined || field.conflict),\n ),\n save: store.pageSave(),\n unsaved: store.unsaved(),\n };\n const text = JSON.stringify(params);\n if (text === last) return;\n last = text;\n try {\n shell.bridge.notify(mostraFields, params);\n } catch (error) {\n // Never silently: the shell's rail would keep its last state (Claude review finding 11).\n console.error(\"Mostra: the page's fields couldn't be reported to the shell.\", error);\n }\n };\n store.subscribe(() => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(report);\n });\n report();\n listenShell({\n request: async (message, params) => {\n if (message !== mostraFlush) return undefined;\n const reason = (params as { reason: \"submit\" | \"switch\" }).reason;\n if (reason === \"submit\") {\n const prepared = await store.prepareSubmit();\n const result: FlushResult = {\n revision: String(prepared.revision),\n unsaved: prepared.unsaved,\n blockers: blockersForShell(prepared.blockers),\n };\n return result;\n }\n const flushed = await store.flush();\n const result: FlushResult = {\n revision: String(flushed.revision),\n unsaved: flushed.unsaved,\n blockers: blockersForShell(store.blockers()),\n };\n return result;\n },\n notification: (message, params) => {\n if (message === mostraFieldFocus) focusField((params as { id: string }).id);\n if (message === mostraVersionAvailable) {\n // The page may show its own notice; the shell's trusted banner always appears (§5).\n window.dispatchEvent(\n new CustomEvent<VersionAvailableParams>(\"mostra:version-available\", {\n detail: params as VersionAvailableParams,\n }),\n );\n }\n },\n });\n}\n","\"use client\";\n\n/**\n * The client side of `\"use server\"` functions (D19 seam 2, D54). The builder compiles every export\n * of a `\"use server\"` module in client code into a server reference: a function that carries the\n * server function's ID and hands the call to the page's runtime, as React's own server references\n * hand theirs to the callback `setServerCallback` installs. The runtime calls Mostra (a plain\n * call: no record, the result streamed back); where there is no Mostra server, such as a static\n * export, the call rejects with `MOSTRA_TARGET_UNAVAILABLE`.\n */\n\n/** A `\"use server\"` function as client code sees it. */\nexport interface ServerReference<A extends unknown[] = unknown[], R = unknown> {\n /** Calls the server function with `args`; resolves with its result. */\n (...args: A): Promise<R>;\n /** The server function's ID: its module path, `#` and its export name (`actions.ts#sendReply`). */\n readonly mostraServerFunctionId: string;\n}\n\n/** How the page's runtime calls a server function. */\nexport type CallServer = (id: string, args: unknown[]) => Promise<unknown>;\n\nconst unavailable: CallServer = async (id) => {\n const error = new Error(\n `The server function ${id} can't run here: this delivery target has no Mostra server. Open the artifact through its Mostra link to use it.`,\n ) as Error & { code: string };\n error.code = \"MOSTRA_TARGET_UNAVAILABLE\";\n throw error;\n};\n\nlet callServer: CallServer = unavailable;\n\n/**\n * Installs how server references call the server: the runtime does it when the page starts (a\n * live page calls Mostra; a static export keeps the default, which rejects). Returns the function\n * that restores the previous one.\n */\nexport function setServerCallback(callback: CallServer): () => void {\n const previous = callServer;\n callServer = callback;\n return () => {\n callServer = previous;\n };\n}\n\n/**\n * Creates the client stub of one server function. The builder emits these calls; artifact code\n * imports the server module as usual and never calls this itself.\n */\nexport function createServerReference(id: string): ServerReference {\n const reference = (...args: unknown[]): Promise<unknown> => callServer(id, args);\n Object.defineProperty(reference, \"mostraServerFunctionId\", { value: id, enumerable: true });\n return reference as unknown as ServerReference;\n}\n","\"use client\";\n\n/**\n * `window.storage`, compatible with Claude artifacts' persistent storage (D53, D112): agents that\n * learned `await window.storage.get(key)` keep working, and their values become Mostra fields.\n * Personal keys are the viewer's draft fields `storage.<key>`, carried over between versions and\n * delivered with the submission; `shared: true` keys are artifact state, every viewer's (D63).\n *\n * Differences from Claude's, by design (D112): a value is any JSON value up to 1 MiB (Mostra's\n * field limit; a larger one rejects with `MOSTRA_FIELD_TOO_LARGE`, never truncated), a missing key\n * resolves `null`, and two writers of one key end with the last write (a write that keeps meeting\n * another writer's change is refused with `MOSTRA_FIELD_CONFLICT`, never reported saved).\n */\nimport { isFieldId } from \"@mostra/protocol\";\nimport { MostraError } from \"./runtime/errors.ts\";\nimport { fieldKey, type Store } from \"./runtime/store.ts\";\n\n/** What `get` and `set` resolve with. */\nexport interface StorageEntry {\n /** The key. */\n readonly key: string;\n /** Its value: any JSON value. */\n readonly value: unknown;\n /** Whether it is shared by every viewer (artifact state) or the viewer's own. */\n readonly shared: boolean;\n}\n\n/** The storage API of Claude artifacts, backed by Mostra fields (D53). */\nexport interface ClaudeCompatibleStorage {\n /** The value of `key`, or `null` when it has none. */\n get(key: string, shared?: boolean): Promise<StorageEntry | null>;\n /** Stores `value` under `key`; resolves once Mostra saved it. */\n set(key: string, value: unknown, shared?: boolean): Promise<StorageEntry>;\n /** Removes `key`; resolves once Mostra saved that. */\n delete(\n key: string,\n shared?: boolean,\n ): Promise<{ readonly key: string; readonly deleted: true; readonly shared: boolean }>;\n /** The keys stored, those starting with `prefix` when it is given. */\n list(\n prefix?: string,\n shared?: boolean,\n ): Promise<{ readonly keys: string[]; readonly prefix?: string; readonly shared: boolean }>;\n}\n\nconst PREFIX = \"storage.\";\n\n/**\n * How many times a write over another writer's change is tried (last write wins, D112) before it\n * is refused with `MOSTRA_FIELD_CONFLICT`.\n */\nconst ATTEMPTS = 6;\n\nfunction fieldIdOf(key: unknown): string {\n if (typeof key !== \"string\" || !isFieldId(`${PREFIX}${key}`)) {\n throw new MostraError(\n \"MOSTRA_FIELD_ID_INVALID\",\n `${JSON.stringify(key)} can't be a storage key: use 1 to 248 characters without control characters or empty dot-separated parts.`,\n );\n }\n return `${PREFIX}${key}`;\n}\n\n/** Creates the `window.storage` of a page's store. */\nexport function createStorage(store: Store): ClaudeCompatibleStorage {\n const write = async (key: string, value: unknown, shared: boolean): Promise<void> => {\n const id = fieldIdOf(key);\n const scope = shared ? \"artifact\" : \"viewer\";\n await store.whenReady();\n if (value !== undefined) {\n const text = JSON.stringify(value);\n if (text === undefined) {\n throw new MostraError(\"MOSTRA_HOST_INVALID_PARAMS\", `The value of ${key} isn't JSON.`);\n }\n }\n store.set(scope, id, value, {\n immediate: true,\n ...(value === undefined ? { delete: true } : {}),\n });\n const k = fieldKey(scope, id);\n // Settled: saved, refused or in conflict. Offline, the write waits in the journal and the\n // promise with it: it resolves when Mostra has the value, never before (GPT review finding 10).\n const settled = (): Promise<void> =>\n new Promise((resolve) => {\n const done = (): boolean =>\n store.refusal(k) !== undefined ||\n store.conflict(k) !== undefined ||\n store.save(k) === \"saved\" ||\n store.save(k) === \"readonly\";\n if (done()) {\n resolve();\n return;\n }\n const stop = store.subscribe(() => {\n if (!done()) return;\n stop();\n resolve();\n });\n });\n for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {\n await store.flush();\n await settled();\n const refused = store.refusal(k);\n if (refused !== undefined) {\n store.takeTheirs(k);\n throw new MostraError(refused.code, refused.message);\n }\n if (!store.conflict(k)) return;\n if (attempt === ATTEMPTS - 1) break;\n // Another writer got in between: written again over theirs, after a short, growing pause.\n await new Promise((resolve) => setTimeout(resolve, 20 * 2 ** attempt * (1 + Math.random())));\n store.keepMine(k);\n }\n // Another writer kept changing it: the write is refused, never reported saved, and the field\n // keeps their value (Claude review finding 9).\n store.takeTheirs(k);\n throw new MostraError(\n \"MOSTRA_FIELD_CONFLICT\",\n `${key} kept changing under another writer, so this write wasn't saved.`,\n );\n };\n return {\n async get(key, shared = false) {\n const id = fieldIdOf(key);\n await store.whenReady();\n const value = store.value(fieldKey(shared ? \"artifact\" : \"viewer\", id), undefined);\n return value === undefined ? null : { key, value, shared };\n },\n async set(key, value, shared = false) {\n await write(key, value, shared);\n return { key, value, shared };\n },\n async delete(key, shared = false) {\n await write(key, undefined, shared);\n return { key, deleted: true as const, shared };\n },\n async list(prefix, shared = false) {\n await store.whenReady();\n const keys = store\n .ids(shared ? \"artifact\" : \"viewer\")\n .filter((id) => id.startsWith(PREFIX))\n .map((id) => id.slice(PREFIX.length))\n .filter((key) => prefix === undefined || key.startsWith(prefix));\n return { keys, ...(prefix !== undefined ? { prefix } : {}), shared };\n },\n };\n}\n\ndeclare global {\n interface Window {\n /** Claude-compatible persistent storage, backed by Mostra fields (D53). */\n storage: ClaudeCompatibleStorage;\n }\n}\n\n/** Installs `window.storage` for the page's store. */\nexport function installStorage(store: Store): void {\n if (typeof window === \"undefined\") return;\n Object.defineProperty(window, \"storage\", {\n value: createStorage(store),\n configurable: true,\n enumerable: false,\n writable: true,\n });\n}\n","\"use client\";\n\n/**\n * Mounting an artifact (D57, D111): the generated client entry hands the page to\n * {@link mountArtifact}, or its `pages/` routes to `mountRoutes` from `@mostra/react/router`. The\n * client runtime starts first, so the page renders with the viewer's saved answers rather than\n * flashing its defaults; after a short wait it renders anyway and catches up when the gateway\n * answers.\n */\nimport { mostraPage, VERIFY_REPORT } from \"@mostra/protocol\";\nimport { type ComponentType, createElement, type ReactNode } from \"react\";\nimport { createRoot, type RootOptions } from \"react-dom/client\";\nimport { type ArtifactMode, RuntimeProvider } from \"./hooks.ts\";\nimport { type Runtime, startRuntime } from \"./runtime/boot.ts\";\nimport { setServerCallback } from \"./server-reference.ts\";\nimport { reportReady } from \"./shell-bridge.ts\";\nimport { installStorage } from \"./storage.ts\";\n\n/** How long the first render waits for the viewer's saved answers. */\nconst FIRST_RENDER_WAIT_MS = 3_000;\n\n/** Starts the runtime, installs `window.storage`, and resolves once the page can render. */\nexport async function prepareArtifact(): Promise<Runtime> {\n const runtime = await startRuntime();\n installStorage(runtime.store);\n // Server references call through this page's runtime in live mode (D54); elsewhere (a static\n // export, a page opened outside its shell) they keep refusing with `MOSTRA_TARGET_UNAVAILABLE`,\n // naming the function.\n if (runtime.store.mode === \"live\") {\n setServerCallback((id, args) => runtime.store.server.call(id, args));\n }\n await runtime.store.whenReady(FIRST_RENDER_WAIT_MS);\n return runtime;\n}\n\n/**\n * The root's error handlers: in the `verify` target, an error a boundary caught goes to verify's\n * recorder with its `cause` chain (React's default logs it with `console.error`, which verify\n * couldn't tell apart from the page's own logging); everywhere else, React's defaults.\n */\nfunction rootOptions(mode: string): RootOptions | undefined {\n if (mode !== \"verify\") return undefined;\n const report = (globalThis as unknown as Record<string, unknown>)[VERIFY_REPORT];\n if (typeof report !== \"function\") return undefined;\n return { onCaughtError: (error: unknown) => (report as (error: unknown) => void)(error) };\n}\n\n/** Renders `node` inside the runtime into `#root`, and reports `mostra/ready`. */\nexport function renderArtifact(runtime: Runtime, node: ReactNode): void {\n const root = document.getElementById(\"root\");\n if (!root) throw new Error(\"The page has no #root element.\");\n createRoot(root, rootOptions(runtime.mode)).render(\n createElement(\n RuntimeProvider,\n { store: runtime.store, mode: runtime.mode as ArtifactMode },\n node,\n ),\n );\n reportReady();\n}\n\n/** Tells the shell which page the viewer is on (D57), so comments record it. */\nexport function reportPage(runtime: Runtime, path: string, title?: string): void {\n runtime.shell?.bridge.notify(mostraPage, {\n path,\n ...(title !== undefined && title !== \"\" ? { title } : {}),\n });\n}\n\n/**\n * Mounts a single-page artifact: the generated entry calls it with the entry's default export.\n * Artifact code doesn't need to.\n */\nexport async function mountArtifact(options: { readonly page: ComponentType }): Promise<void> {\n const runtime = await prepareArtifact();\n renderArtifact(runtime, createElement(options.page));\n reportPage(runtime, \"/\", document.title);\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAg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AAQ;EAAO,MAAM,QAAQ;CAAqB,GAC3D,IACF,CACF;CACA,YAAY;AACd;;AAGA,SAAgB,WAAW,SAAkB,MAAc,OAAsB;CAC/E,QAAQ,OAAO,OAAO,OAAO,YAAY;EACvC;EACA,GAAI,UAAU,KAAA,KAAa,UAAU,KAAK,EAAE,MAAM,IAAI,CAAC;CACzD,CAAC;AACH;;;;;AAMA,eAAsB,cAAc,SAA0D;CAC5F,MAAM,UAAU,MAAM,gBAAgB;CACtC,eAAe,SAAS,cAAc,QAAQ,IAAI,CAAC;CACnD,WAAW,SAAS,KAAK,SAAS,KAAK;AACzC"}
1
+ {"version":3,"file":"mount-BCj41qky.js","names":[],"sources":["../src/runtime/bridge-limits.ts","../src/runtime/service-worker.ts","../src/runtime/verify-probe.ts","../src/runtime/boot.ts","../src/server-reference.ts","../src/storage.ts","../src/mount.ts"],"sourcesContent":["/**\n * What the page sends the shell, fitted to the bridge's limits (Claude review finding 11): a long\n * label or validation message is shortened, and a page with more fields than one message lists\n * sends those that matter first. A report the bridge refuses would leave the shell's rail and its\n * blocker list stale, and a refused flush answer would stop every trusted Submit.\n */\nimport { BRIDGE_FIELDS_MAX, BRIDGE_TEXT_MAX, type SubmitBlocker } from \"@mostra/protocol\";\n\n/** Text shortened to what the bridge carries. */\nexport function clip(text: string): string {\n return text.length <= BRIDGE_TEXT_MAX ? text : `${text.slice(0, BRIDGE_TEXT_MAX - 1)}…`;\n}\n\n/** At most {@link BRIDGE_FIELDS_MAX} items, those that matter first, in their order otherwise. */\nexport function firstThatMatter<T>(items: readonly T[], matters: (item: T) => boolean): T[] {\n if (items.length <= BRIDGE_FIELDS_MAX) return [...items];\n return [...items.filter(matters), ...items.filter((item) => !matters(item))].slice(\n 0,\n BRIDGE_FIELDS_MAX,\n );\n}\n\n/** Blockers as the bridge carries them: labels shortened, at most {@link BRIDGE_FIELDS_MAX}. */\nexport function blockersForShell(blockers: readonly SubmitBlocker[]): SubmitBlocker[] {\n return blockers\n .slice(0, BRIDGE_FIELDS_MAX)\n .map((blocker) =>\n blocker.label === undefined ? blocker : { ...blocker, label: clip(blocker.label) },\n );\n}\n","/**\n * The frame's service worker in worker mode (D70, D158 item 5): where the shell and the artifact\n * are two sites, Mostra's own service worker at `/` signs every request of the frame with its\n * session. An artifact's own worker can't run there: its script is fetched without the session\n * (a browser adds nothing to that request), and a page it controlled would send requests no\n * worker signs, so the page would lose its session. The client runtime refuses such a\n * registration with a diagnostic the page can see, rather than letting it fail obscurely or end\n * the session. On a tailnet, Funnel or local link (cookie mode) the artifact registers its own\n * workers as usual.\n */\nimport { MostraError } from \"./errors.ts\";\n\n/** Mostra's worker, which the gateway serves on every worker-mode artifact origin. */\nconst MOSTRA_WORKER = \"/_mostra/sw.js\";\n\n/** Whether this page runs under Mostra's worker-mode service worker. */\nexport function workerModeFrame(): boolean {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return false;\n const controller = navigator.serviceWorker.controller;\n if (!controller) return false;\n try {\n return new URL(controller.scriptURL).pathname === MOSTRA_WORKER;\n } catch {\n return false;\n }\n}\n\nlet guarded = false;\n\n/**\n * In a worker-mode frame, refuses an artifact's own service worker with\n * `MOSTRA_HYGIENE_FRAME_SESSION` (rejecting the registration's promise and saying so on the\n * console), instead of letting it fail without its session or end the page's. Installed once,\n * before artifact code runs; a no-op anywhere else.\n */\nexport function guardFrameServiceWorker(): void {\n if (guarded || !workerModeFrame()) return;\n guarded = true;\n const container = navigator.serviceWorker;\n const register = container.register.bind(container);\n const guard: typeof container.register = (scriptURL, options) => {\n const script = new URL(String(scriptURL), location.href);\n if (script.origin === location.origin && script.pathname === MOSTRA_WORKER) {\n return register(scriptURL, options);\n }\n const scope = new URL(options?.scope ?? \"./\", script);\n const error = new MostraError(\n \"MOSTRA_HYGIENE_FRAME_SESSION\",\n `This page opened through a link whose frame runs on Mostra's own service worker (a public Cloudflare link), so ${script.pathname} can't be registered here (scope ${scope.pathname}): it would run without the page's session. On a tailnet, Funnel or local link the page registers its own service workers.`,\n );\n console.error(`[MOSTRA_HYGIENE_FRAME_SESSION] ${error.message}`);\n return Promise.reject(error);\n };\n container.register = guard;\n}\n","\"use client\";\n\n/**\n * `verify`'s field probe (D138 item 3): in the `verify` target only, the page keeps a record of\n * every field it mounts (the hook, the scope and the type of the initial value) and how much\n * server work it waits on, and publishes both on `globalThis[VERIFY_PROBE]`, where the verify\n * runner reads them. Viewers' pages never install it.\n */\nimport { type ProbedField, VERIFY_PROBE } from \"@mostra/protocol\";\nimport type { Registration, Store } from \"./store.ts\";\n\n/** `typeof`, with arrays and `null` named as such. */\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\ninterface Entry {\n readonly first: { readonly hook: string; readonly scope: string; readonly initialType: string };\n mounts: number;\n readonly conflicts: Set<string>;\n}\n\n/** Records the store's field mounts on `globalThis[VERIFY_PROBE]`. */\nexport function installVerifyProbe(store: Store): void {\n const entries = new Map<string, Entry>();\n store.observeMounts((registration: Registration, mounted: boolean) => {\n const shape = {\n hook: registration.hook ?? \"useField\",\n scope: registration.scope,\n initialType: typeName(registration.initial),\n };\n let entry = entries.get(registration.id);\n if (!entry) {\n entry = { first: shape, mounts: 0, conflicts: new Set() };\n entries.set(registration.id, entry);\n }\n if (mounted) {\n entry.mounts += 1;\n if (shape.hook !== entry.first.hook)\n entry.conflicts.add(`${entry.first.hook} and ${shape.hook}`);\n if (shape.scope !== entry.first.scope)\n entry.conflicts.add(`scopes ${entry.first.scope} and ${shape.scope}`);\n if (shape.initialType !== entry.first.initialType)\n entry.conflicts.add(\n `initial values of types ${entry.first.initialType} and ${shape.initialType}`,\n );\n } else entry.mounts = Math.max(0, entry.mounts - 1);\n });\n const fields = (): ProbedField[] =>\n [...entries].map(([id, entry]) => ({\n id,\n scope: entry.first.scope as ProbedField[\"scope\"],\n hook: entry.first.hook,\n initialType: entry.first.initialType,\n mounts: entry.mounts,\n conflicts: [...entry.conflicts],\n }));\n // `pending`: the server work the page waits on (calls, runs, first live values), which the\n // runner's quiescence wait includes (Opus review finding 1).\n const pending = (): number => store.server.pending();\n Object.defineProperty(globalThis, VERIFY_PROBE, {\n value: { fields, pending },\n configurable: true,\n });\n}\n","/**\n * Starts the client runtime for the page (D111): reads the delivery target, connects to the shell\n * and the gateway in live mode, opens the journal, and wires the page's lifecycle (blur,\n * `visibilitychange`, `pagehide`) and the bridge (`mostra/fields`, `mostra/flush`,\n * `mostra/field.focus`, `mostra/version.available`) to the store.\n */\nimport {\n type DeliveryTarget,\n type FieldsParams,\n type FlushResult,\n mostraFieldFocus,\n mostraFields,\n mostraFlush,\n mostraVersionAvailable,\n readViewContext,\n type VersionAvailableParams,\n type ViewContext,\n} from \"@mostra/protocol\";\nimport { builtVersion, connectShell, listenShell, type ShellConnection } from \"../shell-bridge.ts\";\nimport { blockersForShell, clip, firstThatMatter } from \"./bridge-limits.ts\";\nimport { IndexedDbJournal, type Journal, MemoryJournal } from \"./journal.ts\";\nimport { guardFrameServiceWorker } from \"./service-worker.ts\";\nimport { Store } from \"./store.ts\";\nimport { HttpTransport } from \"./transport.ts\";\nimport { installVerifyProbe } from \"./verify-probe.ts\";\n\n// Before any artifact code runs: the generated entry imports the runtime first (D70).\nguardFrameServiceWorker();\n\n/** The page's runtime: its store, where it runs, and its shell connection. */\nexport interface Runtime {\n readonly store: Store;\n /** The delivery target the page was built or exported for (D111): it chooses the history. */\n readonly target: DeliveryTarget;\n /**\n * Where the page runs, as `useArtifact` reports it: the target, except that a live page opened\n * outside Mostra's shell has no server features and reports `static`.\n */\n readonly mode: DeliveryTarget;\n /** The shell connection, inside Mostra's shell. */\n readonly shell: ShellConnection | undefined;\n}\n\n/** The delivery target the page was built or exported for: its `mostra-target` meta tag (D111). */\nexport function deliveryTarget(): DeliveryTarget {\n if (typeof document === \"undefined\") return \"live\";\n const content = document\n .querySelector('meta[name=\"mostra-target\"]')\n ?.getAttribute(\"content\")\n ?.trim();\n return content === \"static\" || content === \"mcp-app\" || content === \"verify\" ? content : \"live\";\n}\n\n/** A random ID for this tab. */\nfunction tabId(): string {\n const bytes = new Uint8Array(12);\n globalThis.crypto.getRandomValues(bytes);\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\ninterface Locks {\n request(name: string, callback: () => Promise<unknown>): Promise<unknown>;\n request(\n name: string,\n options: { mode?: \"exclusive\" | \"shared\" },\n callback: () => Promise<unknown>,\n ): Promise<unknown>;\n query(): Promise<{ held?: { name?: string }[] }>;\n}\n\nfunction locks(): Locks | undefined {\n const navigatorLocks = (globalThis.navigator as { locks?: Locks } | undefined)?.locks;\n return navigatorLocks;\n}\n\nconst TAB_LOCK = \"mostra-tab:\";\n\n/** How long a tab waits for other tabs to say they are open, where Web Locks are missing. */\nconst PRESENCE_WAIT_MS = 300;\n\n/**\n * Where Web Locks are missing (they need a secure context, and an artifact served over plain\n * HTTP on a LAN address isn't one), open tabs answer a roll call on a BroadcastChannel, which\n * works everywhere: a tab that doesn't answer within {@link PRESENCE_WAIT_MS} is gone.\n */\nfunction rollCall(\n tab: string,\n): ((tabs: readonly string[]) => Promise<ReadonlySet<string>>) | undefined {\n if (typeof BroadcastChannel === \"undefined\") return undefined;\n const channel = new BroadcastChannel(\"mostra-tabs\");\n channel.onmessage = (event: MessageEvent<{ who?: true; here?: string }>) => {\n if (event.data?.who) channel.postMessage({ here: tab });\n };\n return (tabs) =>\n new Promise((resolve) => {\n const open = new Set<string>();\n const listen = new BroadcastChannel(\"mostra-tabs\");\n listen.onmessage = (event: MessageEvent<{ here?: string }>) => {\n if (typeof event.data?.here === \"string\") open.add(event.data.here);\n };\n listen.postMessage({ who: true });\n setTimeout(() => {\n listen.close();\n resolve(new Set(tabs.filter((other) => !open.has(other))));\n }, PRESENCE_WAIT_MS);\n });\n}\n\n/**\n * Holds this tab's lock for as long as the page lives, so other pages know its journal entries\n * belong to an open tab (Web Locks). Returns which of some tabs hold no lock: they are gone.\n */\nfunction tabPresence(tab: string): (tabs: readonly string[]) => Promise<ReadonlySet<string>> {\n const api = locks();\n if (!api) return rollCall(tab) ?? (async (tabs) => new Set(tabs));\n void api.request(`${TAB_LOCK}${tab}`, () => new Promise<never>(() => undefined));\n return async (tabs) => {\n const held = new Set(\n ((await api.query()).held ?? [])\n .map((lock) => lock.name)\n .filter((name): name is string => name?.startsWith(TAB_LOCK) === true)\n .map((name) => name.slice(TAB_LOCK.length)),\n );\n return new Set(tabs.filter((other) => !held.has(other)));\n };\n}\n\n/** Runs `fn` while no other page of the artifact adopts journal entries. */\nfunction exclusive<T>(fn: () => Promise<T>): Promise<T> {\n const api = locks();\n if (!api) return fn();\n return api.request(\"mostra-journal\", fn) as Promise<T>;\n}\n\n/** The longest pause between two attempts at the shell's handshake. */\nconst SHELL_RETRY_MAX_MS = 8_000;\n\n/**\n * The shell's connection for a framed page. A page inside a frame is inside Mostra's shell (its\n * origin is framed by the shell only): if the handshake fails (the daemon restarting during the\n * frame's load, a slow shell), it tries again rather than run on its own, where its answers\n * would stay in this browser while the shell said \"Saved\" (FAILURE_MODEL §1 rule 4; Claude review\n * finding 4). A page opened on its own has no shell and runs locally.\n */\nasync function framedShell(): Promise<ShellConnection | undefined> {\n if (typeof window === \"undefined\" || window.parent === window) return undefined;\n for (let attempt = 0; ; attempt += 1) {\n const shell = await connectShell();\n if (shell) return shell;\n if (attempt === 1)\n console.warn(\"Mostra: waiting for the shell; the page connects when it can.\");\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(500 * 2 ** attempt, SHELL_RETRY_MAX_MS)),\n );\n }\n}\n\n/**\n * Starts the runtime: live behind the gateway inside Mostra's shell, local otherwise (a static\n * export, an MCP App until its transport arrives, a page opened on its own).\n */\nexport async function startRuntime(): Promise<Runtime> {\n const target = deliveryTarget();\n const tab = tabId();\n const shell = target === \"live\" || target === \"verify\" ? await framedShell() : undefined;\n // Read the tolerant way: a later shell may send values this page doesn't know (Claude review\n // finding 5), which never cost it its view.\n const view: ViewContext | undefined = shell?.host.mostra\n ? readViewContext(shell.host.mostra)\n : undefined;\n const built = builtVersion();\n if (shell && view && built !== undefined && built !== view.version.id) {\n // This page is another version than the view the shell opened: another tab moved the frame\n // session on (D98 item 5). Nothing it shows may be saved as this view, nor kept: the shell,\n // told the page's version in `ui/initialize`, loads the frame again at its own version.\n const scratch = new Map<string, string>();\n const store = new Store({\n mode: \"local\",\n journal: new MemoryJournal(),\n tab,\n local: {\n getItem: (key) => scratch.get(key) ?? null,\n setItem: (key, value) => void scratch.set(key, value),\n removeItem: (key) => void scratch.delete(key),\n },\n });\n store.start();\n return { store, target, mode: view.target, shell };\n }\n if (!shell || !view) {\n const store = new Store({ mode: \"local\", journal: new MemoryJournal(), tab });\n store.start();\n return { store, target, mode: target === \"live\" ? \"static\" : target, shell: undefined };\n }\n const journal: Journal = (await IndexedDbJournal.open()) ?? new MemoryJournal();\n const store = new Store({\n mode: \"live\",\n transport: new HttpTransport(view.viewId, {\n ...(shell.session.csrf !== \"\" ? { csrf: shell.session.csrf } : {}),\n // Worker mode opens streams and polls with tickets, past the service worker (D70).\n ...(shell.session.mode === \"worker\" ? { tickets: true } : {}),\n ...(shell.session.streams ? {} : { streams: false }),\n }),\n journal,\n view,\n scopes: shell.session.scopes,\n ...(shell.session.viewer ? { viewer: shell.session.viewer } : {}),\n tab,\n goneTabs: tabPresence(tab),\n exclusive,\n channel: (name) =>\n typeof BroadcastChannel === \"undefined\" ? undefined : new BroadcastChannel(name),\n });\n // A verify run reads which fields the page mounts (D138); a viewer's page never records them.\n if (target === \"verify\") installVerifyProbe(store);\n store.start();\n wireLifecycle(store);\n wireShell(store, shell);\n return { store, target, mode: view.target, shell };\n}\n\n/** Saves on blur, and when the page is hidden or closed (IN-02). */\nfunction wireLifecycle(store: Store): void {\n if (typeof document === \"undefined\") return;\n document.addEventListener(\"focusout\", () => void store.flush(), true);\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") void store.flush({ keepalive: true });\n });\n window.addEventListener(\"pagehide\", () => void store.flush({ keepalive: true }));\n}\n\n/** Focuses the element a field is bound to, when the viewer picks it in the shell. */\nfunction focusField(id: string): void {\n const escaped = typeof CSS !== \"undefined\" && CSS.escape ? CSS.escape(id) : id;\n const element = document.querySelector<HTMLElement>(\n `[data-mostra-field=\"${escaped}\"], [name=\"${escaped}\"], #${escaped}`,\n );\n element?.scrollIntoView({ block: \"center\" });\n element?.focus();\n}\n\n/** Reports fields and save state to the shell, and answers its requests. */\nfunction wireShell(store: Store, shell: ShellConnection): void {\n let last = \"\";\n let scheduled = false;\n const report = (): void => {\n scheduled = false;\n const fields = store.registrations().map((registration) => ({\n id: registration.id,\n scope: registration.scope,\n ...(registration.label !== undefined ? { label: clip(registration.label) } : {}),\n ...(registration.required !== undefined ? { required: registration.required } : {}),\n ...(registration.sensitive !== undefined ? { sensitive: registration.sensitive } : {}),\n ...(registration.error !== undefined ? { error: clip(registration.error) } : {}),\n ...(store.conflict(`${registration.scope}:${registration.id}`) ? { conflict: true } : {}),\n }));\n const params: FieldsParams = {\n fields: firstThatMatter(fields, (field) =>\n Boolean(field.required || field.error !== undefined || field.conflict),\n ),\n save: store.pageSave(),\n unsaved: store.unsaved(),\n };\n const text = JSON.stringify(params);\n if (text === last) return;\n last = text;\n try {\n shell.bridge.notify(mostraFields, params);\n } catch (error) {\n // Never silently: the shell's rail would keep its last state (Claude review finding 11).\n console.error(\"Mostra: the page's fields couldn't be reported to the shell.\", error);\n }\n };\n store.subscribe(() => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(report);\n });\n report();\n listenShell({\n request: async (message, params) => {\n if (message !== mostraFlush) return undefined;\n const reason = (params as { reason: \"submit\" | \"switch\" }).reason;\n if (reason === \"submit\") {\n const prepared = await store.prepareSubmit();\n const result: FlushResult = {\n revision: String(prepared.revision),\n unsaved: prepared.unsaved,\n blockers: blockersForShell(prepared.blockers),\n };\n return result;\n }\n const flushed = await store.flush();\n const result: FlushResult = {\n revision: String(flushed.revision),\n unsaved: flushed.unsaved,\n blockers: blockersForShell(store.blockers()),\n };\n return result;\n },\n notification: (message, params) => {\n if (message === mostraFieldFocus) focusField((params as { id: string }).id);\n if (message === mostraVersionAvailable) {\n // The page may show its own notice; the shell's trusted banner always appears (§5).\n window.dispatchEvent(\n new CustomEvent<VersionAvailableParams>(\"mostra:version-available\", {\n detail: params as VersionAvailableParams,\n }),\n );\n }\n },\n });\n}\n","\"use client\";\n\n/**\n * The client side of `\"use server\"` functions (D19 seam 2, D54). The builder compiles every export\n * of a `\"use server\"` module in client code into a server reference: a function that carries the\n * server function's ID and hands the call to the page's runtime, as React's own server references\n * hand theirs to the callback `setServerCallback` installs. The runtime calls Mostra (a plain\n * call: no record, the result streamed back); where there is no Mostra server, such as a static\n * export, the call rejects with `MOSTRA_TARGET_UNAVAILABLE`.\n */\n\n/** A `\"use server\"` function as client code sees it. */\nexport interface ServerReference<A extends unknown[] = unknown[], R = unknown> {\n /** Calls the server function with `args`; resolves with its result. */\n (...args: A): Promise<R>;\n /** The server function's ID: its module path, `#` and its export name (`actions.ts#sendReply`). */\n readonly mostraServerFunctionId: string;\n}\n\n/** How the page's runtime calls a server function. */\nexport type CallServer = (id: string, args: unknown[]) => Promise<unknown>;\n\nconst unavailable: CallServer = async (id) => {\n const error = new Error(\n `The server function ${id} can't run here: this delivery target has no Mostra server. Open the artifact through its Mostra link to use it.`,\n ) as Error & { code: string };\n error.code = \"MOSTRA_TARGET_UNAVAILABLE\";\n throw error;\n};\n\nlet callServer: CallServer = unavailable;\n\n/**\n * Installs how server references call the server: the runtime does it when the page starts (a\n * live page calls Mostra; a static export keeps the default, which rejects). Returns the function\n * that restores the previous one.\n */\nexport function setServerCallback(callback: CallServer): () => void {\n const previous = callServer;\n callServer = callback;\n return () => {\n callServer = previous;\n };\n}\n\n/**\n * Creates the client stub of one server function. The builder emits these calls; artifact code\n * imports the server module as usual and never calls this itself.\n */\nexport function createServerReference(id: string): ServerReference {\n const reference = (...args: unknown[]): Promise<unknown> => callServer(id, args);\n Object.defineProperty(reference, \"mostraServerFunctionId\", { value: id, enumerable: true });\n return reference as unknown as ServerReference;\n}\n","\"use client\";\n\n/**\n * `window.storage`, compatible with Claude artifacts' persistent storage (D53, D112): agents that\n * learned `await window.storage.get(key)` keep working, and their values become Mostra fields.\n * Personal keys are the viewer's draft fields `storage.<key>`, carried over between versions and\n * delivered with the submission; `shared: true` keys are artifact state, every viewer's (D63).\n *\n * Differences from Claude's, by design (D112): a value is any JSON value up to 1 MiB (Mostra's\n * field limit; a larger one rejects with `MOSTRA_FIELD_TOO_LARGE`, never truncated), a missing key\n * resolves `null`, and two writers of one key end with the last write (a write that keeps meeting\n * another writer's change is refused with `MOSTRA_FIELD_CONFLICT`, never reported saved).\n */\nimport { isFieldId } from \"@mostra/protocol\";\nimport { MostraError } from \"./runtime/errors.ts\";\nimport { fieldKey, type Store } from \"./runtime/store.ts\";\n\n/** What `get` and `set` resolve with. */\nexport interface StorageEntry {\n /** The key. */\n readonly key: string;\n /** Its value: any JSON value. */\n readonly value: unknown;\n /** Whether it is shared by every viewer (artifact state) or the viewer's own. */\n readonly shared: boolean;\n}\n\n/** The storage API of Claude artifacts, backed by Mostra fields (D53). */\nexport interface ClaudeCompatibleStorage {\n /** The value of `key`, or `null` when it has none. */\n get(key: string, shared?: boolean): Promise<StorageEntry | null>;\n /** Stores `value` under `key`; resolves once Mostra saved it. */\n set(key: string, value: unknown, shared?: boolean): Promise<StorageEntry>;\n /** Removes `key`; resolves once Mostra saved that. */\n delete(\n key: string,\n shared?: boolean,\n ): Promise<{ readonly key: string; readonly deleted: true; readonly shared: boolean }>;\n /** The keys stored, those starting with `prefix` when it is given. */\n list(\n prefix?: string,\n shared?: boolean,\n ): Promise<{ readonly keys: string[]; readonly prefix?: string; readonly shared: boolean }>;\n}\n\nconst PREFIX = \"storage.\";\n\n/**\n * How many times a write over another writer's change is tried (last write wins, D112) before it\n * is refused with `MOSTRA_FIELD_CONFLICT`.\n */\nconst ATTEMPTS = 6;\n\nfunction fieldIdOf(key: unknown): string {\n if (typeof key !== \"string\" || !isFieldId(`${PREFIX}${key}`)) {\n throw new MostraError(\n \"MOSTRA_FIELD_ID_INVALID\",\n `${JSON.stringify(key)} can't be a storage key: use 1 to 248 characters without control characters or empty dot-separated parts.`,\n );\n }\n return `${PREFIX}${key}`;\n}\n\n/** Creates the `window.storage` of a page's store. */\nexport function createStorage(store: Store): ClaudeCompatibleStorage {\n const write = async (key: string, value: unknown, shared: boolean): Promise<void> => {\n const id = fieldIdOf(key);\n const scope = shared ? \"artifact\" : \"viewer\";\n await store.whenReady();\n if (value !== undefined) {\n const text = JSON.stringify(value);\n if (text === undefined) {\n throw new MostraError(\"MOSTRA_HOST_INVALID_PARAMS\", `The value of ${key} isn't JSON.`);\n }\n }\n store.set(scope, id, value, {\n immediate: true,\n ...(value === undefined ? { delete: true } : {}),\n });\n const k = fieldKey(scope, id);\n // Settled: saved, refused or in conflict. Offline, the write waits in the journal and the\n // promise with it: it resolves when Mostra has the value, never before (GPT review finding 10).\n const settled = (): Promise<void> =>\n new Promise((resolve) => {\n const done = (): boolean =>\n store.refusal(k) !== undefined ||\n store.conflict(k) !== undefined ||\n store.save(k) === \"saved\" ||\n store.save(k) === \"readonly\";\n if (done()) {\n resolve();\n return;\n }\n const stop = store.subscribe(() => {\n if (!done()) return;\n stop();\n resolve();\n });\n });\n for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {\n await store.flush();\n await settled();\n const refused = store.refusal(k);\n if (refused !== undefined) {\n store.takeTheirs(k);\n throw new MostraError(refused.code, refused.message);\n }\n if (!store.conflict(k)) return;\n if (attempt === ATTEMPTS - 1) break;\n // Another writer got in between: written again over theirs, after a short, growing pause.\n await new Promise((resolve) => setTimeout(resolve, 20 * 2 ** attempt * (1 + Math.random())));\n store.keepMine(k);\n }\n // Another writer kept changing it: the write is refused, never reported saved, and the field\n // keeps their value (Claude review finding 9).\n store.takeTheirs(k);\n throw new MostraError(\n \"MOSTRA_FIELD_CONFLICT\",\n `${key} kept changing under another writer, so this write wasn't saved.`,\n );\n };\n return {\n async get(key, shared = false) {\n const id = fieldIdOf(key);\n await store.whenReady();\n const value = store.value(fieldKey(shared ? \"artifact\" : \"viewer\", id), undefined);\n return value === undefined ? null : { key, value, shared };\n },\n async set(key, value, shared = false) {\n await write(key, value, shared);\n return { key, value, shared };\n },\n async delete(key, shared = false) {\n await write(key, undefined, shared);\n return { key, deleted: true as const, shared };\n },\n async list(prefix, shared = false) {\n await store.whenReady();\n const keys = store\n .ids(shared ? \"artifact\" : \"viewer\")\n .filter((id) => id.startsWith(PREFIX))\n .map((id) => id.slice(PREFIX.length))\n .filter((key) => prefix === undefined || key.startsWith(prefix));\n return { keys, ...(prefix !== undefined ? { prefix } : {}), shared };\n },\n };\n}\n\ndeclare global {\n interface Window {\n /** Claude-compatible persistent storage, backed by Mostra fields (D53). */\n storage: ClaudeCompatibleStorage;\n }\n}\n\n/** Installs `window.storage` for the page's store. */\nexport function installStorage(store: Store): void {\n if (typeof window === \"undefined\") return;\n Object.defineProperty(window, \"storage\", {\n value: createStorage(store),\n configurable: true,\n enumerable: false,\n writable: true,\n });\n}\n","\"use client\";\n\n/**\n * Mounting an artifact (D57, D111): the generated client entry hands the page to\n * {@link mountArtifact}, or its `pages/` routes to `mountRoutes` from `@mostra/react/router`. The\n * client runtime starts first, so the page renders with the viewer's saved answers rather than\n * flashing its defaults; after a short wait it renders anyway and catches up when the gateway\n * answers.\n */\nimport { mostraPage, VERIFY_REPORT } from \"@mostra/protocol\";\nimport { type ComponentType, createElement, type ReactNode } from \"react\";\nimport { createRoot, type RootOptions } from \"react-dom/client\";\nimport { type ArtifactMode, RuntimeProvider } from \"./hooks.ts\";\nimport { type Runtime, startRuntime } from \"./runtime/boot.ts\";\nimport { setServerCallback } from \"./server-reference.ts\";\nimport { reportReady } from \"./shell-bridge.ts\";\nimport { installStorage } from \"./storage.ts\";\n\n/** How long the first render waits for the viewer's saved answers. */\nconst FIRST_RENDER_WAIT_MS = 3_000;\n\n/** Starts the runtime, installs `window.storage`, and resolves once the page can render. */\nexport async function prepareArtifact(): Promise<Runtime> {\n const runtime = await startRuntime();\n installStorage(runtime.store);\n // Server references call through this page's runtime in live mode (D54); elsewhere (a static\n // export, a page opened outside its shell) they keep refusing with `MOSTRA_TARGET_UNAVAILABLE`,\n // naming the function.\n if (runtime.store.mode === \"live\") {\n setServerCallback((id, args) => runtime.store.server.call(id, args));\n }\n await runtime.store.whenReady(FIRST_RENDER_WAIT_MS);\n return runtime;\n}\n\n/**\n * The root's error handlers: in the `verify` target, an error a boundary caught goes to verify's\n * recorder with its `cause` chain (React's default logs it with `console.error`, which verify\n * couldn't tell apart from the page's own logging); everywhere else, React's defaults.\n */\nfunction rootOptions(mode: string): RootOptions | undefined {\n if (mode !== \"verify\") return undefined;\n const report = (globalThis as unknown as Record<string, unknown>)[VERIFY_REPORT];\n if (typeof report !== \"function\") return undefined;\n return { onCaughtError: (error: unknown) => (report as (error: unknown) => void)(error) };\n}\n\n/** Renders `node` inside the runtime into `#root`, and reports `mostra/ready`. */\nexport function renderArtifact(runtime: Runtime, node: ReactNode): void {\n const root = document.getElementById(\"root\");\n if (!root) throw new Error(\"The page has no #root element.\");\n createRoot(root, rootOptions(runtime.mode)).render(\n createElement(\n RuntimeProvider,\n { store: runtime.store, mode: runtime.mode as ArtifactMode },\n node,\n ),\n );\n reportReady();\n}\n\n/** Tells the shell which page the viewer is on (D57), so comments record it. */\nexport function reportPage(runtime: Runtime, path: string, title?: string): void {\n runtime.shell?.bridge.notify(mostraPage, {\n path,\n ...(title !== undefined && title !== \"\" ? { title } : {}),\n });\n}\n\n/**\n * Mounts a single-page artifact: the generated entry calls it with the entry's default export.\n * Artifact code doesn't need to.\n */\nexport async function mountArtifact(options: { readonly page: ComponentType }): Promise<void> {\n const runtime = await prepareArtifact();\n renderArtifact(runtime, createElement(options.page));\n reportPage(runtime, \"/\", document.title);\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,KAAK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AAO,MAAM,QAAQ;CAAqB,GAC3D,IACF,CACF;CACA,YAAY;AACd;;AAGA,SAAgB,WAAW,SAAkB,MAAc,OAAsB;CAC/E,QAAQ,OAAO,OAAO,OAAO,YAAY;EACvC;EACA,GAAI,UAAU,KAAA,KAAa,UAAU,KAAK,EAAE,MAAM,IAAI,CAAC;CACzD,CAAC;AACH;;;;;AAMA,eAAsB,cAAc,SAA0D;CAC5F,MAAM,UAAU,MAAM,gBAAgB;CACtC,eAAe,SAAS,cAAc,QAAQ,IAAI,CAAC;CACnD,WAAW,SAAS,KAAK,SAAS,KAAK;AACzC"}
package/dist/router.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { i as reportPage, n as prepareArtifact, r as renderArtifact } from "./mount-DSuEcMdp.js";
2
+ import { i as reportPage, n as prepareArtifact, r as renderArtifact } from "./mount-BCj41qky.js";
3
3
  import { createElement } from "react";
4
4
  import { Outlet, createBrowserRouter, createHashRouter, createMemoryRouter } from "react-router";
5
5
  import { RouterProvider } from "react-router/dom";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/react",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Mostra client runtime for artifact authors: fields, submit, signals, choices, window.storage, routing and the shell bridge.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -44,7 +44,7 @@
44
44
  "provenance": true
45
45
  },
46
46
  "dependencies": {
47
- "@mostra/protocol": "0.9.0"
47
+ "@mostra/protocol": "0.10.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@mostra/tools": "0.0.0",
@@ -80,7 +80,7 @@
80
80
  "react-router",
81
81
  "react-hook-form"
82
82
  ],
83
- "limit": "53.5 kB"
83
+ "limit": "54 kB"
84
84
  },
85
85
  {
86
86
  "name": "@mostra/react whole entry, zod excluded",
package/src/hooks.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  mostraControlsRequest,
15
15
  type SubmissionSummary,
16
16
  type SubmitBlocker,
17
+ type ViewerKind,
17
18
  } from "@mostra/protocol";
18
19
  import {
19
20
  createContext,
@@ -492,11 +493,14 @@ export function useChoice(
492
493
 
493
494
  // ── useViewer and useArtifact ───────────────────────────────────────────────────────────
494
495
 
495
- /** Who the page acts as (D104): the home's local user, a tailnet user, or a link's person. */
496
+ /**
497
+ * Who the page acts as (D104): the home's local user, a tailnet user, or a link's person; on a
498
+ * hosted link, a signed-in account or an anonymous visitor (D165 item 8).
499
+ */
496
500
  export function useViewer(): {
497
501
  readonly id: string;
498
502
  readonly name?: string;
499
- readonly source: "local" | "tailnet" | "token" | "host";
503
+ readonly source: ViewerKind;
500
504
  } {
501
505
  const { store } = useRuntime();
502
506
  useStoreVersion(store);
package/src/index.ts CHANGED
@@ -23,7 +23,12 @@
23
23
  */
24
24
  import type { ArtifactManifest } from "@mostra/protocol";
25
25
 
26
- export type { ArtifactManifest, SubmissionSummary, SubmitBlocker } from "@mostra/protocol";
26
+ export type {
27
+ ArtifactManifest,
28
+ SubmissionSummary,
29
+ SubmitBlocker,
30
+ TallyValue,
31
+ } from "@mostra/protocol";
27
32
  export {
28
33
  type ArtifactMode,
29
34
  type ChoiceCandidate,
@@ -49,6 +54,7 @@ export {
49
54
  type LiveSources,
50
55
  type LiveValue,
51
56
  type LiveValuesOf,
57
+ type TallyKey,
52
58
  useAction,
53
59
  useLive,
54
60
  } from "./server-hooks.ts";
@@ -90,6 +90,8 @@ export interface LiveView {
90
90
  readonly revision?: string;
91
91
  readonly at?: string;
92
92
  readonly error?: WireError;
93
+ /** A hosted page's source whose producer can't refresh it while its owner is offline. */
94
+ readonly ownerOffline?: boolean;
93
95
  /** Append mode: the values kept, oldest first, at most the largest window asked for. */
94
96
  readonly ring: readonly unknown[];
95
97
  }
@@ -406,6 +408,11 @@ export class ServerClient {
406
408
  };
407
409
  if (fresh.length > 0 && !tracked.rootDecoded) this.#decodeRoot(tracked);
408
410
  if (isFinalRunStatus(delta.status)) this.#settle(tracked);
411
+ // A relayed run whose owner never said how it ended (D165 item 4): `run()` rejects, and the
412
+ // run stays followed, since the owner's later report replaces `unknown` once.
413
+ else if (delta.status === "unknown") {
414
+ tracked.reject(failure(tracked.view.error, "MOSTRA_REMOTE_OWNER_OFFLINE"));
415
+ }
409
416
  this.#changed();
410
417
  return true;
411
418
  }
@@ -629,10 +636,13 @@ export class ServerClient {
629
636
  // loading, and stays pending for verify, until an update brings its value or its failure. A
630
637
  // key nothing produces, or one that only streams, isn't loading (WP-14, its Opus review).
631
638
  const settled = tracked.newest > 0 || state.error !== undefined || state.awaiting !== true;
639
+ const { ownerOffline: _was, ...held } = tracked.view;
632
640
  tracked.view = {
633
- ...tracked.view,
641
+ ...held,
634
642
  loading: !settled,
635
643
  ...(state.error ? { error: state.error } : {}),
644
+ // Read again at every renewal, so the flag follows the owner (D165 item 4).
645
+ ...(state.ownerOffline ? { ownerOffline: true } : {}),
636
646
  };
637
647
  if (!state.error && tracked.view.error) {
638
648
  const { error: _cleared, ...rest } = tracked.view;
@@ -666,7 +676,8 @@ export class ServerClient {
666
676
  window === undefined ? tracked.view.ring : [...tracked.view.ring, data].slice(-window);
667
677
  if (window !== undefined)
668
678
  tracked.ringRevisions = [...tracked.ringRevisions, revision].slice(-window);
669
- const { error: _cleared, ...rest } = tracked.view;
679
+ // A new value came from its producer, so its owner is back.
680
+ const { error: _cleared, ownerOffline: _back, ...rest } = tracked.view;
670
681
  tracked.view = {
671
682
  ...rest,
672
683
  loading: false,
@@ -513,6 +513,8 @@ export class Store {
513
513
  /** Loads a fresh snapshot, once at a time; a failure leaves it to the next event or submit. */
514
514
  #resync(): Promise<void> {
515
515
  this.#resyncing ??= (async () => {
516
+ // After `??=` made the registration its `finally` clears.
517
+ await Promise.resolve();
516
518
  try {
517
519
  this.#applySnapshot(await this.#transport().snapshot());
518
520
  } catch {