peerpigeon 0.1.1 → 1.0.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.
Files changed (70) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12290 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1945 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  9. package/docs/HUB_QUICK_REF.md +107 -0
  10. package/docs/HUB_SCRIPTS.md +331 -0
  11. package/docs/HUB_SYSTEM.md +552 -0
  12. package/docs/MIGRATION_COMPLETE.md +93 -0
  13. package/docs/NETWORK_NAMESPACES.md +212 -0
  14. package/docs/README.md +107 -0
  15. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  16. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  17. package/examples/bootstrap-hub-example.js +292 -0
  18. package/examples/browser/README.md +278 -0
  19. package/examples/browser/app.js +2426 -49
  20. package/examples/browser/index.html +481 -630
  21. package/examples/browser/minimal/README.md +55 -0
  22. package/examples/browser/minimal/index.html +75 -0
  23. package/examples/browser/minimal/minimal.js +234 -0
  24. package/examples/browser/styles.css +687 -1425
  25. package/examples/browser/test-bundle.html +35 -0
  26. package/examples/browser-2/index.html +30 -0
  27. package/examples/browser-2/package.json +21 -0
  28. package/examples/browser-2/src/App-simple.vue +21 -0
  29. package/examples/browser-2/src/App.vue +420 -0
  30. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  31. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  32. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  33. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  34. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  35. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  36. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  37. package/examples/browser-2/src/main.js +5 -0
  38. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  39. package/examples/browser-2/vite.config.js +6 -0
  40. package/examples/hub-example.js +186 -0
  41. package/examples/multi-hub-test.js +186 -0
  42. package/examples/node/README.md +2 -2
  43. package/examples/selective-streaming-demo.html +698 -0
  44. package/examples/standard-events-demo.js +126 -0
  45. package/package.json +33 -16
  46. package/server/index.js +1032 -98
  47. package/server/start.js +49 -0
  48. package/src/ConnectionManager.js +239 -225
  49. package/src/CryptoManager.js +147 -18
  50. package/src/DebugLogger.js +0 -7
  51. package/src/DistributedStorageManager.js +224 -205
  52. package/src/EnvironmentDetector.js +109 -2
  53. package/src/EventEmitter.js +79 -1
  54. package/src/EvictionManager.js +10 -9
  55. package/src/GossipManager.js +163 -11
  56. package/src/PeerConnection.js +333 -310
  57. package/src/PeerPigeonMesh.js +577 -135
  58. package/src/SignalingClient.js +14 -243
  59. package/src/SignalingHandler.js +31 -10
  60. package/src/StorageManager.js +0 -39
  61. package/src/WebDHT-Simple.js +389 -0
  62. package/src/WebDHT.js +363 -1165
  63. package/src/browser-entry.js +40 -0
  64. package/examples/browser/assets/images/favicon.png +0 -0
  65. package/examples/browser/assets/images/pigeon.png +0 -0
  66. package/examples/browser/crypto-test.html +0 -427
  67. package/examples/browser/ui-old.js +0 -1926
  68. package/examples/browser/ui.js +0 -3391
  69. package/websocket-server/README.md +0 -247
  70. package/websocket-server/server.js +0 -391
@@ -0,0 +1,895 @@
1
+ import { defineStore } from 'pinia';
2
+ import { ref, reactive, computed } from 'vue';
3
+
4
+ export const usePeerPigeonStore = defineStore('peerpigeon', () => {
5
+ // Core state
6
+ const mesh = ref(null);
7
+ const isInitialized = ref(false);
8
+ const isConnected = ref(false);
9
+ const signalingUrl = ref('ws://localhost:3000');
10
+ const peerId = ref('');
11
+
12
+ // Network namespace state
13
+ const networkName = ref('global');
14
+ const originalNetworkName = ref('global');
15
+ const isInFallbackMode = ref(false);
16
+ const allowGlobalFallback = ref(true);
17
+
18
+ // Network state
19
+ const peers = reactive(new Map());
20
+ const discoveredPeers = reactive(new Map());
21
+ const networkStatus = reactive({
22
+ connectedCount: 0,
23
+ maxPeers: 3,
24
+ minPeers: 2,
25
+ autoDiscovery: true,
26
+ evictionStrategy: true,
27
+ xorRouting: true
28
+ });
29
+
30
+ // Messages
31
+ const messages = ref([]);
32
+ const directMessages = reactive(new Map());
33
+
34
+ // Media state
35
+ const mediaState = reactive({
36
+ localStream: null,
37
+ remoteStreams: new Map(),
38
+ audioEnabled: false,
39
+ videoEnabled: false,
40
+ devices: []
41
+ });
42
+
43
+ // DHT state
44
+ const dhtData = reactive(new Map());
45
+ const dhtStats = reactive({});
46
+
47
+ // Storage state
48
+ const storageData = reactive(new Map());
49
+ const storageStats = reactive({});
50
+
51
+ // Crypto state
52
+ const cryptoKeys = ref([]);
53
+ const cryptoState = reactive({
54
+ enabled: false,
55
+ initialized: false,
56
+ publicKey: '',
57
+ peerKeys: new Map()
58
+ });
59
+
60
+ // Debug state
61
+ const debugLogs = ref([]);
62
+ const debugModules = ref([]);
63
+ const enabledModules = ref(new Set());
64
+
65
+ // Computed
66
+ const connectedPeersList = computed(() => {
67
+ return Array.from(peers.values()).filter(peer => peer.connected);
68
+ });
69
+
70
+ const canAcceptMorePeers = computed(() => {
71
+ return networkStatus.connectedCount < networkStatus.maxPeers;
72
+ });
73
+
74
+ // Core methods
75
+ const initMesh = async (options = {}) => {
76
+ try {
77
+ // Use real PeerPigeonMesh if available, otherwise mock
78
+ const PeerPigeonMeshClass = window.PeerPigeon?.PeerPigeonMesh;
79
+
80
+ if (!PeerPigeonMeshClass) {
81
+ // Fallback to mock implementation for development
82
+ const MockPeerPigeonMesh = class {
83
+ constructor(meshOptions) {
84
+ this.options = meshOptions;
85
+ this.peerId = 'mock-peer-' + Math.random().toString(36).substr(2, 9);
86
+ this.eventListeners = new Map();
87
+ this.networkName = meshOptions.networkName || 'global';
88
+ this.originalNetworkName = this.networkName;
89
+ this.isInFallbackMode = false;
90
+ this.allowGlobalFallback = meshOptions.allowGlobalFallback !== false;
91
+ }
92
+
93
+ async init() {
94
+ addDebugLog('Mock mesh initialized', 'success');
95
+ return true;
96
+ }
97
+
98
+ async connect(url) {
99
+ addDebugLog(`Mock connected to ${url}`, 'success');
100
+ return true;
101
+ }
102
+
103
+ disconnect() {
104
+ addDebugLog('Mock disconnected', 'info');
105
+ }
106
+
107
+ addEventListener(event, handler) {
108
+ if (!this.eventListeners.has(event)) {
109
+ this.eventListeners.set(event, []);
110
+ }
111
+ this.eventListeners.get(event).push(handler);
112
+ }
113
+
114
+ sendMessage(content) {
115
+ addDebugLog(`Mock broadcast: ${JSON.stringify(content)}`, 'info');
116
+ return 'mock-message-id-' + Date.now();
117
+ }
118
+
119
+ sendDirectMessage(peerId, content) {
120
+ addDebugLog(`Mock direct to ${peerId}: ${JSON.stringify(content)}`, 'info');
121
+ return 'mock-message-id-' + Date.now();
122
+ }
123
+
124
+ getStatus() {
125
+ return {
126
+ connectedCount: 0,
127
+ maxPeers: networkStatus.maxPeers,
128
+ minPeers: networkStatus.minPeers,
129
+ autoDiscovery: networkStatus.autoDiscovery,
130
+ evictionStrategy: networkStatus.evictionStrategy,
131
+ xorRouting: networkStatus.xorRouting,
132
+ networkName: this.networkName,
133
+ originalNetworkName: this.originalNetworkName,
134
+ isInFallbackMode: this.isInFallbackMode,
135
+ allowGlobalFallback: this.allowGlobalFallback
136
+ };
137
+ }
138
+
139
+ setNetworkName(name) {
140
+ this.networkName = name || 'global';
141
+ this.originalNetworkName = this.networkName;
142
+ this.isInFallbackMode = false;
143
+ addDebugLog(`Mock network changed to: ${this.networkName}`, 'info');
144
+ return this.networkName;
145
+ }
146
+
147
+ getNetworkName() {
148
+ return this.networkName;
149
+ }
150
+
151
+ getOriginalNetworkName() {
152
+ return this.originalNetworkName;
153
+ }
154
+
155
+ isUsingGlobalFallback() {
156
+ return this.isInFallbackMode;
157
+ }
158
+
159
+ setAllowGlobalFallback(allow) {
160
+ this.allowGlobalFallback = allow;
161
+ addDebugLog(`Mock global fallback ${allow ? 'enabled' : 'disabled'}`, 'info');
162
+ return this.allowGlobalFallback;
163
+ }
164
+
165
+ async startMedia(options) {
166
+ addDebugLog(`Mock media started: ${JSON.stringify(options)}`, 'info');
167
+ return null; // Mock stream
168
+ }
169
+
170
+ async stopMedia() {
171
+ addDebugLog('Mock media stopped', 'info');
172
+ }
173
+
174
+ async dhtPut(key, _value, _options) {
175
+ addDebugLog(`Mock DHT PUT: ${key}`, 'info');
176
+ return true;
177
+ }
178
+
179
+ async dhtGet(key, _options) {
180
+ addDebugLog(`Mock DHT GET: ${key}`, 'info');
181
+ return null;
182
+ }
183
+
184
+ getDHTStats() {
185
+ return { entries: 0, peers: 0 };
186
+ }
187
+
188
+ get distributedStorage() {
189
+ return {
190
+ store: async (key, _value, _options) => {
191
+ addDebugLog(`Mock storage STORE: ${key}`, 'info');
192
+ return true;
193
+ },
194
+ retrieve: async (key, _options) => {
195
+ addDebugLog(`Mock storage RETRIEVE: ${key}`, 'info');
196
+ return null;
197
+ },
198
+ getStats: async () => ({ items: 0, size: 0 })
199
+ };
200
+ }
201
+
202
+ get cryptoManager() {
203
+ return {
204
+ init: async () => true,
205
+ getPublicKey: () => 'mock-public-key'
206
+ };
207
+ }
208
+ };
209
+
210
+ const meshOptions = {
211
+ enableWebDHT: true,
212
+ enableCrypto: true,
213
+ enableDistributedStorage: true,
214
+ networkName: networkName.value,
215
+ allowGlobalFallback: allowGlobalFallback.value,
216
+ maxPeers: networkStatus.maxPeers,
217
+ minPeers: networkStatus.minPeers,
218
+ autoDiscovery: networkStatus.autoDiscovery,
219
+ evictionStrategy: networkStatus.evictionStrategy,
220
+ xorRouting: networkStatus.xorRouting,
221
+ ...options
222
+ };
223
+
224
+ mesh.value = new MockPeerPigeonMesh(meshOptions);
225
+ } else {
226
+ // Use real PeerPigeonMesh
227
+ const meshOptions = {
228
+ enableWebDHT: true,
229
+ enableCrypto: true,
230
+ enableDistributedStorage: true,
231
+ networkName: networkName.value,
232
+ allowGlobalFallback: allowGlobalFallback.value,
233
+ maxPeers: networkStatus.maxPeers,
234
+ minPeers: networkStatus.minPeers,
235
+ autoDiscovery: networkStatus.autoDiscovery,
236
+ evictionStrategy: networkStatus.evictionStrategy,
237
+ xorRouting: networkStatus.xorRouting,
238
+ ...options
239
+ };
240
+
241
+ mesh.value = new PeerPigeonMeshClass(meshOptions);
242
+ }
243
+
244
+ setupEventHandlers();
245
+
246
+ await mesh.value.init();
247
+ isInitialized.value = true;
248
+ peerId.value = mesh.value.peerId;
249
+
250
+ // Update network state from mesh
251
+ if (mesh.value.getNetworkName) {
252
+ networkName.value = mesh.value.getNetworkName();
253
+ originalNetworkName.value = mesh.value.getOriginalNetworkName();
254
+ isInFallbackMode.value = mesh.value.isUsingGlobalFallback();
255
+ }
256
+
257
+ // Initialize crypto if enabled
258
+ if (mesh.value.cryptoManager) {
259
+ await mesh.value.cryptoManager.init();
260
+ cryptoState.enabled = true;
261
+ cryptoState.initialized = true;
262
+ cryptoState.publicKey = mesh.value.cryptoManager.getPublicKey();
263
+ }
264
+
265
+ addDebugLog(`Mesh initialized successfully in network: ${networkName.value}`, 'success');
266
+ return true;
267
+ } catch (error) {
268
+ addDebugLog(`Failed to initialize mesh: ${error.message}`, 'error');
269
+ throw error;
270
+ }
271
+ };
272
+
273
+ const connectToSignaling = async (url) => {
274
+ if (!mesh.value || !isInitialized.value) {
275
+ throw new Error('Mesh not initialized');
276
+ }
277
+
278
+ try {
279
+ signalingUrl.value = url;
280
+ await mesh.value.connect(url);
281
+ isConnected.value = true;
282
+ addDebugLog(`Connected to signaling server: ${url}`, 'success');
283
+ return true;
284
+ } catch (error) {
285
+ addDebugLog(`Failed to connect to signaling server: ${error.message}`, 'error');
286
+ throw error;
287
+ }
288
+ };
289
+
290
+ const disconnect = () => {
291
+ if (mesh.value) {
292
+ mesh.value.disconnect();
293
+ isConnected.value = false;
294
+ peers.clear();
295
+ discoveredPeers.clear();
296
+ networkStatus.connectedCount = 0;
297
+ addDebugLog('Disconnected from mesh', 'info');
298
+ }
299
+ };
300
+
301
+ // Event handlers setup
302
+ const setupEventHandlers = () => {
303
+ if (!mesh.value) return;
304
+
305
+ // Connection events
306
+ mesh.value.addEventListener('statusChanged', (event) => {
307
+ addDebugLog(`Status: ${event.type} - ${event.message || ''}`, 'info');
308
+
309
+ // Handle network-specific status changes
310
+ if (event.type === 'network') {
311
+ networkName.value = event.networkName || networkName.value;
312
+ isInFallbackMode.value = event.fallbackMode || false;
313
+ addDebugLog(`Network status: ${event.message}`, event.fallbackMode ? 'warning' : 'info');
314
+ }
315
+
316
+ // Handle settings changes
317
+ if (event.type === 'setting') {
318
+ if (event.setting === 'networkName') {
319
+ networkName.value = event.value;
320
+ } else if (event.setting === 'allowGlobalFallback') {
321
+ allowGlobalFallback.value = event.value;
322
+ }
323
+ }
324
+
325
+ updateNetworkStatus();
326
+ });
327
+
328
+ mesh.value.addEventListener('peerConnected', (event) => {
329
+ const peerInfo = {
330
+ id: event.peerId,
331
+ connected: true,
332
+ connectionTime: new Date(),
333
+ status: 'connected'
334
+ };
335
+ peers.set(event.peerId, peerInfo);
336
+ updateNetworkStatus();
337
+ addDebugLog(`Peer connected: ${event.peerId.substring(0, 8)}...`, 'success');
338
+ });
339
+
340
+ mesh.value.addEventListener('peerDisconnected', (event) => {
341
+ const peer = peers.get(event.peerId);
342
+ if (peer) {
343
+ peer.connected = false;
344
+ peer.status = 'disconnected';
345
+ peer.disconnectionTime = new Date();
346
+ peer.disconnectionReason = event.reason;
347
+ }
348
+ updateNetworkStatus();
349
+ addDebugLog(`Peer disconnected: ${event.peerId.substring(0, 8)}... (${event.reason})`, 'warning');
350
+ });
351
+
352
+ mesh.value.addEventListener('peerDiscovered', (event) => {
353
+ discoveredPeers.set(event.peerId, {
354
+ id: event.peerId,
355
+ discoveryTime: new Date(),
356
+ status: 'discovered'
357
+ });
358
+ addDebugLog(`Peer discovered: ${event.peerId.substring(0, 8)}...`, 'info');
359
+ });
360
+
361
+ // Message events
362
+ mesh.value.addEventListener('messageReceived', (event) => {
363
+ const message = {
364
+ id: event.messageId || Date.now().toString(),
365
+ content: event.message || event.content,
366
+ from: event.from,
367
+ timestamp: new Date(),
368
+ type: event.subtype || 'broadcast',
369
+ fromPeerId: event.from?.substring(0, 8) + '...' || 'unknown'
370
+ };
371
+
372
+ if (event.subtype === 'direct') {
373
+ if (!directMessages.has(event.from)) {
374
+ directMessages.set(event.from, []);
375
+ }
376
+ directMessages.get(event.from).push(message);
377
+ } else {
378
+ messages.value.push(message);
379
+ }
380
+
381
+ addDebugLog(`Message received from ${message.fromPeerId}: ${JSON.stringify(message.content)}`, 'info');
382
+ });
383
+
384
+ // Media events
385
+ mesh.value.addEventListener('localStreamStarted', (event) => {
386
+ mediaState.localStream = event.stream;
387
+ addDebugLog('Local media stream started', 'success');
388
+ });
389
+
390
+ mesh.value.addEventListener('localStreamStopped', () => {
391
+ mediaState.localStream = null;
392
+ addDebugLog('Local media stream stopped', 'info');
393
+ });
394
+
395
+ mesh.value.addEventListener('remoteStream', (event) => {
396
+ mediaState.remoteStreams.set(event.peerId, {
397
+ stream: event.stream,
398
+ peerId: event.peerId,
399
+ startTime: new Date()
400
+ });
401
+ addDebugLog(`Remote stream received from ${event.peerId.substring(0, 8)}...`, 'success');
402
+ });
403
+
404
+ mesh.value.addEventListener('remoteStreamEnded', (event) => {
405
+ mediaState.remoteStreams.delete(event.peerId);
406
+ addDebugLog(`Remote stream ended from ${event.peerId.substring(0, 8)}...`, 'info');
407
+ });
408
+
409
+ // DHT events
410
+ mesh.value.addEventListener('dhtValueChanged', (event) => {
411
+ dhtData.set(event.key, {
412
+ value: event.newValue,
413
+ timestamp: new Date(),
414
+ version: event.version
415
+ });
416
+ addDebugLog(`DHT value changed: ${event.key}`, 'info');
417
+ });
418
+
419
+ // Storage events
420
+ mesh.value.addEventListener('storageDataStored', (event) => {
421
+ addDebugLog(`Storage data stored: ${event.key}`, 'success');
422
+ });
423
+
424
+ mesh.value.addEventListener('storageDataUpdated', (event) => {
425
+ addDebugLog(`Storage data updated: ${event.key} (version ${event.version})`, 'info');
426
+ });
427
+
428
+ // Crypto events
429
+ mesh.value.addEventListener('cryptoReady', () => {
430
+ cryptoState.initialized = true;
431
+ addDebugLog('Crypto system ready', 'success');
432
+ });
433
+
434
+ mesh.value.addEventListener('peerKeyAdded', (event) => {
435
+ cryptoState.peerKeys.set(event.peerId, event.publicKey);
436
+ addDebugLog(`Peer key added: ${event.peerId.substring(0, 8)}...`, 'success');
437
+ });
438
+ };
439
+
440
+ // Utility methods
441
+ const updateNetworkStatus = () => {
442
+ if (!mesh.value) return;
443
+
444
+ const status = mesh.value.getStatus();
445
+ networkStatus.connectedCount = status.connectedCount;
446
+ networkStatus.maxPeers = status.maxPeers;
447
+ networkStatus.minPeers = status.minPeers;
448
+ networkStatus.autoDiscovery = status.autoDiscovery;
449
+ networkStatus.evictionStrategy = status.evictionStrategy;
450
+ networkStatus.xorRouting = status.xorRouting;
451
+ };
452
+
453
+ const addDebugLog = (message, level = 'info') => {
454
+ const log = {
455
+ timestamp: new Date(),
456
+ message,
457
+ level,
458
+ id: Date.now() + Math.random()
459
+ };
460
+ debugLogs.value.push(log);
461
+
462
+ // Keep only last 100 logs
463
+ if (debugLogs.value.length > 100) {
464
+ debugLogs.value.shift();
465
+ }
466
+ };
467
+
468
+ // Messaging methods
469
+ const sendBroadcastMessage = (content) => {
470
+ if (!mesh.value || !isConnected.value) {
471
+ throw new Error('Not connected to mesh');
472
+ }
473
+
474
+ const messageId = mesh.value.sendMessage(content);
475
+ const message = {
476
+ id: messageId,
477
+ content,
478
+ from: peerId.value,
479
+ timestamp: new Date(),
480
+ type: 'broadcast',
481
+ fromPeerId: 'You'
482
+ };
483
+ messages.value.push(message);
484
+ addDebugLog(`Broadcast message sent: ${JSON.stringify(content)}`, 'success');
485
+ return messageId;
486
+ };
487
+
488
+ const sendDirectMessage = (targetPeerId, content) => {
489
+ if (!mesh.value || !isConnected.value) {
490
+ throw new Error('Not connected to mesh');
491
+ }
492
+
493
+ const messageId = mesh.value.sendDirectMessage(targetPeerId, content);
494
+ const message = {
495
+ id: messageId,
496
+ content,
497
+ from: peerId.value,
498
+ to: targetPeerId,
499
+ timestamp: new Date(),
500
+ type: 'direct',
501
+ fromPeerId: 'You'
502
+ };
503
+
504
+ if (!directMessages.has(targetPeerId)) {
505
+ directMessages.set(targetPeerId, []);
506
+ }
507
+ directMessages.get(targetPeerId).push(message);
508
+ addDebugLog(`Direct message sent to ${targetPeerId.substring(0, 8)}...: ${JSON.stringify(content)}`, 'success');
509
+ return messageId;
510
+ };
511
+
512
+ // Media methods
513
+ const startMedia = async (options = {}) => {
514
+ if (!mesh.value) throw new Error('Mesh not initialized');
515
+
516
+ const stream = await mesh.value.startMedia(options);
517
+ mediaState.audioEnabled = stream.getAudioTracks().length > 0;
518
+ mediaState.videoEnabled = stream.getVideoTracks().length > 0;
519
+ return stream;
520
+ };
521
+
522
+ const stopMedia = async () => {
523
+ if (!mesh.value) return;
524
+
525
+ await mesh.value.stopMedia();
526
+ mediaState.audioEnabled = false;
527
+ mediaState.videoEnabled = false;
528
+ };
529
+
530
+ // DHT methods
531
+ const dhtPut = async (key, value, options = {}) => {
532
+ if (!mesh.value) throw new Error('Mesh not initialized');
533
+
534
+ const success = await mesh.value.dhtPut(key, value, options);
535
+ if (success) {
536
+ dhtData.set(key, {
537
+ value,
538
+ timestamp: new Date(),
539
+ local: true
540
+ });
541
+ addDebugLog(`DHT put: ${key}`, 'success');
542
+ }
543
+ return success;
544
+ };
545
+
546
+ const dhtGet = async (key, options = {}) => {
547
+ if (!mesh.value) throw new Error('Mesh not initialized');
548
+
549
+ const value = await mesh.value.dhtGet(key, options);
550
+ if (value !== null) {
551
+ dhtData.set(key, {
552
+ value,
553
+ timestamp: new Date(),
554
+ local: false
555
+ });
556
+ addDebugLog(`DHT get: ${key}`, 'success');
557
+ }
558
+ return value;
559
+ };
560
+
561
+ const getDHTStats = () => {
562
+ if (!mesh.value) return {};
563
+ return mesh.value.getDHTStats();
564
+ };
565
+
566
+ // Storage methods
567
+ const storageStore = async (key, value, options = {}) => {
568
+ if (!mesh.value?.distributedStorage) throw new Error('Distributed storage not available');
569
+
570
+ const result = await mesh.value.distributedStorage.store(key, value, options);
571
+ storageData.set(key, {
572
+ value,
573
+ options,
574
+ timestamp: new Date(),
575
+ local: true
576
+ });
577
+ return result;
578
+ };
579
+
580
+ const storageRetrieve = async (key, options = {}) => {
581
+ if (!mesh.value?.distributedStorage) throw new Error('Distributed storage not available');
582
+
583
+ const value = await mesh.value.distributedStorage.retrieve(key, options);
584
+ if (value !== null) {
585
+ storageData.set(key, {
586
+ value,
587
+ timestamp: new Date(),
588
+ local: false
589
+ });
590
+ }
591
+ return value;
592
+ };
593
+
594
+ const getStorageStats = async () => {
595
+ if (!mesh.value?.distributedStorage) return {};
596
+ return await mesh.value.distributedStorage.getStats();
597
+ };
598
+
599
+ // Debug methods
600
+ const getDebugModules = () => {
601
+ // Return the debug logger modules if available
602
+ if (mesh.value?.debugLogger) {
603
+ return mesh.value.debugLogger.getModules();
604
+ }
605
+ return ['PeerPigeonMesh', 'ConnectionManager', 'GossipManager', 'WebDHT', 'CryptoManager', 'MediaManager'];
606
+ };
607
+
608
+ const enableDebugModule = (moduleName) => {
609
+ enabledModules.value.add(moduleName);
610
+ // Enable the module in DebugLogger if available
611
+ if (mesh.value?.debugLogger) {
612
+ mesh.value.debugLogger.enable(moduleName);
613
+ }
614
+ addDebugLog(`Debug enabled for module: ${moduleName}`, 'info');
615
+ };
616
+
617
+ const disableDebugModule = (moduleName) => {
618
+ enabledModules.value.delete(moduleName);
619
+ // Disable the module in DebugLogger if available
620
+ if (mesh.value?.debugLogger) {
621
+ mesh.value.debugLogger.disable(moduleName);
622
+ }
623
+ addDebugLog(`Debug disabled for module: ${moduleName}`, 'info');
624
+ };
625
+
626
+ const clearDebugLogs = () => {
627
+ debugLogs.value = [];
628
+ };
629
+
630
+ // Crypto methods (placeholder implementations)
631
+ const initializeCrypto = async () => {
632
+ try {
633
+ cryptoState.initialized = true;
634
+ addDebugLog('Crypto system initialized', 'success');
635
+ return true;
636
+ } catch (error) {
637
+ addDebugLog(`Crypto initialization failed: ${error.message}`, 'error');
638
+ return false;
639
+ }
640
+ };
641
+
642
+ const cryptoGenerateKey = async (type, size, name) => {
643
+ try {
644
+ const keyPair = {
645
+ id: Date.now().toString(),
646
+ name,
647
+ type,
648
+ size,
649
+ algorithm: type,
650
+ usage: ['encrypt', 'decrypt', 'sign', 'verify'],
651
+ extractable: true,
652
+ created: Date.now(),
653
+ fingerprint: Math.random().toString(36).substring(2)
654
+ };
655
+
656
+ cryptoKeys.value.push(keyPair);
657
+ addDebugLog(`Generated ${type} key: ${name}`, 'success');
658
+ return keyPair;
659
+ } catch (error) {
660
+ addDebugLog(`Key generation failed: ${error.message}`, 'error');
661
+ return null;
662
+ }
663
+ };
664
+
665
+ const cryptoImportKey = async (keyData, name) => {
666
+ try {
667
+ const key = {
668
+ id: Date.now().toString(),
669
+ name,
670
+ type: 'imported',
671
+ algorithm: 'RSA',
672
+ usage: ['encrypt', 'decrypt'],
673
+ extractable: true,
674
+ created: Date.now(),
675
+ fingerprint: Math.random().toString(36).substring(2)
676
+ };
677
+
678
+ cryptoKeys.value.push(key);
679
+ addDebugLog(`Imported key: ${name}`, 'success');
680
+ return true;
681
+ } catch (error) {
682
+ addDebugLog(`Key import failed: ${error.message}`, 'error');
683
+ return false;
684
+ }
685
+ };
686
+
687
+ const cryptoEncrypt = async (data, keyId, _options) => {
688
+ try {
689
+ // Mock encryption - in real implementation would use WebCrypto
690
+ const encrypted = btoa(JSON.stringify(data));
691
+ addDebugLog(`Data encrypted with key: ${keyId}`, 'success');
692
+ return encrypted;
693
+ } catch (error) {
694
+ addDebugLog(`Encryption failed: ${error.message}`, 'error');
695
+ return null;
696
+ }
697
+ };
698
+
699
+ const cryptoDecrypt = async (encryptedData, keyId) => {
700
+ try {
701
+ // Mock decryption
702
+ const decrypted = JSON.parse(atob(encryptedData));
703
+ addDebugLog(`Data decrypted with key: ${keyId}`, 'success');
704
+ return decrypted;
705
+ } catch (error) {
706
+ addDebugLog(`Decryption failed: ${error.message}`, 'error');
707
+ return null;
708
+ }
709
+ };
710
+
711
+ const cryptoSign = async (data, keyId, _options) => {
712
+ try {
713
+ // Mock signing
714
+ const signature = btoa(data + keyId + Date.now());
715
+ addDebugLog(`Data signed with key: ${keyId}`, 'success');
716
+ return signature;
717
+ } catch (error) {
718
+ addDebugLog(`Signing failed: ${error.message}`, 'error');
719
+ return null;
720
+ }
721
+ };
722
+
723
+ const cryptoVerify = async (data, signature, keyId) => {
724
+ try {
725
+ // Mock verification - always returns true for demo
726
+ addDebugLog(`Signature verified with key: ${keyId}`, 'success');
727
+ return true;
728
+ } catch (error) {
729
+ addDebugLog(`Verification failed: ${error.message}`, 'error');
730
+ return false;
731
+ }
732
+ };
733
+
734
+ const cryptoKeyExchange = async (peerId, method, purpose) => {
735
+ try {
736
+ const exchange = {
737
+ keyId: Date.now().toString(),
738
+ peerId,
739
+ method,
740
+ purpose,
741
+ created: Date.now()
742
+ };
743
+ addDebugLog(`Key exchange initiated: ${method}`, 'success');
744
+ return exchange;
745
+ } catch (error) {
746
+ addDebugLog(`Key exchange failed: ${error.message}`, 'error');
747
+ return null;
748
+ }
749
+ };
750
+
751
+ const cryptoRefreshKeys = async () => {
752
+ addDebugLog('Key store refreshed', 'info');
753
+ };
754
+
755
+ const cryptoExportKey = async (keyId) => {
756
+ const key = cryptoKeys.value.find(k => k.id === keyId);
757
+ if (key) {
758
+ addDebugLog(`Key exported: ${key.name}`, 'success');
759
+ return { ...key, privateKey: 'mock-private-key' };
760
+ }
761
+ return null;
762
+ };
763
+
764
+ const cryptoDeleteKey = async (keyId) => {
765
+ const index = cryptoKeys.value.findIndex(k => k.id === keyId);
766
+ if (index !== -1) {
767
+ const deleted = cryptoKeys.value.splice(index, 1)[0];
768
+ addDebugLog(`Key deleted: ${deleted.name}`, 'info');
769
+ return true;
770
+ }
771
+ return false;
772
+ };
773
+
774
+ // Network management methods
775
+ const setNetworkName = (name) => {
776
+ if (mesh.value && mesh.value.setNetworkName) {
777
+ const newName = mesh.value.setNetworkName(name);
778
+ networkName.value = newName;
779
+ originalNetworkName.value = mesh.value.getOriginalNetworkName();
780
+ isInFallbackMode.value = mesh.value.isUsingGlobalFallback();
781
+ addDebugLog(`Network changed to: ${newName}`, 'success');
782
+ return newName;
783
+ } else {
784
+ networkName.value = name || 'global';
785
+ originalNetworkName.value = networkName.value;
786
+ isInFallbackMode.value = false;
787
+ addDebugLog(`Network name set: ${networkName.value}`, 'info');
788
+ return networkName.value;
789
+ }
790
+ };
791
+
792
+ const getNetworkInfo = () => {
793
+ return {
794
+ currentNetwork: networkName.value,
795
+ originalNetwork: originalNetworkName.value,
796
+ isInFallbackMode: isInFallbackMode.value,
797
+ allowGlobalFallback: allowGlobalFallback.value
798
+ };
799
+ };
800
+
801
+ const setAllowGlobalFallback = (allow) => {
802
+ if (mesh.value && mesh.value.setAllowGlobalFallback) {
803
+ const result = mesh.value.setAllowGlobalFallback(allow);
804
+ allowGlobalFallback.value = result;
805
+ addDebugLog(`Global fallback ${allow ? 'enabled' : 'disabled'}`, 'success');
806
+ return result;
807
+ } else {
808
+ allowGlobalFallback.value = allow;
809
+ addDebugLog(`Global fallback setting: ${allow}`, 'info');
810
+ return allowGlobalFallback.value;
811
+ }
812
+ };
813
+
814
+ const forceReturnToOriginalNetwork = async () => {
815
+ if (mesh.value && mesh.value._tryReturnToOriginalNetwork) {
816
+ await mesh.value._tryReturnToOriginalNetwork();
817
+ networkName.value = mesh.value.getNetworkName();
818
+ isInFallbackMode.value = mesh.value.isUsingGlobalFallback();
819
+ addDebugLog('Attempted to return to original network', 'info');
820
+ } else {
821
+ addDebugLog('Force return to original network not available', 'warning');
822
+ }
823
+ };
824
+
825
+ return {
826
+ // State
827
+ mesh,
828
+ isInitialized,
829
+ isConnected,
830
+ signalingUrl,
831
+ peerId,
832
+ networkName,
833
+ originalNetworkName,
834
+ isInFallbackMode,
835
+ allowGlobalFallback,
836
+ peers,
837
+ discoveredPeers,
838
+ networkStatus,
839
+ messages,
840
+ directMessages,
841
+ mediaState,
842
+ dhtData,
843
+ dhtStats,
844
+ storageData,
845
+ storageStats,
846
+ cryptoKeys,
847
+ cryptoState,
848
+ debugLogs,
849
+ debugModules,
850
+ enabledModules,
851
+
852
+ // Computed
853
+ connectedPeersList,
854
+ canAcceptMorePeers,
855
+
856
+ // Methods
857
+ initMesh,
858
+ connectToSignaling,
859
+ disconnect,
860
+ sendBroadcastMessage,
861
+ sendDirectMessage,
862
+ startMedia,
863
+ stopMedia,
864
+ dhtPut,
865
+ dhtGet,
866
+ getDHTStats,
867
+ storageStore,
868
+ storageRetrieve,
869
+ getStorageStats,
870
+ getDebugModules,
871
+ enableDebugModule,
872
+ disableDebugModule,
873
+ clearDebugLogs,
874
+ addDebugLog,
875
+
876
+ // Network management methods
877
+ setNetworkName,
878
+ getNetworkInfo,
879
+ setAllowGlobalFallback,
880
+ forceReturnToOriginalNetwork,
881
+
882
+ // Crypto methods
883
+ initializeCrypto,
884
+ cryptoGenerateKey,
885
+ cryptoImportKey,
886
+ cryptoEncrypt,
887
+ cryptoDecrypt,
888
+ cryptoSign,
889
+ cryptoVerify,
890
+ cryptoKeyExchange,
891
+ cryptoRefreshKeys,
892
+ cryptoExportKey,
893
+ cryptoDeleteKey
894
+ };
895
+ });