Skip to content

API Overview ​

SymbolPurposeExecutionCommon gotcha
hostTavern()Host a subject: pairing, command validation, snapshot broadcastSync factoryDisposing ends hosting for every guest
joinTavern()Join a session: consume invitation code, produce answer codeAsyncThe session lives only after the host accepts and the first snapshot mounts
TavernHostHost handle: invitation, answer acceptance, kick, notice relay, presence tapN/Adispose() is idempotent; control-plane methods throw TavernDisposedError after
TavernGuestGuest handle: command forwarding, rejection tap, disposalN/Adispose() fires onEnded exactly once
TavernJoinResultJoin outcome: answer code, guest handle, and the ready promiseN/AA ready nobody awaits never surfaces as an unhandled rejection
TavernHostEventHost observability union for tap(): presence, warnings, disposeN/ALifecycle transitions are onEnded, not events
TavernGuestEventGuest observability union for tap(): rejections, warnings, disposeN/AThe opening transition is ready, not an event
TavernCommandsThe host's command table: a record of handlers keyed by command nameN/AA name the record does not hold rejects without applying
TavernSubjectSnapshot reading, change and removal subscriptionsN/Asnapshot returning null skips the broadcast
TavernErrorBase error for every Tavern failureN/AN/A
TavernPairingErrorThe consumer pasted the wrong kind of pairing codeN/AN/A
TavernDisposedErrorA stopped host or ended guest was used againN/AN/A

Package Entry Point ​

ImportPurpose
@vielzeug/tavernComplete public Tavern API
@vielzeug/tavern/testingTest seam: the fake WebRTC factory for sessions

The MeshPeer type carried by host events and the peers getter is re-exported here, so a single import types everything.

hostTavern(options) ​

Creates 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. Declaring subject.id makes the session named: every guest command must name that id as sendCommand's target, and a command that omits or misses it rejects before the table runs. 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 TavernHostEvents, 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.

Returns: TavernHost: the host handle.

OptionTypeDescription
commands?TavernCommandsThe command table guest actions run through; omit for a read-only session
onEnded?() => voidHosting ended: the subject was removed or dispose() ran. Fires exactly once
rtc?MeshRtcFactoryWebRTC factory: the injection point for tests and non-browser runtimes
serializeNotice?(notice) => unknown | nullSerializes a local notice for relayNotice; null skips that notice
subjectTavernSubjectSnapshot reading, change and removal subscriptions for the hosted subject

Example

ts
import { hostTavern } from '@vielzeug/tavern';

const host = hostTavern({
  commands: {
    rename: (args) => myStore.rename(docId, args[0] as string),
    append: (args) => myStore.append(docId, args[0] as string),
  },
  subject: {
    onChanged: (listener) => myStore.onUpdated(docId, listener),
    onRemoved: (listener) => myStore.onRemoved(docId, listener),
    snapshot: () => myStore.read(docId),
  },
});

TavernHost members ​

MemberTypeBehavior
acceptAnswerCode()(code) => Promise<MeshPeer>Consumes a guest's answer code; resolves with the peer once the channel is open
createInvitationCode()() => Promise<string>Produces a single-use invitation code, QR-compact when the environment allows
disposalSignalAbortSignalAborted when hosting ends
dispose()() => voidStops hosting: closes every channel and detaches all subscriptions; idempotent
disposedbooleanWhether hosting has ended
kick()(peerId) => voidDisconnects one guest; the guest observes it and fires onEnded
peersreadonly MeshPeer[]The guests currently connected
relayNotice()(notice) => voidBroadcasts serializeNotice(notice) to every guest. Dropped after hosting ended
tap()(handler, opts?) => () => voidSubscribes to TavernHostEvents; handler errors are swallowed; detaches on abort or end
[Symbol.dispose]()() => voidDelegates to dispose(); enables using declarations

joinTavern(options) ​

Joins 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.

Returns: Promise<TavernJoinResult<Mounted>>: the answer code, the guest handle, and the ready promise. Rejects with TavernPairingError when the invitation code cannot be used.

OptionTypeDescription
invitationCodestringThe invitation code the host produced
mount(snapshot) => Mounted | nullTurns a received snapshot into the mounted mirror; null ignores it. Called per snapshot
namestringThe guest's display name on the channel
onEnded?(subject: Mounted) => voidThe channel ended after joining; receives the mounted subject for unmounting
onNotice?(wire: unknown) => voidReceives a notice the host relayed: re-emit it in the local UI
rtc?MeshRtcFactoryWebRTC factory: the injection point for tests and non-browser runtimes

Example

ts
import { joinTavern } from '@vielzeug/tavern';

const { answerCode, guest, ready } = await joinTavern({
  invitationCode,
  mount: (snapshot) => mySchema.parse(snapshot),
  name: 'Alex',
  onEnded: (subject) => unmountMirror(subject),
});
await host.acceptAnswerCode(answerCode);
await ready; // the mirror is live

TavernJoinResult<Mounted> members ​

MemberTypeBehavior
answerCodestringThe answer code to show back to the host, QR-compact when the environment allows
guestTavernGuestThe guest handle
readyPromise<Mounted>Resolves with the mounted subject on the first mount; rejects with why the session never came up

TavernGuest members ​

MemberTypeBehavior
disposalSignalAbortSignalAborted when the session ends
dispose()() => voidLeaves the session; onEnded fires exactly once
disposedbooleanWhether the session has ended
sendCommand()(name, args?, target?) => voidForwards a command to the host's table; target is required on a named session; throws TavernDisposedError after the session ended
tap()(handler, opts?) => () => voidSubscribes to TavernGuestEvents; handler errors are swallowed; detaches on abort or end
[Symbol.dispose]()() => voidDelegates to dispose(); enables using declarations

Types ​

TavernCommands ​

ts
type TavernCommand = (args: readonly unknown[]) => void;
type TavernCommands = Record<string, TavernCommand>;

The 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.

TavernSubject ​

ts
interface TavernSubject {
  readonly id?: string;
  onChanged(listener: () => void): () => void;
  onRemoved(listener: () => void): () => void;
  snapshot(): unknown;
}

How 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. id is the subject's stable identity: declaring it puts every command under target verification: guests must pass the id as sendCommand's target, and a missing or mismatched target rejects with That command does not target the hosted subject. before the command table runs. The target is a guest claim, not a proof: the guard catches misrouted commands, while handlers and the command table stay the authorization boundary. Omit id for anonymous sessions, where targets carry no meaning.

TavernHostEvent ​

VariantFires when
{ type: 'peer-joined'; peer }A guest's channel opened
{ type: 'peer-left'; peer; reason? }A guest's channel closed
{ type: 'warning'; message; error }A transport error or a throwing snapshot read was survived
{ type: 'dispose' }Hosting ended and the tap stream is about to clear

TavernGuestEvent ​

VariantFires when
{ type: 'rejected'; commandId; message }The host rejected a forwarded command
{ type: 'warning'; message; error }A transport error was survived
{ type: 'dispose' }The session ended and the tap stream is about to clear

Errors ​

TavernError ​

Base class for every Tavern failure; instanceof TavernError narrows the whole hierarchy. Channel failures before the first snapshot reject ready with this class.

TavernPairingError ​

The 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.

TavernDisposedError ​

A 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.

Testing ​

@vielzeug/tavern/testing re-exports createFakeRtc() (and the FakeRtc type): an in-process fake WebRTC factory you pass as the rtc option of hostTavern and joinTavern to drive a real host/guest pair inside one test process, with no browser or network. Consuming this subpath keeps mesh, tavern's transport, out of your dev dependencies.

ts
import { hostTavern, joinTavern } from '@vielzeug/tavern';
import { createFakeRtc } from '@vielzeug/tavern/testing';

const { rtc } = createFakeRtc();
const host = hostTavern({ rtc, subject });
const guest = await joinTavern({ invitationCode: await host.createInvitationCode(), mount, name, rtc });