@statewalker/webrun-streams-signaling 0.1.6 → 0.3.0

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 CHANGED
@@ -71,84 +71,319 @@ const DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }, { urls: "
71
71
  const ROOM_EVENT = {
72
72
  participantConnected: "participantConnected",
73
73
  participantDisconnected: "participantDisconnected",
74
+ disconnected: "disconnected",
74
75
  dataReceived: "dataReceived"
75
76
  };
76
77
  //#endregion
77
78
  //#region src/byte-channel.ts
78
79
  /**
80
+ * ByteChannel adapters — the MessagePort→ByteChannel-style shims the relocation
81
+ * requires. The original `vcs-port-*` helpers surfaced an established
82
+ * connection as a Web `MessagePort` (via the out-of-scope `datachannel-port` /
83
+ * `livekit-port` byte bridges); here the established primitive is wrapped
84
+ * *directly* as a {@link ByteChannel} so the byte transport +
85
+ * multiplexing (`webrun-rpc`'s port stack, via `messageTargetOverByteChannel`) can run on top.
86
+ */
87
+ /**
88
+ * `whenDrained` resolves once the bytes sent and not yet written out are at
89
+ * most this: the transport can take more. The same mark the ws, peerjs,
90
+ * livekit and webrtc adapters use.
91
+ */
92
+ const DRAIN_LOW_WATER = 262144;
93
+ /**
79
94
  * Wrap an established `RTCDataChannel` as a {@link ByteChannel}. Outbound bytes
80
- * go through `channel.send`; inbound `message` events feed `recv`.
95
+ * go through `channel.send`; inbound `message` events feed `recv`. A message
96
+ * that is not bytes, or a `send` that fails (a closed channel, Chrome's full
97
+ * send queue), ends the channel: the stream above it lost a message.
98
+ * `bufferedAmount` is the data channel's; `whenDrained` waits for its
99
+ * `bufferedamountlow`.
81
100
  */
82
101
  function byteChannelFromDataChannel(channel) {
83
102
  const queue = makeByteQueue();
84
103
  let closedResolve;
104
+ let ended = false;
85
105
  const closed = new Promise((r) => {
86
106
  closedResolve = r;
87
107
  });
88
- const onMessage = (ev) => queue.push(toBytes(ev.data));
89
- const onClose = () => {
108
+ const drainWaiters = /* @__PURE__ */ new Set();
109
+ const onMessage = (ev) => {
110
+ if (ended) return;
111
+ let bytes;
112
+ try {
113
+ bytes = toBytes(ev.data);
114
+ } catch {
115
+ close();
116
+ return;
117
+ }
118
+ queue.push(bytes);
119
+ };
120
+ const onDrained = () => {
121
+ for (const w of [...drainWaiters]) w();
122
+ drainWaiters.clear();
123
+ };
124
+ const end = () => {
125
+ if (ended) return;
126
+ ended = true;
127
+ channel.removeEventListener("message", onMessage);
128
+ channel.removeEventListener("close", end);
129
+ channel.removeEventListener("bufferedamountlow", onDrained);
90
130
  queue.done();
91
131
  closedResolve();
132
+ onDrained();
133
+ };
134
+ const close = () => {
135
+ end();
136
+ try {
137
+ channel.close();
138
+ } catch {}
92
139
  };
93
140
  channel.binaryType = "arraybuffer";
141
+ channel.bufferedAmountLowThreshold = DRAIN_LOW_WATER;
94
142
  channel.addEventListener("message", onMessage);
95
- channel.addEventListener("close", onClose);
143
+ channel.addEventListener("close", end);
144
+ channel.addEventListener("bufferedamountlow", onDrained);
96
145
  return {
97
146
  send(bytes) {
147
+ if (ended) return;
98
148
  try {
99
149
  channel.send(bytes);
100
- } catch {}
150
+ } catch {
151
+ close();
152
+ }
101
153
  },
102
154
  recv: queue.recv,
103
155
  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();
156
+ close,
157
+ get bufferedAmount() {
158
+ return channel.bufferedAmount ?? 0;
159
+ },
160
+ whenDrained() {
161
+ if (ended || (channel.bufferedAmount ?? 0) <= 262144) return Promise.resolve();
162
+ return new Promise((resolve) => drainWaiters.add(resolve));
112
163
  }
113
164
  };
114
165
  }
115
166
  /**
167
+ * The topic a {@link byteChannelFromRoom} channel's packets carry, the same
168
+ * default as `webrun-streams-livekit`'s `messageTargetOverLiveKit`; packets on
169
+ * other topics are someone else's. The goodbye goes on this topic with
170
+ * `/close` appended, as there.
171
+ */
172
+ const DEFAULT_ROOM_TOPIC = "webrun/port-stack";
173
+ /**
174
+ * The largest packet a {@link byteChannelFromRoom} channel publishes, as in
175
+ * `webrun-streams-livekit`: livekit-client (2.x) refuses a larger one.
176
+ */
177
+ const DEFAULT_ROOM_MAX_FRAME_BYTES = 64e3;
178
+ /**
116
179
  * 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.
180
+ * `Room`. Outbound bytes are published reliably to `peerId` on the channel's
181
+ * topic; inbound `dataReceived` events from `peerId` on that topic feed
182
+ * `recv`. The packets and the goodbye follow `webrun-streams-livekit`'s
183
+ * conventions, so the port stack over this channel talks to one over
184
+ * `messageTargetOverLiveKit` with the same topic.
185
+ *
186
+ * The channel ends when the room disconnects, the participant leaves, the
187
+ * peer's goodbye arrives, a reliable publish fails, or a `send` exceeds
188
+ * `maxFrameBytes`. When it ends on this side, a goodbye on the close topic
189
+ * ends the peer's channel too: the room stays connected, so nothing else would.
190
+ * `bufferedAmount` counts bytes whose publish has not settled.
120
191
  */
121
- function byteChannelFromRoom(room, peerId) {
192
+ function byteChannelFromRoom(room, peerId, options = {}) {
193
+ const topic = options.topic ?? "webrun/port-stack";
194
+ const closeTopic = `${topic}/close`;
195
+ const maxFrameBytes = options.maxFrameBytes ?? 64e3;
122
196
  const queue = makeByteQueue();
123
197
  let closedResolve;
124
198
  const closed = new Promise((r) => {
125
199
  closedResolve = r;
126
200
  });
201
+ let ended = false;
202
+ let inFlight = 0;
203
+ const drainWaiters = /* @__PURE__ */ new Set();
204
+ const wakeDrainWaiters = () => {
205
+ if (inFlight > 262144 && !ended) return;
206
+ for (const w of [...drainWaiters]) w();
207
+ drainWaiters.clear();
208
+ };
127
209
  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));
210
+ const [payload, participant, , packetTopic] = args;
211
+ if (ended || participant?.identity !== peerId) return;
212
+ if (packetTopic === closeTopic) {
213
+ end(false);
214
+ return;
215
+ }
216
+ if (packetTopic !== topic || payload == null) return;
217
+ let bytes;
218
+ try {
219
+ bytes = toBytes(payload);
220
+ } catch {
221
+ end(true);
222
+ return;
223
+ }
224
+ queue.push(bytes);
225
+ };
226
+ const onParticipantDisconnected = (...args) => {
227
+ if (args[0]?.identity === peerId) end(false);
228
+ };
229
+ const onDisconnected = () => end(false);
230
+ /** `tellPeer`: it ended on this side, and the room is still there to say so. */
231
+ const end = (tellPeer) => {
232
+ if (ended) return;
233
+ ended = true;
234
+ room.off(ROOM_EVENT.dataReceived, onData);
235
+ room.off(ROOM_EVENT.participantDisconnected, onParticipantDisconnected);
236
+ room.off(ROOM_EVENT.disconnected, onDisconnected);
237
+ queue.done();
238
+ closedResolve();
239
+ wakeDrainWaiters();
240
+ if (tellPeer) room.localParticipant.publishData(/* @__PURE__ */ new Uint8Array(0), {
241
+ reliable: true,
242
+ destinationIdentities: [peerId],
243
+ topic: closeTopic
244
+ }).catch(() => void 0);
132
245
  };
133
246
  room.on(ROOM_EVENT.dataReceived, onData);
247
+ room.on(ROOM_EVENT.participantDisconnected, onParticipantDisconnected);
248
+ room.on(ROOM_EVENT.disconnected, onDisconnected);
134
249
  return {
135
250
  send(bytes) {
251
+ if (ended) return;
252
+ if (bytes.byteLength > maxFrameBytes) {
253
+ end(true);
254
+ throw new RangeError(`webrun-streams-signaling: a ${bytes.byteLength}-byte packet exceeds maxFrameBytes (${maxFrameBytes})`);
255
+ }
256
+ const size = bytes.byteLength;
257
+ inFlight += size;
136
258
  room.localParticipant.publishData(bytes, {
137
259
  reliable: true,
138
- destinationIdentities: [peerId]
139
- }).catch(() => {});
260
+ destinationIdentities: [peerId],
261
+ topic
262
+ }).then(() => void 0, () => end(true)).finally(() => {
263
+ inFlight -= size;
264
+ wakeDrainWaiters();
265
+ });
140
266
  },
141
267
  recv: queue.recv,
142
268
  closed,
143
- close() {
144
- room.off(ROOM_EVENT.dataReceived, onData);
145
- queue.done();
146
- closedResolve();
269
+ close: () => end(true),
270
+ get bufferedAmount() {
271
+ return inFlight;
272
+ },
273
+ whenDrained() {
274
+ if (ended || inFlight <= 262144) return Promise.resolve();
275
+ return new Promise((resolve) => drainWaiters.add(resolve));
276
+ }
277
+ };
278
+ }
279
+ //#endregion
280
+ //#region src/message-target.ts
281
+ /**
282
+ * The payload ceiling for a channel over an `RTCDataChannel` (`PeerManager`,
283
+ * `QrSignaling`, `PeerConnection`): 16 KiB, the message size every browser
284
+ * pair delivers, less the 256 bytes the port stack's framing needs (spec D10).
285
+ * For a `byteChannelFromRoom` channel pass `maxMessageSize: 12 * 1024`, as
286
+ * `webrun-streams-livekit` uses: an older LiveKit client dropped larger
287
+ * reliable packets silently.
288
+ */
289
+ const DEFAULT_MAX_MESSAGE_SIZE = 16128;
290
+ /**
291
+ * A `ByteChannel` this package hands back (`PeerManager`, `QrSignaling`,
292
+ * `RoomManager`) as a pipe for `webrun-rpc`'s port stack:
293
+ *
294
+ * ```ts
295
+ * const { target, signal, maxMessageSize } = messageTargetOverByteChannel(channel);
296
+ * const { call } = await connect({
297
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
298
+ * });
299
+ * ```
300
+ *
301
+ * It starts reading the channel at once, so attach listeners in the same tick;
302
+ * a message with no listener is dropped, as on a `MessagePort`. It must be the
303
+ * channel's only reader: a second reader of `recv` would take messages from it.
304
+ * Messages already received when the channel closes are still delivered.
305
+ */
306
+ function messageTargetOverByteChannel(channel, options = {}) {
307
+ const listeners = /* @__PURE__ */ new Set();
308
+ const life = new AbortController();
309
+ let closedHere = false;
310
+ const end = (reason) => {
311
+ if (!life.signal.aborted) life.abort(reason);
312
+ };
313
+ channel.closed.then(() => end(/* @__PURE__ */ new Error("webrun-streams-signaling: the channel closed")));
314
+ (async () => {
315
+ for await (const bytes of channel.recv) {
316
+ if (closedHere) break;
317
+ const event = new MessageEvent("message", { data: bytes.slice() });
318
+ for (const listener of [...listeners]) try {
319
+ Promise.resolve(listener(event)).catch(() => void 0);
320
+ } catch {}
321
+ }
322
+ end(/* @__PURE__ */ new Error("webrun-streams-signaling: the channel closed"));
323
+ })().catch((err) => end(err instanceof Error ? err : new Error(String(err), { cause: err })));
324
+ return {
325
+ signal: life.signal,
326
+ maxMessageSize: options.maxMessageSize ?? 16128,
327
+ target: {
328
+ addEventListener: (_type, listener) => {
329
+ listeners.add(listener);
330
+ },
331
+ removeEventListener: (_type, listener) => {
332
+ listeners.delete(listener);
333
+ },
334
+ postMessage(message) {
335
+ const bytes = message instanceof Uint8Array ? message : message instanceof ArrayBuffer ? new Uint8Array(message) : ArrayBuffer.isView(message) ? new Uint8Array(message.buffer, message.byteOffset, message.byteLength) : void 0;
336
+ if (!bytes) throw new TypeError(`webrun-streams-signaling: a byte pipe carries Uint8Array, ArrayBuffer or a view, got ${Object.prototype.toString.call(message)}`);
337
+ if (life.signal.aborted) return;
338
+ channel.send(bytes.slice());
339
+ },
340
+ async close() {
341
+ listeners.clear();
342
+ closedHere = true;
343
+ end(/* @__PURE__ */ new Error("webrun-streams-signaling: closed locally"));
344
+ try {
345
+ channel.close();
346
+ } catch {}
347
+ },
348
+ get bufferedAmount() {
349
+ return channel.bufferedAmount ?? 0;
350
+ },
351
+ whenDrained() {
352
+ if (life.signal.aborted || !channel.whenDrained) return Promise.resolve();
353
+ const signal = life.signal;
354
+ return new Promise((resolve, reject) => {
355
+ const done = () => {
356
+ signal.removeEventListener("abort", done);
357
+ resolve();
358
+ };
359
+ signal.addEventListener("abort", done);
360
+ channel.whenDrained?.().then(done, (err) => {
361
+ signal.removeEventListener("abort", done);
362
+ reject(err);
363
+ });
364
+ });
365
+ }
147
366
  }
148
367
  };
149
368
  }
150
369
  //#endregion
151
370
  //#region src/peer-connection.ts
371
+ /**
372
+ * WebRTC peer connection lifecycle (single connection).
373
+ *
374
+ * Relocated from `@statewalker/vcs-port-webrtc`'s `PeerManager` and neutralised
375
+ * (no Git/VCS coupling). Handles signaling, ICE candidate gathering and data
376
+ * channel creation for one peer, in either "initiator" (creates offer) or
377
+ * "responder" (creates answer) role.
378
+ *
379
+ * Adaptations vs. the original:
380
+ * - `new RTCPeerConnection(...)` is behind an injectable {@link RtcPeerConnectionFactory}
381
+ * so tests run without a real WebRTC stack.
382
+ * - remote ICE candidates are added as plain `RTCIceCandidateInit` (accepted by
383
+ * `addIceCandidate`) instead of constructing a global `RTCIceCandidate`,
384
+ * which does not exist outside a browser.
385
+ * - `open()` yields a {@link ByteChannel} rather than a `MessagePort`.
386
+ */
152
387
  const DEFAULT_CONNECTION_TIMEOUT = 3e4;
153
388
  const DEFAULT_ICE_GATHERING_TIMEOUT = 5e3;
154
389
  const DEFAULT_CHANNEL_LABEL = "webrun-data";
@@ -176,6 +411,10 @@ var PeerConnection = class {
176
411
  getRole() {
177
412
  return this.role;
178
413
  }
414
+ /** Whether the remote description (the peer's offer or answer) has been applied. */
415
+ hasRemoteDescription() {
416
+ return this.remoteDescriptionSet;
417
+ }
179
418
  getDataChannel() {
180
419
  return this.dataChannel;
181
420
  }
@@ -382,6 +621,7 @@ var PeerConnection = class {
382
621
  const cleanup = () => {
383
622
  this.off("open", onOpen);
384
623
  this.off("error", onError);
624
+ this.off("stateChange", onState);
385
625
  clearTimeout(timer);
386
626
  };
387
627
  const onOpen = () => {
@@ -394,8 +634,14 @@ var PeerConnection = class {
394
634
  cleanup();
395
635
  reject(error);
396
636
  };
637
+ const onState = (state) => {
638
+ if (state !== "closed") return;
639
+ cleanup();
640
+ reject(/* @__PURE__ */ new Error("Connection closed before the data channel opened"));
641
+ };
397
642
  this.on("open", onOpen);
398
643
  this.on("error", onError);
644
+ this.on("stateChange", onState);
399
645
  const timer = setTimeout(() => {
400
646
  cleanup();
401
647
  reject(/* @__PURE__ */ new Error(`Connection timeout after ${timeout}ms`));
@@ -418,6 +664,16 @@ var PeerConnection = class {
418
664
  };
419
665
  //#endregion
420
666
  //#region src/peer-manager.ts
667
+ /**
668
+ * Peer discovery + connection manager over a {@link SignalingTransport}.
669
+ *
670
+ * Wraps the low-level {@link PeerConnection} (relocated from
671
+ * `@statewalker/vcs-port-webrtc`) with a multi-peer, id-keyed surface: dial a
672
+ * peer with `connect(peerId)` or accept inbound dials via `onConnection`. Each
673
+ * established connection yields a {@link ByteChannel}. The WebRTC
674
+ * offer/answer/ICE routing is the original logic; only the routing-by-peer-id
675
+ * and the ByteChannel result are new.
676
+ */
421
677
  var PeerManager = class {
422
678
  signaling;
423
679
  options;
@@ -431,10 +687,18 @@ var PeerManager = class {
431
687
  }
432
688
  /** Dial `peerId` and resolve with the established channel. */
433
689
  async connect(peerId) {
690
+ const previous = this.connections.get(peerId);
691
+ if (previous) this.forget(peerId, previous);
434
692
  const pc = this.makeConnection(peerId, "initiator");
435
693
  const channel = pc.open();
436
- await pc.connect();
437
- return channel;
694
+ try {
695
+ await pc.connect();
696
+ return await channel;
697
+ } catch (err) {
698
+ channel.catch(() => void 0);
699
+ this.forget(peerId, pc);
700
+ throw err;
701
+ }
438
702
  }
439
703
  /** Register a handler for inbound connections. Returns an unsubscribe fn. */
440
704
  onConnection(handler) {
@@ -444,31 +708,68 @@ var PeerManager = class {
444
708
  /** Tear down all connections and stop listening for signaling. */
445
709
  close() {
446
710
  this.unsubscribe();
447
- for (const pc of this.connections.values()) pc.close();
711
+ const all = [...this.connections.values()];
448
712
  this.connections.clear();
713
+ for (const pc of all) pc.close();
449
714
  this.connectionHandlers.clear();
450
715
  }
451
716
  makeConnection(peerId, role) {
452
717
  const pc = new PeerConnection(role, this.options);
453
718
  pc.on("signal", (msg) => this.signaling.send(peerId, msg));
454
- pc.on("close", () => this.connections.delete(peerId));
719
+ pc.on("close", () => this.forget(peerId, pc));
720
+ pc.on("stateChange", (state) => {
721
+ if (state === "failed" || state === "closed") this.forget(peerId, pc);
722
+ });
455
723
  this.connections.set(peerId, pc);
456
724
  return pc;
457
725
  }
726
+ /** Close `pc` and drop it, unless a newer connection to `peerId` replaced it. */
727
+ forget(peerId, pc) {
728
+ if (this.connections.get(peerId) !== pc) return;
729
+ this.connections.delete(peerId);
730
+ pc.close();
731
+ }
732
+ fail(peerId, pc, err) {
733
+ const live = this.connections.get(peerId) === pc;
734
+ this.forget(peerId, pc);
735
+ if (!live) return;
736
+ const error = err instanceof Error ? err : new Error(String(err), { cause: err });
737
+ try {
738
+ this.options.onError?.(error, peerId);
739
+ } catch {}
740
+ }
458
741
  onSignal(from, msg) {
459
742
  let pc = this.connections.get(from);
743
+ if (pc && msg.type === "offer" && (pc.getRole() === "responder" || pc.hasRemoteDescription())) {
744
+ this.forget(from, pc);
745
+ pc = void 0;
746
+ }
460
747
  if (!pc) {
461
748
  if (msg.type !== "offer") return;
462
- pc = this.makeConnection(from, "responder");
463
- pc.open().then((channel) => {
749
+ const responder = this.makeConnection(from, "responder");
750
+ pc = responder;
751
+ responder.open().then((channel) => {
464
752
  for (const handler of this.connectionHandlers) handler(from, channel);
465
- });
753
+ }, (err) => this.fail(from, responder, err));
466
754
  }
467
- pc.handleSignal(msg);
755
+ const target = pc;
756
+ target.handleSignal(msg).catch((err) => this.fail(from, target, err));
468
757
  }
469
758
  };
470
759
  //#endregion
471
760
  //#region src/qr-signaling.ts
761
+ /**
762
+ * QR code signaling for serverless WebRTC connection.
763
+ *
764
+ * Relocated from `@statewalker/vcs-port-webrtc`'s `signaling.ts` (neutralised).
765
+ * Compresses WebRTC signaling data (SDP + ICE candidates) into a compact,
766
+ * base64 form suitable for QR codes, enabling out-of-band manual pairing where
767
+ * peers exchange QR strings instead of using a live signaling server.
768
+ *
769
+ * The compress/expand/encode/decode functions are pure and unchanged; the
770
+ * {@link QrSignaling} class is adapted to the target API and yields
771
+ * {@link ByteChannel}s.
772
+ */
472
773
  /** Current protocol version */
473
774
  const PROTOCOL_VERSION = 1;
474
775
  /** Generate a short random session ID. */
@@ -488,13 +789,44 @@ function compressSdp(sdp) {
488
789
  function expandSdp(compressed) {
489
790
  return `${compressed.split("\n").join("\r\n")}\r\n`;
490
791
  }
491
- /** Compress an ICE candidate to its essential parts. */
792
+ /**
793
+ * Candidate attributes after `typ` that a connection needs: the related
794
+ * address of a srflx/relay candidate and the TCP type of a TCP one. Others
795
+ * (`generation`, `ufrag`, `network-id`, ...) are dropped to keep the QR small.
796
+ */
797
+ const KEPT_CANDIDATE_ATTRIBUTES = /* @__PURE__ */ new Set([
798
+ "raddr",
799
+ "rport",
800
+ "tcptype"
801
+ ]);
802
+ /** An `sdpMLineIndex` as it travels: empty for null. */
803
+ function indexToString(index) {
804
+ return index == null ? "" : String(index);
805
+ }
806
+ function indexFromString(text) {
807
+ if (!text) return null;
808
+ const index = Number.parseInt(text, 10);
809
+ return Number.isNaN(index) ? null : index;
810
+ }
811
+ /**
812
+ * Compress an ICE candidate to its essential parts. A candidate that carries
813
+ * attributes a connection needs (see {@link KEPT_CANDIDATE_ATTRIBUTES}) goes
814
+ * in the raw (`R:`) form, with only those attributes kept.
815
+ */
492
816
  function compressCandidate(candidate) {
493
817
  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}`;
818
+ const index = indexToString(sdpMLineIndex);
819
+ const match = c.match(/candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)(.*)$/);
820
+ if (!match) return `R:${sdpMid ?? ""}:${index}:${c}`;
821
+ const [base, foundation, component, protocol, priority, ip, port, type, rest] = match;
822
+ const words = rest.trim().split(/\s+/).filter(Boolean);
823
+ const kept = [];
824
+ for (let i = 0; i + 1 < words.length; i += 2) if (KEPT_CANDIDATE_ATTRIBUTES.has(words[i])) kept.push(words[i], words[i + 1]);
825
+ if (kept.length) {
826
+ const head = base.slice(0, base.length - rest.length);
827
+ return `R:${sdpMid ?? ""}:${index}:${head} ${kept.join(" ")}`;
828
+ }
829
+ return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${index}`;
498
830
  }
499
831
  /** Expand a compressed ICE candidate. */
500
832
  function expandCandidate(compressed) {
@@ -503,7 +835,7 @@ function expandCandidate(compressed) {
503
835
  return {
504
836
  candidate: rest.join(":"),
505
837
  sdpMid: sdpMid || null,
506
- sdpMLineIndex: Number.parseInt(sdpMLineIndexStr, 10) || null
838
+ sdpMLineIndex: indexFromString(sdpMLineIndexStr)
507
839
  };
508
840
  }
509
841
  const parts = compressed.split("|");
@@ -512,7 +844,7 @@ function expandCandidate(compressed) {
512
844
  return {
513
845
  candidate: `candidate:${foundation} ${component} ${protocol} ${priority} ${ip} ${port} typ ${type}`,
514
846
  sdpMid: sdpMid || null,
515
- sdpMLineIndex: sdpMLineIndexStr ? Number.parseInt(sdpMLineIndexStr, 10) : null
847
+ sdpMLineIndex: indexFromString(sdpMLineIndexStr)
516
848
  };
517
849
  }
518
850
  /** Create a compressed signal for QR code exchange. */
@@ -572,7 +904,6 @@ var QrSignaling = class {
572
904
  /** Create an offer QR; `accept(answerQr)` finishes the handshake. */
573
905
  async offer() {
574
906
  const pc = new PeerConnection("initiator", this.connection);
575
- const channel = pc.open();
576
907
  await pc.connect();
577
908
  await pc.waitForIceGathering();
578
909
  const description = pc.getLocalDescription();
@@ -580,15 +911,22 @@ var QrSignaling = class {
580
911
  return {
581
912
  qr: encodeSignal(createCompressedSignal(this.sessionId, "initiator", description, pc.getCollectedCandidates())),
582
913
  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
- });
914
+ const channel = pc.open();
915
+ try {
916
+ const parsed = parseCompressedSignal(decodeSignal(answerQr));
917
+ await pc.handleSignal({
918
+ type: "answer",
919
+ sdp: parsed.description.sdp
920
+ });
921
+ for (const candidate of parsed.candidates) await pc.handleSignal({
922
+ type: "candidate",
923
+ candidate
924
+ });
925
+ } catch (err) {
926
+ channel.catch(() => void 0);
927
+ pc.close();
928
+ throw err;
929
+ }
592
930
  return channel;
593
931
  }
594
932
  };
@@ -617,6 +955,18 @@ var QrSignaling = class {
617
955
  };
618
956
  //#endregion
619
957
  //#region src/room-manager.ts
958
+ /**
959
+ * Room membership manager over a LiveKit-style `Room`.
960
+ *
961
+ * Relocated from `@statewalker/vcs-port-livekit`'s `RoomManager` and adapted to
962
+ * the target API: `join`/`participants`/`channelTo`/`leave`. Participant
963
+ * tracking is the original event-wiring; `channelTo` yields a per-participant
964
+ * {@link ByteChannel} (see {@link byteChannelFromRoom}).
965
+ *
966
+ * The vendor (`livekit-client`) stays an optional peerDependency: the `Room` is
967
+ * injected via {@link RoomManagerOptions.roomFactory} (production:
968
+ * `() => new Room()`), so this module never hard-imports it.
969
+ */
620
970
  var RoomManager = class {
621
971
  options;
622
972
  room = null;
@@ -688,10 +1038,10 @@ var RoomManager = class {
688
1038
  } };
689
1039
  } };
690
1040
  }
691
- /** Open a {@link ByteChannel} to a specific participant. */
692
- async channelTo(peerId) {
1041
+ /** Open a {@link ByteChannel} to a specific participant (see {@link byteChannelFromRoom}). */
1042
+ async channelTo(peerId, options) {
693
1043
  if (!this.room) throw new Error("channelTo() before join()");
694
- return byteChannelFromRoom(this.room, peerId);
1044
+ return byteChannelFromRoom(this.room, peerId, options);
695
1045
  }
696
1046
  /** Leave the room: unsubscribe and disconnect. */
697
1047
  async leave() {
@@ -705,4 +1055,4 @@ var RoomManager = class {
705
1055
  }
706
1056
  };
707
1057
  //#endregion
708
- export { DEFAULT_ICE_SERVERS, PeerConnection, PeerManager, QrSignaling, ROOM_EVENT, RoomManager, byteChannelFromDataChannel, byteChannelFromRoom, createCompressedSignal, decodeSignal, encodeSignal, generateSessionId, parseCompressedSignal };
1058
+ export { DEFAULT_ICE_SERVERS, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_ROOM_MAX_FRAME_BYTES, DEFAULT_ROOM_TOPIC, DRAIN_LOW_WATER, PeerConnection, PeerManager, QrSignaling, ROOM_EVENT, RoomManager, byteChannelFromDataChannel, byteChannelFromRoom, createCompressedSignal, decodeSignal, encodeSignal, generateSessionId, messageTargetOverByteChannel, parseCompressedSignal };
@@ -0,0 +1,55 @@
1
+ import type { ByteChannel } from "./types.js";
2
+ type Listener = (event: MessageEvent) => void | Promise<void>;
3
+ /**
4
+ * The payload ceiling for a channel over an `RTCDataChannel` (`PeerManager`,
5
+ * `QrSignaling`, `PeerConnection`): 16 KiB, the message size every browser
6
+ * pair delivers, less the 256 bytes the port stack's framing needs (spec D10).
7
+ * For a `byteChannelFromRoom` channel pass `maxMessageSize: 12 * 1024`, as
8
+ * `webrun-streams-livekit` uses: an older LiveKit client dropped larger
9
+ * reliable packets silently.
10
+ */
11
+ export declare const DEFAULT_MAX_MESSAGE_SIZE: number;
12
+ /** What `messageTargetOverByteChannel` gives: a pipe of bytes, its life, and its payload ceiling. */
13
+ export interface ByteChannelMessageTarget {
14
+ /** A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) of bytes, one channel message each. */
15
+ target: {
16
+ addEventListener(type: "message", listener: Listener): void;
17
+ removeEventListener(type: "message", listener: Listener): void;
18
+ /** Sends one message; `TypeError` for anything but bytes. */
19
+ postMessage(message: unknown): void;
20
+ /** Closes the channel. */
21
+ close(): Promise<void>;
22
+ /** The channel's `bufferedAmount`; 0 where it cannot tell. */
23
+ readonly bufferedAmount: number;
24
+ /**
25
+ * The channel's `whenDrained`: resolves once it can take more, or the pipe
26
+ * ended. Resolves at once over a channel without one.
27
+ */
28
+ whenDrained(): Promise<void>;
29
+ };
30
+ /** Aborts when the channel closes. Pass it as `overPipe`'s `signal`. */
31
+ signal: AbortSignal;
32
+ /** Pass as `overPipe`'s `maxMessageSize`. */
33
+ maxMessageSize: number;
34
+ }
35
+ /**
36
+ * A `ByteChannel` this package hands back (`PeerManager`, `QrSignaling`,
37
+ * `RoomManager`) as a pipe for `webrun-rpc`'s port stack:
38
+ *
39
+ * ```ts
40
+ * const { target, signal, maxMessageSize } = messageTargetOverByteChannel(channel);
41
+ * const { call } = await connect({
42
+ * mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
43
+ * });
44
+ * ```
45
+ *
46
+ * It starts reading the channel at once, so attach listeners in the same tick;
47
+ * a message with no listener is dropped, as on a `MessagePort`. It must be the
48
+ * channel's only reader: a second reader of `recv` would take messages from it.
49
+ * Messages already received when the channel closes are still delivered.
50
+ */
51
+ export declare function messageTargetOverByteChannel(channel: ByteChannel, options?: {
52
+ maxMessageSize?: number;
53
+ }): ByteChannelMessageTarget;
54
+ export {};
55
+ //# sourceMappingURL=message-target.d.ts.map