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