peerpigeon 0.0.8 → 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.
@@ -1,5 +1,6 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { PeerConnection } from './PeerConnection.js';
3
+ import DebugLogger from './DebugLogger.js';
3
4
 
4
5
  /**
5
6
  * Handles WebRTC signaling messages (offers, answers, ICE candidates)
@@ -7,6 +8,7 @@ import { PeerConnection } from './PeerConnection.js';
7
8
  export class SignalingHandler extends EventEmitter {
8
9
  constructor(mesh, connectionManager) {
9
10
  super();
11
+ this.debug = DebugLogger.create('SignalingHandler');
10
12
  this.mesh = mesh;
11
13
  this.connectionManager = connectionManager;
12
14
  }
@@ -14,12 +16,41 @@ export class SignalingHandler extends EventEmitter {
14
16
  async handleSignalingMessage(message) {
15
17
  const { type, data, fromPeerId, targetPeerId } = message;
16
18
 
17
- if (fromPeerId === this.mesh.peerId) return;
18
- if (targetPeerId && targetPeerId !== this.mesh.peerId) return;
19
+ // CRITICAL DEBUG: Log all incoming signaling messages for answer tracking
20
+ if (type === 'answer' || type === 'renegotiation-answer') {
21
+ console.log('🚨 SIGNALING CRITICAL:', type, 'from', fromPeerId?.substring(0, 8), 'to', this.mesh.peerId?.substring(0, 8));
22
+ this.debug.log('🔍 SIGNALING DEBUG: Received answer message:', {
23
+ type,
24
+ fromPeerId: fromPeerId?.substring(0, 8) + '...',
25
+ targetPeerId: targetPeerId?.substring(0, 8) + '...',
26
+ ourPeerId: this.mesh.peerId?.substring(0, 8) + '...',
27
+ hasData: !!data,
28
+ dataType: data?.type
29
+ });
30
+ }
31
+
32
+ if (fromPeerId === this.mesh.peerId) {
33
+ if (type === 'answer' || type === 'renegotiation-answer') {
34
+ console.log('🚨 REJECTING:', type, '- from our own peer ID');
35
+ this.debug.log('🔍 SIGNALING DEBUG: Rejecting answer - from our own peer ID');
36
+ }
37
+ return;
38
+ }
39
+
40
+ if (targetPeerId && targetPeerId !== this.mesh.peerId) {
41
+ if (type === 'answer' || type === 'renegotiation-answer') {
42
+ console.log('🚨 REJECTING:', type, '- target mismatch, target:', targetPeerId?.substring(0, 8), 'us:', this.mesh.peerId?.substring(0, 8));
43
+ this.debug.log('🔍 SIGNALING DEBUG: Rejecting answer - target mismatch:', {
44
+ targetPeerId: targetPeerId?.substring(0, 8) + '...',
45
+ ourPeerId: this.mesh.peerId?.substring(0, 8) + '...'
46
+ });
47
+ }
48
+ return;
49
+ }
19
50
 
20
51
  // Ignore cleanup messages - they are handled by the server, not as peer signaling
21
52
  if (type === 'cleanup' || type === 'cleanup-all') {
22
- console.log('Ignoring cleanup message:', { type, fromPeerId });
53
+ this.debug.log('Ignoring cleanup message:', { type, fromPeerId });
23
54
  return;
24
55
  }
25
56
 
@@ -28,7 +59,7 @@ export class SignalingHandler extends EventEmitter {
28
59
  return;
29
60
  }
30
61
 
31
- console.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
62
+ this.debug.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
32
63
 
33
64
  switch (type) {
34
65
  case 'announce':
@@ -46,9 +77,24 @@ export class SignalingHandler extends EventEmitter {
46
77
  case 'offer':
47
78
  await this.handleOffer(data, fromPeerId);
48
79
  break;
80
+ case 'renegotiation-offer':
81
+ await this.handleRenegotiationOffer(data, fromPeerId);
82
+ break;
49
83
  case 'answer':
84
+ console.log('🚨 SWITCH: Reached answer case for', fromPeerId?.substring(0, 8));
85
+ this.debug.log('🔍 SIGNALING DEBUG: Reached answer case in switch statement');
50
86
  await this.handleAnswer(data, fromPeerId);
51
87
  break;
88
+ case 'renegotiation-answer':
89
+ console.log('🚨 SWITCH: Reached renegotiation-answer case for', fromPeerId?.substring(0, 8));
90
+ await this.handleRenegotiationAnswer(data, fromPeerId);
91
+ break;
92
+ case 'ice-restart-offer':
93
+ await this.handleIceRestartOffer(data, fromPeerId);
94
+ break;
95
+ case 'ice-restart-answer':
96
+ await this.handleIceRestartAnswer(data, fromPeerId);
97
+ break;
52
98
  case 'ice-candidate':
53
99
  await this.connectionManager.handleIceCandidate(data, fromPeerId);
54
100
  break;
@@ -61,14 +107,14 @@ export class SignalingHandler extends EventEmitter {
61
107
  handlePeerAnnouncement(fromPeerId) {
62
108
  // Prevent duplicate announcements - only announce if we haven't seen this peer before
63
109
  if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
64
- console.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
110
+ this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
65
111
  return;
66
112
  }
67
113
 
68
114
  this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
69
- console.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
70
- console.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
71
- console.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
115
+ this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
116
+ this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
117
+ this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
72
118
  this.mesh.peerDiscovery.addDiscoveredPeer(fromPeerId);
73
119
  }
74
120
 
@@ -79,7 +125,26 @@ export class SignalingHandler extends EventEmitter {
79
125
  }
80
126
 
81
127
  async handleOffer(offer, fromPeerId) {
82
- console.log('Handling offer from', fromPeerId);
128
+ this.debug.log('Handling offer from', fromPeerId);
129
+
130
+ // Validate offer data structure before proceeding
131
+ if (!offer || typeof offer !== 'object') {
132
+ this.debug.error(`Invalid offer data from ${fromPeerId}:`, offer);
133
+ this.mesh.emit('statusChanged', { type: 'error', message: `Invalid offer data from ${fromPeerId.substring(0, 8)}...` });
134
+ return;
135
+ }
136
+
137
+ if (!offer.type || offer.type !== 'offer') {
138
+ this.debug.error(`Invalid offer type from ${fromPeerId}:`, offer.type);
139
+ this.mesh.emit('statusChanged', { type: 'error', message: `Invalid offer type from ${fromPeerId.substring(0, 8)}...` });
140
+ return;
141
+ }
142
+
143
+ if (!offer.sdp || typeof offer.sdp !== 'string' || offer.sdp.length < 10) {
144
+ this.debug.error(`Invalid offer SDP from ${fromPeerId}:`, offer.sdp?.substring(0, 100) || 'undefined');
145
+ this.mesh.emit('statusChanged', { type: 'error', message: `Invalid offer SDP from ${fromPeerId.substring(0, 8)}...` });
146
+ return;
147
+ }
83
148
 
84
149
  // If we already have a connection or are connecting, handle gracefully
85
150
  if (this.connectionManager.hasPeer(fromPeerId)) {
@@ -88,36 +153,47 @@ export class SignalingHandler extends EventEmitter {
88
153
 
89
154
  // If connection is already established and working, don't interfere
90
155
  if (existingStatus === 'connected') {
91
- console.log(`Connection already established with ${fromPeerId}, ignoring duplicate offer`);
156
+ this.debug.log(`Connection already established with ${fromPeerId}, ignoring duplicate offer`);
92
157
  return;
93
158
  }
94
159
 
95
- // ABSOLUTE RULE: Lexicographically larger peer ID always initiates
96
- // If we're receiving an offer but we should be the initiator, there's a race condition
160
+ // IMPROVED RACE CONDITION HANDLING:
161
+ // Instead of ignoring offers based on initiator flags, resolve race conditions intelligently
97
162
  const weShouldInitiate = this.mesh.peerId > fromPeerId;
98
163
 
164
+ // If both peers are trying to initiate (mutual initiation race condition)
99
165
  if (weShouldInitiate && existingPeer.isInitiator) {
100
- console.log(`Race condition detected! We should initiate (${this.mesh.peerId.substring(0, 8)}... > ${fromPeerId.substring(0, 8)}...) but received offer. Ignoring.`);
101
- return;
166
+ this.debug.log(`🔄 RACE CONDITION: Both peers trying to initiate! We should initiate (${this.mesh.peerId.substring(0, 8)}... > ${fromPeerId.substring(0, 8)}...) but received offer.`);
167
+
168
+ // CRITICAL FIX: Accept the incoming offer if our connection is stuck in "have-local-offer"
169
+ // This completes the SDP handshake that was blocked by the race condition
170
+ const ourSignalingState = existingPeer.connection?.signalingState;
171
+ if (ourSignalingState === 'have-local-offer') {
172
+ this.debug.log(`✅ RACE RESOLUTION: Our connection stuck in "${ourSignalingState}" - accepting their offer to complete handshake`);
173
+ this.connectionManager.cleanupRaceCondition(fromPeerId);
174
+ } else {
175
+ this.debug.log(`❌ RACE RESOLUTION: Our connection in "${ourSignalingState}" - ignoring their offer as we should initiate`);
176
+ return;
177
+ }
102
178
  } else if (!weShouldInitiate && existingPeer.isInitiator) {
103
- console.log(`We're incorrectly initiating to ${fromPeerId.substring(0, 8)}..., backing down for their offer`);
179
+ this.debug.log(`🔄 INITIATOR CORRECTION: We incorrectly initiated to ${fromPeerId.substring(0, 8)}..., backing down for their offer`);
104
180
  // Cleanup our outgoing attempt and accept the incoming offer
105
181
  if (existingStatus === 'connecting' || existingStatus === 'new') {
106
- console.log(`Cleaning up our outgoing connection attempt to ${fromPeerId.substring(0, 8)}...`);
182
+ this.debug.log(`✅ Cleaning up our incorrect connection attempt to ${fromPeerId.substring(0, 8)}...`);
107
183
  this.connectionManager.cleanupRaceCondition(fromPeerId);
108
184
  } else {
109
- console.log('Connection in progress, not cleaning up');
185
+ this.debug.log('Connection in progress, not cleaning up');
110
186
  return;
111
187
  }
112
188
  } else {
113
- console.log('Already processing incoming connection from', fromPeerId);
189
+ this.debug.log('Already processing incoming connection from', fromPeerId);
114
190
  return;
115
191
  }
116
192
  }
117
193
 
118
194
  // Check if we're already attempting to connect to this peer
119
195
  if (this.connectionManager.connectionAttempts.has(fromPeerId)) {
120
- console.log('Already attempting connection to', fromPeerId, 'accepting incoming offer');
196
+ this.debug.log('Already attempting connection to', fromPeerId, 'accepting incoming offer');
121
197
  this.connectionManager.connectionAttempts.delete(fromPeerId);
122
198
  }
123
199
 
@@ -127,33 +203,33 @@ export class SignalingHandler extends EventEmitter {
127
203
  let canAccept = this.mesh.canAcceptMorePeers();
128
204
  let evictPeerId = null;
129
205
 
130
- console.log(`Capacity check for ${fromPeerId.substring(0, 8)}...: ${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers, canAccept: ${canAccept}`);
206
+ this.debug.log(`Capacity check for ${fromPeerId.substring(0, 8)}...: ${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers, canAccept: ${canAccept}`);
131
207
 
132
208
  if (!canAccept) {
133
- console.log(`At capacity (${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) - checking eviction and cleanup options`);
209
+ this.debug.log(`At capacity (${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) - checking eviction and cleanup options`);
134
210
 
135
211
  // First try: Check if we should evict a peer for this new connection
136
212
  if (this.mesh.evictionStrategy) {
137
213
  evictPeerId = this.mesh.evictionManager.shouldEvictForPeer(fromPeerId);
138
214
  if (evictPeerId) {
139
- console.log(`Will evict ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...`);
215
+ this.debug.log(`Will evict ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...`);
140
216
  canAccept = true; // We can accept because we'll evict
141
217
  } else {
142
- console.log(`No suitable peer found for eviction for ${fromPeerId.substring(0, 8)}...`);
218
+ this.debug.log(`No suitable peer found for eviction for ${fromPeerId.substring(0, 8)}...`);
143
219
  }
144
220
  } else {
145
- console.log(`Eviction strategy disabled - cannot evict for ${fromPeerId.substring(0, 8)}...`);
221
+ this.debug.log(`Eviction strategy disabled - cannot evict for ${fromPeerId.substring(0, 8)}...`);
146
222
  }
147
223
 
148
224
  // Second try: Clean up stale peers to make room
149
225
  if (!canAccept) {
150
226
  const stalePeerCount = this.connectionManager.getStalePeerCount();
151
227
  if (stalePeerCount > 0) {
152
- console.log(`No eviction candidate, attempting to clean up ${stalePeerCount} stale peer(s) to make room for ${fromPeerId.substring(0, 8)}...`);
228
+ this.debug.log(`No eviction candidate, attempting to clean up ${stalePeerCount} stale peer(s) to make room for ${fromPeerId.substring(0, 8)}...`);
153
229
  this.connectionManager.cleanupStalePeers();
154
230
  canAccept = this.mesh.canAcceptMorePeers();
155
231
  if (canAccept) {
156
- console.log(`Successfully made room after cleanup for ${fromPeerId.substring(0, 8)}...`);
232
+ this.debug.log(`Successfully made room after cleanup for ${fromPeerId.substring(0, 8)}...`);
157
233
  }
158
234
  }
159
235
  }
@@ -161,22 +237,21 @@ export class SignalingHandler extends EventEmitter {
161
237
  // Final rejection if no options worked
162
238
  if (!canAccept) {
163
239
  const reason = `max_peers_reached (${currentCount}/${this.mesh.maxPeers} connected, ${this.connectionManager.peers.size} total, no eviction candidate)`;
164
- console.log(`Rejecting offer from ${fromPeerId.substring(0, 8)}...: ${reason}`);
240
+ this.debug.log(`Rejecting offer from ${fromPeerId.substring(0, 8)}...: ${reason}`);
165
241
 
166
242
  try {
167
- await this.mesh.signalingClient.sendSignalingMessage({
243
+ await this.mesh.sendSignalingMessage({
168
244
  type: 'connection-rejected',
169
245
  data: {
170
246
  reason: 'max_peers_reached',
171
247
  details: reason,
172
248
  currentCount,
173
249
  maxPeers: this.mesh.maxPeers
174
- },
175
- targetPeerId: fromPeerId
176
- });
177
- console.log(`Sent connection rejection to ${fromPeerId.substring(0, 8)}...`);
250
+ }
251
+ }, fromPeerId);
252
+ this.debug.log(`Sent connection rejection to ${fromPeerId.substring(0, 8)}...`);
178
253
  } catch (error) {
179
- console.error('Failed to send connection rejection:', error);
254
+ this.debug.error('Failed to send connection rejection:', error);
180
255
  }
181
256
  return;
182
257
  }
@@ -193,11 +268,13 @@ export class SignalingHandler extends EventEmitter {
193
268
  const hasMedia = localStream !== null;
194
269
  const options = {
195
270
  localStream,
196
- enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
197
- enableVideo: hasMedia && localStream.getVideoTracks().length > 0
271
+ // ALWAYS enable both audio and video transceivers for maximum compatibility
272
+ // This allows peers to receive media even if they don't have media when connecting
273
+ enableAudio: true,
274
+ enableVideo: true
198
275
  };
199
276
 
200
- console.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
277
+ this.debug.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
201
278
 
202
279
  const peerConnection = new PeerConnection(fromPeerId, false, options);
203
280
 
@@ -207,7 +284,7 @@ export class SignalingHandler extends EventEmitter {
207
284
 
208
285
  await peerConnection.createConnection();
209
286
 
210
- console.log(`Processing offer from ${fromPeerId.substring(0, 8)}...`, {
287
+ this.debug.log(`Processing offer from ${fromPeerId.substring(0, 8)}...`, {
211
288
  type: offer.type,
212
289
  sdpLength: offer.sdp?.length || 0,
213
290
  hasAudio: offer.sdp?.includes('m=audio') || false,
@@ -217,31 +294,38 @@ export class SignalingHandler extends EventEmitter {
217
294
  // Handle the offer using PeerConnection's method
218
295
  const answer = await peerConnection.handleOffer(offer);
219
296
 
220
- console.log(`Answer created for ${fromPeerId.substring(0, 8)}...`, {
297
+ this.debug.log(`Answer created for ${fromPeerId.substring(0, 8)}...`, {
221
298
  type: answer.type,
222
299
  sdpLength: answer.sdp?.length || 0,
223
300
  hasAudio: answer.sdp?.includes('m=audio') || false,
224
301
  hasVideo: answer.sdp?.includes('m=video') || false
225
302
  });
226
303
 
227
- console.log('Sending answer to', fromPeerId);
304
+ this.debug.log('Sending answer to', fromPeerId);
305
+
306
+ // ENHANCED DEBUGGING: Log the exact answer being sent
307
+ this.debug.log(`🔄 ANSWER SEND DEBUG: Sending answer to ${fromPeerId.substring(0, 8)}...`);
308
+ this.debug.log(`🔄 ANSWER SEND DEBUG: Answer type: ${answer.type}`);
309
+ this.debug.log(`🔄 ANSWER SEND DEBUG: Answer SDP length: ${answer.sdp?.length}`);
310
+ this.debug.log(`🔄 ANSWER SEND DEBUG: Target peer ID: ${fromPeerId}`);
228
311
 
229
312
  // Send answer via signaling
230
- await this.mesh.signalingClient.sendSignalingMessage({
313
+ await this.mesh.sendSignalingMessage({
231
314
  type: 'answer',
232
315
  data: answer,
233
- targetPeerId: fromPeerId
234
- });
316
+ timestamp: Date.now()
317
+ }, fromPeerId);
235
318
 
319
+ this.debug.log(`✅ ANSWER SEND DEBUG: Answer successfully sent to ${fromPeerId.substring(0, 8)}...`);
236
320
  this.mesh.emit('statusChanged', { type: 'info', message: `Answer sent to ${fromPeerId.substring(0, 8)}...` });
237
321
  // Clear connection attempt since we're now processing the connection
238
322
  this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
239
323
  } catch (error) {
240
- console.error('Failed to handle offer from', fromPeerId, ':', error);
324
+ this.debug.error('Failed to handle offer from', fromPeerId, ':', error);
241
325
 
242
326
  // If it's a state error, handle gracefully
243
327
  if (error.message.includes('state:')) {
244
- console.log(`Offer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition)`);
328
+ this.debug.log(`Offer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition)`);
245
329
  this.mesh.emit('statusChanged', { type: 'info', message: `Offer skipped for ${fromPeerId.substring(0, 8)}... (connection state conflict)` });
246
330
  } else {
247
331
  this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle offer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
@@ -250,32 +334,90 @@ export class SignalingHandler extends EventEmitter {
250
334
  }
251
335
  }
252
336
 
337
+ async handleRenegotiationOffer(offer, fromPeerId) {
338
+ this.debug.log(`🔄 Handling renegotiation offer via signaling from ${fromPeerId.substring(0, 8)}...`);
339
+
340
+ // Find the existing peer connection
341
+ const peerConnection = this.connectionManager.getPeer(fromPeerId);
342
+ if (!peerConnection) {
343
+ this.debug.error(`No peer connection found for renegotiation from ${fromPeerId.substring(0, 8)}...`);
344
+ return;
345
+ }
346
+
347
+ try {
348
+ // Handle the renegotiation offer and get answer
349
+ const answer = await peerConnection.handleOffer(offer);
350
+
351
+ // CRITICAL FIX: Send the answer back as 'renegotiation-answer', not regular 'answer'
352
+ // This ensures the initiator receives the correct message type for renegotiation completion
353
+ await this.mesh.sendSignalingMessage({
354
+ type: 'renegotiation-answer',
355
+ data: answer,
356
+ timestamp: Date.now()
357
+ }, fromPeerId);
358
+
359
+ this.debug.log(`✅ Renegotiation completed via signaling with ${fromPeerId.substring(0, 8)}...`);
360
+ } catch (error) {
361
+ this.debug.error(`❌ Failed to handle renegotiation offer via signaling from ${fromPeerId.substring(0, 8)}...`, error);
362
+ }
363
+ }
364
+
253
365
  async handleAnswer(answer, fromPeerId) {
254
- console.log('Handling answer from', fromPeerId);
366
+ this.debug.log('🔄 ANSWER RECEIVE DEBUG: Handling answer from', fromPeerId);
367
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Our peer ID: ${this.mesh.peerId.substring(0, 8)}...`);
368
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Answer from: ${fromPeerId.substring(0, 8)}...`);
369
+
370
+ // Validate answer data structure before proceeding
371
+ if (!answer || typeof answer !== 'object') {
372
+ this.debug.error(`Invalid answer data from ${fromPeerId}:`, answer);
373
+ this.mesh.emit('statusChanged', { type: 'error', message: `Invalid answer data from ${fromPeerId.substring(0, 8)}...` });
374
+ return;
375
+ }
255
376
 
377
+ if (!answer.type || answer.type !== 'answer') {
378
+ this.debug.error(`Invalid answer type from ${fromPeerId}:`, answer.type);
379
+ this.mesh.emit('statusChanged', { type: 'error', message: `Invalid answer type from ${fromPeerId.substring(0, 8)}...` });
380
+ return;
381
+ }
382
+
383
+ if (!answer.sdp || typeof answer.sdp !== 'string' || answer.sdp.length < 10) {
384
+ this.debug.error(`Invalid answer SDP from ${fromPeerId}:`, answer.sdp?.substring(0, 100) || 'undefined');
385
+ this.mesh.emit('statusChanged', { type: 'error', message: `Invalid answer SDP from ${fromPeerId.substring(0, 8)}...` });
386
+ return;
387
+ }
388
+
389
+ // CRITICAL DEBUG: Check if we have a peer connection for this answer
256
390
  const peerConnection = this.connectionManager.getPeer(fromPeerId);
391
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Found peer connection: ${!!peerConnection}`);
392
+ if (peerConnection) {
393
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Peer connection state: ${peerConnection.connection?.signalingState}`);
394
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Is initiator: ${peerConnection.isInitiator}`);
395
+ }
396
+
257
397
  if (peerConnection) {
258
398
  try {
399
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Processing answer from ${fromPeerId.substring(0, 8)}...`);
259
400
  await peerConnection.handleAnswer(answer);
401
+ this.debug.log(`✅ ANSWER RECEIVE DEBUG: Answer processed successfully from ${fromPeerId.substring(0, 8)}...`);
260
402
  this.mesh.emit('statusChanged', { type: 'info', message: `Answer processed from ${fromPeerId.substring(0, 8)}...` });
261
403
  } catch (error) {
262
- console.error('Failed to handle answer:', error);
404
+ this.debug.error('❌ ANSWER RECEIVE DEBUG: Failed to handle answer:', error);
263
405
 
264
406
  // If it's a state error (connection already stable), don't treat as failure
265
407
  if (error.message.includes('state:') || error.message.includes('stable')) {
266
- console.log(`Answer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition resolved)`);
408
+ this.debug.log(`Answer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition resolved)`);
267
409
  this.mesh.emit('statusChanged', { type: 'info', message: `Answer skipped for ${fromPeerId.substring(0, 8)}... (connection already stable)` });
268
410
  } else {
269
411
  this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle answer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
270
412
  }
271
413
  }
272
414
  } else {
273
- console.log('No peer connection found for answer from', fromPeerId);
415
+ this.debug.log('❌ ANSWER RECEIVE DEBUG: No peer connection found for answer from', fromPeerId);
274
416
  }
275
417
  }
276
418
 
277
419
  handleConnectionRejected(data, fromPeerId) {
278
- console.log(`Connection rejected by ${fromPeerId.substring(0, 8)}...: ${data.reason} (${data.details})`);
420
+ this.debug.log(`Connection rejected by ${fromPeerId.substring(0, 8)}...: ${data.reason} (${data.details})`);
279
421
  this.mesh.emit('statusChanged', {
280
422
  type: 'info',
281
423
  message: `Connection rejected by ${fromPeerId.substring(0, 8)}... (${data.reason})`
@@ -297,7 +439,7 @@ export class SignalingHandler extends EventEmitter {
297
439
  // If we have no connections, immediately try other peers more aggressively
298
440
  const connectedCount = this.connectionManager.getConnectedPeerCount();
299
441
  if (connectedCount === 0) {
300
- console.log(`Connection rejected and peer is isolated (${connectedCount} connections) - trying alternative peers immediately`);
442
+ this.debug.log(`Connection rejected and peer is isolated (${connectedCount} connections) - trying alternative peers immediately`);
301
443
 
302
444
  // Immediately try to connect to other discovered peers
303
445
  const discoveredPeers = Array.from(this.mesh.peerDiscovery.getDiscoveredPeers());
@@ -316,7 +458,7 @@ export class SignalingHandler extends EventEmitter {
316
458
  });
317
459
 
318
460
  const nextPeer = sortedByDistance[0];
319
- console.log(`Immediately attempting connection to next closest peer: ${nextPeer.peerId.substring(0, 8)}...`);
461
+ this.debug.log(`Immediately attempting connection to next closest peer: ${nextPeer.peerId.substring(0, 8)}...`);
320
462
  this.connectionManager.connectToPeer(nextPeer.peerId);
321
463
  }
322
464
  } else {
@@ -326,4 +468,91 @@ export class SignalingHandler extends EventEmitter {
326
468
  }, 1000);
327
469
  }
328
470
  }
471
+
472
+ async handleRenegotiationAnswer(answer, fromPeerId) {
473
+ console.log('🚨 RENEGOTIATION ANSWER: IMMEDIATE PROCESSING from', fromPeerId?.substring(0, 8), 'to', this.mesh.peerId?.substring(0, 8));
474
+ this.debug.log(`🔄 CRITICAL FIX: IMMEDIATE renegotiation answer from ${fromPeerId.substring(0, 8)}...`);
475
+
476
+ // AGGRESSIVE FIX: Find connection immediately and apply answer
477
+ const peerConnection = this.connectionManager.getPeer(fromPeerId);
478
+ if (!peerConnection) {
479
+ this.debug.error(`❌ CRITICAL: No peer connection for answer from ${fromPeerId.substring(0, 8)}... - CONNECTION LOST`);
480
+ return;
481
+ }
482
+
483
+ // CHECK CONNECTION STATE BEFORE APPLYING ANSWER
484
+ const currentState = peerConnection.connection?.signalingState;
485
+ this.debug.log(`� CRITICAL: Connection state before answer: ${currentState}`);
486
+
487
+ if (currentState !== 'have-local-offer') {
488
+ this.debug.log(`⚠️ CRITICAL: Connection not waiting for answer (state: ${currentState}) - applying anyway`);
489
+ }
490
+
491
+ try {
492
+ // IMMEDIATE ANSWER APPLICATION - NO DELAYS
493
+ this.debug.log(`🔄 CRITICAL: APPLYING ANSWER IMMEDIATELY from ${fromPeerId.substring(0, 8)}...`);
494
+ await peerConnection.handleAnswer(answer);
495
+
496
+ // VERIFY STATE CHANGE
497
+ const newState = peerConnection.connection?.signalingState;
498
+ this.debug.log(`✅ CRITICAL: Answer applied - state changed from ${currentState} to ${newState}`);
499
+
500
+ if (newState === 'stable') {
501
+ this.debug.log(`🎉 SUCCESS: Connection with ${fromPeerId.substring(0, 8)}... is now STABLE - media should work!`);
502
+ } else {
503
+ this.debug.error(`❌ CRITICAL: Connection still not stable after answer - state: ${newState}`);
504
+ }
505
+
506
+ } catch (error) {
507
+ this.debug.error(`❌ CRITICAL: FAILED to apply renegotiation answer from ${fromPeerId.substring(0, 8)}...`, error);
508
+
509
+ // EMERGENCY FIX: Force connection recovery
510
+ this.debug.log(`🆘 EMERGENCY: Forcing connection recovery for ${fromPeerId.substring(0, 8)}...`);
511
+ try {
512
+ await this.connectionManager.connectToPeer(fromPeerId, false, { emergency: true });
513
+ } catch (recoveryError) {
514
+ this.debug.error(`❌ EMERGENCY: Recovery failed for ${fromPeerId.substring(0, 8)}...`, recoveryError);
515
+ }
516
+ }
517
+ }
518
+
519
+ /**
520
+ * Handle ICE restart offers sent over the mesh
521
+ */
522
+ async handleIceRestartOffer(data, fromPeerId) {
523
+ this.debug.log(`Received ICE restart offer from ${fromPeerId.substring(0, 8)}...`);
524
+
525
+ const peerConnection = this.connectionManager.peers.get(fromPeerId);
526
+ if (!peerConnection) {
527
+ this.debug.warn(`No peer connection found for ICE restart offer from ${fromPeerId.substring(0, 8)}...`);
528
+ return;
529
+ }
530
+
531
+ try {
532
+ await peerConnection.handleIceRestartOffer(data.offer);
533
+ this.debug.log(`Successfully handled ICE restart offer from ${fromPeerId.substring(0, 8)}...`);
534
+ } catch (error) {
535
+ this.debug.error(`Failed to handle ICE restart offer from ${fromPeerId.substring(0, 8)}...:`, error);
536
+ }
537
+ }
538
+
539
+ /**
540
+ * Handle ICE restart answers sent over the mesh
541
+ */
542
+ async handleIceRestartAnswer(data, fromPeerId) {
543
+ this.debug.log(`Received ICE restart answer from ${fromPeerId.substring(0, 8)}...`);
544
+
545
+ const peerConnection = this.connectionManager.peers.get(fromPeerId);
546
+ if (!peerConnection) {
547
+ this.debug.warn(`No peer connection found for ICE restart answer from ${fromPeerId.substring(0, 8)}...`);
548
+ return;
549
+ }
550
+
551
+ try {
552
+ await peerConnection.handleIceRestartAnswer(data.answer);
553
+ this.debug.log(`Successfully handled ICE restart answer from ${fromPeerId.substring(0, 8)}...`);
554
+ } catch (error) {
555
+ this.debug.error(`Failed to handle ICE restart answer from ${fromPeerId.substring(0, 8)}...:`, error);
556
+ }
557
+ }
329
558
  }
@@ -1,5 +1,6 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { environmentDetector } from './EnvironmentDetector.js';
3
+ import DebugLogger from './DebugLogger.js';
3
4
 
4
5
  /**
5
6
  * Manages storage operations, URL handling, and configuration persistence
@@ -7,6 +8,7 @@ import { environmentDetector } from './EnvironmentDetector.js';
7
8
  export class StorageManager extends EventEmitter {
8
9
  constructor(mesh) {
9
10
  super();
11
+ this.debug = DebugLogger.create('StorageManager');
10
12
  this.mesh = mesh;
11
13
  }
12
14
 
@@ -21,7 +23,7 @@ export class StorageManager extends EventEmitter {
21
23
  }
22
24
  } else if (environmentDetector.isNodeJS) {
23
25
  // In Node.js, we could potentially use file-based storage
24
- console.log('Local storage not available in Node.js environment');
26
+ this.debug.log('Local storage not available in Node.js environment');
25
27
  }
26
28
  return null;
27
29
  }
@@ -31,7 +33,7 @@ export class StorageManager extends EventEmitter {
31
33
  localStorage.setItem('pigon-signaling-url', url);
32
34
  } else if (environmentDetector.isNodeJS) {
33
35
  // In Node.js, we could potentially save to a config file
34
- console.log('Storage not implemented for Node.js environment');
36
+ this.debug.log('Storage not implemented for Node.js environment');
35
37
  }
36
38
  }
37
39
 
@@ -93,7 +95,7 @@ export class StorageManager extends EventEmitter {
93
95
  array.set(randomBytes);
94
96
  }
95
97
  } catch (e) {
96
- console.warn('Could not use Node.js crypto, falling back to Math.random');
98
+ this.debug.warn('Could not use Node.js crypto, falling back to Math.random');
97
99
  // Fallback to Math.random
98
100
  for (let i = 0; i < array.length; i++) {
99
101
  array[i] = Math.floor(Math.random() * 256);
@@ -102,7 +104,7 @@ export class StorageManager extends EventEmitter {
102
104
  }
103
105
  } else {
104
106
  // Fallback to less secure random generation
105
- console.warn('Secure random values not available, using fallback method');
107
+ this.debug.warn('Secure random values not available, using fallback method');
106
108
  for (let i = 0; i < array.length; i++) {
107
109
  array[i] = Math.floor(Math.random() * 256);
108
110
  }
@@ -128,7 +130,7 @@ export class StorageManager extends EventEmitter {
128
130
  try {
129
131
  return JSON.parse(saved);
130
132
  } catch (error) {
131
- console.error('Failed to parse saved settings:', error);
133
+ this.debug.error('Failed to parse saved settings:', error);
132
134
  }
133
135
  }
134
136
  }
package/src/TimerUtils.js CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { environmentDetector } from './EnvironmentDetector.js';
7
+ import DebugLogger from './DebugLogger.js';
7
8
 
8
9
  // Store original timer functions to avoid issues with wrapped functions
9
10
  let originalSetInterval, originalSetTimeout, originalClearInterval, originalClearTimeout;