peerpigeon 0.0.6 → 0.0.7
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 +46 -8
- package/examples/nativescript/README.md +73 -0
- package/examples/nativescript/app.js +152 -0
- package/examples/nativescript/package.json +27 -0
- package/package.json +8 -48
- package/src/EnvironmentDetector.js +83 -10
- package/src/MediaManager.js +4 -2
- package/src/PeerPigeonMesh.js +23 -3
- package/src/SignalingClient.js +6 -6
- package/src/StorageManager.js +19 -5
- package/src/WebDHT.js +190 -15
package/README.md
CHANGED
|
@@ -892,15 +892,18 @@ open "http://localhost:8080/examples/browser/?api=wss://your-signaling-server.co
|
|
|
892
892
|
- Force connection utilities for testing
|
|
893
893
|
- Real-time peer discovery and connection monitoring
|
|
894
894
|
|
|
895
|
-
## 🌐
|
|
895
|
+
## 🌐 Platform Compatibility & Requirements
|
|
896
896
|
|
|
897
|
-
###
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
897
|
+
### Supported Platforms
|
|
898
|
+
|
|
899
|
+
| Platform | Environment | WebRTC Support | WebSocket Support | Status |
|
|
900
|
+
|---------|-------------|----------------|-------------------|---------|
|
|
901
|
+
| **Web Browsers** | Modern browsers | ✅ Native | ✅ Native | **Full Support** |
|
|
902
|
+
| **Node.js** | Server-side | ⚠️ Via plugin | ✅ Via 'ws' | **Supported** |
|
|
903
|
+
| **NativeScript** | Mobile apps | ⚠️ Via plugin | ✅ Native/Plugin | **Supported** |
|
|
904
|
+
| **Web Workers** | Browser workers | ✅ Limited | ✅ Yes | **Basic Support** |
|
|
902
905
|
|
|
903
|
-
###
|
|
906
|
+
### Browser Compatibility
|
|
904
907
|
|
|
905
908
|
| Browser | Minimum Version | WebRTC Support | WebSocket Support | Status |
|
|
906
909
|
|---------|----------------|----------------|-------------------|---------|
|
|
@@ -911,6 +914,38 @@ open "http://localhost:8080/examples/browser/?api=wss://your-signaling-server.co
|
|
|
911
914
|
| **Mobile Chrome** | 80+ | ✅ Full | ✅ Yes | **Supported** |
|
|
912
915
|
| **Mobile Safari** | 14+ | ✅ Full | ✅ Yes | **Supported** |
|
|
913
916
|
|
|
917
|
+
### Required Features
|
|
918
|
+
- **WebRTC**: RTCPeerConnection and RTCDataChannel support
|
|
919
|
+
- **ES6 Modules**: Dynamic imports and module syntax
|
|
920
|
+
- **Crypto API**: For cryptographically secure peer ID generation
|
|
921
|
+
- **WebSocket API**: For real-time signaling communication
|
|
922
|
+
|
|
923
|
+
### NativeScript Support
|
|
924
|
+
|
|
925
|
+
PeerPigeon includes comprehensive NativeScript support:
|
|
926
|
+
|
|
927
|
+
```javascript
|
|
928
|
+
// NativeScript usage (same API as browser)
|
|
929
|
+
import { PeerPigeonMesh } from 'peerpigeon';
|
|
930
|
+
|
|
931
|
+
const mesh = new PeerPigeonMesh();
|
|
932
|
+
await mesh.init(); // Automatically detects NativeScript environment
|
|
933
|
+
|
|
934
|
+
// Environment detection
|
|
935
|
+
console.log('Environment:', mesh.environmentReport.runtime);
|
|
936
|
+
// { isNativeScript: true, platform: 'android' }
|
|
937
|
+
```
|
|
938
|
+
|
|
939
|
+
**NativeScript Features:**
|
|
940
|
+
- ✅ Environment detection with platform info (Android/iOS/visionOS)
|
|
941
|
+
- ✅ WebSocket signaling (native or via plugin)
|
|
942
|
+
- ✅ Storage management using NativeScript APIs
|
|
943
|
+
- ✅ Basic mesh networking capabilities
|
|
944
|
+
- ⚠️ WebRTC requires additional native plugins
|
|
945
|
+
- ⚠️ Media features require camera/microphone permissions
|
|
946
|
+
|
|
947
|
+
See the [NativeScript example](examples/nativescript/) for complete setup instructions.
|
|
948
|
+
|
|
914
949
|
### Feature Detection
|
|
915
950
|
|
|
916
951
|
PeerPigeon automatically detects browser capabilities:
|
|
@@ -1321,7 +1356,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
1321
1356
|
|
|
1322
1357
|
**Quick Links:**
|
|
1323
1358
|
- [Live Demo](http://localhost:8080/examples/browser/) (after starting local server)
|
|
1359
|
+
- [Browser Examples](examples/browser/) - Complete web-based examples
|
|
1360
|
+
- [Node.js Examples](examples/node/) - Server-side examples
|
|
1361
|
+
- [NativeScript Examples](examples/nativescript/) - Mobile app examples
|
|
1324
1362
|
- [API Documentation](docs/API.md)
|
|
1325
|
-
- [Deployment Guide](docs/DEPLOYMENT.md)
|
|
1363
|
+
- [Deployment Guide](docs/DEPLOYMENT.md)
|
|
1326
1364
|
- [GitHub Issues](https://github.com/danrayadev/pigon/issues)
|
|
1327
1365
|
- [Contributing Guidelines](CONTRIBUTING.md)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# NativeScript Example
|
|
2
|
+
|
|
3
|
+
This example demonstrates how to use PeerPigeon in a NativeScript application.
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
- NativeScript CLI installed (`npm install -g @nativescript/cli`)
|
|
8
|
+
- NativeScript development environment set up for your target platform (iOS/Android)
|
|
9
|
+
- WebRTC plugin for NativeScript (if using media features)
|
|
10
|
+
|
|
11
|
+
## Setup
|
|
12
|
+
|
|
13
|
+
1. Create a new NativeScript project:
|
|
14
|
+
```bash
|
|
15
|
+
ns create MyPeerPigeonApp --js
|
|
16
|
+
cd MyPeerPigeonApp
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
2. Install PeerPigeon:
|
|
20
|
+
```bash
|
|
21
|
+
npm install peerpigeon
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
3. For WebRTC support, install a WebRTC plugin:
|
|
25
|
+
```bash
|
|
26
|
+
# Example plugin (check for latest NativeScript WebRTC plugins)
|
|
27
|
+
ns plugin add @nativescript/webrtc
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
4. Copy the example code from `app.js` to your project's main file.
|
|
31
|
+
|
|
32
|
+
## Features Supported
|
|
33
|
+
|
|
34
|
+
- ✅ Environment detection
|
|
35
|
+
- ✅ WebSocket signaling (with appropriate plugin)
|
|
36
|
+
- ✅ Basic mesh networking
|
|
37
|
+
- ✅ Storage management (using NativeScript's application-settings)
|
|
38
|
+
- ⚠️ WebRTC (requires additional plugin)
|
|
39
|
+
- ⚠️ Media features (requires camera/microphone permissions)
|
|
40
|
+
|
|
41
|
+
## Platform Considerations
|
|
42
|
+
|
|
43
|
+
### Android
|
|
44
|
+
- Requires network permissions in `app/App_Resources/Android/src/main/AndroidManifest.xml`:
|
|
45
|
+
```xml
|
|
46
|
+
<uses-permission android:name="android.permission.INTERNET" />
|
|
47
|
+
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### iOS
|
|
51
|
+
- May require camera/microphone permissions if using media features
|
|
52
|
+
- Add appropriate usage descriptions in `app/App_Resources/iOS/Info.plist`
|
|
53
|
+
|
|
54
|
+
## Running the Example
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
# Run on iOS simulator
|
|
58
|
+
ns run ios
|
|
59
|
+
|
|
60
|
+
# Run on Android emulator
|
|
61
|
+
ns run android
|
|
62
|
+
|
|
63
|
+
# Run on physical device
|
|
64
|
+
ns run ios --device
|
|
65
|
+
ns run android --device
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Notes
|
|
69
|
+
|
|
70
|
+
- This example uses basic mesh networking without WebRTC
|
|
71
|
+
- For full WebRTC support, additional native plugins are required
|
|
72
|
+
- Storage uses NativeScript's application-settings module
|
|
73
|
+
- Network connectivity is automatically detected
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { Application } from '@nativescript/core';
|
|
2
|
+
import { PeerPigeonMesh } from 'peerpigeon';
|
|
3
|
+
|
|
4
|
+
// NativeScript PeerPigeon Example
|
|
5
|
+
console.log('🔮 Starting NativeScript PeerPigeon Example');
|
|
6
|
+
|
|
7
|
+
let mesh;
|
|
8
|
+
let peerId;
|
|
9
|
+
|
|
10
|
+
// Initialize PeerPigeon when app launches
|
|
11
|
+
Application.on(Application.launchEvent, (_args) => {
|
|
12
|
+
console.log('📱 NativeScript app launched');
|
|
13
|
+
initializePeerPigeon();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// Cleanup when app exits
|
|
17
|
+
Application.on(Application.exitEvent, () => {
|
|
18
|
+
console.log('📱 NativeScript app exiting');
|
|
19
|
+
if (mesh) {
|
|
20
|
+
mesh.disconnect();
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
async function initializePeerPigeon() {
|
|
25
|
+
try {
|
|
26
|
+
console.log('🚀 Initializing PeerPigeon...');
|
|
27
|
+
|
|
28
|
+
// Create mesh instance with basic configuration
|
|
29
|
+
mesh = new PeerPigeonMesh({
|
|
30
|
+
enableWebDHT: true,
|
|
31
|
+
enableCrypto: false // Disable crypto for simplicity in this example
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Set up event listeners
|
|
35
|
+
setupEventListeners();
|
|
36
|
+
|
|
37
|
+
// Initialize the mesh
|
|
38
|
+
await mesh.init();
|
|
39
|
+
peerId = mesh.peerId;
|
|
40
|
+
console.log(`✅ PeerPigeon initialized with ID: ${peerId.substring(0, 8)}...`);
|
|
41
|
+
|
|
42
|
+
// Connect to signaling server
|
|
43
|
+
// Replace with your signaling server URL
|
|
44
|
+
const signalingUrl = 'wss://your-signaling-server.com';
|
|
45
|
+
await mesh.connect(signalingUrl);
|
|
46
|
+
|
|
47
|
+
console.log('🌐 Connected to signaling server');
|
|
48
|
+
} catch (error) {
|
|
49
|
+
console.error('❌ Failed to initialize PeerPigeon:', error);
|
|
50
|
+
|
|
51
|
+
// Log environment info for debugging
|
|
52
|
+
const report = mesh?.environmentReport;
|
|
53
|
+
if (report) {
|
|
54
|
+
console.log('🔍 Environment Report:', JSON.stringify(report, null, 2));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function setupEventListeners() {
|
|
60
|
+
// Connection events
|
|
61
|
+
mesh.addEventListener('connected', () => {
|
|
62
|
+
console.log('🔗 Connected to mesh network');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
mesh.addEventListener('disconnected', (data) => {
|
|
66
|
+
console.log('🔌 Disconnected from mesh network:', data.reason);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// Peer events
|
|
70
|
+
mesh.addEventListener('peerConnected', (data) => {
|
|
71
|
+
console.log(`👋 Peer connected: ${data.peerId.substring(0, 8)}...`);
|
|
72
|
+
console.log(`📊 Total peers: ${mesh.getConnectedPeers().length}`);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
mesh.addEventListener('peerDisconnected', (data) => {
|
|
76
|
+
console.log(`👋 Peer disconnected: ${data.peerId.substring(0, 8)}...`);
|
|
77
|
+
console.log(`📊 Total peers: ${mesh.getConnectedPeers().length}`);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// Message events
|
|
81
|
+
mesh.addEventListener('messageReceived', (data) => {
|
|
82
|
+
console.log(`📨 Message from ${data.fromPeerId.substring(0, 8)}...:`, data.message);
|
|
83
|
+
|
|
84
|
+
// Echo the message back
|
|
85
|
+
if (data.message.type === 'ping') {
|
|
86
|
+
sendMessage(data.fromPeerId, { type: 'pong', timestamp: Date.now() });
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// Error events
|
|
91
|
+
mesh.addEventListener('error', (data) => {
|
|
92
|
+
console.error('❌ Mesh error:', data.error);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// Status events
|
|
96
|
+
mesh.addEventListener('statusChanged', (data) => {
|
|
97
|
+
console.log('📈 Status changed:', data);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Send a message to a specific peer or broadcast
|
|
102
|
+
async function sendMessage(targetPeerId, message) {
|
|
103
|
+
try {
|
|
104
|
+
if (targetPeerId) {
|
|
105
|
+
await mesh.sendMessage(targetPeerId, message);
|
|
106
|
+
console.log(`📤 Message sent to ${targetPeerId.substring(0, 8)}...`);
|
|
107
|
+
} else {
|
|
108
|
+
// Broadcast to all peers
|
|
109
|
+
const peers = mesh.getConnectedPeers();
|
|
110
|
+
for (const peer of peers) {
|
|
111
|
+
await mesh.sendMessage(peer.peerId, message);
|
|
112
|
+
}
|
|
113
|
+
console.log(`📡 Message broadcast to ${peers.length} peers`);
|
|
114
|
+
}
|
|
115
|
+
} catch (error) {
|
|
116
|
+
console.error('❌ Failed to send message:', error);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Example: Send a ping message every 30 seconds
|
|
121
|
+
setInterval(() => {
|
|
122
|
+
if (mesh && mesh.connected) {
|
|
123
|
+
const peers = mesh.getConnectedPeers();
|
|
124
|
+
if (peers.length > 0) {
|
|
125
|
+
const randomPeer = peers[Math.floor(Math.random() * peers.length)];
|
|
126
|
+
sendMessage(randomPeer.peerId, {
|
|
127
|
+
type: 'ping',
|
|
128
|
+
timestamp: Date.now(),
|
|
129
|
+
from: 'NativeScript'
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}, 30000);
|
|
134
|
+
|
|
135
|
+
// Example: Log mesh status every 60 seconds
|
|
136
|
+
setInterval(() => {
|
|
137
|
+
if (mesh) {
|
|
138
|
+
const peers = mesh.getConnectedPeers();
|
|
139
|
+
console.log(`📊 Mesh Status - Connected: ${mesh.connected}, Peers: ${peers.length}`);
|
|
140
|
+
|
|
141
|
+
if (peers.length > 0) {
|
|
142
|
+
console.log(`👥 Connected to: ${peers.map(p => p.peerId.substring(0, 8)).join(', ')}...`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}, 60000);
|
|
146
|
+
|
|
147
|
+
// Export functions for potential UI integration
|
|
148
|
+
export {
|
|
149
|
+
mesh,
|
|
150
|
+
sendMessage,
|
|
151
|
+
initializePeerPigeon
|
|
152
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "peerpigeon-nativescript-example",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "NativeScript example for PeerPigeon mesh networking",
|
|
5
|
+
"main": "app.js",
|
|
6
|
+
"dependencies": {
|
|
7
|
+
"@nativescript/core": "^8.0.0",
|
|
8
|
+
"peerpigeon": "^0.0.7"
|
|
9
|
+
},
|
|
10
|
+
"devDependencies": {
|
|
11
|
+
"@nativescript/cli": "^8.0.0"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"ios": "ns run ios",
|
|
15
|
+
"android": "ns run android",
|
|
16
|
+
"clean": "ns clean"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"nativescript",
|
|
20
|
+
"peerpigeon",
|
|
21
|
+
"webrtc",
|
|
22
|
+
"p2p",
|
|
23
|
+
"mesh-networking"
|
|
24
|
+
],
|
|
25
|
+
"author": "PeerPigeon",
|
|
26
|
+
"license": "MIT"
|
|
27
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "peerpigeon",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "WebRTC-based peer-to-peer mesh networking library with intelligent routing and signaling server",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -13,19 +13,9 @@
|
|
|
13
13
|
"dev": "http-server . -p 8080 -c-1",
|
|
14
14
|
"start": "node websocket-server/server.js",
|
|
15
15
|
"server": "node websocket-server/server.js",
|
|
16
|
-
"test": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest",
|
|
17
|
-
"test:unit": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest test/unit",
|
|
18
|
-
"test:integration": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest test/integration",
|
|
19
|
-
"test:media": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest test/unit/media-simple.test.js",
|
|
20
|
-
"test:media-only": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest test/unit/media-only.test.js",
|
|
21
|
-
"test:coverage": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest --coverage",
|
|
22
|
-
"test:watch": "jest --watch",
|
|
23
|
-
"test:custom": "node test/unit/crypto.test.js && node test/unit/mesh.test.js && node test/integration/integration.test.js",
|
|
24
|
-
"test:all": "node test/runner.js",
|
|
25
16
|
"lint": "eslint src/ examples/ websocket-server/ --ext .js",
|
|
26
17
|
"lint:fix": "eslint src/ examples/ websocket-server/ --ext .js --fix",
|
|
27
|
-
"
|
|
28
|
-
"ci": "npm run lint && npm run test:unit",
|
|
18
|
+
"ci": "npm run lint",
|
|
29
19
|
"prepublishOnly": "npm run ci"
|
|
30
20
|
},
|
|
31
21
|
"files": [
|
|
@@ -55,7 +45,8 @@
|
|
|
55
45
|
"gossip",
|
|
56
46
|
"mesh-network",
|
|
57
47
|
"xor-routing",
|
|
58
|
-
"webrtc-mesh"
|
|
48
|
+
"webrtc-mesh",
|
|
49
|
+
"nativescript"
|
|
59
50
|
],
|
|
60
51
|
"author": "Daniel Raeder",
|
|
61
52
|
"license": "MIT",
|
|
@@ -66,48 +57,17 @@
|
|
|
66
57
|
"dependencies": {
|
|
67
58
|
"@koush/wrtc": "^0.5.3",
|
|
68
59
|
"unsea": "^1.1.0",
|
|
69
|
-
"ws": "^8.18.0"
|
|
60
|
+
"ws": "^8.18.0",
|
|
61
|
+
"yamljs": "^0.3.0"
|
|
70
62
|
},
|
|
71
63
|
"devDependencies": {
|
|
72
|
-
"@jest/globals": "^30.0.5",
|
|
73
|
-
"c8": "^10.1.3",
|
|
74
64
|
"eslint": "^8.57.1",
|
|
75
65
|
"eslint-config-standard": "^17.1.0",
|
|
76
66
|
"http-server": "^14.1.1",
|
|
77
|
-
"
|
|
67
|
+
"jsdoc": "^4.0.4",
|
|
68
|
+
"swagger-ui-express": "^5.0.1"
|
|
78
69
|
},
|
|
79
70
|
"engines": {
|
|
80
71
|
"node": ">=14.0.0"
|
|
81
|
-
},
|
|
82
|
-
"browserslist": [
|
|
83
|
-
"last 2 versions",
|
|
84
|
-
"not dead",
|
|
85
|
-
"> 1%"
|
|
86
|
-
],
|
|
87
|
-
"jest": {
|
|
88
|
-
"testEnvironment": "node",
|
|
89
|
-
"globals": {
|
|
90
|
-
"__DEV__": true
|
|
91
|
-
},
|
|
92
|
-
"transform": {},
|
|
93
|
-
"testMatch": [
|
|
94
|
-
"**/test/**/*.test.js"
|
|
95
|
-
],
|
|
96
|
-
"collectCoverageFrom": [
|
|
97
|
-
"src/**/*.js",
|
|
98
|
-
"!src/**/*.test.js"
|
|
99
|
-
],
|
|
100
|
-
"coverageDirectory": "coverage",
|
|
101
|
-
"coverageReporters": [
|
|
102
|
-
"text",
|
|
103
|
-
"lcov",
|
|
104
|
-
"html"
|
|
105
|
-
],
|
|
106
|
-
"verbose": true,
|
|
107
|
-
"setupFilesAfterEnv": ["<rootDir>/test/setup.js"],
|
|
108
|
-
"testTimeout": 30000,
|
|
109
|
-
"detectOpenHandles": true,
|
|
110
|
-
"forceExit": true,
|
|
111
|
-
"clearMocks": true
|
|
112
72
|
}
|
|
113
73
|
}
|
|
@@ -18,6 +18,7 @@ export class EnvironmentDetector {
|
|
|
18
18
|
this._cache.set('isSharedWorker', this._detectSharedWorker());
|
|
19
19
|
this._cache.set('isDeno', this._detectDeno());
|
|
20
20
|
this._cache.set('isBun', this._detectBun());
|
|
21
|
+
this._cache.set('isNativeScript', this._detectNativeScript());
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
// Primary environment detection
|
|
@@ -41,6 +42,15 @@ export class EnvironmentDetector {
|
|
|
41
42
|
return typeof Bun !== 'undefined';
|
|
42
43
|
}
|
|
43
44
|
|
|
45
|
+
_detectNativeScript() {
|
|
46
|
+
return typeof global !== 'undefined' &&
|
|
47
|
+
((typeof global.NativeScriptGlobals !== 'undefined') ||
|
|
48
|
+
(typeof global.__ANDROID__ !== 'undefined') ||
|
|
49
|
+
(typeof global.__IOS__ !== 'undefined') ||
|
|
50
|
+
(typeof global.__VISIONOS__ !== 'undefined') ||
|
|
51
|
+
(typeof global.loadModule === 'function' && typeof global.registerModule === 'function'));
|
|
52
|
+
}
|
|
53
|
+
|
|
44
54
|
_detectWorker() {
|
|
45
55
|
return typeof importScripts !== 'undefined' ||
|
|
46
56
|
this._detectServiceWorker() ||
|
|
@@ -99,12 +109,16 @@ export class EnvironmentDetector {
|
|
|
99
109
|
return this._cache.get('isBun');
|
|
100
110
|
}
|
|
101
111
|
|
|
112
|
+
get isNativeScript() {
|
|
113
|
+
return this._cache.get('isNativeScript');
|
|
114
|
+
}
|
|
115
|
+
|
|
102
116
|
get isServer() {
|
|
103
117
|
return this.isNodeJS || this.isDeno || this.isBun;
|
|
104
118
|
}
|
|
105
119
|
|
|
106
120
|
get isClient() {
|
|
107
|
-
return this.isBrowser || this.isWorker;
|
|
121
|
+
return this.isBrowser || this.isWorker || this.isNativeScript;
|
|
108
122
|
}
|
|
109
123
|
|
|
110
124
|
// WebRTC capability detection
|
|
@@ -120,20 +134,27 @@ export class EnvironmentDetector {
|
|
|
120
134
|
typeof global.RTCPeerConnection !== 'undefined') ||
|
|
121
135
|
typeof RTCPeerConnection !== 'undefined';
|
|
122
136
|
}
|
|
137
|
+
if (this.isNativeScript) {
|
|
138
|
+
// NativeScript can access native WebRTC implementations through native modules
|
|
139
|
+
// Check for globally injected WebRTC first
|
|
140
|
+
return (typeof global !== 'undefined' &&
|
|
141
|
+
typeof global.RTCPeerConnection !== 'undefined') ||
|
|
142
|
+
typeof RTCPeerConnection !== 'undefined';
|
|
143
|
+
}
|
|
123
144
|
return false;
|
|
124
145
|
}
|
|
125
146
|
|
|
126
147
|
get hasDataChannel() {
|
|
127
|
-
return this.hasWebRTC && this.isBrowser;
|
|
148
|
+
return this.hasWebRTC && (this.isBrowser || this.isNativeScript);
|
|
128
149
|
}
|
|
129
150
|
|
|
130
151
|
get hasGetUserMedia() {
|
|
131
|
-
if (!this.isBrowser) return false;
|
|
132
|
-
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ||
|
|
133
|
-
!!(navigator.getUserMedia ||
|
|
152
|
+
if (!this.isBrowser && !this.isNativeScript) return false;
|
|
153
|
+
return !!(navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ||
|
|
154
|
+
!!(navigator && (navigator.getUserMedia ||
|
|
134
155
|
navigator.webkitGetUserMedia ||
|
|
135
156
|
navigator.mozGetUserMedia ||
|
|
136
|
-
navigator.msGetUserMedia);
|
|
157
|
+
navigator.msGetUserMedia));
|
|
137
158
|
}
|
|
138
159
|
|
|
139
160
|
// WebSocket capability detection
|
|
@@ -164,12 +185,17 @@ export class EnvironmentDetector {
|
|
|
164
185
|
return false;
|
|
165
186
|
}
|
|
166
187
|
}
|
|
188
|
+
if (this.isNativeScript) {
|
|
189
|
+
// NativeScript has WebSocket support through global injection or native modules
|
|
190
|
+
return typeof WebSocket !== 'undefined' ||
|
|
191
|
+
(typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined');
|
|
192
|
+
}
|
|
167
193
|
return false;
|
|
168
194
|
}
|
|
169
195
|
|
|
170
196
|
// Storage capability detection
|
|
171
197
|
get hasLocalStorage() {
|
|
172
|
-
if (!this.isBrowser) return false;
|
|
198
|
+
if (!this.isBrowser && !this.isNativeScript) return false;
|
|
173
199
|
try {
|
|
174
200
|
const test = '__storage_test__';
|
|
175
201
|
localStorage.setItem(test, test);
|
|
@@ -181,7 +207,7 @@ export class EnvironmentDetector {
|
|
|
181
207
|
}
|
|
182
208
|
|
|
183
209
|
get hasSessionStorage() {
|
|
184
|
-
if (!this.isBrowser) return false;
|
|
210
|
+
if (!this.isBrowser && !this.isNativeScript) return false;
|
|
185
211
|
try {
|
|
186
212
|
const test = '__storage_test__';
|
|
187
213
|
sessionStorage.setItem(test, test);
|
|
@@ -193,12 +219,12 @@ export class EnvironmentDetector {
|
|
|
193
219
|
}
|
|
194
220
|
|
|
195
221
|
get hasIndexedDB() {
|
|
196
|
-
if (!this.isBrowser) return false;
|
|
222
|
+
if (!this.isBrowser) return false; // NativeScript doesn't typically have IndexedDB
|
|
197
223
|
return typeof indexedDB !== 'undefined';
|
|
198
224
|
}
|
|
199
225
|
|
|
200
226
|
get hasCookies() {
|
|
201
|
-
if (!this.isBrowser) return false;
|
|
227
|
+
if (!this.isBrowser) return false; // NativeScript doesn't have cookies
|
|
202
228
|
return typeof document !== 'undefined' &&
|
|
203
229
|
typeof document.cookie === 'string';
|
|
204
230
|
}
|
|
@@ -243,6 +269,11 @@ export class EnvironmentDetector {
|
|
|
243
269
|
return false;
|
|
244
270
|
}
|
|
245
271
|
}
|
|
272
|
+
if (this.isNativeScript) {
|
|
273
|
+
// NativeScript may have crypto through global polyfills or native modules
|
|
274
|
+
return (typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined') ||
|
|
275
|
+
(typeof global !== 'undefined' && typeof global.crypto !== 'undefined');
|
|
276
|
+
}
|
|
246
277
|
return false;
|
|
247
278
|
}
|
|
248
279
|
|
|
@@ -264,6 +295,13 @@ export class EnvironmentDetector {
|
|
|
264
295
|
return false;
|
|
265
296
|
}
|
|
266
297
|
}
|
|
298
|
+
if (this.isNativeScript) {
|
|
299
|
+
// NativeScript may have crypto random values through global polyfills
|
|
300
|
+
return (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') ||
|
|
301
|
+
(typeof global !== 'undefined' &&
|
|
302
|
+
typeof global.crypto !== 'undefined' &&
|
|
303
|
+
typeof global.crypto.getRandomValues === 'function');
|
|
304
|
+
}
|
|
267
305
|
return false;
|
|
268
306
|
}
|
|
269
307
|
|
|
@@ -318,6 +356,34 @@ export class EnvironmentDetector {
|
|
|
318
356
|
};
|
|
319
357
|
}
|
|
320
358
|
|
|
359
|
+
// NativeScript-specific detection
|
|
360
|
+
getNativeScriptInfo() {
|
|
361
|
+
if (!this.isNativeScript) return null;
|
|
362
|
+
|
|
363
|
+
const info = {
|
|
364
|
+
runtime: 'nativescript'
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
// Detect platform if globals are available
|
|
368
|
+
if (typeof global !== 'undefined') {
|
|
369
|
+
if (global.__ANDROID__) {
|
|
370
|
+
info.platform = 'android';
|
|
371
|
+
} else if (global.__IOS__) {
|
|
372
|
+
info.platform = 'ios';
|
|
373
|
+
} else if (global.__VISIONOS__) {
|
|
374
|
+
info.platform = 'visionos';
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// Add additional NativeScript globals if available
|
|
378
|
+
if (global.NativeScriptGlobals) {
|
|
379
|
+
info.launched = global.NativeScriptGlobals.launched;
|
|
380
|
+
info.appInstanceReady = global.NativeScriptGlobals.appInstanceReady;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
return info;
|
|
385
|
+
}
|
|
386
|
+
|
|
321
387
|
// Device and platform detection
|
|
322
388
|
getPlatformInfo() {
|
|
323
389
|
if (this.isBrowser) {
|
|
@@ -336,6 +402,10 @@ export class EnvironmentDetector {
|
|
|
336
402
|
return this.getNodeInfo();
|
|
337
403
|
}
|
|
338
404
|
|
|
405
|
+
if (this.isNativeScript) {
|
|
406
|
+
return this.getNativeScriptInfo();
|
|
407
|
+
}
|
|
408
|
+
|
|
339
409
|
return null;
|
|
340
410
|
}
|
|
341
411
|
|
|
@@ -390,6 +460,7 @@ export class EnvironmentDetector {
|
|
|
390
460
|
isSharedWorker: this.isSharedWorker,
|
|
391
461
|
isDeno: this.isDeno,
|
|
392
462
|
isBun: this.isBun,
|
|
463
|
+
isNativeScript: this.isNativeScript,
|
|
393
464
|
isServer: this.isServer,
|
|
394
465
|
isClient: this.isClient
|
|
395
466
|
},
|
|
@@ -410,6 +481,7 @@ export class EnvironmentDetector {
|
|
|
410
481
|
platform: this.getPlatformInfo(),
|
|
411
482
|
browser: this.getBrowserInfo(),
|
|
412
483
|
node: this.getNodeInfo(),
|
|
484
|
+
nativescript: this.getNativeScriptInfo(),
|
|
413
485
|
network: {
|
|
414
486
|
online: this.isOnline,
|
|
415
487
|
type: this.networkType
|
|
@@ -436,6 +508,7 @@ export const environmentDetector = new EnvironmentDetector();
|
|
|
436
508
|
export const isBrowser = () => environmentDetector.isBrowser;
|
|
437
509
|
export const isNodeJS = () => environmentDetector.isNodeJS;
|
|
438
510
|
export const isWorker = () => environmentDetector.isWorker;
|
|
511
|
+
export const isNativeScript = () => environmentDetector.isNativeScript;
|
|
439
512
|
export const hasWebRTC = () => environmentDetector.hasWebRTC;
|
|
440
513
|
export const hasWebSocket = () => environmentDetector.hasWebSocket;
|
|
441
514
|
export const getEnvironmentReport = () => environmentDetector.getEnvironmentReport();
|
package/src/MediaManager.js
CHANGED
|
@@ -53,8 +53,10 @@ export class MediaManager extends EventEmitter {
|
|
|
53
53
|
* Get available media devices
|
|
54
54
|
*/
|
|
55
55
|
async enumerateDevices() {
|
|
56
|
-
// Only available in browser environments with media device support
|
|
57
|
-
if (!environmentDetector.isBrowser
|
|
56
|
+
// Only available in browser and NativeScript environments with media device support
|
|
57
|
+
if ((!environmentDetector.isBrowser && !environmentDetector.isNativeScript) ||
|
|
58
|
+
typeof navigator === 'undefined' ||
|
|
59
|
+
typeof navigator.mediaDevices === 'undefined') {
|
|
58
60
|
console.warn('Media device enumeration not available in this environment');
|
|
59
61
|
return;
|
|
60
62
|
}
|
package/src/PeerPigeonMesh.js
CHANGED
|
@@ -135,10 +135,11 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
135
135
|
|
|
136
136
|
// Log environment info
|
|
137
137
|
console.log('🔍 PeerPigeon Environment Detection:', {
|
|
138
|
-
runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}`,
|
|
138
|
+
runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}${report.runtime.isNativeScript ? 'NativeScript' : ''}`,
|
|
139
139
|
webrtc: report.capabilities.webrtc,
|
|
140
140
|
websocket: report.capabilities.webSocket,
|
|
141
|
-
browser: report.browser?.name || 'N/A'
|
|
141
|
+
browser: report.browser?.name || 'N/A',
|
|
142
|
+
nativescript: report.nativescript?.platform || 'N/A'
|
|
142
143
|
});
|
|
143
144
|
|
|
144
145
|
// Check WebRTC support (required for peer connections)
|
|
@@ -147,6 +148,8 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
147
148
|
errors.push('WebRTC is not supported in this browser. PeerPigeon requires WebRTC for peer-to-peer connections.');
|
|
148
149
|
} else if (report.runtime.isNodeJS) {
|
|
149
150
|
warnings.push('WebRTC support not detected in Node.js environment. Consider using a WebRTC library like node-webrtc.');
|
|
151
|
+
} else if (report.runtime.isNativeScript) {
|
|
152
|
+
warnings.push('WebRTC support not detected in NativeScript environment. Consider using a native WebRTC plugin.');
|
|
150
153
|
}
|
|
151
154
|
}
|
|
152
155
|
|
|
@@ -156,11 +159,13 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
156
159
|
errors.push('WebSocket is not supported in this browser. PeerPigeon requires WebSocket for signaling.');
|
|
157
160
|
} else if (report.runtime.isNodeJS) {
|
|
158
161
|
warnings.push('WebSocket support not detected. Install the "ws" package for WebSocket support in Node.js.');
|
|
162
|
+
} else if (report.runtime.isNativeScript) {
|
|
163
|
+
warnings.push('WebSocket support not detected. Consider using a native WebSocket plugin or polyfill.');
|
|
159
164
|
}
|
|
160
165
|
}
|
|
161
166
|
|
|
162
167
|
// Check storage capabilities for persistent peer ID
|
|
163
|
-
if (report.runtime.isBrowser && !report.capabilities.localStorage && !report.capabilities.sessionStorage) {
|
|
168
|
+
if ((report.runtime.isBrowser || report.runtime.isNativeScript) && !report.capabilities.localStorage && !report.capabilities.sessionStorage) {
|
|
164
169
|
warnings.push('No storage mechanism available. Peer ID will not persist between sessions.');
|
|
165
170
|
}
|
|
166
171
|
|
|
@@ -188,6 +193,21 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
188
193
|
}
|
|
189
194
|
}
|
|
190
195
|
|
|
196
|
+
if (report.runtime.isNativeScript) {
|
|
197
|
+
// NativeScript-specific checks
|
|
198
|
+
const nativeScript = report.nativescript;
|
|
199
|
+
if (nativeScript && nativeScript.platform) {
|
|
200
|
+
console.log(`🔮 Running on NativeScript ${nativeScript.platform} platform`);
|
|
201
|
+
|
|
202
|
+
// Platform-specific considerations
|
|
203
|
+
if (nativeScript.platform === 'android') {
|
|
204
|
+
warnings.push('Android WebRTC may require network permissions and appropriate security configurations.');
|
|
205
|
+
} else if (nativeScript.platform === 'ios' || nativeScript.platform === 'visionos') {
|
|
206
|
+
warnings.push('iOS/visionOS WebRTC may require camera/microphone permissions for media features.');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
191
211
|
// Handle errors and warnings
|
|
192
212
|
if (errors.length > 0) {
|
|
193
213
|
const errorMessage = 'PeerPigeon environment validation failed:\n' + errors.join('\n');
|
package/src/SignalingClient.js
CHANGED
|
@@ -60,8 +60,8 @@ export class SignalingClient extends EventEmitter {
|
|
|
60
60
|
console.warn('ws package not found in Node.js environment. Install with: npm install ws');
|
|
61
61
|
throw new Error('WebSocket not available in Node.js. Install the "ws" package.');
|
|
62
62
|
}
|
|
63
|
-
} else if (environmentDetector.isBrowser || environmentDetector.isWorker) {
|
|
64
|
-
// In browser or
|
|
63
|
+
} else if (environmentDetector.isBrowser || environmentDetector.isWorker || environmentDetector.isNativeScript) {
|
|
64
|
+
// In browser, worker, or NativeScript environments, use the native WebSocket
|
|
65
65
|
return new WebSocket(url);
|
|
66
66
|
} else {
|
|
67
67
|
throw new Error('WebSocket not supported in this environment');
|
|
@@ -383,8 +383,8 @@ export class SignalingClient extends EventEmitter {
|
|
|
383
383
|
}
|
|
384
384
|
};
|
|
385
385
|
|
|
386
|
-
if (environmentDetector.isBrowser) {
|
|
387
|
-
this.keepAliveInterval = window.setInterval(keepAliveCallback, this.keepAliveIntervalMs);
|
|
386
|
+
if (environmentDetector.isBrowser || environmentDetector.isNativeScript) {
|
|
387
|
+
this.keepAliveInterval = (typeof window !== 'undefined' ? window.setInterval : setInterval)(keepAliveCallback, this.keepAliveIntervalMs);
|
|
388
388
|
} else {
|
|
389
389
|
this.keepAliveInterval = setInterval(keepAliveCallback, this.keepAliveIntervalMs);
|
|
390
390
|
}
|
|
@@ -467,8 +467,8 @@ export class SignalingClient extends EventEmitter {
|
|
|
467
467
|
}
|
|
468
468
|
};
|
|
469
469
|
|
|
470
|
-
if (environmentDetector.isBrowser) {
|
|
471
|
-
this.healthCheckInterval = window.setInterval(healthCheckCallback, 30000);
|
|
470
|
+
if (environmentDetector.isBrowser || environmentDetector.isNativeScript) {
|
|
471
|
+
this.healthCheckInterval = (typeof window !== 'undefined' ? window.setInterval : setInterval)(healthCheckCallback, 30000);
|
|
472
472
|
} else {
|
|
473
473
|
this.healthCheckInterval = setInterval(healthCheckCallback, 30000);
|
|
474
474
|
}
|
package/src/StorageManager.js
CHANGED
|
@@ -36,11 +36,25 @@ export class StorageManager extends EventEmitter {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
loadSignalingUrlFromQuery() {
|
|
39
|
-
// Only works in browser environments
|
|
40
|
-
if (!environmentDetector.isBrowser) return this.loadSignalingUrlFromStorage();
|
|
39
|
+
// Only works in browser and NativeScript environments with location/URL support
|
|
40
|
+
if (!environmentDetector.isBrowser && !environmentDetector.isNativeScript) return this.loadSignalingUrlFromStorage();
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
|
|
42
|
+
// Check if we have URL search capabilities
|
|
43
|
+
if (typeof URLSearchParams === 'undefined' ||
|
|
44
|
+
(environmentDetector.isBrowser && typeof window === 'undefined') ||
|
|
45
|
+
(environmentDetector.isBrowser && typeof window.location === 'undefined')) {
|
|
46
|
+
return this.loadSignalingUrlFromStorage();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let searchParams;
|
|
50
|
+
if (environmentDetector.isBrowser) {
|
|
51
|
+
searchParams = new URLSearchParams(window.location.search);
|
|
52
|
+
} else if (environmentDetector.isNativeScript) {
|
|
53
|
+
// NativeScript might not have window.location, fallback to storage
|
|
54
|
+
return this.loadSignalingUrlFromStorage();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const signalingUrl = searchParams?.get('api') || searchParams?.get('url') || searchParams?.get('signaling');
|
|
44
58
|
|
|
45
59
|
if (signalingUrl) {
|
|
46
60
|
// Only emit event if URL is different from current one
|
|
@@ -63,7 +77,7 @@ export class StorageManager extends EventEmitter {
|
|
|
63
77
|
|
|
64
78
|
// Environment-aware random value generation
|
|
65
79
|
if (environmentDetector.hasRandomValues) {
|
|
66
|
-
if (environmentDetector.isBrowser || environmentDetector.isWorker) {
|
|
80
|
+
if (environmentDetector.isBrowser || environmentDetector.isWorker || environmentDetector.isNativeScript) {
|
|
67
81
|
crypto.getRandomValues(array);
|
|
68
82
|
} else if (environmentDetector.isNodeJS) {
|
|
69
83
|
// In Node.js, use crypto module (handle both CommonJS and ES modules)
|
package/src/WebDHT.js
CHANGED
|
@@ -22,6 +22,9 @@ export class WebDHT extends EventEmitter {
|
|
|
22
22
|
// Subscriptions: key -> Set of peer IDs that want notifications
|
|
23
23
|
this.subscriptions = new Map();
|
|
24
24
|
|
|
25
|
+
// Pending subscriptions for keys that don't exist yet: keyId -> Set of peer IDs
|
|
26
|
+
this.pendingSubscriptions = new Map();
|
|
27
|
+
|
|
25
28
|
// Active subscriptions from this peer to others
|
|
26
29
|
this.mySubscriptions = new Set();
|
|
27
30
|
|
|
@@ -139,10 +142,42 @@ export class WebDHT extends EventEmitter {
|
|
|
139
142
|
publisher: this.peerId
|
|
140
143
|
};
|
|
141
144
|
|
|
145
|
+
// Check if this is a new key (for pending subscription activation)
|
|
146
|
+
const isNewKey = !this.localStorage.has(keyId);
|
|
147
|
+
|
|
142
148
|
// CRITICAL FIX: Always store locally first (the originator always keeps a copy)
|
|
143
149
|
this.storeLocally(keyId, storeData);
|
|
144
150
|
console.log(`DHT PUT: Stored locally: ${key}`);
|
|
145
151
|
|
|
152
|
+
// If this is a new key, activate any pending subscriptions
|
|
153
|
+
if (isNewKey) {
|
|
154
|
+
const activatedSubscribers = this.activatePendingSubscriptions(keyId);
|
|
155
|
+
|
|
156
|
+
// Notify locally activated subscribers about the new key
|
|
157
|
+
if (activatedSubscribers.length > 0) {
|
|
158
|
+
console.log(`DHT PUT: Notifying ${activatedSubscribers.length} locally pending subscribers about new key ${key}`);
|
|
159
|
+
|
|
160
|
+
const notificationPromises = activatedSubscribers.map(async (subscriberId) => {
|
|
161
|
+
if (subscriberId !== this.peerId) {
|
|
162
|
+
try {
|
|
163
|
+
return await this.sendDHTMessage(subscriberId, 'value_changed', {
|
|
164
|
+
key,
|
|
165
|
+
keyId,
|
|
166
|
+
newValue: value,
|
|
167
|
+
timestamp: storeData.timestamp,
|
|
168
|
+
isNewKey: true
|
|
169
|
+
});
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.warn(`Failed to notify subscriber ${subscriberId.substring(0, 8)} about new key:`, error.message);
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}).filter(Boolean);
|
|
176
|
+
|
|
177
|
+
await Promise.allSettled(notificationPromises);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
146
181
|
// AUTO-SUBSCRIBE: When putting a value, automatically subscribe to future changes
|
|
147
182
|
this.mySubscriptions.add(keyId);
|
|
148
183
|
console.log(`DHT PUT: Auto-subscribed to ${key} for future updates`);
|
|
@@ -159,19 +194,21 @@ export class WebDHT extends EventEmitter {
|
|
|
159
194
|
*/
|
|
160
195
|
async get(key, options = {}) {
|
|
161
196
|
const keyId = await this.generateKeyId(key);
|
|
162
|
-
//
|
|
163
|
-
const subscribe =
|
|
197
|
+
// Subscribe unless explicitly disabled or skipSubscribe is true
|
|
198
|
+
const subscribe = options.skipSubscribe ? false : (options.subscribe !== false);
|
|
164
199
|
const forceRefresh = options.forceRefresh || false;
|
|
165
200
|
|
|
166
|
-
console.log(`DHT GET: ${key} -> ${keyId.substring(0, 8)}... (auto-subscribing, forceRefresh: ${forceRefresh})`);
|
|
201
|
+
console.log(`DHT GET: ${key} -> ${keyId.substring(0, 8)}... (auto-subscribing: ${subscribe}, forceRefresh: ${forceRefresh})`);
|
|
167
202
|
|
|
168
203
|
// Check local storage FIRST (unless force refresh is requested)
|
|
169
204
|
if (!forceRefresh && this.localStorage.has(keyId)) {
|
|
170
205
|
const data = this.localStorage.get(keyId);
|
|
171
206
|
if (!this.isExpired(data)) {
|
|
172
207
|
console.log(`DHT GET: Found locally: ${key} (using cached data)`);
|
|
173
|
-
//
|
|
174
|
-
|
|
208
|
+
// Add subscription even for local data (unless skipSubscribe is true)
|
|
209
|
+
if (subscribe) {
|
|
210
|
+
this.mySubscriptions.add(keyId);
|
|
211
|
+
}
|
|
175
212
|
return data.value;
|
|
176
213
|
} else {
|
|
177
214
|
// Remove expired data
|
|
@@ -192,7 +229,7 @@ export class WebDHT extends EventEmitter {
|
|
|
192
229
|
|
|
193
230
|
/**
|
|
194
231
|
* Subscribe to changes for a key
|
|
195
|
-
* NOTE:
|
|
232
|
+
* NOTE: This now supports subscribing to keys that don't exist yet
|
|
196
233
|
*/
|
|
197
234
|
async subscribe(key) {
|
|
198
235
|
const keyId = await this.generateKeyId(key);
|
|
@@ -202,8 +239,39 @@ export class WebDHT extends EventEmitter {
|
|
|
202
239
|
// Add to our subscriptions immediately
|
|
203
240
|
this.mySubscriptions.add(keyId);
|
|
204
241
|
|
|
205
|
-
//
|
|
206
|
-
const
|
|
242
|
+
// Find the peers responsible for storing this key
|
|
243
|
+
const closestPeers = await this.findClosestPeers(keyId, this.config.replicationFactor);
|
|
244
|
+
|
|
245
|
+
// Send subscription requests to all potential storage peers
|
|
246
|
+
const subscribePromises = closestPeers.map(async (peerId) => {
|
|
247
|
+
if (peerId !== this.peerId) {
|
|
248
|
+
try {
|
|
249
|
+
return await this.sendDHTMessage(peerId, 'subscribe', {
|
|
250
|
+
keyId,
|
|
251
|
+
key,
|
|
252
|
+
subscriber: this.peerId
|
|
253
|
+
});
|
|
254
|
+
} catch (error) {
|
|
255
|
+
console.warn(`DHT SUBSCRIBE: Failed to subscribe to peer ${peerId.substring(0, 8)}:`, error.message);
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}).filter(Boolean);
|
|
260
|
+
|
|
261
|
+
await Promise.allSettled(subscribePromises);
|
|
262
|
+
|
|
263
|
+
// Also add ourselves to pending subscriptions if we're among the closest
|
|
264
|
+
if (this.isAmongClosest(keyId, closestPeers)) {
|
|
265
|
+
this.addPendingSubscription(keyId, this.peerId);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Try to get the current value (if it exists)
|
|
269
|
+
let currentValue = null;
|
|
270
|
+
try {
|
|
271
|
+
currentValue = await this.get(key, { skipSubscribe: true }); // Skip auto-subscribe since we're already subscribed
|
|
272
|
+
} catch (error) {
|
|
273
|
+
console.log(`DHT SUBSCRIBE: Key ${key} doesn't exist yet, but subscription is active for when it's created`);
|
|
274
|
+
}
|
|
207
275
|
|
|
208
276
|
console.log(`DHT SUBSCRIBE: Subscribed to ${key}, current value:`, currentValue);
|
|
209
277
|
return currentValue;
|
|
@@ -243,6 +311,14 @@ export class WebDHT extends EventEmitter {
|
|
|
243
311
|
}
|
|
244
312
|
}
|
|
245
313
|
|
|
314
|
+
// Remove local pending subscription if we're storing this key
|
|
315
|
+
if (this.pendingSubscriptions.has(keyId)) {
|
|
316
|
+
this.pendingSubscriptions.get(keyId).delete(this.peerId);
|
|
317
|
+
if (this.pendingSubscriptions.get(keyId).size === 0) {
|
|
318
|
+
this.pendingSubscriptions.delete(keyId);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
246
322
|
console.log(`DHT UNSUBSCRIBE: ${key} -> ${keyId.substring(0, 8)}...`);
|
|
247
323
|
}
|
|
248
324
|
|
|
@@ -390,8 +466,40 @@ export class WebDHT extends EventEmitter {
|
|
|
390
466
|
const closestPeers = await this.findClosestPeers(keyId, this.config.replicationFactor);
|
|
391
467
|
|
|
392
468
|
if (this.isAmongClosest(keyId, closestPeers)) {
|
|
469
|
+
// Check if this is a new key (for pending subscription activation)
|
|
470
|
+
const isNewKey = !this.localStorage.has(keyId);
|
|
471
|
+
|
|
393
472
|
this.storeLocally(keyId, { key, value, timestamp, ttl, publisher });
|
|
394
473
|
|
|
474
|
+
// If this is a new key, activate any pending subscriptions
|
|
475
|
+
if (isNewKey) {
|
|
476
|
+
const activatedSubscribers = this.activatePendingSubscriptions(keyId);
|
|
477
|
+
|
|
478
|
+
// Notify newly activated subscribers about the new key
|
|
479
|
+
if (activatedSubscribers.length > 0) {
|
|
480
|
+
console.log(`DHT STORE: Notifying ${activatedSubscribers.length} subscribers about new key ${key}`);
|
|
481
|
+
|
|
482
|
+
const notificationPromises = activatedSubscribers.map(async (subscriberId) => {
|
|
483
|
+
if (subscriberId !== this.peerId && subscriberId !== fromPeerId) {
|
|
484
|
+
try {
|
|
485
|
+
return await this.sendDHTMessage(subscriberId, 'value_changed', {
|
|
486
|
+
key,
|
|
487
|
+
keyId,
|
|
488
|
+
newValue: value,
|
|
489
|
+
timestamp,
|
|
490
|
+
isNewKey: true
|
|
491
|
+
});
|
|
492
|
+
} catch (error) {
|
|
493
|
+
console.warn(`Failed to notify subscriber ${subscriberId.substring(0, 8)} about new key:`, error.message);
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}).filter(Boolean);
|
|
498
|
+
|
|
499
|
+
await Promise.allSettled(notificationPromises);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
395
503
|
console.log(`🔥 DHT STORE: Accepting and storing ${key}, sending success response`);
|
|
396
504
|
|
|
397
505
|
// Send response using the same direct messaging structure
|
|
@@ -499,9 +607,16 @@ export class WebDHT extends EventEmitter {
|
|
|
499
607
|
async handleSubscribeRequest(fromPeerId, data) {
|
|
500
608
|
const { keyId, key, subscriber } = data;
|
|
501
609
|
|
|
610
|
+
console.log(`DHT SUBSCRIBE REQUEST: ${key} from ${fromPeerId.substring(0, 8)} for subscriber ${subscriber.substring(0, 8)}`);
|
|
611
|
+
|
|
502
612
|
if (this.localStorage.has(keyId)) {
|
|
613
|
+
// Key exists - add to active subscriptions
|
|
503
614
|
this.addSubscription(keyId, subscriber);
|
|
504
|
-
console.log(`DHT SUBSCRIBE: added ${subscriber.substring(0, 8)}... to ${key} notifications`);
|
|
615
|
+
console.log(`DHT SUBSCRIBE: added ${subscriber.substring(0, 8)}... to ${key} notifications (key exists)`);
|
|
616
|
+
} else {
|
|
617
|
+
// Key doesn't exist yet - add to pending subscriptions
|
|
618
|
+
this.addPendingSubscription(keyId, subscriber);
|
|
619
|
+
console.log(`DHT SUBSCRIBE: added ${subscriber.substring(0, 8)}... to ${key} pending notifications (key doesn't exist yet)`);
|
|
505
620
|
}
|
|
506
621
|
}
|
|
507
622
|
|
|
@@ -511,12 +626,22 @@ export class WebDHT extends EventEmitter {
|
|
|
511
626
|
async handleUnsubscribeRequest(fromPeerId, data) {
|
|
512
627
|
const { keyId, key, subscriber } = data;
|
|
513
628
|
|
|
629
|
+
// Remove from active subscriptions
|
|
514
630
|
if (this.subscriptions.has(keyId)) {
|
|
515
631
|
this.subscriptions.get(keyId).delete(subscriber);
|
|
516
632
|
if (this.subscriptions.get(keyId).size === 0) {
|
|
517
633
|
this.subscriptions.delete(keyId);
|
|
518
634
|
}
|
|
519
|
-
console.log(`DHT UNSUBSCRIBE: removed ${subscriber.substring(0, 8)}... from ${key} notifications`);
|
|
635
|
+
console.log(`DHT UNSUBSCRIBE: removed ${subscriber.substring(0, 8)}... from ${key} active notifications`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// Remove from pending subscriptions
|
|
639
|
+
if (this.pendingSubscriptions.has(keyId)) {
|
|
640
|
+
this.pendingSubscriptions.get(keyId).delete(subscriber);
|
|
641
|
+
if (this.pendingSubscriptions.get(keyId).size === 0) {
|
|
642
|
+
this.pendingSubscriptions.delete(keyId);
|
|
643
|
+
}
|
|
644
|
+
console.log(`DHT UNSUBSCRIBE: removed ${subscriber.substring(0, 8)}... from ${key} pending notifications`);
|
|
520
645
|
}
|
|
521
646
|
}
|
|
522
647
|
|
|
@@ -524,9 +649,9 @@ export class WebDHT extends EventEmitter {
|
|
|
524
649
|
* Handle value changed notification
|
|
525
650
|
*/
|
|
526
651
|
async handleValueChangedNotification(fromPeerId, data) {
|
|
527
|
-
const { key, keyId, newValue, timestamp } = data;
|
|
652
|
+
const { key, keyId, newValue, timestamp, isNewKey } = data;
|
|
528
653
|
|
|
529
|
-
console.log(`🔥 DHT VALUE_CHANGED notification: ${key} = ${newValue} from ${fromPeerId.substring(0, 8)}`);
|
|
654
|
+
console.log(`🔥 DHT VALUE_CHANGED notification: ${key} = ${newValue} from ${fromPeerId.substring(0, 8)}${isNewKey ? ' (NEW KEY)' : ''}`);
|
|
530
655
|
|
|
531
656
|
// CRITICAL FIX: Always update local cache if we have it, regardless of subscriptions
|
|
532
657
|
// This prevents stale cached values from being returned by get() operations
|
|
@@ -540,6 +665,17 @@ export class WebDHT extends EventEmitter {
|
|
|
540
665
|
} else {
|
|
541
666
|
console.log(`🔥 DHT VALUE_CHANGED: Ignoring older notification for ${key} (current: ${storedData.timestamp}, notification: ${timestamp})`);
|
|
542
667
|
}
|
|
668
|
+
} else if (isNewKey) {
|
|
669
|
+
// For new keys, store the data locally even if we don't normally store this key
|
|
670
|
+
// This helps with caching and consistency
|
|
671
|
+
console.log(`🔥 DHT VALUE_CHANGED: Caching new key ${key} locally`);
|
|
672
|
+
this.storeLocally(keyId, {
|
|
673
|
+
key,
|
|
674
|
+
value: newValue,
|
|
675
|
+
timestamp,
|
|
676
|
+
ttl: null, // Use default TTL
|
|
677
|
+
publisher: fromPeerId
|
|
678
|
+
}, false); // Not a primary replica
|
|
543
679
|
}
|
|
544
680
|
|
|
545
681
|
// Check if we have subscribers for this key
|
|
@@ -551,8 +687,8 @@ export class WebDHT extends EventEmitter {
|
|
|
551
687
|
|
|
552
688
|
// Emit change event if this peer is subscribed
|
|
553
689
|
if (hasSubscribers) {
|
|
554
|
-
this.emit('valueChanged', { key, keyId, newValue, timestamp });
|
|
555
|
-
console.log(`🔥 DHT VALUE_CHANGED: Emitted local event for ${key}`);
|
|
690
|
+
this.emit('valueChanged', { key, keyId, newValue, timestamp, isNewKey });
|
|
691
|
+
console.log(`🔥 DHT VALUE_CHANGED: Emitted local event for ${key}${isNewKey ? ' (NEW KEY)' : ''}`);
|
|
556
692
|
}
|
|
557
693
|
|
|
558
694
|
// Forward to local subscribers (other peers that subscribed through this peer)
|
|
@@ -567,7 +703,8 @@ export class WebDHT extends EventEmitter {
|
|
|
567
703
|
key,
|
|
568
704
|
keyId,
|
|
569
705
|
newValue,
|
|
570
|
-
timestamp
|
|
706
|
+
timestamp,
|
|
707
|
+
isNewKey
|
|
571
708
|
});
|
|
572
709
|
} catch (error) {
|
|
573
710
|
console.warn(`Failed to forward notification to ${subscriberId.substring(0, 8)}:`, error.message);
|
|
@@ -808,6 +945,42 @@ export class WebDHT extends EventEmitter {
|
|
|
808
945
|
this.subscriptions.get(keyId).add(subscriberId);
|
|
809
946
|
}
|
|
810
947
|
|
|
948
|
+
/**
|
|
949
|
+
* Add a pending subscription for a key that doesn't exist yet
|
|
950
|
+
*/
|
|
951
|
+
addPendingSubscription(keyId, subscriberId) {
|
|
952
|
+
if (!this.pendingSubscriptions.has(keyId)) {
|
|
953
|
+
this.pendingSubscriptions.set(keyId, new Set());
|
|
954
|
+
}
|
|
955
|
+
this.pendingSubscriptions.get(keyId).add(subscriberId);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/**
|
|
959
|
+
* Activate pending subscriptions when a key is first created
|
|
960
|
+
*/
|
|
961
|
+
activatePendingSubscriptions(keyId) {
|
|
962
|
+
if (this.pendingSubscriptions.has(keyId)) {
|
|
963
|
+
const pendingSubscribers = this.pendingSubscriptions.get(keyId);
|
|
964
|
+
|
|
965
|
+
// Move all pending subscribers to active subscriptions
|
|
966
|
+
if (!this.subscriptions.has(keyId)) {
|
|
967
|
+
this.subscriptions.set(keyId, new Set());
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
pendingSubscribers.forEach(subscriberId => {
|
|
971
|
+
this.subscriptions.get(keyId).add(subscriberId);
|
|
972
|
+
});
|
|
973
|
+
|
|
974
|
+
console.log(`DHT: Activated ${pendingSubscribers.size} pending subscriptions for keyId ${keyId.substring(0, 8)}`);
|
|
975
|
+
|
|
976
|
+
// Clear pending subscriptions for this key
|
|
977
|
+
this.pendingSubscriptions.delete(keyId);
|
|
978
|
+
|
|
979
|
+
return Array.from(pendingSubscribers);
|
|
980
|
+
}
|
|
981
|
+
return [];
|
|
982
|
+
}
|
|
983
|
+
|
|
811
984
|
/**
|
|
812
985
|
* Check if this peer is among the closest to a key
|
|
813
986
|
*/
|
|
@@ -903,6 +1076,7 @@ export class WebDHT extends EventEmitter {
|
|
|
903
1076
|
return {
|
|
904
1077
|
storedKeys: this.localStorage.size,
|
|
905
1078
|
activeSubscriptions: this.subscriptions.size,
|
|
1079
|
+
pendingSubscriptions: this.pendingSubscriptions.size,
|
|
906
1080
|
mySubscriptions: this.mySubscriptions.size,
|
|
907
1081
|
connectedPeers: this.mesh.connectionManager.getConnectedPeerCount()
|
|
908
1082
|
};
|
|
@@ -919,6 +1093,7 @@ export class WebDHT extends EventEmitter {
|
|
|
919
1093
|
|
|
920
1094
|
this.localStorage.clear();
|
|
921
1095
|
this.subscriptions.clear();
|
|
1096
|
+
this.pendingSubscriptions.clear();
|
|
922
1097
|
this.mySubscriptions.clear();
|
|
923
1098
|
|
|
924
1099
|
if (this.responseHandlers) {
|