@statewalker/webrun-streams-signaling 0.2.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-signaling",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Generic P2P signaling/connection-setup (PeerManager, QrSignaling, RoomManager) yielding ByteChannels",
@@ -45,9 +45,10 @@
45
45
  "rolldown": "^1.2.12",
46
46
  "typescript": "^7.0.2",
47
47
  "vitest": "^5.0.5",
48
- "@statewalker/webrun-msgpack": "^0.10.0",
49
- "@statewalker/webrun-streams": "^0.3.0",
50
- "@statewalker/webrun-rpc": "^0.11.0"
48
+ "@statewalker/webrun-msgpack": "^0.11.0",
49
+ "@statewalker/webrun-streams": "^0.4.0",
50
+ "@statewalker/webrun-rpc": "^0.12.0",
51
+ "@statewalker/webrun-streams-conformance": "^0.5.0"
51
52
  },
52
53
  "sideEffects": false,
53
54
  "publishConfig": {
@@ -57,6 +58,8 @@
57
58
  "scripts": {
58
59
  "build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
59
60
  "test": "vitest run",
61
+ "typecheck": "tsc --noEmit",
62
+ "typecheck:tests": "tsc -p tsconfig.tests.json",
60
63
  "lint": "biome check src tests"
61
64
  }
62
65
  }
@@ -11,103 +11,242 @@ import { makeByteQueue, toBytes } from "./byte-queue.js";
11
11
  import type { ByteChannel, RoomLike } from "./types.js";
12
12
  import { ROOM_EVENT } from "./types.js";
13
13
 
14
+ /**
15
+ * `whenDrained` resolves once the bytes sent and not yet written out are at
16
+ * most this: the transport can take more. The same mark the ws, peerjs,
17
+ * livekit and webrtc adapters use.
18
+ */
19
+ export const DRAIN_LOW_WATER = 256 * 1024;
20
+
14
21
  /**
15
22
  * Wrap an established `RTCDataChannel` as a {@link ByteChannel}. Outbound bytes
16
- * go through `channel.send`; inbound `message` events feed `recv`.
23
+ * go through `channel.send`; inbound `message` events feed `recv`. A message
24
+ * that is not bytes, or a `send` that fails (a closed channel, Chrome's full
25
+ * send queue), ends the channel: the stream above it lost a message.
26
+ * `bufferedAmount` is the data channel's; `whenDrained` waits for its
27
+ * `bufferedamountlow`.
17
28
  */
18
29
  export function byteChannelFromDataChannel(channel: RTCDataChannel): ByteChannel {
19
30
  const queue = makeByteQueue();
20
31
  let closedResolve!: () => void;
32
+ let ended = false;
21
33
  const closed = new Promise<void>((r) => {
22
34
  closedResolve = r;
23
35
  });
36
+ const drainWaiters = new Set<() => void>();
24
37
 
25
- const onMessage = (ev: MessageEvent): void => queue.push(toBytes(ev.data));
26
- const onClose = (): void => {
38
+ const onMessage = (ev: MessageEvent): void => {
39
+ if (ended) return;
40
+ let bytes: Uint8Array;
41
+ try {
42
+ bytes = toBytes(ev.data);
43
+ } catch {
44
+ close();
45
+ return;
46
+ }
47
+ queue.push(bytes);
48
+ };
49
+ const onDrained = (): void => {
50
+ for (const w of [...drainWaiters]) w();
51
+ drainWaiters.clear();
52
+ };
53
+ const end = (): void => {
54
+ if (ended) return;
55
+ ended = true;
56
+ channel.removeEventListener("message", onMessage as EventListener);
57
+ channel.removeEventListener("close", end);
58
+ channel.removeEventListener("bufferedamountlow", onDrained);
27
59
  queue.done();
28
60
  closedResolve();
61
+ onDrained();
62
+ };
63
+ const close = (): void => {
64
+ end();
65
+ try {
66
+ channel.close();
67
+ } catch {
68
+ /* ignore */
69
+ }
29
70
  };
30
71
 
31
72
  channel.binaryType = "arraybuffer";
73
+ channel.bufferedAmountLowThreshold = DRAIN_LOW_WATER;
32
74
  channel.addEventListener("message", onMessage as EventListener);
33
- channel.addEventListener("close", onClose as EventListener);
75
+ channel.addEventListener("close", end);
76
+ channel.addEventListener("bufferedamountlow", onDrained);
34
77
 
35
78
  return {
36
79
  send(bytes) {
80
+ if (ended) return;
37
81
  try {
38
82
  // Cast around the DOM lib's `ArrayBufferView<ArrayBuffer>` overload:
39
83
  // a plain `Uint8Array` is `ArrayBufferLike`-backed at the type level.
40
84
  channel.send(bytes as unknown as ArrayBufferView<ArrayBuffer>);
41
85
  } catch {
42
- /* channel closed by peer */
86
+ close();
43
87
  }
44
88
  },
45
89
  recv: queue.recv,
46
90
  closed,
47
- close() {
48
- channel.removeEventListener("message", onMessage as EventListener);
49
- channel.removeEventListener("close", onClose as EventListener);
50
- try {
51
- channel.close();
52
- } catch {
53
- /* ignore */
54
- }
55
- queue.done();
56
- closedResolve();
91
+ close,
92
+ get bufferedAmount() {
93
+ return channel.bufferedAmount ?? 0;
94
+ },
95
+ whenDrained() {
96
+ if (ended || (channel.bufferedAmount ?? 0) <= DRAIN_LOW_WATER) return Promise.resolve();
97
+ return new Promise<void>((resolve) => drainWaiters.add(resolve));
57
98
  },
58
99
  };
59
100
  }
60
101
 
102
+ /**
103
+ * The topic a {@link byteChannelFromRoom} channel's packets carry, the same
104
+ * default as `webrun-streams-livekit`'s `messageTargetOverLiveKit`; packets on
105
+ * other topics are someone else's. The goodbye goes on this topic with
106
+ * `/close` appended, as there.
107
+ */
108
+ export const DEFAULT_ROOM_TOPIC = "webrun/port-stack";
109
+
110
+ /**
111
+ * The largest packet a {@link byteChannelFromRoom} channel publishes, as in
112
+ * `webrun-streams-livekit`: livekit-client (2.x) refuses a larger one.
113
+ */
114
+ export const DEFAULT_ROOM_MAX_FRAME_BYTES = 64_000;
115
+
116
+ /** Options for {@link byteChannelFromRoom}. */
117
+ export interface ByteChannelFromRoomOptions {
118
+ /**
119
+ * The data topic, default {@link DEFAULT_ROOM_TOPIC}; the goodbye uses it
120
+ * with `/close` appended. Both ends must agree. Use another to run two
121
+ * channels to the same participant.
122
+ */
123
+ topic?: string;
124
+ /** The largest packet sent; past it `send` ends the channel and throws `RangeError`. Default {@link DEFAULT_ROOM_MAX_FRAME_BYTES}. */
125
+ maxFrameBytes?: number;
126
+ }
127
+
61
128
  /**
62
129
  * Build a {@link ByteChannel} to a single room participant over a LiveKit-style
63
- * `Room`. Outbound bytes are published to `peerId`; inbound `dataReceived`
64
- * events from `peerId` feed `recv`. This is the per-participant filtering the
65
- * retired `vcs-port-livekit` `livekit-port` performed, adapted to ByteChannel.
130
+ * `Room`. Outbound bytes are published reliably to `peerId` on the channel's
131
+ * topic; inbound `dataReceived` events from `peerId` on that topic feed
132
+ * `recv`. The packets and the goodbye follow `webrun-streams-livekit`'s
133
+ * conventions, so the port stack over this channel talks to one over
134
+ * `messageTargetOverLiveKit` with the same topic.
135
+ *
136
+ * The channel ends when the room disconnects, the participant leaves, the
137
+ * peer's goodbye arrives, a reliable publish fails, or a `send` exceeds
138
+ * `maxFrameBytes`. When it ends on this side, a goodbye on the close topic
139
+ * ends the peer's channel too: the room stays connected, so nothing else would.
140
+ * `bufferedAmount` counts bytes whose publish has not settled.
66
141
  */
67
- export function byteChannelFromRoom(room: RoomLike, peerId: string): ByteChannel {
142
+ export function byteChannelFromRoom(
143
+ room: RoomLike,
144
+ peerId: string,
145
+ options: ByteChannelFromRoomOptions = {},
146
+ ): ByteChannel {
147
+ const topic = options.topic ?? DEFAULT_ROOM_TOPIC;
148
+ const closeTopic = `${topic}/close`;
149
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_ROOM_MAX_FRAME_BYTES;
68
150
  const queue = makeByteQueue();
69
151
  let closedResolve!: () => void;
70
152
  const closed = new Promise<void>((r) => {
71
153
  closedResolve = r;
72
154
  });
73
155
  let ended = false;
156
+ let inFlight = 0;
157
+ const drainWaiters = new Set<() => void>();
158
+ const wakeDrainWaiters = (): void => {
159
+ if (inFlight > DRAIN_LOW_WATER && !ended) return;
160
+ for (const w of [...drainWaiters]) w();
161
+ drainWaiters.clear();
162
+ };
74
163
 
75
164
  const onData = (...args: unknown[]): void => {
76
- const payload = args[0];
77
- const participant = args[1] as { identity?: string } | undefined;
165
+ const [payload, participant, , packetTopic] = args as [
166
+ unknown,
167
+ { identity?: string } | undefined,
168
+ unknown,
169
+ string | undefined,
170
+ ];
78
171
  // A packet with no participant is the server's, not the peer's.
79
- if (participant?.identity !== peerId) return;
80
- if (payload != null) queue.push(toBytes(payload));
172
+ if (ended || participant?.identity !== peerId) return;
173
+ if (packetTopic === closeTopic) {
174
+ end(false);
175
+ return;
176
+ }
177
+ if (packetTopic !== topic || payload == null) return;
178
+ let bytes: Uint8Array;
179
+ try {
180
+ bytes = toBytes(payload);
181
+ } catch {
182
+ end(true);
183
+ return;
184
+ }
185
+ queue.push(bytes);
81
186
  };
82
187
  const onParticipantDisconnected = (...args: unknown[]): void => {
83
- if ((args[0] as { identity?: string } | undefined)?.identity === peerId) end();
188
+ if ((args[0] as { identity?: string } | undefined)?.identity === peerId) end(false);
84
189
  };
85
- // The channel ends with the room or with the peer: otherwise nothing above
86
- // it would ever learn the other end is gone.
87
- const end = (): void => {
190
+ const onDisconnected = (): void => end(false);
191
+ // The channel ends with the room, with the peer, or with the peer's
192
+ // goodbye: otherwise nothing above it would ever learn the other end is gone.
193
+ /** `tellPeer`: it ended on this side, and the room is still there to say so. */
194
+ const end = (tellPeer: boolean): void => {
88
195
  if (ended) return;
89
196
  ended = true;
90
197
  room.off(ROOM_EVENT.dataReceived, onData);
91
198
  room.off(ROOM_EVENT.participantDisconnected, onParticipantDisconnected);
92
- room.off(ROOM_EVENT.disconnected, end);
199
+ room.off(ROOM_EVENT.disconnected, onDisconnected);
93
200
  queue.done();
94
201
  closedResolve();
202
+ wakeDrainWaiters();
203
+ if (tellPeer) {
204
+ room.localParticipant
205
+ .publishData(new Uint8Array(0), {
206
+ reliable: true,
207
+ destinationIdentities: [peerId],
208
+ topic: closeTopic,
209
+ })
210
+ .catch(() => undefined);
211
+ }
95
212
  };
96
213
 
97
214
  room.on(ROOM_EVENT.dataReceived, onData);
98
215
  room.on(ROOM_EVENT.participantDisconnected, onParticipantDisconnected);
99
- room.on(ROOM_EVENT.disconnected, end);
216
+ room.on(ROOM_EVENT.disconnected, onDisconnected);
100
217
 
101
218
  return {
102
219
  send(bytes) {
103
220
  if (ended) return;
104
- void room.localParticipant
105
- .publishData(bytes, { reliable: true, destinationIdentities: [peerId] })
221
+ if (bytes.byteLength > maxFrameBytes) {
222
+ end(true);
223
+ throw new RangeError(
224
+ `webrun-streams-signaling: a ${bytes.byteLength}-byte packet exceeds maxFrameBytes (${maxFrameBytes})`,
225
+ );
226
+ }
227
+ const size = bytes.byteLength;
228
+ inFlight += size;
229
+ room.localParticipant
230
+ .publishData(bytes, { reliable: true, destinationIdentities: [peerId], topic })
106
231
  // A reliable publish that fails lost a message: the stream above is broken.
107
- .catch(end);
232
+ .then(
233
+ () => undefined,
234
+ () => end(true),
235
+ )
236
+ .finally(() => {
237
+ inFlight -= size;
238
+ wakeDrainWaiters();
239
+ });
108
240
  },
109
241
  recv: queue.recv,
110
242
  closed,
111
- close: end,
243
+ close: () => end(true),
244
+ get bufferedAmount() {
245
+ return inFlight;
246
+ },
247
+ whenDrained() {
248
+ if (ended || inFlight <= DRAIN_LOW_WATER) return Promise.resolve();
249
+ return new Promise<void>((resolve) => drainWaiters.add(resolve));
250
+ },
112
251
  };
113
252
  }
package/src/index.ts CHANGED
@@ -14,7 +14,14 @@
14
14
  * @packageDocumentation
15
15
  */
16
16
 
17
- export { byteChannelFromDataChannel, byteChannelFromRoom } from "./byte-channel.js";
17
+ export {
18
+ type ByteChannelFromRoomOptions,
19
+ byteChannelFromDataChannel,
20
+ byteChannelFromRoom,
21
+ DEFAULT_ROOM_MAX_FRAME_BYTES,
22
+ DEFAULT_ROOM_TOPIC,
23
+ DRAIN_LOW_WATER,
24
+ } from "./byte-channel.js";
18
25
  export * from "./message-target.js";
19
26
  export { PeerConnection } from "./peer-connection.js";
20
27
  export { PeerManager, type PeerManagerOptions } from "./peer-manager.js";
@@ -22,6 +22,13 @@ export interface ByteChannelMessageTarget {
22
22
  postMessage(message: unknown): void;
23
23
  /** Closes the channel. */
24
24
  close(): Promise<void>;
25
+ /** The channel's `bufferedAmount`; 0 where it cannot tell. */
26
+ readonly bufferedAmount: number;
27
+ /**
28
+ * The channel's `whenDrained`: resolves once it can take more, or the pipe
29
+ * ended. Resolves at once over a channel without one.
30
+ */
31
+ whenDrained(): Promise<void>;
25
32
  };
26
33
  /** Aborts when the channel closes. Pass it as `overPipe`'s `signal`. */
27
34
  signal: AbortSignal;
@@ -107,6 +114,24 @@ export function messageTargetOverByteChannel(
107
114
  channel.close();
108
115
  } catch {}
109
116
  },
117
+ get bufferedAmount() {
118
+ return channel.bufferedAmount ?? 0;
119
+ },
120
+ whenDrained() {
121
+ if (life.signal.aborted || !channel.whenDrained) return Promise.resolve();
122
+ const signal = life.signal;
123
+ return new Promise<void>((resolve, reject) => {
124
+ const done = (): void => {
125
+ signal.removeEventListener("abort", done);
126
+ resolve();
127
+ };
128
+ signal.addEventListener("abort", done);
129
+ channel.whenDrained?.().then(done, (err: unknown) => {
130
+ signal.removeEventListener("abort", done);
131
+ reject(err);
132
+ });
133
+ });
134
+ },
110
135
  },
111
136
  };
112
137
  }
@@ -68,6 +68,11 @@ export class PeerConnection {
68
68
  return this.role;
69
69
  }
70
70
 
71
+ /** Whether the remote description (the peer's offer or answer) has been applied. */
72
+ hasRemoteDescription(): boolean {
73
+ return this.remoteDescriptionSet;
74
+ }
75
+
71
76
  getDataChannel(): RTCDataChannel | null {
72
77
  return this.dataChannel;
73
78
  }
@@ -318,6 +323,7 @@ export class PeerConnection {
318
323
  const cleanup = () => {
319
324
  this.off("open", onOpen);
320
325
  this.off("error", onError);
326
+ this.off("stateChange", onState);
321
327
  clearTimeout(timer);
322
328
  };
323
329
  const onOpen = () => {
@@ -330,8 +336,15 @@ export class PeerConnection {
330
336
  cleanup();
331
337
  reject(error);
332
338
  };
339
+ // Closed before the channel opened: it never will.
340
+ const onState = (state: ConnectionState) => {
341
+ if (state !== "closed") return;
342
+ cleanup();
343
+ reject(new Error("Connection closed before the data channel opened"));
344
+ };
333
345
  this.on("open", onOpen);
334
346
  this.on("error", onError);
347
+ this.on("stateChange", onState);
335
348
  const timer = setTimeout(() => {
336
349
  cleanup();
337
350
  reject(new Error(`Connection timeout after ${timeout}ms`));
@@ -17,7 +17,16 @@ import type {
17
17
  WebRtcConnectionOptions,
18
18
  } from "./types.js";
19
19
 
20
- export type PeerManagerOptions = WebRtcConnectionOptions;
20
+ export type PeerManagerOptions = WebRtcConnectionOptions & {
21
+ /**
22
+ * Called when a connection fails with no caller to tell: a signal it
23
+ * rejects (an offer during glare, malformed SDP or candidates), or an
24
+ * inbound connection whose channel never opens. The connection has already
25
+ * been closed and forgotten, so the peer can dial again. Errors are dropped
26
+ * when unset. A failed `connect()` rejects instead.
27
+ */
28
+ onError?: (error: Error, peerId: string) => void;
29
+ };
21
30
 
22
31
  export class PeerManager {
23
32
  private readonly signaling: SignalingTransport;
@@ -34,10 +43,19 @@ export class PeerManager {
34
43
 
35
44
  /** Dial `peerId` and resolve with the established channel. */
36
45
  async connect(peerId: string): Promise<ByteChannel> {
46
+ // Dialing again replaces whatever connection to this peer there was.
47
+ const previous = this.connections.get(peerId);
48
+ if (previous) this.forget(peerId, previous);
37
49
  const pc = this.makeConnection(peerId, "initiator");
38
50
  const channel = pc.open();
39
- await pc.connect();
40
- return channel;
51
+ try {
52
+ await pc.connect();
53
+ return await channel;
54
+ } catch (err) {
55
+ channel.catch(() => undefined);
56
+ this.forget(peerId, pc);
57
+ throw err;
58
+ }
41
59
  }
42
60
 
43
61
  /** Register a handler for inbound connections. Returns an unsubscribe fn. */
@@ -49,30 +67,66 @@ export class PeerManager {
49
67
  /** Tear down all connections and stop listening for signaling. */
50
68
  close(): void {
51
69
  this.unsubscribe();
52
- for (const pc of this.connections.values()) pc.close();
70
+ const all = [...this.connections.values()];
53
71
  this.connections.clear();
72
+ for (const pc of all) pc.close();
54
73
  this.connectionHandlers.clear();
55
74
  }
56
75
 
57
76
  private makeConnection(peerId: string, role: "initiator" | "responder"): PeerConnection {
58
77
  const pc = new PeerConnection(role, this.options);
59
78
  pc.on("signal", (msg) => this.signaling.send(peerId, msg));
60
- pc.on("close", () => this.connections.delete(peerId));
79
+ pc.on("close", () => this.forget(peerId, pc));
80
+ // A failed connection never recovers: forget it so the peer's next offer
81
+ // starts a new one instead of reaching this one.
82
+ pc.on("stateChange", (state) => {
83
+ if (state === "failed" || state === "closed") this.forget(peerId, pc);
84
+ });
61
85
  this.connections.set(peerId, pc);
62
86
  return pc;
63
87
  }
64
88
 
89
+ /** Close `pc` and drop it, unless a newer connection to `peerId` replaced it. */
90
+ private forget(peerId: string, pc: PeerConnection): void {
91
+ if (this.connections.get(peerId) !== pc) return;
92
+ this.connections.delete(peerId);
93
+ pc.close();
94
+ }
95
+
96
+ private fail(peerId: string, pc: PeerConnection, err: unknown): void {
97
+ const live = this.connections.get(peerId) === pc;
98
+ this.forget(peerId, pc);
99
+ if (!live) return; // closed on purpose meanwhile
100
+ const error = err instanceof Error ? err : new Error(String(err), { cause: err });
101
+ try {
102
+ this.options.onError?.(error, peerId);
103
+ } catch {}
104
+ }
105
+
65
106
  private onSignal(from: string, msg: SignalingMessage): void {
66
107
  let pc = this.connections.get(from);
108
+ // A connection makes one offer, so a new offer from a peer we answered
109
+ // before, or whose answer we already applied, means it started over: the
110
+ // old connection is stale. (An offer to an initiator still waiting for
111
+ // its answer is glare: handleSignal rejects it below.)
112
+ if (pc && msg.type === "offer" && (pc.getRole() === "responder" || pc.hasRemoteDescription())) {
113
+ this.forget(from, pc);
114
+ pc = undefined;
115
+ }
67
116
  if (!pc) {
68
117
  // Only an inbound offer starts a new responder connection; stray
69
118
  // candidates/answers for an unknown peer are ignored.
70
119
  if (msg.type !== "offer") return;
71
- pc = this.makeConnection(from, "responder");
72
- void pc.open().then((channel) => {
73
- for (const handler of this.connectionHandlers) handler(from, channel);
74
- });
120
+ const responder = this.makeConnection(from, "responder");
121
+ pc = responder;
122
+ responder.open().then(
123
+ (channel) => {
124
+ for (const handler of this.connectionHandlers) handler(from, channel);
125
+ },
126
+ (err: unknown) => this.fail(from, responder, err),
127
+ );
75
128
  }
76
- void pc.handleSignal(msg);
129
+ const target = pc;
130
+ target.handleSignal(msg).catch((err: unknown) => this.fail(from, target, err));
77
131
  }
78
132
  }
@@ -67,15 +67,49 @@ function expandSdp(compressed: string): string {
67
67
  return `${lines.join("\r\n")}\r\n`;
68
68
  }
69
69
 
70
- /** Compress an ICE candidate to its essential parts. */
70
+ /**
71
+ * Candidate attributes after `typ` that a connection needs: the related
72
+ * address of a srflx/relay candidate and the TCP type of a TCP one. Others
73
+ * (`generation`, `ufrag`, `network-id`, ...) are dropped to keep the QR small.
74
+ */
75
+ const KEPT_CANDIDATE_ATTRIBUTES = new Set(["raddr", "rport", "tcptype"]);
76
+
77
+ /** An `sdpMLineIndex` as it travels: empty for null. */
78
+ function indexToString(index: number | null): string {
79
+ return index == null ? "" : String(index);
80
+ }
81
+
82
+ function indexFromString(text: string | undefined): number | null {
83
+ if (!text) return null;
84
+ const index = Number.parseInt(text, 10);
85
+ return Number.isNaN(index) ? null : index;
86
+ }
87
+
88
+ /**
89
+ * Compress an ICE candidate to its essential parts. A candidate that carries
90
+ * attributes a connection needs (see {@link KEPT_CANDIDATE_ATTRIBUTES}) goes
91
+ * in the raw (`R:`) form, with only those attributes kept.
92
+ */
71
93
  function compressCandidate(candidate: IceCandidate): string {
72
94
  const { candidate: c, sdpMid, sdpMLineIndex } = candidate;
73
- const match = c.match(/candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)/);
95
+ const index = indexToString(sdpMLineIndex);
96
+ const match = c.match(
97
+ /candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)(.*)$/,
98
+ );
74
99
  if (!match) {
75
- return `R:${sdpMid ?? ""}:${sdpMLineIndex ?? 0}:${c}`;
100
+ return `R:${sdpMid ?? ""}:${index}:${c}`;
76
101
  }
77
- const [, foundation, component, protocol, priority, ip, port, type] = match;
78
- return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${sdpMLineIndex ?? 0}`;
102
+ const [base, foundation, component, protocol, priority, ip, port, type, rest] = match;
103
+ const words = rest.trim().split(/\s+/).filter(Boolean);
104
+ const kept: string[] = [];
105
+ for (let i = 0; i + 1 < words.length; i += 2) {
106
+ if (KEPT_CANDIDATE_ATTRIBUTES.has(words[i])) kept.push(words[i], words[i + 1]);
107
+ }
108
+ if (kept.length) {
109
+ const head = base.slice(0, base.length - rest.length);
110
+ return `R:${sdpMid ?? ""}:${index}:${head} ${kept.join(" ")}`;
111
+ }
112
+ return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${index}`;
79
113
  }
80
114
 
81
115
  /** Expand a compressed ICE candidate. */
@@ -85,7 +119,7 @@ function expandCandidate(compressed: string): IceCandidate {
85
119
  return {
86
120
  candidate: rest.join(":"),
87
121
  sdpMid: sdpMid || null,
88
- sdpMLineIndex: Number.parseInt(sdpMLineIndexStr, 10) || null,
122
+ sdpMLineIndex: indexFromString(sdpMLineIndexStr),
89
123
  };
90
124
  }
91
125
  const parts = compressed.split("|");
@@ -98,7 +132,7 @@ function expandCandidate(compressed: string): IceCandidate {
98
132
  return {
99
133
  candidate,
100
134
  sdpMid: sdpMid || null,
101
- sdpMLineIndex: sdpMLineIndexStr ? Number.parseInt(sdpMLineIndexStr, 10) : null,
135
+ sdpMLineIndex: indexFromString(sdpMLineIndexStr),
102
136
  };
103
137
  }
104
138
 
@@ -181,7 +215,6 @@ export class QrSignaling {
181
215
  /** Create an offer QR; `accept(answerQr)` finishes the handshake. */
182
216
  async offer(): Promise<{ qr: string; accept(answerQr: string): Promise<ByteChannel> }> {
183
217
  const pc = new PeerConnection("initiator", this.connection);
184
- const channel = pc.open();
185
218
  await pc.connect();
186
219
  await pc.waitForIceGathering();
187
220
 
@@ -194,10 +227,19 @@ export class QrSignaling {
194
227
  return {
195
228
  qr,
196
229
  accept: async (answerQr: string): Promise<ByteChannel> => {
197
- const parsed = parseCompressedSignal(decodeSignal(answerQr));
198
- await pc.handleSignal({ type: "answer", sdp: parsed.description.sdp });
199
- for (const candidate of parsed.candidates) {
200
- await pc.handleSignal({ type: "candidate", candidate });
230
+ // The connection timeout starts here, not at offer time: the QR
231
+ // exchange between the two takes as long as the people take.
232
+ const channel = pc.open();
233
+ try {
234
+ const parsed = parseCompressedSignal(decodeSignal(answerQr));
235
+ await pc.handleSignal({ type: "answer", sdp: parsed.description.sdp });
236
+ for (const candidate of parsed.candidates) {
237
+ await pc.handleSignal({ type: "candidate", candidate });
238
+ }
239
+ } catch (err) {
240
+ channel.catch(() => undefined);
241
+ pc.close();
242
+ throw err;
201
243
  }
202
244
  return channel;
203
245
  },
@@ -11,7 +11,7 @@
11
11
  * `() => new Room()`), so this module never hard-imports it.
12
12
  */
13
13
 
14
- import { byteChannelFromRoom } from "./byte-channel.js";
14
+ import { type ByteChannelFromRoomOptions, byteChannelFromRoom } from "./byte-channel.js";
15
15
  import type { ByteChannel, RoomLike, RoomManagerOptions, RoomParticipantLike } from "./types.js";
16
16
  import { ROOM_EVENT } from "./types.js";
17
17
 
@@ -94,10 +94,10 @@ export class RoomManager {
94
94
  };
95
95
  }
96
96
 
97
- /** Open a {@link ByteChannel} to a specific participant. */
98
- async channelTo(peerId: string): Promise<ByteChannel> {
97
+ /** Open a {@link ByteChannel} to a specific participant (see {@link byteChannelFromRoom}). */
98
+ async channelTo(peerId: string, options?: ByteChannelFromRoomOptions): Promise<ByteChannel> {
99
99
  if (!this.room) throw new Error("channelTo() before join()");
100
- return byteChannelFromRoom(this.room, peerId);
100
+ return byteChannelFromRoom(this.room, peerId, options);
101
101
  }
102
102
 
103
103
  /** Leave the room: unsubscribe and disconnect. */
package/src/types.ts CHANGED
@@ -19,6 +19,13 @@ export type ByteChannel = {
19
19
  recv: AsyncIterable<Uint8Array>;
20
20
  closed: Promise<void>;
21
21
  close(): void;
22
+ /** Bytes sent and not yet written out, where the transport can tell. */
23
+ readonly bufferedAmount?: number;
24
+ /**
25
+ * Resolves once the transport can take more (`bufferedAmount` at most a
26
+ * low-water mark) or the channel closed. Absent where it cannot tell.
27
+ */
28
+ whenDrained?(): Promise<void>;
22
29
  };
23
30
 
24
31
  /** WebRTC peer role in the connection. */
@@ -159,7 +166,7 @@ export interface RoomParticipantLike {
159
166
  export interface RoomLocalParticipantLike {
160
167
  publishData(
161
168
  data: Uint8Array,
162
- opts?: { reliable?: boolean; destinationIdentities?: string[] },
169
+ opts?: { reliable?: boolean; destinationIdentities?: string[]; topic?: string },
163
170
  ): Promise<void>;
164
171
  }
165
172