peerpigeon 0.0.2 → 0.0.3
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.
- package/README.md +4 -4
- package/examples/node/test-node.js +153 -0
- package/index.js +12 -0
- package/package.json +3 -3
- package/src/ConnectionManager.js +11 -4
- package/src/EnvironmentDetector.js +441 -0
- package/src/GossipManager.js +11 -3
- package/src/MediaManager.js +14 -0
- package/src/PeerConnection.js +30 -13
- package/src/PeerDiscovery.js +10 -3
- package/src/PeerPigeonMesh.js +187 -2
- package/src/SignalingClient.js +65 -12
- package/src/StorageManager.js +48 -6
- package/src/TimerUtils.js +36 -8
- package/websocket-server/node_modules/.package-lock.json +0 -29
- package/websocket-server/node_modules/ws/LICENSE +0 -20
- package/websocket-server/node_modules/ws/README.md +0 -548
- package/websocket-server/node_modules/ws/browser.js +0 -8
- package/websocket-server/node_modules/ws/index.js +0 -13
- package/websocket-server/node_modules/ws/lib/buffer-util.js +0 -131
- package/websocket-server/node_modules/ws/lib/constants.js +0 -18
- package/websocket-server/node_modules/ws/lib/event-target.js +0 -292
- package/websocket-server/node_modules/ws/lib/extension.js +0 -203
- package/websocket-server/node_modules/ws/lib/limiter.js +0 -55
- package/websocket-server/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/websocket-server/node_modules/ws/lib/receiver.js +0 -706
- package/websocket-server/node_modules/ws/lib/sender.js +0 -602
- package/websocket-server/node_modules/ws/lib/stream.js +0 -161
- package/websocket-server/node_modules/ws/lib/subprotocol.js +0 -62
- package/websocket-server/node_modules/ws/lib/validation.js +0 -152
- package/websocket-server/node_modules/ws/lib/websocket-server.js +0 -550
- package/websocket-server/node_modules/ws/lib/websocket.js +0 -1388
- package/websocket-server/node_modules/ws/package.json +0 -69
- package/websocket-server/node_modules/ws/wrapper.mjs +0 -8
- package/websocket-server/package-lock.json +0 -39
package/src/GossipManager.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Manages gossip protocol for message propagation across the mesh network
|
|
@@ -379,9 +380,16 @@ export class GossipManager extends EventEmitter {
|
|
|
379
380
|
if (this.cleanupTimer) {
|
|
380
381
|
clearInterval(this.cleanupTimer);
|
|
381
382
|
}
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
383
|
+
|
|
384
|
+
if (environmentDetector.isBrowser) {
|
|
385
|
+
this.cleanupTimer = window.setInterval(() => {
|
|
386
|
+
this.cleanupExpiredMessages();
|
|
387
|
+
}, this.cleanupInterval);
|
|
388
|
+
} else {
|
|
389
|
+
this.cleanupTimer = setInterval(() => {
|
|
390
|
+
this.cleanupExpiredMessages();
|
|
391
|
+
}, this.cleanupInterval);
|
|
392
|
+
}
|
|
385
393
|
}
|
|
386
394
|
|
|
387
395
|
cleanupExpiredMessages() {
|
package/src/MediaManager.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
2
3
|
|
|
3
4
|
export class MediaManager extends EventEmitter {
|
|
4
5
|
constructor() {
|
|
@@ -30,6 +31,13 @@ export class MediaManager extends EventEmitter {
|
|
|
30
31
|
* Initialize media devices and permissions
|
|
31
32
|
*/
|
|
32
33
|
async init() {
|
|
34
|
+
// Check if media APIs are available
|
|
35
|
+
if (!environmentDetector.hasGetUserMedia) {
|
|
36
|
+
console.warn('getUserMedia not available in this environment');
|
|
37
|
+
this.emit('error', { type: 'init', error: new Error('getUserMedia not supported') });
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
|
|
33
41
|
try {
|
|
34
42
|
// Enumerate available devices
|
|
35
43
|
await this.enumerateDevices();
|
|
@@ -45,6 +53,12 @@ export class MediaManager extends EventEmitter {
|
|
|
45
53
|
* Get available media devices
|
|
46
54
|
*/
|
|
47
55
|
async enumerateDevices() {
|
|
56
|
+
// Only available in browser environments with media device support
|
|
57
|
+
if (!environmentDetector.isBrowser || typeof navigator.mediaDevices === 'undefined') {
|
|
58
|
+
console.warn('Media device enumeration not available in this environment');
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
|
|
48
62
|
try {
|
|
49
63
|
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
50
64
|
|
package/src/PeerConnection.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
2
3
|
|
|
3
4
|
export class PeerConnection extends EventEmitter {
|
|
4
5
|
constructor(peerId, isInitiator = false, options = {}) {
|
|
@@ -34,6 +35,13 @@ export class PeerConnection extends EventEmitter {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
async createConnection() {
|
|
38
|
+
// Validate WebRTC support before creating connection
|
|
39
|
+
if (!environmentDetector.hasWebRTC) {
|
|
40
|
+
const error = new Error('WebRTC not supported in this environment');
|
|
41
|
+
this.emit('connectionFailed', { peerId: this.peerId, reason: error.message });
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
|
|
37
45
|
this.connection = new RTCPeerConnection({
|
|
38
46
|
iceServers: [
|
|
39
47
|
{ urls: 'stun:stun.l.google.com:19302' },
|
|
@@ -138,11 +146,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
138
146
|
this.connection.onconnectionstatechange = () => {
|
|
139
147
|
console.log(`🔗 Connection state with ${this.peerId}: ${this.connection.connectionState} (previous signaling: ${this.connection.signalingState})`);
|
|
140
148
|
|
|
141
|
-
// Log additional context about transceivers and media
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
149
|
+
// Log additional context about transceivers and media with Node.js compatibility
|
|
150
|
+
try {
|
|
151
|
+
const transceivers = this.connection.getTransceivers();
|
|
152
|
+
const audioSending = this.audioTransceiver && this.audioTransceiver.sender && this.audioTransceiver.sender.track;
|
|
153
|
+
const videoSending = this.videoTransceiver && this.videoTransceiver.sender && this.videoTransceiver.sender.track;
|
|
154
|
+
console.log(`🔗 Media context: Audio sending=${!!audioSending}, Video sending=${!!videoSending}, Transceivers=${transceivers.length}`);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
// Handle Node.js WebRTC compatibility issues
|
|
157
|
+
console.log(`🔗 Media context: Unable to access transceiver details (${error.message})`);
|
|
158
|
+
}
|
|
146
159
|
|
|
147
160
|
if (this.connection.connectionState === 'connected') {
|
|
148
161
|
// Clear any pending timeouts
|
|
@@ -249,14 +262,18 @@ export class PeerConnection extends EventEmitter {
|
|
|
249
262
|
// Any renegotiation indicates a problem with our transceiver approach
|
|
250
263
|
console.log('🚫 UNEXPECTED: Renegotiation triggered despite transceiver approach - investigating...');
|
|
251
264
|
|
|
252
|
-
// Log debug info about current transceivers
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
265
|
+
// Log debug info about current transceivers (with error handling for Node.js WebRTC)
|
|
266
|
+
try {
|
|
267
|
+
const transceivers = this.connection.getTransceivers();
|
|
268
|
+
console.log('� Transceivers state during unexpected negotiation:', transceivers.map(t => ({
|
|
269
|
+
kind: t.receiver?.track?.kind || 'unknown',
|
|
270
|
+
direction: t.direction,
|
|
271
|
+
hasTrack: !!t.sender?.track,
|
|
272
|
+
mid: t.mid
|
|
273
|
+
})));
|
|
274
|
+
} catch (error) {
|
|
275
|
+
console.log('� Cannot inspect transceivers (Node.js WebRTC limitation):', error.message);
|
|
276
|
+
}
|
|
260
277
|
|
|
261
278
|
// For now, ignore renegotiation to prevent connection issues
|
|
262
279
|
// this.emit('renegotiationNeeded', { peerId: this.peerId });
|
package/src/PeerDiscovery.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
2
3
|
|
|
3
4
|
export class PeerDiscovery extends EventEmitter {
|
|
4
5
|
constructor(peerId, options = {}) {
|
|
@@ -210,9 +211,15 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
210
211
|
}
|
|
211
212
|
|
|
212
213
|
startCleanupInterval() {
|
|
213
|
-
|
|
214
|
-
this.
|
|
215
|
-
|
|
214
|
+
if (environmentDetector.isBrowser) {
|
|
215
|
+
this.cleanupInterval = window.setInterval(() => {
|
|
216
|
+
this.cleanupStaleDiscoveredPeers();
|
|
217
|
+
}, 30000);
|
|
218
|
+
} else {
|
|
219
|
+
this.cleanupInterval = setInterval(() => {
|
|
220
|
+
this.cleanupStaleDiscoveredPeers();
|
|
221
|
+
}, 30000);
|
|
222
|
+
}
|
|
216
223
|
}
|
|
217
224
|
|
|
218
225
|
cleanupStaleDiscoveredPeers() {
|
package/src/PeerPigeonMesh.js
CHANGED
|
@@ -10,10 +10,15 @@ import { StorageManager } from './StorageManager.js';
|
|
|
10
10
|
import { GossipManager } from './GossipManager.js';
|
|
11
11
|
import { MediaManager } from './MediaManager.js';
|
|
12
12
|
import { WebDHT } from './WebDHT.js';
|
|
13
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
13
14
|
|
|
14
15
|
export class PeerPigeonMesh extends EventEmitter {
|
|
15
16
|
constructor(options = {}) {
|
|
16
17
|
super();
|
|
18
|
+
|
|
19
|
+
// Validate environment capabilities
|
|
20
|
+
this.environmentReport = this.validateEnvironment(options);
|
|
21
|
+
|
|
17
22
|
this.peerId = null;
|
|
18
23
|
this.providedPeerId = options.peerId || null;
|
|
19
24
|
this.signalingClient = null;
|
|
@@ -104,6 +109,86 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
104
109
|
});
|
|
105
110
|
}
|
|
106
111
|
|
|
112
|
+
validateEnvironment(options = {}) {
|
|
113
|
+
const report = environmentDetector.getEnvironmentReport();
|
|
114
|
+
const warnings = [];
|
|
115
|
+
const errors = [];
|
|
116
|
+
|
|
117
|
+
// Log environment info
|
|
118
|
+
console.log('🔍 PeerPigeon Environment Detection:', {
|
|
119
|
+
runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}`,
|
|
120
|
+
webrtc: report.capabilities.webrtc,
|
|
121
|
+
websocket: report.capabilities.webSocket,
|
|
122
|
+
browser: report.browser?.name || 'N/A'
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// Check WebRTC support (required for peer connections)
|
|
126
|
+
if (!report.capabilities.webrtc) {
|
|
127
|
+
if (report.runtime.isBrowser) {
|
|
128
|
+
errors.push('WebRTC is not supported in this browser. PeerPigeon requires WebRTC for peer-to-peer connections.');
|
|
129
|
+
} else if (report.runtime.isNodeJS) {
|
|
130
|
+
warnings.push('WebRTC support not detected in Node.js environment. Consider using a WebRTC library like node-webrtc.');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Check WebSocket support (required for signaling)
|
|
135
|
+
if (!report.capabilities.webSocket) {
|
|
136
|
+
if (report.runtime.isBrowser) {
|
|
137
|
+
errors.push('WebSocket is not supported in this browser. PeerPigeon requires WebSocket for signaling.');
|
|
138
|
+
} else if (report.runtime.isNodeJS) {
|
|
139
|
+
warnings.push('WebSocket support not detected. Install the "ws" package for WebSocket support in Node.js.');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Check storage capabilities for persistent peer ID
|
|
144
|
+
if (report.runtime.isBrowser && !report.capabilities.localStorage && !report.capabilities.sessionStorage) {
|
|
145
|
+
warnings.push('No storage mechanism available. Peer ID will not persist between sessions.');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Check crypto support for secure peer ID generation
|
|
149
|
+
if (!report.capabilities.randomValues) {
|
|
150
|
+
warnings.push('Crypto random values not available. Peer ID generation may be less secure.');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Network connectivity checks
|
|
154
|
+
if (report.runtime.isBrowser && !report.network.online) {
|
|
155
|
+
warnings.push('Browser reports offline status. Mesh networking may not function properly.');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Environment-specific warnings
|
|
159
|
+
if (report.runtime.isBrowser) {
|
|
160
|
+
// Browser-specific checks
|
|
161
|
+
const browser = report.browser;
|
|
162
|
+
if (browser && browser.name === 'ie') {
|
|
163
|
+
errors.push('Internet Explorer is not supported. Please use a modern browser.');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Check for secure context in production
|
|
167
|
+
if (typeof location !== 'undefined' && location.protocol === 'http:' && location.hostname !== 'localhost') {
|
|
168
|
+
warnings.push('Running on HTTP in production. Some WebRTC features may be limited. Consider using HTTPS.');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Handle errors and warnings
|
|
173
|
+
if (errors.length > 0) {
|
|
174
|
+
const errorMessage = 'PeerPigeon environment validation failed:\n' + errors.join('\n');
|
|
175
|
+
console.error(errorMessage);
|
|
176
|
+
if (!options.ignoreEnvironmentErrors) {
|
|
177
|
+
throw new Error(errorMessage);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (warnings.length > 0) {
|
|
182
|
+
console.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Store capabilities for runtime checks
|
|
186
|
+
this.capabilities = report.capabilities;
|
|
187
|
+
this.runtimeInfo = report.runtime;
|
|
188
|
+
|
|
189
|
+
return report;
|
|
190
|
+
}
|
|
191
|
+
|
|
107
192
|
async init() {
|
|
108
193
|
try {
|
|
109
194
|
// Use provided peer ID if valid, otherwise generate one
|
|
@@ -458,7 +543,8 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
458
543
|
clearInterval(this.connectionMonitorInterval);
|
|
459
544
|
}
|
|
460
545
|
|
|
461
|
-
|
|
546
|
+
// Environment-aware timer
|
|
547
|
+
const intervalCallback = () => {
|
|
462
548
|
if (this.signalingClient) {
|
|
463
549
|
const stats = this.signalingClient.getConnectionStats();
|
|
464
550
|
console.log('Connection monitoring:', stats);
|
|
@@ -475,7 +561,13 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
475
561
|
// Emit connection status for UI
|
|
476
562
|
this.emit('connectionStats', stats);
|
|
477
563
|
}
|
|
478
|
-
}
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
if (environmentDetector.isBrowser) {
|
|
567
|
+
this.connectionMonitorInterval = window.setInterval(intervalCallback, 120000);
|
|
568
|
+
} else {
|
|
569
|
+
this.connectionMonitorInterval = setInterval(intervalCallback, 120000);
|
|
570
|
+
}
|
|
479
571
|
|
|
480
572
|
console.log('Started connection monitoring');
|
|
481
573
|
}
|
|
@@ -700,4 +792,97 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
700
792
|
|
|
701
793
|
return this.connectionManager.connectToPeer(peerId);
|
|
702
794
|
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Get the current environment report
|
|
798
|
+
* @returns {object} Complete environment detection report
|
|
799
|
+
*/
|
|
800
|
+
getEnvironmentReport() {
|
|
801
|
+
return this.environmentReport;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* Get runtime capabilities
|
|
806
|
+
* @returns {object} Capabilities detected during initialization
|
|
807
|
+
*/
|
|
808
|
+
getCapabilities() {
|
|
809
|
+
return this.capabilities;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Get runtime information
|
|
814
|
+
* @returns {object} Runtime environment information
|
|
815
|
+
*/
|
|
816
|
+
getRuntimeInfo() {
|
|
817
|
+
return this.runtimeInfo;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Check if a specific feature is supported
|
|
822
|
+
* @param {string} feature - The feature to check (e.g., 'webrtc', 'websocket', 'localstorage')
|
|
823
|
+
* @returns {boolean} True if the feature is supported
|
|
824
|
+
*/
|
|
825
|
+
hasFeature(feature) {
|
|
826
|
+
return environmentDetector.hasFeature(feature);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* Get environment-specific recommendations
|
|
831
|
+
* @returns {object} Recommendations based on current environment
|
|
832
|
+
*/
|
|
833
|
+
getEnvironmentRecommendations() {
|
|
834
|
+
const recommendations = [];
|
|
835
|
+
const report = this.environmentReport;
|
|
836
|
+
|
|
837
|
+
if (report.runtime.isBrowser) {
|
|
838
|
+
if (!report.network.online) {
|
|
839
|
+
recommendations.push({
|
|
840
|
+
type: 'warning',
|
|
841
|
+
message: 'Browser is offline. Enable network connectivity for mesh functionality.'
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
if (typeof location !== 'undefined' && location.protocol === 'http:' && location.hostname !== 'localhost') {
|
|
846
|
+
recommendations.push({
|
|
847
|
+
type: 'security',
|
|
848
|
+
message: 'Consider using HTTPS for better WebRTC compatibility and security.'
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
if (report.browser && report.browser.name === 'safari') {
|
|
853
|
+
recommendations.push({
|
|
854
|
+
type: 'compatibility',
|
|
855
|
+
message: 'Safari has some WebRTC limitations. Test thoroughly for production use.'
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
if (report.runtime.isNodeJS) {
|
|
861
|
+
if (!report.capabilities.webSocket) {
|
|
862
|
+
recommendations.push({
|
|
863
|
+
type: 'dependency',
|
|
864
|
+
message: 'Install the "ws" package for WebSocket support: npm install ws'
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
if (!report.capabilities.webrtc) {
|
|
869
|
+
recommendations.push({
|
|
870
|
+
type: 'dependency',
|
|
871
|
+
message: 'Install "node-webrtc" or similar for WebRTC support in Node.js: npm install node-webrtc'
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
if (!report.capabilities.localStorage && !report.capabilities.sessionStorage) {
|
|
877
|
+
recommendations.push({
|
|
878
|
+
type: 'feature',
|
|
879
|
+
message: 'No persistent storage available. Peer ID will change on restart.'
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
return {
|
|
884
|
+
environment: report.runtime,
|
|
885
|
+
recommendations
|
|
886
|
+
};
|
|
887
|
+
}
|
|
703
888
|
}
|
package/src/SignalingClient.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
2
3
|
|
|
3
4
|
export class SignalingClient extends EventEmitter {
|
|
4
5
|
constructor(peerId, maxPeers = 10, mesh = null) {
|
|
@@ -34,6 +35,39 @@ export class SignalingClient extends EventEmitter {
|
|
|
34
35
|
console.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
|
|
35
36
|
}
|
|
36
37
|
|
|
38
|
+
createWebSocket(url) {
|
|
39
|
+
// Environment-aware WebSocket creation
|
|
40
|
+
if (environmentDetector.isNodeJS) {
|
|
41
|
+
// Check for globally injected WebSocket first (set by user)
|
|
42
|
+
if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') {
|
|
43
|
+
return new global.WebSocket(url);
|
|
44
|
+
}
|
|
45
|
+
if (typeof WebSocket !== 'undefined') {
|
|
46
|
+
return new WebSocket(url);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Try to use the 'ws' package if available
|
|
50
|
+
try {
|
|
51
|
+
if (typeof require !== 'undefined') {
|
|
52
|
+
const WebSocket = require('ws');
|
|
53
|
+
return new WebSocket(url);
|
|
54
|
+
} else {
|
|
55
|
+
// In ES modules, dynamic import would be needed
|
|
56
|
+
console.warn('WebSocket package detection not available in ES modules. Ensure "ws" is installed.');
|
|
57
|
+
throw new Error('WebSocket not available in Node.js ES modules. Install the "ws" package and import it manually.');
|
|
58
|
+
}
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.warn('ws package not found in Node.js environment. Install with: npm install ws');
|
|
61
|
+
throw new Error('WebSocket not available in Node.js. Install the "ws" package.');
|
|
62
|
+
}
|
|
63
|
+
} else if (environmentDetector.isBrowser || environmentDetector.isWorker) {
|
|
64
|
+
// In browser or worker environments, use the native WebSocket
|
|
65
|
+
return new WebSocket(url);
|
|
66
|
+
} else {
|
|
67
|
+
throw new Error('WebSocket not supported in this environment');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
37
71
|
async sendSignalingMessage(message) {
|
|
38
72
|
// Check connection health before sending
|
|
39
73
|
if (!this.isConnected()) {
|
|
@@ -72,6 +106,13 @@ export class SignalingClient extends EventEmitter {
|
|
|
72
106
|
}
|
|
73
107
|
|
|
74
108
|
async connect(websocketUrl) {
|
|
109
|
+
// Validate WebSocket support before attempting connection
|
|
110
|
+
if (!environmentDetector.hasWebSocket) {
|
|
111
|
+
const error = new Error('WebSocket not supported in this environment');
|
|
112
|
+
this.emit('statusChanged', { type: 'error', message: error.message });
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
|
|
75
116
|
// Prevent multiple simultaneous connection attempts
|
|
76
117
|
if (this.connectionPromise) {
|
|
77
118
|
console.log('Connection already in progress, waiting for completion...');
|
|
@@ -100,7 +141,8 @@ export class SignalingClient extends EventEmitter {
|
|
|
100
141
|
|
|
101
142
|
this.connectionPromise = new Promise((resolve, reject) => {
|
|
102
143
|
try {
|
|
103
|
-
|
|
144
|
+
// Create WebSocket with environment-specific handling
|
|
145
|
+
this.websocket = this.createWebSocket(url.toString());
|
|
104
146
|
|
|
105
147
|
const connectTimeout = setTimeout(() => {
|
|
106
148
|
if (this.websocket.readyState === WebSocket.CONNECTING) {
|
|
@@ -324,7 +366,8 @@ export class SignalingClient extends EventEmitter {
|
|
|
324
366
|
if (this.keepAliveInterval) return;
|
|
325
367
|
|
|
326
368
|
console.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
|
|
327
|
-
|
|
369
|
+
|
|
370
|
+
const keepAliveCallback = () => {
|
|
328
371
|
if (this.connected) {
|
|
329
372
|
// Check if this peer should send the ping
|
|
330
373
|
if (this.shouldSendKeepAlivePing()) {
|
|
@@ -339,7 +382,13 @@ export class SignalingClient extends EventEmitter {
|
|
|
339
382
|
console.log('Skipping keep-alive ping (not designated peer)');
|
|
340
383
|
}
|
|
341
384
|
}
|
|
342
|
-
}
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
if (environmentDetector.isBrowser) {
|
|
388
|
+
this.keepAliveInterval = window.setInterval(keepAliveCallback, this.keepAliveIntervalMs);
|
|
389
|
+
} else {
|
|
390
|
+
this.keepAliveInterval = setInterval(keepAliveCallback, this.keepAliveIntervalMs);
|
|
391
|
+
}
|
|
343
392
|
}
|
|
344
393
|
|
|
345
394
|
/**
|
|
@@ -386,7 +435,8 @@ export class SignalingClient extends EventEmitter {
|
|
|
386
435
|
if (this.healthCheckInterval) return;
|
|
387
436
|
|
|
388
437
|
console.log('Starting connection health monitoring');
|
|
389
|
-
|
|
438
|
+
|
|
439
|
+
const healthCheckCallback = () => {
|
|
390
440
|
// Check WebSocket state first
|
|
391
441
|
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
|
392
442
|
console.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
|
|
@@ -407,19 +457,22 @@ export class SignalingClient extends EventEmitter {
|
|
|
407
457
|
// Check if we have an old pong that indicates connection issues
|
|
408
458
|
if (this.lastPingTime && this.lastPongTime &&
|
|
409
459
|
(this.lastPingTime > this.lastPongTime) &&
|
|
410
|
-
(now - this.lastPingTime
|
|
411
|
-
console.warn('Connection
|
|
460
|
+
(now - this.lastPingTime > this.connectionQualityTimeout)) {
|
|
461
|
+
console.warn('Connection unhealthy - ping/pong timeout');
|
|
412
462
|
this.handleUnhealthyConnection();
|
|
413
463
|
return;
|
|
414
464
|
}
|
|
415
|
-
|
|
416
|
-
// Send health
|
|
465
|
+
|
|
466
|
+
// Send health ping
|
|
417
467
|
this.sendHealthPing();
|
|
418
|
-
} else {
|
|
419
|
-
console.warn('Connection marked as disconnected but health monitoring still running');
|
|
420
|
-
this.handleUnhealthyConnection();
|
|
421
468
|
}
|
|
422
|
-
}
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
if (environmentDetector.isBrowser) {
|
|
472
|
+
this.healthCheckInterval = window.setInterval(healthCheckCallback, 30000);
|
|
473
|
+
} else {
|
|
474
|
+
this.healthCheckInterval = setInterval(healthCheckCallback, 30000);
|
|
475
|
+
}
|
|
423
476
|
}
|
|
424
477
|
|
|
425
478
|
stopHealthMonitoring() {
|
package/src/StorageManager.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { environmentDetector } from './EnvironmentDetector.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Manages storage operations, URL handling, and configuration persistence
|
|
@@ -10,25 +11,33 @@ export class StorageManager extends EventEmitter {
|
|
|
10
11
|
}
|
|
11
12
|
|
|
12
13
|
loadSignalingUrlFromStorage() {
|
|
13
|
-
|
|
14
|
+
// Use environment-aware storage detection
|
|
15
|
+
if (environmentDetector.hasLocalStorage) {
|
|
14
16
|
const savedUrl = localStorage.getItem('pigon-signaling-url');
|
|
15
17
|
if (savedUrl) {
|
|
16
18
|
this.mesh.signalingUrl = savedUrl;
|
|
17
19
|
this.mesh.emit('statusChanged', { type: 'urlLoaded', signalingUrl: savedUrl });
|
|
18
20
|
return savedUrl;
|
|
19
21
|
}
|
|
22
|
+
} else if (environmentDetector.isNodeJS) {
|
|
23
|
+
// In Node.js, we could potentially use file-based storage
|
|
24
|
+
console.log('Local storage not available in Node.js environment');
|
|
20
25
|
}
|
|
21
26
|
return null;
|
|
22
27
|
}
|
|
23
28
|
|
|
24
29
|
saveSignalingUrlToStorage(url) {
|
|
25
|
-
if (
|
|
30
|
+
if (environmentDetector.hasLocalStorage && url) {
|
|
26
31
|
localStorage.setItem('pigon-signaling-url', url);
|
|
32
|
+
} else if (environmentDetector.isNodeJS) {
|
|
33
|
+
// In Node.js, we could potentially save to a config file
|
|
34
|
+
console.log('Storage not implemented for Node.js environment');
|
|
27
35
|
}
|
|
28
36
|
}
|
|
29
37
|
|
|
30
38
|
loadSignalingUrlFromQuery() {
|
|
31
|
-
|
|
39
|
+
// Only works in browser environments
|
|
40
|
+
if (!environmentDetector.isBrowser) return this.loadSignalingUrlFromStorage();
|
|
32
41
|
|
|
33
42
|
const urlParams = new URLSearchParams(window.location.search);
|
|
34
43
|
const signalingUrl = urlParams.get('api') || urlParams.get('url') || urlParams.get('signaling');
|
|
@@ -51,7 +60,40 @@ export class StorageManager extends EventEmitter {
|
|
|
51
60
|
|
|
52
61
|
async generatePeerId() {
|
|
53
62
|
const array = new Uint8Array(20);
|
|
54
|
-
|
|
63
|
+
|
|
64
|
+
// Environment-aware random value generation
|
|
65
|
+
if (environmentDetector.hasRandomValues) {
|
|
66
|
+
if (environmentDetector.isBrowser || environmentDetector.isWorker) {
|
|
67
|
+
crypto.getRandomValues(array);
|
|
68
|
+
} else if (environmentDetector.isNodeJS) {
|
|
69
|
+
// In Node.js, use crypto module (handle both CommonJS and ES modules)
|
|
70
|
+
try {
|
|
71
|
+
if (typeof require !== 'undefined') {
|
|
72
|
+
const crypto = require('crypto');
|
|
73
|
+
const randomBytes = crypto.randomBytes(20);
|
|
74
|
+
array.set(randomBytes);
|
|
75
|
+
} else {
|
|
76
|
+
// ES module approach - import crypto dynamically
|
|
77
|
+
const crypto = await import('crypto');
|
|
78
|
+
const randomBytes = crypto.randomBytes(20);
|
|
79
|
+
array.set(randomBytes);
|
|
80
|
+
}
|
|
81
|
+
} catch (e) {
|
|
82
|
+
console.warn('Could not use Node.js crypto, falling back to Math.random');
|
|
83
|
+
// Fallback to Math.random
|
|
84
|
+
for (let i = 0; i < array.length; i++) {
|
|
85
|
+
array[i] = Math.floor(Math.random() * 256);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
// Fallback to less secure random generation
|
|
91
|
+
console.warn('Secure random values not available, using fallback method');
|
|
92
|
+
for (let i = 0; i < array.length; i++) {
|
|
93
|
+
array[i] = Math.floor(Math.random() * 256);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
55
97
|
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
56
98
|
}
|
|
57
99
|
|
|
@@ -60,13 +102,13 @@ export class StorageManager extends EventEmitter {
|
|
|
60
102
|
}
|
|
61
103
|
|
|
62
104
|
saveSettings(settings) {
|
|
63
|
-
if (
|
|
105
|
+
if (environmentDetector.hasLocalStorage) {
|
|
64
106
|
localStorage.setItem('pigon-settings', JSON.stringify(settings));
|
|
65
107
|
}
|
|
66
108
|
}
|
|
67
109
|
|
|
68
110
|
loadSettings() {
|
|
69
|
-
if (
|
|
111
|
+
if (environmentDetector.hasLocalStorage) {
|
|
70
112
|
const saved = localStorage.getItem('pigon-settings');
|
|
71
113
|
if (saved) {
|
|
72
114
|
try {
|