@yrzhao/aves-core 0.1.0 → 0.2.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.
@@ -5,25 +5,17 @@ const EventEmitter_1 = require("./EventEmitter");
5
5
  const WebRTCManager_1 = require("./WebRTCManager");
6
6
  const SignalingClient_1 = require("./SignalingClient");
7
7
  /**
8
- * AvesClient - Main client class for WebRTC communication
9
- *
10
- * This class coordinates WebRTCManager and SignalingClient to provide
11
- * a simple API for WebRTC-based real-time communication.
12
- *
13
- * Features:
14
- * - Room management (create, join, leave)
15
- * - Automatic WebRTC connection establishment
16
- * - Message sending and receiving
17
- * - Connection state monitoring
18
- * - Automatic reconnection
8
+ * AvesClient - Main client class for WebRTC communication.
19
9
  */
20
10
  class AvesClient extends EventEmitter_1.EventEmitter {
21
11
  constructor(config) {
22
12
  super();
23
13
  this.currentRoomId = null;
24
14
  this.currentUserId = null;
15
+ this.currentUserName = null;
25
16
  this.participants = new Map();
26
- // Apply default configuration
17
+ this.preparedPeers = new Set();
18
+ this.shouldRestoreSession = false;
27
19
  const maxAttempts = config.reconnect?.maxAttempts ?? 5;
28
20
  const delay = config.reconnect?.delay ?? 3000;
29
21
  this.config = {
@@ -31,74 +23,55 @@ class AvesClient extends EventEmitter_1.EventEmitter {
31
23
  iceServers: config.iceServers || [
32
24
  { urls: "stun:stun.l.google.com:19302" },
33
25
  ],
26
+ fileChunkSize: config.fileChunkSize ?? 16 * 1024,
34
27
  reconnect: {
35
28
  maxAttempts,
36
29
  delay,
37
30
  },
38
31
  debug: config.debug ?? false,
39
32
  };
40
- // Initialize WebRTC manager
41
- this.webrtcManager = new WebRTCManager_1.WebRTCManager(this.config.iceServers);
42
- // Initialize signaling client
33
+ this.webrtcManager = new WebRTCManager_1.WebRTCManager(this.config.iceServers, this.config.fileChunkSize);
43
34
  this.signalingClient = new SignalingClient_1.SignalingClient({
44
35
  maxAttempts,
45
36
  delay,
46
37
  });
47
- // Setup event forwarding and coordination
48
38
  this.setupEventHandlers();
49
39
  }
50
- /**
51
- * Setup event handlers to coordinate between components
52
- */
53
40
  setupEventHandlers() {
54
- // Forward signaling state changes
55
41
  this.signalingClient.on("stateChange", (state) => {
56
42
  this.emit("signalingStateChange", state);
43
+ if (state === "disconnected" &&
44
+ this.currentRoomId &&
45
+ this.currentUserId &&
46
+ this.currentUserName) {
47
+ this.shouldRestoreSession = true;
48
+ }
49
+ if (state === "connected" && this.shouldRestoreSession) {
50
+ this.shouldRestoreSession = false;
51
+ void this.restoreRoomSession();
52
+ }
57
53
  });
58
- // Forward errors
59
54
  this.signalingClient.on("error", (error) => {
60
55
  this.emit("error", error);
61
56
  });
62
- // Handle user joined - establish WebRTC connection
63
57
  this.signalingClient.on("userJoined", async (user) => {
64
58
  this.participants.set(user.id, user);
65
59
  this.emit("userJoined", user);
66
- // Initiate WebRTC connection only if our ID is smaller (to avoid both sides initiating)
67
60
  if (this.currentUserId && this.currentUserId < user.id) {
68
61
  await this.initiateConnection(user.id);
69
62
  }
70
63
  });
71
- // Handle user left - cleanup connection
72
64
  this.signalingClient.on("userLeft", (userId) => {
73
65
  this.participants.delete(userId);
66
+ this.preparedPeers.delete(userId);
74
67
  this.webrtcManager.closePeerConnection(userId);
75
68
  this.emit("userLeft", userId);
76
69
  });
77
- // Handle incoming offer - create answer
78
70
  this.signalingClient.on("offer", async (fromId, offer) => {
79
71
  try {
80
- console.log(`[AvesClient] Received offer from ${fromId}`);
81
- const pc = this.webrtcManager.createPeerConnection(fromId);
82
- // Setup ICE candidate forwarding
83
- this.webrtcManager.onIceCandidate(fromId, (candidate) => {
84
- if (this.currentUserId) {
85
- this.signalingClient.sendIceCandidate(fromId, this.currentUserId, candidate);
86
- }
87
- });
88
- // Setup connection state monitoring
89
- this.webrtcManager.onConnectionStateChange(fromId, (state) => {
90
- console.log(`[AvesClient] Connection state with ${fromId}: ${state}`);
91
- this.emit("connectionStateChange", fromId, state);
92
- });
93
- // Setup DataChannel state monitoring
94
- this.webrtcManager.onDataChannelStateChange(fromId, (state) => {
95
- console.log(`[AvesClient] DataChannel state with ${fromId}: ${state}`);
96
- this.emit("dataChannelStateChange", fromId, state);
97
- });
98
- // Create and send answer
72
+ this.preparePeerConnection(fromId);
99
73
  const answer = await this.webrtcManager.createAnswer(fromId, offer);
100
74
  if (this.currentUserId) {
101
- console.log(`[AvesClient] Sending answer to ${fromId} from ${this.currentUserId}`);
102
75
  this.signalingClient.sendAnswer(fromId, this.currentUserId, answer);
103
76
  }
104
77
  }
@@ -106,19 +79,14 @@ class AvesClient extends EventEmitter_1.EventEmitter {
106
79
  this.emit("error", new Error(`Failed to handle offer from ${fromId}: ${error}`));
107
80
  }
108
81
  });
109
- // Handle incoming answer - set remote description
110
82
  this.signalingClient.on("answer", async (fromId, answer) => {
111
83
  try {
112
- console.log(`[AvesClient] Received answer from ${fromId}`);
113
84
  await this.webrtcManager.setRemoteAnswer(fromId, answer);
114
- console.log(`[AvesClient] Successfully set remote answer from ${fromId}`);
115
85
  }
116
86
  catch (error) {
117
- console.error(`[AvesClient] Failed to handle answer from ${fromId}:`, error);
118
87
  this.emit("error", new Error(`Failed to handle answer from ${fromId}: ${error}`));
119
88
  }
120
89
  });
121
- // Handle incoming ICE candidate
122
90
  this.signalingClient.on("iceCandidate", async (fromId, candidate) => {
123
91
  try {
124
92
  await this.webrtcManager.addIceCandidate(fromId, candidate);
@@ -127,38 +95,86 @@ class AvesClient extends EventEmitter_1.EventEmitter {
127
95
  this.emit("error", new Error(`Failed to add ICE candidate from ${fromId}: ${error}`));
128
96
  }
129
97
  });
130
- // Forward messages from WebRTC
131
98
  this.webrtcManager.onMessage((peerId, message) => {
132
99
  this.emit("message", peerId, message);
133
100
  });
101
+ this.webrtcManager.onFileTransferStarted((peerId, info) => {
102
+ this.emit("fileTransferStarted", peerId, info);
103
+ });
104
+ this.webrtcManager.onFileTransferProgress((peerId, progress) => {
105
+ this.emit("fileTransferProgress", peerId, progress);
106
+ });
107
+ this.webrtcManager.onFileTransferCompleted((peerId, result) => {
108
+ this.emit("fileTransferCompleted", peerId, result);
109
+ });
110
+ this.webrtcManager.onFileTransferFailed((peerId, info, error) => {
111
+ this.emit("fileTransferFailed", peerId, info, error);
112
+ });
113
+ this.webrtcManager.onRemoteAudioTrack((peerId, stream, track) => {
114
+ this.emit("remoteAudioTrack", peerId, stream, track);
115
+ });
116
+ this.webrtcManager.onLocalAudioStateChange((state) => {
117
+ this.emit("localAudioStateChange", state);
118
+ });
134
119
  }
135
- /**
136
- * Initiate a WebRTC connection with a peer (as offerer)
137
- */
138
- async initiateConnection(peerId) {
120
+ async restoreRoomSession() {
121
+ if (!this.currentRoomId || !this.currentUserId || !this.currentUserName) {
122
+ return;
123
+ }
139
124
  try {
140
- console.log(`[AvesClient] Initiating connection to ${peerId} from ${this.currentUserId}`);
141
- const pc = this.webrtcManager.createPeerConnection(peerId);
142
- // Setup ICE candidate forwarding
143
- this.webrtcManager.onIceCandidate(peerId, (candidate) => {
144
- if (this.currentUserId) {
145
- this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
125
+ this.webrtcManager.closeAll();
126
+ this.participants.clear();
127
+ this.preparedPeers.clear();
128
+ const joinResult = await this.signalingClient.joinRoom(this.currentRoomId, this.currentUserId, this.currentUserName);
129
+ this.currentUserId = joinResult.userId;
130
+ const participants = joinResult.participants;
131
+ this.participants.clear();
132
+ participants.forEach((participant) => this.participants.set(participant.id, participant));
133
+ for (const participant of participants) {
134
+ if (participant.id !== this.currentUserId &&
135
+ this.currentUserId < participant.id) {
136
+ await this.initiateConnection(participant.id);
146
137
  }
147
- });
148
- // Setup connection state monitoring
149
- this.webrtcManager.onConnectionStateChange(peerId, (state) => {
150
- console.log(`[AvesClient] Connection state with ${peerId}: ${state}`);
151
- this.emit("connectionStateChange", peerId, state);
152
- });
153
- // Setup DataChannel state monitoring
154
- this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
155
- console.log(`[AvesClient] DataChannel state with ${peerId}: ${state}`);
156
- this.emit("dataChannelStateChange", peerId, state);
157
- });
158
- // Create and send offer
138
+ }
139
+ }
140
+ catch (error) {
141
+ this.currentRoomId = null;
142
+ this.currentUserId = null;
143
+ this.currentUserName = null;
144
+ this.participants.clear();
145
+ this.preparedPeers.clear();
146
+ this.emit("error", new Error(`Failed to restore room session: ${error}`));
147
+ }
148
+ }
149
+ preparePeerConnection(peerId) {
150
+ const pc = this.webrtcManager.createPeerConnection(peerId);
151
+ if (this.preparedPeers.has(peerId)) {
152
+ return pc;
153
+ }
154
+ this.preparedPeers.add(peerId);
155
+ this.webrtcManager.onIceCandidate(peerId, (candidate) => {
156
+ if (this.currentUserId) {
157
+ this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
158
+ }
159
+ });
160
+ this.webrtcManager.onConnectionStateChange(peerId, (state) => {
161
+ if (state === "failed" ||
162
+ state === "disconnected" ||
163
+ state === "closed") {
164
+ this.preparedPeers.delete(peerId);
165
+ }
166
+ this.emit("connectionStateChange", peerId, state);
167
+ });
168
+ this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
169
+ this.emit("dataChannelStateChange", peerId, state);
170
+ });
171
+ return pc;
172
+ }
173
+ async initiateConnection(peerId) {
174
+ try {
175
+ this.preparePeerConnection(peerId);
159
176
  const offer = await this.webrtcManager.createOffer(peerId);
160
177
  if (this.currentUserId) {
161
- console.log(`[AvesClient] Sending offer to ${peerId} from ${this.currentUserId}`);
162
178
  this.signalingClient.sendOffer(peerId, this.currentUserId, offer);
163
179
  }
164
180
  }
@@ -166,109 +182,96 @@ class AvesClient extends EventEmitter_1.EventEmitter {
166
182
  this.emit("error", new Error(`Failed to initiate connection with ${peerId}: ${error}`));
167
183
  }
168
184
  }
169
- /**
170
- * Create a new room
171
- * @returns Promise that resolves with the room ID
172
- */
173
185
  async createRoom() {
174
- // Connect to signaling server if not connected
175
- if (!this.isConnected()) {
186
+ if (!this.signalingClient.isConnected()) {
176
187
  await this.signalingClient.connect(this.config.signalingUrl);
177
188
  }
178
189
  const roomId = await this.signalingClient.createRoom();
179
190
  this.currentRoomId = roomId;
180
191
  return roomId;
181
192
  }
182
- /**
183
- * Join an existing room
184
- * @param roomId - Room ID to join
185
- * @param userId - User ID
186
- * @param userName - User name
187
- * @returns Promise that resolves with the list of current participants
188
- */
189
- async joinRoom(roomId, userId, userName) {
190
- // Connect to signaling server if not connected
191
- if (!this.isConnected()) {
193
+ async joinRoom(roomId, userIdOrName, maybeUserName) {
194
+ if (!this.signalingClient.isConnected()) {
192
195
  await this.signalingClient.connect(this.config.signalingUrl);
193
196
  }
194
- this.currentUserId = userId;
197
+ const requestedUserId = maybeUserName ? userIdOrName : null;
198
+ const userName = maybeUserName ?? userIdOrName;
199
+ this.currentUserId = requestedUserId;
195
200
  this.currentRoomId = roomId;
196
- const participants = await this.signalingClient.joinRoom(roomId, userId, userName);
197
- // Store participants
201
+ this.currentUserName = userName;
202
+ const joinResult = requestedUserId
203
+ ? await this.signalingClient.joinRoom(roomId, requestedUserId, userName)
204
+ : await this.signalingClient.joinRoom(roomId, userName);
205
+ const participants = joinResult.participants;
206
+ this.currentUserId = joinResult.userId;
198
207
  this.participants.clear();
199
- participants.forEach((p) => this.participants.set(p.id, p));
200
- // Initiate WebRTC connections with existing participants
201
- // Only initiate if our ID is smaller to avoid both sides initiating
208
+ participants.forEach((participant) => this.participants.set(participant.id, participant));
202
209
  for (const participant of participants) {
203
- if (participant.id !== userId && userId < participant.id) {
210
+ if (this.currentUserId &&
211
+ participant.id !== this.currentUserId &&
212
+ this.currentUserId < participant.id) {
204
213
  await this.initiateConnection(participant.id);
205
214
  }
206
215
  }
207
216
  return participants;
208
217
  }
209
- /**
210
- * Leave the current room
211
- * Disconnects from signaling server and closes all WebRTC connections
212
- */
213
218
  async leaveRoom() {
214
- this.signalingClient.leaveRoom();
219
+ if (this.currentUserId) {
220
+ await this.signalingClient.leaveRoom(this.currentUserId);
221
+ }
215
222
  this.webrtcManager.closeAll();
216
223
  this.participants.clear();
224
+ this.preparedPeers.clear();
217
225
  this.currentRoomId = null;
218
226
  this.currentUserId = null;
219
- this.signalingClient.disconnect();
227
+ this.currentUserName = null;
228
+ this.shouldRestoreSession = false;
220
229
  }
221
- /**
222
- * Send a message to all connected peers
223
- * @param message - Message to send (will be JSON serialized)
224
- * @throws Error if any DataChannel is not ready
225
- */
226
230
  sendMessage(message) {
227
231
  this.webrtcManager.sendMessage(message);
228
232
  }
229
- /**
230
- * Send a message to a specific peer
231
- * @param peerId - Target peer ID
232
- * @param message - Message to send (will be JSON serialized)
233
- * @throws Error if DataChannel is not ready
234
- */
235
233
  sendMessageToPeer(peerId, message) {
236
234
  this.webrtcManager.sendMessageToPeer(peerId, message);
237
235
  }
238
- /**
239
- * Get the connection state for a specific peer
240
- * @param peerId - Peer ID
241
- * @returns Connection state or 'closed' if peer not found
242
- */
236
+ async sendFile(blob, options = {}) {
237
+ return this.webrtcManager.sendFile(blob, options);
238
+ }
239
+ async startVoice() {
240
+ return this.webrtcManager.startVoice();
241
+ }
242
+ stopVoice() {
243
+ this.webrtcManager.stopVoice();
244
+ }
245
+ setMuted(muted) {
246
+ this.webrtcManager.setMuted(muted);
247
+ }
248
+ getLocalAudioState() {
249
+ return this.webrtcManager.getLocalAudioState();
250
+ }
251
+ getRemoteAudioStream(peerId) {
252
+ return this.webrtcManager.getRemoteAudioStream(peerId);
253
+ }
243
254
  getConnectionState(peerId) {
244
255
  return this.webrtcManager.isConnected(peerId) ? "connected" : "closed";
245
256
  }
246
- /**
247
- * Get the list of current participants in the room
248
- * @returns Array of participants
249
- */
250
257
  getParticipants() {
251
258
  return Array.from(this.participants.values());
252
259
  }
253
- /**
254
- * Check if connected to the signaling server
255
- * @returns true if connected, false otherwise
256
- */
260
+ getCurrentUserId() {
261
+ return this.currentUserId;
262
+ }
257
263
  isConnected() {
258
- // Check if we have an active signaling connection
259
- // This is a simplified check - in production you might want more sophisticated state tracking
260
- return this.currentRoomId !== null;
264
+ return this.signalingClient.isConnected();
261
265
  }
262
- /**
263
- * Destroy the client and clean up all resources
264
- * Closes all connections and removes all event listeners
265
- */
266
266
  destroy() {
267
- this.signalingClient.disconnect();
268
- this.webrtcManager.closeAll();
269
- this.participants.clear();
270
267
  this.currentRoomId = null;
271
268
  this.currentUserId = null;
269
+ this.currentUserName = null;
270
+ this.shouldRestoreSession = false;
271
+ this.participants.clear();
272
+ this.preparedPeers.clear();
273
+ this.signalingClient.disconnect();
274
+ this.webrtcManager.destroy();
272
275
  this.removeAllListeners();
273
276
  }
274
277
  }
@@ -1,5 +1,5 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
- import { Participant, ReconnectConfig } from "../types/types";
2
+ import { JoinRoomResult, ReconnectConfig } from "../types/types";
3
3
  /**
4
4
  * SignalingClient manages WebSocket connection and signaling message exchange
5
5
  * Extends EventEmitter to provide event-driven communication
@@ -12,6 +12,7 @@ export declare class SignalingClient extends EventEmitter {
12
12
  private url;
13
13
  private shouldReconnect;
14
14
  private pendingRequests;
15
+ private requestCounter;
15
16
  constructor(reconnectConfig: ReconnectConfig);
16
17
  /**
17
18
  * Connect to the signaling server
@@ -23,6 +24,7 @@ export declare class SignalingClient extends EventEmitter {
23
24
  * Disconnect from the signaling server
24
25
  */
25
26
  disconnect(): void;
27
+ isConnected(): boolean;
26
28
  /**
27
29
  * Handle WebSocket disconnection and attempt reconnection
28
30
  */
@@ -49,11 +51,12 @@ export declare class SignalingClient extends EventEmitter {
49
51
  * @param userName - User name
50
52
  * @returns Promise that resolves with the list of participants
51
53
  */
52
- joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
54
+ joinRoom(roomId: string, userName: string): Promise<JoinRoomResult>;
55
+ joinRoom(roomId: string, userId: string, userName: string): Promise<JoinRoomResult>;
53
56
  /**
54
57
  * Leave the current room
55
58
  */
56
- leaveRoom(): void;
59
+ leaveRoom(userId: string): Promise<void>;
57
60
  /**
58
61
  * Send an offer to a peer
59
62
  * @param targetId - Target peer ID
@@ -81,9 +84,13 @@ export declare class SignalingClient extends EventEmitter {
81
84
  * @param value - Value to resolve with
82
85
  */
83
86
  private resolvePendingRequest;
87
+ private handleErrorMessage;
84
88
  /**
85
89
  * Reject all pending requests
86
90
  * @param error - Error to reject with
87
91
  */
88
92
  private rejectPendingRequests;
93
+ private createRequestId;
94
+ private findPendingRequestByType;
95
+ private deletePendingRequestByReference;
89
96
  }