@vielzeug/mesh 26.11.16 → 26.11.18

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/dist/guest.js CHANGED
@@ -1,153 +1,153 @@
1
1
  import "./_defaults.js";
2
- import { createMessenger as e, createNodeCore as t, createPeerRecord as n } from "./_node.js";
3
- import { createProof as r } from "./_proof.js";
4
- import { randomId as i } from "./_random.js";
5
- import { nativeRtcFactory as a, normalizeSdp as o, waitIceGathering as s } from "./_rtc.js";
6
- import { MeshConnectionError as c, MeshDisposedError as l, MeshPairingError as u, MeshTimeoutError as d } from "./errors.js";
7
- import { timer as f } from "@vielzeug/arsenal";
2
+ import { createMessenger as e, createNodeCore as t, createPeerRecord as n, wireDisposalSignal as r } from "./_node.js";
3
+ import { createProof as i } from "./_proof.js";
4
+ import { randomId as a } from "./_random.js";
5
+ import { nativeRtcFactory as o, normalizeSdp as s, waitIceGathering as c } from "./_rtc.js";
6
+ import { MeshConnectionError as l, MeshDisposedError as u, MeshPairingError as d, MeshTimeoutError as f } from "./errors.js";
7
+ import { timer as p } from "@vielzeug/arsenal";
8
8
  // src/guest.ts
9
- function createMeshGuest(p = {}) {
10
- let m = p.rtc ?? a, h = p.clock ?? (() => Date.now()), g = p.maxMessageBytes ?? 65536, _ = p.channelOpenTimeoutMs ?? 6e4, v = p.iceGatheringTimeoutMs ?? 5e3, y = t(p.signal), b = e({
11
- clock: h,
12
- emitTap: y.emitTap,
13
- maxMessageBytes: g,
14
- random: p.random
15
- }), x = null, S = f(() => {
16
- x?.status === "connecting" && failPeer(x, openTimeoutError());
17
- }), openTimeoutError = () => new d(`Timed out waiting ${_}ms for the data channel to open`);
9
+ function createMeshGuest(m = {}) {
10
+ let h = m.rtc ?? o, g = m.clock ?? (() => Date.now()), _ = m.maxMessageBytes ?? 65536, v = m.channelOpenTimeoutMs ?? 6e4, y = m.iceGatheringTimeoutMs ?? 5e3, b = t(), x = e({
11
+ clock: g,
12
+ emitTap: b.emitTap,
13
+ maxMessageBytes: _
14
+ }), S = null, C = p(() => {
15
+ S?.status === "connecting" && failPeer(S, openTimeoutError());
16
+ }), openTimeoutError = () => new f(`Timed out waiting ${v}ms for the data channel to open`);
18
17
  function failPeer(e, t) {
19
- y.disposed || e !== x || e.status === "failed" || (e.status = "failed", S.cancel(), setTimeout(() => {
18
+ b.disposed || e !== S || e.status === "failed" || (e.status = "failed", C.cancel(), setTimeout(() => {
20
19
  e.dc?.close(), e.pc?.close();
21
- }, 0), y.emitTap({
20
+ }, 0), b.emitTap({
22
21
  peerId: e.id,
23
22
  status: "failed",
24
23
  type: "peer-status-change"
25
- }), y.emitTap({
24
+ }), b.emitTap({
26
25
  error: t,
27
26
  type: "error"
28
- }), y.emitTap({
27
+ }), b.emitTap({
29
28
  peer: e.publicPeer,
30
29
  reason: t.message,
31
30
  type: "peer-left"
32
- }), y.setStatus("failed"));
31
+ }), b.setStatus("failed"));
33
32
  }
34
33
  function disconnectPeer(e, t) {
35
- y.disposed || e !== x || e.status !== "disconnected" && e.status !== "failed" && (e.status = "disconnected", e.pc?.close(), y.emitTap({
34
+ b.disposed || e !== S || e.status !== "disconnected" && e.status !== "failed" && (e.status = "disconnected", e.pc?.close(), b.emitTap({
36
35
  peerId: e.id,
37
36
  status: "disconnected",
38
37
  type: "peer-status-change"
39
- }), y.emitTap({
38
+ }), b.emitTap({
40
39
  peer: e.publicPeer,
41
40
  reason: t,
42
41
  type: "peer-left"
43
- }), y.setStatus("disconnected"));
42
+ }), b.setStatus("disconnected"));
44
43
  }
45
44
  function wireChannel(e, t, n) {
46
45
  e.dc = n, n.addEventListener("open", () => {
47
- y.disposed || (S.cancel(), e.status = "connected", y.emitTap({
46
+ b.disposed || (C.cancel(), e.status = "connected", b.emitTap({
48
47
  peerId: e.id,
49
48
  status: "connected",
50
49
  type: "peer-status-change"
51
- }), y.emitTap({
50
+ }), b.emitTap({
52
51
  peer: e.publicPeer,
53
52
  type: "peer-joined"
54
- }), y.setStatus("connected"));
53
+ }), b.setStatus("connected"));
55
54
  }), n.addEventListener("message", (t) => {
56
- y.disposed || b.handleInbound(e, t.data);
55
+ b.disposed || x.handleInbound(e, t.data);
57
56
  }), n.addEventListener("close", () => {
58
- y.disposed || (e.status === "connecting" ? failPeer(e, S.pending ? openTimeoutError() : new c("channel closed before opening", e.id)) : disconnectPeer(e, "channel closed"));
57
+ b.disposed || (e.status === "connecting" ? failPeer(e, C.pending ? openTimeoutError() : new l("channel closed before opening", e.id)) : disconnectPeer(e, "channel closed"));
59
58
  }), n.addEventListener("error", () => {
60
- y.disposed || failPeer(e, new c("channel error", e.id));
59
+ b.disposed || failPeer(e, new l("channel error", e.id));
61
60
  }), t.addEventListener("iceconnectionstatechange", () => {
62
- if (y.disposed) return;
61
+ if (b.disposed) return;
63
62
  let n = t.iceConnectionState;
64
- n === "failed" || n === "closed" ? failPeer(e, new c(`ice ${n}`, e.id)) : n === "disconnected" && e.status === "connected" && disconnectPeer(e, "ice disconnected");
63
+ (n === "failed" || n === "closed") && failPeer(e, new l(`ice ${n}`, e.id));
65
64
  });
66
65
  }
67
- return {
66
+ let w = {
68
67
  async acceptInvitation(e, t) {
69
- if (y.ensureLive(), x && x.status !== "failed" && x.status !== "disconnected") throw new u("Guest is already paired");
70
- if (e?.v !== 1) throw new u("Unsupported invitation version");
71
- if (h() >= e.expiresAt) throw new u("Invitation expired");
72
- x &&= (S.cancel(), x.pc?.close(), null), y.setStatus("pairing");
73
- let a;
68
+ if (b.ensureLive(), S && S.status !== "failed" && S.status !== "disconnected") throw new d("Guest is already paired");
69
+ if (e?.v !== 1) throw new d("Unsupported invitation version");
70
+ if (g() >= e.expiresAt) throw new d("Invitation expired");
71
+ S &&= (C.cancel(), S.pc?.close(), null), b.setStatus("pairing");
72
+ let r;
74
73
  try {
75
- a = m.createPeerConnection({ iceServers: [...p.iceServers ?? []] });
74
+ r = h.createPeerConnection({ iceServers: [...m.iceServers ?? []] });
76
75
  } catch (e) {
77
- throw y.setStatus("idle"), e;
76
+ throw b.setStatus("idle"), e;
78
77
  }
79
- let d = n(e.sessionId, e.hostName, "host");
80
- d.pc = a, x = d, a.addEventListener("datachannel", (e) => {
81
- wireChannel(d, a, e.channel);
82
- }), a.addEventListener("iceconnectionstatechange", () => {
83
- y.disposed || y.emitTap({
84
- peerId: d.id,
85
- state: a.iceConnectionState,
78
+ let o = n(e.sessionId, e.hostName, "host");
79
+ o.pc = r, S = o, r.addEventListener("datachannel", (e) => {
80
+ wireChannel(o, r, e.channel);
81
+ }), r.addEventListener("iceconnectionstatechange", () => {
82
+ b.disposed || b.emitTap({
83
+ peerId: o.id,
84
+ state: r.iceConnectionState,
86
85
  type: "ice-state"
87
86
  });
88
87
  });
89
88
  try {
90
- await a.setRemoteDescription({
91
- sdp: o(e.sdp),
89
+ await r.setRemoteDescription({
90
+ sdp: s(e.sdp),
92
91
  type: "offer"
93
92
  });
94
93
  } catch (e) {
95
- throw x = null, y.setStatus("idle"), new u("Invalid invitation SDP", { cause: e });
94
+ throw S = null, b.setStatus("idle"), new d("Invalid invitation SDP", { cause: e });
96
95
  }
97
96
  let f;
98
97
  try {
99
- await a.setLocalDescription(await a.createAnswer()), await s(a, v), f = a.localDescription?.sdp ?? "";
98
+ await r.setLocalDescription(await r.createAnswer()), await c(r, y), f = r.localDescription?.sdp ?? "";
100
99
  } catch (e) {
101
- throw x = null, a.close(), y.setStatus("idle"), new c("Failed to create answer", null, { cause: e });
100
+ throw S = null, r.close(), b.setStatus("idle"), new l("Failed to create answer", null, { cause: e });
102
101
  }
103
- if (y.disposed) throw a.close(), new l();
104
- if (!f) throw x = null, a.close(), y.setStatus("idle"), new c("Local description has no SDP");
105
- let g = i(p.random), b;
102
+ if (b.disposed) throw r.close(), new u();
103
+ if (!f) throw S = null, r.close(), b.setStatus("idle"), new l("Local description has no SDP");
104
+ let p = a(m.random), _;
106
105
  try {
107
- b = await r(e.secret, f);
106
+ _ = await i(e.secret, f);
108
107
  } catch (e) {
109
- throw x = null, a.close(), y.setStatus("idle"), e;
108
+ throw S = null, r.close(), b.setStatus("idle"), e;
110
109
  }
111
- return y.setStatus("connecting"), S.arm(_), {
112
- peer: t?.name === void 0 ? { id: g } : {
113
- id: g,
110
+ return b.setStatus("connecting"), C.arm(v), {
111
+ peer: t?.name === void 0 ? { id: p } : {
112
+ id: p,
114
113
  name: t.name
115
114
  },
116
- proof: b,
115
+ proof: _,
117
116
  sdp: f,
118
117
  sessionId: e.sessionId,
119
118
  v: 1
120
119
  };
121
120
  },
122
121
  get disposalSignal() {
123
- return y.disposalCtrl.signal;
122
+ return b.disposalCtrl.signal;
124
123
  },
125
124
  dispose() {
126
- y.disposed || (y.markDisposed(), S.cancel(), x && (x.dc?.close(), x.pc?.close()), b.clear());
125
+ b.disposed || (b.markDisposed(), C.cancel(), S && (S.dc?.close(), S.pc?.close()), x.clear());
127
126
  },
128
127
  get disposed() {
129
- return y.disposed;
128
+ return b.disposed;
130
129
  },
131
130
  get host() {
132
- return x?.publicPeer ?? null;
131
+ return S?.publicPeer ?? null;
133
132
  },
134
133
  on(e, t) {
135
- return y.ensureLive(), b.on(e, t);
134
+ return b.ensureLive(), x.on(e, t);
136
135
  },
137
136
  send(e, t) {
138
- if (y.ensureLive(), !x) throw new c("Guest is not paired");
139
- b.sendTo(x, e, t);
137
+ if (b.ensureLive(), !S) throw new l("Guest is not paired");
138
+ x.sendTo(S, e, t);
140
139
  },
141
140
  get status() {
142
- return y.status;
141
+ return b.status;
143
142
  },
144
143
  tap(e, t) {
145
- return y.tap(e, t);
144
+ return b.tap(e, t);
146
145
  },
147
146
  [Symbol.dispose]() {
148
147
  this.dispose();
149
148
  }
150
149
  };
150
+ return r(m.signal, () => w.dispose()), w;
151
151
  }
152
152
  export { createMeshGuest };
153
153
 
package/dist/guest.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"guest.js","names":["rtc","options","nativeRtcFactory","clock","maxMessageBytes","channelOpenTimeoutMs","iceGatheringTimeoutMs","core","createNodeCore","messenger","createMessenger","hostPeer","openTimer","timer","MeshTimeoutError","peer","error","dc","event","MeshConnectionError","pc","state","MeshPairingError","invitation","createPeerRecord","normalizeSdp","cause","answerSdp","waitIceGathering","MeshDisposedError","peerId","randomId","proof","createProof","meta","type","handler","payload","tapOptions"],"sources":["../src/guest.ts"],"sourcesContent":["import { timer } from '@vielzeug/arsenal';\nimport {\n DEFAULT_CHANNEL_OPEN_TIMEOUT_MS,\n DEFAULT_ICE_GATHERING_TIMEOUT_MS,\n DEFAULT_MAX_MESSAGE_BYTES,\n} from './_defaults';\nimport { createMessenger, createNodeCore, createPeerRecord, type PeerRecord } from './_node';\nimport { createProof } from './_proof';\nimport { randomId } from './_random';\nimport { nativeRtcFactory, normalizeSdp, waitIceGathering } from './_rtc';\nimport { MeshConnectionError, MeshDisposedError, type MeshError, MeshPairingError, MeshTimeoutError } from './errors';\nimport type {\n MeshGuest,\n MeshGuestOptions,\n MeshInbound,\n MeshPeer,\n MeshProtocol,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n} from './types';\n\n/**\n * Create a guest mesh node. The guest pairs with one host by consuming an\n * out-of-band invitation and returning an answer.\n */\nexport function createMeshGuest<P extends MeshProtocol>(options: MeshGuestOptions = {}): MeshGuest<P> {\n const rtc = options.rtc ?? nativeRtcFactory;\n const clock = options.clock ?? (() => Date.now());\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const channelOpenTimeoutMs = options.channelOpenTimeoutMs ?? DEFAULT_CHANNEL_OPEN_TIMEOUT_MS;\n const iceGatheringTimeoutMs = options.iceGatheringTimeoutMs ?? DEFAULT_ICE_GATHERING_TIMEOUT_MS;\n\n const core = createNodeCore(options.signal);\n const messenger = createMessenger({\n clock,\n emitTap: core.emitTap,\n maxMessageBytes,\n random: options.random,\n });\n\n let hostPeer: PeerRecord | null = null;\n const openTimer = timer(() => {\n if (hostPeer?.status === 'connecting') {\n failPeer(hostPeer, openTimeoutError());\n }\n });\n\n const openTimeoutError = (): MeshTimeoutError =>\n new MeshTimeoutError(`Timed out waiting ${channelOpenTimeoutMs}ms for the data channel to open`);\n\n function failPeer(peer: PeerRecord, error: MeshError): void {\n // Ignore events from a superseded peer after re-pairing replaced hostPeer.\n if (core.disposed || peer !== hostPeer || peer.status === 'failed') return;\n peer.status = 'failed';\n openTimer.cancel();\n // Teardown is deferred a macrotask so a peer racing its own open\n // deadline reports its timeout rather than this hangup.\n setTimeout(() => {\n peer.dc?.close();\n peer.pc?.close();\n }, 0);\n core.emitTap({ peerId: peer.id, status: 'failed', type: 'peer-status-change' });\n core.emitTap({ error, type: 'error' });\n core.emitTap({ peer: peer.publicPeer, reason: error.message, type: 'peer-left' });\n core.setStatus('failed');\n }\n\n function disconnectPeer(peer: PeerRecord, reason: string): void {\n if (core.disposed || peer !== hostPeer) return;\n if (peer.status === 'disconnected' || peer.status === 'failed') return;\n peer.status = 'disconnected';\n peer.pc?.close();\n core.emitTap({ peerId: peer.id, status: 'disconnected', type: 'peer-status-change' });\n core.emitTap({ peer: peer.publicPeer, reason, type: 'peer-left' });\n core.setStatus('disconnected');\n }\n\n function wireChannel(peer: PeerRecord, pc: RTCPeerConnectionLike, dc: RTCDataChannelLike): void {\n peer.dc = dc;\n\n dc.addEventListener('open', () => {\n if (core.disposed) return;\n openTimer.cancel();\n peer.status = 'connected';\n core.emitTap({ peerId: peer.id, status: 'connected', type: 'peer-status-change' });\n core.emitTap({ peer: peer.publicPeer, type: 'peer-joined' });\n core.setStatus('connected');\n });\n dc.addEventListener('message', (event) => {\n if (core.disposed) return;\n messenger.handleInbound(peer, event.data);\n });\n dc.addEventListener('close', () => {\n if (core.disposed) return;\n if (peer.status === 'connecting')\n failPeer(\n peer,\n openTimer.pending ? openTimeoutError() : new MeshConnectionError('channel closed before opening', peer.id),\n );\n else disconnectPeer(peer, 'channel closed');\n });\n dc.addEventListener('error', () => {\n if (core.disposed) return;\n failPeer(peer, new MeshConnectionError('channel error', peer.id));\n });\n\n // The ice-state emission lives on the pairing-scoped listener above; this\n // one owns channel-lifecycle transitions only, so each ICE change emits\n // exactly one ice-state event.\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n const state = pc.iceConnectionState;\n if (state === 'failed' || state === 'closed') {\n failPeer(peer, new MeshConnectionError(`ice ${state}`, peer.id));\n } else if (state === 'disconnected' && peer.status === 'connected') {\n disconnectPeer(peer, 'ice disconnected');\n }\n });\n }\n\n const guest: MeshGuest<P> = {\n async acceptInvitation(invitation, meta) {\n core.ensureLive();\n // A terminal host peer (failed/disconnected) may be replaced by a fresh\n // pairing on the same node: listeners stay attached and keep working.\n if (hostPeer && hostPeer.status !== 'failed' && hostPeer.status !== 'disconnected') {\n throw new MeshPairingError('Guest is already paired');\n }\n if (invitation?.v !== 1) throw new MeshPairingError('Unsupported invitation version');\n if (clock() >= invitation.expiresAt) throw new MeshPairingError('Invitation expired');\n\n if (hostPeer) {\n openTimer.cancel();\n hostPeer.pc?.close();\n hostPeer = null;\n }\n\n core.setStatus('pairing');\n let pc: RTCPeerConnectionLike;\n try {\n pc = rtc.createPeerConnection({ iceServers: [...(options.iceServers ?? [])] });\n } catch (error) {\n core.setStatus('idle');\n throw error;\n }\n\n // The invitation carries no host identity beyond an optional display\n // name: the session id doubles as the host-side peer id for inbound\n // metadata and tap events.\n const peer = createPeerRecord(invitation.sessionId, invitation.hostName, 'host');\n peer.pc = pc;\n hostPeer = peer;\n\n pc.addEventListener('datachannel', (event) => {\n wireChannel(peer, pc, event.channel);\n });\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n core.emitTap({ peerId: peer.id, state: pc.iceConnectionState, type: 'ice-state' });\n });\n\n try {\n await pc.setRemoteDescription({ sdp: normalizeSdp(invitation.sdp), type: 'offer' });\n } catch (cause) {\n hostPeer = null;\n core.setStatus('idle');\n throw new MeshPairingError('Invalid invitation SDP', { cause });\n }\n\n let answerSdp: string;\n try {\n await pc.setLocalDescription(await pc.createAnswer());\n await waitIceGathering(pc, iceGatheringTimeoutMs);\n answerSdp = pc.localDescription?.sdp ?? '';\n } catch (cause) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw new MeshConnectionError('Failed to create answer', null, { cause });\n }\n if (core.disposed) {\n pc.close();\n throw new MeshDisposedError();\n }\n if (!answerSdp) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw new MeshConnectionError('Local description has no SDP');\n }\n\n const peerId = randomId(options.random);\n let proof: string;\n try {\n proof = await createProof(invitation.secret, answerSdp);\n } catch (cause) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw cause;\n }\n core.setStatus('connecting');\n\n // If the channel never opens (host never accepts the answer), fail loudly\n // instead of hanging in 'connecting' forever. The deadline must cover\n // the human carry-back of the answer, not just machine negotiation.\n openTimer.arm(channelOpenTimeoutMs);\n\n return {\n peer: meta?.name === undefined ? { id: peerId } : { id: peerId, name: meta.name },\n proof,\n sdp: answerSdp,\n sessionId: invitation.sessionId,\n v: 1,\n };\n },\n get disposalSignal() {\n return core.disposalCtrl.signal;\n },\n\n dispose() {\n if (core.disposed) return;\n core.markDisposed();\n openTimer.cancel();\n if (hostPeer) {\n hostPeer.dc?.close();\n hostPeer.pc?.close();\n }\n messenger.clear();\n },\n get disposed() {\n return core.disposed;\n },\n get host(): MeshPeer | null {\n return hostPeer?.publicPeer ?? null;\n },\n\n on(type, handler) {\n core.ensureLive();\n return messenger.on(type, handler as (message: MeshInbound<unknown>) => void);\n },\n\n send(type, payload) {\n core.ensureLive();\n if (!hostPeer) throw new MeshConnectionError('Guest is not paired');\n messenger.sendTo(hostPeer, type, payload);\n },\n get status() {\n return core.status;\n },\n\n tap(handler, tapOptions) {\n return core.tap(handler, tapOptions);\n },\n\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n\n return guest;\n}\n"],"mappings":";;;;;;;;AAyBA,SAAgB,gBAAwC,IAA4B,CAAC,GAAiB;CACpG,IAAMA,IAAMC,EAAQ,OAAOC,GACrBC,IAAQ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eRtcFactory","clock","maxMessageBytes","channelOpenTimeoutMs","iceGatheringTimeoutMs","core","createNodeCore","messenger","createMessenger","hostPeer","openTimer","timer","MeshTimeoutError","peer","error","dc","event","MeshConnectionError","pc","state","guest","MeshPairingError","invitation","createPeerRecord","normalizeSdp","cause","answerSdp","waitIceGathering","MeshDisposedError","peerId","randomId","proof","createProof","meta","type","handler","payload","tapOptions","wireDisposalSignal"],"sources":["../src/guest.ts"],"sourcesContent":["import { timer } from '@vielzeug/arsenal';\nimport {\n DEFAULT_CHANNEL_OPEN_TIMEOUT_MS,\n DEFAULT_ICE_GATHERING_TIMEOUT_MS,\n DEFAULT_MAX_MESSAGE_BYTES,\n} from './_defaults';\nimport { createMessenger, createNodeCore, createPeerRecord, type PeerRecord, wireDisposalSignal } from './_node';\nimport { createProof } from './_proof';\nimport { randomId } from './_random';\nimport { nativeRtcFactory, normalizeSdp, waitIceGathering } from './_rtc';\nimport { MeshConnectionError, MeshDisposedError, type MeshError, MeshPairingError, MeshTimeoutError } from './errors';\nimport type {\n MeshGuest,\n MeshGuestOptions,\n MeshInbound,\n MeshPeer,\n MeshProtocol,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n} from './types';\n\n/**\n * Create a guest mesh node. The guest pairs with one host by consuming an\n * out-of-band invitation and returning an answer.\n */\nexport function createMeshGuest<P extends MeshProtocol>(options: MeshGuestOptions = {}): MeshGuest<P> {\n const rtc = options.rtc ?? nativeRtcFactory;\n const clock = options.clock ?? (() => Date.now());\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const channelOpenTimeoutMs = options.channelOpenTimeoutMs ?? DEFAULT_CHANNEL_OPEN_TIMEOUT_MS;\n const iceGatheringTimeoutMs = options.iceGatheringTimeoutMs ?? DEFAULT_ICE_GATHERING_TIMEOUT_MS;\n\n const core = createNodeCore();\n const messenger = createMessenger({\n clock,\n emitTap: core.emitTap,\n maxMessageBytes,\n });\n\n let hostPeer: PeerRecord | null = null;\n const openTimer = timer(() => {\n if (hostPeer?.status === 'connecting') {\n failPeer(hostPeer, openTimeoutError());\n }\n });\n\n const openTimeoutError = (): MeshTimeoutError =>\n new MeshTimeoutError(`Timed out waiting ${channelOpenTimeoutMs}ms for the data channel to open`);\n\n function failPeer(peer: PeerRecord, error: MeshError): void {\n // Ignore events from a superseded peer after re-pairing replaced hostPeer.\n if (core.disposed || peer !== hostPeer || peer.status === 'failed') return;\n peer.status = 'failed';\n openTimer.cancel();\n // Teardown is deferred a macrotask so a peer racing its own open\n // deadline reports its timeout rather than this hangup.\n setTimeout(() => {\n peer.dc?.close();\n peer.pc?.close();\n }, 0);\n core.emitTap({ peerId: peer.id, status: 'failed', type: 'peer-status-change' });\n core.emitTap({ error, type: 'error' });\n core.emitTap({ peer: peer.publicPeer, reason: error.message, type: 'peer-left' });\n core.setStatus('failed');\n }\n\n function disconnectPeer(peer: PeerRecord, reason: string): void {\n if (core.disposed || peer !== hostPeer) return;\n if (peer.status === 'disconnected' || peer.status === 'failed') return;\n peer.status = 'disconnected';\n peer.pc?.close();\n core.emitTap({ peerId: peer.id, status: 'disconnected', type: 'peer-status-change' });\n core.emitTap({ peer: peer.publicPeer, reason, type: 'peer-left' });\n core.setStatus('disconnected');\n }\n\n function wireChannel(peer: PeerRecord, pc: RTCPeerConnectionLike, dc: RTCDataChannelLike): void {\n peer.dc = dc;\n\n dc.addEventListener('open', () => {\n if (core.disposed) return;\n openTimer.cancel();\n peer.status = 'connected';\n core.emitTap({ peerId: peer.id, status: 'connected', type: 'peer-status-change' });\n core.emitTap({ peer: peer.publicPeer, type: 'peer-joined' });\n core.setStatus('connected');\n });\n dc.addEventListener('message', (event) => {\n if (core.disposed) return;\n messenger.handleInbound(peer, event.data);\n });\n dc.addEventListener('close', () => {\n if (core.disposed) return;\n if (peer.status === 'connecting')\n failPeer(\n peer,\n openTimer.pending ? openTimeoutError() : new MeshConnectionError('channel closed before opening', peer.id),\n );\n else disconnectPeer(peer, 'channel closed');\n });\n dc.addEventListener('error', () => {\n if (core.disposed) return;\n failPeer(peer, new MeshConnectionError('channel error', peer.id));\n });\n\n // The ice-state emission lives on the pairing-scoped listener above; this\n // one owns channel-lifecycle transitions only, so each ICE change emits\n // exactly one ice-state event. ICE `disconnected` is transient: the\n // channel's own `close`/`error` events own peer teardown.\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n const state = pc.iceConnectionState;\n if (state === 'failed' || state === 'closed') {\n failPeer(peer, new MeshConnectionError(`ice ${state}`, peer.id));\n }\n });\n }\n\n const guest: MeshGuest<P> = {\n async acceptInvitation(invitation, meta) {\n core.ensureLive();\n // A terminal host peer (failed/disconnected) may be replaced by a fresh\n // pairing on the same node: listeners stay attached and keep working.\n if (hostPeer && hostPeer.status !== 'failed' && hostPeer.status !== 'disconnected') {\n throw new MeshPairingError('Guest is already paired');\n }\n if (invitation?.v !== 1) throw new MeshPairingError('Unsupported invitation version');\n if (clock() >= invitation.expiresAt) throw new MeshPairingError('Invitation expired');\n\n if (hostPeer) {\n openTimer.cancel();\n hostPeer.pc?.close();\n hostPeer = null;\n }\n\n core.setStatus('pairing');\n let pc: RTCPeerConnectionLike;\n try {\n pc = rtc.createPeerConnection({ iceServers: [...(options.iceServers ?? [])] });\n } catch (error) {\n core.setStatus('idle');\n throw error;\n }\n\n // The invitation carries no host identity beyond an optional display\n // name: the session id doubles as the host-side peer id for inbound\n // metadata and tap events.\n const peer = createPeerRecord(invitation.sessionId, invitation.hostName, 'host');\n peer.pc = pc;\n hostPeer = peer;\n\n pc.addEventListener('datachannel', (event) => {\n wireChannel(peer, pc, event.channel);\n });\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n core.emitTap({ peerId: peer.id, state: pc.iceConnectionState, type: 'ice-state' });\n });\n\n try {\n await pc.setRemoteDescription({ sdp: normalizeSdp(invitation.sdp), type: 'offer' });\n } catch (cause) {\n hostPeer = null;\n core.setStatus('idle');\n throw new MeshPairingError('Invalid invitation SDP', { cause });\n }\n\n let answerSdp: string;\n try {\n await pc.setLocalDescription(await pc.createAnswer());\n await waitIceGathering(pc, iceGatheringTimeoutMs);\n answerSdp = pc.localDescription?.sdp ?? '';\n } catch (cause) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw new MeshConnectionError('Failed to create answer', null, { cause });\n }\n if (core.disposed) {\n pc.close();\n throw new MeshDisposedError();\n }\n if (!answerSdp) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw new MeshConnectionError('Local description has no SDP');\n }\n\n const peerId = randomId(options.random);\n let proof: string;\n try {\n proof = await createProof(invitation.secret, answerSdp);\n } catch (cause) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw cause;\n }\n core.setStatus('connecting');\n\n // If the channel never opens (host never accepts the answer), fail loudly\n // instead of hanging in 'connecting' forever. The deadline must cover\n // the human carry-back of the answer, not just machine negotiation.\n openTimer.arm(channelOpenTimeoutMs);\n\n return {\n peer: meta?.name === undefined ? { id: peerId } : { id: peerId, name: meta.name },\n proof,\n sdp: answerSdp,\n sessionId: invitation.sessionId,\n v: 1,\n };\n },\n get disposalSignal() {\n return core.disposalCtrl.signal;\n },\n\n dispose() {\n if (core.disposed) return;\n core.markDisposed();\n openTimer.cancel();\n if (hostPeer) {\n hostPeer.dc?.close();\n hostPeer.pc?.close();\n }\n messenger.clear();\n },\n get disposed() {\n return core.disposed;\n },\n get host(): MeshPeer | null {\n return hostPeer?.publicPeer ?? null;\n },\n\n on(type, handler) {\n core.ensureLive();\n return messenger.on(type, handler as (message: MeshInbound<unknown>) => void);\n },\n\n send(type, payload) {\n core.ensureLive();\n if (!hostPeer) throw new MeshConnectionError('Guest is not paired');\n messenger.sendTo(hostPeer, type, payload);\n },\n get status() {\n return core.status;\n },\n\n tap(handler, tapOptions) {\n return core.tap(handler, tapOptions);\n },\n\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n\n wireDisposalSignal(options.signal, () => guest.dispose());\n return guest;\n}\n"],"mappings":";;;;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AAM,QAAQ,CAAC,GACjDA;AACT"}
package/dist/host.cjs CHANGED
@@ -1,2 +1,2 @@
1
- require("./_defaults.cjs");const e=require("./_node.cjs"),t=require("./_proof.cjs"),n=require("./_random.cjs"),r=require("./_rtc.cjs"),i=require("./errors.cjs");let a=require("@vielzeug/arsenal");function createMeshHost(o={}){let s=o.rtc??r.nativeRtcFactory,c=o.clock??(()=>Date.now()),l=o.maxMessageBytes??65536,u=o.invitationTtlMs??3e5,d=o.channelOpenTimeoutMs??6e4,f=o.iceGatheringTimeoutMs??5e3,p={label:`mesh`,ordered:!0,...o.channel},m=e.createNodeCore(o.signal),h=e.createMessenger({clock:c,emitTap:m.emitTap,maxMessageBytes:l,random:o.random}),g=new Map,_=new Map,v=!1,y=!1;function recomputeStatus(){let e=_.size>0?`pairing`:v?`disconnected`:y?`failed`:`idle`;for(let t of g.values()){if(t.status===`connected`){e=`connected`;break}t.status===`connecting`&&(e=`connecting`)}m.setStatus(e)}function expireInvitation(e){let t=_.get(e);t&&(_.delete(e),clearTimeout(t.expiryTimer),t.pc.close(),m.emitTap({sessionId:e,type:`invitation-expired`}),recomputeStatus())}function setPeerStatus(e,t){e.status!==t&&(e.status=t,m.emitTap({peerId:e.id,status:t,type:`peer-status-change`}),recomputeStatus())}function leavePeer(e,t,n=!1){g.has(e.id)&&(g.delete(e.id),e.status=n?`failed`:`disconnected`,e.pc?.close(),e.dc?.close(),m.emitTap({peerId:e.id,status:e.status,type:`peer-status-change`}),m.emitTap({peer:e.publicPeer,reason:t,type:`peer-left`}),n||(v=!0),y||=n,recomputeStatus())}function wirePeerTransport(e,t,n){e.pc=t,e.dc=n,n.addEventListener(`message`,t=>{m.disposed||h.handleInbound(e,t.data)}),n.addEventListener(`close`,()=>{m.disposed||leavePeer(e,`channel closed`)}),n.addEventListener(`error`,()=>{m.disposed||leavePeer(e,`channel error`,!0)}),t.addEventListener(`iceconnectionstatechange`,()=>{if(m.disposed)return;let n=t.iceConnectionState;m.emitTap({peerId:e.id,state:n,type:`ice-state`}),n===`failed`||n===`closed`?leavePeer(e,`ice ${n}`,n===`failed`):n===`disconnected`&&e.status===`connected`&&setPeerStatus(e,`disconnected`)})}function markPeerConnected(e){v=!0,g.set(e.id,e),setPeerStatus(e,`connected`),m.emitTap({peer:e,type:`peer-joined`})}return{async acceptAnswer(n){if(m.ensureLive(),n?.v!==1)throw new i.MeshPairingError(`Unsupported answer version`);if(!n.peer?.id)throw new i.MeshPairingError(`Answer is missing a peer id`);let a=_.get(n.sessionId);if(!a)throw new i.MeshPairingError(`Unknown or expired session`);if(a.answered)throw new i.MeshPairingError(`Invitation already answered`);if(g.has(n.peer.id))throw new i.MeshPairingError(`Peer "${n.peer.id}" is already connected`);if(c()>=a.expiresAt)throw expireInvitation(n.sessionId),new i.MeshPairingError(`Invitation expired`);let s=await t.createProof(a.secret,n.sdp);if(n.proof!==s)throw new i.MeshPairingError(`Proof mismatch`);if(!(await o.approvePeer?.(n.peer)??!0))throw m.emitTap({peerId:n.peer.id,type:`peer-rejected`}),new i.MeshPairingError(`Peer "${n.peer.id}" rejected by host`);if(m.emitTap({peerId:n.peer.id,type:`peer-approved`}),g.has(n.peer.id))throw new i.MeshPairingError(`Peer "${n.peer.id}" is already connected`);a.answered=!0,_.delete(n.sessionId),clearTimeout(a.expiryTimer);let l=e.createPeerRecord(n.peer.id,n.peer.name,`guest`),u=r.waitChannelOpen(a.dc,a.pc,d,l.id,m.disposalCtrl.signal);wirePeerTransport(l,a.pc,a.dc),g.set(l.id,l),recomputeStatus();try{await a.pc.setRemoteDescription({sdp:r.normalizeSdp(n.sdp),type:`answer`})}catch(e){throw leavePeer(l,`invalid answer sdp`,!0),new i.MeshPairingError(`Invalid answer SDP`,{cause:e})}try{await u}catch(e){let t=!(e instanceof i.MeshDisposedError);throw leavePeer(l,e instanceof Error?e.message:`open failed`,t),e}return markPeerConnected(l),l.publicPeer},broadcast(e,t,n){m.ensureLive();for(let r of g.values())r.status!==`connected`||n?.except?.includes(r.id)||h.sendTo(r,e,t)},async createInvitation(e){m.ensureLive();let t=s.createPeerConnection({iceServers:[...o.iceServers??[]]}),l=t.createDataChannel(p.label,{maxRetransmits:p.maxRetransmits,ordered:p.ordered}),d=n.randomId(o.random),h=(0,a.bytesToBase64Url)(n.randomBytes(32,o.random)),g=c()+u;try{await t.setLocalDescription(await t.createOffer()),await r.waitIceGathering(t,f)}catch(e){throw t.close(),new i.MeshConnectionError(`Failed to create offer`,null,{cause:e})}if(m.disposed)throw t.close(),new i.MeshDisposedError;let v=t.localDescription?.sdp;if(!v)throw t.close(),new i.MeshConnectionError(`Local description has no SDP`);let y=setTimeout(()=>expireInvitation(d),u);return _.set(d,{answered:!1,dc:l,expiresAt:g,expiryTimer:y,pc:t,secret:h,sessionId:d}),m.emitTap({sessionId:d,type:`invitation-created`}),recomputeStatus(),{expiresAt:g,sdp:v,secret:h,sessionId:d,v:1,...e?.name===void 0?{}:{hostName:e.name}}},get disposalSignal(){return m.disposalCtrl.signal},dispose(){if(!m.disposed){m.markDisposed();for(let e of _.values())clearTimeout(e.expiryTimer),e.pc.close();_.clear();for(let e of g.values())e.dc?.close(),e.pc?.close();g.clear(),h.clear()}},get disposed(){return m.disposed},kick(e,t){m.ensureLive();let n=g.get(e);if(!n)throw new i.MeshConnectionError(`Unknown peer "${e}"`,e);leavePeer(n,t??`kicked`)},on(e,t){return m.ensureLive(),h.on(e,t)},get peers(){return g},send(e,t,n){m.ensureLive();let r=g.get(e);if(!r)throw new i.MeshConnectionError(`Unknown peer "${e}"`,e);h.sendTo(r,t,n)},get status(){return m.status},tap(e,t){return m.tap(e,t)},[Symbol.dispose](){this.dispose()}}}exports.createMeshHost=createMeshHost;
1
+ require("./_defaults.cjs");const e=require("./_node.cjs"),t=require("./_proof.cjs"),n=require("./_random.cjs"),r=require("./_rtc.cjs"),i=require("./errors.cjs");let a=require("@vielzeug/arsenal");function createMeshHost(o={}){let s=o.rtc??r.nativeRtcFactory,c=o.clock??(()=>Date.now()),l=o.maxMessageBytes??65536,u=o.invitationTtlMs??3e5,d=o.channelOpenTimeoutMs??6e4,f=o.iceGatheringTimeoutMs??5e3,p={label:`mesh`,ordered:!0,...o.channel},m=e.createNodeCore(),h=e.createMessenger({clock:c,emitTap:m.emitTap,maxMessageBytes:l}),g=new Map,_=new Map,v=!1,y=!1;function recomputeStatus(){let e=_.size>0?`pairing`:v?`disconnected`:y?`failed`:`idle`;for(let t of g.values()){if(t.status===`connected`){e=`connected`;break}t.status===`connecting`&&(e=`connecting`)}m.setStatus(e)}function expireInvitation(e){let t=_.get(e);t&&(_.delete(e),clearTimeout(t.expiryTimer),t.pc.close(),m.emitTap({sessionId:e,type:`invitation-expired`}),recomputeStatus())}function releaseInvitation(e,t){_.get(e)===t&&(t.state=`open`)}function consumeInvitation(e,t){_.get(e)===t&&(_.delete(e),clearTimeout(t.expiryTimer))}function discardInvitation(e,t){consumeInvitation(e,t),t.pc.close()}function setPeerStatus(e,t){e.status!==t&&(e.status=t,m.emitTap({peerId:e.id,status:t,type:`peer-status-change`}),recomputeStatus())}function leavePeer(e,t,n=!1){g.has(e.id)&&(g.delete(e.id),e.status=n?`failed`:`disconnected`,e.pc?.close(),e.dc?.close(),m.emitTap({peerId:e.id,status:e.status,type:`peer-status-change`}),m.emitTap({peer:e.publicPeer,reason:t,type:`peer-left`}),n||(v=!0),y||=n,recomputeStatus())}function wirePeerTransport(e,t,n){e.pc=t,e.dc=n,n.addEventListener(`message`,t=>{m.disposed||h.handleInbound(e,t.data)}),n.addEventListener(`close`,()=>{m.disposed||leavePeer(e,`channel closed`)}),n.addEventListener(`error`,()=>{m.disposed||leavePeer(e,`channel error`,!0)}),t.addEventListener(`iceconnectionstatechange`,()=>{if(m.disposed)return;let n=t.iceConnectionState;m.emitTap({peerId:e.id,state:n,type:`ice-state`}),(n===`failed`||n===`closed`)&&leavePeer(e,`ice ${n}`,n===`failed`)})}function markPeerConnected(e){v=!0,g.set(e.id,e),setPeerStatus(e,`connected`),m.emitTap({peer:e,type:`peer-joined`})}let b={async acceptAnswer(n){if(m.ensureLive(),n?.v!==1)throw new i.MeshPairingError(`Unsupported answer version`);if(!n.peer?.id)throw new i.MeshPairingError(`Answer is missing a peer id`);let a=_.get(n.sessionId);if(!a)throw new i.MeshPairingError(`Unknown or expired session`);if(a.state!==`open`)throw new i.MeshPairingError(`Invitation already answered`);if(g.has(n.peer.id))throw new i.MeshPairingError(`Peer "${n.peer.id}" is already connected`);if(c()>=a.expiresAt)throw expireInvitation(n.sessionId),new i.MeshPairingError(`Invitation expired`);a.state=`reserved`;let s;try{let e=await t.createProof(a.secret,n.sdp);if(n.proof!==e)throw new i.MeshPairingError(`Proof mismatch`);s=await o.approvePeer?.(n.peer)??!0}catch(e){throw releaseInvitation(n.sessionId,a),e}if(m.ensureLive(),!s)throw m.emitTap({peerId:n.peer.id,type:`peer-rejected`}),discardInvitation(n.sessionId,a),recomputeStatus(),new i.MeshPairingError(`Peer "${n.peer.id}" rejected by host`);if(m.emitTap({peerId:n.peer.id,type:`peer-approved`}),_.get(n.sessionId)!==a)throw new i.MeshPairingError(`Invitation expired`);if(g.has(n.peer.id))throw releaseInvitation(n.sessionId,a),new i.MeshPairingError(`Peer "${n.peer.id}" is already connected`);consumeInvitation(n.sessionId,a);let l=e.createPeerRecord(n.peer.id,n.peer.name,`guest`),u=r.waitChannelOpen(a.dc,a.pc,d,l.id,m.disposalCtrl.signal);wirePeerTransport(l,a.pc,a.dc),g.set(l.id,l),recomputeStatus();try{await a.pc.setRemoteDescription({sdp:r.normalizeSdp(n.sdp),type:`answer`})}catch(e){throw leavePeer(l,`invalid answer sdp`,!0),new i.MeshPairingError(`Invalid answer SDP`,{cause:e})}try{await u}catch(e){let t=!(e instanceof i.MeshDisposedError);throw leavePeer(l,e instanceof Error?e.message:`open failed`,t),e}return markPeerConnected(l),l.publicPeer},broadcast(e,t,n){m.ensureLive();for(let r of g.values())r.status!==`connected`||n?.except?.includes(r.id)||h.sendTo(r,e,t)},async createInvitation(e){m.ensureLive();let t=s.createPeerConnection({iceServers:[...o.iceServers??[]]}),l=t.createDataChannel(p.label,{maxRetransmits:p.maxRetransmits,ordered:p.ordered}),d=n.randomId(o.random),h=(0,a.bytesToBase64Url)(n.randomBytes(32,o.random)),g=c()+u;try{await t.setLocalDescription(await t.createOffer()),await r.waitIceGathering(t,f)}catch(e){throw t.close(),new i.MeshConnectionError(`Failed to create offer`,null,{cause:e})}if(m.disposed)throw t.close(),new i.MeshDisposedError;let v=t.localDescription?.sdp;if(!v)throw t.close(),new i.MeshConnectionError(`Local description has no SDP`);let y=setTimeout(()=>expireInvitation(d),u);return _.set(d,{dc:l,expiresAt:g,expiryTimer:y,pc:t,secret:h,sessionId:d,state:`open`}),m.emitTap({sessionId:d,type:`invitation-created`}),recomputeStatus(),{expiresAt:g,sdp:v,secret:h,sessionId:d,v:1,...e?.name===void 0?{}:{hostName:e.name}}},get disposalSignal(){return m.disposalCtrl.signal},dispose(){if(!m.disposed){m.markDisposed();for(let e of _.values())clearTimeout(e.expiryTimer),e.pc.close();_.clear();for(let e of g.values())e.dc?.close(),e.pc?.close();g.clear(),h.clear()}},get disposed(){return m.disposed},kick(e,t){m.ensureLive();let n=g.get(e);if(!n)throw new i.MeshConnectionError(`Unknown peer "${e}"`,e);leavePeer(n,t??`kicked`)},on(e,t){return m.ensureLive(),h.on(e,t)},get peers(){return g},send(e,t,n){m.ensureLive();let r=g.get(e);if(!r)throw new i.MeshConnectionError(`Unknown peer "${e}"`,e);h.sendTo(r,t,n)},get status(){return m.status},tap(e,t){return m.tap(e,t)},[Symbol.dispose](){this.dispose()}};return e.wireDisposalSignal(o.signal,()=>b.dispose()),b}exports.createMeshHost=createMeshHost;
2
2
  //# sourceMappingURL=host.cjs.map
package/dist/host.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.cjs","names":["nativeRtcFactory","createNodeCore","createMessenger","MeshPairingError","createProof","createPeerRecord","waitChannelOpen","normalizeSdp","MeshDisposedError","randomId","bytesToBase64Url","randomBytes","waitIceGathering","MeshConnectionError","require__node","require__proof","require__random","require__rtc","require_errors","_vielzeug_arsenal","rtc","options","clock","maxMessageBytes","invitationTtlMs","channelOpenTimeoutMs","iceGatheringTimeoutMs","channelInit","core","messenger","peers","pending","sawPeer","sawFailure","next","peer","invitation","sessionId","status","failed","pc","dc","event","state","answer","expected","opened","cause","error","broadcastOptions","type","payload","secret","expiresAt","sdp","expiryTimer","meta","peerId","reason","handler","tapOptions"],"sources":["../src/host.ts"],"sourcesContent":["import { bytesToBase64Url } from '@vielzeug/arsenal';\nimport {\n DEFAULT_CHANNEL_OPEN_TIMEOUT_MS,\n DEFAULT_ICE_GATHERING_TIMEOUT_MS,\n DEFAULT_INVITATION_TTL_MS,\n DEFAULT_MAX_MESSAGE_BYTES,\n} from './_defaults';\nimport { createMessenger, createNodeCore, createPeerRecord, type PeerRecord } from './_node';\nimport { createProof } from './_proof';\nimport { randomBytes, randomId } from './_random';\nimport { nativeRtcFactory, normalizeSdp, waitChannelOpen, waitIceGathering } from './_rtc';\nimport { MeshConnectionError, MeshDisposedError, MeshPairingError } from './errors';\nimport type {\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshPeer,\n MeshProtocol,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n} from './types';\n\ninterface PendingInvitation {\n answered: boolean;\n readonly dc: RTCDataChannelLike;\n readonly expiresAt: number;\n readonly expiryTimer: ReturnType<typeof setTimeout>;\n readonly pc: RTCPeerConnectionLike;\n readonly secret: string;\n readonly sessionId: string;\n}\n\n/**\n * Create a host-authoritative mesh node. The host holds one peer connection\n * per guest and pairs each one through a manual invitation/answer exchange.\n */\nexport function createMeshHost<P extends MeshProtocol>(options: MeshHostOptions = {}): MeshHost<P> {\n const rtc = options.rtc ?? nativeRtcFactory;\n const clock = options.clock ?? (() => Date.now());\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const invitationTtlMs = options.invitationTtlMs ?? DEFAULT_INVITATION_TTL_MS;\n const channelOpenTimeoutMs = options.channelOpenTimeoutMs ?? DEFAULT_CHANNEL_OPEN_TIMEOUT_MS;\n const iceGatheringTimeoutMs = options.iceGatheringTimeoutMs ?? DEFAULT_ICE_GATHERING_TIMEOUT_MS;\n const channelInit = { label: 'mesh', ordered: true, ...options.channel };\n\n const core = createNodeCore(options.signal);\n const messenger = createMessenger({\n clock,\n emitTap: core.emitTap,\n maxMessageBytes,\n random: options.random,\n });\n\n const peers = new Map<string, PeerRecord>();\n const pending = new Map<string, PendingInvitation>();\n\n let sawPeer = false;\n let sawFailure = false;\n\n function recomputeStatus(): void {\n let next: MeshStatus = pending.size > 0 ? 'pairing' : sawPeer ? 'disconnected' : sawFailure ? 'failed' : 'idle';\n for (const peer of peers.values()) {\n if (peer.status === 'connected') {\n next = 'connected';\n break;\n }\n if (peer.status === 'connecting') next = 'connecting';\n }\n core.setStatus(next);\n }\n\n function expireInvitation(sessionId: string): void {\n const invitation = pending.get(sessionId);\n if (!invitation) return;\n pending.delete(sessionId);\n clearTimeout(invitation.expiryTimer);\n invitation.pc.close();\n core.emitTap({ sessionId, type: 'invitation-expired' });\n recomputeStatus();\n }\n\n function setPeerStatus(peer: PeerRecord, status: PeerRecord['status']): void {\n if (peer.status === status) return;\n peer.status = status;\n core.emitTap({ peerId: peer.id, status, type: 'peer-status-change' });\n recomputeStatus();\n }\n\n function leavePeer(peer: PeerRecord, reason: string | undefined, failed = false): void {\n if (!peers.has(peer.id)) return;\n peers.delete(peer.id);\n peer.status = failed ? 'failed' : 'disconnected';\n peer.pc?.close();\n peer.dc?.close();\n core.emitTap({ peerId: peer.id, status: peer.status, type: 'peer-status-change' });\n core.emitTap({ peer: peer.publicPeer, reason, type: 'peer-left' });\n if (!failed) sawPeer = true;\n sawFailure = sawFailure || failed;\n recomputeStatus();\n }\n\n function wirePeerTransport(peer: PeerRecord, pc: RTCPeerConnectionLike, dc: RTCDataChannelLike): void {\n peer.pc = pc;\n peer.dc = dc;\n\n dc.addEventListener('message', (event) => {\n if (core.disposed) return;\n messenger.handleInbound(peer, event.data);\n });\n dc.addEventListener('close', () => {\n if (core.disposed) return;\n leavePeer(peer, 'channel closed');\n });\n dc.addEventListener('error', () => {\n if (core.disposed) return;\n leavePeer(peer, 'channel error', true);\n });\n\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n const state = pc.iceConnectionState;\n core.emitTap({ peerId: peer.id, state, type: 'ice-state' });\n if (state === 'failed' || state === 'closed') {\n leavePeer(peer, `ice ${state}`, state === 'failed');\n } else if (state === 'disconnected' && peer.status === 'connected') {\n setPeerStatus(peer, 'disconnected');\n }\n });\n }\n\n function markPeerConnected(peer: PeerRecord): void {\n sawPeer = true;\n peers.set(peer.id, peer);\n setPeerStatus(peer, 'connected');\n core.emitTap({ peer, type: 'peer-joined' });\n }\n\n const host: MeshHost<P> = {\n async acceptAnswer(answer) {\n core.ensureLive();\n\n if (answer?.v !== 1) throw new MeshPairingError('Unsupported answer version');\n if (!answer.peer?.id) throw new MeshPairingError('Answer is missing a peer id');\n const invitation = pending.get(answer.sessionId);\n if (!invitation) throw new MeshPairingError('Unknown or expired session');\n if (invitation.answered) throw new MeshPairingError('Invitation already answered');\n if (peers.has(answer.peer.id)) throw new MeshPairingError(`Peer \"${answer.peer.id}\" is already connected`);\n if (clock() >= invitation.expiresAt) {\n expireInvitation(answer.sessionId);\n throw new MeshPairingError('Invitation expired');\n }\n\n const expected = await createProof(invitation.secret, answer.sdp);\n if (answer.proof !== expected) throw new MeshPairingError('Proof mismatch');\n\n const approved = (await options.approvePeer?.(answer.peer)) ?? true;\n if (!approved) {\n core.emitTap({ peerId: answer.peer.id, type: 'peer-rejected' });\n throw new MeshPairingError(`Peer \"${answer.peer.id}\" rejected by host`);\n }\n core.emitTap({ peerId: answer.peer.id, type: 'peer-approved' });\n\n // Re-check after the proof/approval awaits: concurrent answers for\n // different sessions could both have passed the check above.\n if (peers.has(answer.peer.id)) throw new MeshPairingError(`Peer \"${answer.peer.id}\" is already connected`);\n\n invitation.answered = true;\n pending.delete(answer.sessionId);\n clearTimeout(invitation.expiryTimer);\n\n const peer = createPeerRecord(answer.peer.id, answer.peer.name, 'guest');\n const opened = waitChannelOpen(\n invitation.dc,\n invitation.pc,\n channelOpenTimeoutMs,\n peer.id,\n core.disposalCtrl.signal,\n );\n wirePeerTransport(peer, invitation.pc, invitation.dc);\n peers.set(peer.id, peer);\n recomputeStatus();\n\n try {\n await invitation.pc.setRemoteDescription({ sdp: normalizeSdp(answer.sdp), type: 'answer' });\n } catch (cause) {\n leavePeer(peer, 'invalid answer sdp', true);\n throw new MeshPairingError('Invalid answer SDP', { cause });\n }\n\n try {\n await opened;\n } catch (error) {\n const failed = !(error instanceof MeshDisposedError);\n leavePeer(peer, error instanceof Error ? error.message : 'open failed', failed);\n throw error;\n }\n\n markPeerConnected(peer);\n return peer.publicPeer;\n },\n\n broadcast(type, payload, broadcastOptions) {\n core.ensureLive();\n for (const peer of peers.values()) {\n if (peer.status !== 'connected' || broadcastOptions?.except?.includes(peer.id)) continue;\n messenger.sendTo(peer, type, payload);\n }\n },\n\n async createInvitation(meta) {\n core.ensureLive();\n\n const pc = rtc.createPeerConnection({ iceServers: [...(options.iceServers ?? [])] });\n const dc = pc.createDataChannel(channelInit.label, {\n maxRetransmits: channelInit.maxRetransmits,\n ordered: channelInit.ordered,\n });\n\n const sessionId = randomId(options.random);\n const secret = bytesToBase64Url(randomBytes(32, options.random));\n const expiresAt = clock() + invitationTtlMs;\n\n try {\n await pc.setLocalDescription(await pc.createOffer());\n await waitIceGathering(pc, iceGatheringTimeoutMs);\n } catch (cause) {\n pc.close();\n throw new MeshConnectionError('Failed to create offer', null, { cause });\n }\n if (core.disposed) {\n pc.close();\n throw new MeshDisposedError();\n }\n\n const sdp = pc.localDescription?.sdp;\n if (!sdp) {\n pc.close();\n throw new MeshConnectionError('Local description has no SDP');\n }\n\n const expiryTimer = setTimeout(() => expireInvitation(sessionId), invitationTtlMs);\n pending.set(sessionId, { answered: false, dc, expiresAt, expiryTimer, pc, secret, sessionId });\n core.emitTap({ sessionId, type: 'invitation-created' });\n recomputeStatus();\n return { expiresAt, sdp, secret, sessionId, v: 1, ...(meta?.name === undefined ? {} : { hostName: meta.name }) };\n },\n get disposalSignal() {\n return core.disposalCtrl.signal;\n },\n\n dispose() {\n if (core.disposed) return;\n core.markDisposed();\n for (const invitation of pending.values()) {\n clearTimeout(invitation.expiryTimer);\n invitation.pc.close();\n }\n pending.clear();\n for (const peer of peers.values()) {\n peer.dc?.close();\n peer.pc?.close();\n }\n peers.clear();\n messenger.clear();\n },\n get disposed() {\n return core.disposed;\n },\n\n kick(peerId, reason) {\n core.ensureLive();\n const peer = peers.get(peerId);\n if (!peer) throw new MeshConnectionError(`Unknown peer \"${peerId}\"`, peerId);\n leavePeer(peer, reason ?? 'kicked');\n },\n\n on(type, handler) {\n core.ensureLive();\n return messenger.on(type, handler as (message: MeshInbound<unknown>) => void);\n },\n get peers() {\n return peers as ReadonlyMap<string, MeshPeer>;\n },\n\n send(peerId, type, payload) {\n core.ensureLive();\n const peer = peers.get(peerId);\n if (!peer) throw new MeshConnectionError(`Unknown peer \"${peerId}\"`, peerId);\n messenger.sendTo(peer, type, payload);\n },\n get status() {\n return core.status;\n },\n\n tap(handler, tapOptions) {\n return core.tap(handler, tapOptions);\n },\n\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n\n return host;\n}\n"],"mappings":"A,oMAqCA,SAAgB,eAAuC,EAA2B,CAAC,EAAgB,CACjG,IAAMoB,EAAMC,EAAQ,KAAOrB,EAAAA,iBACrBsB,EAAQD,EAAQ,YAAgB,KAAK,IAAI,GACzCE,EAAkBF,EAAQ,iBAAA,MAC1BG,EAAkBH,EAAQ,iBAAA,IAC1BI,EAAuBJ,EAAQ,sBAAA,IAC/BK,EAAwBL,EAAQ,uBAAA,IAChCM,EAAc,CAAE,MAAO,OAAQ,QAAS,GAAM,GAAGN,EAAQ,OAAQ,EAEj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,IAAMO,EAAOL,EAAM,IAAI2B,CAAM,EAC7B,GAAI,CAACtB,EAAM,MAAM,IAAItB,EAAAA,oBAAoB,iBAAiB4C,EAAO,GAAIA,CAAM,EAC3E5B,EAAU,OAAOM,EAAMe,EAAMC,CAAO,CACtC,EACA,IAAI,QAAS,CACX,OAAOvB,EAAK,MACd,EAEA,IAAI,EAAS,EAAY,CACvB,OAAOA,EAAK,IAAI+B,EAASC,CAAU,CACrC,EAEA,CAAC,OAAO,UAAW,CACjB,KAAK,QAAQ,CACf,CAGK,CACT,C"}
1
+ {"version":3,"file":"host.cjs","names":["nativeRtcFactory","createNodeCore","createMessenger","MeshPairingError","createProof","createPeerRecord","waitChannelOpen","normalizeSdp","MeshDisposedError","randomId","bytesToBase64Url","randomBytes","waitIceGathering","MeshConnectionError","require__node","require__proof","require__random","require__rtc","require_errors","_vielzeug_arsenal","rtc","options","clock","maxMessageBytes","invitationTtlMs","channelOpenTimeoutMs","iceGatheringTimeoutMs","channelInit","core","messenger","peers","pending","sawPeer","sawFailure","next","peer","invitation","sessionId","status","failed","pc","dc","event","state","host","answer","approved","expected","error","opened","cause","broadcastOptions","type","payload","secret","expiresAt","sdp","expiryTimer","meta","peerId","reason","handler","tapOptions"],"sources":["../src/host.ts"],"sourcesContent":["import { bytesToBase64Url } from '@vielzeug/arsenal';\nimport {\n DEFAULT_CHANNEL_OPEN_TIMEOUT_MS,\n DEFAULT_ICE_GATHERING_TIMEOUT_MS,\n DEFAULT_INVITATION_TTL_MS,\n DEFAULT_MAX_MESSAGE_BYTES,\n} from './_defaults';\nimport { createMessenger, createNodeCore, createPeerRecord, type PeerRecord, wireDisposalSignal } from './_node';\nimport { createProof } from './_proof';\nimport { randomBytes, randomId } from './_random';\nimport { nativeRtcFactory, normalizeSdp, waitChannelOpen, waitIceGathering } from './_rtc';\nimport { MeshConnectionError, MeshDisposedError, MeshPairingError } from './errors';\nimport type {\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshPeer,\n MeshProtocol,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n} from './types';\n\ninterface PendingInvitation {\n readonly dc: RTCDataChannelLike;\n readonly expiresAt: number;\n readonly expiryTimer: ReturnType<typeof setTimeout>;\n readonly pc: RTCPeerConnectionLike;\n readonly secret: string;\n readonly sessionId: string;\n /**\n * Single-use reservation, taken synchronously before any `await` in\n * `acceptAnswer` so concurrent answers cannot both pass validation.\n */\n state: 'open' | 'reserved';\n}\n\n/**\n * Create a host-authoritative mesh node. The host holds one peer connection\n * per guest and pairs each one through a manual invitation/answer exchange.\n */\nexport function createMeshHost<P extends MeshProtocol>(options: MeshHostOptions = {}): MeshHost<P> {\n const rtc = options.rtc ?? nativeRtcFactory;\n const clock = options.clock ?? (() => Date.now());\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const invitationTtlMs = options.invitationTtlMs ?? DEFAULT_INVITATION_TTL_MS;\n const channelOpenTimeoutMs = options.channelOpenTimeoutMs ?? DEFAULT_CHANNEL_OPEN_TIMEOUT_MS;\n const iceGatheringTimeoutMs = options.iceGatheringTimeoutMs ?? DEFAULT_ICE_GATHERING_TIMEOUT_MS;\n const channelInit = { label: 'mesh', ordered: true, ...options.channel };\n\n const core = createNodeCore();\n const messenger = createMessenger({\n clock,\n emitTap: core.emitTap,\n maxMessageBytes,\n });\n\n const peers = new Map<string, PeerRecord>();\n const pending = new Map<string, PendingInvitation>();\n\n let sawPeer = false;\n let sawFailure = false;\n\n function recomputeStatus(): void {\n let next: MeshStatus = pending.size > 0 ? 'pairing' : sawPeer ? 'disconnected' : sawFailure ? 'failed' : 'idle';\n for (const peer of peers.values()) {\n if (peer.status === 'connected') {\n next = 'connected';\n break;\n }\n if (peer.status === 'connecting') next = 'connecting';\n }\n core.setStatus(next);\n }\n\n function expireInvitation(sessionId: string): void {\n const invitation = pending.get(sessionId);\n if (!invitation) return;\n pending.delete(sessionId);\n clearTimeout(invitation.expiryTimer);\n invitation.pc.close();\n core.emitTap({ sessionId, type: 'invitation-expired' });\n recomputeStatus();\n }\n\n /** Opens a reserved invitation for another answer, unless it already expired. */\n function releaseInvitation(sessionId: string, invitation: PendingInvitation): void {\n if (pending.get(sessionId) === invitation) invitation.state = 'open';\n }\n\n /**\n * Retires an invitation for good: no further answer will be accepted for\n * it. Callers recompute status once their own state is in place. Used when\n * the invitation's transport is handed to a peer; refusing a peer must\n * teardown the transport through `discardInvitation` instead.\n */\n function consumeInvitation(sessionId: string, invitation: PendingInvitation): void {\n if (pending.get(sessionId) !== invitation) return;\n pending.delete(sessionId);\n clearTimeout(invitation.expiryTimer);\n }\n\n /** Retires an invitation that will never become a peer and closes its transport. */\n function discardInvitation(sessionId: string, invitation: PendingInvitation): void {\n consumeInvitation(sessionId, invitation);\n invitation.pc.close();\n }\n\n function setPeerStatus(peer: PeerRecord, status: PeerRecord['status']): void {\n if (peer.status === status) return;\n peer.status = status;\n core.emitTap({ peerId: peer.id, status, type: 'peer-status-change' });\n recomputeStatus();\n }\n\n function leavePeer(peer: PeerRecord, reason: string | undefined, failed = false): void {\n if (!peers.has(peer.id)) return;\n peers.delete(peer.id);\n peer.status = failed ? 'failed' : 'disconnected';\n peer.pc?.close();\n peer.dc?.close();\n core.emitTap({ peerId: peer.id, status: peer.status, type: 'peer-status-change' });\n core.emitTap({ peer: peer.publicPeer, reason, type: 'peer-left' });\n if (!failed) sawPeer = true;\n sawFailure = sawFailure || failed;\n recomputeStatus();\n }\n\n function wirePeerTransport(peer: PeerRecord, pc: RTCPeerConnectionLike, dc: RTCDataChannelLike): void {\n peer.pc = pc;\n peer.dc = dc;\n\n dc.addEventListener('message', (event) => {\n if (core.disposed) return;\n messenger.handleInbound(peer, event.data);\n });\n dc.addEventListener('close', () => {\n if (core.disposed) return;\n leavePeer(peer, 'channel closed');\n });\n dc.addEventListener('error', () => {\n if (core.disposed) return;\n leavePeer(peer, 'channel error', true);\n });\n\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n const state = pc.iceConnectionState;\n core.emitTap({ peerId: peer.id, state, type: 'ice-state' });\n if (state === 'failed' || state === 'closed') {\n leavePeer(peer, `ice ${state}`, state === 'failed');\n }\n // `disconnected` is transient in WebRTC and often recovers: peer\n // liveness follows the data channel, so a blip only surfaces as the\n // `ice-state` tap event above.\n });\n }\n\n function markPeerConnected(peer: PeerRecord): void {\n sawPeer = true;\n peers.set(peer.id, peer);\n setPeerStatus(peer, 'connected');\n core.emitTap({ peer, type: 'peer-joined' });\n }\n\n const host: MeshHost<P> = {\n async acceptAnswer(answer) {\n core.ensureLive();\n\n if (answer?.v !== 1) throw new MeshPairingError('Unsupported answer version');\n if (!answer.peer?.id) throw new MeshPairingError('Answer is missing a peer id');\n const invitation = pending.get(answer.sessionId);\n if (!invitation) throw new MeshPairingError('Unknown or expired session');\n if (invitation.state !== 'open') throw new MeshPairingError('Invitation already answered');\n if (peers.has(answer.peer.id)) throw new MeshPairingError(`Peer \"${answer.peer.id}\" is already connected`);\n if (clock() >= invitation.expiresAt) {\n expireInvitation(answer.sessionId);\n throw new MeshPairingError('Invitation expired');\n }\n // Reserve synchronously before the first await: a concurrent answer for\n // this session can only lose here, never race through the awaits below.\n invitation.state = 'reserved';\n\n let approved: boolean;\n try {\n const expected = await createProof(invitation.secret, answer.sdp);\n if (answer.proof !== expected) throw new MeshPairingError('Proof mismatch');\n approved = (await options.approvePeer?.(answer.peer)) ?? true;\n } catch (error) {\n // Proof mismatch or an approval/proof failure: the invitation was not\n // decided, so the genuine guest can still answer it.\n releaseInvitation(answer.sessionId, invitation);\n throw error;\n }\n\n // Disposal while awaiting proof/approval must win over the approval\n // result: the node was torn down, it never decided anything.\n core.ensureLive();\n\n if (!approved) {\n core.emitTap({ peerId: answer.peer.id, type: 'peer-rejected' });\n // The host made a decision for this session: the invitation is spent\n // and its transport is torn down, or refused peers would leak one\n // connection per attempt.\n discardInvitation(answer.sessionId, invitation);\n recomputeStatus();\n throw new MeshPairingError(`Peer \"${answer.peer.id}\" rejected by host`);\n }\n core.emitTap({ peerId: answer.peer.id, type: 'peer-approved' });\n\n // The expiry timer may have retired the invitation mid-flight; its peer\n // connection is already closed.\n if (pending.get(answer.sessionId) !== invitation) throw new MeshPairingError('Invitation expired');\n // Concurrent answers for different sessions could both have passed the check above.\n if (peers.has(answer.peer.id)) {\n // The collision is about the peer id, not this session: leave it answerable.\n releaseInvitation(answer.sessionId, invitation);\n throw new MeshPairingError(`Peer \"${answer.peer.id}\" is already connected`);\n }\n consumeInvitation(answer.sessionId, invitation);\n\n const peer = createPeerRecord(answer.peer.id, answer.peer.name, 'guest');\n const opened = waitChannelOpen(\n invitation.dc,\n invitation.pc,\n channelOpenTimeoutMs,\n peer.id,\n core.disposalCtrl.signal,\n );\n wirePeerTransport(peer, invitation.pc, invitation.dc);\n peers.set(peer.id, peer);\n recomputeStatus();\n\n try {\n await invitation.pc.setRemoteDescription({ sdp: normalizeSdp(answer.sdp), type: 'answer' });\n } catch (cause) {\n leavePeer(peer, 'invalid answer sdp', true);\n throw new MeshPairingError('Invalid answer SDP', { cause });\n }\n\n try {\n await opened;\n } catch (error) {\n const failed = !(error instanceof MeshDisposedError);\n leavePeer(peer, error instanceof Error ? error.message : 'open failed', failed);\n throw error;\n }\n\n markPeerConnected(peer);\n return peer.publicPeer;\n },\n\n broadcast(type, payload, broadcastOptions) {\n core.ensureLive();\n for (const peer of peers.values()) {\n if (peer.status !== 'connected' || broadcastOptions?.except?.includes(peer.id)) continue;\n messenger.sendTo(peer, type, payload);\n }\n },\n\n async createInvitation(meta) {\n core.ensureLive();\n\n const pc = rtc.createPeerConnection({ iceServers: [...(options.iceServers ?? [])] });\n const dc = pc.createDataChannel(channelInit.label, {\n maxRetransmits: channelInit.maxRetransmits,\n ordered: channelInit.ordered,\n });\n\n const sessionId = randomId(options.random);\n const secret = bytesToBase64Url(randomBytes(32, options.random));\n const expiresAt = clock() + invitationTtlMs;\n\n try {\n await pc.setLocalDescription(await pc.createOffer());\n await waitIceGathering(pc, iceGatheringTimeoutMs);\n } catch (cause) {\n pc.close();\n throw new MeshConnectionError('Failed to create offer', null, { cause });\n }\n if (core.disposed) {\n pc.close();\n throw new MeshDisposedError();\n }\n\n const sdp = pc.localDescription?.sdp;\n if (!sdp) {\n pc.close();\n throw new MeshConnectionError('Local description has no SDP');\n }\n\n const expiryTimer = setTimeout(() => expireInvitation(sessionId), invitationTtlMs);\n pending.set(sessionId, { dc, expiresAt, expiryTimer, pc, secret, sessionId, state: 'open' });\n core.emitTap({ sessionId, type: 'invitation-created' });\n recomputeStatus();\n return { expiresAt, sdp, secret, sessionId, v: 1, ...(meta?.name === undefined ? {} : { hostName: meta.name }) };\n },\n get disposalSignal() {\n return core.disposalCtrl.signal;\n },\n\n dispose() {\n if (core.disposed) return;\n core.markDisposed();\n for (const invitation of pending.values()) {\n clearTimeout(invitation.expiryTimer);\n invitation.pc.close();\n }\n pending.clear();\n for (const peer of peers.values()) {\n peer.dc?.close();\n peer.pc?.close();\n }\n peers.clear();\n messenger.clear();\n },\n get disposed() {\n return core.disposed;\n },\n\n kick(peerId, reason) {\n core.ensureLive();\n const peer = peers.get(peerId);\n if (!peer) throw new MeshConnectionError(`Unknown peer \"${peerId}\"`, peerId);\n leavePeer(peer, reason ?? 'kicked');\n },\n\n on(type, handler) {\n core.ensureLive();\n return messenger.on(type, handler as (message: MeshInbound<unknown>) => void);\n },\n get peers() {\n return peers as ReadonlyMap<string, MeshPeer>;\n },\n\n send(peerId, type, payload) {\n core.ensureLive();\n const peer = peers.get(peerId);\n if (!peer) throw new MeshConnectionError(`Unknown peer \"${peerId}\"`, peerId);\n messenger.sendTo(peer, type, payload);\n },\n get status() {\n return core.status;\n },\n\n tap(handler, tapOptions) {\n return core.tap(handler, tapOptions);\n },\n\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n\n wireDisposalSignal(options.signal, () => host.dispose());\n return host;\n}\n"],"mappings":"A,oMAyCA,SAAgB,eAAuC,EAA2B,CAAC,EAAgB,C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}
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,QAAQ,EACR,eAAe,EAGf,YAAY,EAIb,MAAM,SAAS,CAAC;AAYjB;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,YAAY,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAAC,CAAC,CAAC,CA4QjG"}
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,QAAQ,EACR,eAAe,EAGf,YAAY,EAIb,MAAM,SAAS,CAAC;AAgBjB;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,YAAY,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAAC,CAAC,CAAC,CA2TjG"}