@statewalker/webrun-streams-signaling 0.1.4 → 0.1.5

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.
Files changed (2) hide show
  1. package/README.md +209 -108
  2. package/package.json +7 -4
package/README.md CHANGED
@@ -1,146 +1,247 @@
1
1
  # @statewalker/webrun-streams-signaling
2
2
 
3
- Generic P2P signaling / connection-setup helpers — `PeerManager`, `QrSignaling`, `RoomManager` — that each yield a webrun-streams `ByteChannel`.
3
+ ## What it is
4
4
 
5
- ## Overview
5
+ Connection-setup helpers for peer-to-peer links. Each one runs a handshake and hands back an
6
+ established `@statewalker/webrun-streams` `ByteChannel` (`send` / `recv` / `closed` / `close`).
7
+ `PeerManager` runs WebRTC offer/answer/ICE over a signaling transport you supply; `QrSignaling`
8
+ pairs two devices without a server by exchanging compact QR strings; `RoomManager` joins a
9
+ LiveKit-style room and opens a channel per participant. What runs on the channel afterwards —
10
+ typically `webrun-streams`' `emulateMux` — is up to you.
6
11
 
7
- Signaling here is **transport-setup only**: it runs the handshake (WebRTC offer/answer/ICE, or LiveKit room membership) that *establishes* a peer connection, then hands back an established `ByteChannel`. The byte transport and multiplexing on top of that channel is `@statewalker/webrun-streams`. These helpers were relocated out of the retired `@statewalker/vcs-port-*` packages and neutralised — nothing here is Git/VCS-specific — so a generic P2P concern lives in the webrun ecosystem. Vendor libraries (`livekit-client`) are optional peer-deps injected via a factory; native WebRTC is likewise injectable, so tests need no vendor install.
12
+ ## Why it exists
8
13
 
9
- **Out of scope:** the byte transport / multiplexing (`@statewalker/webrun-streams`), and the signaling *server* (STUN/TURN/rendezvous) — a deployment concern; these are clients.
14
+ Every peer-to-peer transport needs the same preliminary step: find the peer, exchange session
15
+ descriptions and ICE candidates, and wait for a data channel to open. That step is separate from
16
+ moving bytes. This package does only that step and stops at a `ByteChannel`, so any byte protocol
17
+ can run on the result. It contains no signaling server (STUN/TURN/rendezvous); these are clients.
18
+ Vendor code stays out of the import graph: native WebRTC is reached through an injectable factory
19
+ and LiveKit through a structural `RoomLike` interface and a `roomFactory`, so the package can be
20
+ tested with in-memory mocks and `livekit-client` is only needed if you use `RoomManager`.
10
21
 
11
- ## Installation
22
+ ## How to use
12
23
 
13
- ```bash
24
+ ```sh
14
25
  pnpm add @statewalker/webrun-streams-signaling
26
+ # only for RoomManager:
27
+ pnpm add livekit-client
15
28
  ```
16
29
 
17
- ## Quick Start
18
-
19
- `PeerManager` dials a peer over a `SignalingTransport` (your websocket / rendezvous side-channel) and resolves with a `ByteChannel`:
20
-
21
- ```typescript
22
- import { PeerManager } from "@statewalker/webrun-streams-signaling";
30
+ `livekit-client` (`^2.18.3`) is an optional peer dependency; the package never imports it, you
31
+ pass `() => new Room()`. One entry point, `.`, ESM only. It targets browsers: it uses
32
+ `RTCPeerConnection` (unless you inject `rtc`), `crypto.getRandomValues`, `btoa` / `atob`. In Node,
33
+ pass an `rtc` factory from a WebRTC implementation.
34
+
35
+ ### Exports
36
+
37
+ | Export | Purpose |
38
+ | --- | --- |
39
+ | `new PeerManager(signaling, options?)` | WebRTC connections keyed by peer id over a `SignalingTransport`. `connect(peerId): Promise<ByteChannel>`, `onConnection((peerId, ch) => void): () => void`, `close()`. |
40
+ | `PeerManagerOptions` | Same as `WebRtcConnectionOptions`. |
41
+ | `new QrSignaling(options?)` | Serverless pairing. `offer(): Promise<{ qr, accept(answerQr): Promise<ByteChannel> }>`, `answer(offerQr): Promise<{ qr, channel }>`, `getSessionId()`. |
42
+ | `QrSignalingOptions` | `{ sessionId?: string; connection?: WebRtcConnectionOptions }`. |
43
+ | `new RoomManager(options: RoomManagerOptions)` | Room membership. `join(room)`, `participants(): AsyncIterable<string>`, `channelTo(peerId): Promise<ByteChannel>`, `leave()`. |
44
+ | `new PeerConnection(role, options?)` | One WebRTC connection's lifecycle, which `PeerManager` and `QrSignaling` build on. `connect()`, `handleSignal(msg)`, `open(): Promise<ByteChannel>`, `waitForIceGathering()`, `getLocalDescription()`, `getCollectedCandidates()`, `getState()`, `getRole()`, `getDataChannel()`, `on` / `off`, `close()`. |
45
+ | `byteChannelFromDataChannel(dc)` | Wrap an `RTCDataChannel` as a `ByteChannel`. |
46
+ | `byteChannelFromRoom(room, peerId)` | A `ByteChannel` to one participant of a `RoomLike`. |
47
+ | `generateSessionId()`, `createCompressedSignal(...)`, `parseCompressedSignal(signal)`, `encodeSignal(signal)`, `decodeSignal(text)` | The pure QR payload functions. |
48
+
49
+ Types and constants: `SignalingTransport` (`localId`, `send(to, msg)`,
50
+ `onMessage(handler): () => void`), `SignalingMessage` (`offer` / `answer` / `candidate` /
51
+ `ready`), `SessionDescription`, `IceCandidate`, `PeerRole`, `ConnectionState`,
52
+ `PeerConnectionEvents` (`stateChange`, `signal`, `open`, `close`, `error`),
53
+ `WebRtcConnectionOptions`, `RtcPeerConnectionFactory`, `DEFAULT_ICE_SERVERS` (two Google STUN
54
+ servers), `CompressedSignal`, `RoomLike`, `RoomParticipantLike`, `RoomLocalParticipantLike`,
55
+ `RoomManagerOptions` (`url`, `getToken(room)`, `roomFactory`), `ROOM_EVENT` (the three LiveKit
56
+ event names used), `ParticipantInfo` (exported, not used by any API here).
57
+
58
+ `WebRtcConnectionOptions`:
59
+
60
+ | option | default | meaning |
61
+ | --- | --- | --- |
62
+ | `iceServers` | `DEFAULT_ICE_SERVERS` | ICE servers. |
63
+ | `connectionTimeout` | 30000 ms | How long `open()` waits for the data channel. |
64
+ | `iceGatheringTimeout` | 5000 ms | How long `QrSignaling` waits for ICE gathering before using what it has. |
65
+ | `channelLabel` | `"webrun-data"` | Data channel label. |
66
+ | `ordered` | `true` | Ordered delivery. |
67
+ | `maxRetransmits` | unset | Retransmit limit for unreliable mode. |
68
+ | `rtc` | `new RTCPeerConnection(config)` | Factory for the peer connection. |
69
+
70
+ ## Examples
71
+
72
+ ### `PeerManager`: dial a peer over your signaling channel, then multiplex
73
+
74
+ The `SignalingTransport` below is an in-memory bus, so both peers run in one page; in an
75
+ application it wraps your WebSocket or other rendezvous channel.
76
+
77
+ ```ts
78
+ import { emulateMux } from "@statewalker/webrun-streams";
79
+ import {
80
+ PeerManager,
81
+ type SignalingMessage,
82
+ type SignalingTransport,
83
+ } from "@statewalker/webrun-streams-signaling";
84
+
85
+ function signalingBus() {
86
+ const handlers = new Map<string, (from: string, msg: SignalingMessage) => void>();
87
+ return (localId: string): SignalingTransport => ({
88
+ localId,
89
+ send: (to, msg) => queueMicrotask(() => handlers.get(to)?.(localId, msg)),
90
+ onMessage(handler) {
91
+ handlers.set(localId, handler);
92
+ return () => handlers.delete(localId);
93
+ },
94
+ });
95
+ }
23
96
 
24
- // `signaling` is your SignalingTransport (localId + send + onMessage).
25
- // In production `PeerConnection` defaults to `new RTCPeerConnection(config)`;
26
- // pass `{ rtc }` only to inject a factory (tests, or a non-browser stack).
27
- const a = new PeerManager(signalingA);
28
- const b = new PeerManager(signalingB);
97
+ const bus = signalingBus();
98
+ const a = new PeerManager(bus("A"));
99
+ const b = new PeerManager(bus("B"));
29
100
 
30
- b.onConnection((peerId, ch) => {
31
- ch.send(new Uint8Array([1, 2, 3]));
101
+ b.onConnection((peerId, channel) => {
102
+ const mux = emulateMux(channel, { side: "responder" });
103
+ mux.serve(async function* echo(input) {
104
+ for await (const chunk of input) yield chunk;
105
+ });
32
106
  });
33
107
 
34
- const ch = await a.connect("B"); // Promise<ByteChannel>
35
- ch.send(new Uint8Array([9, 8]));
108
+ const channel = await a.connect("B");
109
+ const mux = emulateMux(channel, { side: "initiator" });
110
+ for await (const chunk of mux.call([new TextEncoder().encode("ping")])) {
111
+ console.log(new TextDecoder().decode(chunk)); // "ping"
112
+ }
113
+
114
+ a.close();
115
+ b.close();
36
116
  ```
37
117
 
38
- `QrSignaling` pairs two devices serverless, exchanging compact QR strings:
118
+ ### `QrSignaling`: pair two devices without a server
39
119
 
40
- ```typescript
120
+ ```ts
41
121
  import { QrSignaling } from "@statewalker/webrun-streams-signaling";
42
122
 
123
+ // Device A
43
124
  const deviceA = new QrSignaling();
125
+ const { qr: offerQr, accept } = await deviceA.offer(); // show offerQr as a QR code
126
+
127
+ // Device B, after scanning offerQr
44
128
  const deviceB = new QrSignaling();
129
+ const { qr: answerQr, channel: channelB } = await deviceB.answer(offerQr); // show answerQr
45
130
 
46
- const { qr: offerQr, accept } = await deviceA.offer(); // display offerQr
47
- const { qr: answerQr, channel: chB } = await deviceB.answer(offerQr); // scan + reply
48
- const chA = await accept(answerQr); // both sides now have a ByteChannel
131
+ // Device A, after scanning answerQr
132
+ const channelA = await accept(answerQr);
49
133
  ```
50
134
 
51
- `RoomManager` joins a LiveKit-style room and opens a `ByteChannel` per participant:
135
+ **This flow does not currently complete against a real WebRTC stack**; see
136
+ [What `answer()` waits for](#what-answer-waits-for).
52
137
 
53
- ```typescript
54
- import { RoomManager } from "@statewalker/webrun-streams-signaling";
138
+ ### `RoomManager`: one channel per participant
139
+
140
+ ```ts
55
141
  import { Room } from "livekit-client";
142
+ import { RoomManager } from "@statewalker/webrun-streams-signaling";
56
143
 
57
- const room = new RoomManager({
58
- url: "wss://my-livekit-host",
59
- getToken: (name) => fetchToken(name),
144
+ const rooms = new RoomManager({
145
+ url: "wss://livekit.example.com",
146
+ getToken: (room) => fetch(`/token?room=${room}`).then((r) => r.text()),
60
147
  roomFactory: () => new Room(),
61
148
  });
62
149
 
63
- await room.join("room1");
64
- for await (const peerId of room.participants()) {
65
- const ch = await room.channelTo(peerId);
66
- ch.send(new Uint8Array([5, 5]));
150
+ await rooms.join("room1");
151
+ for await (const peerId of rooms.participants()) {
152
+ const channel = await rooms.channelTo(peerId);
153
+ channel.send(new Uint8Array([5, 5]));
67
154
  }
68
- await room.leave();
155
+ // participants() does not end until leave() is called
69
156
  ```
70
157
 
71
- ## API
72
-
73
- ### Managers
74
-
75
- - **`class PeerManager`** — `new PeerManager(signaling: SignalingTransport, options?: PeerManagerOptions)`. WebRTC peer discovery + connection over a signaling transport.
76
- - `connect(peerId: string): Promise<ByteChannel>` — dial a peer; resolves with the established channel.
77
- - `onConnection(handler: (peerId: string, ch: ByteChannel) => void): () => void` — accept inbound dials; returns an unsubscribe fn.
78
- - `close(): void` — tear down all connections and stop listening.
79
- - **`class QrSignaling`** — `new QrSignaling(options?: QrSignalingOptions)`. Serverless offer/answer exchange via QR strings.
80
- - `offer(): Promise<{ qr: string; accept(answerQr: string): Promise<ByteChannel> }>` — create an offer QR; `accept` finishes the handshake.
81
- - `answer(offerQr: string): Promise<{ qr: string; channel: ByteChannel }>` — consume an offer QR, produce an answer QR + the channel.
82
- - `getSessionId(): string`.
83
- - **`class RoomManager`** — `new RoomManager(options: RoomManagerOptions)`. LiveKit room membership + per-participant channels.
84
- - `join(room: string): Promise<void>`, `participants(): AsyncIterable<string>`, `channelTo(peerId: string): Promise<ByteChannel>`, `leave(): Promise<void>`.
85
-
86
- ### ByteChannel adapters
158
+ ## Internals
87
159
 
88
- - **`byteChannelFromDataChannel(channel: RTCDataChannel): ByteChannel`** — wrap an established `RTCDataChannel`.
89
- - **`byteChannelFromRoom(room: RoomLike, peerId: string): ByteChannel`** — per-participant channel over a LiveKit-style `Room`.
90
-
91
- ### Low-level
92
-
93
- - **`class PeerConnection`** — single WebRTC connection lifecycle (offer/answer/ICE) that `PeerManager` and `QrSignaling` build on.
94
-
95
- ### QR pure functions
96
-
97
- - **`generateSessionId(): string`** — short random session id.
98
- - **`createCompressedSignal(sessionId, role, description, candidates): CompressedSignal`** — build a compact QR payload from SDP + ICE.
99
- - **`parseCompressedSignal(signal): { sessionId, role, description, candidates }`** — reverse of the above.
100
- - **`encodeSignal(signal): string`** / **`decodeSignal(encoded): CompressedSignal`** — URL-safe base64 (de)serialisation for QR strings.
101
-
102
- ### Types and constants
103
-
104
- All re-exported from `./types` at the package root.
105
-
106
- | Export | Kind | Purpose |
107
- | --- | --- | --- |
108
- | `SignalingTransport` | interface | The pluggable channel offers/answers travel over. |
109
- | `SignalingMessage` | union | Offer / answer / ICE-candidate envelopes. |
110
- | `SessionDescription` / `IceCandidate` | interface | Structural views of the WebRTC handshake payloads (no DOM types required). |
111
- | `PeerRole` | `"initiator" \| "responder"` | Which side of the handshake this peer plays. |
112
- | `ConnectionState` | union | Lifecycle state reported by `PeerConnection`. |
113
- | `PeerConnectionEvents` | interface | The event callbacks `PeerConnection` accepts. |
114
- | `WebRtcConnectionOptions` | interface | ICE configuration and the injected `rtc` factory. |
115
- | `RtcPeerConnectionFactory` | type | `(config: RTCConfiguration) => RTCPeerConnection` — the injection seam that keeps native WebRTC out of the import graph. |
116
- | `DEFAULT_ICE_SERVERS` | const | STUN servers used when none are supplied. |
117
- | `CompressedSignal` | interface | The compact offer/answer shape behind the QR helpers. |
118
- | `RoomLike` / `RoomParticipantLike` / `RoomLocalParticipantLike` | interface | Structural view of a LiveKit room, so `livekit-client` stays an optional peer dependency. |
119
- | `RoomManagerOptions` | interface | Includes `roomFactory`, the injection point for the real `Room`. |
120
- | `ParticipantInfo` | interface | Identity + metadata for a room participant. |
121
- | `ROOM_EVENT` | const | Room event-name constants used by `RoomManager`. |
122
-
123
- ## Notes
124
-
125
- - Each helper yields a webrun-streams **`ByteChannel`** (`send` / `recv` / `closed` / `close`), not a `MessagePort` — the byte transport and `emulateMux` run on top via `@statewalker/webrun-streams`.
126
- - **Vendor coupling stays behind optional peer-deps.** `livekit-client` is injected via `RoomManagerOptions.roomFactory` (the module keeps only a structural `RoomLike` view), and native WebRTC is injected via the optional `rtc` factory (defaulting to `new RTCPeerConnection`). So the tests use in-memory mocks and require no vendor install.
127
- - **`peerjs` is not a dependency.** These helpers use native WebRTC; the peerjs byte transport lives in `@statewalker/webrun-streams-peerjs`.
128
- - Built red/green TDD.
129
-
130
- ## Dependencies
131
-
132
- | Dependency | Kind | Why |
133
- | --- | --- | --- |
134
- | [`@statewalker/webrun-streams`](../webrun-streams) | runtime | `ByteChannel`, and `emulateMux` for the transport built on top. |
135
- | `livekit-client` | **peer, optional** (`^2.18.3`) | Only for `RoomManager`. Injected via `RoomManagerOptions.roomFactory`; the module itself keeps a structural `RoomLike` view, so the dependency is avoidable. |
136
-
137
- Native WebRTC is likewise injected (the optional `rtc` factory, defaulting to
138
- `new RTCPeerConnection`), which is why the test suite needs no vendor install.
139
- `peerjs` is deliberately **not** a dependency — that transport lives in
140
- [`@statewalker/webrun-streams-peerjs`](../webrun-streams-peerjs).
160
+ ```
161
+ SignalingTransport / QR strings / LiveKit room (you provide)
162
+ │ offer, answer, ICE candidates
163
+ ▼
164
+ PeerConnection ── RTCPeerConnection (or your `rtc` factory)
165
+ │ data channel opens
166
+ ▼
167
+ ByteChannel ── send / recv / closed / close
168
+ │
169
+ ▼
170
+ emulateMux or any byte protocol (you run)
171
+ ```
141
172
 
142
- ESM only (`"type": "module"`).
173
+ ### How `PeerManager` routes signals
174
+
175
+ Each peer id maps to one `PeerConnection`. `connect(peerId)` creates an initiator, creates the
176
+ data channel and offer, and resolves when the channel opens. An inbound `offer` from an unknown
177
+ peer creates a responder; `onConnection` handlers are called when its channel opens. Answers and
178
+ candidates from unknown peers are ignored. Candidates that arrive before the remote description
179
+ is set are queued and applied after it. When ICE gathering completes, a `{ type: "ready" }`
180
+ signal is sent; receivers ignore it. A connection is forgotten when its data channel closes.
181
+
182
+ ### What `answer()` waits for
183
+
184
+ `QrSignaling` sends everything in one payload: it waits for ICE gathering (up to
185
+ `iceGatheringTimeout`), then packs the SDP and all gathered candidates. `offer()` returns the
186
+ offer QR and an `accept` that applies the answer. `answer()`, however, awaits the responder's data
187
+ channel before it returns the answer QR. With a real WebRTC stack that channel opens only after
188
+ the initiator has applied the answer, which needs the answer QR. So `answer()` rejects with
189
+ `Connection timeout after <connectionTimeout>ms` instead of returning, and the flow in the example
190
+ above does not complete. The test suite uses a mock `RTCPeerConnection` that opens the channel as
191
+ soon as both descriptions are set on one side, so it does not exercise this ordering.
192
+
193
+ `offer()` starts waiting for its channel immediately. If `accept` is never called, that wait
194
+ rejects after `connectionTimeout` with nothing attached to it: an unhandled rejection, which
195
+ terminates a Node process.
196
+
197
+ ### How QR payloads stay small
198
+
199
+ `createCompressedSignal` keeps only the SDP lines needed to connect (`v=`, `o=`, `s=`, `t=`,
200
+ `m=`, `c=`, `a=group:`, `a=ice-ufrag:`, `a=ice-pwd:`, `a=fingerprint:`, `a=setup:`, `a=mid:`,
201
+ `a=sctp-port:`, `a=max-message-size:`) and packs each candidate into a `|`-separated string
202
+ (unparseable candidates are kept raw, prefixed `R:`). `encodeSignal` is URL-safe base64 of the
203
+ JSON, without padding. `parseCompressedSignal` throws `Unsupported protocol version: <v>` for any
204
+ version other than 1, and a malformed packed candidate throws
205
+ `Invalid compressed candidate: <text>`.
206
+
207
+ ### How the channels behave
208
+
209
+ - Both channels buffer inbound bytes from the moment they are created, so data that arrives
210
+ before your `for await` starts is not lost.
211
+ - `byteChannelFromDataChannel` sets `binaryType = "arraybuffer"` and copies every inbound payload.
212
+ A non-byte message (a string) throws `TypeError: byte channel received a non-byte payload`
213
+ inside the channel's `message` listener. `closed` resolves on the data channel's `close` event
214
+ or on `close()`. A `send` on a closed channel is swallowed.
215
+ - `byteChannelFromRoom` publishes with `reliable: true` to `destinationIdentities: [peerId]` and
216
+ accepts `dataReceived` events from that participant (or with no participant). Its `closed`
217
+ resolves only when you call `close()`; it does not watch for the participant leaving or the
218
+ room disconnecting.
219
+
220
+ ### What `RoomManager` tracks
221
+
222
+ `participants()` yields the identities already in the room when `join` returns, then each one
223
+ that joins, and ends at `leave()`. Departures are not reported. Only the most recently created
224
+ `participants()` iterator receives new joiners. `channelTo()` before `join()` throws
225
+ `channelTo() before join()`.
226
+
227
+ ### Failure modes
228
+
229
+ - `PeerConnection.open()` rejects with `Connection timeout after <n>ms`, with the data channel's
230
+ error, or with `Connection failed` when the connection state becomes `failed`.
231
+ - `connect()` on a responder throws `connect() should only be called by initiator`; an offer to an
232
+ initiator throws `Received offer but not in responder role`; an answer to a responder throws
233
+ `Received answer but not in initiator role`.
234
+ - On the `PeerManager` responder side, a connection that never opens is never reported to
235
+ `onConnection`; its `open()` rejection has no handler attached and surfaces as an unhandled
236
+ rejection.
237
+
238
+ ### Dependencies
239
+
240
+ Zero runtime imports: the bundle imports nothing. `@statewalker/webrun-streams` is a dependency
241
+ for the `ByteChannel` type only. `livekit-client` is an optional peer, used only through the
242
+ `RoomLike` shape you inject. A neutrality test (`tests/neutrality.test.ts`) keeps the source from
243
+ importing anything else.
143
244
 
144
245
  ## License
145
246
 
146
- MIT © statewalker — see [LICENSE](../../LICENSE).
247
+ MIT
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-signaling",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Generic P2P signaling/connection-setup (PeerManager, QrSignaling, RoomManager) yielding webrun-streams ByteChannels",
7
- "homepage": "https://github.com/statewalker/webrun-wire",
7
+ "bugs": {
8
+ "url": "https://github.com/statewalker/webrun-wire/issues"
9
+ },
10
+ "homepage": "https://github.com/statewalker/webrun-wire/tree/main/packages/webrun-streams-signaling#readme",
8
11
  "author": {
9
12
  "name": "Mikhail Kotelnikov",
10
13
  "email": "mikhail.kotelnikov@gmail.com"
@@ -12,7 +15,7 @@
12
15
  "license": "MIT",
13
16
  "repository": {
14
17
  "type": "git",
15
- "url": "git@github.com:statewalker/webrun-wire.git",
18
+ "url": "git+https://github.com/statewalker/webrun-wire.git",
16
19
  "directory": "packages/webrun-streams-signaling"
17
20
  },
18
21
  "exports": {
@@ -27,7 +30,7 @@
27
30
  "src"
28
31
  ],
29
32
  "dependencies": {
30
- "@statewalker/webrun-streams": "^0.2.1"
33
+ "@statewalker/webrun-streams": "^0.2.2"
31
34
  },
32
35
  "peerDependencies": {
33
36
  "livekit-client": "^2.18.3"