@vielzeug/tavern 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.
@@ -0,0 +1,155 @@
1
+ import type { MeshPeer, MeshRtcFactory } from '@vielzeug/mesh';
2
+ /** A single guest-forwardable command; throwing rejects the guest with the error's message. */
3
+ export type TavernCommand = (args: readonly unknown[]) => void;
4
+ /**
5
+ * The host's command table, keyed by name. A guest command is applied only if the table
6
+ * holds it; the same table the host's own UI calls, so remote actions follow exactly the
7
+ * same code path as local ones. Omit the table for a read-only session: guests mirror the
8
+ * subject but every command rejects.
9
+ */
10
+ export type TavernCommands = Record<string, TavernCommand>;
11
+ /** How the host reads and watches the single subject it is sharing. */
12
+ export interface TavernSubject {
13
+ /** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */
14
+ onChanged(listener: () => void): () => void;
15
+ /** Subscribes to the hosted subject's removal: hosting ends when it fires. */
16
+ onRemoved(listener: () => void): () => void;
17
+ /** Reads the snapshot to broadcast; null while the subject is missing. */
18
+ snapshot(): unknown;
19
+ }
20
+ /** Notable host moments reported through {@link TavernHost.tap}. */
21
+ export type TavernHostEvent = {
22
+ readonly type: 'dispose';
23
+ } | {
24
+ readonly peer: MeshPeer;
25
+ readonly type: 'peer-joined';
26
+ } | {
27
+ readonly peer: MeshPeer;
28
+ readonly reason?: string;
29
+ readonly type: 'peer-left';
30
+ } | {
31
+ readonly error: unknown;
32
+ readonly message: string;
33
+ readonly type: 'warning';
34
+ };
35
+ /** Notable guest moments reported through {@link TavernGuest.tap}. */
36
+ export type TavernGuestEvent = {
37
+ readonly type: 'dispose';
38
+ } | {
39
+ readonly commandId: string;
40
+ readonly message: string;
41
+ readonly type: 'rejected';
42
+ } | {
43
+ readonly error: unknown;
44
+ readonly message: string;
45
+ readonly type: 'warning';
46
+ };
47
+ export interface TavernHostOptions {
48
+ /** The command table guest actions run through; omit for a read-only session. */
49
+ commands?: TavernCommands;
50
+ /**
51
+ * Hosting ended: the subject was removed or the host was disposed. Fires exactly
52
+ * once. This is a lifecycle transition, not observability: presence, transport
53
+ * warnings, and the peer list all belong to {@link TavernHost.tap} and
54
+ * {@link TavernHost.peers}.
55
+ */
56
+ onEnded?(): void;
57
+ rtc?: MeshRtcFactory;
58
+ /**
59
+ * Serializes a local notice for the wire via {@link TavernHost.relayNotice}; null skips
60
+ * this one. Notices are ephemeral out-of-band UI signals (a toast fired elsewhere, a
61
+ * comment added); the wire shape is yours.
62
+ *
63
+ * **Echo guard**: a tab that both hosts and guests must guard against re-broadcasting a
64
+ * wire-originated notice back to its own guests: {@link TavernGuestOptions.onNotice}
65
+ * emits locally, the host's local subscription picks it up, and without a guard it would
66
+ * loop. The consumer owns this guard because only they know their local event system; one
67
+ * boolean set during `onNotice` and checked in `serializeNotice` is sufficient.
68
+ */
69
+ serializeNotice?(notice: unknown): unknown | null;
70
+ /** The subject being shared: read, watched, and rebroadcast by tavern. */
71
+ subject: TavernSubject;
72
+ }
73
+ export interface TavernHost {
74
+ /** Consumes a guest's answer code; resolves with the peer once the channel is open. */
75
+ acceptAnswerCode(code: string): Promise<MeshPeer>;
76
+ /** Produces a single-use invitation code, QR-compact when the environment allows. */
77
+ createInvitationCode(): Promise<string>;
78
+ /** `AbortSignal` aborted when hosting ends. */
79
+ readonly disposalSignal: AbortSignal;
80
+ /** Stops hosting: closes every channel and detaches all subscriptions. */
81
+ dispose(): void;
82
+ /** Whether hosting has ended: the subject was removed or `dispose()` ran. */
83
+ readonly disposed: boolean;
84
+ kick(peerId: string): void;
85
+ /** The guests currently connected: read it from a `peer-joined`/`peer-left` tap event. */
86
+ readonly peers: readonly MeshPeer[];
87
+ /** Relays one local notice to every guest; `serializeNotice` decides what crosses.
88
+ * A notice relayed after hosting ended is dropped, not thrown: it is ephemeral
89
+ * UI state with no audience left, unlike the control-plane methods, which fail
90
+ * with `TavernDisposedError` so a leaked handle surfaces. */
91
+ relayNotice(notice: unknown): void;
92
+ /** Subscribes to {@link TavernHostEvent}s. Handler errors are swallowed; the
93
+ * subscription detaches when `signal` aborts or hosting ends. */
94
+ tap(handler: (event: TavernHostEvent) => void, options?: {
95
+ readonly signal?: AbortSignal;
96
+ }): () => void;
97
+ /** Delegates to `dispose()`. Enables `using` declarations. */
98
+ [Symbol.dispose](): void;
99
+ }
100
+ export interface TavernGuestOptions<Mounted> {
101
+ /** The invitation code the host produced. */
102
+ invitationCode: string;
103
+ /**
104
+ * Mounts a received snapshot; the mounted value, or null to ignore. Called for every
105
+ * snapshot the host broadcasts. The snapshot arrives as parsed JSON: validate before
106
+ * trusting it.
107
+ */
108
+ mount(snapshot: unknown): Mounted | null;
109
+ /** The guest's display name on the channel. */
110
+ name: string;
111
+ /**
112
+ * The channel ended after joining; the mounted value is passed for unmounting.
113
+ * Lifecycle, not observability: rejections and transport warnings belong to
114
+ * {@link TavernGuest.tap}, and the opening transition is {@link TavernJoinResult.ready}.
115
+ */
116
+ onEnded?(subject: Mounted): void;
117
+ /** Receives a notice the host relayed: re-emit it in the local UI. */
118
+ onNotice?(wire: unknown): void;
119
+ rtc?: MeshRtcFactory;
120
+ }
121
+ export interface TavernGuest {
122
+ /** `AbortSignal` aborted when the session ends. */
123
+ readonly disposalSignal: AbortSignal;
124
+ /** Leaves the session and drops the channel. */
125
+ dispose(): void;
126
+ /** Whether the session has ended: the channel dropped or `dispose()` ran. */
127
+ readonly disposed: boolean;
128
+ /**
129
+ * Forwards a command to the host's command table. The host rejects a name its table
130
+ * does not hold, and a handler that throws rejects with its message; a successful
131
+ * command needs no separate answer because its effect arrives with the next snapshot.
132
+ * Throws `TavernDisposedError` after the session has ended.
133
+ */
134
+ sendCommand(name: string, args?: readonly unknown[]): void;
135
+ /** Subscribes to {@link TavernGuestEvent}s. Handler errors are swallowed; the
136
+ * subscription detaches when `signal` aborts or the session ends. */
137
+ tap(handler: (event: TavernGuestEvent) => void, options?: {
138
+ readonly signal?: AbortSignal;
139
+ }): () => void;
140
+ /** Delegates to `dispose()`. Enables `using` declarations. */
141
+ [Symbol.dispose](): void;
142
+ }
143
+ export interface TavernJoinResult<Mounted> {
144
+ /** The answer code to show back to the host, QR-compact when the environment allows. */
145
+ readonly answerCode: string;
146
+ readonly guest: TavernGuest;
147
+ /**
148
+ * Resolves with the mounted subject once the host's first snapshot arrives and mounts.
149
+ * Rejects with a `TavernError` if the channel fails or drops before that, or with a
150
+ * `TavernDisposedError` if the guest leaves first. The rejection is pre-handled: a
151
+ * consumer who never awaits `ready` never sees an unhandled rejection.
152
+ */
153
+ readonly ready: Promise<Mounted>;
154
+ }
155
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAE/D,+FAA+F;AAC/F,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,SAAS,OAAO,EAAE,KAAK,IAAI,CAAC;AAE/D;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AAE3D,uEAAuE;AACvE,MAAM,WAAW,aAAa;IAC5B,mFAAmF;IACnF,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,8EAA8E;IAC9E,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,0EAA0E;IAC1E,QAAQ,IAAI,OAAO,CAAC;CACrB;AAED,oEAAoE;AACpE,MAAM,MAAM,eAAe,GACvB;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAA;CAAE,GACzD;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAA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;0EACsE;IACtE,GAAG,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,MAAM,IAAI,CAAC;IACzG,8DAA8D;IAC9D,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB,CAAC,OAAO;IACvC,wFAAwF;IACxF,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;CAClC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vielzeug/tavern",
3
- "version": "26.11.12",
3
+ "version": "26.11.13",
4
4
  "description": "Table sessions over mesh: host-owned state replication with guest command forwarding",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,7 +40,7 @@
40
40
  "test": "vitest"
41
41
  },
42
42
  "dependencies": {
43
- "@vielzeug/mesh": "26.11.12"
43
+ "@vielzeug/mesh": "26.11.13"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/node": "^26.6.6",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["TavernPairingError","createMeshHost","createTappers","TavernDisposedError","meshQrCodec","MeshPairingError","createMeshGuest","require__tappers","require_errors","_vielzeug_mesh","message","error","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","subjectId","args","host","options","tappers","closed","flushScheduled","off","detach","snapshot","command","peerId","payload","event","decoded","text","wire","notice","guest","mounted","ended","subject","answer"],"sources":["../src/index.ts"],"sourcesContent":["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"],"mappings":"A,+JAsBA,SAAS,eAAe,EAAoC,CAC1D,IAAMU,EAAUC,aAAiB,MAAQA,EAAM,QAAU,+BACzD,OAAO,IAAIX,EAAAA,mBAAmBU,EAAS,CAAE,MAAOC,CAAM,CAAC,CACzD,CAyEA,IAAMC,EAA4B,OAE5B,cAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,IAGvG,SAAS,iBAAiB,EAAuF,CAC/G,GAAI,OAAOC,GAAQ,WAAYA,EAAc,OAAO,KACpD,GAAM,CAAE,OAAM,KAAI,OAAM,aAAcA,EAItC,OAHI,OAAOC,GAAO,UAAY,OAAOC,GAAS,UAAY,OAAOC,GAAc,UAAY,CAAC,MAAM,QAAQC,CAAI,EACrG,KAEF,CAAE,OAAM,KAAI,OAAM,WAAU,CACrC,CAqDA,SAAgB,WAAW,EAAwC,CACjE,IAAMC,GAAA,EAAOjB,EA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AULT_MAX_MESSAGE_BYTES","raw","id","name","subjectId","args","host","createMeshHost","options","tappers","createTappers","closed","flushScheduled","off","detach","TavernDisposedError","snapshot","command","peerId","payload","event","decoded","meshQrCodec","text","MeshPairingError","wire","notice","guest","createMeshGuest","mounted","ended","subject","answer","TavernError"],"sources":["../src/index.ts"],"sourcesContent":["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"],"mappings":";;;;AAsBA,SAAS,eAAe,GAAoC;CAC1D,IAAMA,IAAUC,aAAiB,QAAQA,EAAM,UAAU;CACzD,OAAO,IAAIC,EAAmBF,GAAS,EAAE,OAAOC,EAAM,CAAC;AACzD;AAyEA,IAAME,IAA4B,QAE5B,kBAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE;A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