@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.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * WebRTC peer connection lifecycle (single connection).
3
+ *
4
+ * Relocated from `@statewalker/vcs-port-webrtc`'s `PeerManager` and neutralised
5
+ * (no Git/VCS coupling). Handles signaling, ICE candidate gathering and data
6
+ * channel creation for one peer, in either "initiator" (creates offer) or
7
+ * "responder" (creates answer) role.
8
+ *
9
+ * Adaptations vs. the original:
10
+ * - `new RTCPeerConnection(...)` is behind an injectable {@link RtcPeerConnectionFactory}
11
+ * so tests run without a real WebRTC stack.
12
+ * - remote ICE candidates are added as plain `RTCIceCandidateInit` (accepted by
13
+ * `addIceCandidate`) instead of constructing a global `RTCIceCandidate`,
14
+ * which does not exist outside a browser.
15
+ * - `open()` yields a webrun-streams {@link ByteChannel} rather than a `MessagePort`.
16
+ */
17
+ import type { ByteChannel } from "@statewalker/webrun-streams";
18
+ import type { ConnectionState, IceCandidate, PeerConnectionEvents, PeerRole, SessionDescription, SignalingMessage, WebRtcConnectionOptions } from "./types.js";
19
+ /**
20
+ * Manages a single WebRTC peer connection lifecycle.
21
+ */
22
+ export declare class PeerConnection {
23
+ private readonly role;
24
+ private readonly options;
25
+ private pc;
26
+ private dataChannel;
27
+ private state;
28
+ private readonly listeners;
29
+ private pendingCandidates;
30
+ private remoteDescriptionSet;
31
+ private collectedCandidates;
32
+ private iceGatheringComplete;
33
+ constructor(role: PeerRole, options?: WebRtcConnectionOptions);
34
+ getState(): ConnectionState;
35
+ getRole(): PeerRole;
36
+ getDataChannel(): RTCDataChannel | null;
37
+ on<K extends keyof PeerConnectionEvents>(event: K, listener: PeerConnectionEvents[K]): this;
38
+ off<K extends keyof PeerConnectionEvents>(event: K, listener: PeerConnectionEvents[K]): this;
39
+ private emit;
40
+ private createRtc;
41
+ private initConnection;
42
+ private setupDataChannel;
43
+ private setState;
44
+ /**
45
+ * Start connection as initiator: create the data channel and offer, emit the
46
+ * offer via the `signal` event.
47
+ */
48
+ connect(): Promise<void>;
49
+ /** Handle a signaling message from the remote peer. */
50
+ handleSignal(message: SignalingMessage): Promise<void>;
51
+ private handleOffer;
52
+ private handleAnswer;
53
+ private handleCandidate;
54
+ private processPendingCandidates;
55
+ /**
56
+ * Wait for ICE gathering to complete (batch/QR signaling). Resolves early on
57
+ * timeout, using whatever candidates were collected.
58
+ */
59
+ waitForIceGathering(): Promise<void>;
60
+ /** Local session description after negotiation. */
61
+ getLocalDescription(): SessionDescription | null;
62
+ /** Collected ICE candidates (batch/QR signaling). */
63
+ getCollectedCandidates(): IceCandidate[];
64
+ /**
65
+ * Resolve with a {@link ByteChannel} once the data channel opens. Rejects on
66
+ * error or after {@link WebRtcConnectionOptions.connectionTimeout}.
67
+ */
68
+ open(): Promise<ByteChannel>;
69
+ /** Close the connection and release resources. */
70
+ close(): void;
71
+ }
72
+ //# sourceMappingURL=peer-connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer-connection.d.ts","sourceRoot":"","sources":["../src/peer-connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAE/D,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,QAAQ,EACR,kBAAkB,EAClB,gBAAgB,EAChB,uBAAuB,EACxB,MAAM,YAAY,CAAC;AASpB;;GAEG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAW;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAClD,OAAO,CAAC,EAAE,CAAkC;IAC5C,OAAO,CAAC,WAAW,CAA+B;IAClD,OAAO,CAAC,KAAK,CAA0B;IAEvC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAGZ;IAEd,OAAO,CAAC,iBAAiB,CAA6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+ *
4
+ * Wraps the low-level {@link PeerConnection} (relocated from
5
+ * `@statewalker/vcs-port-webrtc`) with a multi-peer, id-keyed surface: dial a
6
+ * peer with `connect(peerId)` or accept inbound dials via `onConnection`. Each
7
+ * established connection yields a webrun-streams {@link ByteChannel}. The WebRTC
8
+ * offer/answer/ICE routing is the original logic; only the routing-by-peer-id
9
+ * and the ByteChannel result are new.
10
+ */
11
+ import type { ByteChannel } from "@statewalker/webrun-streams";
12
+ import type { SignalingTransport, WebRtcConnectionOptions } from "./types.js";
13
+ export type PeerManagerOptions = WebRtcConnectionOptions;
14
+ export declare class PeerManager {
15
+ private readonly signaling;
16
+ private readonly options;
17
+ private readonly connections;
18
+ private readonly connectionHandlers;
19
+ private readonly unsubscribe;
20
+ constructor(signaling: SignalingTransport, options?: PeerManagerOptions);
21
+ /** Dial `peerId` and resolve with the established channel. */
22
+ connect(peerId: string): Promise<ByteChannel>;
23
+ /** Register a handler for inbound connections. Returns an unsubscribe fn. */
24
+ onConnection(handler: (peerId: string, ch: ByteChannel) => void): () => void;
25
+ /** Tear down all connections and stop listening for signaling. */
26
+ close(): void;
27
+ private makeConnection;
28
+ private onSignal;
29
+ }
30
+ //# sourceMappingURL=peer-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer-manager.d.ts","sourceRoot":"","sources":["../src/peer-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAE/D,OAAO,KAAK,EAAoB,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEhG,MAAM,MAAM,kBAAkB,GAAG,uBAAuB,CAAC;AAEzD,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAqB;IAC/C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqC;IACjE,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAwD;IAC3F,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAa;IAEzC,YAAY,SAAS,EAAE,kBAAkB,EAAE,OAAO,GAAE,kBAAuB,EAI1E;IAED,8DAA8D;IACxD,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAKlD;IAED,6EAA6E;IAC7E,YAAY,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,KAAK,IAAI,GAAG,MAAM,IAAI,CAG3E;IAED,kEAAkE;IAClE,KAAK,IAAI,IAAI,CAKZ;IAED,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,QAAQ;CAajB"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * QR code signaling for serverless WebRTC connection.
3
+ *
4
+ * Relocated from `@statewalker/vcs-port-webrtc`'s `signaling.ts` (neutralised).
5
+ * Compresses WebRTC signaling data (SDP + ICE candidates) into a compact,
6
+ * base64 form suitable for QR codes, enabling out-of-band manual pairing where
7
+ * peers exchange QR strings instead of using a live signaling server.
8
+ *
9
+ * The compress/expand/encode/decode functions are pure and unchanged; the
10
+ * {@link QrSignaling} class is adapted to the target API and yields
11
+ * webrun-streams {@link ByteChannel}s.
12
+ */
13
+ import type { ByteChannel } from "@statewalker/webrun-streams";
14
+ import type { CompressedSignal, IceCandidate, PeerRole, SessionDescription, WebRtcConnectionOptions } from "./types.js";
15
+ /** Generate a short random session ID. */
16
+ export declare function generateSessionId(): string;
17
+ /** Create a compressed signal for QR code exchange. */
18
+ export declare function createCompressedSignal(sessionId: string, role: PeerRole, description: SessionDescription, candidates: IceCandidate[]): CompressedSignal;
19
+ /** Parse a compressed signal. */
20
+ export declare function parseCompressedSignal(signal: CompressedSignal): {
21
+ sessionId: string;
22
+ role: PeerRole;
23
+ description: SessionDescription;
24
+ candidates: IceCandidate[];
25
+ };
26
+ /** Encode a compressed signal to a URL-safe base64 string for a QR code. */
27
+ export declare function encodeSignal(signal: CompressedSignal): string;
28
+ /** Decode a signal string from a QR code. */
29
+ export declare function decodeSignal(encoded: string): CompressedSignal;
30
+ /** Options for {@link QrSignaling}. */
31
+ export interface QrSignalingOptions {
32
+ sessionId?: string;
33
+ connection?: WebRtcConnectionOptions;
34
+ }
35
+ /**
36
+ * Serverless WebRTC pairing over QR codes.
37
+ *
38
+ * Flow:
39
+ * 1. Initiator `offer()` → `{ qr, accept }`; displays `qr`.
40
+ * 2. Responder `answer(offerQr)` → `{ qr, channel }`; displays its `qr`.
41
+ * 3. Initiator `accept(answerQr)` → `channel`. Both ends now hold a working
42
+ * {@link ByteChannel}.
43
+ */
44
+ export declare class QrSignaling {
45
+ private readonly sessionId;
46
+ private readonly connection;
47
+ constructor(options?: QrSignalingOptions);
48
+ getSessionId(): string;
49
+ /** Create an offer QR; `accept(answerQr)` finishes the handshake. */
50
+ offer(): Promise<{
51
+ qr: string;
52
+ accept(answerQr: string): Promise<ByteChannel>;
53
+ }>;
54
+ /** Consume an offer QR and produce an answer QR + the established channel. */
55
+ answer(offerQr: string): Promise<{
56
+ qr: string;
57
+ channel: ByteChannel;
58
+ }>;
59
+ }
60
+ //# sourceMappingURL=qr-signaling.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qr-signaling.d.ts","sourceRoot":"","sources":["../src/qr-signaling.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAE/D,OAAO,KAAK,EACV,gBAAgB,EAChB,YAAY,EACZ,QAAQ,EACR,kBAAkB,EAClB,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAKpB,0CAA0C;AAC1C,wBAAgB,iBAAiB,IAAI,MAAM,CAO1C;AAsED,uDAAuD;AACvD,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,QAAQ,EACd,WAAW,EAAE,kBAAkB,EAC/B,UAAU,EAAE,YAAY,EAAE,GACzB,gBAAgB,CAQlB;AAED,iCAAiC;AACjC,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,gBAAgB,GAAG;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,QAAQ,CAAC;IACf,WAAW,EAAE,kBAAkB,CAAC;IAChC,UAAU,EAAE,YAAY,EAAE,CAAC;CAC5B,CAWA;AAED,4EAA4E;AAC5E,wBAAgB,YAAY,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM,CAG7D;AAED,6CAA6C;AAC7C,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,gBAAgB,CAI9D;AAED,uCAAuC;AACvC,MAAM,WAAW,kBAAkB;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,uBAAuB,CAAC;CACtC;AAED;;;;;;;;GAQG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA0B;IAErD,YAAY,OAAO,GAAE,kBAAuB,EAG3C;IAED,YAAY,IAAI,MAAM,CAErB;IAED,qEAAqE;IAC/D,KAAK,IAAI,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAAA;KAAE,CAAC,CAuBrF;IAED,8EAA8E;IACxE,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,WAAW,CAAA;KAAE,CAAC,CAkB3E;CACF"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Room membership manager over a LiveKit-style `Room`.
3
+ *
4
+ * Relocated from `@statewalker/vcs-port-livekit`'s `RoomManager` and adapted to
5
+ * the target API: `join`/`participants`/`channelTo`/`leave`. Participant
6
+ * tracking is the original event-wiring; `channelTo` yields a per-participant
7
+ * webrun-streams {@link ByteChannel} (see {@link byteChannelFromRoom}).
8
+ *
9
+ * The vendor (`livekit-client`) stays an optional peerDependency: the `Room` is
10
+ * injected via {@link RoomManagerOptions.roomFactory} (production:
11
+ * `() => new Room()`), so this module never hard-imports it.
12
+ */
13
+ import type { ByteChannel } from "@statewalker/webrun-streams";
14
+ import type { RoomManagerOptions } from "./types.js";
15
+ export declare class RoomManager {
16
+ private readonly options;
17
+ private room;
18
+ private readonly seen;
19
+ private live;
20
+ private endParticipants;
21
+ private readonly cleanups;
22
+ constructor(options: RoomManagerOptions);
23
+ /** Join a room by name (token is resolved via `options.getToken`). */
24
+ join(room: string): Promise<void>;
25
+ /** Observe participant identities: those already present, then joiners. */
26
+ participants(): AsyncIterable<string>;
27
+ /** Open a {@link ByteChannel} to a specific participant. */
28
+ channelTo(peerId: string): Promise<ByteChannel>;
29
+ /** Leave the room: unsubscribe and disconnect. */
30
+ leave(): Promise<void>;
31
+ }
32
+ //# sourceMappingURL=room-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room-manager.d.ts","sourceRoot":"","sources":["../src/room-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAE/D,OAAO,KAAK,EAAY,kBAAkB,EAAuB,MAAM,YAAY,CAAC;AAGpF,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,IAAI,CAAyB;IAErC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAgB;IACrC,OAAO,CAAC,IAAI,CAA6C;IACzD,OAAO,CAAC,eAAe,CAA6B;IACpD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;IAElD,YAAY,OAAO,EAAE,kBAAkB,EAEtC;IAED,sEAAsE;IAChE,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAmBtC;IAED,2EAA2E;IAC3E,YAAY,IAAI,aAAa,CAAC,MAAM,CAAC,CAyCpC;IAED,4DAA4D;IACtD,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAGpD;IAED,kDAAkD;IAC5C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAQ3B;CACF"}
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Signaling / connection-setup types.
3
+ *
4
+ * Relocated from the retiring `@statewalker/vcs-port-{webrtc,livekit}` packages
5
+ * and neutralised: nothing here is VCS/Git-specific. These describe the generic
6
+ * P2P handshake (WebRTC offer/answer/ICE, QR payloads, LiveKit room membership)
7
+ * used to *establish* a channel. The byte transport itself is
8
+ * `@statewalker/webrun-streams` (a `ByteChannel`), not this package.
9
+ */
10
+ /** WebRTC peer role in the connection. */
11
+ export type PeerRole = "initiator" | "responder";
12
+ /** Connection state for a WebRTC peer. */
13
+ export type ConnectionState = "new" | "connecting" | "connected" | "disconnected" | "failed" | "closed";
14
+ /** ICE candidate for connection establishment. */
15
+ export interface IceCandidate {
16
+ candidate: string;
17
+ sdpMid: string | null;
18
+ sdpMLineIndex: number | null;
19
+ }
20
+ /** Session description for WebRTC signaling. */
21
+ export interface SessionDescription {
22
+ type: "offer" | "answer";
23
+ sdp: string;
24
+ }
25
+ /** Signaling message exchanged between peers. */
26
+ export type SignalingMessage = {
27
+ type: "offer";
28
+ sdp: string;
29
+ } | {
30
+ type: "answer";
31
+ sdp: string;
32
+ } | {
33
+ type: "candidate";
34
+ candidate: IceCandidate;
35
+ } | {
36
+ type: "ready";
37
+ };
38
+ /**
39
+ * Compressed signaling data for QR code exchange.
40
+ *
41
+ * Contains everything needed to establish a connection in a single compact
42
+ * payload suitable for QR codes.
43
+ */
44
+ export interface CompressedSignal {
45
+ /** Protocol version */
46
+ v: number;
47
+ /** Session ID for matching peers */
48
+ id: string;
49
+ /** Peer role */
50
+ role: PeerRole;
51
+ /** SDP offer or answer (compressed) */
52
+ sdp: string;
53
+ /** ICE candidates (compressed) */
54
+ ice: string[];
55
+ }
56
+ /**
57
+ * Factory for the underlying WebRTC peer connection. Defaults to
58
+ * `new RTCPeerConnection(config)`; tests inject a mock so no real vendor
59
+ * network is required.
60
+ */
61
+ export type RtcPeerConnectionFactory = (config: RTCConfiguration) => RTCPeerConnection;
62
+ /** Options for creating a WebRTC peer connection. */
63
+ export interface WebRtcConnectionOptions {
64
+ /** ICE servers for connection establishment */
65
+ iceServers?: RTCIceServer[];
66
+ /** Timeout for connection establishment (ms) */
67
+ connectionTimeout?: number;
68
+ /** Timeout for ICE gathering (ms) */
69
+ iceGatheringTimeout?: number;
70
+ /** Data channel label */
71
+ channelLabel?: string;
72
+ /** Whether to use ordered delivery */
73
+ ordered?: boolean;
74
+ /** Maximum retransmits for unreliable mode */
75
+ maxRetransmits?: number;
76
+ /** Underlying peer-connection factory (injected in tests). */
77
+ rtc?: RtcPeerConnectionFactory;
78
+ }
79
+ /** Events emitted by a low-level {@link PeerConnection}. */
80
+ export interface PeerConnectionEvents {
81
+ /** Emitted when connection state changes */
82
+ stateChange: (state: ConnectionState) => void;
83
+ /** Emitted when a signaling message is ready to send */
84
+ signal: (message: SignalingMessage) => void;
85
+ /** Emitted when the data channel opens */
86
+ open: () => void;
87
+ /** Emitted when the connection closes */
88
+ close: () => void;
89
+ /** Emitted on error */
90
+ error: (error: Error) => void;
91
+ }
92
+ /**
93
+ * A signaling transport routes {@link SignalingMessage}s to and from peers by
94
+ * id. It is the rendezvous side-channel over which the WebRTC handshake flows;
95
+ * the concrete implementation (websocket, room, in-memory bus) is out of scope
96
+ * for this package. Tests provide an in-memory pair.
97
+ */
98
+ export interface SignalingTransport {
99
+ /** This endpoint's own peer id. */
100
+ readonly localId: string;
101
+ /** Send a signaling message to a specific peer. */
102
+ send(to: string, msg: SignalingMessage): void;
103
+ /** Subscribe to inbound signaling messages; returns an unsubscribe fn. */
104
+ onMessage(handler: (from: string, msg: SignalingMessage) => void): () => void;
105
+ }
106
+ /** Default ICE servers (public STUN servers). */
107
+ export declare const DEFAULT_ICE_SERVERS: RTCIceServer[];
108
+ /**
109
+ * Information about a participant in a room.
110
+ * Relocated from `@statewalker/vcs-port-livekit`.
111
+ */
112
+ export interface ParticipantInfo {
113
+ /** Unique identity string */
114
+ identity: string;
115
+ /** Display name (may be empty) */
116
+ name: string;
117
+ /** Whether the participant is currently connected */
118
+ connected: boolean;
119
+ }
120
+ /**
121
+ * Narrow structural view of a LiveKit `Room`. Kept structural (rather than a
122
+ * hard `import` of `livekit-client`) so the vendor stays an *optional*
123
+ * peerDependency and tests can supply a mock without installing it. A real
124
+ * `livekit-client` `Room` satisfies this shape.
125
+ */
126
+ export interface RoomParticipantLike {
127
+ identity: string;
128
+ name?: string;
129
+ }
130
+ export interface RoomLocalParticipantLike {
131
+ publishData(data: Uint8Array, opts?: {
132
+ reliable?: boolean;
133
+ destinationIdentities?: string[];
134
+ }): Promise<void>;
135
+ }
136
+ export interface RoomLike {
137
+ connect(url: string, token: string): Promise<void>;
138
+ disconnect(): Promise<void>;
139
+ readonly remoteParticipants: Map<string, RoomParticipantLike>;
140
+ readonly localParticipant: RoomLocalParticipantLike;
141
+ on(event: string, cb: (...args: unknown[]) => void): unknown;
142
+ off(event: string, cb: (...args: unknown[]) => void): unknown;
143
+ }
144
+ /** Options for a {@link RoomManager}. */
145
+ export interface RoomManagerOptions {
146
+ /** Room server URL (e.g. "ws://localhost:7880"). */
147
+ url: string;
148
+ /** Resolve an access token for a given room name (out of scope: token issuer). */
149
+ getToken: (room: string) => Promise<string>;
150
+ /** Room factory. Production: `() => new Room()` from `livekit-client`. */
151
+ roomFactory: () => RoomLike;
152
+ }
153
+ /** LiveKit `RoomEvent` string values used here (avoids a runtime vendor import). */
154
+ export declare const ROOM_EVENT: {
155
+ readonly participantConnected: "participantConnected";
156
+ readonly participantDisconnected: "participantDisconnected";
157
+ readonly dataReceived: "dataReceived";
158
+ };
159
+ //# sourceMapp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IAC5C,0EAA0E;IAC1E,WAAW,EAAE,MAAM,QAAQ,CAAC;CAC7B;AAED,oFAAoF;AACpF,eAAO,MAAM,UAAU;aACrB,oBAAoB,EAAE,sBAAsB;aAC5C,uBAAuB,EAAE,yBAAyB;aAClD,YAAY,EAAE,cAAc;CACpB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@statewalker/webrun-streams-signaling",
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Generic P2P signaling/connection-setup (PeerManager, QrSignaling, RoomManager) yielding webrun-streams ByteChannels",
7
+ "homepage": "https://github.com/statewalker/webrun-wire",
8
+ "author": {
9
+ "name": "Mikhail Kotelnikov",
10
+ "email": "mikhail.kotelnikov@gmail.com"
11
+ },
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git@github.com:statewalker/webrun-wire.git",
16
+ "directory": "packages/webrun-streams-signaling"
17
+ },
18
+ "exports": {
19
+ ".": "./src/index.ts"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "src"
24
+ ],
25
+ "dependencies": {
26
+ "@statewalker/webrun-streams": "0.1.1"
27
+ },
28
+ "peerDependencies": {
29
+ "livekit-client": "^2.18.3"
30
+ },
31
+ "peerDependenciesMeta": {
32
+ "livekit-client": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^26.2.0",
38
+ "livekit-client": "^2.18.3",
39
+ "rimraf": "^6.1.3",
40
+ "rolldown": "^1.2.4",
41
+ "typescript": "^7.0.2",
42
+ "vitest": "^4.1.10"
43
+ },
44
+ "sideEffects": false,
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
50
+ "test": "vitest run",
51
+ "lint": "biome check src tests"
52
+ }
53
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * ByteChannel adapters — the MessagePort→ByteChannel-style shims the relocation
3
+ * requires. The original `vcs-port-*` helpers surfaced an established
4
+ * connection as a Web `MessagePort` (via the out-of-scope `datachannel-port` /
5
+ * `livekit-port` byte bridges); here the established primitive is wrapped
6
+ * *directly* as a webrun-streams {@link ByteChannel} so the byte transport +
7
+ * multiplexing (`emulateMux`) can run on top.
8
+ */
9
+ import type { ByteChannel } from "@statewalker/webrun-streams";
10
+ import { makeByteQueue, toBytes } from "./byte-queue.js";
11
+ import type { RoomLike } from "./types.js";
12
+ import { ROOM_EVENT } from "./types.js";
13
+
14
+ /**
15
+ * Wrap an established `RTCDataChannel` as a {@link ByteChannel}. Outbound bytes
16
+ * go through `channel.send`; inbound `message` events feed `recv`.
17
+ */
18
+ export function byteChannelFromDataChannel(channel: RTCDataChannel): ByteChannel {
19
+ const queue = makeByteQueue();
20
+ let closedResolve!: () => void;
21
+ const closed = new Promise<void>((r) => {
22
+ closedResolve = r;
23
+ });
24
+
25
+ const onMessage = (ev: MessageEvent): void => queue.push(toBytes(ev.data));
26
+ const onClose = (): void => {
27
+ queue.done();
28
+ closedResolve();
29
+ };
30
+
31
+ channel.binaryType = "arraybuffer";
32
+ channel.addEventListener("message", onMessage as EventListener);
33
+ channel.addEventListener("close", onClose as EventListener);
34
+
35
+ return {
36
+ send(bytes) {
37
+ try {
38
+ // Cast around the DOM lib's `ArrayBufferView<ArrayBuffer>` overload:
39
+ // a plain `Uint8Array` is `ArrayBufferLike`-backed at the type level.
40
+ channel.send(bytes as unknown as ArrayBufferView<ArrayBuffer>);
41
+ } catch {
42
+ /* channel closed by peer */
43
+ }
44
+ },
45
+ recv: queue.recv,
46
+ 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();
57
+ },
58
+ };
59
+ }
60
+
61
+ /**
62
+ * 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.
66
+ */
67
+ export function byteChannelFromRoom(room: RoomLike, peerId: string): ByteChannel {
68
+ const queue = makeByteQueue();
69
+ let closedResolve!: () => void;
70
+ const closed = new Promise<void>((r) => {
71
+ closedResolve = r;
72
+ });
73
+
74
+ const onData = (...args: unknown[]): void => {
75
+ const payload = args[0];
76
+ const participant = args[1] as { identity?: string } | undefined;
77
+ if (participant && participant.identity !== peerId) return;
78
+ if (payload != null) queue.push(toBytes(payload));
79
+ };
80
+
81
+ room.on(ROOM_EVENT.dataReceived, onData);
82
+
83
+ return {
84
+ send(bytes) {
85
+ void room.localParticipant
86
+ .publishData(bytes, { reliable: true, destinationIdentities: [peerId] })
87
+ .catch(() => {
88
+ /* room closed */
89
+ });
90
+ },
91
+ recv: queue.recv,
92
+ closed,
93
+ close() {
94
+ room.off(ROOM_EVENT.dataReceived, onData);
95
+ queue.done();
96
+ closedResolve();
97
+ },
98
+ };
99
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Minimal eager push/pull byte queue backing the `recv` side of the
3
+ * {@link ByteChannel} adapters. "Eager" = bytes pushed before the consumer
4
+ * starts iterating are buffered (not dropped), which the signaling adapters
5
+ * need because a channel can receive data the instant it opens, before the
6
+ * caller wires up its `for await`.
7
+ */
8
+ export function makeByteQueue(): {
9
+ recv: AsyncIterable<Uint8Array>;
10
+ push: (bytes: Uint8Array) => void;
11
+ done: () => void;
12
+ } {
13
+ const chunks: Uint8Array[] = [];
14
+ let pending: ((r: IteratorResult<Uint8Array>) => void) | null = null;
15
+ let ended = false;
16
+
17
+ const push = (bytes: Uint8Array): void => {
18
+ if (ended) return;
19
+ if (pending) {
20
+ const resolve = pending;
21
+ pending = null;
22
+ resolve({ value: bytes, done: false });
23
+ } else {
24
+ chunks.push(bytes);
25
+ }
26
+ };
27
+
28
+ const done = (): void => {
29
+ if (ended) return;
30
+ ended = true;
31
+ if (pending) {
32
+ const resolve = pending;
33
+ pending = null;
34
+ resolve({ value: undefined, done: true } as IteratorResult<Uint8Array>);
35
+ }
36
+ };
37
+
38
+ const recv: AsyncIterable<Uint8Array> = {
39
+ [Symbol.asyncIterator]() {
40
+ return {
41
+ next(): Promise<IteratorResult<Uint8Array>> {
42
+ if (chunks.length > 0) {
43
+ return Promise.resolve({ value: chunks.shift() as Uint8Array, done: false });
44
+ }
45
+ if (ended) {
46
+ return Promise.resolve({ value: undefined, done: true } as IteratorResult<Uint8Array>);
47
+ }
48
+ return new Promise<IteratorResult<Uint8Array>>((resolve) => {
49
+ pending = resolve;
50
+ });
51
+ },
52
+ };
53
+ },
54
+ };
55
+
56
+ return { recv, push, done };
57
+ }
58
+
59
+ /** Coerce a message payload (Uint8Array / ArrayBuffer / view) to a Uint8Array copy. */
60
+ export function toBytes(data: unknown): Uint8Array {
61
+ if (data instanceof Uint8Array) return new Uint8Array(data);
62
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
63
+ if (ArrayBuffer.isView(data)) {
64
+ const view = data as ArrayBufferView;
65
+ return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
66
+ }
67
+ throw new TypeError("byte channel received a non-byte payload");
68
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @statewalker/webrun-streams-signaling
3
+ *
4
+ * Generic P2P signaling / connection-setup helpers, relocated from the retiring
5
+ * `@statewalker/vcs-port-{webrtc,livekit}` packages and adapted to yield
6
+ * webrun-streams {@link ByteChannel}s. Signaling here is *transport-setup only*:
7
+ * it establishes a peer connection and hands back an established channel; the
8
+ * byte transport + multiplexing is `@statewalker/webrun-streams`.
9
+ *
10
+ * - {@link PeerManager} — WebRTC peer discovery + connection over a signaling transport.
11
+ * - {@link QrSignaling} — serverless offer/answer exchange via QR strings.
12
+ * - {@link RoomManager} — LiveKit room membership + per-participant channels.
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+
17
+ export { byteChannelFromDataChannel, byteChannelFromRoom } from "./byte-channel.js";
18
+ export { PeerConnection } from "./peer-connection.js";
19
+ export { PeerManager, type PeerManagerOptions } from "./peer-manager.js";
20
+ export {
21
+ createCompressedSignal,
22
+ decodeSignal,
23
+ encodeSignal,
24
+ generateSessionId,
25
+ parseCompressedSignal,
26
+ QrSignaling,
27
+ type QrSignalingOptions,
28
+ } from "./qr-signaling.js";
29
+ export { RoomManager } from "./room-manager.js";
30
+ export * from "./types.js";