@statewalker/webrun-streams-signaling 0.1.1

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/index.js ADDED
@@ -0,0 +1,708 @@
1
+ //#region src/byte-queue.ts
2
+ /**
3
+ * Minimal eager push/pull byte queue backing the `recv` side of the
4
+ * {@link ByteChannel} adapters. "Eager" = bytes pushed before the consumer
5
+ * starts iterating are buffered (not dropped), which the signaling adapters
6
+ * need because a channel can receive data the instant it opens, before the
7
+ * caller wires up its `for await`.
8
+ */
9
+ function makeByteQueue() {
10
+ const chunks = [];
11
+ let pending = null;
12
+ let ended = false;
13
+ const push = (bytes) => {
14
+ if (ended) return;
15
+ if (pending) {
16
+ const resolve = pending;
17
+ pending = null;
18
+ resolve({
19
+ value: bytes,
20
+ done: false
21
+ });
22
+ } else chunks.push(bytes);
23
+ };
24
+ const done = () => {
25
+ if (ended) return;
26
+ ended = true;
27
+ if (pending) {
28
+ const resolve = pending;
29
+ pending = null;
30
+ resolve({
31
+ value: void 0,
32
+ done: true
33
+ });
34
+ }
35
+ };
36
+ return {
37
+ recv: { [Symbol.asyncIterator]() {
38
+ return { next() {
39
+ if (chunks.length > 0) return Promise.resolve({
40
+ value: chunks.shift(),
41
+ done: false
42
+ });
43
+ if (ended) return Promise.resolve({
44
+ value: void 0,
45
+ done: true
46
+ });
47
+ return new Promise((resolve) => {
48
+ pending = resolve;
49
+ });
50
+ } };
51
+ } },
52
+ push,
53
+ done
54
+ };
55
+ }
56
+ /** Coerce a message payload (Uint8Array / ArrayBuffer / view) to a Uint8Array copy. */
57
+ function toBytes(data) {
58
+ if (data instanceof Uint8Array) return new Uint8Array(data);
59
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
60
+ if (ArrayBuffer.isView(data)) {
61
+ const view = data;
62
+ return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
63
+ }
64
+ throw new TypeError("byte channel received a non-byte payload");
65
+ }
66
+ //#endregion
67
+ //#region src/types.ts
68
+ /** Default ICE servers (public STUN servers). */
69
+ const DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }];
70
+ /** LiveKit `RoomEvent` string values used here (avoids a runtime vendor import). */
71
+ const ROOM_EVENT = {
72
+ participantConnected: "participantConnected",
73
+ participantDisconnected: "participantDisconnected",
74
+ dataReceived: "dataReceived"
75
+ };
76
+ //#endregion
77
+ //#region src/byte-channel.ts
78
+ /**
79
+ * Wrap an established `RTCDataChannel` as a {@link ByteChannel}. Outbound bytes
80
+ * go through `channel.send`; inbound `message` events feed `recv`.
81
+ */
82
+ function byteChannelFromDataChannel(channel) {
83
+ const queue = makeByteQueue();
84
+ let closedResolve;
85
+ const closed = new Promise((r) => {
86
+ closedResolve = r;
87
+ });
88
+ const onMessage = (ev) => queue.push(toBytes(ev.data));
89
+ const onClose = () => {
90
+ queue.done();
91
+ closedResolve();
92
+ };
93
+ channel.binaryType = "arraybuffer";
94
+ channel.addEventListener("message", onMessage);
95
+ channel.addEventListener("close", onClose);
96
+ return {
97
+ send(bytes) {
98
+ try {
99
+ channel.send(bytes);
100
+ } catch {}
101
+ },
102
+ recv: queue.recv,
103
+ closed,
104
+ close() {
105
+ channel.removeEventListener("message", onMessage);
106
+ channel.removeEventListener("close", onClose);
107
+ try {
108
+ channel.close();
109
+ } catch {}
110
+ queue.done();
111
+ closedResolve();
112
+ }
113
+ };
114
+ }
115
+ /**
116
+ * Build a {@link ByteChannel} to a single room participant over a LiveKit-style
117
+ * `Room`. Outbound bytes are published to `peerId`; inbound `dataReceived`
118
+ * events from `peerId` feed `recv`. This is the per-participant filtering the
119
+ * retired `vcs-port-livekit` `livekit-port` performed, adapted to ByteChannel.
120
+ */
121
+ function byteChannelFromRoom(room, peerId) {
122
+ const queue = makeByteQueue();
123
+ let closedResolve;
124
+ const closed = new Promise((r) => {
125
+ closedResolve = r;
126
+ });
127
+ const onData = (...args) => {
128
+ const payload = args[0];
129
+ const participant = args[1];
130
+ if (participant && participant.identity !== peerId) return;
131
+ if (payload != null) queue.push(toBytes(payload));
132
+ };
133
+ room.on(ROOM_EVENT.dataReceived, onData);
134
+ return {
135
+ send(bytes) {
136
+ room.localParticipant.publishData(bytes, {
137
+ reliable: true,
138
+ destinationIdentities: [peerId]
139
+ }).catch(() => {});
140
+ },
141
+ recv: queue.recv,
142
+ closed,
143
+ close() {
144
+ room.off(ROOM_EVENT.dataReceived, onData);
145
+ queue.done();
146
+ closedResolve();
147
+ }
148
+ };
149
+ }
150
+ //#endregion
151
+ //#region src/peer-connection.ts
152
+ const DEFAULT_CONNECTION_TIMEOUT = 3e4;
153
+ const DEFAULT_ICE_GATHERING_TIMEOUT = 5e3;
154
+ const DEFAULT_CHANNEL_LABEL = "webrun-data";
155
+ /**
156
+ * Manages a single WebRTC peer connection lifecycle.
157
+ */
158
+ var PeerConnection = class {
159
+ role;
160
+ options;
161
+ pc = null;
162
+ dataChannel = null;
163
+ state = "new";
164
+ listeners = /* @__PURE__ */ new Map();
165
+ pendingCandidates = [];
166
+ remoteDescriptionSet = false;
167
+ collectedCandidates = [];
168
+ iceGatheringComplete = false;
169
+ constructor(role, options = {}) {
170
+ this.role = role;
171
+ this.options = options;
172
+ }
173
+ getState() {
174
+ return this.state;
175
+ }
176
+ getRole() {
177
+ return this.role;
178
+ }
179
+ getDataChannel() {
180
+ return this.dataChannel;
181
+ }
182
+ on(event, listener) {
183
+ let listeners = this.listeners.get(event);
184
+ if (!listeners) {
185
+ listeners = /* @__PURE__ */ new Set();
186
+ this.listeners.set(event, listeners);
187
+ }
188
+ listeners.add(listener);
189
+ return this;
190
+ }
191
+ off(event, listener) {
192
+ this.listeners.get(event)?.delete(listener);
193
+ return this;
194
+ }
195
+ emit(event, ...args) {
196
+ const listeners = this.listeners.get(event);
197
+ if (listeners) for (const listener of listeners) listener(...args);
198
+ }
199
+ createRtc(config) {
200
+ return (this.options.rtc ?? ((c) => new RTCPeerConnection(c)))(config);
201
+ }
202
+ initConnection() {
203
+ if (this.pc) return this.pc;
204
+ this.setState("connecting");
205
+ const iceServers = this.options.iceServers ?? DEFAULT_ICE_SERVERS;
206
+ this.pc = this.createRtc({ iceServers });
207
+ this.pc.onicecandidate = (event) => {
208
+ if (event.candidate) {
209
+ this.collectedCandidates.push({
210
+ candidate: event.candidate.candidate,
211
+ sdpMid: event.candidate.sdpMid,
212
+ sdpMLineIndex: event.candidate.sdpMLineIndex
213
+ });
214
+ this.emit("signal", {
215
+ type: "candidate",
216
+ candidate: {
217
+ candidate: event.candidate.candidate,
218
+ sdpMid: event.candidate.sdpMid,
219
+ sdpMLineIndex: event.candidate.sdpMLineIndex
220
+ }
221
+ });
222
+ }
223
+ };
224
+ this.pc.onicegatheringstatechange = () => {
225
+ if (this.pc?.iceGatheringState === "complete") {
226
+ this.iceGatheringComplete = true;
227
+ this.emit("signal", { type: "ready" });
228
+ }
229
+ };
230
+ this.pc.onconnectionstatechange = () => {
231
+ switch (this.pc?.connectionState) {
232
+ case "connected":
233
+ this.setState("connected");
234
+ break;
235
+ case "disconnected":
236
+ this.setState("disconnected");
237
+ break;
238
+ case "failed":
239
+ this.setState("failed");
240
+ this.emit("error", /* @__PURE__ */ new Error("Connection failed"));
241
+ break;
242
+ case "closed": this.setState("closed");
243
+ }
244
+ };
245
+ this.pc.ondatachannel = (event) => {
246
+ this.dataChannel = event.channel;
247
+ this.setupDataChannel();
248
+ };
249
+ return this.pc;
250
+ }
251
+ setupDataChannel() {
252
+ if (!this.dataChannel) return;
253
+ this.dataChannel.binaryType = "arraybuffer";
254
+ this.dataChannel.onopen = () => this.emit("open");
255
+ this.dataChannel.onclose = () => this.emit("close");
256
+ this.dataChannel.onerror = (event) => {
257
+ const errorEvent = event;
258
+ this.emit("error", errorEvent.error ?? /* @__PURE__ */ new Error("DataChannel error"));
259
+ };
260
+ }
261
+ setState(newState) {
262
+ if (this.state !== newState) {
263
+ this.state = newState;
264
+ this.emit("stateChange", newState);
265
+ }
266
+ }
267
+ /**
268
+ * Start connection as initiator: create the data channel and offer, emit the
269
+ * offer via the `signal` event.
270
+ */
271
+ async connect() {
272
+ if (this.role !== "initiator") throw new Error("connect() should only be called by initiator");
273
+ const pc = this.initConnection();
274
+ const label = this.options.channelLabel ?? DEFAULT_CHANNEL_LABEL;
275
+ this.dataChannel = pc.createDataChannel(label, {
276
+ ordered: this.options.ordered ?? true,
277
+ maxRetransmits: this.options.maxRetransmits
278
+ });
279
+ this.setupDataChannel();
280
+ const offer = await pc.createOffer();
281
+ await pc.setLocalDescription(offer);
282
+ if (offer.sdp) this.emit("signal", {
283
+ type: "offer",
284
+ sdp: offer.sdp
285
+ });
286
+ }
287
+ /** Handle a signaling message from the remote peer. */
288
+ async handleSignal(message) {
289
+ const pc = this.initConnection();
290
+ switch (message.type) {
291
+ case "offer":
292
+ await this.handleOffer(pc, message.sdp);
293
+ break;
294
+ case "answer":
295
+ await this.handleAnswer(pc, message.sdp);
296
+ break;
297
+ case "candidate": await this.handleCandidate(pc, message.candidate);
298
+ }
299
+ }
300
+ async handleOffer(pc, sdp) {
301
+ if (this.role !== "responder") throw new Error("Received offer but not in responder role");
302
+ await pc.setRemoteDescription({
303
+ type: "offer",
304
+ sdp
305
+ });
306
+ this.remoteDescriptionSet = true;
307
+ await this.processPendingCandidates(pc);
308
+ const answer = await pc.createAnswer();
309
+ await pc.setLocalDescription(answer);
310
+ if (answer.sdp) this.emit("signal", {
311
+ type: "answer",
312
+ sdp: answer.sdp
313
+ });
314
+ }
315
+ async handleAnswer(pc, sdp) {
316
+ if (this.role !== "initiator") throw new Error("Received answer but not in initiator role");
317
+ await pc.setRemoteDescription({
318
+ type: "answer",
319
+ sdp
320
+ });
321
+ this.remoteDescriptionSet = true;
322
+ await this.processPendingCandidates(pc);
323
+ }
324
+ async handleCandidate(pc, candidate) {
325
+ const init = {
326
+ candidate: candidate.candidate,
327
+ sdpMid: candidate.sdpMid,
328
+ sdpMLineIndex: candidate.sdpMLineIndex
329
+ };
330
+ if (this.remoteDescriptionSet) await pc.addIceCandidate(init);
331
+ else this.pendingCandidates.push(init);
332
+ }
333
+ async processPendingCandidates(pc) {
334
+ for (const candidate of this.pendingCandidates) await pc.addIceCandidate(candidate);
335
+ this.pendingCandidates = [];
336
+ }
337
+ /**
338
+ * Wait for ICE gathering to complete (batch/QR signaling). Resolves early on
339
+ * timeout, using whatever candidates were collected.
340
+ */
341
+ async waitForIceGathering() {
342
+ if (this.iceGatheringComplete) return;
343
+ const timeout = this.options.iceGatheringTimeout ?? DEFAULT_ICE_GATHERING_TIMEOUT;
344
+ return new Promise((resolve) => {
345
+ const interval = setInterval(() => {
346
+ if (this.iceGatheringComplete) {
347
+ clearInterval(interval);
348
+ clearTimeout(timer);
349
+ resolve();
350
+ }
351
+ }, 20);
352
+ const timer = setTimeout(() => {
353
+ clearInterval(interval);
354
+ resolve();
355
+ }, timeout);
356
+ });
357
+ }
358
+ /** Local session description after negotiation. */
359
+ getLocalDescription() {
360
+ if (!this.pc?.localDescription) return null;
361
+ return {
362
+ type: this.pc.localDescription.type,
363
+ sdp: this.pc.localDescription.sdp
364
+ };
365
+ }
366
+ /** Collected ICE candidates (batch/QR signaling). */
367
+ getCollectedCandidates() {
368
+ return [...this.collectedCandidates];
369
+ }
370
+ /**
371
+ * Resolve with a {@link ByteChannel} once the data channel opens. Rejects on
372
+ * error or after {@link WebRtcConnectionOptions.connectionTimeout}.
373
+ */
374
+ open() {
375
+ const timeout = this.options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT;
376
+ return new Promise((resolve, reject) => {
377
+ const existing = this.dataChannel;
378
+ if (existing && existing.readyState === "open") {
379
+ resolve(byteChannelFromDataChannel(existing));
380
+ return;
381
+ }
382
+ const cleanup = () => {
383
+ this.off("open", onOpen);
384
+ this.off("error", onError);
385
+ clearTimeout(timer);
386
+ };
387
+ const onOpen = () => {
388
+ cleanup();
389
+ const ch = this.dataChannel;
390
+ if (ch) resolve(byteChannelFromDataChannel(ch));
391
+ else reject(/* @__PURE__ */ new Error("No data channel after open"));
392
+ };
393
+ const onError = (error) => {
394
+ cleanup();
395
+ reject(error);
396
+ };
397
+ this.on("open", onOpen);
398
+ this.on("error", onError);
399
+ const timer = setTimeout(() => {
400
+ cleanup();
401
+ reject(/* @__PURE__ */ new Error(`Connection timeout after ${timeout}ms`));
402
+ }, timeout);
403
+ });
404
+ }
405
+ /** Close the connection and release resources. */
406
+ close() {
407
+ if (this.dataChannel) {
408
+ this.dataChannel.close();
409
+ this.dataChannel = null;
410
+ }
411
+ if (this.pc) {
412
+ this.pc.close();
413
+ this.pc = null;
414
+ }
415
+ this.setState("closed");
416
+ this.listeners.clear();
417
+ }
418
+ };
419
+ //#endregion
420
+ //#region src/peer-manager.ts
421
+ var PeerManager = class {
422
+ signaling;
423
+ options;
424
+ connections = /* @__PURE__ */ new Map();
425
+ connectionHandlers = /* @__PURE__ */ new Set();
426
+ unsubscribe;
427
+ constructor(signaling, options = {}) {
428
+ this.signaling = signaling;
429
+ this.options = options;
430
+ this.unsubscribe = signaling.onMessage((from, msg) => this.onSignal(from, msg));
431
+ }
432
+ /** Dial `peerId` and resolve with the established channel. */
433
+ async connect(peerId) {
434
+ const pc = this.makeConnection(peerId, "initiator");
435
+ const channel = pc.open();
436
+ await pc.connect();
437
+ return channel;
438
+ }
439
+ /** Register a handler for inbound connections. Returns an unsubscribe fn. */
440
+ onConnection(handler) {
441
+ this.connectionHandlers.add(handler);
442
+ return () => this.connectionHandlers.delete(handler);
443
+ }
444
+ /** Tear down all connections and stop listening for signaling. */
445
+ close() {
446
+ this.unsubscribe();
447
+ for (const pc of this.connections.values()) pc.close();
448
+ this.connections.clear();
449
+ this.connectionHandlers.clear();
450
+ }
451
+ makeConnection(peerId, role) {
452
+ const pc = new PeerConnection(role, this.options);
453
+ pc.on("signal", (msg) => this.signaling.send(peerId, msg));
454
+ pc.on("close", () => this.connections.delete(peerId));
455
+ this.connections.set(peerId, pc);
456
+ return pc;
457
+ }
458
+ onSignal(from, msg) {
459
+ let pc = this.connections.get(from);
460
+ if (!pc) {
461
+ if (msg.type !== "offer") return;
462
+ pc = this.makeConnection(from, "responder");
463
+ pc.open().then((channel) => {
464
+ for (const handler of this.connectionHandlers) handler(from, channel);
465
+ });
466
+ }
467
+ pc.handleSignal(msg);
468
+ }
469
+ };
470
+ //#endregion
471
+ //#region src/qr-signaling.ts
472
+ /** Current protocol version */
473
+ const PROTOCOL_VERSION = 1;
474
+ /** Generate a short random session ID. */
475
+ function generateSessionId() {
476
+ const bytes = /* @__PURE__ */ new Uint8Array(6);
477
+ crypto.getRandomValues(bytes);
478
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
479
+ }
480
+ /** Compress SDP by keeping only the essential lines. */
481
+ function compressSdp(sdp) {
482
+ const lines = sdp.split("\r\n");
483
+ const essential = [];
484
+ for (const line of lines) if (line.startsWith("v=") || line.startsWith("o=") || line.startsWith("s=") || line.startsWith("t=") || line.startsWith("a=group:") || line.startsWith("a=ice-ufrag:") || line.startsWith("a=ice-pwd:") || line.startsWith("a=fingerprint:") || line.startsWith("a=setup:") || line.startsWith("m=") || line.startsWith("c=") || line.startsWith("a=mid:") || line.startsWith("a=sctp-port:") || line.startsWith("a=max-message-size:")) essential.push(line);
485
+ return essential.join("\n");
486
+ }
487
+ /** Expand compressed SDP back to a valid (CRLF) form. */
488
+ function expandSdp(compressed) {
489
+ return `${compressed.split("\n").join("\r\n")}\r\n`;
490
+ }
491
+ /** Compress an ICE candidate to its essential parts. */
492
+ function compressCandidate(candidate) {
493
+ const { candidate: c, sdpMid, sdpMLineIndex } = candidate;
494
+ const match = c.match(/candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)/);
495
+ if (!match) return `R:${sdpMid ?? ""}:${sdpMLineIndex ?? 0}:${c}`;
496
+ const [, foundation, component, protocol, priority, ip, port, type] = match;
497
+ return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${sdpMLineIndex ?? 0}`;
498
+ }
499
+ /** Expand a compressed ICE candidate. */
500
+ function expandCandidate(compressed) {
501
+ if (compressed.startsWith("R:")) {
502
+ const [, sdpMid, sdpMLineIndexStr, ...rest] = compressed.split(":");
503
+ return {
504
+ candidate: rest.join(":"),
505
+ sdpMid: sdpMid || null,
506
+ sdpMLineIndex: Number.parseInt(sdpMLineIndexStr, 10) || null
507
+ };
508
+ }
509
+ const parts = compressed.split("|");
510
+ if (parts.length < 9) throw new Error(`Invalid compressed candidate: ${compressed}`);
511
+ const [foundation, component, protocol, priority, ip, port, type, sdpMid, sdpMLineIndexStr] = parts;
512
+ return {
513
+ candidate: `candidate:${foundation} ${component} ${protocol} ${priority} ${ip} ${port} typ ${type}`,
514
+ sdpMid: sdpMid || null,
515
+ sdpMLineIndex: sdpMLineIndexStr ? Number.parseInt(sdpMLineIndexStr, 10) : null
516
+ };
517
+ }
518
+ /** Create a compressed signal for QR code exchange. */
519
+ function createCompressedSignal(sessionId, role, description, candidates) {
520
+ return {
521
+ v: PROTOCOL_VERSION,
522
+ id: sessionId,
523
+ role,
524
+ sdp: compressSdp(description.sdp),
525
+ ice: candidates.map(compressCandidate)
526
+ };
527
+ }
528
+ /** Parse a compressed signal. */
529
+ function parseCompressedSignal(signal) {
530
+ if (signal.v !== PROTOCOL_VERSION) throw new Error(`Unsupported protocol version: ${signal.v}`);
531
+ const type = signal.role === "initiator" ? "offer" : "answer";
532
+ return {
533
+ sessionId: signal.id,
534
+ role: signal.role,
535
+ description: {
536
+ type,
537
+ sdp: expandSdp(signal.sdp)
538
+ },
539
+ candidates: signal.ice.map(expandCandidate)
540
+ };
541
+ }
542
+ /** Encode a compressed signal to a URL-safe base64 string for a QR code. */
543
+ function encodeSignal(signal) {
544
+ const json = JSON.stringify(signal);
545
+ return btoa(json).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
546
+ }
547
+ /** Decode a signal string from a QR code. */
548
+ function decodeSignal(encoded) {
549
+ let base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
550
+ while (base64.length % 4) base64 += "=";
551
+ return JSON.parse(atob(base64));
552
+ }
553
+ /**
554
+ * Serverless WebRTC pairing over QR codes.
555
+ *
556
+ * Flow:
557
+ * 1. Initiator `offer()` → `{ qr, accept }`; displays `qr`.
558
+ * 2. Responder `answer(offerQr)` → `{ qr, channel }`; displays its `qr`.
559
+ * 3. Initiator `accept(answerQr)` → `channel`. Both ends now hold a working
560
+ * {@link ByteChannel}.
561
+ */
562
+ var QrSignaling = class {
563
+ sessionId;
564
+ connection;
565
+ constructor(options = {}) {
566
+ this.sessionId = options.sessionId ?? generateSessionId();
567
+ this.connection = options.connection ?? {};
568
+ }
569
+ getSessionId() {
570
+ return this.sessionId;
571
+ }
572
+ /** Create an offer QR; `accept(answerQr)` finishes the handshake. */
573
+ async offer() {
574
+ const pc = new PeerConnection("initiator", this.connection);
575
+ const channel = pc.open();
576
+ await pc.connect();
577
+ await pc.waitForIceGathering();
578
+ const description = pc.getLocalDescription();
579
+ if (!description) throw new Error("No local description after offer");
580
+ return {
581
+ qr: encodeSignal(createCompressedSignal(this.sessionId, "initiator", description, pc.getCollectedCandidates())),
582
+ accept: async (answerQr) => {
583
+ const parsed = parseCompressedSignal(decodeSignal(answerQr));
584
+ await pc.handleSignal({
585
+ type: "answer",
586
+ sdp: parsed.description.sdp
587
+ });
588
+ for (const candidate of parsed.candidates) await pc.handleSignal({
589
+ type: "candidate",
590
+ candidate
591
+ });
592
+ return channel;
593
+ }
594
+ };
595
+ }
596
+ /** Consume an offer QR and produce an answer QR + the established channel. */
597
+ async answer(offerQr) {
598
+ const parsed = parseCompressedSignal(decodeSignal(offerQr));
599
+ const pc = new PeerConnection("responder", this.connection);
600
+ const channel = pc.open();
601
+ await pc.handleSignal({
602
+ type: "offer",
603
+ sdp: parsed.description.sdp
604
+ });
605
+ for (const candidate of parsed.candidates) await pc.handleSignal({
606
+ type: "candidate",
607
+ candidate
608
+ });
609
+ await pc.waitForIceGathering();
610
+ const description = pc.getLocalDescription();
611
+ if (!description) throw new Error("No local description after answer");
612
+ return {
613
+ qr: encodeSignal(createCompressedSignal(parsed.sessionId, "responder", description, pc.getCollectedCandidates())),
614
+ channel: await channel
615
+ };
616
+ }
617
+ };
618
+ //#endregion
619
+ //#region src/room-manager.ts
620
+ var RoomManager = class {
621
+ options;
622
+ room = null;
623
+ seen = [];
624
+ live = null;
625
+ endParticipants = null;
626
+ cleanups = [];
627
+ constructor(options) {
628
+ this.options = options;
629
+ }
630
+ /** Join a room by name (token is resolved via `options.getToken`). */
631
+ async join(room) {
632
+ const token = await this.options.getToken(room);
633
+ const instance = this.options.roomFactory();
634
+ this.room = instance;
635
+ const onJoin = (...args) => {
636
+ const participant = args[0];
637
+ this.seen.push(participant.identity);
638
+ this.live?.(participant.identity);
639
+ };
640
+ instance.on(ROOM_EVENT.participantConnected, onJoin);
641
+ this.cleanups.push(() => instance.off(ROOM_EVENT.participantConnected, onJoin));
642
+ await instance.connect(this.options.url, token);
643
+ for (const [, participant] of instance.remoteParticipants) {
644
+ this.seen.push(participant.identity);
645
+ this.live?.(participant.identity);
646
+ }
647
+ }
648
+ /** Observe participant identities: those already present, then joiners. */
649
+ participants() {
650
+ return { [Symbol.asyncIterator]: () => {
651
+ const buffer = [...this.seen];
652
+ let cursor = 0;
653
+ let pending = null;
654
+ let ended = false;
655
+ this.live = (identity) => {
656
+ if (pending) {
657
+ const resolve = pending;
658
+ pending = null;
659
+ resolve({
660
+ value: identity,
661
+ done: false
662
+ });
663
+ } else buffer.push(identity);
664
+ };
665
+ this.endParticipants = () => {
666
+ ended = true;
667
+ if (pending) {
668
+ const resolve = pending;
669
+ pending = null;
670
+ resolve({
671
+ value: void 0,
672
+ done: true
673
+ });
674
+ }
675
+ };
676
+ return { next: () => {
677
+ if (cursor < buffer.length) return Promise.resolve({
678
+ value: buffer[cursor++],
679
+ done: false
680
+ });
681
+ if (ended) return Promise.resolve({
682
+ value: void 0,
683
+ done: true
684
+ });
685
+ return new Promise((resolve) => {
686
+ pending = resolve;
687
+ });
688
+ } };
689
+ } };
690
+ }
691
+ /** Open a {@link ByteChannel} to a specific participant. */
692
+ async channelTo(peerId) {
693
+ if (!this.room) throw new Error("channelTo() before join()");
694
+ return byteChannelFromRoom(this.room, peerId);
695
+ }
696
+ /** Leave the room: unsubscribe and disconnect. */
697
+ async leave() {
698
+ for (const cleanup of this.cleanups) cleanup();
699
+ this.cleanups.length = 0;
700
+ this.endParticipants?.();
701
+ this.live = null;
702
+ const room = this.room;
703
+ this.room = null;
704
+ if (room) await room.disconnect();
705
+ }
706
+ };
707
+ //#endregion
708
+ export { DEFAULT_ICE_SERVERS, PeerConnection, PeerManager, QrSignaling, ROOM_EVENT, RoomManager, byteChannelFromDataChannel, byteChannelFromRoom, createCompressedSignal, decodeSignal, encodeSignal, generateSessionId, parseCompressedSignal };