peerpigeon 0.0.8 → 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.
@@ -2,6 +2,8 @@
2
2
  * EnvironmentDetector - Utility for detecting runtime environment and capabilities
3
3
  * Provides comprehensive environment detection for browser, Node.js, Worker contexts
4
4
  */
5
+ import DebugLogger from './DebugLogger.js';
6
+
5
7
  export class EnvironmentDetector {
6
8
  constructor() {
7
9
  this._cache = new Map();
@@ -179,7 +181,7 @@ export class EnvironmentDetector {
179
181
  } else {
180
182
  // In ES modules, we can't easily check if a package is available
181
183
  // without actually importing it, so we'll assume it might be available
182
- return false; // Conservative approach
184
+ return false;
183
185
  }
184
186
  } catch (e) {
185
187
  return false;
@@ -1,3 +1,4 @@
1
+ import DebugLogger from './DebugLogger.js';
1
2
  export class EventEmitter {
2
3
  constructor() {
3
4
  this.eventListeners = {};
@@ -1,4 +1,5 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
+ import DebugLogger from './DebugLogger.js';
2
3
 
3
4
  /**
4
5
  * Simple eviction manager for mesh topology optimization
@@ -7,6 +8,7 @@ import { EventEmitter } from './EventEmitter.js';
7
8
  export class EvictionManager extends EventEmitter {
8
9
  constructor(mesh, connectionManager) {
9
10
  super();
11
+ this.debug = DebugLogger.create('EvictionManager');
10
12
  this.mesh = mesh;
11
13
  this.connectionManager = connectionManager;
12
14
  }
@@ -14,25 +16,25 @@ export class EvictionManager extends EventEmitter {
14
16
  shouldEvictForPeer(newPeerId) {
15
17
  // Only evict for mesh topology optimization
16
18
  if (!this.mesh.evictionStrategy) {
17
- console.log('Eviction disabled - evictionStrategy is false');
19
+ this.debug.log('Eviction disabled - evictionStrategy is false');
18
20
  return null;
19
21
  }
20
22
 
21
23
  // Check total peer count (including connecting peers) to prevent race conditions
22
24
  const totalPeerCount = this.connectionManager.peers.size;
23
25
  if (totalPeerCount < this.mesh.maxPeers) {
24
- console.log(`No eviction needed: ${totalPeerCount}/${this.mesh.maxPeers} peers`);
26
+ this.debug.log(`No eviction needed: ${totalPeerCount}/${this.mesh.maxPeers} peers`);
25
27
  return null;
26
28
  }
27
29
 
28
30
  // Special case: if we have 0 connected peers (isolated), be very aggressive about making room
29
31
  const connectedCount = this.connectionManager.getConnectedPeerCount();
30
32
  if (connectedCount === 0) {
31
- console.log(`Isolated peer scenario: finding any peer to evict for ${newPeerId.substring(0, 8)}...`);
33
+ this.debug.log(`Isolated peer scenario: finding any peer to evict for ${newPeerId.substring(0, 8)}...`);
32
34
  // Find any peer to evict (even connecting ones) to make room for this connection
33
35
  const anyPeerId = Array.from(this.connectionManager.peers.keys())[0];
34
36
  if (anyPeerId) {
35
- console.log(`Will evict any peer ${anyPeerId.substring(0, 8)}... to escape isolation for ${newPeerId.substring(0, 8)}...`);
37
+ this.debug.log(`Will evict any peer ${anyPeerId.substring(0, 8)}... to escape isolation for ${newPeerId.substring(0, 8)}...`);
36
38
  return anyPeerId;
37
39
  }
38
40
  }
@@ -43,13 +45,13 @@ export class EvictionManager extends EventEmitter {
43
45
  const farthestPeerId = this.findFarthestPeer();
44
46
 
45
47
  if (!farthestPeerId) {
46
- console.log('No eviction candidate found (no peers to evict)');
48
+ this.debug.log('No eviction candidate found (no peers to evict)');
47
49
  return null;
48
50
  }
49
51
 
50
52
  const farthestDistance = this.calculateXorDistance(this.mesh.peerId, farthestPeerId);
51
53
 
52
- console.log(`Eviction check: new peer ${newPeerId.substring(0, 8)}... (distance: ${newPeerDistance.toString(16).substring(0, 8)}) vs farthest ${farthestPeerId.substring(0, 8)}... (distance: ${farthestDistance.toString(16).substring(0, 8)})`);
54
+ this.debug.log(`Eviction check: new peer ${newPeerId.substring(0, 8)}... (distance: ${newPeerDistance.toString(16).substring(0, 8)}) vs farthest ${farthestPeerId.substring(0, 8)}... (distance: ${farthestDistance.toString(16).substring(0, 8)})`);
53
55
 
54
56
  // LOOSENED RULE: If we're at max capacity, always try to evict the farthest peer
55
57
  // even if the new peer isn't strictly closer (helps with network connectivity)
@@ -57,22 +59,22 @@ export class EvictionManager extends EventEmitter {
57
59
  (totalPeerCount >= this.mesh.maxPeers && connectedCount < this.mesh.minPeers);
58
60
 
59
61
  if (shouldEvict) {
60
- console.log(`Will evict ${farthestPeerId.substring(0, 8)}... for ${newPeerDistance < farthestDistance ? 'closer' : 'network connectivity'} peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
62
+ this.debug.log(`Will evict ${farthestPeerId.substring(0, 8)}... for ${newPeerDistance < farthestDistance ? 'closer' : 'network connectivity'} peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
61
63
  return farthestPeerId;
62
64
  }
63
65
 
64
- console.log(`Not evicting for ${newPeerId.substring(0, 8)}... - criteria not met (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
66
+ this.debug.log(`Not evicting for ${newPeerId.substring(0, 8)}... - criteria not met (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
65
67
  return null;
66
68
  } else {
67
69
  // If XOR routing is disabled, use simple FIFO eviction - evict oldest peer
68
- console.log(`XOR routing disabled - using FIFO eviction for ${newPeerId.substring(0, 8)}...`);
70
+ this.debug.log(`XOR routing disabled - using FIFO eviction for ${newPeerId.substring(0, 8)}...`);
69
71
  const oldestPeerId = this.findOldestPeer();
70
72
  if (oldestPeerId) {
71
- console.log(`Will evict oldest peer ${oldestPeerId.substring(0, 8)}... for new peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
73
+ this.debug.log(`Will evict oldest peer ${oldestPeerId.substring(0, 8)}... for new peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
72
74
  return oldestPeerId;
73
75
  }
74
76
 
75
- console.log('No eviction candidate found (no peers to evict)');
77
+ this.debug.log('No eviction candidate found (no peers to evict)');
76
78
  return null;
77
79
  }
78
80
  }
@@ -80,11 +82,11 @@ export class EvictionManager extends EventEmitter {
80
82
  async evictPeer(peerId, reason = 'topology optimization') {
81
83
  const peerConnection = this.connectionManager.getPeer(peerId);
82
84
  if (!peerConnection) {
83
- console.log(`Cannot evict ${peerId.substring(0, 8)}... - peer not found`);
85
+ this.debug.log(`Cannot evict ${peerId.substring(0, 8)}... - peer not found`);
84
86
  return;
85
87
  }
86
88
 
87
- console.log(`Evicting ${peerId.substring(0, 8)}... (${reason})`);
89
+ this.debug.log(`Evicting ${peerId.substring(0, 8)}... (${reason})`);
88
90
 
89
91
  // Send eviction notice
90
92
  try {
@@ -94,7 +96,7 @@ export class EvictionManager extends EventEmitter {
94
96
  from: this.mesh.peerId
95
97
  });
96
98
  } catch (error) {
97
- console.log('Failed to send eviction notice:', error.message);
99
+ this.debug.log('Failed to send eviction notice:', error.message);
98
100
  }
99
101
 
100
102
  // Close connection and clean up
@@ -107,7 +109,7 @@ export class EvictionManager extends EventEmitter {
107
109
  }
108
110
 
109
111
  handleEvictionNotice(message, fromPeerId) {
110
- console.log(`Evicted by ${fromPeerId.substring(0, 8)}... (${message.reason})`);
112
+ this.debug.log(`Evicted by ${fromPeerId.substring(0, 8)}... (${message.reason})`);
111
113
 
112
114
  // Clean up the connection
113
115
  this.connectionManager.peers.delete(fromPeerId);
@@ -133,7 +135,7 @@ export class EvictionManager extends EventEmitter {
133
135
 
134
136
  findFarthestPeer() {
135
137
  if (this.connectionManager.peers.size === 0) {
136
- console.log('No peers available for eviction');
138
+ this.debug.log('No peers available for eviction');
137
139
  return null;
138
140
  }
139
141
 
@@ -159,7 +161,7 @@ export class EvictionManager extends EventEmitter {
159
161
 
160
162
  // FALLBACK: If no candidates found with strict criteria, try ANY peer
161
163
  if (!farthestPeer && this.connectionManager.peers.size > 0) {
162
- console.log('No eviction candidates with connected/connecting status, trying any peer...');
164
+ this.debug.log('No eviction candidates with connected/connecting status, trying any peer...');
163
165
  this.connectionManager.peers.forEach((peerConnection, peerId) => {
164
166
  candidateCount++;
165
167
  const distance = this.calculateXorDistance(this.mesh.peerId, peerId);
@@ -171,9 +173,9 @@ export class EvictionManager extends EventEmitter {
171
173
  }
172
174
 
173
175
  if (farthestPeer) {
174
- console.log(`Found farthest peer for eviction: ${farthestPeer.substring(0, 8)}... (distance: ${maxDistance.toString(16).substring(0, 8)}, ${candidateCount} candidate peers)`);
176
+ this.debug.log(`Found farthest peer for eviction: ${farthestPeer.substring(0, 8)}... (distance: ${maxDistance.toString(16).substring(0, 8)}, ${candidateCount} candidate peers)`);
175
177
  } else {
176
- console.log(`No peers available for eviction (${candidateCount} candidate peers)`);
178
+ this.debug.log(`No peers available for eviction (${candidateCount} candidate peers)`);
177
179
  }
178
180
 
179
181
  return farthestPeer;
@@ -181,7 +183,7 @@ export class EvictionManager extends EventEmitter {
181
183
 
182
184
  findOldestPeer() {
183
185
  if (this.connectionManager.peers.size === 0) {
184
- console.log('No peers available for FIFO eviction');
186
+ this.debug.log('No peers available for FIFO eviction');
185
187
  return null;
186
188
  }
187
189
 
@@ -207,7 +209,7 @@ export class EvictionManager extends EventEmitter {
207
209
 
208
210
  // FALLBACK: If no candidates found with strict criteria, try ANY peer
209
211
  if (!oldestPeer && this.connectionManager.peers.size > 0) {
210
- console.log('No FIFO eviction candidates with connected/connecting status, trying any peer...');
212
+ this.debug.log('No FIFO eviction candidates with connected/connecting status, trying any peer...');
211
213
  this.connectionManager.peers.forEach((peerConnection, peerId) => {
212
214
  candidateCount++;
213
215
  const connectionTime = peerConnection.connectionStartTime || Date.now();
@@ -219,9 +221,9 @@ export class EvictionManager extends EventEmitter {
219
221
  }
220
222
 
221
223
  if (oldestPeer) {
222
- console.log(`Found oldest peer for eviction: ${oldestPeer.substring(0, 8)}... (connected at: ${new Date(oldestTime).toLocaleTimeString()}, ${candidateCount} candidates)`);
224
+ this.debug.log(`Found oldest peer for eviction: ${oldestPeer.substring(0, 8)}... (connected at: ${new Date(oldestTime).toLocaleTimeString()}, ${candidateCount} candidates)`);
223
225
  } else {
224
- console.log(`No peers available for FIFO eviction (${candidateCount} candidates)`);
226
+ this.debug.log(`No peers available for FIFO eviction (${candidateCount} candidates)`);
225
227
  }
226
228
 
227
229
  return oldestPeer;
@@ -237,7 +239,7 @@ export class EvictionManager extends EventEmitter {
237
239
  const toDisconnect = peerEntries.slice(0, this.connectionManager.peers.size - this.mesh.maxPeers);
238
240
 
239
241
  toDisconnect.forEach(([peerId, peerConnection]) => {
240
- console.log(`Disconnecting ${peerId.substring(0, 8)}... (over max peers limit)`);
242
+ this.debug.log(`Disconnecting ${peerId.substring(0, 8)}... (over max peers limit)`);
241
243
  peerConnection.close();
242
244
  this.connectionManager.peers.delete(peerId);
243
245
  this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
@@ -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 gossip protocol for message propagation across the mesh network
@@ -10,6 +11,7 @@ export class GossipManager extends EventEmitter {
10
11
  super();
11
12
  this.mesh = mesh;
12
13
  this.connectionManager = connectionManager;
14
+ this.debug = DebugLogger.create('GossipManager');
13
15
 
14
16
  // Track message history to prevent infinite loops
15
17
  this.seenMessages = new Map(); // messageId -> { timestamp, ttl }
@@ -30,17 +32,17 @@ export class GossipManager extends EventEmitter {
30
32
  broadcastMessage(content, messageType = 'chat') {
31
33
  // Validate content
32
34
  if (content === undefined || content === null) {
33
- console.error('Cannot broadcast message with undefined/null content');
35
+ this.debug.error('Cannot broadcast message with undefined/null content');
34
36
  return null;
35
37
  }
36
38
 
37
39
  if (messageType === 'chat' && (typeof content !== 'string' || content.trim().length === 0)) {
38
- console.error('Cannot broadcast empty chat message');
40
+ this.debug.error('Cannot broadcast empty chat message');
39
41
  return null;
40
42
  }
41
43
 
42
44
  if (messageType === 'encrypted' && (typeof content !== 'object' || !content.encrypted)) {
43
- console.error('Cannot broadcast invalid encrypted message');
45
+ this.debug.error('Cannot broadcast invalid encrypted message');
44
46
  return null;
45
47
  }
46
48
 
@@ -56,7 +58,7 @@ export class GossipManager extends EventEmitter {
56
58
  path: [this.mesh.peerId] // Track propagation path
57
59
  };
58
60
 
59
- console.log(`Broadcasting ${messageType} message: ${messageId.substring(0, 8)}... content: "${content}"`);
61
+ this.debug.log(`Broadcasting ${messageType} message: ${messageId.substring(0, 8)}... content: "${content}"`);
60
62
 
61
63
  // Store our own message
62
64
  this.seenMessages.set(messageId, {
@@ -91,13 +93,13 @@ export class GossipManager extends EventEmitter {
91
93
  */
92
94
  sendDirectMessage(targetPeerId, content, subtype = 'dm') {
93
95
  if (!targetPeerId || typeof targetPeerId !== 'string') {
94
- console.error('Invalid targetPeerId for direct message');
96
+ this.debug.error('Invalid targetPeerId for direct message');
95
97
  return null;
96
98
  }
97
99
 
98
100
  // Validate peer ID format (40-character hex string)
99
101
  if (!/^[a-fA-F0-9]{40}$/.test(targetPeerId)) {
100
- console.error('Invalid peer ID format for direct message:', targetPeerId);
102
+ this.debug.error('Invalid peer ID format for direct message:', targetPeerId);
101
103
  return null;
102
104
  }
103
105
 
@@ -128,36 +130,36 @@ export class GossipManager extends EventEmitter {
128
130
  * Handle incoming gossip message from a peer
129
131
  */
130
132
  async handleGossipMessage(message, fromPeerId) {
131
- console.log(`🔥🔥🔥 GOSSIP MESSAGE RECEIVED! From: ${fromPeerId?.substring(0, 8)}...`);
132
- console.log('🔥🔥🔥 Message:', message);
133
+ this.debug.log(`🔥🔥🔥 GOSSIP MESSAGE RECEIVED! From: ${fromPeerId?.substring(0, 8)}...`);
134
+ this.debug.log('🔥🔥🔥 Message:', message);
133
135
 
134
136
  const { id: messageId, ttl, from: originPeerId, subtype, content, timestamp, path, to } = message;
135
137
 
136
138
  // Validate message structure
137
139
  if (!messageId || !originPeerId || !subtype || content === undefined) {
138
- console.error('Invalid gossip message structure:', message);
140
+ this.debug.error('Invalid gossip message structure:', message);
139
141
  return;
140
142
  }
141
143
 
142
144
  // Check if we've already seen this message
143
145
  if (this.seenMessages.has(messageId)) {
144
- console.log(`Ignoring duplicate message: ${messageId.substring(0, 8)}...`);
146
+ this.debug.log(`Ignoring duplicate message: ${messageId.substring(0, 8)}...`);
145
147
  return;
146
148
  }
147
149
 
148
150
  // Check TTL
149
151
  if (ttl <= 0) {
150
- console.log(`Message expired: ${messageId.substring(0, 8)}...`);
152
+ this.debug.log(`Message expired: ${messageId.substring(0, 8)}...`);
151
153
  return;
152
154
  }
153
155
 
154
156
  // Check for loops (our peer ID in path)
155
157
  if (path && path.includes(this.mesh.peerId)) {
156
- console.log(`Preventing message loop: ${messageId.substring(0, 8)}...`);
158
+ this.debug.log(`Preventing message loop: ${messageId.substring(0, 8)}...`);
157
159
  return;
158
160
  }
159
161
 
160
- console.log(`Received gossip message: ${messageId.substring(0, 8)}... from ${fromPeerId.substring(0, 8)}... (TTL: ${ttl}, content: "${content}")`);
162
+ this.debug.log(`Received gossip message: ${messageId.substring(0, 8)}... from ${fromPeerId.substring(0, 8)}... (TTL: ${ttl}, content: "${content}")`);
161
163
 
162
164
  // Store message to prevent duplicates
163
165
  this.seenMessages.set(messageId, {
@@ -183,9 +185,9 @@ export class GossipManager extends EventEmitter {
183
185
  try {
184
186
  processedContent = await this.mesh.decryptMessage(content);
185
187
  isEncrypted = true;
186
- console.log(`🔐 Decrypted message from ${originPeerId.substring(0, 8)}...`);
188
+ this.debug.log(`🔐 Decrypted message from ${originPeerId.substring(0, 8)}...`);
187
189
  } catch (error) {
188
- console.error('Failed to decrypt message:', error);
190
+ this.debug.error('Failed to decrypt message:', error);
189
191
  // Continue with original content
190
192
  processedContent = content;
191
193
  }
@@ -205,7 +207,7 @@ export class GossipManager extends EventEmitter {
205
207
  encrypted: isEncrypted
206
208
  });
207
209
  } else {
208
- console.warn('Ignoring gossip chat message with invalid content:', processedContent);
210
+ this.debug.warn('Ignoring gossip chat message with invalid content:', processedContent);
209
211
  return;
210
212
  }
211
213
  } else if (subtype === 'encrypted') {
@@ -221,6 +223,9 @@ export class GossipManager extends EventEmitter {
221
223
  });
222
224
  } else if (subtype === 'peer-announcement') {
223
225
  this.handlePeerAnnouncement(content, originPeerId);
226
+ } else if (subtype === 'mediaEvent') {
227
+ // Handle media streaming events
228
+ this.handleMediaEvent(content, originPeerId);
224
229
  } else if (subtype === 'dm') {
225
230
  // Direct message logic
226
231
  if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
@@ -242,7 +247,7 @@ export class GossipManager extends EventEmitter {
242
247
  } else if (subtype === 'dht-routing') {
243
248
  // DHT routing message - check if we're the target
244
249
  if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
245
- console.log(`DHT: Received routed message for us from ${originPeerId.substring(0, 8)}`);
250
+ this.debug.log(`DHT: Received routed message for us from ${originPeerId.substring(0, 8)}`);
246
251
  // We are the target, deliver the DHT message locally
247
252
  if (this.mesh.webDHT && content) {
248
253
  // Simulate receiving the message from the original sender
@@ -251,7 +256,7 @@ export class GossipManager extends EventEmitter {
251
256
  // Do NOT relay further since we are the recipient
252
257
  return;
253
258
  } else {
254
- console.log(`DHT: Routing message for ${to?.substring(0, 8)} (not us)`);
259
+ this.debug.log(`DHT: Routing message for ${to?.substring(0, 8)} (not us)`);
255
260
  // Not the target, continue routing
256
261
  }
257
262
  }
@@ -271,7 +276,7 @@ export class GossipManager extends EventEmitter {
271
276
  handlePeerAnnouncement(announcementData, originPeerId) {
272
277
  const { peerId: announcedPeerId } = announcementData;
273
278
 
274
- console.log(`Gossip peer announcement: ${announcedPeerId.substring(0, 8)}... via ${originPeerId.substring(0, 8)}...`);
279
+ this.debug.log(`Gossip peer announcement: ${announcedPeerId.substring(0, 8)}... via ${originPeerId.substring(0, 8)}...`);
275
280
 
276
281
  // Add to discovered peers if we don't know about them
277
282
  if (!this.mesh.peerDiscovery.hasPeer(announcedPeerId) &&
@@ -285,6 +290,37 @@ export class GossipManager extends EventEmitter {
285
290
  }
286
291
  }
287
292
 
293
+ /**
294
+ * Handle media streaming events received via gossip
295
+ */
296
+ handleMediaEvent(eventData, originPeerId) {
297
+ const { event, peerId, hasVideo, hasAudio, timestamp } = eventData;
298
+
299
+ this.debug.log(`Media event gossip: ${event} from ${peerId.substring(0, 8)}... via ${originPeerId.substring(0, 8)}...`);
300
+
301
+ // Don't process our own events
302
+ if (peerId === this.mesh.peerId) {
303
+ return;
304
+ }
305
+
306
+ // Emit the media event for the UI to handle
307
+ if (event === 'streamStarted') {
308
+ this.mesh.emit('remoteStreamAnnouncement', {
309
+ peerId,
310
+ hasVideo,
311
+ hasAudio,
312
+ timestamp,
313
+ event: 'started'
314
+ });
315
+ } else if (event === 'streamStopped') {
316
+ this.mesh.emit('remoteStreamAnnouncement', {
317
+ peerId,
318
+ timestamp,
319
+ event: 'stopped'
320
+ });
321
+ }
322
+ }
323
+
288
324
  /**
289
325
  * Broadcast peer announcement via gossip when we connect
290
326
  */
@@ -294,7 +330,7 @@ export class GossipManager extends EventEmitter {
294
330
  timestamp: Date.now()
295
331
  };
296
332
 
297
- console.log(`Gossiping peer announcement for: ${peerId.substring(0, 8)}...`);
333
+ this.debug.log(`Gossiping peer announcement for: ${peerId.substring(0, 8)}...`);
298
334
  this.broadcastMessage(announcementData, 'peer-announcement');
299
335
  }
300
336
 
@@ -337,9 +373,9 @@ export class GossipManager extends EventEmitter {
337
373
  try {
338
374
  peer.sendMessage(message);
339
375
  const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
340
- console.log(`${routingType} routed to closest peer: ${peer.peerId.substring(0, 8)}...`);
376
+ this.debug.log(`${routingType} routed to closest peer: ${peer.peerId.substring(0, 8)}...`);
341
377
  } catch (error) {
342
- console.error(`${message.subtype} routing failed:`, error);
378
+ this.debug.error(`${message.subtype} routing failed:`, error);
343
379
  }
344
380
  });
345
381
  } else {
@@ -349,9 +385,9 @@ export class GossipManager extends EventEmitter {
349
385
  try {
350
386
  peerConnection.sendMessage(message);
351
387
  const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
352
- console.log(`${routingType} fallback relay to: ${peerConnection.peerId.substring(0, 8)}...`);
388
+ this.debug.log(`${routingType} fallback relay to: ${peerConnection.peerId.substring(0, 8)}...`);
353
389
  } catch (error) {
354
- console.error(`${message.subtype} fallback relay failed:`, error);
390
+ this.debug.error(`${message.subtype} fallback relay failed:`, error);
355
391
  }
356
392
  });
357
393
  }
@@ -367,8 +403,8 @@ export class GossipManager extends EventEmitter {
367
403
 
368
404
  let propagatedTo = 0;
369
405
 
370
- console.log(`🚀 AGGRESSIVE GOSSIP: Found ${capablePeers.length}/${allPeers.length} peers with open data channels`);
371
- console.log(`Message: ${message.id.substring(0, 8)}..., TTL: ${message.ttl}, Exclude: ${excludePeerId?.substring(0, 8) || 'none'}`);
406
+ this.debug.log(`🚀 AGGRESSIVE GOSSIP: Found ${capablePeers.length}/${allPeers.length} peers with open data channels`);
407
+ this.debug.log(`Message: ${message.id.substring(0, 8)}..., TTL: ${message.ttl}, Exclude: ${excludePeerId?.substring(0, 8) || 'none'}`);
372
408
 
373
409
  // Debug: show state of ALL peers
374
410
  allPeers.forEach(peerConnection => {
@@ -376,7 +412,7 @@ export class GossipManager extends EventEmitter {
376
412
  const dataChannelState = peerConnection.dataChannel?.readyState || 'none';
377
413
  const canSend = peerConnection.dataChannel && peerConnection.dataChannel.readyState === 'open';
378
414
  const isExcluded = peerConnection.peerId === excludePeerId;
379
- console.log(` ${peerConnection.peerId.substring(0, 8)}... - Status: ${status}, DataChannel: ${dataChannelState}, CanSend: ${canSend}, Excluded: ${isExcluded}`);
415
+ this.debug.log(` ${peerConnection.peerId.substring(0, 8)}... - Status: ${status}, DataChannel: ${dataChannelState}, CanSend: ${canSend}, Excluded: ${isExcluded}`);
380
416
  });
381
417
 
382
418
  capablePeers.forEach(peerConnection => {
@@ -390,16 +426,16 @@ export class GossipManager extends EventEmitter {
390
426
  try {
391
427
  peerConnection.sendMessage(message);
392
428
  propagatedTo++;
393
- console.log(`✅ GOSSIP SUCCESS: Sent to ${peerId.substring(0, 8)}...`);
429
+ this.debug.log(`✅ GOSSIP SUCCESS: Sent to ${peerId.substring(0, 8)}...`);
394
430
  } catch (error) {
395
- console.error(`❌ GOSSIP FAILED: Could not send to ${peerId.substring(0, 8)}...`, error);
431
+ this.debug.error(`❌ GOSSIP FAILED: Could not send to ${peerId.substring(0, 8)}...`, error);
396
432
  }
397
433
  });
398
434
 
399
- console.log(`🎯 GOSSIP RESULT: Propagated to ${propagatedTo}/${capablePeers.length} capable peers`);
435
+ this.debug.log(`🎯 GOSSIP RESULT: Propagated to ${propagatedTo}/${capablePeers.length} capable peers`);
400
436
 
401
437
  if (propagatedTo === 0 && allPeers.length > 0) {
402
- console.error(`🚨 GOSSIP FAILURE: NO PROPAGATION! ${allPeers.length} total peers, ${capablePeers.length} with data channels`);
438
+ this.debug.error(`🚨 GOSSIP FAILURE: NO PROPAGATION! ${allPeers.length} total peers, ${capablePeers.length} with data channels`);
403
439
  }
404
440
  }
405
441
 
@@ -467,7 +503,7 @@ export class GossipManager extends EventEmitter {
467
503
  });
468
504
 
469
505
  if (cleaned > 0) {
470
- console.log(`Cleaned up ${cleaned} expired gossip messages`);
506
+ this.debug.log(`Cleaned up ${cleaned} expired gossip messages`);
471
507
  }
472
508
  }
473
509
 
@@ -490,7 +526,7 @@ export class GossipManager extends EventEmitter {
490
526
  // Handle key exchange messages
491
527
  if (subtype === 'key_exchange' || subtype === 'key_exchange_response') {
492
528
  if (content && (content.type === 'key_exchange' || content.type === 'key_exchange_response') && content.publicKey) {
493
- console.log(`🔐 Received ${content.type} from peer ${originPeerId.substring(0, 8)}...`);
529
+ this.debug.log(`🔐 Received ${content.type} from peer ${originPeerId.substring(0, 8)}...`);
494
530
 
495
531
  // Use the mesh's key exchange handler which properly handles both pub and epub keys
496
532
  this.mesh._handleKeyExchange(content, originPeerId);
@@ -1,9 +1,11 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { environmentDetector } from './EnvironmentDetector.js';
3
+ import DebugLogger from './DebugLogger.js';
3
4
 
4
5
  export class MediaManager extends EventEmitter {
5
6
  constructor() {
6
7
  super();
8
+ this.debug = DebugLogger.create('MediaManager');
7
9
  this.localStream = null;
8
10
  this.isVideoEnabled = false;
9
11
  this.isAudioEnabled = false;
@@ -33,7 +35,7 @@ export class MediaManager extends EventEmitter {
33
35
  async init() {
34
36
  // Check if media APIs are available
35
37
  if (!environmentDetector.hasGetUserMedia) {
36
- console.warn('getUserMedia not available in this environment');
38
+ this.debug.warn('getUserMedia not available in this environment');
37
39
  this.emit('error', { type: 'init', error: new Error('getUserMedia not supported') });
38
40
  return false;
39
41
  }
@@ -43,7 +45,7 @@ export class MediaManager extends EventEmitter {
43
45
  await this.enumerateDevices();
44
46
  return true;
45
47
  } catch (error) {
46
- console.error('Failed to initialize media manager:', error);
48
+ this.debug.error('Failed to initialize media manager:', error);
47
49
  this.emit('error', { type: 'init', error });
48
50
  return false;
49
51
  }
@@ -57,7 +59,7 @@ export class MediaManager extends EventEmitter {
57
59
  if ((!environmentDetector.isBrowser && !environmentDetector.isNativeScript) ||
58
60
  typeof navigator === 'undefined' ||
59
61
  typeof navigator.mediaDevices === 'undefined') {
60
- console.warn('Media device enumeration not available in this environment');
62
+ this.debug.warn('Media device enumeration not available in this environment');
61
63
  return;
62
64
  }
63
65
 
@@ -71,7 +73,7 @@ export class MediaManager extends EventEmitter {
71
73
  this.emit('devicesUpdated', this.devices);
72
74
  return this.devices;
73
75
  } catch (error) {
74
- console.error('Failed to enumerate devices:', error);
76
+ this.debug.error('Failed to enumerate devices:', error);
75
77
  this.emit('error', { type: 'enumerate', error });
76
78
  throw error;
77
79
  }
@@ -116,7 +118,7 @@ export class MediaManager extends EventEmitter {
116
118
  // Mark stream as local origin to prevent confusion with remote streams
117
119
  this.markStreamAsLocal(this.localStream);
118
120
 
119
- console.log('Local media stream started:', {
121
+ this.debug.log('Local media stream started:', {
120
122
  video: this.isVideoEnabled,
121
123
  audio: this.isAudioEnabled,
122
124
  tracks: this.localStream.getTracks().map(track => ({
@@ -134,7 +136,7 @@ export class MediaManager extends EventEmitter {
134
136
 
135
137
  return this.localStream;
136
138
  } catch (error) {
137
- console.error('Failed to start local media stream:', error);
139
+ this.debug.error('Failed to start local media stream:', error);
138
140
  this.emit('error', { type: 'getUserMedia', error });
139
141
  throw error;
140
142
  }
@@ -145,7 +147,7 @@ export class MediaManager extends EventEmitter {
145
147
  */
146
148
  stopLocalStream() {
147
149
  if (this.localStream) {
148
- console.log('Stopping local media stream');
150
+ this.debug.log('Stopping local media stream');
149
151
  this.localStream.getTracks().forEach(track => {
150
152
  track.stop();
151
153
  });
@@ -237,7 +239,7 @@ export class MediaManager extends EventEmitter {
237
239
 
238
240
  return permissions;
239
241
  } catch (error) {
240
- console.warn('Could not check media permissions:', error);
242
+ this.debug.warn('Could not check media permissions:', error);
241
243
  return {};
242
244
  }
243
245
  }
@@ -256,9 +258,9 @@ export class MediaManager extends EventEmitter {
256
258
  configurable: false
257
259
  });
258
260
 
259
- console.log(`🔒 Stream ${stream.id} marked as local origin in MediaManager`);
261
+ this.debug.log(`🔒 Stream ${stream.id} marked as local origin in MediaManager`);
260
262
  } catch (error) {
261
- console.warn('Could not mark stream as local origin:', error);
263
+ this.debug.warn('Could not mark stream as local origin:', error);
262
264
  }
263
265
  }
264
266
  }