@yrzhao/aves-core 0.1.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.
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SignalingClient = void 0;
4
+ const EventEmitter_1 = require("./EventEmitter");
5
+ /**
6
+ * SignalingClient manages WebSocket connection and signaling message exchange
7
+ * Extends EventEmitter to provide event-driven communication
8
+ */
9
+ class SignalingClient extends EventEmitter_1.EventEmitter {
10
+ constructor(reconnectConfig) {
11
+ super();
12
+ this.ws = null;
13
+ this.reconnectAttempts = 0;
14
+ this.reconnectTimer = null;
15
+ this.url = "";
16
+ this.shouldReconnect = true;
17
+ this.pendingRequests = new Map();
18
+ this.reconnectConfig = reconnectConfig;
19
+ }
20
+ /**
21
+ * Connect to the signaling server
22
+ * @param url - WebSocket server URL
23
+ * @returns Promise that resolves when connected
24
+ */
25
+ connect(url) {
26
+ this.url = url;
27
+ this.shouldReconnect = true;
28
+ return new Promise((resolve, reject) => {
29
+ try {
30
+ this.ws = new WebSocket(url);
31
+ this.ws.onopen = () => {
32
+ this.reconnectAttempts = 0;
33
+ this.emit("stateChange", "connected");
34
+ resolve();
35
+ };
36
+ this.ws.onclose = () => {
37
+ this.emit("stateChange", "disconnected");
38
+ this.handleDisconnect();
39
+ };
40
+ this.ws.onerror = (error) => {
41
+ this.emit("error", new Error("WebSocket error"));
42
+ reject(new Error("WebSocket connection failed"));
43
+ };
44
+ this.ws.onmessage = (event) => {
45
+ this.handleMessage(event.data);
46
+ };
47
+ this.emit("stateChange", "connecting");
48
+ }
49
+ catch (error) {
50
+ reject(error);
51
+ }
52
+ });
53
+ }
54
+ /**
55
+ * Disconnect from the signaling server
56
+ */
57
+ disconnect() {
58
+ this.shouldReconnect = false;
59
+ if (this.reconnectTimer !== null) {
60
+ clearTimeout(this.reconnectTimer);
61
+ this.reconnectTimer = null;
62
+ }
63
+ if (this.ws) {
64
+ this.ws.close();
65
+ this.ws = null;
66
+ }
67
+ this.emit("stateChange", "disconnected");
68
+ }
69
+ /**
70
+ * Handle WebSocket disconnection and attempt reconnection
71
+ */
72
+ handleDisconnect() {
73
+ this.ws = null;
74
+ if (!this.shouldReconnect) {
75
+ return;
76
+ }
77
+ if (this.reconnectAttempts < this.reconnectConfig.maxAttempts) {
78
+ this.reconnectAttempts++;
79
+ this.reconnectTimer = setTimeout(() => {
80
+ this.connect(this.url).catch((error) => {
81
+ // Connection failed, will retry on next attempt
82
+ });
83
+ }, this.reconnectConfig.delay);
84
+ }
85
+ else {
86
+ this.emit("error", new Error(`Max reconnection attempts (${this.reconnectConfig.maxAttempts}) reached`));
87
+ }
88
+ }
89
+ /**
90
+ * Handle incoming WebSocket messages
91
+ * @param data - Raw message data
92
+ */
93
+ handleMessage(data) {
94
+ try {
95
+ const message = JSON.parse(data);
96
+ switch (message.type) {
97
+ case "room-created":
98
+ this.resolvePendingRequest("create-room", message.roomId);
99
+ break;
100
+ case "room-joined":
101
+ this.resolvePendingRequest("join-room", message.participants);
102
+ break;
103
+ case "user-joined":
104
+ this.emit("userJoined", message.user);
105
+ break;
106
+ case "user-left":
107
+ this.emit("userLeft", message.userId);
108
+ break;
109
+ case "offer":
110
+ this.emit("offer", message.fromId, message.offer);
111
+ break;
112
+ case "answer":
113
+ this.emit("answer", message.fromId, message.answer);
114
+ break;
115
+ case "ice-candidate":
116
+ this.emit("iceCandidate", message.fromId, message.candidate);
117
+ break;
118
+ case "error":
119
+ this.rejectPendingRequests(new Error(message.message));
120
+ this.emit("error", new Error(message.message));
121
+ break;
122
+ }
123
+ }
124
+ catch (error) {
125
+ this.emit("error", new Error("Failed to parse signaling message"));
126
+ }
127
+ }
128
+ /**
129
+ * Send a message to the signaling server
130
+ * @param message - Signaling message to send
131
+ */
132
+ send(message) {
133
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
134
+ throw new Error("WebSocket is not connected");
135
+ }
136
+ this.ws.send(JSON.stringify(message));
137
+ }
138
+ /**
139
+ * Create a new room
140
+ * @returns Promise that resolves with the room ID
141
+ */
142
+ createRoom() {
143
+ return new Promise((resolve, reject) => {
144
+ this.pendingRequests.set("create-room", { resolve, reject });
145
+ try {
146
+ this.send({ type: "create-room" });
147
+ }
148
+ catch (error) {
149
+ this.pendingRequests.delete("create-room");
150
+ reject(error);
151
+ }
152
+ });
153
+ }
154
+ /**
155
+ * Join an existing room
156
+ * @param roomId - Room ID to join
157
+ * @param userId - User ID
158
+ * @param userName - User name
159
+ * @returns Promise that resolves with the list of participants
160
+ */
161
+ joinRoom(roomId, userId, userName) {
162
+ return new Promise((resolve, reject) => {
163
+ this.pendingRequests.set("join-room", { resolve, reject });
164
+ try {
165
+ this.send({ type: "join-room", roomId, userId, userName });
166
+ }
167
+ catch (error) {
168
+ this.pendingRequests.delete("join-room");
169
+ reject(error);
170
+ }
171
+ });
172
+ }
173
+ /**
174
+ * Leave the current room
175
+ */
176
+ leaveRoom() {
177
+ // In the current design, leaving is handled by disconnecting
178
+ // or the server will handle it when the connection closes
179
+ // This method is here for API completeness
180
+ }
181
+ /**
182
+ * Send an offer to a peer
183
+ * @param targetId - Target peer ID
184
+ * @param fromId - Sender ID
185
+ * @param offer - RTC session description (offer)
186
+ */
187
+ sendOffer(targetId, fromId, offer) {
188
+ this.send({ type: "offer", targetId, fromId, offer });
189
+ }
190
+ /**
191
+ * Send an answer to a peer
192
+ * @param targetId - Target peer ID
193
+ * @param fromId - Sender ID
194
+ * @param answer - RTC session description (answer)
195
+ */
196
+ sendAnswer(targetId, fromId, answer) {
197
+ this.send({ type: "answer", targetId, fromId, answer });
198
+ }
199
+ /**
200
+ * Send an ICE candidate to a peer
201
+ * @param targetId - Target peer ID
202
+ * @param fromId - Sender ID
203
+ * @param candidate - ICE candidate
204
+ */
205
+ sendIceCandidate(targetId, fromId, candidate) {
206
+ this.send({ type: "ice-candidate", targetId, fromId, candidate });
207
+ }
208
+ /**
209
+ * Resolve a pending request
210
+ * @param requestType - Type of request to resolve
211
+ * @param value - Value to resolve with
212
+ */
213
+ resolvePendingRequest(requestType, value) {
214
+ const request = this.pendingRequests.get(requestType);
215
+ if (request) {
216
+ request.resolve(value);
217
+ this.pendingRequests.delete(requestType);
218
+ }
219
+ }
220
+ /**
221
+ * Reject all pending requests
222
+ * @param error - Error to reject with
223
+ */
224
+ rejectPendingRequests(error) {
225
+ for (const [key, request] of this.pendingRequests) {
226
+ request.reject(error);
227
+ }
228
+ this.pendingRequests.clear();
229
+ }
230
+ }
231
+ exports.SignalingClient = SignalingClient;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * WebRTCManager - Manages WebRTC PeerConnections and DataChannels
3
+ *
4
+ * This class handles the low-level WebRTC connection management including:
5
+ * - Creating and managing RTCPeerConnection instances
6
+ * - Creating and managing RTCDataChannel instances
7
+ * - Handling ICE candidate exchange
8
+ * - Serializing and deserializing messages
9
+ * - Managing connection lifecycle and cleanup
10
+ */
11
+ export declare class WebRTCManager {
12
+ private peerConnections;
13
+ private dataChannels;
14
+ private iceServers;
15
+ private messageCallbacks;
16
+ private connectionStateCallbacks;
17
+ private dataChannelStateCallbacks;
18
+ private iceCandidateCallbacks;
19
+ constructor(iceServers: RTCIceServer[]);
20
+ /**
21
+ * Create a new PeerConnection for the specified peer
22
+ * If a connection already exists, returns the existing connection
23
+ */
24
+ createPeerConnection(peerId: string): RTCPeerConnection;
25
+ /**
26
+ * Create an offer for the specified peer
27
+ * This also creates the DataChannel (offer side creates the channel)
28
+ */
29
+ createOffer(peerId: string): Promise<RTCSessionDescriptionInit>;
30
+ /**
31
+ * Create an answer for the specified peer
32
+ * Sets up the remote offer and creates an answer
33
+ */
34
+ createAnswer(peerId: string, offer: RTCSessionDescriptionInit): Promise<RTCSessionDescriptionInit>;
35
+ /**
36
+ * Set the remote answer for the specified peer
37
+ */
38
+ setRemoteAnswer(peerId: string, answer: RTCSessionDescriptionInit): Promise<void>;
39
+ /**
40
+ * Add an ICE candidate for the specified peer
41
+ */
42
+ addIceCandidate(peerId: string, candidate: RTCIceCandidateInit): Promise<void>;
43
+ /**
44
+ * Register a callback for ICE candidates from the specified peer
45
+ */
46
+ onIceCandidate(peerId: string, callback: (candidate: RTCIceCandidateInit) => void): void;
47
+ /**
48
+ * Register a callback for connection state changes
49
+ */
50
+ onConnectionStateChange(peerId: string, callback: (state: RTCPeerConnectionState) => void): void;
51
+ /**
52
+ * Register a callback for DataChannel state changes
53
+ */
54
+ onDataChannelStateChange(peerId: string, callback: (state: RTCDataChannelState) => void): void;
55
+ /**
56
+ * Register a callback for incoming messages
57
+ */
58
+ onMessage(callback: (peerId: string, message: any) => void): void;
59
+ /**
60
+ * Setup DataChannel event handlers
61
+ */
62
+ private setupDataChannel;
63
+ /**
64
+ * Send a message to all connected peers
65
+ * Throws error if any DataChannel is not ready
66
+ */
67
+ sendMessage(message: any): void;
68
+ /**
69
+ * Send a message to a specific peer
70
+ * Throws error if DataChannel is not ready
71
+ */
72
+ sendMessageToPeer(peerId: string, message: any): void;
73
+ /**
74
+ * Close the connection with a specific peer
75
+ */
76
+ closePeerConnection(peerId: string): void;
77
+ /**
78
+ * Close all connections and clean up resources
79
+ */
80
+ closeAll(): void;
81
+ /**
82
+ * Get all active peer IDs
83
+ */
84
+ getActivePeers(): string[];
85
+ /**
86
+ * Check if connected to a specific peer
87
+ */
88
+ isConnected(peerId: string): boolean;
89
+ /**
90
+ * Check if DataChannel is ready for a specific peer
91
+ */
92
+ isDataChannelReady(peerId: string): boolean;
93
+ }
@@ -0,0 +1,308 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebRTCManager = void 0;
4
+ /**
5
+ * WebRTCManager - Manages WebRTC PeerConnections and DataChannels
6
+ *
7
+ * This class handles the low-level WebRTC connection management including:
8
+ * - Creating and managing RTCPeerConnection instances
9
+ * - Creating and managing RTCDataChannel instances
10
+ * - Handling ICE candidate exchange
11
+ * - Serializing and deserializing messages
12
+ * - Managing connection lifecycle and cleanup
13
+ */
14
+ class WebRTCManager {
15
+ constructor(iceServers) {
16
+ this.peerConnections = new Map();
17
+ this.dataChannels = new Map();
18
+ this.iceServers = iceServers;
19
+ this.messageCallbacks = new Set();
20
+ this.connectionStateCallbacks = new Map();
21
+ this.dataChannelStateCallbacks = new Map();
22
+ this.iceCandidateCallbacks = new Map();
23
+ }
24
+ /**
25
+ * Create a new PeerConnection for the specified peer
26
+ * If a connection already exists, returns the existing connection
27
+ */
28
+ createPeerConnection(peerId) {
29
+ if (this.peerConnections.has(peerId)) {
30
+ console.log(`[WebRTCManager] Reusing existing PeerConnection for ${peerId}`);
31
+ return this.peerConnections.get(peerId);
32
+ }
33
+ console.log(`[WebRTCManager] Creating new PeerConnection for ${peerId}`);
34
+ const pc = new RTCPeerConnection({
35
+ iceServers: this.iceServers,
36
+ });
37
+ this.peerConnections.set(peerId, pc);
38
+ // Monitor connection state changes
39
+ pc.onconnectionstatechange = () => {
40
+ console.log(`[WebRTCManager] Connection state for ${peerId}: ${pc.connectionState}`);
41
+ const callbacks = this.connectionStateCallbacks.get(peerId);
42
+ if (callbacks) {
43
+ callbacks.forEach((callback) => callback(pc.connectionState));
44
+ }
45
+ // Auto-cleanup on failed/closed/disconnected states
46
+ if (pc.connectionState === "failed" ||
47
+ pc.connectionState === "closed" ||
48
+ pc.connectionState === "disconnected") {
49
+ this.closePeerConnection(peerId);
50
+ }
51
+ };
52
+ return pc;
53
+ }
54
+ /**
55
+ * Create an offer for the specified peer
56
+ * This also creates the DataChannel (offer side creates the channel)
57
+ */
58
+ async createOffer(peerId) {
59
+ const pc = this.peerConnections.get(peerId);
60
+ if (!pc) {
61
+ throw new Error(`No peer connection found for ${peerId}`);
62
+ }
63
+ console.log(`[WebRTCManager] Creating offer for ${peerId}, current state: ${pc.signalingState}`);
64
+ // Create DataChannel (offer side creates it)
65
+ const dataChannel = pc.createDataChannel("data");
66
+ this.setupDataChannel(peerId, dataChannel);
67
+ const offer = await pc.createOffer();
68
+ await pc.setLocalDescription(offer);
69
+ console.log(`[WebRTCManager] Created offer for ${peerId}, new state: ${pc.signalingState}`);
70
+ return offer;
71
+ }
72
+ /**
73
+ * Create an answer for the specified peer
74
+ * Sets up the remote offer and creates an answer
75
+ */
76
+ async createAnswer(peerId, offer) {
77
+ const pc = this.peerConnections.get(peerId);
78
+ if (!pc) {
79
+ throw new Error(`No peer connection found for ${peerId}`);
80
+ }
81
+ // Listen for DataChannel (answer side receives it)
82
+ pc.ondatachannel = (event) => {
83
+ this.setupDataChannel(peerId, event.channel);
84
+ };
85
+ console.log(`[WebRTCManager] Creating answer for ${peerId}, current state: ${pc.signalingState}`);
86
+ await pc.setRemoteDescription(new RTCSessionDescription(offer));
87
+ console.log(`[WebRTCManager] Set remote offer for ${peerId}, new state: ${pc.signalingState}`);
88
+ const answer = await pc.createAnswer();
89
+ await pc.setLocalDescription(answer);
90
+ console.log(`[WebRTCManager] Created answer for ${peerId}, new state: ${pc.signalingState}`);
91
+ return answer;
92
+ }
93
+ /**
94
+ * Set the remote answer for the specified peer
95
+ */
96
+ async setRemoteAnswer(peerId, answer) {
97
+ const pc = this.peerConnections.get(peerId);
98
+ if (!pc) {
99
+ throw new Error(`No peer connection found for ${peerId}`);
100
+ }
101
+ console.log(`[WebRTCManager] Setting remote answer for ${peerId}, current state: ${pc.signalingState}`);
102
+ // Check if we're in the correct state to set remote answer
103
+ if (pc.signalingState !== "have-local-offer") {
104
+ throw new Error(`Cannot set remote answer for ${peerId}: wrong state ${pc.signalingState}, expected have-local-offer`);
105
+ }
106
+ await pc.setRemoteDescription(new RTCSessionDescription(answer));
107
+ console.log(`[WebRTCManager] Successfully set remote answer for ${peerId}`);
108
+ }
109
+ /**
110
+ * Add an ICE candidate for the specified peer
111
+ */
112
+ async addIceCandidate(peerId, candidate) {
113
+ const pc = this.peerConnections.get(peerId);
114
+ if (!pc) {
115
+ throw new Error(`No peer connection found for ${peerId}`);
116
+ }
117
+ try {
118
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
119
+ }
120
+ catch (error) {
121
+ console.error(`Error adding ICE candidate for ${peerId}:`, error);
122
+ throw error;
123
+ }
124
+ }
125
+ /**
126
+ * Register a callback for ICE candidates from the specified peer
127
+ */
128
+ onIceCandidate(peerId, callback) {
129
+ const pc = this.peerConnections.get(peerId);
130
+ if (!pc) {
131
+ throw new Error(`No peer connection found for ${peerId}`);
132
+ }
133
+ if (!this.iceCandidateCallbacks.has(peerId)) {
134
+ this.iceCandidateCallbacks.set(peerId, new Set());
135
+ }
136
+ this.iceCandidateCallbacks.get(peerId).add(callback);
137
+ pc.onicecandidate = (event) => {
138
+ if (event.candidate) {
139
+ const callbacks = this.iceCandidateCallbacks.get(peerId);
140
+ if (callbacks) {
141
+ callbacks.forEach((cb) => cb(event.candidate.toJSON()));
142
+ }
143
+ }
144
+ };
145
+ }
146
+ /**
147
+ * Register a callback for connection state changes
148
+ */
149
+ onConnectionStateChange(peerId, callback) {
150
+ if (!this.connectionStateCallbacks.has(peerId)) {
151
+ this.connectionStateCallbacks.set(peerId, new Set());
152
+ }
153
+ this.connectionStateCallbacks.get(peerId).add(callback);
154
+ }
155
+ /**
156
+ * Register a callback for DataChannel state changes
157
+ */
158
+ onDataChannelStateChange(peerId, callback) {
159
+ if (!this.dataChannelStateCallbacks.has(peerId)) {
160
+ this.dataChannelStateCallbacks.set(peerId, new Set());
161
+ }
162
+ this.dataChannelStateCallbacks.get(peerId).add(callback);
163
+ }
164
+ /**
165
+ * Register a callback for incoming messages
166
+ */
167
+ onMessage(callback) {
168
+ this.messageCallbacks.add(callback);
169
+ }
170
+ /**
171
+ * Setup DataChannel event handlers
172
+ */
173
+ setupDataChannel(peerId, dataChannel) {
174
+ this.dataChannels.set(peerId, dataChannel);
175
+ dataChannel.onopen = () => {
176
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
177
+ if (callbacks) {
178
+ callbacks.forEach((callback) => callback(dataChannel.readyState));
179
+ }
180
+ };
181
+ dataChannel.onclose = () => {
182
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
183
+ if (callbacks) {
184
+ callbacks.forEach((callback) => callback(dataChannel.readyState));
185
+ }
186
+ this.dataChannels.delete(peerId);
187
+ };
188
+ dataChannel.onerror = (error) => {
189
+ console.error(`DataChannel error with ${peerId}:`, error);
190
+ };
191
+ dataChannel.onmessage = (event) => {
192
+ try {
193
+ // Deserialize JSON message
194
+ const message = JSON.parse(event.data);
195
+ this.messageCallbacks.forEach((callback) => callback(peerId, message));
196
+ }
197
+ catch (error) {
198
+ // Log error but don't interrupt connection
199
+ console.error(`Failed to parse message from ${peerId}:`, error);
200
+ }
201
+ };
202
+ }
203
+ /**
204
+ * Send a message to all connected peers
205
+ * Throws error if any DataChannel is not ready
206
+ */
207
+ sendMessage(message) {
208
+ const errors = [];
209
+ this.dataChannels.forEach((dataChannel, peerId) => {
210
+ if (dataChannel.readyState === "open") {
211
+ try {
212
+ // Serialize message to JSON
213
+ const serialized = JSON.stringify(message);
214
+ dataChannel.send(serialized);
215
+ }
216
+ catch (error) {
217
+ console.error(`Failed to send message to ${peerId}:`, error);
218
+ errors.push(peerId);
219
+ }
220
+ }
221
+ else {
222
+ errors.push(peerId);
223
+ }
224
+ });
225
+ if (errors.length > 0) {
226
+ throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
227
+ }
228
+ }
229
+ /**
230
+ * Send a message to a specific peer
231
+ * Throws error if DataChannel is not ready
232
+ */
233
+ sendMessageToPeer(peerId, message) {
234
+ const dataChannel = this.dataChannels.get(peerId);
235
+ if (!dataChannel) {
236
+ throw new Error(`No DataChannel found for ${peerId}`);
237
+ }
238
+ if (dataChannel.readyState !== "open") {
239
+ throw new Error(`DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`);
240
+ }
241
+ try {
242
+ // Serialize message to JSON
243
+ const serialized = JSON.stringify(message);
244
+ dataChannel.send(serialized);
245
+ }
246
+ catch (error) {
247
+ console.error(`Failed to send message to ${peerId}:`, error);
248
+ throw error;
249
+ }
250
+ }
251
+ /**
252
+ * Close the connection with a specific peer
253
+ */
254
+ closePeerConnection(peerId) {
255
+ const dataChannel = this.dataChannels.get(peerId);
256
+ if (dataChannel) {
257
+ dataChannel.close();
258
+ this.dataChannels.delete(peerId);
259
+ }
260
+ const pc = this.peerConnections.get(peerId);
261
+ if (pc) {
262
+ pc.close();
263
+ this.peerConnections.delete(peerId);
264
+ }
265
+ // Clean up callbacks
266
+ this.connectionStateCallbacks.delete(peerId);
267
+ this.dataChannelStateCallbacks.delete(peerId);
268
+ this.iceCandidateCallbacks.delete(peerId);
269
+ }
270
+ /**
271
+ * Close all connections and clean up resources
272
+ */
273
+ closeAll() {
274
+ this.dataChannels.forEach((dataChannel) => {
275
+ dataChannel.close();
276
+ });
277
+ this.dataChannels.clear();
278
+ this.peerConnections.forEach((pc) => {
279
+ pc.close();
280
+ });
281
+ this.peerConnections.clear();
282
+ this.messageCallbacks.clear();
283
+ this.connectionStateCallbacks.clear();
284
+ this.dataChannelStateCallbacks.clear();
285
+ this.iceCandidateCallbacks.clear();
286
+ }
287
+ /**
288
+ * Get all active peer IDs
289
+ */
290
+ getActivePeers() {
291
+ return Array.from(this.peerConnections.keys());
292
+ }
293
+ /**
294
+ * Check if connected to a specific peer
295
+ */
296
+ isConnected(peerId) {
297
+ const pc = this.peerConnections.get(peerId);
298
+ return pc?.connectionState === "connected";
299
+ }
300
+ /**
301
+ * Check if DataChannel is ready for a specific peer
302
+ */
303
+ isDataChannelReady(peerId) {
304
+ const dataChannel = this.dataChannels.get(peerId);
305
+ return dataChannel?.readyState === "open";
306
+ }
307
+ }
308
+ exports.WebRTCManager = WebRTCManager;