@vielzeug/tavern 26.11.12 → 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.
- package/README.md +11 -14
- package/dist/_protocol.cjs +2 -0
- package/dist/_protocol.cjs.map +1 -0
- package/dist/_protocol.d.ts +39 -0
- package/dist/_protocol.d.ts.map +1 -0
- package/dist/_protocol.js +30 -0
- package/dist/_protocol.js.map +1 -0
- package/dist/guest.cjs +2 -0
- package/dist/guest.cjs.map +1 -0
- package/dist/guest.d.ts +9 -0
- package/dist/guest.d.ts.map +1 -0
- package/dist/guest.js +89 -0
- package/dist/guest.js.map +1 -0
- package/dist/host.cjs +2 -0
- package/dist/host.cjs.map +1 -0
- package/dist/host.d.ts +8 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +129 -0
- package/dist/host.js.map +1 -0
- package/dist/index.cjs +1 -2
- package/dist/index.d.ts +5 -173
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -203
- package/dist/tavern.cjs +1 -1
- package/dist/tavern.cjs.map +1 -1
- package/dist/tavern.iife.js +1 -1
- package/dist/tavern.iife.js.map +1 -1
- package/dist/tavern.js +137 -106
- package/dist/tavern.js.map +1 -1
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing.cjs +1 -0
- package/dist/testing.js +1 -0
- package/dist/types.d.ts +166 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +14 -2
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -16,27 +16,24 @@ yarn add @vielzeug/tavern
|
|
|
16
16
|
import { hostTavern, joinTavern } from '@vielzeug/tavern';
|
|
17
17
|
|
|
18
18
|
const host = hostTavern({
|
|
19
|
-
commands: {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
subjects: {
|
|
25
|
-
onChanged: (listener) => myStore.onUpdated('doc-1', listener),
|
|
26
|
-
onRemoved: (listener) => myStore.onRemoved('doc-1', listener),
|
|
27
|
-
snapshot: () => myStore.read('doc-1'),
|
|
19
|
+
commands: { rename: (args) => myStore.rename(docId, args[0] as string) },
|
|
20
|
+
subject: {
|
|
21
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
22
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
23
|
+
snapshot: () => myStore.read(docId),
|
|
28
24
|
},
|
|
29
25
|
});
|
|
30
26
|
|
|
31
|
-
const
|
|
32
|
-
const {
|
|
33
|
-
|
|
27
|
+
const invitationCode = await host.createInvitationCode();
|
|
28
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
29
|
+
invitationCode,
|
|
34
30
|
mount: (snapshot) => parseAndMount(snapshot),
|
|
35
31
|
name: 'Alex',
|
|
36
32
|
});
|
|
37
|
-
await host.
|
|
33
|
+
await host.acceptAnswerCode(answerCode);
|
|
34
|
+
await ready; // the mirror is live
|
|
38
35
|
|
|
39
|
-
guest.sendCommand('
|
|
36
|
+
guest.sendCommand('rename', ['Quarterly report']);
|
|
40
37
|
```
|
|
41
38
|
|
|
42
39
|
## Documentation
|
|
@@ -0,0 +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,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
|
+
//# sourceMappingURL=_protocol.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { MeshAnswer, MeshInvitation, MeshProtocol } from '@vielzeug/mesh';
|
|
2
|
+
import { TavernPairingError } from './errors';
|
|
3
|
+
/** Snapshots can be large; the default mesh frame cap is too tight for whole documents. */
|
|
4
|
+
export declare const DEFAULT_MAX_MESSAGE_BYTES: number;
|
|
5
|
+
/** What travels guest to host: a named command, its arguments, an optional subject
|
|
6
|
+
* target, and an id tagging the reply. */
|
|
7
|
+
export interface WireCommand {
|
|
8
|
+
readonly args: unknown[];
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly name: string;
|
|
11
|
+
readonly target?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface WireProtocol extends MeshProtocol {
|
|
14
|
+
toGuest: {
|
|
15
|
+
notice: unknown;
|
|
16
|
+
rejected: {
|
|
17
|
+
commandId: string;
|
|
18
|
+
message: string;
|
|
19
|
+
};
|
|
20
|
+
snapshot: unknown;
|
|
21
|
+
};
|
|
22
|
+
toHost: {
|
|
23
|
+
command: WireCommand;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export declare const commandId: () => string;
|
|
27
|
+
/** Runtime guard for the wire command shape: the protocol is Tavern's, so Tavern validates it. */
|
|
28
|
+
export declare function parseWireCommand(raw: unknown): WireCommand | null;
|
|
29
|
+
/**
|
|
30
|
+
* Reclassifies a mesh pairing failure as the tavern-level user mistake it is:
|
|
31
|
+
* the code the consumer pasted could not be used. The message is preserved and
|
|
32
|
+
* the original error is chained as `cause`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function toPairingError(error: unknown): TavernPairingError;
|
|
35
|
+
/** narrows a decoded pairing code to the guest's half of the handshake. */
|
|
36
|
+
export declare function isMeshAnswer(decoded: MeshInvitation | MeshAnswer): decoded is MeshAnswer;
|
|
37
|
+
/** narrows a decoded pairing code to the host's half of the handshake. */
|
|
38
|
+
export declare function isMeshInvitation(decoded: MeshInvitation | MeshAnswer): decoded is MeshInvitation;
|
|
39
|
+
//# sourceMappingURL=_protocol.d.ts.map
|
|
@@ -0,0 +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;2CAC2C;AAC3C,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;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;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;AAElH,kGAAkG;AAClG,wBAAgB,gBAAgB,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"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { TavernPairingError as e } from "./errors.js";
|
|
2
|
+
// src/_protocol.ts
|
|
3
|
+
var t = 524288, commandId = () => `cmd-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
|
|
4
|
+
function parseWireCommand(e) {
|
|
5
|
+
if (typeof e != "object" || !e) return 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
|
+
args: t,
|
|
9
|
+
id: n,
|
|
10
|
+
name: r
|
|
11
|
+
} : {
|
|
12
|
+
args: t,
|
|
13
|
+
id: n,
|
|
14
|
+
name: r,
|
|
15
|
+
target: i
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function toPairingError(t) {
|
|
19
|
+
let n = t instanceof Error ? t.message : "That code could not be read.";
|
|
20
|
+
return new e(n, { cause: t });
|
|
21
|
+
}
|
|
22
|
+
function isMeshAnswer(e) {
|
|
23
|
+
return "proof" in e;
|
|
24
|
+
}
|
|
25
|
+
function isMeshInvitation(e) {
|
|
26
|
+
return "secret" in e;
|
|
27
|
+
}
|
|
28
|
+
export { t as DEFAULT_MAX_MESSAGE_BYTES, commandId, isMeshAnswer, isMeshInvitation, parseWireCommand, toPairingError };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=_protocol.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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
ADDED
|
@@ -0,0 +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=[],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
|
+
//# sourceMappingURL=guest.cjs.map
|
|
@@ -0,0 +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","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,EA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,MAAO,CACL,WAAY,MAAMhB,EAAAA,YAAY,OAAOiC,CAAM,EAC3C,MAAO,CACL,IAAI,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"}
|
package/dist/guest.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { TavernGuestOptions, TavernJoinResult } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Joins a session as a guest: consumes the host's invitation code and returns the answer
|
|
4
|
+
* code to show back. The session goes live once the host accepts the answer and the first
|
|
5
|
+
* snapshot mounts; that transition settles {@link TavernJoinResult.ready}. Disposing the
|
|
6
|
+
* guest (or the channel dropping) ends the session exactly once.
|
|
7
|
+
*/
|
|
8
|
+
export declare function joinTavern<Mounted>(options: TavernGuestOptions<Mounted>): Promise<TavernJoinResult<Mounted>>;
|
|
9
|
+
//# sourceMappingURL=guest.d.ts.map
|
|
@@ -0,0 +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,CAiHlH"}
|
package/dist/guest.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { DEFAULT_MAX_MESSAGE_BYTES as e, commandId as t, isMeshInvitation as n, toPairingError as r } from "./_protocol.js";
|
|
2
|
+
import { createTappers as i } from "./_tappers.js";
|
|
3
|
+
import { TavernDisposedError as a, TavernError as o, TavernPairingError as s } from "./errors.js";
|
|
4
|
+
import { MeshPairingError as c, createMeshGuest as l, meshQrCodec as u } from "@vielzeug/mesh";
|
|
5
|
+
// src/guest.ts
|
|
6
|
+
async function joinTavern(d) {
|
|
7
|
+
let f;
|
|
8
|
+
try {
|
|
9
|
+
f = await u.decode(d.invitationCode);
|
|
10
|
+
} catch (e) {
|
|
11
|
+
throw e instanceof c ? r(e) : e;
|
|
12
|
+
}
|
|
13
|
+
if (!n(f)) throw new s("That code is not a session invitation.");
|
|
14
|
+
let p = l({
|
|
15
|
+
maxMessageBytes: e,
|
|
16
|
+
rtc: d.rtc
|
|
17
|
+
}), m = i(), h = null, g = !1, _, v, y = new Promise((e, t) => {
|
|
18
|
+
_ = e, v = t;
|
|
19
|
+
});
|
|
20
|
+
y.catch(() => void 0);
|
|
21
|
+
let endSession = (e) => {
|
|
22
|
+
if (g) return;
|
|
23
|
+
g = !0;
|
|
24
|
+
let t = h;
|
|
25
|
+
h = null;
|
|
26
|
+
for (let e of b.splice(0)) e();
|
|
27
|
+
p.dispose(), m.emit({ type: "dispose" }), m.stop(), t === null ? v(e) : d.onEnded?.(t);
|
|
28
|
+
}, b = [
|
|
29
|
+
p.on("snapshot", ({ payload: e }) => {
|
|
30
|
+
let t = d.mount(e);
|
|
31
|
+
t === null || g || h === null && (h = t, _(t));
|
|
32
|
+
}),
|
|
33
|
+
p.on("notice", ({ payload: e }) => {
|
|
34
|
+
d.onNotice?.(e);
|
|
35
|
+
}),
|
|
36
|
+
p.on("rejected", ({ payload: e }) => {
|
|
37
|
+
m.emit({
|
|
38
|
+
commandId: e.commandId,
|
|
39
|
+
message: e.message || "The host rejected the action.",
|
|
40
|
+
type: "rejected"
|
|
41
|
+
});
|
|
42
|
+
}),
|
|
43
|
+
p.tap((e) => {
|
|
44
|
+
e.type === "ice-state" && e.state === "failed" ? endSession(new o("The connection to the host failed.")) : e.type !== "status-change" && e.type !== "peer-status-change" || e.type === "peer-status-change" && e.peerId !== p.host?.id || (e.status === "failed" && endSession(new o("The host did not accept the answer in time.")), e.status === "disconnected" && endSession(new o("The host closed the session.")));
|
|
45
|
+
}),
|
|
46
|
+
p.tap((e) => {
|
|
47
|
+
e.type === "error" && m.emit({
|
|
48
|
+
error: e.error,
|
|
49
|
+
message: e.error.message,
|
|
50
|
+
type: "warning"
|
|
51
|
+
});
|
|
52
|
+
})
|
|
53
|
+
];
|
|
54
|
+
try {
|
|
55
|
+
let e = await p.acceptInvitation(f, { name: d.name });
|
|
56
|
+
return {
|
|
57
|
+
answerCode: await u.encode(e),
|
|
58
|
+
guest: {
|
|
59
|
+
get disposalSignal() {
|
|
60
|
+
return p.disposalSignal;
|
|
61
|
+
},
|
|
62
|
+
dispose: () => endSession(new a("The guest left before the first snapshot arrived.")),
|
|
63
|
+
get disposed() {
|
|
64
|
+
return g;
|
|
65
|
+
},
|
|
66
|
+
sendCommand: (e, n = [], r) => {
|
|
67
|
+
if (g) throw new a("The session has ended.");
|
|
68
|
+
p.send("command", {
|
|
69
|
+
args: [...n],
|
|
70
|
+
id: t(),
|
|
71
|
+
name: e,
|
|
72
|
+
...r === void 0 ? void 0 : { target: r }
|
|
73
|
+
});
|
|
74
|
+
},
|
|
75
|
+
tap: m.tap,
|
|
76
|
+
[Symbol.dispose]() {
|
|
77
|
+
endSession(new a("The guest left before the first snapshot arrived."));
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
ready: y
|
|
81
|
+
};
|
|
82
|
+
} catch (e) {
|
|
83
|
+
let t = e instanceof c ? r(e) : e;
|
|
84
|
+
throw endSession(t instanceof Error ? t : new o("The invitation could not be accepted.")), t;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export { joinTavern };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=guest.js.map
|
|
@@ -0,0 +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","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;EACR,IAAMM,IAAUP;EAChB,IAAU;EACV,KAAK,IAAMQ,KAAOC,EAAO,OAAO,CAAC,GAAG,EAAI;EAIxC,AAHAd,E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AM;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
ADDED
|
@@ -0,0 +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}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
|
+
//# sourceMappingURL=host.cjs.map
|
|
@@ -0,0 +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 // 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,SAAU,CAAC,CAC1G,EAGM,iBAA8B,CAClC,GAAI,CACF,OAAON,EAAQ,QAAQ,SAAS,CAClC,OAASM,EAAO,CAEd,OADA,KAAKA,CAAK,EACH,IACT,CACF,EAGM,sBAAgC,CAChCJ,GAAUC,IACd,EAAiB,GACjB,mBAAq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OAAO,UAAW,CACjB,MAAM,CACR,CACF,CACF,C"}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { TavernHost, TavernHostOptions } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Starts hosting one subject over mesh. Every guest command is validated and applied
|
|
4
|
+
* through the command table; local changes re-broadcast the snapshot (coalesced on a
|
|
5
|
+
* microtask); removal ends the session.
|
|
6
|
+
*/
|
|
7
|
+
export declare function hostTavern(options: TavernHostOptions): TavernHost;
|
|
8
|
+
//# sourceMappingURL=host.d.ts.map
|
|
@@ -0,0 +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,CAkJjE"}
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { DEFAULT_MAX_MESSAGE_BYTES as e, isMeshAnswer as t, parseWireCommand as n, toPairingError as r } from "./_protocol.js";
|
|
2
|
+
import { createTappers as i } from "./_tappers.js";
|
|
3
|
+
import { TavernDisposedError as a, TavernPairingError as o } from "./errors.js";
|
|
4
|
+
import { MeshPairingError as s, createMeshHost as c, meshQrCodec as l } from "@vielzeug/mesh";
|
|
5
|
+
// src/host.ts
|
|
6
|
+
function hostTavern(u) {
|
|
7
|
+
let d = c({
|
|
8
|
+
maxMessageBytes: e,
|
|
9
|
+
rtc: u.rtc
|
|
10
|
+
}), f = i(), p = !1, m = !1, close = () => {
|
|
11
|
+
if (!p) {
|
|
12
|
+
p = !0;
|
|
13
|
+
for (let e of h.splice(0)) e();
|
|
14
|
+
d.dispose(), f.emit({ type: "dispose" }), f.stop(), u.onEnded?.();
|
|
15
|
+
}
|
|
16
|
+
}, disposedError = () => new a("This host has stopped."), warn = (e) => {
|
|
17
|
+
f.emit({
|
|
18
|
+
error: e,
|
|
19
|
+
message: e instanceof Error ? e.message : String(e),
|
|
20
|
+
type: "warning"
|
|
21
|
+
});
|
|
22
|
+
}, readSnapshot = () => {
|
|
23
|
+
try {
|
|
24
|
+
return u.subject.snapshot();
|
|
25
|
+
} catch (e) {
|
|
26
|
+
return warn(e), null;
|
|
27
|
+
}
|
|
28
|
+
}, broadcastSnapshot = () => {
|
|
29
|
+
p || m || (m = !0, queueMicrotask(() => {
|
|
30
|
+
if (m = !1, p) return;
|
|
31
|
+
let e = readSnapshot();
|
|
32
|
+
e != null && d.broadcast("snapshot", e);
|
|
33
|
+
}));
|
|
34
|
+
}, handleGuestCommand = (e, t) => {
|
|
35
|
+
let r = n(t);
|
|
36
|
+
if (!r) {
|
|
37
|
+
d.send(e, "rejected", {
|
|
38
|
+
commandId: "",
|
|
39
|
+
message: "That command could not be read."
|
|
40
|
+
});
|
|
41
|
+
return;
|
|
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
|
+
}
|
|
50
|
+
let i = u.commands, a = i && Object.hasOwn(i, r.name) ? i[r.name] : void 0;
|
|
51
|
+
if (typeof a != "function") d.send(e, "rejected", {
|
|
52
|
+
commandId: r.id,
|
|
53
|
+
message: `The host has no command named "${r.name}".`
|
|
54
|
+
});
|
|
55
|
+
else try {
|
|
56
|
+
a(r.args);
|
|
57
|
+
} catch (t) {
|
|
58
|
+
d.send(e, "rejected", {
|
|
59
|
+
commandId: r.id,
|
|
60
|
+
message: t instanceof Error ? t.message : "The host could not apply the command."
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}, h = [
|
|
64
|
+
d.on("command", ({ peerId: e, payload: t }) => handleGuestCommand(e, t)),
|
|
65
|
+
u.subject.onChanged(broadcastSnapshot),
|
|
66
|
+
u.subject.onRemoved(close),
|
|
67
|
+
d.tap((e) => {
|
|
68
|
+
if (e.type === "peer-joined") {
|
|
69
|
+
let t = readSnapshot();
|
|
70
|
+
t != null && d.send(e.peer.id, "snapshot", t), f.emit({
|
|
71
|
+
peer: e.peer,
|
|
72
|
+
type: "peer-joined"
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
e.type === "peer-left" && f.emit({
|
|
76
|
+
peer: e.peer,
|
|
77
|
+
reason: e.reason,
|
|
78
|
+
type: "peer-left"
|
|
79
|
+
}), e.type === "error" && warn(e.error);
|
|
80
|
+
})
|
|
81
|
+
];
|
|
82
|
+
return {
|
|
83
|
+
acceptAnswerCode: async (e) => {
|
|
84
|
+
if (p) throw disposedError();
|
|
85
|
+
let n;
|
|
86
|
+
try {
|
|
87
|
+
n = await l.decode(e);
|
|
88
|
+
} catch (e) {
|
|
89
|
+
throw e instanceof s ? r(e) : e;
|
|
90
|
+
}
|
|
91
|
+
if (!t(n)) throw new o("That code is an invitation, not a guest answer.");
|
|
92
|
+
try {
|
|
93
|
+
return await d.acceptAnswer(n);
|
|
94
|
+
} catch (e) {
|
|
95
|
+
throw e instanceof s ? r(e) : e;
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
createInvitationCode: async () => {
|
|
99
|
+
if (p) throw disposedError();
|
|
100
|
+
return l.encode(await d.createInvitation());
|
|
101
|
+
},
|
|
102
|
+
get disposalSignal() {
|
|
103
|
+
return d.disposalSignal;
|
|
104
|
+
},
|
|
105
|
+
dispose: close,
|
|
106
|
+
get disposed() {
|
|
107
|
+
return p;
|
|
108
|
+
},
|
|
109
|
+
kick: (e) => {
|
|
110
|
+
if (p) throw disposedError();
|
|
111
|
+
d.kick(e);
|
|
112
|
+
},
|
|
113
|
+
get peers() {
|
|
114
|
+
return [...d.peers.values()];
|
|
115
|
+
},
|
|
116
|
+
relayNotice: (e) => {
|
|
117
|
+
if (p) return;
|
|
118
|
+
let t = u.serializeNotice ? u.serializeNotice(e) : null;
|
|
119
|
+
t != null && d.broadcast("notice", t);
|
|
120
|
+
},
|
|
121
|
+
tap: f.tap,
|
|
122
|
+
[Symbol.dispose]() {
|
|
123
|
+
close();
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
export { hostTavern };
|
|
128
|
+
|
|
129
|
+
//# sourceMappingURL=host.js.map
|
package/dist/host.js.map
ADDED
|
@@ -0,0 +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 // 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":";;;;;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,GAChC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9B,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/index.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./guest.cjs"),n=require("./host.cjs");exports.TavernDisposedError=e.TavernDisposedError,exports.TavernError=e.TavernError,exports.TavernPairingError=e.TavernPairingError,exports.hostTavern=n.hostTavern,exports.joinTavern=t.joinTavern;
|