@vielzeug/tavern 26.11.13 → 26.11.14

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.
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs");var t=524288,commandId=()=>`cmd-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;function parseWireCommand(e){if(typeof e!=`object`||!e)return null;let{args:t,id:n,name:r}=e;return typeof n!=`string`||typeof r!=`string`||!Array.isArray(t)?null:{args:t,id:n,name:r}}function toPairingError(t){let n=t instanceof Error?t.message:`That code could not be read.`;return new e.TavernPairingError(n,{cause:t})}function isMeshAnswer(e){return`proof`in e}function isMeshInvitation(e){return`secret`in e}exports.DEFAULT_MAX_MESSAGE_BYTES=t,exports.commandId=commandId,exports.isMeshAnswer=isMeshAnswer,exports.isMeshInvitation=isMeshInvitation,exports.parseWireCommand=parseWireCommand,exports.toPairingError=toPairingError;
1
+ const e=require("./errors.cjs");var t=524288,commandId=()=>`cmd-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;function parseWireCommand(e){if(typeof e!=`object`||!e)return null;let{args:t,id:n,name:r,target:i}=e;return typeof n!=`string`||typeof r!=`string`||!Array.isArray(t)||i!==void 0&&typeof i!=`string`?null:i===void 0?{args:t,id:n,name:r}:{args:t,id:n,name:r,target:i}}function toPairingError(t){let n=t instanceof Error?t.message:`That code could not be read.`;return new e.TavernPairingError(n,{cause:t})}function isMeshAnswer(e){return`proof`in e}function isMeshInvitation(e){return`secret`in e}exports.DEFAULT_MAX_MESSAGE_BYTES=t,exports.commandId=commandId,exports.isMeshAnswer=isMeshAnswer,exports.isMeshInvitation=isMeshInvitation,exports.parseWireCommand=parseWireCommand,exports.toPairingError=toPairingError;
2
2
  //# sourceMappingURL=_protocol.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"_protocol.cjs","names":["TavernPairingError","require_errors","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","message","error","decoded"],"sources":["../src/_protocol.ts"],"sourcesContent":["import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n"],"mappings":"A,gCAKA,IAAaE,EAA4B,OAoB5B,cAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,IAG9G,SAAgB,iBAAiB,EAAkC,CACjE,GAAI,OAAOC,GAAQ,WAAYA,EAAc,OAAO,KACpD,GAAM,CAAE,OAAM,KAAI,QAASA,EAE3B,OADI,OAAOC,GAAO,UAAY,OAAOC,GAAS,UAAY,CAAC,MAAM,QAAQC,CAAI,EAAU,KAChF,CAAE,OAAM,KAAI,MAAK,CAC1B,CAOA,SAAgB,eAAe,EAAoC,CACjE,IAAMC,EAAUC,aAAiB,MAAQA,EAAM,QAAU,+BACzD,OAAO,IAAIR,EAAAA,mBAAmBO,EAAS,CAAE,MAAOC,CAAM,CAAC,CACzD,CAGA,SAAgB,aAAa,EAA6D,CACxF,MAAO,UAAWC,CACpB,CAGA,SAAgB,iBAAiB,EAAiE,CAChG,MAAO,WAAYA,CACrB,C"}
1
+ {"version":3,"file":"_protocol.cjs","names":["TavernPairingError","require_errors","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","target","message","error","decoded"],"sources":["../src/_protocol.ts"],"sourcesContent":["import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command, its arguments, an optional subject\n * target, and an id tagging the reply. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n readonly target?: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, target } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n if (target !== undefined && typeof target !== 'string') return null;\n return target === undefined ? { args, id, name } : { args, id, name, target };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n"],"mappings":"A,gCAKA,IAAaE,EAA4B,OAsB5B,cAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,IAG9G,SAAgB,iBAAiB,EAAkC,CACjE,GAAI,OAAOC,GAAQ,WAAYA,EAAc,OAAO,KACpD,GAAM,CAAE,OAAM,KAAI,OAAM,UAAWA,EAGnC,OAFI,OAAOC,GAAO,UAAY,OAAOC,GAAS,UAAY,CAAC,MAAM,QAAQC,CAAI,GACzEC,IAAW,IAAA,IAAa,OAAOA,GAAW,SAAiB,KACxDA,IAAW,IAAA,GAAY,CAAE,OAAM,KAAI,MAAK,EAAI,CAAE,OAAM,KAAI,OAAM,QAAO,CAC9E,CAOA,SAAgB,eAAe,EAAoC,CACjE,IAAMC,EAAUC,aAAiB,MAAQA,EAAM,QAAU,+BACzD,OAAO,IAAIT,EAAAA,mBAAmBQ,EAAS,CAAE,MAAOC,CAAM,CAAC,CACzD,CAGA,SAAgB,aAAa,EAA6D,CACxF,MAAO,UAAWC,CACpB,CAGA,SAAgB,iBAAiB,EAAiE,CAChG,MAAO,WAAYA,CACrB,C"}
@@ -2,11 +2,13 @@ import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';
2
2
  import { TavernPairingError } from './errors';
3
3
  /** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */
4
4
  export declare const DEFAULT_MAX_MESSAGE_BYTES: number;
5
- /** What travels guest to host: a named command and its arguments, tagged for rejection. */
5
+ /** What travels guest to host: a named command, its arguments, an optional subject
6
+ * target, and an id tagging the reply. */
6
7
  export interface WireCommand {
7
8
  readonly args: unknown[];
8
9
  readonly id: string;
9
10
  readonly name: string;
11
+ readonly target?: string;
10
12
  }
11
13
  export interface WireProtocol extends MeshProtocol {
12
14
  toGuest: {
@@ -1 +1 @@
1
- {"version":3,"file":"_protocol.d.ts","sourceRoot":"","sources":["../src/_protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE9C,2FAA2F;AAC3F,eAAO,MAAM,yBAAyB,QAAa,CAAC;AAEpD,2FAA2F;AAC3F,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,YAAa,SAAQ,YAAY;IAChD,OAAO,EAAE;QACP,MAAM,EAAE,OAAO,CAAC;QAChB,QAAQ,EAAE;YAAE,SAAS,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,CAAC;QACjD,QAAQ,EAAE,OAAO,CAAC;KACnB,CAAC;IACF,MAAM,EAAE;QACN,OAAO,EAAE,WAAW,CAAC;KACtB,CAAC;CACH;AAED,eAAO,MAAM,SAAS,QAAO,MAAoF,CAAC;A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,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,GAAG,IAAI,CAMjE;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB,CAGjE;AAED,2EAA2E;AAC3E,wBAAgB,YAAY,CAAC,OAAO,EAAE,cAAc,GAAG,UAAU,GAAG,OAAO,IAAI,UAAU,CAExF;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,UAAU,GAAG,OAAO,IAAI,cAAc,CAEhG"}
package/dist/_protocol.js CHANGED
@@ -3,11 +3,16 @@ import { TavernPairingError as e } from "./errors.js";
3
3
  var t = 524288, commandId = () => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
4
4
  function parseWireCommand(e) {
5
5
  if (typeof e != "object" || !e) return null;
6
- let { args: t, id: n, name: r } = e;
7
- return typeof n != "string" || typeof r != "string" || !Array.isArray(t) ? null : {
6
+ let { args: t, id: n, name: r, target: i } = e;
7
+ return typeof n != "string" || typeof r != "string" || !Array.isArray(t) || i !== void 0 && typeof i != "string" ? null : i === void 0 ? {
8
8
  args: t,
9
9
  id: n,
10
10
  name: r
11
+ } : {
12
+ args: t,
13
+ id: n,
14
+ name: r,
15
+ target: i
11
16
  };
12
17
  }
13
18
  function toPairingError(t) {
@@ -1 +1 @@
1
- {"version":3,"file":"_protocol.js","names":["DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","message","error","TavernPairingError","decoded"],"sources":["../src/_protocol.ts"],"sourcesContent":["import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n"],"mappings":";;AAKA,IAAaA,IAA4B,QAoB5B,kBAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE;AAG9G,SAAgB,iBAAiB,GAAkC;CACjE,IAAI,OAAOC,KAAQ,aAAYA,GAAc,OAAO;CACpD,IAAM,EAAE,SAAM,OAAI,YAASA;CAE3B,OADI,OAAOC,KAAO,YAAY,OAAOC,KAAS,YAAY,CAAC,MAAM,QAAQC,CAAI,IAAU,OAChF;EAAE;EAAM;EAAI;CAAK;AAC1B;AAOA,SAAgB,eAAe,GAAoC;CACjE,IAAMC,IAAUC,aAAiB,QAAQA,EAAM,UAAU;CACzD,OAAO,IAAIC,EAAmBF,GAAS,EAAE,OAAOC,EAAM,CAAC;AACzD;AAGA,SAAgB,aAAa,GAA6D;CACxF,OAAO,WAAWE;AACpB;AAGA,SAAgB,iBAAiB,GAAiE;CAChG,OAAO,YAAYA;AACrB"}
1
+ {"version":3,"file":"_protocol.js","names":["DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","target","message","error","TavernPairingError","decoded"],"sources":["../src/_protocol.ts"],"sourcesContent":["import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command, its arguments, an optional subject\n * target, and an id tagging the reply. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n readonly target?: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, target } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n if (target !== undefined && typeof target !== 'string') return null;\n return target === undefined ? { args, id, name } : { args, id, name, target };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n"],"mappings":";;AAKA,IAAaA,IAA4B,QAsB5B,kBAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE;AAG9G,SAAgB,iBAAiB,GAAkC;CACjE,IAAI,OAAOC,KAAQ,aAAYA,GAAc,OAAO;CACpD,IAAM,EAAE,SAAM,OAAI,SAAM,cAAWA;CAGnC,OAFI,OAAOC,KAAO,YAAY,OAAOC,KAAS,YAAY,CAAC,MAAM,QAAQC,CAAI,KACzEC,MAAW,KAAA,KAAa,OAAOA,KAAW,WAAiB,OACxDA,MAAW,KAAA,IAAY;EAAE;EAAM;EAAI;CAAK,IAAI;EAAE;EAAM;EAAI;EAAM;CAAO;AAC9E;AAOA,SAAgB,eAAe,GAAoC;CACjE,IAAMC,IAAUC,aAAiB,QAAQA,EAAM,UAAU;CACzD,OAAO,IAAIC,EAAmBF,GAAS,EAAE,OAAOC,EAAM,CAAC;AACzD;AAGA,SAAgB,aAAa,GAA6D;CACxF,OAAO,WAAWE;AACpB;AAGA,SAAgB,iBAAiB,GAAiE;CAChG,OAAO,YAAYA;AACrB"}
package/dist/guest.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./_protocol.cjs"),t=require("./_tappers.cjs"),n=require("./errors.cjs");let r=require("@vielzeug/mesh");async function joinTavern(i){let a;try{a=await r.meshQrCodec.decode(i.invitationCode)}catch(t){throw t instanceof r.MeshPairingError?e.toPairingError(t):t}if(!e.isMeshInvitation(a))throw new n.TavernPairingError(`That code is not a session invitation.`);let o=(0,r.createMeshGuest)({maxMessageBytes:e.DEFAULT_MAX_MESSAGE_BYTES,rtc:i.rtc}),s=t.createTappers(),c=null,l=!1,u,d,f=new Promise((e,t)=>{u=e,d=t});f.catch(()=>void 0);let endSession=e=>{if(l)return;l=!0;let t=c;c=null;for(let e of p.splice(0))e();o.dispose(),s.emit({type:`dispose`}),s.stop(),t===null?d(e):i.onEnded?.(t)},p=[o.on(`snapshot`,({payload:e})=>{let t=i.mount(e);t===null||l||c===null&&(c=t,u(t))}),o.on(`notice`,({payload:e})=>{i.onNotice?.(e)}),o.on(`rejected`,({payload:e})=>{s.emit({commandId:e.commandId,message:e.message||`The host rejected the action.`,type:`rejected`})}),o.tap(e=>{e.type===`ice-state`&&e.state===`failed`?endSession(new n.TavernError(`The connection to the host failed.`)):e.type!==`status-change`&&e.type!==`peer-status-change`||e.type===`peer-status-change`&&e.peerId!==o.host?.id||(e.status===`failed`&&endSession(new n.TavernError(`The host did not accept the answer in time.`)),e.status===`disconnected`&&endSession(new n.TavernError(`The host closed the session.`)))}),o.tap(e=>{e.type===`error`&&s.emit({error:e.error,message:e.error.message,type:`warning`})})];try{let t=await o.acceptInvitation(a,{name:i.name});return{answerCode:await r.meshQrCodec.encode(t),guest:{get disposalSignal(){return o.disposalSignal},dispose:()=>endSession(new n.TavernDisposedError(`The guest left before the first snapshot arrived.`)),get disposed(){return l},sendCommand:(t,r=[])=>{if(l)throw new n.TavernDisposedError(`The session has ended.`);o.send(`command`,{args:[...r],id:e.commandId(),name:t})},tap:s.tap,[Symbol.dispose](){endSession(new n.TavernDisposedError(`The guest left before the first snapshot arrived.`))}},ready:f}}catch(t){let i=t instanceof r.MeshPairingError?e.toPairingError(t):t;throw endSession(i instanceof Error?i:new n.TavernError(`The invitation could not be accepted.`)),i}}exports.joinTavern=joinTavern;
1
+ const e=require("./_protocol.cjs"),t=require("./_tappers.cjs"),n=require("./errors.cjs");let r=require("@vielzeug/mesh");async function joinTavern(i){let a;try{a=await r.meshQrCodec.decode(i.invitationCode)}catch(t){throw t instanceof r.MeshPairingError?e.toPairingError(t):t}if(!e.isMeshInvitation(a))throw new n.TavernPairingError(`That code is not a session invitation.`);let o=(0,r.createMeshGuest)({maxMessageBytes:e.DEFAULT_MAX_MESSAGE_BYTES,rtc:i.rtc}),s=t.createTappers(),c=null,l=!1,u,d,f=new Promise((e,t)=>{u=e,d=t});f.catch(()=>void 0);let endSession=e=>{if(l)return;l=!0;let t=c;c=null;for(let e of p.splice(0))e();o.dispose(),s.emit({type:`dispose`}),s.stop(),t===null?d(e):i.onEnded?.(t)},p=[o.on(`snapshot`,({payload:e})=>{let t=i.mount(e);t===null||l||c===null&&(c=t,u(t))}),o.on(`notice`,({payload:e})=>{i.onNotice?.(e)}),o.on(`rejected`,({payload:e})=>{s.emit({commandId:e.commandId,message:e.message||`The host rejected the action.`,type:`rejected`})}),o.tap(e=>{e.type===`ice-state`&&e.state===`failed`?endSession(new n.TavernError(`The connection to the host failed.`)):e.type!==`status-change`&&e.type!==`peer-status-change`||e.type===`peer-status-change`&&e.peerId!==o.host?.id||(e.status===`failed`&&endSession(new n.TavernError(`The host did not accept the answer in time.`)),e.status===`disconnected`&&endSession(new n.TavernError(`The host closed the session.`)))}),o.tap(e=>{e.type===`error`&&s.emit({error:e.error,message:e.error.message,type:`warning`})})];try{let t=await o.acceptInvitation(a,{name:i.name});return{answerCode:await r.meshQrCodec.encode(t),guest:{get disposalSignal(){return o.disposalSignal},dispose:()=>endSession(new n.TavernDisposedError(`The guest left before the first snapshot arrived.`)),get disposed(){return l},sendCommand:(t,r=[],i)=>{if(l)throw new n.TavernDisposedError(`The session has ended.`);o.send(`command`,{args:[...r],id:e.commandId(),name:t,...i===void 0?void 0:{target:i}})},tap:s.tap,[Symbol.dispose](){endSession(new n.TavernDisposedError(`The guest left before the first snapshot arrived.`))}},ready:f}}catch(t){let i=t instanceof r.MeshPairingError?e.toPairingError(t):t;throw endSession(i instanceof Error?i:new n.TavernError(`The invitation could not be accepted.`)),i}}exports.joinTavern=joinTavern;
2
2
  //# sourceMappingURL=guest.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"guest.cjs","names":["meshQrCodec","MeshPairingError","toPairingError","isMeshInvitation","TavernPairingError","createMeshGuest","DEFAULT_MAX_MESSAGE_BYTES","createTappers","TavernError","TavernDisposedError","commandId","require__protocol","require__tappers","require_errors","_vielzeug_mesh","decoded","options","error","guest","tappers","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","event","answer","args","wrapped"],"sources":["../src/guest.ts"],"sourcesContent":["import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (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 });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n"],"mappings":"A,yHAYA,eAAsB,WAAoB,EAA0E,CAClH,IAAIe,EACJ,GAAI,CACF,EAAU,MAAMf,EAAAA,YAAY,OAAOgB,EAAQ,cAAc,CAC3D,OAASC,EAAO,CACd,MAAMA,aAAiBhB,EAAAA,iBAAmBC,EAAAA,eAAee,CAAK,EAAIA,CACpE,CACA,GAAI,CAACd,EAAAA,iBAAiBY,CAAO,EAC3B,MAAM,IAAIX,EAAAA,mBAAmB,wCAAwC,EAGvE,IAAMc,GAAA,EAAQb,EAAAA,gBAAAA,CAA8B,CAC1C,gBAAiBC,EAAAA,0BACjB,IAAKU,EAAQ,GACf,CAAC,EACKG,EAAUZ,EAAAA,cAAgC,EAC5Ca,EAA0B,KAC1BC,EAAQ,GACRC,EACAC,EACEC,EAAQ,IAAI,SAAkB,EAAS,IAAW,CACtD,EAAeC,EACf,EAAcC,CAChB,CAAC,EAEDF,EAAW,UAAY,IAAA,EAAS,EAGhC,IAAM,WAAc,GAA2B,CAC7C,GAAIH,EAAO,OACX,EAAQ,GACR,IAAMM,EAAUP,EAChB,EAAU,KACV,IAAK,IAAMQ,KAAOC,EAAO,OAAO,CAAC,EAAGD,EAAI,EACxCV,EAAM,QAAQ,EACdC,EAAQ,KAAK,CAAE,KAAM,SAAU,CAAC,EAChCA,EAAQ,KAAK,EACTQ,IAAY,KACXJ,EAAYO,CAAS,EADJd,EAAQ,UAAUW,CAAO,CAEjD,EAEME,EAAS,CACbX,EAAM,GAAG,YAAa,CAAE,aAAc,CACpC,IAAMS,EAAUX,EAAQ,MAAMe,CAAO,EACjCJ,IAAY,MAAQN,GACpBD,IAAY,OACd,EAAUO,EACVL,EAAaK,CAAO,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,EACA,IAAKS,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,WAAW,IAAIV,EAAAA,oBAAoB,mDAAmD,CAAC,CACzF,CACF,EACA,OACF,CACF,OAASQ,EAAO,CAEd,IAAMkB,EAAUlB,aAAiBhB,EAAAA,iBAAmBC,EAAAA,eAAee,CAAK,EAAIA,EAE5E,MADA,WAAWkB,aAAmB,MAAQA,EAAU,IAAI3B,EAAAA,YAAY,uCAAuC,CAAC,EAClG2B,CACR,CACF,C"}
1
+ {"version":3,"file":"guest.cjs","names":["meshQrCodec","MeshPairingError","toPairingError","isMeshInvitation","TavernPairingError","createMeshGuest","DEFAULT_MAX_MESSAGE_BYTES","createTappers","TavernError","TavernDisposedError","commandId","require__protocol","require__tappers","require_errors","_vielzeug_mesh","decoded","options","error","guest","tappers","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","event","answer","args","target","wrapped"],"sources":["../src/guest.ts"],"sourcesContent":["import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = [], target?: string): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', {\n args: [...args],\n id: commandId(),\n name,\n ...(target === undefined ? undefined : { target }),\n });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n"],"mappings":"A,yHAYA,eAAsB,WAAoB,EAA0E,CAClH,IAAIe,EACJ,GAAI,CACF,EAAU,MAAMf,EAAAA,YAAY,OAAOgB,EAAQ,cAAc,CAC3D,OAASC,EAAO,CACd,MAAMA,aAAiBhB,EAAAA,iBAAmBC,EAAAA,eAAee,CAAK,EAAIA,CACpE,CACA,GAAI,CAACd,EAAAA,iBAAiBY,CAAO,EAC3B,MAAM,IAAIX,EAAAA,mBAAmB,wCAAwC,EAGvE,IAAMc,GAAA,EAAQb,EAAAA,gBAAAA,CAA8B,CAC1C,gBAAiBC,EAAAA,0BACjB,IAAKU,EAAQ,GACf,CAAC,EACKG,EAAUZ,EAAAA,cAAgC,EAC5Ca,EAA0B,KAC1BC,EAAQ,GACRC,EACAC,EACEC,EAAQ,IAAI,SAAkB,EAAS,IAAW,CACtD,EAAeC,EACf,EAAcC,CAChB,CAAC,EAEDF,EAAW,UAAY,IAAA,EAAS,EAGhC,IAAM,WAAc,GAA2B,CAC7C,GAAIH,EAAO,OACX,EAAQ,GACR,IAAMM,EAAUP,EAChB,EAAU,KACV,IAAK,IAAMQ,KAAOC,EAAO,OAAO,CAA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gBAAiB,CACnB,OAAOf,EAAM,cACf,EACA,YAAe,WAAW,IAAIT,EAAAA,oBAAoB,mDAAmD,CAAC,EACtG,IAAI,UAAW,CACb,OAAOY,CACT,EACA,aAAc,EAAc,EAA2B,CAAC,EAAG,IAA0B,CACnF,GAAIA,EAAO,MAAM,IAAIZ,EAAAA,oBAAoB,wBAAwB,EACjES,EAAM,KAAK,UAAW,CACpB,KAAM,CAAC,GAAGgB,CAAI,EACd,GAAIxB,EAAAA,UAAU,EACd,OACA,GAAIyB,IAAW,IAAA,GAAY,IAAA,GAAY,CAAE,QAAO,CAClD,CAAC,CACH,EACA,IAAKhB,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,WAAW,IAAIV,EAAAA,oBAAoB,mDAAmD,CAAC,CACzF,CACF,EACA,OACF,CACF,OAASQ,EAAO,CAEd,IAAMmB,EAAUnB,aAAiBhB,EAAAA,iBAAmBC,EAAAA,eAAee,CAAK,EAAIA,EAE5E,MADA,WAAWmB,aAAmB,MAAQA,EAAU,IAAI5B,EAAAA,YAAY,uCAAuC,CAAC,EAClG4B,CACR,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"guest.d.ts","sourceRoot":"","sources":["../src/guest.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoB,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEtF;;;;;GAKG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,kBAAkB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CA4GlH"}
1
+ {"version":3,"file":"guest.d.ts","sourceRoot":"","sources":["../src/guest.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoB,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEtF;;;;;GAKG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,kBAAkB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAiHlH"}
package/dist/guest.js CHANGED
@@ -63,12 +63,13 @@ async function joinTavern(d) {
63
63
  get disposed() {
64
64
  return g;
65
65
  },
66
- sendCommand: (e, n = []) => {
66
+ sendCommand: (e, n = [], r) => {
67
67
  if (g) throw new a("The session has ended.");
68
68
  p.send("command", {
69
69
  args: [...n],
70
70
  id: t(),
71
- name: e
71
+ name: e,
72
+ ...r === void 0 ? void 0 : { target: r }
72
73
  });
73
74
  },
74
75
  tap: m.tap,
package/dist/guest.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"guest.js","names":["decoded","meshQrCodec","options","error","MeshPairingError","toPairingError","isMeshInvitation","TavernPairingError","guest","createMeshGuest","DEFAULT_MAX_MESSAGE_BYTES","tappers","createTappers","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","event","TavernError","answer","TavernDisposedError","args","commandId","wrapped"],"sources":["../src/guest.ts"],"sourcesContent":["import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (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 });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n"],"mappings":";;;;;AAYA,eAAsB,WAAoB,GAA0E;CAClH,IAAIA;CACJ,IAAI;EACF,IAAU,MAAMC,EAAY,OAAOC,EAAQ,cAAc;CAC3D,SAASC,GAAO;EACd,MAAMA,aAAiBC,IAAmBC,EAAeF,CAAK,IAAIA;CACpE;CACA,IAAI,CAACG,EAAiBN,CAAO,GAC3B,MAAM,IAAIO,EAAmB,wCAAwC;CAGvE,IAAMC,IAAQC,EAA8B;EAC1C,iBAAiBC;EACjB,KAAKR,EAAQ;CACf,CAAC,GACKS,IAAUC,EAAgC,GAC5CC,IAA0B,MAC1BC,IAAQ,IACRC,GACAC,GACEC,IAAQ,IAAI,SAAkB,GAAS,MAAW;EAEtD,AADA,IAAeC,GACf,IAAcC;CAChB,CAAC;CAED,EAAW,YAAY,KAAA,CAAS;CAGhC,IAAM,cAAc,MAA2B;EAC7C,IAAIL,GAAO;EACX,IAAQ;EACR,IAAMM,IAAUP;EAChB,IAAU;EACV,KAAK,IAAMQ,KAAOC,EAAO,OAAO,CAAC,GAAG,EAAI;EAIxC,AAHAd,EAAM,QAAQ,GACdG,EAAQ,KAAK,EAAE,MAAM,UAAU,C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AAC;IACtG,IAAI,WAAW;KACb,OAAOd;IACT;IACA,cAAc,GAAc,IAA2B,CAAC,MAAY;KAClE,IAAIA,GAAO,MAAM,IAAIc,EAAoB,wBAAwB;KACjE,EAAM,KAAK,WAAW;MAAE,MAAM,CAAC,GAAGC,CAAI;MAAG,IAAIC,EAAU;MAAG;KAAK,CAAC;IAClE;IACA,KAAKnB,EAAQ;IACb,CAAC,OAAO,WAAW;KACjB,WAAW,IAAIiB,EAAoB,mDAAmD,CAAC;IACzF;GACF;GACA;EACF;CACF,SAASzB,GAAO;EAEd,IAAM4B,IAAU5B,aAAiBC,IAAmBC,EAAeF,CAAK,IAAIA;EAE5E,MADA,WAAW4B,aAAmB,QAAQA,IAAU,IAAIL,EAAY,uCAAuC,CAAC,GAClGK;CACR;AACF"}
1
+ {"version":3,"file":"guest.js","names":["decoded","meshQrCodec","options","error","MeshPairingError","toPairingError","isMeshInvitation","TavernPairingError","guest","createMeshGuest","DEFAULT_MAX_MESSAGE_BYTES","tappers","createTappers","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","event","TavernError","answer","TavernDisposedError","args","commandId","target","wrapped"],"sources":["../src/guest.ts"],"sourcesContent":["import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = [], target?: string): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', {\n args: [...args],\n id: commandId(),\n name,\n ...(target === undefined ? undefined : { target }),\n });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n"],"mappings":";;;;;AAYA,eAAsB,WAAoB,GAA0E;CAClH,IAAIA;CACJ,IAAI;EACF,IAAU,MAAMC,EAAY,OAAOC,EAAQ,cAAc;CAC3D,SAASC,GAAO;EACd,MAAMA,aAAiBC,IAAmBC,EAAeF,CAAK,IAAIA;CACpE;CACA,IAAI,CAACG,EAAiBN,CAAO,GAC3B,MAAM,IAAIO,EAAmB,wCAAwC;CAGvE,IAAMC,IAAQC,EAA8B;EAC1C,iBAAiBC;EACjB,KAAKR,EAAQ;CACf,CAAC,GACKS,IAAUC,EAAgC,GAC5CC,IAA0B,MAC1BC,IAAQ,IACRC,GACAC,GACEC,IAAQ,IAAI,SAAkB,GAAS,MAAW;EAEtD,AADA,IAAeC,GACf,IAAcC;CAChB,CAAC;CAED,EAAW,YAAY,KAAA,CAAS;CAGhC,IAAM,cAAc,MAA2B;EAC7C,IAAIL,GAAO;EACX,IAAQ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AAC;EAC3E,OAAO;GACL,YAAY,MAAMD,EAAY,OAAO0B,CAAM;GAC3C,OAAO;IACL,IAAI,iBAAiB;KACnB,OAAOnB,EAAM;IACf;IACA,eAAe,WAAW,IAAIoB,EAAoB,mDAAmD,CAAC;IACtG,IAAI,WAAW;KACb,OAAOd;IACT;IACA,cAAc,GAAc,IAA2B,CAAC,GAAG,MAA0B;KACnF,IAAIA,GAAO,MAAM,IAAIc,EAAoB,wBAAwB;KACjE,EAAM,KAAK,WAAW;MACpB,MAAM,CAAC,GAAGC,CAAI;MACd,IAAIC,EAAU;MACd;MACA,GAAIC,MAAW,KAAA,IAAY,KAAA,IAAY,EAAE,UAAO;KAClD,CAAC;IACH;IACA,KAAKpB,EAAQ;IACb,CAAC,OAAO,WAAW;KACjB,WAAW,IAAIiB,EAAoB,mDAAmD,CAAC;IACzF;GACF;GACA;EACF;CACF,SAASzB,GAAO;EAEd,IAAM6B,IAAU7B,aAAiBC,IAAmBC,EAAeF,CAAK,IAAIA;EAE5E,MADA,WAAW6B,aAAmB,QAAQA,IAAU,IAAIN,EAAY,uCAAuC,CAAC,GAClGM;CACR;AACF"}
package/dist/host.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./_protocol.cjs"),t=require("./_tappers.cjs"),n=require("./errors.cjs");let r=require("@vielzeug/mesh");function hostTavern(i){let a=(0,r.createMeshHost)({maxMessageBytes:e.DEFAULT_MAX_MESSAGE_BYTES,rtc:i.rtc}),o=t.createTappers(),s=!1,c=!1,close=()=>{if(!s){s=!0;for(let e of l.splice(0))e();a.dispose(),o.emit({type:`dispose`}),o.stop(),i.onEnded?.()}},disposedError=()=>new n.TavernDisposedError(`This host has stopped.`),warn=e=>{o.emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},readSnapshot=()=>{try{return i.subject.snapshot()}catch(e){return warn(e),null}},broadcastSnapshot=()=>{s||c||(c=!0,queueMicrotask(()=>{if(c=!1,s)return;let e=readSnapshot();e!=null&&a.broadcast(`snapshot`,e)}))},handleGuestCommand=(t,n)=>{let r=e.parseWireCommand(n);if(!r){a.send(t,`rejected`,{commandId:``,message:`That command could not be read.`});return}let o=i.commands,s=o&&Object.hasOwn(o,r.name)?o[r.name]:void 0;if(typeof s!=`function`)a.send(t,`rejected`,{commandId:r.id,message:`The host has no command named "${r.name}".`});else try{s(r.args)}catch(e){a.send(t,`rejected`,{commandId:r.id,message:e instanceof Error?e.message:`The host could not apply the command.`})}},l=[a.on(`command`,({peerId:e,payload:t})=>handleGuestCommand(e,t)),i.subject.onChanged(broadcastSnapshot),i.subject.onRemoved(close),a.tap(e=>{if(e.type===`peer-joined`){let t=readSnapshot();t!=null&&a.send(e.peer.id,`snapshot`,t),o.emit({peer:e.peer,type:`peer-joined`})}e.type===`peer-left`&&o.emit({peer:e.peer,reason:e.reason,type:`peer-left`}),e.type===`error`&&warn(e.error)})];return{acceptAnswerCode:async t=>{if(s)throw disposedError();let i;try{i=await r.meshQrCodec.decode(t)}catch(t){throw t instanceof r.MeshPairingError?e.toPairingError(t):t}if(!e.isMeshAnswer(i))throw new n.TavernPairingError(`That code is an invitation, not a guest answer.`);try{return await a.acceptAnswer(i)}catch(t){throw t instanceof r.MeshPairingError?e.toPairingError(t):t}},createInvitationCode:async()=>{if(s)throw disposedError();return r.meshQrCodec.encode(await a.createInvitation())},get disposalSignal(){return a.disposalSignal},dispose:close,get disposed(){return s},kick:e=>{if(s)throw disposedError();a.kick(e)},get peers(){return[...a.peers.values()]},relayNotice:e=>{if(s)return;let t=i.serializeNotice?i.serializeNotice(e):null;t!=null&&a.broadcast(`notice`,t)},tap:o.tap,[Symbol.dispose](){close()}}}exports.hostTavern=hostTavern;
1
+ const e=require("./_protocol.cjs"),t=require("./_tappers.cjs"),n=require("./errors.cjs");let r=require("@vielzeug/mesh");function hostTavern(i){let a=(0,r.createMeshHost)({maxMessageBytes:e.DEFAULT_MAX_MESSAGE_BYTES,rtc:i.rtc}),o=t.createTappers(),s=!1,c=!1,close=()=>{if(!s){s=!0;for(let e of l.splice(0))e();a.dispose(),o.emit({type:`dispose`}),o.stop(),i.onEnded?.()}},disposedError=()=>new n.TavernDisposedError(`This host has stopped.`),warn=e=>{o.emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},readSnapshot=()=>{try{return i.subject.snapshot()}catch(e){return warn(e),null}},broadcastSnapshot=()=>{s||c||(c=!0,queueMicrotask(()=>{if(c=!1,s)return;let e=readSnapshot();e!=null&&a.broadcast(`snapshot`,e)}))},handleGuestCommand=(t,n)=>{let r=e.parseWireCommand(n);if(!r){a.send(t,`rejected`,{commandId:``,message:`That command could not be read.`});return}if(i.subject.id!==void 0&&r.target!==i.subject.id){a.send(t,`rejected`,{commandId:r.id,message:`That command does not target the hosted subject.`});return}let o=i.commands,s=o&&Object.hasOwn(o,r.name)?o[r.name]:void 0;if(typeof s!=`function`)a.send(t,`rejected`,{commandId:r.id,message:`The host has no command named "${r.name}".`});else try{s(r.args)}catch(e){a.send(t,`rejected`,{commandId:r.id,message:e instanceof Error?e.message:`The host could not apply the command.`})}},l=[a.on(`command`,({peerId:e,payload:t})=>handleGuestCommand(e,t)),i.subject.onChanged(broadcastSnapshot),i.subject.onRemoved(close),a.tap(e=>{if(e.type===`peer-joined`){let t=readSnapshot();t!=null&&a.send(e.peer.id,`snapshot`,t),o.emit({peer:e.peer,type:`peer-joined`})}e.type===`peer-left`&&o.emit({peer:e.peer,reason:e.reason,type:`peer-left`}),e.type===`error`&&warn(e.error)})];return{acceptAnswerCode:async t=>{if(s)throw disposedError();let i;try{i=await r.meshQrCodec.decode(t)}catch(t){throw t instanceof r.MeshPairingError?e.toPairingError(t):t}if(!e.isMeshAnswer(i))throw new n.TavernPairingError(`That code is an invitation, not a guest answer.`);try{return await a.acceptAnswer(i)}catch(t){throw t instanceof r.MeshPairingError?e.toPairingError(t):t}},createInvitationCode:async()=>{if(s)throw disposedError();return r.meshQrCodec.encode(await a.createInvitation())},get disposalSignal(){return a.disposalSignal},dispose:close,get disposed(){return s},kick:e=>{if(s)throw disposedError();a.kick(e)},get peers(){return[...a.peers.values()]},relayNotice:e=>{if(s)return;let t=i.serializeNotice?i.serializeNotice(e):null;t!=null&&a.broadcast(`notice`,t)},tap:o.tap,[Symbol.dispose](){close()}}}exports.hostTavern=hostTavern;
2
2
  //# sourceMappingURL=host.cjs.map
package/dist/host.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.cjs","names":["createMeshHost","DEFAULT_MAX_MESSAGE_BYTES","createTappers","TavernDisposedError","parseWireCommand","meshQrCodec","MeshPairingError","toPairingError","isMeshAnswer","TavernPairingError","require__protocol","require__tappers","require_errors","_vielzeug_mesh","host","options","tappers","closed","flushScheduled","off","detach","error","snapshot","command","raw","peerId","table","apply","payload","event","decoded","code","wire","notice"],"sources":["../src/host.ts"],"sourcesContent":["import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":"A,yHAwBA,SAAgB,WAAW,EAAwC,CACjE,IAAMc,GAAA,EAAOd,EAAAA,eAAAA,CAA6B,CACxC,gBAAiBC,EAAAA,0BACjB,IAAKc,EAAQ,GACf,CAAC,EACKC,EAAUd,EAAAA,cAA+B,EAC3Ce,EAAS,GACTC,EAAiB,GAEf,UAAoB,CACxB,GAAI,GACJ,GAAS,GACT,IAAK,IAAMC,KAAOC,EAAO,OAAO,CAAC,EAAGD,EAAI,EACxCL,EAAK,QAAQ,EACbE,EAAQ,KAAK,CAAE,KAAM,SAAU,CAAC,EAChCA,EAAQ,KAAK,EACbD,EAAQ,UAAU,CALT,CAMX,EACM,kBAA2C,IAAIZ,EAAAA,oBAAoB,wBAAwB,EAC3F,KAAQ,GAAyB,CACrCa,EAAQ,KAAK,CAAE,QAAO,QAASK,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EAAG,KAAM,SAAU,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b,CAAC,OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
1
+ {"version":3,"file":"host.cjs","names":["createMeshHost","DEFAULT_MAX_MESSAGE_BYTES","createTappers","TavernDisposedError","parseWireCommand","meshQrCodec","MeshPairingError","toPairingError","isMeshAnswer","TavernPairingError","require__protocol","require__tappers","require_errors","_vielzeug_mesh","host","options","tappers","closed","flushScheduled","off","detach","error","snapshot","command","raw","peerId","table","apply","payload","event","decoded","code","wire","notice"],"sources":["../src/host.ts"],"sourcesContent":["import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // A named session checks every command's target: missing and mismatched targets are\n // rejected before the table runs, so a guest cannot opt out of naming its subject.\n // (The command table stays the authorization boundary; this guards honest misrouting.)\n if (options.subject.id !== undefined && command.target !== options.subject.id) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: 'That command does not target the hosted subject.',\n });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":"A,yHAwBA,SAAgB,WAAW,EAAwC,CACjE,IAAMc,GAAA,EAAOd,EAAAA,eAAAA,CAA6B,CACxC,gBAAiBC,EAAAA,0BACjB,IAAKc,EAAQ,GACf,CAAC,EACKC,EAAUd,EAAAA,cAA+B,EAC3Ce,EAAS,GACTC,EAAiB,GAEf,UAAoB,CACxB,GAAI,GACJ,GAAS,GACT,IAAK,IAAMC,KAAOC,EAAO,OAAO,CAAC,EAAGD,EAAI,EACxCL,EAAK,QAAQ,EACbE,EAAQ,KAAK,CAAE,KAAM,SAAU,CAAC,EAChCA,EAAQ,KAAK,EACbD,EAAQ,UAAU,CALT,CAMX,EACM,kBAA2C,IAAIZ,EAAAA,oBAAoB,wBAAwB,EAC3F,KAAQ,GAAyB,CACrCa,EAAQ,KAAK,CAAE,QAAO,QAASK,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EAAG,KAAM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,YAAc,GAA0B,CACtC,GAAIG,EAAQ,OACZ,IAAMe,EAAOjB,EAAQ,gBAAkBA,EAAQ,gBAAgBkB,CAAM,EAAI,KACrED,GAAS,MAA4BlB,EAAK,UAAU,SAAUkB,CAAI,CACxE,EACA,IAAKhB,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,UAAU,EAAmB,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE9E;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,UAAU,CAwIjE"}
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,UAAU,EAAmB,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE9E;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,UAAU,CAkJjE"}
package/dist/host.js CHANGED
@@ -40,6 +40,13 @@ function hostTavern(u) {
40
40
  });
41
41
  return;
42
42
  }
43
+ if (u.subject.id !== void 0 && r.target !== u.subject.id) {
44
+ d.send(e, "rejected", {
45
+ commandId: r.id,
46
+ message: "That command does not target the hosted subject."
47
+ });
48
+ return;
49
+ }
43
50
  let i = u.commands, a = i && Object.hasOwn(i, r.name) ? i[r.name] : void 0;
44
51
  if (typeof a != "function") d.send(e, "rejected", {
45
52
  commandId: r.id,
package/dist/host.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":["host","createMeshHost","DEFAULT_MAX_MESSAGE_BYTES","options","tappers","createTappers","closed","flushScheduled","off","detach","TavernDisposedError","error","snapshot","command","parseWireCommand","raw","peerId","table","apply","payload","event","decoded","meshQrCodec","code","MeshPairingError","toPairingError","isMeshAnswer","TavernPairingError","wire","notice"],"sources":["../src/host.ts"],"sourcesContent":["import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":";;;;;AAwBA,SAAgB,WAAW,GAAwC;CACjE,IAAMA,IAAOC,EAA6B;EACxC,iBAAiBC;EACjB,KAAKC,EAAQ;CACf,CAAC,GACKC,IAAUC,EAA+B,GAC3CC,IAAS,IACTC,IAAiB,IAEf,cAAoB;EACxB,IAAI,IACJ;OAAS;GACT,KAAK,IAAMC,KAAOC,EAAO,OAAO,CAAC,GAAG,EAAI;GAIxC,AAHAT,EAAK,QAAQ,GACbI,EAAQ,KAAK,EAAE,MAAM,UAAU,CAAC,GAChCA,EAAQ,KAAK,GACbD,EAAQ,UAAU;EALT;CAMX,GACM,sBAA2C,IAAIO,EAAoB,wBAAwB,GAC3F,QAAQ,MAAyB;EACrC,EAAQ,KAAK;GAAE;GAAO,SAASC,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;GAAG,MAAM;EAAU,CAAC;CAC1G,GAGM,qBAA8B;EAClC,IAAI;GACF,OAAOR,EAAQ,QAAQ,SAAS;EAClC,SAASQ,GAAO;GAEd,OADA,KAAKA,CAAK,GACH;EACT;CACF,GAGM,0BAAgC;EACpC,AAAIL,KAAUC,MACd,IAAiB,IACjB,qBAAqB;GAEnB,IADA,IAAiB,IACbD,GAAQ;GACZ,IAAMM,IAAW,aAAa;GAC9B,AAAIA,KAAa,QAAgCZ,EAAK,UAAU,YAAYY,CAAQ;EACtF,CAAC;CACH,GAMM,sBAAsB,GAAgB,MAAuB;EACjE,IAAMC,IAAUC,EAAiBC,CAAG;EACpC,IAAI,CAACF,GAAS;GACZ,EAAK,KAAKG,GAAQ,YAAY;IAAE,WAAW;IAAI,SAAS;GAAkC,CAAC;GAC3F;EACF;EAEA,IAAMC,IAAQd,EAAQ,UAChBe,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F,OAAO,MAAM3B,EAAK,aAAaqB,CAAO;GACxC,SAASV,GAAO;IACd,MAAMA,aAAiBa,IAAmBC,EAAed,CAAK,IAAIA;GACpE;EACF;EACA,sBAAsB,YAAY;GAChC,IAAIL,GAAQ,MAAM,cAAc;GAChC,OAAOgB,EAAY,OAAO,MAAMtB,EAAK,iBAAiB,CAAC;EACzD;EACA,IAAI,iBAAiB;GACnB,OAAOA,EAAK;EACd;EACA,SAAS;EACT,IAAI,WAAW;GACb,OAAOM;EACT;EACA,OAAO,MAAyB;GAC9B,IAAIA,GAAQ,MAAM,cAAc;GAChC,EAAK,KAAKU,CAAM;EAClB;EACA,IAAI,QAA6B;GAC/B,OAAO,CAAC,GAAGhB,EAAK,MAAM,OAAO,CAAC;EAChC;EACA,cAAc,MAA0B;GACtC,IAAIM,GAAQ;GACZ,IAAMsB,IAAOzB,EAAQ,kBAAkBA,EAAQ,gBAAgB0B,CAAM,IAAI;GACzE,AAAID,KAAS,QAA4B5B,EAAK,UAAU,UAAU4B,CAAI;EACxE;EACA,KAAKxB,EAAQ;EACb,CAAC,OAAO,WAAW;GACjB,MAAM;EACR;CACF;AACF"}
1
+ {"version":3,"file":"host.js","names":["host","createMeshHost","DEFAULT_MAX_MESSAGE_BYTES","options","tappers","createTappers","closed","flushScheduled","off","detach","TavernDisposedError","error","snapshot","command","parseWireCommand","raw","peerId","table","apply","payload","event","decoded","meshQrCodec","code","MeshPairingError","toPairingError","isMeshAnswer","TavernPairingError","wire","notice"],"sources":["../src/host.ts"],"sourcesContent":["import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // A named session checks every command's target: missing and mismatched targets are\n // rejected before the table runs, so a guest cannot opt out of naming its subject.\n // (The command table stays the authorization boundary; this guards honest misrouting.)\n if (options.subject.id !== undefined && command.target !== options.subject.id) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: 'That command does not target the hosted subject.',\n });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast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,CAAO,GACvB,MAAM,IAAIM,EAAmB,iDAAiD;GAEhF,IAAI;IACF,OAAO,MAAM3B,EAAK,aAAaqB,CAAO;GACxC,SAASV,GAAO;IACd,MAAMA,aAAiBa,IAAmBC,EAAed,CAAK,IAAIA;GACpE;EACF;EACA,sBAAsB,YAAY;GAChC,IAAIL,GAAQ,MAAM,cAAc;GAChC,OAAOgB,EAAY,OAAO,MAAMtB,EAAK,iBAAiB,CAAC;EACzD;EACA,IAAI,iBAAiB;GACnB,OAAOA,EAAK;EACd;EACA,SAAS;EACT,IAAI,WAAW;GACb,OAAOM;EACT;EACA,OAAO,MAAyB;GAC9B,IAAIA,GAAQ,MAAM,cAAc;GAChC,EAAK,KAAKU,CAAM;EAClB;EACA,IAAI,QAA6B;GAC/B,OAAO,CAAC,GAAGhB,EAAK,MAAM,OAAO,CAAC;EAChC;EACA,cAAc,MAA0B;GACtC,IAAIM,GAAQ;GACZ,IAAMsB,IAAOzB,EAAQ,kBAAkBA,EAAQ,gBAAgB0B,CAAM,IAAI;GACzE,AAAID,KAAS,QAA4B5B,EAAK,UAAU,UAAU4B,CAAI;EACxE;EACA,KAAKxB,EAAQ;EACb,CAAC,OAAO,WAAW;GACjB,MAAM;EACR;CACF;AACF"}
package/dist/tavern.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/mesh");var TavernError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TavernPairingError=class extends TavernError{},TavernDisposedError=class extends TavernError{},t=524288,commandId=()=>`cmd-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;function parseWireCommand(e){if(typeof e!=`object`||!e)return null;let{args:t,id:n,name:r}=e;return typeof n!=`string`||typeof r!=`string`||!Array.isArray(t)?null:{args:t,id:n,name:r}}function toPairingError(e){return new TavernPairingError(e instanceof Error?e.message:`That code could not be read.`,{cause:e})}function isMeshAnswer(e){return`proof`in e}function isMeshInvitation(e){return`secret`in e}function createTappers(){let e=new Set,t=!1;return{emit(t){if(e.size!==0)for(let n of e)try{n(t)}catch{}},stop(){t=!0,e.clear()},tap(n,r){if(t||r?.signal?.aborted)return()=>{};let detach=()=>{e.delete(n)};return e.add(n),r?.signal?.addEventListener(`abort`,detach,{once:!0}),detach}}}async function joinTavern(n){let r;try{r=await e.meshQrCodec.decode(n.invitationCode)}catch(t){throw t instanceof e.MeshPairingError?toPairingError(t):t}if(!isMeshInvitation(r))throw new TavernPairingError(`That code is not a session invitation.`);let i=(0,e.createMeshGuest)({maxMessageBytes:t,rtc:n.rtc}),a=createTappers(),o=null,s=!1,c,l,u=new Promise((e,t)=>{c=e,l=t});u.catch(()=>void 0);let endSession=e=>{if(s)return;s=!0;let t=o;o=null;for(let e of d.splice(0))e();i.dispose(),a.emit({type:`dispose`}),a.stop(),t===null?l(e):n.onEnded?.(t)},d=[i.on(`snapshot`,({payload:e})=>{let t=n.mount(e);t===null||s||o===null&&(o=t,c(t))}),i.on(`notice`,({payload:e})=>{n.onNotice?.(e)}),i.on(`rejected`,({payload:e})=>{a.emit({commandId:e.commandId,message:e.message||`The host rejected the action.`,type:`rejected`})}),i.tap(e=>{e.type===`ice-state`&&e.state===`failed`?endSession(new TavernError(`The connection to the host failed.`)):e.type!==`status-change`&&e.type!==`peer-status-change`||e.type===`peer-status-change`&&e.peerId!==i.host?.id||(e.status===`failed`&&endSession(new TavernError(`The host did not accept the answer in time.`)),e.status===`disconnected`&&endSession(new TavernError(`The host closed the session.`)))}),i.tap(e=>{e.type===`error`&&a.emit({error:e.error,message:e.error.message,type:`warning`})})];try{let t=await i.acceptInvitation(r,{name:n.name});return{answerCode:await e.meshQrCodec.encode(t),guest:{get disposalSignal(){return i.disposalSignal},dispose:()=>endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`)),get disposed(){return s},sendCommand:(e,t=[])=>{if(s)throw new TavernDisposedError(`The session has ended.`);i.send(`command`,{args:[...t],id:commandId(),name:e})},tap:a.tap,[Symbol.dispose](){endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`))}},ready:u}}catch(t){let n=t instanceof e.MeshPairingError?toPairingError(t):t;throw endSession(n instanceof Error?n:new TavernError(`The invitation could not be accepted.`)),n}}function hostTavern(n){let r=(0,e.createMeshHost)({maxMessageBytes:t,rtc:n.rtc}),i=createTappers(),a=!1,o=!1,close=()=>{if(!a){a=!0;for(let e of s.splice(0))e();r.dispose(),i.emit({type:`dispose`}),i.stop(),n.onEnded?.()}},disposedError=()=>new TavernDisposedError(`This host has stopped.`),warn=e=>{i.emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},readSnapshot=()=>{try{return n.subject.snapshot()}catch(e){return warn(e),null}},broadcastSnapshot=()=>{a||o||(o=!0,queueMicrotask(()=>{if(o=!1,a)return;let e=readSnapshot();e!=null&&r.broadcast(`snapshot`,e)}))},handleGuestCommand=(e,t)=>{let i=parseWireCommand(t);if(!i){r.send(e,`rejected`,{commandId:``,message:`That command could not be read.`});return}let a=n.commands,o=a&&Object.hasOwn(a,i.name)?a[i.name]:void 0;if(typeof o!=`function`)r.send(e,`rejected`,{commandId:i.id,message:`The host has no command named "${i.name}".`});else try{o(i.args)}catch(t){r.send(e,`rejected`,{commandId:i.id,message:t instanceof Error?t.message:`The host could not apply the command.`})}},s=[r.on(`command`,({peerId:e,payload:t})=>handleGuestCommand(e,t)),n.subject.onChanged(broadcastSnapshot),n.subject.onRemoved(close),r.tap(e=>{if(e.type===`peer-joined`){let t=readSnapshot();t!=null&&r.send(e.peer.id,`snapshot`,t),i.emit({peer:e.peer,type:`peer-joined`})}e.type===`peer-left`&&i.emit({peer:e.peer,reason:e.reason,type:`peer-left`}),e.type===`error`&&warn(e.error)})];return{acceptAnswerCode:async t=>{if(a)throw disposedError();let n;try{n=await e.meshQrCodec.decode(t)}catch(t){throw t instanceof e.MeshPairingError?toPairingError(t):t}if(!isMeshAnswer(n))throw new TavernPairingError(`That code is an invitation, not a guest answer.`);try{return await r.acceptAnswer(n)}catch(t){throw t instanceof e.MeshPairingError?toPairingError(t):t}},createInvitationCode:async()=>{if(a)throw disposedError();return e.meshQrCodec.encode(await r.createInvitation())},get disposalSignal(){return r.disposalSignal},dispose:close,get disposed(){return a},kick:e=>{if(a)throw disposedError();r.kick(e)},get peers(){return[...r.peers.values()]},relayNotice:e=>{if(a)return;let t=n.serializeNotice?n.serializeNotice(e):null;t!=null&&r.broadcast(`notice`,t)},tap:i.tap,[Symbol.dispose](){close()}}}exports.TavernDisposedError=TavernDisposedError,exports.TavernError=TavernError,exports.TavernPairingError=TavernPairingError,exports.hostTavern=hostTavern,exports.joinTavern=joinTavern;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/mesh");var TavernError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TavernPairingError=class extends TavernError{},TavernDisposedError=class extends TavernError{},t=524288,commandId=()=>`cmd-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;function parseWireCommand(e){if(typeof e!=`object`||!e)return null;let{args:t,id:n,name:r,target:i}=e;return typeof n!=`string`||typeof r!=`string`||!Array.isArray(t)||i!==void 0&&typeof i!=`string`?null:i===void 0?{args:t,id:n,name:r}:{args:t,id:n,name:r,target:i}}function toPairingError(e){return new TavernPairingError(e instanceof Error?e.message:`That code could not be read.`,{cause:e})}function isMeshAnswer(e){return`proof`in e}function isMeshInvitation(e){return`secret`in e}function createTappers(){let e=new Set,t=!1;return{emit(t){if(e.size!==0)for(let n of e)try{n(t)}catch{}},stop(){t=!0,e.clear()},tap(n,r){if(t||r?.signal?.aborted)return()=>{};let detach=()=>{e.delete(n)};return e.add(n),r?.signal?.addEventListener(`abort`,detach,{once:!0}),detach}}}async function joinTavern(n){let r;try{r=await e.meshQrCodec.decode(n.invitationCode)}catch(t){throw t instanceof e.MeshPairingError?toPairingError(t):t}if(!isMeshInvitation(r))throw new TavernPairingError(`That code is not a session invitation.`);let i=(0,e.createMeshGuest)({maxMessageBytes:t,rtc:n.rtc}),a=createTappers(),o=null,s=!1,c,l,u=new Promise((e,t)=>{c=e,l=t});u.catch(()=>void 0);let endSession=e=>{if(s)return;s=!0;let t=o;o=null;for(let e of d.splice(0))e();i.dispose(),a.emit({type:`dispose`}),a.stop(),t===null?l(e):n.onEnded?.(t)},d=[i.on(`snapshot`,({payload:e})=>{let t=n.mount(e);t===null||s||o===null&&(o=t,c(t))}),i.on(`notice`,({payload:e})=>{n.onNotice?.(e)}),i.on(`rejected`,({payload:e})=>{a.emit({commandId:e.commandId,message:e.message||`The host rejected the action.`,type:`rejected`})}),i.tap(e=>{e.type===`ice-state`&&e.state===`failed`?endSession(new TavernError(`The connection to the host failed.`)):e.type!==`status-change`&&e.type!==`peer-status-change`||e.type===`peer-status-change`&&e.peerId!==i.host?.id||(e.status===`failed`&&endSession(new TavernError(`The host did not accept the answer in time.`)),e.status===`disconnected`&&endSession(new TavernError(`The host closed the session.`)))}),i.tap(e=>{e.type===`error`&&a.emit({error:e.error,message:e.error.message,type:`warning`})})];try{let t=await i.acceptInvitation(r,{name:n.name});return{answerCode:await e.meshQrCodec.encode(t),guest:{get disposalSignal(){return i.disposalSignal},dispose:()=>endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`)),get disposed(){return s},sendCommand:(e,t=[],n)=>{if(s)throw new TavernDisposedError(`The session has ended.`);i.send(`command`,{args:[...t],id:commandId(),name:e,...n===void 0?void 0:{target:n}})},tap:a.tap,[Symbol.dispose](){endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`))}},ready:u}}catch(t){let n=t instanceof e.MeshPairingError?toPairingError(t):t;throw endSession(n instanceof Error?n:new TavernError(`The invitation could not be accepted.`)),n}}function hostTavern(n){let r=(0,e.createMeshHost)({maxMessageBytes:t,rtc:n.rtc}),i=createTappers(),a=!1,o=!1,close=()=>{if(!a){a=!0;for(let e of s.splice(0))e();r.dispose(),i.emit({type:`dispose`}),i.stop(),n.onEnded?.()}},disposedError=()=>new TavernDisposedError(`This host has stopped.`),warn=e=>{i.emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},readSnapshot=()=>{try{return n.subject.snapshot()}catch(e){return warn(e),null}},broadcastSnapshot=()=>{a||o||(o=!0,queueMicrotask(()=>{if(o=!1,a)return;let e=readSnapshot();e!=null&&r.broadcast(`snapshot`,e)}))},handleGuestCommand=(e,t)=>{let i=parseWireCommand(t);if(!i){r.send(e,`rejected`,{commandId:``,message:`That command could not be read.`});return}if(n.subject.id!==void 0&&i.target!==n.subject.id){r.send(e,`rejected`,{commandId:i.id,message:`That command does not target the hosted subject.`});return}let a=n.commands,o=a&&Object.hasOwn(a,i.name)?a[i.name]:void 0;if(typeof o!=`function`)r.send(e,`rejected`,{commandId:i.id,message:`The host has no command named "${i.name}".`});else try{o(i.args)}catch(t){r.send(e,`rejected`,{commandId:i.id,message:t instanceof Error?t.message:`The host could not apply the command.`})}},s=[r.on(`command`,({peerId:e,payload:t})=>handleGuestCommand(e,t)),n.subject.onChanged(broadcastSnapshot),n.subject.onRemoved(close),r.tap(e=>{if(e.type===`peer-joined`){let t=readSnapshot();t!=null&&r.send(e.peer.id,`snapshot`,t),i.emit({peer:e.peer,type:`peer-joined`})}e.type===`peer-left`&&i.emit({peer:e.peer,reason:e.reason,type:`peer-left`}),e.type===`error`&&warn(e.error)})];return{acceptAnswerCode:async t=>{if(a)throw disposedError();let n;try{n=await e.meshQrCodec.decode(t)}catch(t){throw t instanceof e.MeshPairingError?toPairingError(t):t}if(!isMeshAnswer(n))throw new TavernPairingError(`That code is an invitation, not a guest answer.`);try{return await r.acceptAnswer(n)}catch(t){throw t instanceof e.MeshPairingError?toPairingError(t):t}},createInvitationCode:async()=>{if(a)throw disposedError();return e.meshQrCodec.encode(await r.createInvitation())},get disposalSignal(){return r.disposalSignal},dispose:close,get disposed(){return a},kick:e=>{if(a)throw disposedError();r.kick(e)},get peers(){return[...r.peers.values()]},relayNotice:e=>{if(a)return;let t=n.serializeNotice?n.serializeNotice(e):null;t!=null&&r.broadcast(`notice`,t)},tap:i.tap,[Symbol.dispose](){close()}}}exports.TavernDisposedError=TavernDisposedError,exports.TavernError=TavernError,exports.TavernPairingError=TavernPairingError,exports.hostTavern=hostTavern,exports.joinTavern=joinTavern;
2
2
  //# sourceMappingURL=tavern.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tavern.cjs","names":["meshQrCodec","MeshPairingError","createMeshGuest","createMeshHost","meshQrCodec","MeshPairingError","_vielzeug_mesh","message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","error","decoded","tappers","stopped","tapper","event","options","handler","guest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (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 });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":"A,mGAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMO,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,mBAAb,cAAwC,WAAY,CAAC,EAOxC,oBAAb,cAAyC,WAAY,CAAC,ECfzCC,EAA4B,OAoB5B,cAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,IAG9G,SAAgB,iBAAiB,EAAkC,CACjE,GAAI,OAAOC,GAAQ,WAAYA,EAAc,OAAO,KACpD,GAAM,CAAE,OAAM,KAAI,QAASA,EAE3B,OADI,OAAOC,GAAO,UAAY,OAAOC,GAAS,UAAY,CAAC,MAAM,QAAQC,CAAI,EAAU,KAChF,CAAE,OAAM,KAAI,MAAK,CAC1B,CAOA,SAAgB,eAAe,EAAoC,CAEjE,OAAO,IAAI,mBADKC,aAAiB,MAAQA,EAAM,QAAU,+BAClB,CAAE,MAAOA,CAAM,CAAC,CACzD,CAGA,SAAgB,aAAa,EAA6D,CACxF,MAAO,UAAWC,CACpB,CAGA,SAAgB,iBAAiB,EAAiE,CAChG,MAAO,WAAYA,CACrB,CCrCA,SAAgB,eAAiE,CAC/E,IAAMC,EAAU,IAAI,IAChBC,EAAU,GAEd,MAAO,CACL,KAAK,EAAa,CAChB,GAAID,EAAQ,OAAS,EACrB,I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AAY,OAAOyC,CAAI,CACzC,OAAS/B,EAAO,CACd,MAAMA,aAAiBT,EAAAA,iBAAmB,eAAeS,CAAK,EAAIA,CACpE,CACA,GAAI,CAAC,aAAaC,CAAO,EACvB,MAAM,IAAI,mBAAmB,iDAAiD,EAEhF,GAAI,CACF,OAAO,MAAMsB,EAAK,aAAatB,CAAO,CACxC,OAASD,EAAO,CACd,MAAMA,aAAiBT,EAAAA,iBAAmB,eAAeS,CAAK,EAAIA,CACpE,CACF,EACA,qBAAsB,SAAY,CAChC,GAAIwB,EAAQ,MAAM,cAAc,EAChC,OAAOlC,EAAAA,YAAY,OAAO,MAAMiC,EAAK,iBAAiB,CAAC,CACzD,EACA,IAAI,gBAAiB,CACnB,OAAOA,EAAK,cACd,EACA,QAAS,MACT,IAAI,UAAW,CACb,OAAOC,CACT,EACA,KAAO,GAAyB,CAC9B,GAAIA,EAAQ,MAAM,cAAc,EAChCD,EAAK,KAAKK,CAAM,CAClB,EACA,IAAI,OAA6B,CAC/B,MAAO,CAAC,GAAGL,EAAK,MAAM,OAAO,CAAC,CAChC,EACA,YAAc,GAA0B,CACtC,GAAIC,EAAQ,OACZ,IAAMQ,EAAO1B,EAAQ,gBAAkBA,EAAQ,gBAAgB2B,CAAM,EAAI,KACrED,GAAS,MAA4BT,EAAK,UAAU,SAAUS,CAAI,CACxE,EACA,IAAK9B,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
1
+ {"version":3,"file":"tavern.cjs","names":["meshQrCodec","MeshPairingError","createMeshGuest","createMeshHost","meshQrCodec","MeshPairingError","_vielzeug_mesh","message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","target","error","decoded","tappers","stopped","tapper","event","options","handler","guest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command, its arguments, an optional subject\n * target, and an id tagging the reply. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n readonly target?: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, target } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n if (target !== undefined && typeof target !== 'string') return null;\n return target === undefined ? { args, id, name } : { args, id, name, target };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = [], target?: string): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', {\n args: [...args],\n id: commandId(),\n name,\n ...(target === undefined ? undefined : { target }),\n });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // A named session checks every command's target: missing and mismatched targets are\n // rejected before the table runs, so a guest cannot opt out of naming its subject.\n // (The command table stays the authorization boundary; this guards honest misrouting.)\n if (options.subject.id !== undefined && command.target !== options.subject.id) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: 'That command does not target the hosted subject.',\n });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(notice) : null;\n if (wire !== null && wire !== undefined) host.broadcast('notice', wire);\n },\n tap: tappers.tap,\n [Symbol.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CAC3D,GAAImB,EAAQ,MAAM,cAAc,EAChC,IAAIvB,EACJ,GAAI,CACF,EAAU,MAAMZ,EAAAA,YAAY,OAAO0C,CAAI,CACzC,OAAS/B,EAAO,CACd,MAAMA,aAAiBV,EAAAA,iBAAmB,eAAeU,CAAK,EAAIA,CACpE,CACA,GAAI,CAAC,aAAaC,CAAO,EACvB,MAAM,IAAI,mBAAmB,iDAAiD,EAEhF,GAAI,CACF,OAAO,MAAMsB,EAAK,aAAatB,CAAO,CACxC,OAASD,EAAO,CACd,MAAMA,aAAiBV,EAAAA,iBAAmB,eAAeU,CAAK,EAAIA,CACpE,CACF,EACA,qBAAsB,SAAY,CAChC,GAAIwB,EAAQ,MAAM,cAAc,EAChC,OAAOnC,EAAAA,YAAY,OAAO,MAAMkC,EAAK,iBAAiB,CAAC,CACzD,EACA,IAAI,gBAAiB,CACnB,OAAOA,EAAK,cACd,EACA,QAAS,MACT,IAAI,UAAW,CACb,OAAOC,CACT,EACA,KAAO,GAAyB,CAC9B,GAAIA,EAAQ,MAAM,cAAc,EAChCD,EAAK,KAAKK,CAAM,CAClB,EACA,IAAI,OAA6B,CAC/B,MAAO,CAAC,GAAGL,EAAK,MAAM,OAAO,CAAC,CAChC,EACA,YAAc,GAA0B,CACtC,GAAIC,EAAQ,OACZ,IAAMQ,EAAO1B,EAAQ,gBAAkBA,EAAQ,gBAAgB2B,CAAM,EAAI,KACrED,GAAS,MAA4BT,EAAK,UAAU,SAAUS,CAAI,CACxE,EACA,IAAK9B,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
@@ -1,2 +1,2 @@
1
- var Tavern=(function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var TavernError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TavernPairingError=class extends TavernError{},TavernDisposedError=class extends TavernError{},n=524288,commandId=()=>`cmd-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;function parseWireCommand(e){if(typeof e!=`object`||!e)return null;let{args:t,id:n,name:r}=e;return typeof n!=`string`||typeof r!=`string`||!Array.isArray(t)?null:{args:t,id:n,name:r}}function toPairingError(e){return new TavernPairingError(e instanceof Error?e.message:`That code could not be read.`,{cause:e})}function isMeshAnswer(e){return`proof`in e}function isMeshInvitation(e){return`secret`in e}function createTappers(){let e=new Set,t=!1;return{emit(t){if(e.size!==0)for(let n of e)try{n(t)}catch{}},stop(){t=!0,e.clear()},tap(n,r){if(t||r?.signal?.aborted)return()=>{};let detach=()=>{e.delete(n)};return e.add(n),r?.signal?.addEventListener(`abort`,detach,{once:!0}),detach}}}async function joinTavern(e){let r;try{r=await t.meshQrCodec.decode(e.invitationCode)}catch(e){throw e instanceof t.MeshPairingError?toPairingError(e):e}if(!isMeshInvitation(r))throw new TavernPairingError(`That code is not a session invitation.`);let i=(0,t.createMeshGuest)({maxMessageBytes:n,rtc:e.rtc}),a=createTappers(),o=null,s=!1,c,l,u=new Promise((e,t)=>{c=e,l=t});u.catch(()=>void 0);let endSession=t=>{if(s)return;s=!0;let n=o;o=null;for(let e of d.splice(0))e();i.dispose(),a.emit({type:`dispose`}),a.stop(),n===null?l(t):e.onEnded?.(n)},d=[i.on(`snapshot`,({payload:t})=>{let n=e.mount(t);n===null||s||o===null&&(o=n,c(n))}),i.on(`notice`,({payload:t})=>{e.onNotice?.(t)}),i.on(`rejected`,({payload:e})=>{a.emit({commandId:e.commandId,message:e.message||`The host rejected the action.`,type:`rejected`})}),i.tap(e=>{e.type===`ice-state`&&e.state===`failed`?endSession(new TavernError(`The connection to the host failed.`)):e.type!==`status-change`&&e.type!==`peer-status-change`||e.type===`peer-status-change`&&e.peerId!==i.host?.id||(e.status===`failed`&&endSession(new TavernError(`The host did not accept the answer in time.`)),e.status===`disconnected`&&endSession(new TavernError(`The host closed the session.`)))}),i.tap(e=>{e.type===`error`&&a.emit({error:e.error,message:e.error.message,type:`warning`})})];try{let n=await i.acceptInvitation(r,{name:e.name});return{answerCode:await t.meshQrCodec.encode(n),guest:{get disposalSignal(){return i.disposalSignal},dispose:()=>endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`)),get disposed(){return s},sendCommand:(e,t=[])=>{if(s)throw new TavernDisposedError(`The session has ended.`);i.send(`command`,{args:[...t],id:commandId(),name:e})},tap:a.tap,[Symbol.dispose](){endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`))}},ready:u}}catch(e){let n=e instanceof t.MeshPairingError?toPairingError(e):e;throw endSession(n instanceof Error?n:new TavernError(`The invitation could not be accepted.`)),n}}function hostTavern(e){let r=(0,t.createMeshHost)({maxMessageBytes:n,rtc:e.rtc}),i=createTappers(),a=!1,o=!1,close=()=>{if(!a){a=!0;for(let e of s.splice(0))e();r.dispose(),i.emit({type:`dispose`}),i.stop(),e.onEnded?.()}},disposedError=()=>new TavernDisposedError(`This host has stopped.`),warn=e=>{i.emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},readSnapshot=()=>{try{return e.subject.snapshot()}catch(e){return warn(e),null}},broadcastSnapshot=()=>{a||o||(o=!0,queueMicrotask(()=>{if(o=!1,a)return;let e=readSnapshot();e!=null&&r.broadcast(`snapshot`,e)}))},handleGuestCommand=(t,n)=>{let i=parseWireCommand(n);if(!i){r.send(t,`rejected`,{commandId:``,message:`That command could not be read.`});return}let a=e.commands,o=a&&Object.hasOwn(a,i.name)?a[i.name]:void 0;if(typeof o!=`function`)r.send(t,`rejected`,{commandId:i.id,message:`The host has no command named "${i.name}".`});else try{o(i.args)}catch(e){r.send(t,`rejected`,{commandId:i.id,message:e instanceof Error?e.message:`The host could not apply the command.`})}},s=[r.on(`command`,({peerId:e,payload:t})=>handleGuestCommand(e,t)),e.subject.onChanged(broadcastSnapshot),e.subject.onRemoved(close),r.tap(e=>{if(e.type===`peer-joined`){let t=readSnapshot();t!=null&&r.send(e.peer.id,`snapshot`,t),i.emit({peer:e.peer,type:`peer-joined`})}e.type===`peer-left`&&i.emit({peer:e.peer,reason:e.reason,type:`peer-left`}),e.type===`error`&&warn(e.error)})];return{acceptAnswerCode:async e=>{if(a)throw disposedError();let n;try{n=await t.meshQrCodec.decode(e)}catch(e){throw e instanceof t.MeshPairingError?toPairingError(e):e}if(!isMeshAnswer(n))throw new TavernPairingError(`That code is an invitation, not a guest answer.`);try{return await r.acceptAnswer(n)}catch(e){throw e instanceof t.MeshPairingError?toPairingError(e):e}},createInvitationCode:async()=>{if(a)throw disposedError();return t.meshQrCodec.encode(await r.createInvitation())},get disposalSignal(){return r.disposalSignal},dispose:close,get disposed(){return a},kick:e=>{if(a)throw disposedError();r.kick(e)},get peers(){return[...r.peers.values()]},relayNotice:t=>{if(a)return;let n=e.serializeNotice?e.serializeNotice(t):null;n!=null&&r.broadcast(`notice`,n)},tap:i.tap,[Symbol.dispose](){close()}}}return e.TavernDisposedError=TavernDisposedError,e.TavernError=TavernError,e.TavernPairingError=TavernPairingError,e.hostTavern=hostTavern,e.joinTavern=joinTavern,e})({},Mesh);
1
+ var Tavern=(function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var TavernError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TavernPairingError=class extends TavernError{},TavernDisposedError=class extends TavernError{},n=524288,commandId=()=>`cmd-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;function parseWireCommand(e){if(typeof e!=`object`||!e)return null;let{args:t,id:n,name:r,target:i}=e;return typeof n!=`string`||typeof r!=`string`||!Array.isArray(t)||i!==void 0&&typeof i!=`string`?null:i===void 0?{args:t,id:n,name:r}:{args:t,id:n,name:r,target:i}}function toPairingError(e){return new TavernPairingError(e instanceof Error?e.message:`That code could not be read.`,{cause:e})}function isMeshAnswer(e){return`proof`in e}function isMeshInvitation(e){return`secret`in e}function createTappers(){let e=new Set,t=!1;return{emit(t){if(e.size!==0)for(let n of e)try{n(t)}catch{}},stop(){t=!0,e.clear()},tap(n,r){if(t||r?.signal?.aborted)return()=>{};let detach=()=>{e.delete(n)};return e.add(n),r?.signal?.addEventListener(`abort`,detach,{once:!0}),detach}}}async function joinTavern(e){let r;try{r=await t.meshQrCodec.decode(e.invitationCode)}catch(e){throw e instanceof t.MeshPairingError?toPairingError(e):e}if(!isMeshInvitation(r))throw new TavernPairingError(`That code is not a session invitation.`);let i=(0,t.createMeshGuest)({maxMessageBytes:n,rtc:e.rtc}),a=createTappers(),o=null,s=!1,c,l,u=new Promise((e,t)=>{c=e,l=t});u.catch(()=>void 0);let endSession=t=>{if(s)return;s=!0;let n=o;o=null;for(let e of d.splice(0))e();i.dispose(),a.emit({type:`dispose`}),a.stop(),n===null?l(t):e.onEnded?.(n)},d=[i.on(`snapshot`,({payload:t})=>{let n=e.mount(t);n===null||s||o===null&&(o=n,c(n))}),i.on(`notice`,({payload:t})=>{e.onNotice?.(t)}),i.on(`rejected`,({payload:e})=>{a.emit({commandId:e.commandId,message:e.message||`The host rejected the action.`,type:`rejected`})}),i.tap(e=>{e.type===`ice-state`&&e.state===`failed`?endSession(new TavernError(`The connection to the host failed.`)):e.type!==`status-change`&&e.type!==`peer-status-change`||e.type===`peer-status-change`&&e.peerId!==i.host?.id||(e.status===`failed`&&endSession(new TavernError(`The host did not accept the answer in time.`)),e.status===`disconnected`&&endSession(new TavernError(`The host closed the session.`)))}),i.tap(e=>{e.type===`error`&&a.emit({error:e.error,message:e.error.message,type:`warning`})})];try{let n=await i.acceptInvitation(r,{name:e.name});return{answerCode:await t.meshQrCodec.encode(n),guest:{get disposalSignal(){return i.disposalSignal},dispose:()=>endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`)),get disposed(){return s},sendCommand:(e,t=[],n)=>{if(s)throw new TavernDisposedError(`The session has ended.`);i.send(`command`,{args:[...t],id:commandId(),name:e,...n===void 0?void 0:{target:n}})},tap:a.tap,[Symbol.dispose](){endSession(new TavernDisposedError(`The guest left before the first snapshot arrived.`))}},ready:u}}catch(e){let n=e instanceof t.MeshPairingError?toPairingError(e):e;throw endSession(n instanceof Error?n:new TavernError(`The invitation could not be accepted.`)),n}}function hostTavern(e){let r=(0,t.createMeshHost)({maxMessageBytes:n,rtc:e.rtc}),i=createTappers(),a=!1,o=!1,close=()=>{if(!a){a=!0;for(let e of s.splice(0))e();r.dispose(),i.emit({type:`dispose`}),i.stop(),e.onEnded?.()}},disposedError=()=>new TavernDisposedError(`This host has stopped.`),warn=e=>{i.emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},readSnapshot=()=>{try{return e.subject.snapshot()}catch(e){return warn(e),null}},broadcastSnapshot=()=>{a||o||(o=!0,queueMicrotask(()=>{if(o=!1,a)return;let e=readSnapshot();e!=null&&r.broadcast(`snapshot`,e)}))},handleGuestCommand=(t,n)=>{let i=parseWireCommand(n);if(!i){r.send(t,`rejected`,{commandId:``,message:`That command could not be read.`});return}if(e.subject.id!==void 0&&i.target!==e.subject.id){r.send(t,`rejected`,{commandId:i.id,message:`That command does not target the hosted subject.`});return}let a=e.commands,o=a&&Object.hasOwn(a,i.name)?a[i.name]:void 0;if(typeof o!=`function`)r.send(t,`rejected`,{commandId:i.id,message:`The host has no command named "${i.name}".`});else try{o(i.args)}catch(e){r.send(t,`rejected`,{commandId:i.id,message:e instanceof Error?e.message:`The host could not apply the command.`})}},s=[r.on(`command`,({peerId:e,payload:t})=>handleGuestCommand(e,t)),e.subject.onChanged(broadcastSnapshot),e.subject.onRemoved(close),r.tap(e=>{if(e.type===`peer-joined`){let t=readSnapshot();t!=null&&r.send(e.peer.id,`snapshot`,t),i.emit({peer:e.peer,type:`peer-joined`})}e.type===`peer-left`&&i.emit({peer:e.peer,reason:e.reason,type:`peer-left`}),e.type===`error`&&warn(e.error)})];return{acceptAnswerCode:async e=>{if(a)throw disposedError();let n;try{n=await t.meshQrCodec.decode(e)}catch(e){throw e instanceof t.MeshPairingError?toPairingError(e):e}if(!isMeshAnswer(n))throw new TavernPairingError(`That code is an invitation, not a guest answer.`);try{return await r.acceptAnswer(n)}catch(e){throw e instanceof t.MeshPairingError?toPairingError(e):e}},createInvitationCode:async()=>{if(a)throw disposedError();return t.meshQrCodec.encode(await r.createInvitation())},get disposalSignal(){return r.disposalSignal},dispose:close,get disposed(){return a},kick:e=>{if(a)throw disposedError();r.kick(e)},get peers(){return[...r.peers.values()]},relayNotice:t=>{if(a)return;let n=e.serializeNotice?e.serializeNotice(t):null;n!=null&&r.broadcast(`notice`,n)},tap:i.tap,[Symbol.dispose](){close()}}}return e.TavernDisposedError=TavernDisposedError,e.TavernError=TavernError,e.TavernPairingError=TavernPairingError,e.hostTavern=hostTavern,e.joinTavern=joinTavern,e})({},Mesh);
2
2
  //# sourceMappingURL=tavern.iife.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tavern.iife.js","names":["meshQrCodec","MeshPairingError","createMeshGuest","createMeshHost","meshQrCodec","MeshPairingError","exports","message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","error","decoded","tappers","stopped","tapper","event","options","handler","_vielzeug_mesh","guest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (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 });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":"A,uFAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMO,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,mBAAb,cAAwC,WAAY,CAAC,EAOxC,oBAAb,cAAyC,WAAY,CAAC,ECfzCC,EAA4B,OAoB5B,cAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,IAG9G,SAAgB,iBAAiB,EAAkC,CACjE,GAAI,OAAOC,GAAQ,WAAYA,EAAc,OAAO,KACpD,GAAM,CAAE,OAAM,KAAI,QAASA,EAE3B,OADI,OAAOC,GAAO,UAAY,OAAOC,GAAS,UAAY,CAAC,MAAM,QAAQC,CAAI,EAAU,KAChF,CAAE,OAAM,KAAI,MAAK,CAC1B,CAOA,SAAgB,eAAe,EAAoC,CAEjE,OAAO,IAAI,mBADKC,aAAiB,MAAQA,EAAM,QAAU,+BAClB,CAAE,MAAOA,CAAM,CAAC,CACzD,CAGA,SAAgB,aAAa,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OAAQ,KAAM,WAAY,CAAC,EACtGA,EAAM,OAAS,SAAS,KAAKA,EAAM,KAAK,CAC9C,CAAC,CACH,EAEA,MAAO,CACL,iBAAkB,KAAO,IAAoC,CAC3D,GAAIoB,EAAQ,MAAM,cAAc,EAChC,IAAIxB,EACJ,GAAI,CACF,EAAU,MAAMX,EAAAA,YAAY,OAAO0C,CAAI,CACzC,OAAShC,EAAO,CACd,MAAMA,aAAiBT,EAAAA,iBAAmB,eAAeS,CAAK,EAAIA,CACpE,CACA,GAAI,CAAC,aAAaC,CAAO,EACvB,MAAM,IAAI,mBAAmB,iDAAiD,EAEhF,GAAI,CACF,OAAO,MAAMuB,EAAK,aAAavB,CAAO,CACxC,OAASD,EAAO,CACd,MAAMA,aAAiBT,EAAAA,iBAAmB,eAAeS,CAAK,EAAIA,CACpE,CACF,EACA,qBAAsB,SAAY,CAChC,GAAIyB,EAAQ,MAAM,cAAc,EAChC,OAAOnC,EAAAA,YAAY,OAAO,MAAMkC,EAAK,iBAAiB,CAAC,CACzD,EACA,IAAI,gBAAiB,CACnB,OAAOA,EAAK,cACd,EACA,QAAS,MACT,IAAI,UAAW,CACb,OAAOC,CACT,EACA,KAAO,GAAyB,CAC9B,GAAIA,EAAQ,MAAM,cAAc,EAChCD,EAAK,KAAKK,CAAM,CAClB,EACA,IAAI,OAA6B,CAC/B,MAAO,CAAC,GAAGL,EAAK,MAAM,OAAO,CAAC,CAChC,EACA,YAAc,GAA0B,CACtC,GAAIC,EAAQ,OACZ,IAAMQ,EAAO3B,EAAQ,gBAAkBA,EAAQ,gBAAgB4B,CAAM,EAAI,KACrED,GAAS,MAA4BT,EAAK,UAAU,SAAUS,CAAI,CACxE,EACA,IAAK/B,EAAQ,IACb,CAAC,OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
1
+ {"version":3,"file":"tavern.iife.js","names":["meshQrCodec","MeshPairingError","createMeshGuest","createMeshHost","meshQrCodec","MeshPairingError","exports","message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","target","error","decoded","tappers","stopped","tapper","event","options","handler","_vielzeug_mesh","guest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command, its arguments, an optional subject\n * target, and an id tagging the reply. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n readonly target?: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, target } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n if (target !== undefined && typeof target !== 'string') return null;\n return target === undefined ? { args, id, name } : { args, id, name, target };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = [], target?: string): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', {\n args: [...args],\n id: commandId(),\n name,\n ...(target === undefined ? undefined : { target }),\n });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // A named session checks every command's target: missing and mismatched targets are\n // rejected before the table runs, so a guest cannot opt out of naming its subject.\n // (The command table stays the authorization boundary; this guards honest misrouting.)\n if (options.subject.id !== undefined && command.target !== options.subject.id) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: 'That command does not target the hosted subject.',\n });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":"A,uFAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMO,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,mBAAb,cAAwC,WAAY,CAAC,EAOxC,oBAAb,cAAyC,WAAY,CAAC,ECfzCC,EAA4B,OAsB5B,cAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,IAG9G,SAAgB,iBAAiB,EAAkC,CACjE,GAAI,OAAOC,GAAQ,WAAYA,EAAc,OAAO,KACpD,GAAM,CAAE,OAAM,KAAI,OAAM,UAAWA,EAGnC,OAFI,OAAOC,GAAO,UAAY,OAAOC,GAAS,UAAY,CAAC,MAAM,QAAQC,CAAI,GACzEC,IAAW,IAAA,IAAa,OAAOA,GAAW,SAAiB,KACxDA,IAAW,IAAA,GAAY,CAAE,OAAM,KAAI,MAAK,EAAI,CAAE,OAAM,KAAI,OAAM,QAAO,CAC9E,CAOA,SAAgB,eAAe,EAAoC,CAEjE,OAAO,IAAI,mBADKC,aAAiB,MAAQA,EAAM,QAAU,+BAClB,CAAE,MAAOA,CAAM,CAAC,CACzD,CAGA,SAAgB,aAAa,EAA6D,CACxF,MAAO,UAAWC,CACpB,CAGA,SAAgB,iBAAiB,EAAiE,CAChG,MAAO,WAAYA,CACrB,CCxCA,SAAgB,eAAiE,CAC/E,IAAMC,EAAU,IAAI,IACh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ANGED
@@ -7,11 +7,16 @@ var TavernError = class extends Error {
7
7
  }, TavernPairingError = class extends TavernError {}, TavernDisposedError = class extends TavernError {}, i = 524288, commandId = () => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
8
8
  function parseWireCommand(e) {
9
9
  if (typeof e != "object" || !e) return null;
10
- let { args: t, id: n, name: r } = e;
11
- return typeof n != "string" || typeof r != "string" || !Array.isArray(t) ? null : {
10
+ let { args: t, id: n, name: r, target: i } = e;
11
+ return typeof n != "string" || typeof r != "string" || !Array.isArray(t) || i !== void 0 && typeof i != "string" ? null : i === void 0 ? {
12
12
  args: t,
13
13
  id: n,
14
14
  name: r
15
+ } : {
16
+ args: t,
17
+ id: n,
18
+ name: r,
19
+ target: i
15
20
  };
16
21
  }
17
22
  function toPairingError(e) {
@@ -105,12 +110,13 @@ async function joinTavern(n) {
105
110
  get disposed() {
106
111
  return l;
107
112
  },
108
- sendCommand: (e, t = []) => {
113
+ sendCommand: (e, t = [], n) => {
109
114
  if (l) throw new TavernDisposedError("The session has ended.");
110
115
  o.send("command", {
111
116
  args: [...t],
112
117
  id: commandId(),
113
- name: e
118
+ name: e,
119
+ ...n === void 0 ? void 0 : { target: n }
114
120
  });
115
121
  },
116
122
  tap: s.tap,
@@ -163,6 +169,13 @@ function hostTavern(t) {
163
169
  });
164
170
  return;
165
171
  }
172
+ if (t.subject.id !== void 0 && r.target !== t.subject.id) {
173
+ a.send(e, "rejected", {
174
+ commandId: r.id,
175
+ message: "That command does not target the hosted subject."
176
+ });
177
+ return;
178
+ }
166
179
  let i = t.commands, o = i && Object.hasOwn(i, r.name) ? i[r.name] : void 0;
167
180
  if (typeof o != "function") a.send(e, "rejected", {
168
181
  commandId: r.id,
@@ -1 +1 @@
1
- {"version":3,"file":"tavern.js","names":["message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","error","decoded","tappers","stopped","tapper","event","options","handler","meshQrCodec","MeshPairingError","guest","createMeshGuest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","createMeshHost","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command and its arguments, tagged for rejection. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n return { args, id, name };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (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 });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":";;AAIA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,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,EAAK;EACd;EACA,SAAS;EACT,IAAI,WAAW;GACb,OAAOE;EACT;EACA,OAAO,MAAyB;GAC9B,IAAIA,GAAQ,MAAM,cAAc;GAChC,EAAK,KAAKI,CAAM;EAClB;EACA,IAAI,QAA6B;GAC/B,OAAO,CAAC,GAAGN,EAAK,MAAM,OAAO,CAAC;EAChC;EACA,cAAc,MAA0B;GACtC,IAAIE,GAAQ;GACZ,IAAMQ,IAAO9B,EAAQ,kBAAkBA,EAAQ,gBAAgB+B,CAAM,IAAI;GACzE,AAAID,KAAS,QAA4BV,EAAK,UAAU,UAAUU,CAAI;EACxE;EACA,KAAKlC,EAAQ;EACb,CAAC,OAAO,WAAW;GACjB,MAAM;EACR;CACF;AACF"}
1
+ {"version":3,"file":"tavern.js","names":["message","opts","DEFAULT_MAX_MESSAGE_BYTES","raw","id","name","args","target","error","decoded","tappers","stopped","tapper","event","options","handler","meshQrCodec","MeshPairingError","guest","createMeshGuest","mounted","ended","resolveReady","rejectReady","ready","resolve","reject","subject","off","detach","earlyExit","payload","answer","wrapped","host","createMeshHost","closed","flushScheduled","snapshot","command","peerId","table","apply","code","wire","notice"],"sources":["../src/errors.ts","../src/_protocol.ts","../src/_tappers.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["/**\n * Base class for all tavern errors.\n * Use `instanceof TavernError` to catch any tavern-originated error in one branch.\n */\nexport class TavernError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** A pairing code the consumer pasted could not be used: a user-input mistake, not a bug. */\nexport class TavernPairingError extends TavernError {}\n\n/**\n * Thrown when a stopped host or an ended guest session is used again. Mirrors\n * mesh's `MeshDisposedError` inside the tavern error hierarchy, so\n * `instanceof TavernError` catches every tavern failure in one branch.\n */\nexport class TavernDisposedError extends TavernError {}\n","import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';\n\nimport { TavernPairingError } from './errors';\n\n/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */\nexport const DEFAULT_MAX_MESSAGE_BYTES = 512 * 1024;\n\n/** What travels guest to host: a named command, its arguments, an optional subject\n * target, and an id tagging the reply. */\nexport interface WireCommand {\n readonly args: unknown[];\n readonly id: string;\n readonly name: string;\n readonly target?: string;\n}\n\nexport interface WireProtocol extends MeshProtocol {\n toGuest: {\n notice: unknown;\n rejected: { commandId: string; message: string };\n snapshot: unknown;\n };\n toHost: {\n command: WireCommand;\n };\n}\n\nexport const 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. */\nexport function parseWireCommand(raw: unknown): WireCommand | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { args, id, name, target } = raw as Record<string, unknown>;\n if (typeof id !== 'string' || typeof name !== 'string' || !Array.isArray(args)) return null;\n if (target !== undefined && typeof target !== 'string') return null;\n return target === undefined ? { args, id, name } : { args, id, name, target };\n}\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 */\nexport function 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/** narrows a decoded pairing code to the guest's half of the handshake. */\nexport function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer {\n return 'proof' in decoded;\n}\n\n/** narrows a decoded pairing code to the host's half of the handshake. */\nexport function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation {\n return 'secret' in decoded;\n}\n","/**\n * The `tap()` machinery shared by the host and guest handles. Kept private: the\n * public contract is each handle's `tap` method and its event union, not this.\n *\n * Follows the repo observability rules: zero overhead with no tappers, handler\n * errors swallowed, auto-detach on an abort signal, and a no-op unsubscribe once\n * the handle has stopped.\n */\nexport interface Tappers<E extends { readonly type: string }> {\n /** Emits to every tapper; a no-op when none are registered. */\n emit(event: E): void;\n /** Drops every tapper and makes later `tap` calls no-ops. Idempotent. */\n stop(): void;\n tap(handler: (event: E) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport function createTappers<E extends { readonly type: string }>(): Tappers<E> {\n const tappers = new Set<(event: E) => void>();\n let stopped = false;\n\n return {\n emit(event): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect session behavior.\n }\n }\n },\n stop(): void {\n stopped = true;\n tappers.clear();\n },\n tap(handler, options): () => void {\n if (stopped || options?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n options?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n };\n}\n","import { createMeshGuest, type MeshAnswer, type MeshInvitation, MeshPairingError, meshQrCodec } from '@vielzeug/mesh';\nimport { commandId, DEFAULT_MAX_MESSAGE_BYTES, isMeshInvitation, toPairingError, type WireProtocol } from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nimport type { TavernGuestEvent, TavernGuestOptions, TavernJoinResult } from './types';\n\n/**\n * Joins a session as a guest: consumes the host's invitation code and returns the answer\n * code to show back. The session goes live once the host accepts the answer and the first\n * snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the\n * guest (or the channel dropping) ends the session exactly once.\n */\nexport async function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>> {\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(options.invitationCode);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshInvitation(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 let resolveReady!: (subject: Mounted) => void;\n let rejectReady!: (error: Error) => void;\n const ready = new Promise<Mounted>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A ready the consumer never awaits must not surface as an unhandled rejection.\n void ready.catch(() => undefined);\n\n /** Ends the session exactly once: from the channel dropping or an explicit dispose. */\n const endSession = (earlyExit: Error): 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.emit({ type: 'dispose' });\n tappers.stop();\n if (subject !== null) options.onEnded?.(subject);\n else rejectReady(earlyExit);\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 resolveReady(subject);\n }\n }),\n guest.on('notice', ({ payload }) => {\n options.onNotice?.(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 // A failed ICE negotiation before the channel opens surfaces only as the raw\n // ice-state event; once a channel exists, mesh reports failed/disconnected statuses.\n if (event.type === 'ice-state' && event.state === 'failed') {\n endSession(new TavernError('The connection to the host failed.'));\n return;\n }\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') endSession(new TavernError('The host did not accept the answer in time.'));\n if (event.status === 'disconnected') endSession(new TavernError('The host closed the session.'));\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 answerCode: await meshQrCodec.encode(answer),\n guest: {\n get disposalSignal() {\n return guest.disposalSignal;\n },\n dispose: () => endSession(new TavernDisposedError('The guest left before the first snapshot arrived.')),\n get disposed() {\n return ended;\n },\n sendCommand: (name: string, args: readonly unknown[] = [], target?: string): void => {\n if (ended) throw new TavernDisposedError('The session has ended.');\n guest.send('command', {\n args: [...args],\n id: commandId(),\n name,\n ...(target === undefined ? undefined : { target }),\n });\n },\n tap: tappers.tap,\n [Symbol.dispose]() {\n endSession(new TavernDisposedError('The guest left before the first snapshot arrived.'));\n },\n },\n ready,\n };\n } catch (error) {\n // A failed join must not leave the node and its subscriptions behind.\n const wrapped = error instanceof MeshPairingError ? toPairingError(error) : error;\n endSession(wrapped instanceof Error ? wrapped : new TavernError('The invitation could not be accepted.'));\n throw wrapped;\n }\n}\n","import {\n createMeshHost,\n type MeshAnswer,\n type MeshInvitation,\n MeshPairingError,\n type MeshPeer,\n meshQrCodec,\n} from '@vielzeug/mesh';\nimport {\n DEFAULT_MAX_MESSAGE_BYTES,\n isMeshAnswer,\n parseWireCommand,\n toPairingError,\n type WireProtocol,\n} from './_protocol';\nimport { createTappers } from './_tappers';\nimport { TavernDisposedError, TavernPairingError } from './errors';\nimport type { TavernHost, TavernHostEvent, TavernHostOptions } from './types';\n\n/**\n * Starts hosting one subject over mesh. Every guest command is validated and applied\n * through the command table; local changes re-broadcast the snapshot (coalesced on a\n * microtask); removal 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.emit({ type: '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.subject.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 or a rule violation is all the host can ever reject with.\n */\n const handleGuestCommand = (peerId: string, raw: unknown): void => {\n const command = parseWireCommand(raw);\n if (!command) {\n host.send(peerId, 'rejected', { commandId: '', message: 'That command could not be read.' });\n return;\n }\n // A named session checks every command's target: missing and mismatched targets are\n // rejected before the table runs, so a guest cannot opt out of naming its subject.\n // (The command table stays the authorization boundary; this guards honest misrouting.)\n if (options.subject.id !== undefined && command.target !== options.subject.id) {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: 'That command does not target the hosted subject.',\n });\n return;\n }\n // Own-property lookup only: a guest must not reach Object.prototype members.\n const table = options.commands;\n const apply = table && Object.hasOwn(table, command.name) ? table[command.name] : undefined;\n if (typeof apply !== 'function') {\n host.send(peerId, 'rejected', {\n commandId: command.id,\n message: `The host has no command named \"${command.name}\".`,\n });\n return;\n }\n try {\n apply(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.subject.onChanged(broadcastSnapshot),\n options.subject.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 acceptAnswerCode: async (code: string): Promise<MeshPeer> => {\n if (closed) throw disposedError();\n let decoded: MeshInvitation | MeshAnswer;\n try {\n decoded = await meshQrCodec.decode(code);\n } catch (error) {\n throw error instanceof MeshPairingError ? toPairingError(error) : error;\n }\n if (!isMeshAnswer(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 createInvitationCode: 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.serializeNotice ? options.serializeNotice(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"],"mappings":";;AAIA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,qBAAb,cAAwC,YAAY,CAAC,GAOxC,sBAAb,cAAyC,YAAY,CAAC,GCfzCC,IAA4B,QAsB5B,kBAA0B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE;AAG9G,SAAgB,iBAAiB,GAAkC;CACjE,IAAI,OAAOC,KAAQ,aAAYA,GAAc,OAAO;CACp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BAAiB;GACnB,OAAOA,EAAK;EACd;EACA,SAAS;EACT,IAAI,WAAW;GACb,OAAOE;EACT;EACA,OAAO,MAAyB;GAC9B,IAAIA,GAAQ,MAAM,cAAc;GAChC,EAAK,KAAKI,CAAM;EAClB;EACA,IAAI,QAA6B;GAC/B,OAAO,CAAC,GAAGN,EAAK,MAAM,OAAO,CAAC;EAChC;EACA,cAAc,MAA0B;GACtC,IAAIE,GAAQ;GACZ,IAAMQ,IAAO9B,EAAQ,kBAAkBA,EAAQ,gBAAgB+B,CAAM,IAAI;GACzE,AAAID,KAAS,QAA4BV,EAAK,UAAU,UAAUU,CAAI;EACxE;EACA,KAAKlC,EAAQ;EACb,CAAC,OAAO,WAAW;GACjB,MAAM;EACR;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ export { createFakeRtc, type FakeRtc } from '@vielzeug/mesh/testing';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,KAAK,OAAO,EAAE,MAAM,wBAAwB,CAAC"}
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/mesh/testing");Object.defineProperty(exports,"createFakeRtc",{enumerable:!0,get:function(){return e.createFakeRtc}});
@@ -0,0 +1 @@
1
+ export { createFakeRtc } from "@vielzeug/mesh/testing";
package/dist/types.d.ts CHANGED
@@ -10,6 +10,13 @@ export type TavernCommand = (args: readonly unknown[]) => void;
10
10
  export type TavernCommands = Record<string, TavernCommand>;
11
11
  /** How the host reads and watches the single subject it is sharing. */
12
12
  export interface TavernSubject {
13
+ /**
14
+ * The subject's stable id. Declaring it turns every command into a checked request:
15
+ * a guest must name this id as {@link TavernGuest.sendCommand}'s `target`, and tavern
16
+ * rejects any command that omits or misses it before the command table ever runs.
17
+ * Omit it for anonymous sessions, where commands carry no target.
18
+ */
19
+ readonly id?: string;
13
20
  /** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */
14
21
  onChanged(listener: () => void): () => void;
15
22
  /** Subscribes to the hosted subject's removal: hosting ends when it fires. */
@@ -129,9 +136,13 @@ export interface TavernGuest {
129
136
  * Forwards a command to the host's command table. The host rejects a name its table
130
137
  * does not hold, and a handler that throws rejects with its message; a successful
131
138
  * command needs no separate answer because its effect arrives with the next snapshot.
139
+ * When the host shares a named subject (its `subject.id`), `target` must name that
140
+ * subject id or the command is rejected before the table runs; pass it as the third
141
+ * argument for every command on a named session. For an anonymous host the argument
142
+ * is ignored.
132
143
  * Throws `TavernDisposedError` after the session has ended.
133
144
  */
134
- sendCommand(name: string, args?: readonly unknown[]): void;
145
+ sendCommand(name: string, args?: readonly unknown[], target?: string): void;
135
146
  /** Subscribes to {@link TavernGuestEvent}s. Handler errors are swallowed; the
136
147
  * subscription detaches when `signal` aborts or the session ends. */
137
148
  tap(handler: (event: TavernGuestEvent) => void, options?: {
@@ -1 +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,oEAAo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E,OAAO,GAAG,IAAI,CAAC;IAC/B,GAAG,CAAC,EAAE,cAAc,CAAC;CACtB;AAED,MAAM,WAAW,WAAW;IAC1B,mDAAmD;IACnD,QAAQ,CAAC,cAAc,EAAE,WAAW,CAAC;IACrC,gDAAgD;IAChD,OAAO,IAAI,IAAI,CAAC;IAChB,6EAA6E;IAC7E,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B;;;;;;;;;OASG;IACH,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,SAAS,OAAO,EAAE,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5E;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.13",
3
+ "version": "26.11.14",
4
4
  "description": "Table sessions over mesh: host-owned state replication with guest command forwarding",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,6 +23,18 @@
23
23
  "import": "./dist/index.js",
24
24
  "require": "./dist/index.cjs",
25
25
  "types": "./dist/index.d.ts"
26
+ },
27
+ "./testing": {
28
+ "import": "./dist/testing.js",
29
+ "require": "./dist/testing.cjs",
30
+ "types": "./dist/testing/index.d.ts"
31
+ }
32
+ },
33
+ "typesVersions": {
34
+ "*": {
35
+ "testing": [
36
+ "dist/testing/index.d.ts"
37
+ ]
26
38
  }
27
39
  },
28
40
  "sideEffects": false,
@@ -40,7 +52,7 @@
40
52
  "test": "vitest"
41
53
  },
42
54
  "dependencies": {
43
- "@vielzeug/mesh": "26.11.13"
55
+ "@vielzeug/mesh": "26.11.14"
44
56
  },
45
57
  "devDependencies": {
46
58
  "@types/node": "^26.6.6",