@niscorp/moss 0.2.4 → 0.3.2

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/node.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { IncomingMessage } from 'node:http';
2
2
  import { Duplex } from 'node:stream';
3
- import { k as DocumentConfig, Z as SocketAccept, z as MossServer, A as NiscApp, N as NiscRuntime } from './document-Jhfii6kd.cjs';
3
+ import { k as DocumentConfig, Z as SocketAccept, z as MossServer, A as NiscApp, N as NiscRuntime } from './document-D9khv9jI.cjs';
4
4
  import '@niscorp/nova/document';
5
5
  import '@niscorp/nova';
6
6
  import '@niscorp/vex';
package/dist/node.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { IncomingMessage } from 'node:http';
2
2
  import { Duplex } from 'node:stream';
3
- import { k as DocumentConfig, Z as SocketAccept, z as MossServer, A as NiscApp, N as NiscRuntime } from './document-Jhfii6kd.js';
3
+ import { k as DocumentConfig, Z as SocketAccept, z as MossServer, A as NiscApp, N as NiscRuntime } from './document-D9khv9jI.js';
4
4
  import '@niscorp/nova/document';
5
5
  import '@niscorp/nova';
6
6
  import '@niscorp/vex';
package/dist/node.js CHANGED
@@ -1,5 +1,5 @@
1
- export { MOSS_PATHS, attachSocket, mountSite, serve } from './chunk-CDNJ2CBA.js';
2
- import './chunk-D6E4SV6F.js';
1
+ export { MOSS_PATHS, attachSocket, mountSite, serve } from './chunk-SUVDISEG.js';
2
+ import './chunk-ZP3C53AC.js';
3
3
  import './chunk-ZOEUEMDX.js';
4
4
  //# sourceMappingURL=node.js.map
5
5
  //# sourceMappingURL=node.js.map
@@ -284,10 +284,10 @@ var trapBack = (handler) => {
284
284
  window.removeEventListener("popstate", onPopState);
285
285
  };
286
286
  };
287
- var followTitle = (api, subscribe) => {
287
+ var followHead = (api, subscribe) => {
288
288
  if (typeof document === "undefined") return () => void 0;
289
- const keep = document$1.createTitleKeeper(document);
290
- const read = () => keep(document$1.headOf(api)?.head);
289
+ const keep = document$1.createHeadKeeper(document);
290
+ const read = () => keep(document$1.headOf(api)?.elements);
291
291
  read();
292
292
  return subscribe(read);
293
293
  };
@@ -303,11 +303,11 @@ var createTerminal = (config) => {
303
303
  };
304
304
  const mount = target(api);
305
305
  const unsubscribe = wire.subscribe(mount.update);
306
- const stopTitle = followTitle(api, wire.subscribe);
306
+ const stopHead = followHead(api, wire.subscribe);
307
307
  return {
308
308
  destroy: () => {
309
309
  unsubscribe();
310
- stopTitle();
310
+ stopHead();
311
311
  mount.destroy();
312
312
  }
313
313
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/socket.ts","../../src/delta.ts","../../src/client/index.ts","../../src/terminal/hotkey.ts","../../src/terminal/history.ts","../../src/terminal/title.ts","../../src/terminal/index.ts"],"names":["createTitleKeeper","headOf"],"mappings":";;;;;;AAmGO,IAAM,QAAA,GAAW,CAAA;AACjB,IAAM,YAAA,GAAe,CAAA;AAGrB,IAAM,mBAAA,GAAsB,IAAA;AAI5B,IAAM,gBAAA,GAAmB,IAAA;AAWzB,IAAM,uBAAA,GAA0B,IAAA;;;ACzChC,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,GAAA,KAAoC;AAC3E,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,MAAM,GAAA,EAAK;AACpB,IAAA,IAAI,EAAA,CAAG,CAAC,CAAA,KAAM,CAAA,EAAG;AACf,MAAA,GAAA,IAAO,GAAG,CAAC,CAAA;AACX,MAAA;AAAA,IACF;AACA,IAAA,MAAM,GAAG,MAAA,EAAQ,MAAM,CAAA,GAAI,EAAA;AAC3B,IAAA,IAAI,SAAS,CAAA,IAAK,MAAA,GAAS,KAAK,MAAA,GAAS,MAAA,GAAS,KAAK,MAAA,EAAQ;AAC7D,MAAA,MAAM,IAAI,MAAM,CAAA,iBAAA,EAAoB,MAAM,IAAI,MAAM,CAAA,sBAAA,EAAyB,IAAA,CAAK,MAAM,CAAA,C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,IAAA,CAAK,MAAA;AAC3B,IAAA,MAAA,GAAS,eAAe,EAAE,MAAA,EAAQ,SAAS,KAAK,CAAA,EAAG,MAAM,CAAA;AAAA,EAC3D,CAAA;AAEA,EAAA,MAAM,KAAA,GAAQ,MAAY,IAAA,CAAK,KAAA,EAAM;AACrC,EAAA,MAAM,IAAA,GAAO,MAAY,IAAA,CAAK,IAAA,EAAK;AAEnC,EAAA,MAAM,cAAA,GAAiB,OAAO,OAAA,KAAY,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,SAAS,IAAI,CAAA;AAC/F,EAAA,MAAM,eAAA,GAAkB,OAAO,QAAA,KAAa,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,UAAU,KAAK,CAAA;AACnG,EAAA,MAAM,kBAAkB,MAAA,CAAO,QAAA,KAAa,KAAA,GAAQ,MAAA,GAAY,SAAS,IAAI,CAAA;AAI7E,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,cAAA,IAAiB;AACjB,MAAA,eAAA,IAAkB;AAClB,MAAA,eAAA,IAAkB;AAClB,MAAA,MAAA,CAAO,OAAA,EAAQ;AACf,MAAA,IAAI,QAAA,OAAe,OAAA,EAAQ;AAAA,IAC7B;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions; everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n | { type: 'session'; token: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N`, beside the\n// token — known before the first frame is sent); one that says nothing speaks 1,\n// which is every terminal built before the question existed. Outside the range\n// the connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\nexport const PROTOCOL = 1;\nexport const PROTOCOL_MIN = 1;\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const token = params.get('token');\n let principal: string | null = null;\n if (token !== null && token !== '') {\n principal = await ctx.session(token);\n if (principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n","import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\n\n// ═══════════════════════════════════════════════════════════════\n// The wire — moss's protocol client, the other end of ../socket. Plain\n// code: a token slot, a websocket with reconnect, and session lifecycle —\n// a `session` message (login redeemed server-side) stores the token and\n// reconnects authenticated; a 4403 close clears it and reconnects\n// anonymous (the lock screen is the anonymous principal's application,\n// served like everything else). Rendering the snapshot is the app's\n// (framework's) business; nothing framework-shaped lives here.\n//\n// The wire never reaches for globals: everything host-shaped — where the\n// token lives, how a socket is constructed, what url \"here\" means — comes\n// in as a `WireEnv`. `browserEnv` (the default) is localStorage + location;\n// `./node` ships `nodeEnv` (a token file, an explicit url). The socket API\n// itself is WHATWG-standard in every host (browser, Node ≥22, Bun), so an\n// env only constructs it.\n// ═══════════════════════════════════════════════════════════════\n\n// Where the session token lives between connects.\nexport type WireTokenStore = {\n load: () => string | null;\n save: (token: string) => void;\n clear: () => void;\n};\n\n// The host seam: what the wire would otherwise take from globals.\nexport type WireEnv = {\n tokens: WireTokenStore;\n // construct a socket for this url — `new WebSocket(url)` in every host\n socket: (url: string) => WebSocket;\n // the socket url when `config.url` is absent\n defaultUrl: () => string;\n};\n\nexport type WireConfig = {\n // The socket url; default: `env.defaultUrl()`.\n url?: string;\n // The host environment; default: `browserEnv()`.\n env?: WireEnv;\n // Accept canvas frames as DELTAS against the last frame received (default:\n // off). Both ends have to want it: this tells the server the terminal can\n // rebuild them, and the server sends them only if `runtime.shellFrameDelta`\n // is on and the delta is decisively smaller. Nothing else about the terminal\n // changes — the snapshot it renders is identical either way. See DOCS.md\n // § Frame deltas.\n delta?: boolean;\n // The screen the page already shows — the snapshot a server-rendered\n // document carries (`readDocumentSnapshot`). The wire starts from it instead\n // of from nothing, so the first render matches the HTML and the first frames\n // off the socket confirm it rather than paint it. Absent, or made for\n // somebody else (see `DocumentSnapshot.principal`): the wire starts empty, as\n // it always has.\n initial?: DocumentSnapshot;\n // The path this terminal is on, named on the socket so the server can tell a\n // page's terminal from the app's (a page is served a shell of its own, for\n // this connection alone). Default: the path the page's snapshot was drawn\n // for; a page that was not drawn on the server passes `location.pathname`.\n path?: string;\n};\n\n// What a server-rendered document carries beside its HTML.\nexport type DocumentSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // The id seed an anonymous page's shell was built under; named on the first\n // connect so the socket's shell mints the same instance ids.\n seed?: string;\n // Whether the page was rendered for a signed-in principal. A page rendered\n // for nobody is not this terminal's screen if it holds a token, and the other\n // way round — the wire then starts empty rather than from the wrong screen.\n principal: boolean;\n // The path it was drawn for.\n path?: string;\n // False when nothing on the drawn screen can still happen: the trees are the\n // whole of it, and the wire opens no socket at all (status `static`). Absent\n // is live — a page that does not say is not concluded finished.\n live?: boolean;\n};\n\n// The id of the element a document carries its snapshot in.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\n// Read the snapshot out of the page, if it has one. Never throws: a page\n// without one, or with one that does not parse, is a page that was not\n// server-rendered, and the terminal starts the way it always has.\nexport const readDocumentSnapshot = (doc: Pick<Document, 'getElementById'> = document): DocumentSnapshot | undefined => {\n try {\n const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;\n if (text === undefined || text === null || text === '') return undefined;\n const parsed: unknown = JSON.parse(text);\n if (parsed === null || typeof parsed !== 'object') return undefined;\n const { frame, trees, seed, principal, path, live } = parsed as Record<string, unknown>;\n if (!Array.isArray(frame) || trees === null || typeof trees !== 'object' || typeof principal !== 'boolean') return undefined;\n return {\n frame: frame as RenderNode[],\n trees: trees as Record<string, RenderNode[]>,\n principal,\n ...(typeof seed === 'string' ? { seed } : {}),\n ...(typeof path === 'string' ? { path } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n } catch {\n return undefined;\n }\n};\n\nexport type WireSnapshot = {\n // the frame: the canvas ARRANGEMENT — a served layout whose CanvasSlot\n // markers resolve against `trees`\n frame: RenderNode[];\n // the current tree per canvas id\n trees: ReadonlyMap<string, RenderNode[]>;\n};\n\n// The socket's health, as a renderer needs it: `connecting` (a connect is in\n// flight or scheduled), `open`, `closed` (lost; a retry will flip it back to\n// connecting). Status changes notify subscribers like snapshot changes do —\n// a terminal that renders nothing on a dead socket is indistinguishable from\n// a working terminal rendering an empty app, so the state must be readable.\n// `incompatible`: this terminal and the server speak protocols the other\n// cannot (see PROTOCOL in ../socket). Terminal state — the wire stops retrying,\n// because every retry would speak the same protocol again.\n// `static`: the page was drawn on the server and nothing on it can still\n// happen, so no socket was opened. Not a fault and not a wait — `reset` (or a\n// token arriving) connects after all.\nexport type WireStatus = 'connecting' | 'open' | 'closed' | 'incompatible' | 'static';\n\nexport type Wire = {\n subscribe: (listener: () => void) => () => void;\n snapshot: () => WireSnapshot;\n status: () => WireStatus;\n // an event from inside a canvas, tagged with the canvas it came from\n dispatch: (canvasId: string, event: NovaEvent) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Ask the server to throw this session's shell away and serve a fresh one —\n // the escape from a wedged shell, and the only one that can work. The shell\n // is SERVER state keyed by principal: dropping the token here would just\n // hand us a throwaway anonymous shell, and signing back in would reattach\n // to the same wreck. On a dead socket this reconnects instead, which is the\n // same recovery one layer down.\n reset: () => void;\n // Undo the shell's last navigation. Fire-and-forget by design: what comes\n // back is whatever canvases moved, over the same stream every other change\n // arrives on — the terminal never holds a location to keep in step.\n back: () => void;\n // Jump to an ancestor already on a canvas's stack — one message the shell\n // executes atomically, rather than N back gestures racing each other.\n popTo: (canvas: string, instance: string) => void;\n dispose: () => void;\n};\n\ntype ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n | { type: 'resync' }\n | { type: 'reset' }\n | { type: 'back' }\n | { type: 'popTo'; canvas: string; instance: string };\n\nconst EMPTY: WireSnapshot = { frame: [], trees: new Map() };\n\n// The browser host: token in localStorage, url derived from location, the\n// page's WebSocket. The try/catches keep a storage-less context (private\n// mode, sandboxed iframe) alive — the session just lives for this page only.\n//\n// `cookie: true` keeps a COPY of the token in a cookie of the same name, written\n// and cleared with the stored one. A page request carries cookies and nothing\n// else, so this is what lets a server render the document for whoever is asking.\n// The cookie is only ever read to render a page: every other surface still wants\n// the token itself (the socket's URL, a Bearer header), so it adds no way in.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n const mirror = (token: string | null): void => {\n if (config.cookie !== true) return;\n try {\n const secure = window.location.protocol === 'https:' ? '; Secure' : '';\n document.cookie =\n token === null\n ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}`\n : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;\n } catch {\n /* no document, or cookies refused — the page is simply rendered for nobody */\n }\n };\n return {\n tokens: {\n load: () => {\n try {\n const token = window.localStorage.getItem(tokenKey);\n // Level the copy with the stored one — a token put there by something\n // other than this wire (a sign-in handoff page) reaches the cookie on\n // the first load after it, and a token that is gone takes its copy along.\n mirror(token);\n return token;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n window.localStorage.setItem(tokenKey, token);\n } catch {\n /* storage unavailable — the session lives for this page only */\n }\n mirror(token);\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n mirror(null);\n },\n },\n socket: (url) => new WebSocket(url),\n defaultUrl: () => {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}/socket`;\n },\n };\n};\n\nexport const createWire = (config: WireConfig = {}): Wire => {\n const env = config.env ?? browserEnv();\n\n let token = env.tokens.load();\n // The page's own snapshot, when it was rendered for who this terminal is —\n // signed in and holding a token, or neither. Anything else is somebody else's\n // screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null) ? config.initial : undefined;\n let snapshot: WireSnapshot = initial === undefined ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };\n // Named on the FIRST connect only: it belongs to the page's own shell, and a\n // later connect (a retry, another principal) is not that shell.\n let seed = initial?.seed;\n const path = config.path ?? config.initial?.path;\n let status: WireStatus = 'connecting';\n // Set by a protocol mismatch in either direction; ends the reconnect loop.\n let incompatible = false;\n let socket: WebSocket | null = null;\n let retry: ReturnType<typeof setTimeout> | undefined;\n // Consecutive failed connects — resets to 0 the moment one opens. Drives the\n // reconnect backoff so a dead server is polled ever more slowly, not every\n // second forever.\n let attempts = 0;\n let disposed = false;\n const listeners = new Set<() => void>();\n const publishSnapshot = (next: WireSnapshot): void => {\n snapshot = next;\n for (const listener of listeners) listener();\n };\n const setStatus = (next: WireStatus): void => {\n if (status === next) return;\n status = next;\n for (const listener of listeners) listener();\n };\n\n const url = (): string => config.url ?? env.defaultUrl();\n\n // Only on an OPEN socket, and never queued — the posture `back` and `popTo`\n // always had, now everybody's. A page rendered server-side is on screen\n // before the socket is, so there is a moment in which something can be\n // pressed with nothing to send it over: that press is dropped, not held. An\n // intention replayed against a screen that may have moved is worse than one\n // lost, and a browser socket that is still connecting throws on `send`.\n const send = (message: ClientMessage): void => {\n if (socket === null || status !== 'open') return;\n socket.send(JSON.stringify(message));\n };\n\n // The last `render` message TEXT per canvas — the base a delta is written\n // against, byte for byte as the server holds it. Only populated when deltas\n // are on; cleared on every connect, because attaching serves whole frames and\n // a base carried across a reconnect is a base the server never assumed.\n const bases = new Map<string, string>();\n\n const connect = (): void => {\n if (disposed) return;\n setStatus('connecting');\n bases.clear();\n const params: string[] = [];\n if (token !== null) params.push(`token=${encodeURIComponent(token)}`);\n params.push(`protocol=${PROTOCOL}`);\n if (config.delta === true) params.push('delta=1');\n if (seed !== undefined) params.push(`seed=${encodeURIComponent(seed)}`);\n seed = undefined;\n if (path !== undefined) params.push(`path=${encodeURIComponent(path)}`);\n const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join('&')}` : ''}`);\n socket = ws;\n // A connection that opens is a healthy connection: forget the backoff.\n ws.onopen = () => {\n attempts = 0;\n setStatus('open');\n };\n ws.onmessage = (e) => {\n const text = String(e.data);\n const data = JSON.parse(text) as {\n type: string;\n canvas?: string;\n tree?: RenderNode[];\n ops?: DeltaOp[];\n hash?: number;\n protocol?: number;\n token?: string;\n code?: string;\n message?: string;\n };\n if (data.type === 'render' && data.canvas !== undefined && data.tree !== undefined) {\n if (config.delta === true) bases.set(data.canvas, text);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });\n } else if (data.type === 'render-delta' && data.canvas !== undefined && data.ops !== undefined && data.hash !== undefined) {\n // Rebuild, then PROVE it. Anything short of the server's own checksum\n // and we would be rendering a frame nobody authored — so every failure\n // here takes the one exit that always works: ask for whole frames.\n // Never a thrown error and never a partial apply; a terminal that goes\n // blank on a bad delta is worse than one that costs a round trip.\n const base = bases.get(data.canvas);\n let rebuilt: string | null = null;\n if (base !== undefined) {\n try {\n const candidate = applyDelta(base, data.ops);\n rebuilt = frameHash(candidate) === data.hash ? candidate : null;\n } catch {\n rebuilt = null;\n }\n }\n if (rebuilt === null) {\n console.warn(`[moss/wire] canvas \"${data.canvas}\": delta did not rebuild the server's frame — resyncing.`);\n bases.delete(data.canvas);\n send({ type: 'resync' });\n return;\n }\n const frame = JSON.parse(rebuilt) as { canvas: string; tree: RenderNode[] };\n bases.set(data.canvas, rebuilt);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });\n } else if (data.type === 'frame' && data.tree !== undefined) {\n publishSnapshot({ ...snapshot, frame: data.tree });\n } else if (data.type === 'session' && typeof data.token === 'string') {\n // Login redeemed server-side: become that principal.\n become(data.token);\n } else if (data.type === 'error') {\n // Diagnostics, not authority — surfaced, never swallowed: a wire that\n // silently stops updating is the worst thing to debug. `invalid_token`\n // arrives here too, from the server's revalidation pass, and it is\n // worth the line: the AUTHORITY is the 4401 close that follows (see\n // onclose), and this is the breadcrumb saying the session expired\n // rather than the network dropping.\n console.warn(`[moss/wire] server error${data.code !== undefined ? ` (${data.code})` : ''}: ${data.message ?? ''}`);\n } else if (data.type === 'hello' && (data.protocol ?? 1) < PROTOCOL_MIN) {\n // The other half of the handshake: the server checked this terminal on\n // the upgrade; this checks the server. One that predates the question\n // sends no `protocol` and speaks 1.\n console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}–${PROTOCOL}. The server has not been updated yet.`);\n incompatible = true;\n ws.close();\n } else if (data.type !== 'hello' && data.type !== 'catalog') {\n // hello/catalog are known and deliberately ignored (the terminal is\n // grant-blind — it renders what it is served, never what it may do);\n // anything else is protocol drift worth a shout.\n console.warn(`[moss/wire] unhandled server message: ${data.type}`);\n }\n };\n // The socket is ephemeral, the shell is durable: reconnect re-sends\n // current state. Two application close codes are recoveries, not retries —\n // SIGNED_OUT (a deliberate revoke) and INVALID_TOKEN (the stored token went\n // stale; retrying WITH it would loop forever) both drop the token and\n // reconnect anonymous (the served lock screen). Every other close backs off\n // and retries carrying the current token.\n ws.onclose = (e) => {\n if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {\n incompatible = true;\n setStatus('incompatible');\n return;\n }\n setStatus('closed');\n if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {\n become(null);\n return;\n }\n if (!disposed) scheduleReconnect();\n };\n };\n\n // Exponential backoff with jitter, capped: a dead server is polled ever more\n // slowly (never faster than ~½s, never slower than the cap), and the jitter\n // spreads a thundering herd of terminals reconnecting on the same outage.\n const RECONNECT_CAP_MS = 30_000;\n const scheduleReconnect = (): void => {\n const ceiling = Math.min(RECONNECT_CAP_MS, 1000 * 2 ** attempts);\n attempts += 1;\n const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n retry = setTimeout(connect, delay);\n };\n\n // A different principal — possibly none — is a different application:\n // store the token, blank the screen, reconnect.\n const become = (next: string | null): void => {\n if (next === null) env.tokens.clear();\n else env.tokens.save(next);\n token = next;\n clearTimeout(retry);\n attempts = 0; // a new principal is a fresh session — start backoff clean\n publishSnapshot(EMPTY);\n const old = socket;\n socket = null;\n if (old !== null) {\n old.onclose = null;\n old.close();\n }\n connect();\n };\n\n // A drawn page with nothing left to happen needs no socket. Everything that\n // would later need one — `reset`, a token arriving — connects by itself.\n if (initial?.live === false) status = 'static';\n else connect();\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n snapshot: () => snapshot,\n status: () => status,\n dispatch: (canvasId, event) => send({ type: 'event', canvas: canvasId, event: event as unknown as Record<string, unknown> }),\n publish: (channel, payload) => send(payload === undefined ? { type: 'publish', channel } : { type: 'publish', channel, payload }),\n // Only on an open socket, and deliberately not queued: a back pressed while\n // the connection is down is a gesture about a screen the person is no\n // longer being served, and replaying it on reconnect would move them\n // somewhere they asked to go some seconds and one outage ago.\n back: () => {\n if (socket === null || status !== 'open') return;\n send({ type: 'back' });\n },\n // Same posture as `back`: only on an open socket, never queued. A jump\n // replayed on reconnect would move somebody to where they wanted to be\n // one outage ago.\n popTo: (canvas: string, instance: string) => {\n if (socket === null || status !== 'open') return;\n send({ type: 'popTo', canvas, instance });\n },\n reset: () => {\n if (disposed) return;\n // Open: ask the server, and the fresh frame arrives on this same socket.\n // Asked of our OWN status rather than `readyState`, because the socket\n // is whatever the host env constructed and the status is ours.\n if (socket !== null && status === 'open') {\n send({ type: 'reset' });\n return;\n }\n // Not open: the backoff may have us waiting half a minute for a retry,\n // and somebody pressing reset is telling us they are waiting NOW. Jump\n // the queue — reattaching re-sends the current trees anyway.\n clearTimeout(retry);\n attempts = 0;\n connect();\n },\n dispose: () => {\n disposed = true;\n status = 'closed'; // sync truth for late readers; no notification after dispose\n clearTimeout(retry);\n socket?.close();\n },\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The live-swap hotkey — isolated here because it is the one imperative,\n// gimmicky corner of the terminal (a render target is not app state, so it\n// can't be a nova action; it's client chrome). Keyed on `event.key`, the\n// CHARACTER the key produces, so a combo matches the key the user actually\n// presses on any layout — `event.code` would bind a physical QWERTY position\n// (the key labelled Y sits elsewhere on QWERTZ/AZERTY). Use letter keys, not\n// punctuation, so Shift never remaps the character.\n// ═══════════════════════════════════════════════════════════════\n\nexport type HotkeyDisposer = () => void;\n\n// Attach `handler` to a keydown matching `spec` (e.g. \"ctrl+shift+y\"); returns\n// a disposer. Matches modifiers exactly, so \"ctrl+shift+y\" never fires on\n// \"ctrl+shift+alt+y\".\nexport const onHotkey = (spec: string, handler: () => void): HotkeyDisposer => {\n const parts = spec.toLowerCase().split('+');\n const key = parts[parts.length - 1] ?? '';\n const mods = new Set(parts.slice(0, -1));\n const listener = (event: KeyboardEvent): void => {\n if (\n event.key.toLowerCase() === key &&\n event.ctrlKey === mods.has('ctrl') &&\n event.shiftKey === mods.has('shift') &&\n event.altKey === mods.has('alt') &&\n event.metaKey === (mods.has('meta') || mods.has('cmd'))\n ) {\n event.preventDefault();\n handler();\n }\n };\n window.addEventListener('keydown', listener);\n return () => window.removeEventListener('keydown', listener);\n};\n","// ═══════════════════════════════════════════════════════════════\n// The browser's back button, caught.\n//\n// ⟲ IT USED TO UNLOAD THE APPLICATION. A moss terminal never touched the URL,\n// so a tab held exactly one history entry and back meant \"leave the page\" —\n// the socket dropped, the shell went unattended, and somebody who wanted to\n// close a screen got a blank tab instead. Nothing was lost (the shell is\n// durable, keyed by principal, and a reload reattaches to it) but nobody\n// pressing back is thinking about that.\n//\n// What it does instead: keep ONE spare history entry ahead of the page and\n// spend it on every press. Back consumes the spare, this puts another one\n// straight back, and the gesture is handed to the terminal — which sends it up\n// the wire, where the shell that owns the navigation decides what back means.\n//\n// The URL never changes. That is the honest position while location lives on\n// the SERVER: the shell is keyed by principal, not by tab, so an address bar\n// would be a per-tab claim on state two tabs share. When deep links arrive they\n// arrive as a projection of the shell's own location, and this file is where\n// the gesture will already be.\n// ═══════════════════════════════════════════════════════════════\n\nexport type BackTrapDisposer = () => void;\n\n// Marks the entry as ours, so a host that keeps its own history state can tell\n// this one apart. Nothing reads it yet; a debugger looking at `history.state`\n// deserves to find a name rather than an empty object.\nconst SENTINEL = { nisc: 'terminal-back' } as const;\n\n// Catch the host's back gesture and call `handler` instead of letting the page\n// unload. A no-op (and a disposer that does nothing) wherever there is no\n// history to trap — a TTY, a TUI, a plain process — so the conductor can ask\n// for it unconditionally.\nexport const trapBack = (handler: () => void): BackTrapDisposer => {\n if (typeof window === 'undefined') return () => undefined;\n const history = window.history as History | undefined;\n if (history === undefined || typeof history.pushState !== 'function') return () => undefined;\n\n // The spare. `pushState` with no url keeps the current address, so this adds\n // an entry without changing what the address bar says or asking the server\n // for anything.\n const spare = (): void => {\n try {\n history.pushState(SENTINEL, '');\n } catch {\n // A sandboxed document can refuse this. Back then behaves as it always\n // did rather than throwing on the way out of a keypress.\n }\n };\n\n const onPopState = (): void => {\n // One entry was just spent — replace it, then act. In that order: the\n // handler sends a message up the wire and the answer arrives on another\n // tick, and the history has to be whole before the next press, not after.\n spare();\n handler();\n };\n\n spare();\n window.addEventListener('popstate', onPopState);\n return () => {\n window.removeEventListener('popstate', onPopState);\n // The spare entry stays. It cannot be removed without navigating, and one\n // dead entry is a far smaller surprise than a navigation nobody asked for.\n };\n};\n","import { createTitleKeeper, headOf } from '@niscorp/nova/document';\nimport type { TerminalApi } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The tab's title, kept on the screen.\n//\n// A drawn page arrives with its head written (../document). From then on the\n// screen moves over the wire and the page is never fetched again, so the part\n// of a head somebody can see — the title — is read off the trees the wire\n// holds, whenever they change. A screen with no head has the page's own title.\n//\n// Terminal chrome, like the back trap beside it: the title is the terminal's\n// relationship to the surface it is painted on, the same for every render\n// target, and the app authors nothing to keep it. Where there is no document\n// (a TTY, a TUI) there is no title, and this does nothing.\n// ═══════════════════════════════════════════════════════════════\n\nexport const followTitle = (api: TerminalApi, subscribe: (listener: () => void) => () => void): (() => void) => {\n if (typeof document === 'undefined') return () => undefined;\n const keep = createTitleKeeper(document);\n const read = (): void => keep(headOf(api)?.head);\n read();\n return subscribe(read);\n};\n","import type { RenderApi } from '@niscorp/nova';\nimport { createWire } from '../client';\nimport type { Wire } from '../client';\nimport { onHotkey } from './hotkey';\nimport { trapBack } from './history';\nimport { followTitle } from './title';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/terminal — the terminal, owned by the protocol that defines\n// it. A terminal is the wire (../client) plus a RENDER TARGET (react, dom,\n// console, …) painting the wire's snapshot and sending events back. This\n// module is framework-blind: the conductor drives one target against the\n// wire; the switcher cycles targets on a hotkey, sharing one wire so the\n// session survives the swap. Targets live in the subpaths (./react, ./dom);\n// the framework-shaped code stays there, never here.\n// ═══════════════════════════════════════════════════════════════\n\n// What a target renders against — nova core's `RenderApi`: the wire's snapshot\n// as pull functions (frame + per-canvas trees) plus the event sinks (dispatch\n// tagged by canvas, publish). Aliased, not redeclared — the dom adapter, the\n// react adapter, and this conductor share ONE contract, so a target written\n// for nova's dom view drops straight onto the wire. A target never touches the\n// wire directly.\nexport type TerminalApi = RenderApi;\n\n// A mounted target: re-render on demand, tear down on swap.\nexport type TerminalMount = { update: () => void; destroy: () => void };\n\n// A render target: paint the api onto the target's own surface, return the\n// mount handle. The surface — a DOM root, a stdio pair — is construction\n// config on the concrete target (`reactTarget({ root, … })`, `domTarget({\n// root })`), never part of this contract: the conductor stays surface-blind\n// and runs anywhere the wire does. A target renders once on mount; the\n// conductor calls `update` on every wire change.\nexport type Target = (api: TerminalApi) => TerminalMount;\n\n// The conductor: one target, one wire. Subscribes the target's `update` to\n// the wire and routes events back. Nothing framework-shaped.\nexport const createTerminal = (config: { target: Target; wire: Wire }): { destroy: () => void } => {\n const { target, wire } = config;\n const api: TerminalApi = {\n frame: () => wire.snapshot().frame,\n canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],\n dispatch: (id, event) => wire.dispatch(id, event),\n publish: (channel, payload) => wire.publish(channel, payload),\n };\n const mount = target(api);\n const unsubscribe = wire.subscribe(mount.update);\n const stopTitle = followTitle(api, wire.subscribe);\n return {\n destroy: () => {\n unsubscribe();\n stopTitle();\n mount.destroy();\n },\n };\n};\n\nexport type MountTerminalConfig = {\n // render targets by name; the hotkey cycles them in insertion order\n targets: Record<string, Target>;\n // e.g. \"ctrl+shift+t\" — the live render-target swap. Omit for no swapping.\n swapKey?: string;\n // e.g. \"ctrl+shift+r\" — ask the server for a fresh shell. Omit for no key.\n //\n // The one control that must work when nothing else does. It sits on a\n // keystroke for the same reason the swap does — it acts on the terminal's\n // relationship to the server, not on anything the app models — but the\n // reason it exists at all is stronger: a shell lives on the SERVER, keyed by\n // principal, so a broken one survives every gesture a client can make alone.\n // Reloading reattaches to it. Clearing the token and signing back in\n // reattaches to it. Without a key that says \"throw it away\", somebody\n // watching a dead screen has no move left.\n resetKey?: string;\n // Catch the host's BACK gesture — the browser's back button — and send it up\n // the wire instead of letting it unload the page. Default: on, wherever a\n // history exists to catch (see ./history); nothing at all in a TTY or a TUI.\n //\n // Terminal chrome for the same reason the swap and reset keys are: back is\n // the terminal's relationship to the surface it is painted on, and the app\n // authors nothing to receive it. What back MEANS is decided a layer up, by\n // the shell that owns the navigation.\n trapBack?: boolean;\n // which target to mount first (default: the first key)\n initial?: string;\n // inject an existing wire (shared across swaps), or let the terminal make\n // one — `url` seeds a self-made wire (default: /socket on the host).\n wire?: Wire;\n url?: string;\n};\n\n// The switcher: mount a terminal that can hot-swap its render target on a\n// keystroke, over ONE wire (created here unless injected) so the socket,\n// session, and current trees survive the swap. The hotkey is the one legit\n// piece of imperative client chrome — a render target is not app state, so\n// it is not a nova action; it lives here, in the terminal.\nexport const mountTerminal = (config: MountTerminalConfig): { swap: () => void; reset: () => void; back: () => void; destroy: () => void } => {\n const keys = Object.keys(config.targets);\n if (keys.length === 0) throw new Error('mountTerminal: at least one target is required');\n\n const ownsWire = config.wire === undefined;\n const wire = config.wire ?? createWire(config.url !== undefined ? { url: config.url } : {});\n\n const targetAt = (i: number): Target => {\n const key = keys[i];\n const target = key === undefined ? undefined : config.targets[key];\n if (target === undefined) throw new Error(`mountTerminal: no target at index ${i}`);\n return target;\n };\n\n const start = config.initial === undefined ? 0 : keys.indexOf(config.initial);\n let index = start < 0 ? 0 : start;\n let active = createTerminal({ target: targetAt(index), wire });\n\n const swap = (): void => {\n active.destroy();\n index = (index + 1) % keys.length;\n active = createTerminal({ target: targetAt(index), wire });\n };\n\n const reset = (): void => wire.reset();\n const back = (): void => wire.back();\n\n const disposeSwapKey = config.swapKey === undefined ? undefined : onHotkey(config.swapKey, swap);\n const disposeResetKey = config.resetKey === undefined ? undefined : onHotkey(config.resetKey, reset);\n const disposeBackTrap = config.trapBack === false ? undefined : trapBack(back);\n\n // All three are returned so a host can bind its own control (a button, a\n // console call) — the keys and the trap are a convenience, not the only way in.\n return {\n swap,\n reset,\n back,\n destroy: () => {\n disposeSwapKey?.();\n disposeResetKey?.();\n disposeBackTrap?.();\n active.destroy();\n if (ownsWire) wire.dispose();\n },\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/socket.ts","../../src/delta.ts","../../src/client/index.ts","../../src/terminal/hotkey.ts","../../src/terminal/history.ts","../../src/terminal/head.ts","../../src/terminal/index.ts"],"names":["createHeadKeeper","headOf"],"mappings":";;;;;;AAmGO,IAAM,QAAA,GAAW,CAAA;AACjB,IAAM,YAAA,GAAe,CAAA;AAGrB,IAAM,mBAAA,GAAsB,IAAA;AAI5B,IAAM,gBAAA,GAAmB,IAAA;AAWzB,IAAM,uBAAA,GAA0B,IAAA;;;ACzChC,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,GAAA,KAAoC;AAC3E,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AQ;AACf,MAAA,IAAI,QAAA,OAAe,OAAA,EAAQ;AAAA,IAC7B;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions; everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n | { type: 'session'; token: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N`, beside the\n// token — known before the first frame is sent); one that says nothing speaks 1,\n// which is every terminal built before the question existed. Outside the range\n// the connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\nexport const PROTOCOL = 1;\nexport const PROTOCOL_MIN = 1;\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const token = params.get('token');\n let principal: string | null = null;\n if (token !== null && token !== '') {\n principal = await ctx.session(token);\n if (principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n","import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\n\n// ═══════════════════════════════════════════════════════════════\n// The wire — moss's protocol client, the other end of ../socket. Plain\n// code: a token slot, a websocket with reconnect, and session lifecycle —\n// a `session` message (login redeemed server-side) stores the token and\n// reconnects authenticated; a 4403 close clears it and reconnects\n// anonymous (the lock screen is the anonymous principal's application,\n// served like everything else). Rendering the snapshot is the app's\n// (framework's) business; nothing framework-shaped lives here.\n//\n// The wire never reaches for globals: everything host-shaped — where the\n// token lives, how a socket is constructed, what url \"here\" means — comes\n// in as a `WireEnv`. `browserEnv` (the default) is localStorage + location;\n// `./node` ships `nodeEnv` (a token file, an explicit url). The socket API\n// itself is WHATWG-standard in every host (browser, Node ≥22, Bun), so an\n// env only constructs it.\n// ═══════════════════════════════════════════════════════════════\n\n// Where the session token lives between connects.\nexport type WireTokenStore = {\n load: () => string | null;\n save: (token: string) => void;\n clear: () => void;\n};\n\n// The host seam: what the wire would otherwise take from globals.\nexport type WireEnv = {\n tokens: WireTokenStore;\n // construct a socket for this url — `new WebSocket(url)` in every host\n socket: (url: string) => WebSocket;\n // the socket url when `config.url` is absent\n defaultUrl: () => string;\n};\n\nexport type WireConfig = {\n // The socket url; default: `env.defaultUrl()`.\n url?: string;\n // The host environment; default: `browserEnv()`.\n env?: WireEnv;\n // Accept canvas frames as DELTAS against the last frame received (default:\n // off). Both ends have to want it: this tells the server the terminal can\n // rebuild them, and the server sends them only if `runtime.shellFrameDelta`\n // is on and the delta is decisively smaller. Nothing else about the terminal\n // changes — the snapshot it renders is identical either way. See DOCS.md\n // § Frame deltas.\n delta?: boolean;\n // The screen the page already shows — the snapshot a server-rendered\n // document carries (`readDocumentSnapshot`). The wire starts from it instead\n // of from nothing, so the first render matches the HTML and the first frames\n // off the socket confirm it rather than paint it. Absent, or made for\n // somebody else (see `DocumentSnapshot.principal`): the wire starts empty, as\n // it always has.\n initial?: DocumentSnapshot;\n // The path this terminal is on, named on the socket so the server can tell a\n // page's terminal from the app's (a page is served a shell of its own, for\n // this connection alone). Default: the path the page's snapshot was drawn\n // for; a page that was not drawn on the server passes `location.pathname`.\n path?: string;\n};\n\n// What a server-rendered document carries beside its HTML.\nexport type DocumentSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // The id seed an anonymous page's shell was built under; named on the first\n // connect so the socket's shell mints the same instance ids.\n seed?: string;\n // Whether the page was rendered for a signed-in principal. A page rendered\n // for nobody is not this terminal's screen if it holds a token, and the other\n // way round — the wire then starts empty rather than from the wrong screen.\n principal: boolean;\n // The path it was drawn for.\n path?: string;\n // False when nothing on the drawn screen can still happen: the trees are the\n // whole of it, and the wire opens no socket at all (status `static`). Absent\n // is live — a page that does not say is not concluded finished.\n live?: boolean;\n};\n\n// The id of the element a document carries its snapshot in.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\n// Read the snapshot out of the page, if it has one. Never throws: a page\n// without one, or with one that does not parse, is a page that was not\n// server-rendered, and the terminal starts the way it always has.\nexport const readDocumentSnapshot = (doc: Pick<Document, 'getElementById'> = document): DocumentSnapshot | undefined => {\n try {\n const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;\n if (text === undefined || text === null || text === '') return undefined;\n const parsed: unknown = JSON.parse(text);\n if (parsed === null || typeof parsed !== 'object') return undefined;\n const { frame, trees, seed, principal, path, live } = parsed as Record<string, unknown>;\n if (!Array.isArray(frame) || trees === null || typeof trees !== 'object' || typeof principal !== 'boolean') return undefined;\n return {\n frame: frame as RenderNode[],\n trees: trees as Record<string, RenderNode[]>,\n principal,\n ...(typeof seed === 'string' ? { seed } : {}),\n ...(typeof path === 'string' ? { path } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n } catch {\n return undefined;\n }\n};\n\nexport type WireSnapshot = {\n // the frame: the canvas ARRANGEMENT — a served layout whose CanvasSlot\n // markers resolve against `trees`\n frame: RenderNode[];\n // the current tree per canvas id\n trees: ReadonlyMap<string, RenderNode[]>;\n};\n\n// The socket's health, as a renderer needs it: `connecting` (a connect is in\n// flight or scheduled), `open`, `closed` (lost; a retry will flip it back to\n// connecting). Status changes notify subscribers like snapshot changes do —\n// a terminal that renders nothing on a dead socket is indistinguishable from\n// a working terminal rendering an empty app, so the state must be readable.\n// `incompatible`: this terminal and the server speak protocols the other\n// cannot (see PROTOCOL in ../socket). Terminal state — the wire stops retrying,\n// because every retry would speak the same protocol again.\n// `static`: the page was drawn on the server and nothing on it can still\n// happen, so no socket was opened. Not a fault and not a wait — `reset` (or a\n// token arriving) connects after all.\nexport type WireStatus = 'connecting' | 'open' | 'closed' | 'incompatible' | 'static';\n\nexport type Wire = {\n subscribe: (listener: () => void) => () => void;\n snapshot: () => WireSnapshot;\n status: () => WireStatus;\n // an event from inside a canvas, tagged with the canvas it came from\n dispatch: (canvasId: string, event: NovaEvent) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Ask the server to throw this session's shell away and serve a fresh one —\n // the escape from a wedged shell, and the only one that can work. The shell\n // is SERVER state keyed by principal: dropping the token here would just\n // hand us a throwaway anonymous shell, and signing back in would reattach\n // to the same wreck. On a dead socket this reconnects instead, which is the\n // same recovery one layer down.\n reset: () => void;\n // Undo the shell's last navigation. Fire-and-forget by design: what comes\n // back is whatever canvases moved, over the same stream every other change\n // arrives on — the terminal never holds a location to keep in step.\n back: () => void;\n // Jump to an ancestor already on a canvas's stack — one message the shell\n // executes atomically, rather than N back gestures racing each other.\n popTo: (canvas: string, instance: string) => void;\n dispose: () => void;\n};\n\ntype ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n | { type: 'resync' }\n | { type: 'reset' }\n | { type: 'back' }\n | { type: 'popTo'; canvas: string; instance: string };\n\nconst EMPTY: WireSnapshot = { frame: [], trees: new Map() };\n\n// The browser host: token in localStorage, url derived from location, the\n// page's WebSocket. The try/catches keep a storage-less context (private\n// mode, sandboxed iframe) alive — the session just lives for this page only.\n//\n// `cookie: true` keeps a COPY of the token in a cookie of the same name, written\n// and cleared with the stored one. A page request carries cookies and nothing\n// else, so this is what lets a server render the document for whoever is asking.\n// The cookie is only ever read to render a page: every other surface still wants\n// the token itself (the socket's URL, a Bearer header), so it adds no way in.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n const mirror = (token: string | null): void => {\n if (config.cookie !== true) return;\n try {\n const secure = window.location.protocol === 'https:' ? '; Secure' : '';\n document.cookie =\n token === null\n ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}`\n : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;\n } catch {\n /* no document, or cookies refused — the page is simply rendered for nobody */\n }\n };\n return {\n tokens: {\n load: () => {\n try {\n const token = window.localStorage.getItem(tokenKey);\n // Level the copy with the stored one — a token put there by something\n // other than this wire (a sign-in handoff page) reaches the cookie on\n // the first load after it, and a token that is gone takes its copy along.\n mirror(token);\n return token;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n window.localStorage.setItem(tokenKey, token);\n } catch {\n /* storage unavailable — the session lives for this page only */\n }\n mirror(token);\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n mirror(null);\n },\n },\n socket: (url) => new WebSocket(url),\n defaultUrl: () => {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}/socket`;\n },\n };\n};\n\nexport const createWire = (config: WireConfig = {}): Wire => {\n const env = config.env ?? browserEnv();\n\n let token = env.tokens.load();\n // The page's own snapshot, when it was rendered for who this terminal is —\n // signed in and holding a token, or neither. Anything else is somebody else's\n // screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null) ? config.initial : undefined;\n let snapshot: WireSnapshot = initial === undefined ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };\n // Named on the FIRST connect only: it belongs to the page's own shell, and a\n // later connect (a retry, another principal) is not that shell.\n let seed = initial?.seed;\n const path = config.path ?? config.initial?.path;\n let status: WireStatus = 'connecting';\n // Set by a protocol mismatch in either direction; ends the reconnect loop.\n let incompatible = false;\n let socket: WebSocket | null = null;\n let retry: ReturnType<typeof setTimeout> | undefined;\n // Consecutive failed connects — resets to 0 the moment one opens. Drives the\n // reconnect backoff so a dead server is polled ever more slowly, not every\n // second forever.\n let attempts = 0;\n let disposed = false;\n const listeners = new Set<() => void>();\n const publishSnapshot = (next: WireSnapshot): void => {\n snapshot = next;\n for (const listener of listeners) listener();\n };\n const setStatus = (next: WireStatus): void => {\n if (status === next) return;\n status = next;\n for (const listener of listeners) listener();\n };\n\n const url = (): string => config.url ?? env.defaultUrl();\n\n // Only on an OPEN socket, and never queued — the posture `back` and `popTo`\n // always had, now everybody's. A page rendered server-side is on screen\n // before the socket is, so there is a moment in which something can be\n // pressed with nothing to send it over: that press is dropped, not held. An\n // intention replayed against a screen that may have moved is worse than one\n // lost, and a browser socket that is still connecting throws on `send`.\n const send = (message: ClientMessage): void => {\n if (socket === null || status !== 'open') return;\n socket.send(JSON.stringify(message));\n };\n\n // The last `render` message TEXT per canvas — the base a delta is written\n // against, byte for byte as the server holds it. Only populated when deltas\n // are on; cleared on every connect, because attaching serves whole frames and\n // a base carried across a reconnect is a base the server never assumed.\n const bases = new Map<string, string>();\n\n const connect = (): void => {\n if (disposed) return;\n setStatus('connecting');\n bases.clear();\n const params: string[] = [];\n if (token !== null) params.push(`token=${encodeURIComponent(token)}`);\n params.push(`protocol=${PROTOCOL}`);\n if (config.delta === true) params.push('delta=1');\n if (seed !== undefined) params.push(`seed=${encodeURIComponent(seed)}`);\n seed = undefined;\n if (path !== undefined) params.push(`path=${encodeURIComponent(path)}`);\n const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join('&')}` : ''}`);\n socket = ws;\n // A connection that opens is a healthy connection: forget the backoff.\n ws.onopen = () => {\n attempts = 0;\n setStatus('open');\n };\n ws.onmessage = (e) => {\n const text = String(e.data);\n const data = JSON.parse(text) as {\n type: string;\n canvas?: string;\n tree?: RenderNode[];\n ops?: DeltaOp[];\n hash?: number;\n protocol?: number;\n token?: string;\n code?: string;\n message?: string;\n };\n if (data.type === 'render' && data.canvas !== undefined && data.tree !== undefined) {\n if (config.delta === true) bases.set(data.canvas, text);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });\n } else if (data.type === 'render-delta' && data.canvas !== undefined && data.ops !== undefined && data.hash !== undefined) {\n // Rebuild, then PROVE it. Anything short of the server's own checksum\n // and we would be rendering a frame nobody authored — so every failure\n // here takes the one exit that always works: ask for whole frames.\n // Never a thrown error and never a partial apply; a terminal that goes\n // blank on a bad delta is worse than one that costs a round trip.\n const base = bases.get(data.canvas);\n let rebuilt: string | null = null;\n if (base !== undefined) {\n try {\n const candidate = applyDelta(base, data.ops);\n rebuilt = frameHash(candidate) === data.hash ? candidate : null;\n } catch {\n rebuilt = null;\n }\n }\n if (rebuilt === null) {\n console.warn(`[moss/wire] canvas \"${data.canvas}\": delta did not rebuild the server's frame — resyncing.`);\n bases.delete(data.canvas);\n send({ type: 'resync' });\n return;\n }\n const frame = JSON.parse(rebuilt) as { canvas: string; tree: RenderNode[] };\n bases.set(data.canvas, rebuilt);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });\n } else if (data.type === 'frame' && data.tree !== undefined) {\n publishSnapshot({ ...snapshot, frame: data.tree });\n } else if (data.type === 'session' && typeof data.token === 'string') {\n // Login redeemed server-side: become that principal.\n become(data.token);\n } else if (data.type === 'error') {\n // Diagnostics, not authority — surfaced, never swallowed: a wire that\n // silently stops updating is the worst thing to debug. `invalid_token`\n // arrives here too, from the server's revalidation pass, and it is\n // worth the line: the AUTHORITY is the 4401 close that follows (see\n // onclose), and this is the breadcrumb saying the session expired\n // rather than the network dropping.\n console.warn(`[moss/wire] server error${data.code !== undefined ? ` (${data.code})` : ''}: ${data.message ?? ''}`);\n } else if (data.type === 'hello' && (data.protocol ?? 1) < PROTOCOL_MIN) {\n // The other half of the handshake: the server checked this terminal on\n // the upgrade; this checks the server. One that predates the question\n // sends no `protocol` and speaks 1.\n console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}–${PROTOCOL}. The server has not been updated yet.`);\n incompatible = true;\n ws.close();\n } else if (data.type !== 'hello' && data.type !== 'catalog') {\n // hello/catalog are known and deliberately ignored (the terminal is\n // grant-blind — it renders what it is served, never what it may do);\n // anything else is protocol drift worth a shout.\n console.warn(`[moss/wire] unhandled server message: ${data.type}`);\n }\n };\n // The socket is ephemeral, the shell is durable: reconnect re-sends\n // current state. Two application close codes are recoveries, not retries —\n // SIGNED_OUT (a deliberate revoke) and INVALID_TOKEN (the stored token went\n // stale; retrying WITH it would loop forever) both drop the token and\n // reconnect anonymous (the served lock screen). Every other close backs off\n // and retries carrying the current token.\n ws.onclose = (e) => {\n if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {\n incompatible = true;\n setStatus('incompatible');\n return;\n }\n setStatus('closed');\n if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {\n become(null);\n return;\n }\n if (!disposed) scheduleReconnect();\n };\n };\n\n // Exponential backoff with jitter, capped: a dead server is polled ever more\n // slowly (never faster than ~½s, never slower than the cap), and the jitter\n // spreads a thundering herd of terminals reconnecting on the same outage.\n const RECONNECT_CAP_MS = 30_000;\n const scheduleReconnect = (): void => {\n const ceiling = Math.min(RECONNECT_CAP_MS, 1000 * 2 ** attempts);\n attempts += 1;\n const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n retry = setTimeout(connect, delay);\n };\n\n // A different principal — possibly none — is a different application:\n // store the token, blank the screen, reconnect.\n const become = (next: string | null): void => {\n if (next === null) env.tokens.clear();\n else env.tokens.save(next);\n token = next;\n clearTimeout(retry);\n attempts = 0; // a new principal is a fresh session — start backoff clean\n publishSnapshot(EMPTY);\n const old = socket;\n socket = null;\n if (old !== null) {\n old.onclose = null;\n old.close();\n }\n connect();\n };\n\n // A drawn page with nothing left to happen needs no socket. Everything that\n // would later need one — `reset`, a token arriving — connects by itself.\n if (initial?.live === false) status = 'static';\n else connect();\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n snapshot: () => snapshot,\n status: () => status,\n dispatch: (canvasId, event) => send({ type: 'event', canvas: canvasId, event: event as unknown as Record<string, unknown> }),\n publish: (channel, payload) => send(payload === undefined ? { type: 'publish', channel } : { type: 'publish', channel, payload }),\n // Only on an open socket, and deliberately not queued: a back pressed while\n // the connection is down is a gesture about a screen the person is no\n // longer being served, and replaying it on reconnect would move them\n // somewhere they asked to go some seconds and one outage ago.\n back: () => {\n if (socket === null || status !== 'open') return;\n send({ type: 'back' });\n },\n // Same posture as `back`: only on an open socket, never queued. A jump\n // replayed on reconnect would move somebody to where they wanted to be\n // one outage ago.\n popTo: (canvas: string, instance: string) => {\n if (socket === null || status !== 'open') return;\n send({ type: 'popTo', canvas, instance });\n },\n reset: () => {\n if (disposed) return;\n // Open: ask the server, and the fresh frame arrives on this same socket.\n // Asked of our OWN status rather than `readyState`, because the socket\n // is whatever the host env constructed and the status is ours.\n if (socket !== null && status === 'open') {\n send({ type: 'reset' });\n return;\n }\n // Not open: the backoff may have us waiting half a minute for a retry,\n // and somebody pressing reset is telling us they are waiting NOW. Jump\n // the queue — reattaching re-sends the current trees anyway.\n clearTimeout(retry);\n attempts = 0;\n connect();\n },\n dispose: () => {\n disposed = true;\n status = 'closed'; // sync truth for late readers; no notification after dispose\n clearTimeout(retry);\n socket?.close();\n },\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The live-swap hotkey — isolated here because it is the one imperative,\n// gimmicky corner of the terminal (a render target is not app state, so it\n// can't be a nova action; it's client chrome). Keyed on `event.key`, the\n// CHARACTER the key produces, so a combo matches the key the user actually\n// presses on any layout — `event.code` would bind a physical QWERTY position\n// (the key labelled Y sits elsewhere on QWERTZ/AZERTY). Use letter keys, not\n// punctuation, so Shift never remaps the character.\n// ═══════════════════════════════════════════════════════════════\n\nexport type HotkeyDisposer = () => void;\n\n// Attach `handler` to a keydown matching `spec` (e.g. \"ctrl+shift+y\"); returns\n// a disposer. Matches modifiers exactly, so \"ctrl+shift+y\" never fires on\n// \"ctrl+shift+alt+y\".\nexport const onHotkey = (spec: string, handler: () => void): HotkeyDisposer => {\n const parts = spec.toLowerCase().split('+');\n const key = parts[parts.length - 1] ?? '';\n const mods = new Set(parts.slice(0, -1));\n const listener = (event: KeyboardEvent): void => {\n if (\n event.key.toLowerCase() === key &&\n event.ctrlKey === mods.has('ctrl') &&\n event.shiftKey === mods.has('shift') &&\n event.altKey === mods.has('alt') &&\n event.metaKey === (mods.has('meta') || mods.has('cmd'))\n ) {\n event.preventDefault();\n handler();\n }\n };\n window.addEventListener('keydown', listener);\n return () => window.removeEventListener('keydown', listener);\n};\n","// ═══════════════════════════════════════════════════════════════\n// The browser's back button, caught.\n//\n// ⟲ IT USED TO UNLOAD THE APPLICATION. A moss terminal never touched the URL,\n// so a tab held exactly one history entry and back meant \"leave the page\" —\n// the socket dropped, the shell went unattended, and somebody who wanted to\n// close a screen got a blank tab instead. Nothing was lost (the shell is\n// durable, keyed by principal, and a reload reattaches to it) but nobody\n// pressing back is thinking about that.\n//\n// What it does instead: keep ONE spare history entry ahead of the page and\n// spend it on every press. Back consumes the spare, this puts another one\n// straight back, and the gesture is handed to the terminal — which sends it up\n// the wire, where the shell that owns the navigation decides what back means.\n//\n// The URL never changes. That is the honest position while location lives on\n// the SERVER: the shell is keyed by principal, not by tab, so an address bar\n// would be a per-tab claim on state two tabs share. When deep links arrive they\n// arrive as a projection of the shell's own location, and this file is where\n// the gesture will already be.\n// ═══════════════════════════════════════════════════════════════\n\nexport type BackTrapDisposer = () => void;\n\n// Marks the entry as ours, so a host that keeps its own history state can tell\n// this one apart. Nothing reads it yet; a debugger looking at `history.state`\n// deserves to find a name rather than an empty object.\nconst SENTINEL = { nisc: 'terminal-back' } as const;\n\n// Catch the host's back gesture and call `handler` instead of letting the page\n// unload. A no-op (and a disposer that does nothing) wherever there is no\n// history to trap — a TTY, a TUI, a plain process — so the conductor can ask\n// for it unconditionally.\nexport const trapBack = (handler: () => void): BackTrapDisposer => {\n if (typeof window === 'undefined') return () => undefined;\n const history = window.history as History | undefined;\n if (history === undefined || typeof history.pushState !== 'function') return () => undefined;\n\n // The spare. `pushState` with no url keeps the current address, so this adds\n // an entry without changing what the address bar says or asking the server\n // for anything.\n const spare = (): void => {\n try {\n history.pushState(SENTINEL, '');\n } catch {\n // A sandboxed document can refuse this. Back then behaves as it always\n // did rather than throwing on the way out of a keypress.\n }\n };\n\n const onPopState = (): void => {\n // One entry was just spent — replace it, then act. In that order: the\n // handler sends a message up the wire and the answer arrives on another\n // tick, and the history has to be whole before the next press, not after.\n spare();\n handler();\n };\n\n spare();\n window.addEventListener('popstate', onPopState);\n return () => {\n window.removeEventListener('popstate', onPopState);\n // The spare entry stays. It cannot be removed without navigating, and one\n // dead entry is a far smaller surprise than a navigation nobody asked for.\n };\n};\n","import { createHeadKeeper, headOf } from '@niscorp/nova/document';\nimport type { TerminalApi } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The page's <head>, kept on the screen.\n//\n// A drawn page arrives with its head written (../document). From then on the\n// screen moves over the wire and the page is never fetched again, so the head\n// is read off the trees the wire holds, whenever they change: the elements the\n// screen's head holds go into the page's, and the page's own tags give way to\n// them and come back (nova's head keeper).\n//\n// Terminal chrome, like the back trap beside it: the head is the terminal's\n// relationship to the surface it is painted on, the same for every render\n// target, and the app authors nothing to keep it. Where there is no document\n// (a TTY, a TUI) there is no head, and this does nothing.\n// ═══════════════════════════════════════════════════════════════\n\nexport const followHead = (api: TerminalApi, subscribe: (listener: () => void) => () => void): (() => void) => {\n if (typeof document === 'undefined') return () => undefined;\n const keep = createHeadKeeper(document);\n const read = (): void => keep(headOf(api)?.elements);\n read();\n return subscribe(read);\n};\n","import type { RenderApi } from '@niscorp/nova';\nimport { createWire } from '../client';\nimport type { Wire } from '../client';\nimport { onHotkey } from './hotkey';\nimport { trapBack } from './history';\nimport { followHead } from './head';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/terminal — the terminal, owned by the protocol that defines\n// it. A terminal is the wire (../client) plus a RENDER TARGET (react, dom,\n// console, …) painting the wire's snapshot and sending events back. This\n// module is framework-blind: the conductor drives one target against the\n// wire; the switcher cycles targets on a hotkey, sharing one wire so the\n// session survives the swap. Targets live in the subpaths (./react, ./dom);\n// the framework-shaped code stays there, never here.\n// ═══════════════════════════════════════════════════════════════\n\n// What a target renders against — nova core's `RenderApi`: the wire's snapshot\n// as pull functions (frame + per-canvas trees) plus the event sinks (dispatch\n// tagged by canvas, publish). Aliased, not redeclared — the dom adapter, the\n// react adapter, and this conductor share ONE contract, so a target written\n// for nova's dom view drops straight onto the wire. A target never touches the\n// wire directly.\nexport type TerminalApi = RenderApi;\n\n// A mounted target: re-render on demand, tear down on swap.\nexport type TerminalMount = { update: () => void; destroy: () => void };\n\n// A render target: paint the api onto the target's own surface, return the\n// mount handle. The surface — a DOM root, a stdio pair — is construction\n// config on the concrete target (`reactTarget({ root, … })`, `domTarget({\n// root })`), never part of this contract: the conductor stays surface-blind\n// and runs anywhere the wire does. A target renders once on mount; the\n// conductor calls `update` on every wire change.\nexport type Target = (api: TerminalApi) => TerminalMount;\n\n// The conductor: one target, one wire. Subscribes the target's `update` to\n// the wire and routes events back. Nothing framework-shaped.\nexport const createTerminal = (config: { target: Target; wire: Wire }): { destroy: () => void } => {\n const { target, wire } = config;\n const api: TerminalApi = {\n frame: () => wire.snapshot().frame,\n canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],\n dispatch: (id, event) => wire.dispatch(id, event),\n publish: (channel, payload) => wire.publish(channel, payload),\n };\n const mount = target(api);\n const unsubscribe = wire.subscribe(mount.update);\n const stopHead = followHead(api, wire.subscribe);\n return {\n destroy: () => {\n unsubscribe();\n stopHead();\n mount.destroy();\n },\n };\n};\n\nexport type MountTerminalConfig = {\n // render targets by name; the hotkey cycles them in insertion order\n targets: Record<string, Target>;\n // e.g. \"ctrl+shift+t\" — the live render-target swap. Omit for no swapping.\n swapKey?: string;\n // e.g. \"ctrl+shift+r\" — ask the server for a fresh shell. Omit for no key.\n //\n // The one control that must work when nothing else does. It sits on a\n // keystroke for the same reason the swap does — it acts on the terminal's\n // relationship to the server, not on anything the app models — but the\n // reason it exists at all is stronger: a shell lives on the SERVER, keyed by\n // principal, so a broken one survives every gesture a client can make alone.\n // Reloading reattaches to it. Clearing the token and signing back in\n // reattaches to it. Without a key that says \"throw it away\", somebody\n // watching a dead screen has no move left.\n resetKey?: string;\n // Catch the host's BACK gesture — the browser's back button — and send it up\n // the wire instead of letting it unload the page. Default: on, wherever a\n // history exists to catch (see ./history); nothing at all in a TTY or a TUI.\n //\n // Terminal chrome for the same reason the swap and reset keys are: back is\n // the terminal's relationship to the surface it is painted on, and the app\n // authors nothing to receive it. What back MEANS is decided a layer up, by\n // the shell that owns the navigation.\n trapBack?: boolean;\n // which target to mount first (default: the first key)\n initial?: string;\n // inject an existing wire (shared across swaps), or let the terminal make\n // one — `url` seeds a self-made wire (default: /socket on the host).\n wire?: Wire;\n url?: string;\n};\n\n// The switcher: mount a terminal that can hot-swap its render target on a\n// keystroke, over ONE wire (created here unless injected) so the socket,\n// session, and current trees survive the swap. The hotkey is the one legit\n// piece of imperative client chrome — a render target is not app state, so\n// it is not a nova action; it lives here, in the terminal.\nexport const mountTerminal = (config: MountTerminalConfig): { swap: () => void; reset: () => void; back: () => void; destroy: () => void } => {\n const keys = Object.keys(config.targets);\n if (keys.length === 0) throw new Error('mountTerminal: at least one target is required');\n\n const ownsWire = config.wire === undefined;\n const wire = config.wire ?? createWire(config.url !== undefined ? { url: config.url } : {});\n\n const targetAt = (i: number): Target => {\n const key = keys[i];\n const target = key === undefined ? undefined : config.targets[key];\n if (target === undefined) throw new Error(`mountTerminal: no target at index ${i}`);\n return target;\n };\n\n const start = config.initial === undefined ? 0 : keys.indexOf(config.initial);\n let index = start < 0 ? 0 : start;\n let active = createTerminal({ target: targetAt(index), wire });\n\n const swap = (): void => {\n active.destroy();\n index = (index + 1) % keys.length;\n active = createTerminal({ target: targetAt(index), wire });\n };\n\n const reset = (): void => wire.reset();\n const back = (): void => wire.back();\n\n const disposeSwapKey = config.swapKey === undefined ? undefined : onHotkey(config.swapKey, swap);\n const disposeResetKey = config.resetKey === undefined ? undefined : onHotkey(config.resetKey, reset);\n const disposeBackTrap = config.trapBack === false ? undefined : trapBack(back);\n\n // All three are returned so a host can bind its own control (a button, a\n // console call) — the keys and the trap are a convenience, not the only way in.\n return {\n swap,\n reset,\n back,\n destroy: () => {\n disposeSwapKey?.();\n disposeResetKey?.();\n disposeBackTrap?.();\n active.destroy();\n if (ownsWire) wire.dispose();\n },\n };\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  import { createWire } from '../chunk-J72N3EMJ.js';
2
2
  import '../chunk-ZOEUEMDX.js';
3
- import { createTitleKeeper, headOf } from '@niscorp/nova/document';
3
+ import { createHeadKeeper, headOf } from '@niscorp/nova/document';
4
4
 
5
5
  // src/terminal/hotkey.ts
6
6
  var onHotkey = (spec, handler) => {
@@ -39,10 +39,10 @@ var trapBack = (handler) => {
39
39
  window.removeEventListener("popstate", onPopState);
40
40
  };
41
41
  };
42
- var followTitle = (api, subscribe) => {
42
+ var followHead = (api, subscribe) => {
43
43
  if (typeof document === "undefined") return () => void 0;
44
- const keep = createTitleKeeper(document);
45
- const read = () => keep(headOf(api)?.head);
44
+ const keep = createHeadKeeper(document);
45
+ const read = () => keep(headOf(api)?.elements);
46
46
  read();
47
47
  return subscribe(read);
48
48
  };
@@ -58,11 +58,11 @@ var createTerminal = (config) => {
58
58
  };
59
59
  const mount = target(api);
60
60
  const unsubscribe = wire.subscribe(mount.update);
61
- const stopTitle = followTitle(api, wire.subscribe);
61
+ const stopHead = followHead(api, wire.subscribe);
62
62
  return {
63
63
  destroy: () => {
64
64
  unsubscribe();
65
- stopTitle();
65
+ stopHead();
66
66
  mount.destroy();
67
67
  }
68
68
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/terminal/hotkey.ts","../../src/terminal/history.ts","../../src/terminal/title.ts","../../src/terminal/index.ts"],"names":[],"mappings":";;;;;AAeO,IAAM,QAAA,GAAW,CAAC,IAAA,EAAc,OAAA,KAAwC;AAC7E,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,WAAA,EAAY,CAAE,MAAM,GAAG,CAAA;AAC1C,EAAA,MAAM,GAAA,GAAM,KAAA,CAAM,KAAA,CAAM,MAAA,GAAS,CAAC,CAAA,IAAK,EAAA;AACvC,EAAA,MAAM,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;AAE7D,EAAA,MAAM,OAAO,MAAY;AACvB,IAAA,MAAA,CAAO,OAAA,EAAQ;AACf,IAAA,KAAA,GAAA,CAAS,KAAA,GAAQ,KAAK,IAAA,CAAK,MAAA;AAC3B,IAAA,MAAA,GAAS,eAAe,EAAE,MAAA,EAAQ,SAAS,KAAK,CAAA,EAAG,MAAM,CAAA;AAAA,EAC3D,CAAA;AAEA,EAAA,MAAM,KAAA,GAAQ,MAAY,IAAA,CAAK,KAAA,EAAM;AACrC,EAAA,MAAM,IAAA,GAAO,MAAY,IAAA,CAAK,IAAA,EAAK;AAEnC,EAAA,MAAM,cAAA,GAAiB,OAAO,OAAA,KAAY,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,SAAS,IAAI,CAAA;AAC/F,EAAA,MAAM,eAAA,GAAkB,OAAO,QAAA,KAAa,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,UAAU,KAAK,CAAA;AACnG,EAAA,MAAM,kBAAkB,MAAA,CAAO,QAAA,KAAa,KAAA,GAAQ,MAAA,GAAY,SAAS,IAAI,CAAA;AAI7E,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,cAAA,IAAiB;AACjB,MAAA,eAAA,IAAkB;AAClB,MAAA,eAAA,IAAkB;AAClB,MAAA,MAAA,CAAO,OAAA,EAAQ;AACf,MAAA,IAAI,QAAA,OAAe,OAAA,EAAQ;AAAA,IAC7B;AAAA,GACF;AACF","file":"index.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// The live-swap hotkey — isolated here because it is the one imperative,\n// gimmicky corner of the terminal (a render target is not app state, so it\n// can't be a nova action; it's client chrome). Keyed on `event.key`, the\n// CHARACTER the key produces, so a combo matches the key the user actually\n// presses on any layout — `event.code` would bind a physical QWERTY position\n// (the key labelled Y sits elsewhere on QWERTZ/AZERTY). Use letter keys, not\n// punctuation, so Shift never remaps the character.\n// ═══════════════════════════════════════════════════════════════\n\nexport type HotkeyDisposer = () => void;\n\n// Attach `handler` to a keydown matching `spec` (e.g. \"ctrl+shift+y\"); returns\n// a disposer. Matches modifiers exactly, so \"ctrl+shift+y\" never fires on\n// \"ctrl+shift+alt+y\".\nexport const onHotkey = (spec: string, handler: () => void): HotkeyDisposer => {\n const parts = spec.toLowerCase().split('+');\n const key = parts[parts.length - 1] ?? '';\n const mods = new Set(parts.slice(0, -1));\n const listener = (event: KeyboardEvent): void => {\n if (\n event.key.toLowerCase() === key &&\n event.ctrlKey === mods.has('ctrl') &&\n event.shiftKey === mods.has('shift') &&\n event.altKey === mods.has('alt') &&\n event.metaKey === (mods.has('meta') || mods.has('cmd'))\n ) {\n event.preventDefault();\n handler();\n }\n };\n window.addEventListener('keydown', listener);\n return () => window.removeEventListener('keydown', listener);\n};\n","// ═══════════════════════════════════════════════════════════════\n// The browser's back button, caught.\n//\n// ⟲ IT USED TO UNLOAD THE APPLICATION. A moss terminal never touched the URL,\n// so a tab held exactly one history entry and back meant \"leave the page\" —\n// the socket dropped, the shell went unattended, and somebody who wanted to\n// close a screen got a blank tab instead. Nothing was lost (the shell is\n// durable, keyed by principal, and a reload reattaches to it) but nobody\n// pressing back is thinking about that.\n//\n// What it does instead: keep ONE spare history entry ahead of the page and\n// spend it on every press. Back consumes the spare, this puts another one\n// straight back, and the gesture is handed to the terminal — which sends it up\n// the wire, where the shell that owns the navigation decides what back means.\n//\n// The URL never changes. That is the honest position while location lives on\n// the SERVER: the shell is keyed by principal, not by tab, so an address bar\n// would be a per-tab claim on state two tabs share. When deep links arrive they\n// arrive as a projection of the shell's own location, and this file is where\n// the gesture will already be.\n// ═══════════════════════════════════════════════════════════════\n\nexport type BackTrapDisposer = () => void;\n\n// Marks the entry as ours, so a host that keeps its own history state can tell\n// this one apart. Nothing reads it yet; a debugger looking at `history.state`\n// deserves to find a name rather than an empty object.\nconst SENTINEL = { nisc: 'terminal-back' } as const;\n\n// Catch the host's back gesture and call `handler` instead of letting the page\n// unload. A no-op (and a disposer that does nothing) wherever there is no\n// history to trap — a TTY, a TUI, a plain process — so the conductor can ask\n// for it unconditionally.\nexport const trapBack = (handler: () => void): BackTrapDisposer => {\n if (typeof window === 'undefined') return () => undefined;\n const history = window.history as History | undefined;\n if (history === undefined || typeof history.pushState !== 'function') return () => undefined;\n\n // The spare. `pushState` with no url keeps the current address, so this adds\n // an entry without changing what the address bar says or asking the server\n // for anything.\n const spare = (): void => {\n try {\n history.pushState(SENTINEL, '');\n } catch {\n // A sandboxed document can refuse this. Back then behaves as it always\n // did rather than throwing on the way out of a keypress.\n }\n };\n\n const onPopState = (): void => {\n // One entry was just spent — replace it, then act. In that order: the\n // handler sends a message up the wire and the answer arrives on another\n // tick, and the history has to be whole before the next press, not after.\n spare();\n handler();\n };\n\n spare();\n window.addEventListener('popstate', onPopState);\n return () => {\n window.removeEventListener('popstate', onPopState);\n // The spare entry stays. It cannot be removed without navigating, and one\n // dead entry is a far smaller surprise than a navigation nobody asked for.\n };\n};\n","import { createTitleKeeper, headOf } from '@niscorp/nova/document';\nimport type { TerminalApi } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The tab's title, kept on the screen.\n//\n// A drawn page arrives with its head written (../document). From then on the\n// screen moves over the wire and the page is never fetched again, so the part\n// of a head somebody can see — the title — is read off the trees the wire\n// holds, whenever they change. A screen with no head has the page's own title.\n//\n// Terminal chrome, like the back trap beside it: the title is the terminal's\n// relationship to the surface it is painted on, the same for every render\n// target, and the app authors nothing to keep it. Where there is no document\n// (a TTY, a TUI) there is no title, and this does nothing.\n// ═══════════════════════════════════════════════════════════════\n\nexport const followTitle = (api: TerminalApi, subscribe: (listener: () => void) => () => void): (() => void) => {\n if (typeof document === 'undefined') return () => undefined;\n const keep = createTitleKeeper(document);\n const read = (): void => keep(headOf(api)?.head);\n read();\n return subscribe(read);\n};\n","import type { RenderApi } from '@niscorp/nova';\nimport { createWire } from '../client';\nimport type { Wire } from '../client';\nimport { onHotkey } from './hotkey';\nimport { trapBack } from './history';\nimport { followTitle } from './title';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/terminal — the terminal, owned by the protocol that defines\n// it. A terminal is the wire (../client) plus a RENDER TARGET (react, dom,\n// console, …) painting the wire's snapshot and sending events back. This\n// module is framework-blind: the conductor drives one target against the\n// wire; the switcher cycles targets on a hotkey, sharing one wire so the\n// session survives the swap. Targets live in the subpaths (./react, ./dom);\n// the framework-shaped code stays there, never here.\n// ═══════════════════════════════════════════════════════════════\n\n// What a target renders against — nova core's `RenderApi`: the wire's snapshot\n// as pull functions (frame + per-canvas trees) plus the event sinks (dispatch\n// tagged by canvas, publish). Aliased, not redeclared — the dom adapter, the\n// react adapter, and this conductor share ONE contract, so a target written\n// for nova's dom view drops straight onto the wire. A target never touches the\n// wire directly.\nexport type TerminalApi = RenderApi;\n\n// A mounted target: re-render on demand, tear down on swap.\nexport type TerminalMount = { update: () => void; destroy: () => void };\n\n// A render target: paint the api onto the target's own surface, return the\n// mount handle. The surface — a DOM root, a stdio pair — is construction\n// config on the concrete target (`reactTarget({ root, … })`, `domTarget({\n// root })`), never part of this contract: the conductor stays surface-blind\n// and runs anywhere the wire does. A target renders once on mount; the\n// conductor calls `update` on every wire change.\nexport type Target = (api: TerminalApi) => TerminalMount;\n\n// The conductor: one target, one wire. Subscribes the target's `update` to\n// the wire and routes events back. Nothing framework-shaped.\nexport const createTerminal = (config: { target: Target; wire: Wire }): { destroy: () => void } => {\n const { target, wire } = config;\n const api: TerminalApi = {\n frame: () => wire.snapshot().frame,\n canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],\n dispatch: (id, event) => wire.dispatch(id, event),\n publish: (channel, payload) => wire.publish(channel, payload),\n };\n const mount = target(api);\n const unsubscribe = wire.subscribe(mount.update);\n const stopTitle = followTitle(api, wire.subscribe);\n return {\n destroy: () => {\n unsubscribe();\n stopTitle();\n mount.destroy();\n },\n };\n};\n\nexport type MountTerminalConfig = {\n // render targets by name; the hotkey cycles them in insertion order\n targets: Record<string, Target>;\n // e.g. \"ctrl+shift+t\" — the live render-target swap. Omit for no swapping.\n swapKey?: string;\n // e.g. \"ctrl+shift+r\" — ask the server for a fresh shell. Omit for no key.\n //\n // The one control that must work when nothing else does. It sits on a\n // keystroke for the same reason the swap does — it acts on the terminal's\n // relationship to the server, not on anything the app models — but the\n // reason it exists at all is stronger: a shell lives on the SERVER, keyed by\n // principal, so a broken one survives every gesture a client can make alone.\n // Reloading reattaches to it. Clearing the token and signing back in\n // reattaches to it. Without a key that says \"throw it away\", somebody\n // watching a dead screen has no move left.\n resetKey?: string;\n // Catch the host's BACK gesture — the browser's back button — and send it up\n // the wire instead of letting it unload the page. Default: on, wherever a\n // history exists to catch (see ./history); nothing at all in a TTY or a TUI.\n //\n // Terminal chrome for the same reason the swap and reset keys are: back is\n // the terminal's relationship to the surface it is painted on, and the app\n // authors nothing to receive it. What back MEANS is decided a layer up, by\n // the shell that owns the navigation.\n trapBack?: boolean;\n // which target to mount first (default: the first key)\n initial?: string;\n // inject an existing wire (shared across swaps), or let the terminal make\n // one — `url` seeds a self-made wire (default: /socket on the host).\n wire?: Wire;\n url?: string;\n};\n\n// The switcher: mount a terminal that can hot-swap its render target on a\n// keystroke, over ONE wire (created here unless injected) so the socket,\n// session, and current trees survive the swap. The hotkey is the one legit\n// piece of imperative client chrome — a render target is not app state, so\n// it is not a nova action; it lives here, in the terminal.\nexport const mountTerminal = (config: MountTerminalConfig): { swap: () => void; reset: () => void; back: () => void; destroy: () => void } => {\n const keys = Object.keys(config.targets);\n if (keys.length === 0) throw new Error('mountTerminal: at least one target is required');\n\n const ownsWire = config.wire === undefined;\n const wire = config.wire ?? createWire(config.url !== undefined ? { url: config.url } : {});\n\n const targetAt = (i: number): Target => {\n const key = keys[i];\n const target = key === undefined ? undefined : config.targets[key];\n if (target === undefined) throw new Error(`mountTerminal: no target at index ${i}`);\n return target;\n };\n\n const start = config.initial === undefined ? 0 : keys.indexOf(config.initial);\n let index = start < 0 ? 0 : start;\n let active = createTerminal({ target: targetAt(index), wire });\n\n const swap = (): void => {\n active.destroy();\n index = (index + 1) % keys.length;\n active = createTerminal({ target: targetAt(index), wire });\n };\n\n const reset = (): void => wire.reset();\n const back = (): void => wire.back();\n\n const disposeSwapKey = config.swapKey === undefined ? undefined : onHotkey(config.swapKey, swap);\n const disposeResetKey = config.resetKey === undefined ? undefined : onHotkey(config.resetKey, reset);\n const disposeBackTrap = config.trapBack === false ? undefined : trapBack(back);\n\n // All three are returned so a host can bind its own control (a button, a\n // console call) — the keys and the trap are a convenience, not the only way in.\n return {\n swap,\n reset,\n back,\n destroy: () => {\n disposeSwapKey?.();\n disposeResetKey?.();\n disposeBackTrap?.();\n active.destroy();\n if (ownsWire) wire.dispose();\n },\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/terminal/hotkey.ts","../../src/terminal/history.ts","../../src/terminal/head.ts","../../src/terminal/index.ts"],"names":[],"mappings":";;;;;AAeO,IAAM,QAAA,GAAW,CAAC,IAAA,EAAc,OAAA,KAAwC;AAC7E,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,WAAA,EAAY,CAAE,MAAM,GAAG,CAAA;AAC1C,EAAA,MAAM,GAAA,GAAM,KAAA,CAAM,KAAA,CAAM,MAAA,GAAS,CAAC,CAAA,IAAK,EAAA;AACvC,EAAA,MAAM,OAAO,IAAI,GAAA,CAAI,MAAM,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA;AACvC,EAAA,MAAM,QAAA,GAAW,CAAC,KAAA,KAA+B;AAC/C,IAAA,IACE,KAAA,CAAM,GAAA,CAAI,WAAA,EAAY,KAAM,OAC5B,KAAA,CAAM,OAAA,KAAY,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA,IACjC,KAAA,CAAM,QAAA,KAAa,KAAK,GAAA,CAAI,OAAO,CAAA,IACnC,KAAA,CAAM,MAAA,KAAW,IAAA,CAAK,GAAA,CAAI,KAAK,KAC/B,KAAA,CAAM,OAAA,M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B,OAAO,OAAA,KAAY,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,SAAS,IAAI,CAAA;AAC/F,EAAA,MAAM,eAAA,GAAkB,OAAO,QAAA,KAAa,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,UAAU,KAAK,CAAA;AACnG,EAAA,MAAM,kBAAkB,MAAA,CAAO,QAAA,KAAa,KAAA,GAAQ,MAAA,GAAY,SAAS,IAAI,CAAA;AAI7E,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,cAAA,IAAiB;AACjB,MAAA,eAAA,IAAkB;AAClB,MAAA,eAAA,IAAkB;AAClB,MAAA,MAAA,CAAO,OAAA,EAAQ;AACf,MAAA,IAAI,QAAA,OAAe,OAAA,EAAQ;AAAA,IAC7B;AAAA,GACF;AACF","file":"index.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// The live-swap hotkey — isolated here because it is the one imperative,\n// gimmicky corner of the terminal (a render target is not app state, so it\n// can't be a nova action; it's client chrome). Keyed on `event.key`, the\n// CHARACTER the key produces, so a combo matches the key the user actually\n// presses on any layout — `event.code` would bind a physical QWERTY position\n// (the key labelled Y sits elsewhere on QWERTZ/AZERTY). Use letter keys, not\n// punctuation, so Shift never remaps the character.\n// ═══════════════════════════════════════════════════════════════\n\nexport type HotkeyDisposer = () => void;\n\n// Attach `handler` to a keydown matching `spec` (e.g. \"ctrl+shift+y\"); returns\n// a disposer. Matches modifiers exactly, so \"ctrl+shift+y\" never fires on\n// \"ctrl+shift+alt+y\".\nexport const onHotkey = (spec: string, handler: () => void): HotkeyDisposer => {\n const parts = spec.toLowerCase().split('+');\n const key = parts[parts.length - 1] ?? '';\n const mods = new Set(parts.slice(0, -1));\n const listener = (event: KeyboardEvent): void => {\n if (\n event.key.toLowerCase() === key &&\n event.ctrlKey === mods.has('ctrl') &&\n event.shiftKey === mods.has('shift') &&\n event.altKey === mods.has('alt') &&\n event.metaKey === (mods.has('meta') || mods.has('cmd'))\n ) {\n event.preventDefault();\n handler();\n }\n };\n window.addEventListener('keydown', listener);\n return () => window.removeEventListener('keydown', listener);\n};\n","// ═══════════════════════════════════════════════════════════════\n// The browser's back button, caught.\n//\n// ⟲ IT USED TO UNLOAD THE APPLICATION. A moss terminal never touched the URL,\n// so a tab held exactly one history entry and back meant \"leave the page\" —\n// the socket dropped, the shell went unattended, and somebody who wanted to\n// close a screen got a blank tab instead. Nothing was lost (the shell is\n// durable, keyed by principal, and a reload reattaches to it) but nobody\n// pressing back is thinking about that.\n//\n// What it does instead: keep ONE spare history entry ahead of the page and\n// spend it on every press. Back consumes the spare, this puts another one\n// straight back, and the gesture is handed to the terminal — which sends it up\n// the wire, where the shell that owns the navigation decides what back means.\n//\n// The URL never changes. That is the honest position while location lives on\n// the SERVER: the shell is keyed by principal, not by tab, so an address bar\n// would be a per-tab claim on state two tabs share. When deep links arrive they\n// arrive as a projection of the shell's own location, and this file is where\n// the gesture will already be.\n// ═══════════════════════════════════════════════════════════════\n\nexport type BackTrapDisposer = () => void;\n\n// Marks the entry as ours, so a host that keeps its own history state can tell\n// this one apart. Nothing reads it yet; a debugger looking at `history.state`\n// deserves to find a name rather than an empty object.\nconst SENTINEL = { nisc: 'terminal-back' } as const;\n\n// Catch the host's back gesture and call `handler` instead of letting the page\n// unload. A no-op (and a disposer that does nothing) wherever there is no\n// history to trap — a TTY, a TUI, a plain process — so the conductor can ask\n// for it unconditionally.\nexport const trapBack = (handler: () => void): BackTrapDisposer => {\n if (typeof window === 'undefined') return () => undefined;\n const history = window.history as History | undefined;\n if (history === undefined || typeof history.pushState !== 'function') return () => undefined;\n\n // The spare. `pushState` with no url keeps the current address, so this adds\n // an entry without changing what the address bar says or asking the server\n // for anything.\n const spare = (): void => {\n try {\n history.pushState(SENTINEL, '');\n } catch {\n // A sandboxed document can refuse this. Back then behaves as it always\n // did rather than throwing on the way out of a keypress.\n }\n };\n\n const onPopState = (): void => {\n // One entry was just spent — replace it, then act. In that order: the\n // handler sends a message up the wire and the answer arrives on another\n // tick, and the history has to be whole before the next press, not after.\n spare();\n handler();\n };\n\n spare();\n window.addEventListener('popstate', onPopState);\n return () => {\n window.removeEventListener('popstate', onPopState);\n // The spare entry stays. It cannot be removed without navigating, and one\n // dead entry is a far smaller surprise than a navigation nobody asked for.\n };\n};\n","import { createHeadKeeper, headOf } from '@niscorp/nova/document';\nimport type { TerminalApi } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The page's <head>, kept on the screen.\n//\n// A drawn page arrives with its head written (../document). From then on the\n// screen moves over the wire and the page is never fetched again, so the head\n// is read off the trees the wire holds, whenever they change: the elements the\n// screen's head holds go into the page's, and the page's own tags give way to\n// them and come back (nova's head keeper).\n//\n// Terminal chrome, like the back trap beside it: the head is the terminal's\n// relationship to the surface it is painted on, the same for every render\n// target, and the app authors nothing to keep it. Where there is no document\n// (a TTY, a TUI) there is no head, and this does nothing.\n// ═══════════════════════════════════════════════════════════════\n\nexport const followHead = (api: TerminalApi, subscribe: (listener: () => void) => () => void): (() => void) => {\n if (typeof document === 'undefined') return () => undefined;\n const keep = createHeadKeeper(document);\n const read = (): void => keep(headOf(api)?.elements);\n read();\n return subscribe(read);\n};\n","import type { RenderApi } from '@niscorp/nova';\nimport { createWire } from '../client';\nimport type { Wire } from '../client';\nimport { onHotkey } from './hotkey';\nimport { trapBack } from './history';\nimport { followHead } from './head';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/terminal — the terminal, owned by the protocol that defines\n// it. A terminal is the wire (../client) plus a RENDER TARGET (react, dom,\n// console, …) painting the wire's snapshot and sending events back. This\n// module is framework-blind: the conductor drives one target against the\n// wire; the switcher cycles targets on a hotkey, sharing one wire so the\n// session survives the swap. Targets live in the subpaths (./react, ./dom);\n// the framework-shaped code stays there, never here.\n// ═══════════════════════════════════════════════════════════════\n\n// What a target renders against — nova core's `RenderApi`: the wire's snapshot\n// as pull functions (frame + per-canvas trees) plus the event sinks (dispatch\n// tagged by canvas, publish). Aliased, not redeclared — the dom adapter, the\n// react adapter, and this conductor share ONE contract, so a target written\n// for nova's dom view drops straight onto the wire. A target never touches the\n// wire directly.\nexport type TerminalApi = RenderApi;\n\n// A mounted target: re-render on demand, tear down on swap.\nexport type TerminalMount = { update: () => void; destroy: () => void };\n\n// A render target: paint the api onto the target's own surface, return the\n// mount handle. The surface — a DOM root, a stdio pair — is construction\n// config on the concrete target (`reactTarget({ root, … })`, `domTarget({\n// root })`), never part of this contract: the conductor stays surface-blind\n// and runs anywhere the wire does. A target renders once on mount; the\n// conductor calls `update` on every wire change.\nexport type Target = (api: TerminalApi) => TerminalMount;\n\n// The conductor: one target, one wire. Subscribes the target's `update` to\n// the wire and routes events back. Nothing framework-shaped.\nexport const createTerminal = (config: { target: Target; wire: Wire }): { destroy: () => void } => {\n const { target, wire } = config;\n const api: TerminalApi = {\n frame: () => wire.snapshot().frame,\n canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],\n dispatch: (id, event) => wire.dispatch(id, event),\n publish: (channel, payload) => wire.publish(channel, payload),\n };\n const mount = target(api);\n const unsubscribe = wire.subscribe(mount.update);\n const stopHead = followHead(api, wire.subscribe);\n return {\n destroy: () => {\n unsubscribe();\n stopHead();\n mount.destroy();\n },\n };\n};\n\nexport type MountTerminalConfig = {\n // render targets by name; the hotkey cycles them in insertion order\n targets: Record<string, Target>;\n // e.g. \"ctrl+shift+t\" — the live render-target swap. Omit for no swapping.\n swapKey?: string;\n // e.g. \"ctrl+shift+r\" — ask the server for a fresh shell. Omit for no key.\n //\n // The one control that must work when nothing else does. It sits on a\n // keystroke for the same reason the swap does — it acts on the terminal's\n // relationship to the server, not on anything the app models — but the\n // reason it exists at all is stronger: a shell lives on the SERVER, keyed by\n // principal, so a broken one survives every gesture a client can make alone.\n // Reloading reattaches to it. Clearing the token and signing back in\n // reattaches to it. Without a key that says \"throw it away\", somebody\n // watching a dead screen has no move left.\n resetKey?: string;\n // Catch the host's BACK gesture — the browser's back button — and send it up\n // the wire instead of letting it unload the page. Default: on, wherever a\n // history exists to catch (see ./history); nothing at all in a TTY or a TUI.\n //\n // Terminal chrome for the same reason the swap and reset keys are: back is\n // the terminal's relationship to the surface it is painted on, and the app\n // authors nothing to receive it. What back MEANS is decided a layer up, by\n // the shell that owns the navigation.\n trapBack?: boolean;\n // which target to mount first (default: the first key)\n initial?: string;\n // inject an existing wire (shared across swaps), or let the terminal make\n // one — `url` seeds a self-made wire (default: /socket on the host).\n wire?: Wire;\n url?: string;\n};\n\n// The switcher: mount a terminal that can hot-swap its render target on a\n// keystroke, over ONE wire (created here unless injected) so the socket,\n// session, and current trees survive the swap. The hotkey is the one legit\n// piece of imperative client chrome — a render target is not app state, so\n// it is not a nova action; it lives here, in the terminal.\nexport const mountTerminal = (config: MountTerminalConfig): { swap: () => void; reset: () => void; back: () => void; destroy: () => void } => {\n const keys = Object.keys(config.targets);\n if (keys.length === 0) throw new Error('mountTerminal: at least one target is required');\n\n const ownsWire = config.wire === undefined;\n const wire = config.wire ?? createWire(config.url !== undefined ? { url: config.url } : {});\n\n const targetAt = (i: number): Target => {\n const key = keys[i];\n const target = key === undefined ? undefined : config.targets[key];\n if (target === undefined) throw new Error(`mountTerminal: no target at index ${i}`);\n return target;\n };\n\n const start = config.initial === undefined ? 0 : keys.indexOf(config.initial);\n let index = start < 0 ? 0 : start;\n let active = createTerminal({ target: targetAt(index), wire });\n\n const swap = (): void => {\n active.destroy();\n index = (index + 1) % keys.length;\n active = createTerminal({ target: targetAt(index), wire });\n };\n\n const reset = (): void => wire.reset();\n const back = (): void => wire.back();\n\n const disposeSwapKey = config.swapKey === undefined ? undefined : onHotkey(config.swapKey, swap);\n const disposeResetKey = config.resetKey === undefined ? undefined : onHotkey(config.resetKey, reset);\n const disposeBackTrap = config.trapBack === false ? undefined : trapBack(back);\n\n // All three are returned so a host can bind its own control (a button, a\n // console call) — the keys and the trap are a convenience, not the only way in.\n return {\n swap,\n reset,\n back,\n destroy: () => {\n disposeSwapKey?.();\n disposeResetKey?.();\n disposeBackTrap?.();\n active.destroy();\n if (ownsWire) wire.dispose();\n },\n };\n};\n"]}
package/dist/vite.cjs CHANGED
@@ -53,7 +53,8 @@ var renderDocument = async (config) => {
53
53
  const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
54
54
  const placed = template.replace(root, () => `${root.replace("></div>", () => `>${screen}</div>`)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
55
55
  const head = document.headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
56
- const html = document.placeHead(placed, head?.head, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
56
+ for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
57
+ const html = document.placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
57
58
  return {
58
59
  html,
59
60
  ...head !== void 0 ? { head } : {},