@vielzeug/codex 26.11.12 → 26.11.13
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/data/catalog.json +181 -61
- package/data/llms-full.txt +1546 -918
- package/data/llms.txt +4 -1
- package/data/manifest.json +2 -6
- package/data/packages/archive.json +1 -1
- package/data/packages/arsenal.json +4 -2
- package/data/packages/clockwork.json +3 -3
- package/data/packages/codex.json +20 -11
- package/data/packages/coins.json +22 -24
- package/data/packages/courier.json +12 -11
- package/data/packages/flux.json +2 -2
- package/data/packages/forge.json +3 -3
- package/data/packages/herald.json +2 -2
- package/data/packages/lingua.json +37 -42
- package/data/packages/patchwork.json +45 -0
- package/data/packages/postmaster.json +8 -8
- package/data/packages/refine.json +2 -2
- package/data/packages/scribe.json +57 -0
- package/data/packages/sentinel.json +1 -1
- package/data/packages/sourcerer.json +2 -2
- package/data/packages/tabula.json +40 -0
- package/data/packages/tavern.json +20 -18
- package/data/packages/tempo.json +48 -63
- package/data/packages/vault.json +29 -31
- package/data/packages/wayfinder.json +3 -6
- package/data/refine.json +76 -0
- package/dist/catalog.d.ts +13 -1
- package/dist/catalog.js +80 -53
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/errors.js +0 -1
- package/dist/errors.js.map +1 -1
- package/dist/http.d.ts +0 -1
- package/dist/http.js +0 -5
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/port.js +2 -2
- package/dist/port.js.map +1 -1
- package/dist/server.d.ts +5 -3
- package/dist/server.js +10 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +11 -8
- package/dist/snapshot.js +24 -128
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +0 -2
- package/dist/tools/index.js +0 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/refine.d.ts +2 -2
- package/dist/tools/refine.js.map +1 -1
- package/dist/types.d.ts +2 -30
- package/dist/types.js +1 -1
- package/package.json +2 -13
- package/skills/vielzeug/SKILL.md +3 -0
- package/data/search.json +0 -1688
- package/dist/refine-catalog.d.ts +0 -15
- package/dist/refine-catalog.js +0 -27
- package/dist/refine-catalog.js.map +0 -1
- package/dist/refine.d.ts +0 -7
- package/dist/refine.js +0 -9
- package/dist/refine.js.map +0 -1
|
@@ -1,26 +1,28 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "import {\n createMeshGuest,\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n type MeshProtocol,\n type MeshRtcFactory,\n meshQrCodec,\n} from '@vielzeug/mesh';\n\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\n\nexport { TavernDisposedError, TavernError, TavernPairingError };\n\n/**\n * Reclassifies a mesh pairing failure as the tavern-level user mistake it is:\n * the code the consumer pasted could not be used. The message is preserved and\n * the original error is chained as `cause`.\n */\nfunction toPairingError(error: unknown): TavernPairingError {\n const message = error instanceof Error ? error.message : 'That code could not be read.';\n return new TavernPairingError(message, { cause: error });\n}\n\n/**\n * Table sessions over `@vielzeug/mesh`: one host owns the canonical state of a subject, guests\n * mirror it and forward every command through the host's command table, so guest actions follow\n * exactly the same code path as host actions.\n *\n * The consumer supplies the seams, which commands exist, how subject state is read and mounted,\n * how notices cross between the wire and the local UI. Tavern owns the pairing, the protocol,\n * command validation, snapshot broadcasting, notice relaying, and presence.\n */\n\n/** What the host can do on behalf of a guest. */\nexport interface TavernCommands {\n /** Applies the command; throwing rejects the guest with the error's message. */\n apply(name: string, args: readonly unknown[]): unknown;\n /** Whether a command name is known; unknown names reject without applying. */\n has(name: string): boolean;\n}\n\n/**\n * How the host reads and watches the subject it is sharing. All three close over whatever\n * subject state the consumer owns: the host routes by `subjectId`, not by a subject object.\n */\nexport interface TavernSubjects {\n /** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */\n onChanged(listener: () => void): () => void;\n /** Subscribes to the hosted subject's removal: hosting ends when it fires. */\n onRemoved(listener: () => void): () => void;\n /** Reads the snapshot to broadcast; null while the subject is missing. */\n snapshot(): unknown;\n}\n\n/**\n * Notice relay between host and guests. Notices cross the wire as opaque values: each client\n * translates locally.\n *\n * **Echo guard**: a tab that both hosts and guests must guard against re-broadcasting a\n * wire-originated notice back to its own guests: `fromWire` emits locally, the host's local\n * subscription picks it up, and without a guard it would loop. The consumer owns this guard\n * because only they know their local event system; one boolean set during `fromWire` and\n * checked in `toWire` is sufficient.\n */\nexport interface TavernNotices {\n /** Re-emits a received wire notice locally. */\n fromWire(wire: unknown): void;\n /** Serializes a local notice for the wire; null skips this one. */\n toWire(notice: unknown): unknown | null;\n}\n\ninterface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: { args: unknown[]; id: string; name: string; subjectId: string };\n };\n}\n\n/** Notable host moments reported through {@link TavernHost.tap}. */\nexport type TavernHostEvent =\n | { readonly peer: MeshPeer; readonly type: 'peer-joined' }\n | { readonly peer: MeshPeer; readonly reason?: string; readonly type: 'peer-left' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Notable guest moments reported through {@link TavernGuest.tap}. */\nexport type TavernGuestEvent =\n | { readonly commandId: string; readonly message: string; readonly type: 'rejected' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nconst DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\nconst commandId = (): string => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;\n\n/** Runtime guard for the wire command shape: the protocol is Tavern's, so Tavern validates it. */\nfunction parseWireCommand(raw: unknown): { args: unknown[]; id: string; name: string; subjectId: string } | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, subjectId } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || typeof subjectId !== 'string' || !Array.isArray(args)) {\n return null;\n }\n return { args, id, name, subjectId };\n}\n\n// ---------------------------------------------------------------------------\n// Host\n// ---------------------------------------------------------------------------\n\nexport interface TavernHostOptions {\n commands: TavernCommands;\n notices?: TavernNotices;\n /**\n * Hosting ended: the subject was removed or the host was disposed. Fires exactly\n * once. This is a lifecycle transition, not observability: presence, transport\n * warnings, and the peer list all belong to {@link TavernHost.tap} and\n * {@link TavernHost.peers}.\n */\n onEnded?(): void;\n rtc?: MeshRtcFactory;\n /** The id of the subject being hosted: guest commands targeting anything else reject. */\n subjectId: string;\n subjects: TavernSubjects;\n}\n\nexport interface TavernHost {\n /** Consumes a guest's answer code; resolves with the peer once the channel is open. */\n acceptAnswerText(text: string): Promise<MeshPeer>;\n /** Produces a single-use invitation code, QR-compact when the environment allows. */\n createInvitationText(): Promise<string>;\n /** `AbortSignal` aborted when hosting ends. */\n readonly disposalSignal: AbortSignal;\n /** Stops hosting: closes every channel and detaches all subscriptions. */\n dispose(): void;\n /** Whether hosting has ended: the subject was removed or `dispose()` ran. */\n readonly disposed: boolean;\n kick(peerId: string): void;\n /** The guests currently connected: read it from a `peer-joined`/`peer-left` tap event. */\n readonly peers: readonly MeshPeer[];\n /** Relays one local notice to every guest; the serializer decides what crosses.\n * A notice relayed after hosting ended is dropped, not thrown: it is ephemeral\n * UI state with no audience left, unlike the control-plane methods, which fail\n * with `TavernDisposedError` so a leaked handle surfaces. */\n relayNotice(notice: unknown): void;\n /** Subscribes to {@link TavernHostEvent}s. Handler errors are swallowed; the\n * subscription detaches when `signal` aborts or hosting ends. */\n tap(handler: (event: TavernHostEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n}\n\n/**\n * Starts hosting one subject. Every guest command is validated and applied through the\n * command table; local changes re-broadcast the snapshot (coalesced on a microtask); removal\n * ends the session.\n */\nexport function hostTavern(options: TavernHostOptions): TavernHost {\n const host = createMeshHost<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernHostEvent>();\n let closed = false;\n let flushScheduled = false;\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n for (const off of detach.splice(0)) off();\n host.dispose();\n tappers.stop();\n options.onEnded?.();\n };\n const disposedError = (): TavernDisposedError => new TavernDisposedError('This host has stopped.');\n const warn = (error: unknown): void => {\n tappers.emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n /** Reads the snapshot for a broadcast; a throwing read warns instead of crashing the host. */\n const readSnapshot = (): unknown => {\n try {\n return options.subjects.snapshot();\n } catch (error) {\n warn(error);\n return null;\n }\n };\n\n /** Coalesces broadcasts on a microtask so bursts of local changes ship one snapshot. */\n const broadcastSnapshot = (): void => {\n if (closed || flushScheduled) return;\n flushScheduled = true;\n queueMicrotask(() => {\n flushScheduled = false;\n if (closed) return;\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.broadcast('snapshot', snapshot);\n });\n };\n\n /**\n * Applies a guest command through the command table: the same table the host's own UI\n * calls, so an unknown name, a foreign subject id or a rule violation is all the host\n * can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command || !options.commands.has(command.name) || command.subjectId !== options.subjectId) {\n host.send(peerId, 'rejected', {\n commandId: command?.id ?? '',\n message: 'The host rejected an unknown or out-of-session command.',\n });\n return;\n }\n try {\n options.commands.apply(command.name, command.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: error instanceof Error ? error.message : 'The host could not apply the command.',\n });\n }\n };\n\n const detach = [\n host.on('command', ({ peerId, payload }) => handleGuestCommand(peerId, payload)),\n options.subjects.onChanged(broadcastSnapshot),\n options.subjects.onRemoved(close),\n host.tap((event) => {\n if (event.type === 'peer-joined') {\n const snapshot = readSnapshot();\n if (snapshot !== null && snapshot !== undefined) host.send(event.peer.id, 'snapshot', snapshot);\n tappers.emit({ peer: event.peer, type: 'peer-joined' });\n }\n if (event.type === 'peer-left') tappers.emit({ peer: event.peer, reason: event.reason, type: 'peer-left' });\n if (event.type === 'error') warn(event.error);\n }),\n ];\n\n return {\n acceptAnswerText: async (text: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(text);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!('proof' in decoded)) {\n throw new TavernPairingError('That code is an invitation, not a guest answer.');\n }\n try {\n return await host.acceptAnswer(decoded);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n },\n createInvitationText: async () => {\n if (closed) throw disposedError();\n return meshQrCodec.encode(await host.createInvitation());\n },\n get disposalSignal() {\n return host.disposalSignal;\n },\n dispose: close,\n get disposed() {\n return closed;\n },\n kick: (peerId: string): void => {\n if (closed) throw disposedError();\n host.kick(peerId);\n },\n get peers(): readonly MeshPeer[] {\n return [...host.peers.values()];\n },\n relayNotice: (notice: unknown): void => {\n if (closed) return;\n const wire = options.notices ? options.notices.toWire(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast('notice', wire);\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n close();\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Guest\n// ---------------------------------------------------------------------------\n\nexport interface TavernGuestOptions<Mounted> {\n /** The invitation code the host produced. */\n invitationText: string;\n /**\n * Mounts a received snapshot; the mounted value, or null to ignore. The snapshot arrives\n * as parsed JSON: validate before trusting it.\n */\n mount(snapshot: unknown): Mounted | null;\n /** The guest's display name on the channel. */\n name: string;\n notices?: TavernNotices;\n /**\n * The channel ended after joining; the mounted value is passed for unmounting.\n * Lifecycle, not observability: rejections and transport warnings belong to\n * {@link TavernGuest.tap}. `onJoined` and `onFailed` stay callbacks for the same\n * reason: they fire while {@link joinTavern} is still resolving, before the\n * consumer can hold the handle and register a tapper.\n */\n onEnded?(subject: Mounted): void;\n /** The host never accepted the answer in time. */\n onFailed?(reason: string): void;\n /** The mounted value once the first snapshot arrives. */\n onJoined?(subject: Mounted): void;\n rtc?: MeshRtcFactory;\n}\n\nexport interface TavernGuest {\n /** `AbortSignal` aborted when the session ends. */\n readonly disposalSignal: AbortSignal;\n /** Leaves the session and drops the channel. */\n dispose(): void;\n /** Whether the session has ended: the channel dropped or `dispose()` ran. */\n readonly disposed: boolean;\n /**\n * Forwards a command to the host. The subject id is the consumer's routing key: the host\n * rejects commands that do not name the subject it is hosting.\n * Throws `TavernDisposedError` after the session has ended.\n */\n sendCommand(subjectId: string, name: string, args: readonly unknown[]): void;\n /** Subscribes to {@link TavernGuestEvent}s. Handler errors are swallowed; the\n * subscription detaches when `signal` aborts or the session ends. */\n tap(handler: (event: TavernGuestEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n}\n\n/**\n * Joins a session as a guest: consumes the host's invitation and returns the answer code to\n * show back. The session goes live once the host accepts the answer and the first snapshot\n * mounts; disposing the guest (or the channel dropping) ends it exactly once.\n */\nexport async function joinTavern<Mounted>(\n options: TavernGuestOptions<Mounted>,\n): Promise<{ answerText: string; guest: TavernGuest }> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationText);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!('secret' in decoded)) {\n throw new TavernPairingError('That code is not a session invitation.');\n }\n\n const guest = createMeshGuest<WireProtocol>({\n maxMessageBytes: DEFAULT_MAX_MESSAGE_BYTES,\n rtc: options.rtc,\n });\n const tappers = createTappers<TavernGuestEvent>();\n let mounted: Mounted | null = null;\n let ended = false;\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (): void => {\n if (ended) return;\n ended = true;\n const subject = mounted;\n mounted = null;\n for (const off of detach.splice(0)) off();\n guest.dispose();\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n };\n\n const detach = [\n guest.on('snapshot', ({ payload }) => {\n const subject = options.mount(payload);\n if (subject === null || ended) return;\n if (mounted === null) {\n mounted = subject;\n options.onJoined?.(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.notices?.fromWire(payload);\n }),\n guest.on('rejected', ({ payload }) => {\n tappers.emit({\n commandId: payload.commandId,\n message: payload.message || 'The host rejected the action.',\n type: 'rejected',\n });\n }),\n guest.tap((event) => {\n if (event.type !== 'status-change' && event.type !== 'peer-status-change') return;\n if (event.type === 'peer-status-change' && event.peerId !== guest.host?.id) return;\n if (event.status === 'failed' && mounted === null && !ended) {\n options.onFailed?.('The host did not accept the answer in time.');\n }\n if (event.status === 'disconnected' || event.status === 'failed') endSession();\n }),\n guest.tap((event) => {\n if (event.type === 'error') {\n tappers.emit({ error: event.error, message: event.error.message, type: 'warning' });\n }\n }),\n ];\n\n try {\n const answer = await guest.acceptInvitation(decoded, { name: options.name });\n return {\n answerText: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: endSession,\n get disposed() {\n return ended;\n },\n sendCommand: (subjectId: string, name: string, args: readonly unknown[]): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', { args: [...args], id: commandId(), name, subjectId });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession();\n },\n },\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n endSession();\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n}\n",
|
|
2
|
+
"apiSource": "// Public root surface of @vielzeug/tavern. Every public export goes through this file.\n\n// The mesh peer rides tavern's own event payloads; re-exported so the tavern import\n// alone types them.\nexport type { MeshPeer } from '@vielzeug/mesh';\nexport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nexport { joinTavern } from './guest';\nexport { hostTavern } from './host';\nexport type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: Tavern\ndescription: 'Table sessions over mesh: host-owned state replication with guest command forwarding'\npackage: tavern\ncategory: utilities\nkeywords: [session, host, guest, replication, mesh, commands, snapshots, collaboration, peer-to-peer]\nexports:\n [\n hostTavern,\n joinTavern,\n TavernHost,\n
|
|
5
|
-
"api": "---\ntitle: 'Tavern: API Reference'\ndescription: Public API of @vielzeug/tavern.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------- |\n| `hostTavern()` | Host a subject: pairing, command validation, snapshot broadcast | Sync factory | Disposing ends hosting for every guest |\n| `joinTavern()` | Join a session: consume invitation, produce answer | Async | The session lives only after the host accepts and the first snapshot mounts |\n| `TavernHost` | Host handle: invitation, answer acceptance, kick, notice relay, presence tap | N/A | `dispose()` is idempotent; control-plane methods throw `TavernDisposedError` after |\n| `TavernGuest` | Guest handle: command forwarding, rejection tap, disposal | N/A | `dispose()` fires `onEnded` exactly once |\n| `TavernHostEvent` | Host observability union for `tap()`: presence and warnings | N/A | Lifecycle transitions are callbacks, not events |\n| `TavernGuestEvent` | Guest observability union for `tap()`: rejections and warnings | N/A | `onJoined`/`onFailed` fire before the handle exists, so they stay callbacks |\n| `TavernCommands` | The host's command table | N/A | Unknown names and foreign subject ids reject without applying |\n| `TavernSubjects` | Snapshot reading, change and removal subscriptions | N/A | `snapshot` returning `null` skips the broadcast |\n| `TavernNotices` | Wire serialization of local notices | N/A | `toWire` returning `null` skips that notice |\n| `TavernError` | Base error for every Tavern failure | N/A | N/A |\n| `TavernPairingError` | The consumer pasted the wrong kind of pairing code | N/A | N/A |\n| `TavernDisposedError` | A stopped host or ended guest was used again | N/A | N/A |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------- |\n| `@vielzeug/tavern` | Complete public Tavern API |\n\n## `hostTavern(options)`\n\nCreates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol), checked against `commands.has` and the `subjectId`, then applied through `commands.apply`: throwing rejects the guest with the error's message. Local changes (via `subjects.onChanged`) re-broadcast `subjects.snapshot()`: coalesced on a microtask; `subjects.onRemoved` ends hosting. Presence and transport warnings are reported through `tap()` as `TavernHostEvent`s, and the live peer list is the `peers` getter; hosting ending: from removal or `dispose()`: fires `onEnded` exactly once. `relayNotice` serializes through `notices.toWire` and broadcasts to every guest.\n\n**Returns:** `TavernHost`: the host handle.\n\n| Option | Type | Description |\n| ----------- | ---------------- | ----------------------------------------------------------------------------- |\n| `commands` | `TavernCommands` | The host's command table: the same object the host's own UI calls |\n| `notices?` | `TavernNotices` | Notice relay; omit to disable notice broadcasting |\n| `onEnded?` | `() => void` | Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n| `subjectId` | `string` | The id of the hosted subject: guest commands targeting anything else reject |\n| `subjects` | `TavernSubjects` | Snapshot reading, change and removal subscriptions |\n\n**Example**\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n apply: (name, args) => myStore.apply(name, args),\n has: (name) => name in myStore,\n },\n subjectId: 'doc-1',\n subjects: {\n onChanged: (listener) => myStore.onUpdated('doc-1', listener),\n onRemoved: (listener) => myStore.onRemoved('doc-1', listener),\n snapshot: () => myStore.read('doc-1'),\n },\n});\n```\n\n### `TavernHost` members\n\n| Member | Returns | Description |\n| ------------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `acceptAnswerText(text)` | `Promise<MeshPeer>` | Consumes a guest's answer code; resolves with the peer once the channel opens. Throws `TavernPairingError` for any unusable code: wrong kind, malformed, expired: with the underlying error as `cause`. Throws `TavernDisposedError` after `dispose()` |\n| `createInvitationText()` | `Promise<string>` | Produces a single-use invitation code, QR-compact when the environment allows. Throws `TavernDisposedError` after `dispose()` |\n| `disposalSignal` | `AbortSignal` | Aborted when hosting ends |\n| `dispose()` | `void` | Stops hosting: closes every channel and detaches all subscriptions. Idempotent; fires `onEnded` exactly once |\n| `disposed` | `boolean` | Whether hosting has ended |\n| `kick(peerId)` | `void` | Disconnects a peer; the guest observes a disconnect. Throws `TavernDisposedError` after `dispose()` |\n| `peers` | `readonly MeshPeer[]` | The guests currently connected; current inside a `peer-joined`/`peer-left` tap event |\n| `relayNotice(notice)` | `void` | Relays one local notice to every guest; the serializer decides what crosses. A notice relayed after `dispose()` is dropped: ephemeral UI state with no audience left |\n| `tap(handler, options?)` | `() => void` | Observes `TavernHostEvent`s; returns an unsubscribe function |\n| `[Symbol.dispose]()` | `void` | Delegates to `dispose()`. Enables `using` declarations |\n\n---\n\n## `joinTavern(options)`\n\nConsumes an invitation and returns `{ answerText, guest }`. The guest mounts snapshots through `mount(snapshot)`: the first successful mount fires `onJoined`; wire notices are relayed through `notices.fromWire`; host rejections and transport warnings arrive through `tap()` as `TavernGuestEvent`s. Channel failures before the first mount fire `onFailed` (once); afterwards, a disconnect or `guest.dispose()` fires `onEnded` with the mounted subject exactly once. `guest.sendCommand` forwards a command to the host with the subject id the consumer routes by. An unusable invitation: wrong kind, malformed, expired: rejects with `TavernPairingError` and leaves no node or subscriptions behind.\n\n**Returns:** `Promise<{ answerText: string; guest: TavernGuest }>`: the answer code to show back and the guest handle.\n\n| Option | Type | Description |\n| ---------------- | ---------------------------------------- | --------------------------------------------------------------------------- |\n| `invitationText` | `string` | The invitation code the host produced |\n| `mount` | `(snapshot: unknown) => Mounted \\| null` | Mounts a received snapshot; the mounted value, or `null` to ignore |\n| `name` | `string` | The guest's display name on the channel |\n| `notices?` | `TavernNotices` | Notice relay; wire notices re-emit locally through `fromWire` |\n| `onEnded?` | `(subject: Mounted) => void` | The channel ended after joining; the mounted value is passed for unmounting |\n| `onFailed?` | `(reason: string) => void` | The host never accepted the answer in time |\n| `onJoined?` | `(subject: Mounted) => void` | The mounted value once the first snapshot arrives |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n\n**Example**\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerText, guest } = await joinTavern({\n invitationText: invitation,\n mount: (snapshot) => sanitizeAndMount(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject.id),\n onJoined: (subject) => mountMirror(subject),\n});\nguest.tap((event) => {\n if (event.type === 'rejected') console.warn(event.commandId, event.message);\n});\n\nguest.sendCommand('doc-1', 'rename', ['New name']);\nguest.dispose();\n```\n\n### `TavernGuest` members\n\n| Member | Returns | Description |\n| ------------------------------------ | ------------- | ------------------------------------------------------------------------------------- |\n| `disposalSignal` | `AbortSignal` | Aborted when the session ends |\n| `dispose()` | `void` | Leaves the session and drops the channel. Fires `onEnded` exactly once |\n| `disposed` | `boolean` | Whether the session has ended: the channel dropped or `dispose()` ran |\n| `sendCommand(subjectId, name, args)` | `void` | Forwards a command to the host. Throws `TavernDisposedError` if the session has ended |\n| `tap(handler, options?)` | `() => void` | Observes `TavernGuestEvent`s; returns an unsubscribe function |\n| `[Symbol.dispose]()` | `void` | Delegates to `dispose()`. Enables `using` declarations |\n\n---\n\n## Types\n\n```ts\n/** What the host can do on behalf of a guest. */\ninterface TavernCommands {\n /** Whether a command name is known; unknown names reject without applying. */\n has(name: string): boolean;\n /** Applies the command; throwing rejects the guest with the error's message. */\n apply(name: string, args: readonly unknown[]): unknown;\n}\n\n/**\n * How the host reads and watches the subject it is sharing. All three close over\n * whatever subject state the consumer owns: the host routes by `subjectId`,\n * not by a subject object.\n */\ninterface TavernSubjects {\n /** Reads the snapshot to broadcast; null while the subject is missing. */\n snapshot(): unknown;\n /** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */\n onChanged(listener: () => void): () => void;\n /** Subscribes to the hosted subject's removal: hosting ends when it fires. */\n onRemoved(listener: () => void): () => void;\n}\n\n/**\n * Notice relay between host and guests. Notices cross the wire as opaque\n * values: each client translates locally.\n */\ninterface TavernNotices {\n /** Serializes a local notice for the wire; null skips this one. */\n toWire(notice: unknown): unknown | null;\n /** Re-emits a received wire notice locally. */\n fromWire(wire: unknown): void;\n}\n\n/** Notable host moments reported through `TavernHost.tap`. */\ntype TavernHostEvent =\n | { readonly peer: MeshPeer; readonly type: 'peer-joined' }\n | { readonly peer: MeshPeer; readonly reason?: string; readonly type: 'peer-left' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Notable guest moments reported through `TavernGuest.tap`. */\ntype TavernGuestEvent =\n | { readonly commandId: string; readonly message: string; readonly type: 'rejected' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' };\n\n/** Options for `hostTavern`. */\ninterface TavernHostOptions {\n commands: TavernCommands;\n notices?: TavernNotices;\n /** Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once. */\n onEnded?(): void;\n rtc?: MeshRtcFactory;\n subjectId: string;\n subjects: TavernSubjects;\n}\n\n/** Options for `joinTavern`. */\ninterface TavernGuestOptions<Mounted> {\n invitationText: string;\n /** Mounts a received snapshot; the mounted value, or null to ignore. */\n mount(snapshot: unknown): Mounted | null;\n name: string;\n notices?: TavernNotices;\n onEnded?(subject: Mounted): void;\n onFailed?(reason: string): void;\n onJoined?(subject: Mounted): void;\n rtc?: MeshRtcFactory;\n}\n\n/** Host handle returned by `hostTavern`. */\ninterface TavernHost {\n acceptAnswerText(text: string): Promise<MeshPeer>;\n createInvitationText(): Promise<string>;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n kick(peerId: string): void;\n readonly peers: readonly MeshPeer[];\n relayNotice(notice: unknown): void;\n tap(handler: (event: TavernHostEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n [Symbol.dispose](): void;\n}\n\n/** Guest handle returned by `joinTavern`. */\ninterface TavernGuest {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n sendCommand(subjectId: string, name: string, args: readonly unknown[]): void;\n tap(handler: (event: TavernGuestEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n [Symbol.dispose](): void;\n}\n```\n\n## Errors\n\n| Error | Triggered by | Notable properties |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |\n| `TavernError` | Base class for every Tavern failure: catch this to handle all Tavern errors in one branch | N/A |\n| `TavernPairingError` | A pairing code the consumer pasted could not be used: wrong kind, malformed, expired, or refused by the host. The mesh-level failure is chained as `cause` | `cause` |\n| `TavernDisposedError` | A stopped host (`kick`, `createInvitationText`, `acceptAnswerText`) or an ended guest (`sendCommand`) was used again | N/A |\n\n`TavernPairingError` and `TavernDisposedError` extend `TavernError`. Every user-input pairing mistake: a garbage code, the wrong code kind, an expired invitation, a refused answer: surfaces as `TavernPairingError` from `acceptAnswerText` and `joinTavern`; transport-level failures (timeouts, connection errors) propagate unchanged. Post-dispose use fails loudly with `TavernDisposedError`, mirroring mesh inside the Tavern error hierarchy.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Tavern: Usage Guide'\ndescription: How to use @vielzeug/tavern.\n---\n\n[[toc]]\n\n## Basic Usage\n\nHost one subject per session; guests join through the invitation/answer pair.
|
|
4
|
+
"index": "---\ntitle: Tavern\ndescription: 'Table sessions over mesh: host-owned state replication with guest command forwarding'\npackage: tavern\ncategory: utilities\nkeywords: [session, host, guest, replication, mesh, commands, snapshots, collaboration, peer-to-peer]\nexports:\n [\n hostTavern,\n joinTavern,\n TavernCommand,\n TavernCommands,\n TavernSubject,\n TavernHost,\n TavernHostOptions,\n TavernHostEvent,\n TavernGuest,\n TavernGuestOptions,\n TavernGuestEvent,\n TavernJoinResult,\n TavernError,\n TavernPairingError,\n TavernDisposedError,\n ]\nrelated: [mesh, ledger, herald]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tavern\" />\n\n## Why Tavern?\n\nPeer-to-peer apps share one arrangement problem: the canonical state of something: a document, a dashboard, a record: lives on exactly one device, while every other participant should see it and be able to change it from their own. Tavern turns that arrangement into a session: **one host owns the canonical state, guests mirror it, and every guest command is forwarded through the host's own command table**, so remote actions follow exactly the same code path as local ones.\n\n```ts\n// Before: hand-rolled session orchestration: pairing, protocol validation,\n// command routing, snapshot broadcasting, notice relaying, presence tracking.\nconst host = createMeshHost({\n /* ... */\n});\nhost.on('command', ({ peerId, payload }) => {\n const command = mySchema.safeParse(payload);\n if (!command.success) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n return;\n }\n try {\n applySubjectCommand(command.data.name, subject, command.data.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n }\n});\nbus.on('subject:updated', () => {\n host.broadcast('snapshot', snapshotFor(subject));\n});\n// ... 40+ more lines of plumbing\n\n// After: tavern owns the protocol, the validation, the broadcasting.\nconst host = hostTavern({\n commands: { rename: (args) => store.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => store.onUpdated(docId, listener),\n onRemoved: (listener) => store.onRemoved(docId, listener),\n snapshot: () => store.read(docId),\n },\n});\n```\n\n| Feature | Tavern | Raw mesh | Socket.io rooms |\n| ------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"tavern\" type=\"size\" /> | <PackageInfo package=\"mesh\" type=\"size\" /> | N/A |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Host-authoritative commands | <ore-icon name=\"check\" size=\"16\"></ore-icon>: same table as local UI | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself |\n| Snapshot replication | <ore-icon name=\"check\" size=\"16\"></ore-icon>: microtask-coalesced | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Out-of-band pairing (QR / copy-paste) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon>: needs a server |\n| Notice relaying | <ore-icon name=\"check\" size=\"16\"></ore-icon>: consumer-defined wire shape | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: server-mediated |\n\n<div class=\"decision-callout\">\n\n**Use Tavern when** one device should own the canonical state of something: a shared document, a live dashboard, a record under review, and every other device should mirror it and send commands back through the host's own command table, which stays the single validation path.\n\n**Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, file transfer, or custom topologies.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tavern\n```\n\n```sh [npm]\nnpm install @vielzeug/tavern\n```\n\n```sh [yarn]\nyarn add @vielzeug/tavern\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\n\n// Host: wire the command table and snapshot access for the shared subject.\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Produce a single-use invitation code; deliver it out-of-band (QR, copy/paste).\nconst invitationCode = await host.createInvitationCode();\n\n// Guest: consume the invitation code, produce an answer code for the host.\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => parseAndMount(snapshot),\n name: 'Alex',\n});\nawait host.acceptAnswerCode(answerCode);\n\n// `ready` settles once the first snapshot arrives and mounts: the mirror is live.\nawait ready;\n\n// The guest's commands run through the host's own table; their effect\n// arrives with the next snapshot, so a successful command needs no ack.\nguest.sendCommand('rename', ['Quarterly report']);\n\n// Cleanup: hosting ends for every guest; onEnded fires exactly once on both sides.\nhost.dispose();\nguest.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`hostTavern`**: host one subject: pairing, protocol validation, command application, coalesced snapshot broadcasts\n- **`joinTavern`**: join as a guest: consume the invitation code, produce the answer code, mirror the host's snapshots\n- **`TavernCommands`**: the host's command table as a plain record of handlers: the same functions the host's own UI calls, so remote actions cannot bypass validation\n- **`ready` promise**: the join lifecycle is awaitable: `ready` resolves with the mounted mirror or rejects with why the session never came up\n- **Coalesced snapshots**: bursts of local changes ship one snapshot per microtask, not one per change\n- **`onEnded` fires exactly once**: on both handles: channel drops, subject removal, and explicit disposal share a single idempotent cleanup path\n- **Typed errors**: `TavernPairingError` covers every unusable pasted code with the mesh failure chained as `cause`\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Mesh](/mesh/): the P2P transport underneath: WebRTC pairing, data channels, QR-optimized codecs.\n- [Ledger](/ledger/): undo/redo history for the commands the host applies.\n- [Herald](/herald/): typed event bus for the local notice stream tavern relays.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Tavern: API Reference'\ndescription: Public API of @vielzeug/tavern.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------- |\n| `hostTavern()` | Host a subject: pairing, command validation, snapshot broadcast | Sync factory | Disposing ends hosting for every guest |\n| `joinTavern()` | Join a session: consume invitation code, produce answer code | Async | The session lives only after the host accepts and the first snapshot mounts |\n| `TavernHost` | Host handle: invitation, answer acceptance, kick, notice relay, presence tap | N/A | `dispose()` is idempotent; control-plane methods throw `TavernDisposedError` after |\n| `TavernGuest` | Guest handle: command forwarding, rejection tap, disposal | N/A | `dispose()` fires `onEnded` exactly once |\n| `TavernJoinResult` | Join outcome: answer code, guest handle, and the `ready` promise | N/A | A `ready` nobody awaits never surfaces as an unhandled rejection |\n| `TavernHostEvent` | Host observability union for `tap()`: presence, warnings, dispose | N/A | Lifecycle transitions are `onEnded`, not events |\n| `TavernGuestEvent` | Guest observability union for `tap()`: rejections, warnings, dispose | N/A | The opening transition is `ready`, not an event |\n| `TavernCommands` | The host's command table: a record of handlers keyed by command name | N/A | A name the record does not hold rejects without applying |\n| `TavernSubject` | Snapshot reading, change and removal subscriptions | N/A | `snapshot` returning `null` skips the broadcast |\n| `TavernError` | Base error for every Tavern failure | N/A | N/A |\n| `TavernPairingError` | The consumer pasted the wrong kind of pairing code | N/A | N/A |\n| `TavernDisposedError` | A stopped host or ended guest was used again | N/A | N/A |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------- |\n| `@vielzeug/tavern` | Complete public Tavern API |\n\nThe `MeshPeer` type carried by host events and the `peers` getter is re-exported here, so a single import types everything.\n\n## `hostTavern(options)`\n\nCreates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol) and checked against `commands`: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with the error's message. Local changes (via `subject.onChanged`) re-broadcast `subject.snapshot()`: coalesced on a microtask; `subject.onRemoved` ends hosting. Presence and transport warnings are reported through `tap()` as `TavernHostEvent`s, and the live peer list is the `peers` getter; hosting ending: from removal or `dispose()`: fires `onEnded` exactly once. `relayNotice` serializes through `serializeNotice` and broadcasts to every guest.\n\n**Returns:** `TavernHost`: the host handle.\n\n| Option | Type | Description |\n| ------------------ | ----------------------------- | ----------------------------------------------------------------------------- |\n| `commands?` | `TavernCommands` | The command table guest actions run through; omit for a read-only session |\n| `onEnded?` | `() => void` | Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n| `serializeNotice?` | `(notice) => unknown \\| null` | Serializes a local notice for `relayNotice`; null skips that notice |\n| `subject` | `TavernSubject` | Snapshot reading, change and removal subscriptions for the hosted subject |\n\n**Example**\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n```\n\n### `TavernHost` members\n\n| Member | Type | Behavior |\n| ------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------- |\n| `acceptAnswerCode()` | `(code) => Promise<MeshPeer>` | Consumes a guest's answer code; resolves with the peer once the channel is open |\n| `createInvitationCode()` | `() => Promise<string>` | Produces a single-use invitation code, QR-compact when the environment allows |\n| `disposalSignal` | `AbortSignal` | Aborted when hosting ends |\n| `dispose()` | `() => void` | Stops hosting: closes every channel and detaches all subscriptions; idempotent |\n| `disposed` | `boolean` | Whether hosting has ended |\n| `kick()` | `(peerId) => void` | Disconnects one guest; the guest observes it and fires `onEnded` |\n| `peers` | `readonly MeshPeer[]` | The guests currently connected |\n| `relayNotice()` | `(notice) => void` | Broadcasts `serializeNotice(notice)` to every guest. Dropped after hosting ended |\n| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernHostEvent`s; handler errors are swallowed; detaches on abort or end |\n| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |\n\n## `joinTavern(options)`\n\nJoins a session as a guest: decodes the invitation code, opens the mesh guest, and returns the answer code to show back. Snapshots mount through `mount` as they arrive; the first non-null mount settles `ready`. The session ends exactly once: from the channel dropping (`TavernError`), an early exit before mounting (`TavernDisposedError`), or disposal.\n\n**Returns:** `Promise<TavernJoinResult<Mounted>>`: the answer code, the guest handle, and the `ready` promise. Rejects with `TavernPairingError` when the invitation code cannot be used.\n\n| Option | Type | Description |\n| ---------------- | ------------------------------- | --------------------------------------------------------------------------------------- |\n| `invitationCode` | `string` | The invitation code the host produced |\n| `mount` | `(snapshot) => Mounted \\| null` | Turns a received snapshot into the mounted mirror; null ignores it. Called per snapshot |\n| `name` | `string` | The guest's display name on the channel |\n| `onEnded?` | `(subject: Mounted) => void` | The channel ended after joining; receives the mounted subject for unmounting |\n| `onNotice?` | `(wire: unknown) => void` | Receives a notice the host relayed: re-emit it in the local UI |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n\n**Example**\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => mySchema.parse(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject),\n});\nawait host.acceptAnswerCode(answerCode);\nawait ready; // the mirror is live\n```\n\n### `TavernJoinResult<Mounted>` members\n\n| Member | Type | Behavior |\n| ------------ | ------------------ | ------------------------------------------------------------------------------------------------ |\n| `answerCode` | `string` | The answer code to show back to the host, QR-compact when the environment allows |\n| `guest` | `TavernGuest` | The guest handle |\n| `ready` | `Promise<Mounted>` | Resolves with the mounted subject on the first mount; rejects with why the session never came up |\n\n### `TavernGuest` members\n\n| Member | Type | Behavior |\n| -------------------- | -------------------------------- | -------------------------------------------------------------------------------------------- |\n| `disposalSignal` | `AbortSignal` | Aborted when the session ends |\n| `dispose()` | `() => void` | Leaves the session; `onEnded` fires exactly once |\n| `disposed` | `boolean` | Whether the session has ended |\n| `sendCommand()` | `(name, args?) => void` | Forwards a command to the host's table; throws `TavernDisposedError` after the session ended |\n| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernGuestEvent`s; handler errors are swallowed; detaches on abort or end |\n| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |\n\n## Types\n\n### `TavernCommands`\n\n```ts\ntype TavernCommand = (args: readonly unknown[]) => void;\ntype TavernCommands = Record<string, TavernCommand>;\n```\n\nThe host's command table, keyed by name: the same functions the host's own UI calls, so guest actions follow exactly the same validation path as local ones. A missing key rejects the guest with `The host has no command named \"...\"`; a throwing handler rejects with its message. Omit the table entirely for a read-only session.\n\n### `TavernSubject`\n\n```ts\ninterface TavernSubject {\n onChanged(listener: () => void): () => void;\n onRemoved(listener: () => void): () => void;\n snapshot(): unknown;\n}\n```\n\nHow the host reads and watches the single subject it shares. `onChanged` is the re-broadcast trigger; `onRemoved` ends hosting; `snapshot()` returns the JSON-serializable state to broadcast, or `null` while the subject is missing (the broadcast skips). A throwing `snapshot` is reported as a `warning` tap event instead of crashing the host.\n\n### `TavernHostEvent`\n\n| Variant | Fires when |\n| -------------------------------------- | ---------------------------------------------------------- |\n| `{ type: 'peer-joined'; peer }` | A guest's channel opened |\n| `{ type: 'peer-left'; peer; reason? }` | A guest's channel closed |\n| `{ type: 'warning'; message; error }` | A transport error or a throwing snapshot read was survived |\n| `{ type: 'dispose' }` | Hosting ended and the tap stream is about to clear |\n\n### `TavernGuestEvent`\n\n| Variant | Fires when |\n| ------------------------------------------ | ------------------------------------------------------ |\n| `{ type: 'rejected'; commandId; message }` | The host rejected a forwarded command |\n| `{ type: 'warning'; message; error }` | A transport error was survived |\n| `{ type: 'dispose' }` | The session ended and the tap stream is about to clear |\n\n## Errors\n\n### `TavernError`\n\nBase class for every Tavern failure; `instanceof TavernError` narrows the whole hierarchy. Channel failures before the first snapshot reject `ready` with this class.\n\n### `TavernPairingError`\n\nThe code the consumer pasted could not be used: garbage, the wrong kind, an expired invitation, or an answer the host refuses. The underlying `@vielzeug/mesh` failure is chained as `cause`.\n\n### `TavernDisposedError`\n\nA stopped host or ended guest was used again: control-plane calls throw it so leaked handles surface, and it rejects `ready` when the guest leaves before the first snapshot.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Tavern: Usage Guide'\ndescription: How to use @vielzeug/tavern.\n---\n\n[[toc]]\n\n## Basic Usage\n\nHost one subject per session; guests join through the invitation/answer code pair. A session always carries exactly one subject: the guest handle needs no routing keys, and the host's command table is the single validation path for local and remote actions alike.\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: { rename: (args) => myStore.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\nconst invitationCode = await host.createInvitationCode();\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => parseAndMount(snapshot),\n name: 'Alex',\n});\nawait host.acceptAnswerCode(answerCode);\nawait ready;\n\nguest.sendCommand('rename', ['Quarterly report']);\n```\n\n## Host a Subject\n\nThe host validates every guest command against its command table: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with its message. The snapshot re-broadcasts on every local change: coalesced on a microtask, so bursts of changes ship one snapshot, not many. `onEnded` fires exactly once when hosting ends, whether the subject was removed or the host was disposed: reset your session UI there instead of intercepting your own `onRemoved` seam.\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n onEnded: () => updateSessionUi(), // hosting ended: subject removed or disposed\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Presence and transport warnings arrive through tap(); the peer list is a getter.\nhost.tap((event) => {\n if (event.type === 'peer-joined') toast(`${event.peer.name ?? 'A guest'} joined`);\n if (event.type === 'peer-left') toast(`${event.peer.name ?? 'A guest'} left`);\n if (event.type === 'warning') log.warn(event.message, event.error);\n updatePeerList(host.peers); // always current inside a presence event\n});\n\nconst invitationCode = await host.createInvitationCode();\n// Show the invitation code (QR or copy/paste); the guest returns an answer code.\nawait host.acceptAnswerCode(answerCode);\n\n// Kick a peer; the guest observes a disconnect and fires onEnded.\nhost.kick(peerId);\n\nhost.dispose(); // stop hosting: every guest disconnects\n```\n\nOmit `commands` for a read-only session: guests mirror the subject, and every command rejects with `The host has no command named \"...\"`.\n\n## Join as a Guest\n\nJoining consumes the invitation code and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot mounts: that transition settles the `ready` promise, so there is no race between the handshake and your code attaching handlers.\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => sanitizeAndMount(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject.id),\n});\nguest.tap((event) => {\n if (event.type === 'rejected') showToast(event.message); // event.commandId names the command it answers\n if (event.type === 'warning') log.warn(event.message, event.error);\n});\n\ntry {\n await ready; // resolves with the mounted mirror once the first snapshot arrives\n} catch (error) {\n showError(error.message); // the channel failed, the host closed it, or the guest left early\n}\n\nguest.sendCommand('rename', ['New name']);\nguest.dispose(); // leave; onEnded fires with the mounted subject exactly once\n```\n\nThe snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. It is called for every snapshot the host broadcasts. Returning `null` ignores one; the first non-null return becomes the mounted subject: it settles `ready` and is passed to `onEnded` when the session ends. A `ready` you never await is safe: its rejection is pre-handled and never surfaces as an unhandled rejection.\n\n## Relay Notices\n\nNotices are ephemeral out-of-band UI signals: a toast fired elsewhere, a comment added. Catalog keys rather than prose cross the wire, so each client translates locally. The host serializes its own notices with `serializeNotice` and relays them with `relayNotice`; guests receive them through `onNotice`.\n\n```ts\n// Host side: forward local notices through the session.\nconst host = hostTavern({\n /* ... */\n serializeNotice: (notice) => (isLocalNotice(notice) ? toWireShape(notice) : null),\n});\nhost.relayNotice(localNotice); // null from serializeNotice skips this one\n\n// Guest side: re-emit received notices in the local UI.\nconst { guest } = await joinTavern({\n /* ... */\n onNotice: (wire) => bus.emit('notify', wire),\n});\n```\n\n**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests: `onNotice` emits locally, the host's local subscription picks it up, and without a guard it would loop. One boolean set during `onNotice` and checked in `serializeNotice` is sufficient: the consumer owns this because only they know their local event system.\n\n## Observe with tap()\n\nBoth handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle stays out of the observability stream: `ready` covers the opening transition on the guest, and `onEnded` covers the closing transition on both handles.\n\n```ts\nimport type { TavernGuestEvent, TavernHostEvent } from '@vielzeug/tavern';\n\nhost.tap((event: TavernHostEvent) => {\n if (event.type === 'warning') log.warn(event.message, event.error); // the original error, not just text\n if (event.type === 'dispose') log.info('hosting ended');\n});\nguest.tap((event: TavernGuestEvent) => {\n if (event.type === 'rejected') log.info(`command ${event.commandId} rejected: ${event.message}`);\n});\n```\n\n## Handle Pairing Mistakes\n\nEvery user-input pairing failure surfaces as `TavernPairingError` from both `acceptAnswerCode` and `joinTavern`: a garbage code, the wrong code kind, an expired invitation, or an answer the host refuses. Catch it to show a helpful message instead of a raw error; the underlying mesh failure is chained as `cause` when you need it.\n\n```ts\nimport { hostTavern, TavernPairingError } from '@vielzeug/tavern';\n\ntry {\n await host.acceptAnswerCode(pastedCode);\n} catch (error) {\n if (error instanceof TavernPairingError) {\n showToast(error.message); // \"That code is an invitation, not a guest answer.\"\n } else {\n throw error;\n }\n}\n```\n\n## Working with Other Vielzeug Libraries\n\nTavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes. The peers carried by tap events and the {@link TavernHost.peers} getter are mesh types, re-exported by tavern so one import types everything.\n\n```ts\nimport type { MeshRtcFactory } from '@vielzeug/mesh';\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n // ... commands, subject\n rtc: myTestRtcFactory, // inject an in-memory WebRTC fake\n});\n```\n\nPair `@vielzeug/ledger` on the host to give the commands tavern applies an undo history: commands applied through the table land in the ledger like local ones.\n\n## Best Practices\n\n- Keep the command table the same functions the host's own UI calls, so guest actions cannot bypass local validation.\n- Return `null` from `snapshot` while the subject is missing: the broadcast simply skips.\n- Reset host-side session UI in `onEnded`: it fires exactly once for subject removal and explicit disposal alike, so you never need to double-wire your own `onRemoved` seam.\n- Await `ready` before trusting the mirror: it names the exact reason a session never came up, and its rejection is safe to ignore when you do not care.\n- Treat notices as catalog keys, not prose: each client translates locally.\n- Guard against notice echo if a tab can both host and guest: one boolean in `serializeNotice` is sufficient.\n- Dispose guests and hosts when their screen unmounts; channels also clean up on disconnect through `onEnded`, which fires exactly once on both sides.\n- Catch `TavernPairingError` separately from other errors: it means the pasted code could not be used, not that something is broken.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Tavern: Examples'\ndescription: Practical examples and recipes for @vielzeug/tavern.\n---\n\n## Examples\n\n- [Share State Across Devices](./examples/share-state-across-devices.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [],
|
|
10
10
|
"typeSignatures": {
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
11
|
+
"MeshPeer": "export type { MeshPeer } from '@vielzeug/mesh';",
|
|
12
|
+
"TavernDisposedError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
|
13
|
+
"TavernError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
|
14
|
+
"TavernPairingError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
|
15
|
+
"joinTavern": "export { joinTavern } from './guest';",
|
|
16
|
+
"hostTavern": "export { hostTavern } from './host';",
|
|
17
|
+
"TavernCommand": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
18
|
+
"TavernCommands": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
19
|
+
"TavernGuest": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
20
|
+
"TavernGuestEvent": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
21
|
+
"TavernGuestOptions": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
22
|
+
"TavernHost": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
23
|
+
"TavernHostEvent": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
24
|
+
"TavernHostOptions": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
25
|
+
"TavernJoinResult": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
26
|
+
"TavernSubject": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';"
|
|
25
27
|
}
|
|
26
28
|
}
|