peerpigeon 1.0.3 → 1.0.6
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 +60 -1
- package/dist/peerpigeon-browser.js +439 -6
- package/dist/peerpigeon-browser.js.map +3 -3
- package/docs/BINARY_IMPLEMENTATION_SUMMARY.md +304 -0
- package/docs/BINARY_MESSAGES.md +332 -0
- package/docs/STREAMING_API.md +542 -0
- package/docs/STREAMING_IMPLEMENTATION_SUMMARY.md +286 -0
- package/examples/binary-message-demo.html +496 -0
- package/examples/browser-2/EXPRESS_SOLUTION.md +183 -0
- package/examples/browser-2/ICE_DEBUG.md +171 -0
- package/examples/browser-2/IMPLEMENTATION.md +218 -0
- package/examples/browser-2/QUICK_START.md +149 -0
- package/examples/browser-2/README.md +303 -0
- package/examples/browser-2/dist/assets/index-Cck_6WJV.css +1 -0
- package/examples/browser-2/dist/assets/index-D8-cNlWQ.js +57 -0
- package/examples/browser-2/dist/index.html +32 -0
- package/examples/browser-2/dist/peerpigeon-browser.js +12483 -0
- package/examples/browser-2/index.html +2 -1
- package/examples/browser-2/package-lock.json +1276 -0
- package/examples/browser-2/package.json +5 -3
- package/examples/browser-2/public/peerpigeon-browser.js +12483 -0
- package/examples/browser-2/src/App.vue +7 -4
- package/examples/browser-2/src/components/CryptoView.vue +4 -4
- package/examples/browser-2/src/components/TestingView.vue +794 -0
- package/examples/browser-2/src/main.js +7 -1
- package/examples/browser-2/src/router.js +63 -0
- package/examples/browser-2/src/stores/peerpigeon.js +68 -7
- package/examples/browser-2/vite.config.js +15 -1
- package/examples/stream-file-transfer-demo.html +935 -0
- package/package.json +2 -2
- package/src/ConnectionManager.js +30 -0
- package/src/PeerConnection.js +409 -4
- package/src/PeerPigeonMesh.js +120 -1
- package/src/SignalingClient.js +12 -5
- package/src/browser-entry.js +5 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "peerpigeon",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
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",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"homepage": "https://github.com/PeerPigeon/PeerPigeon#readme",
|
|
80
80
|
"dependencies": {
|
|
81
81
|
"@koush/wrtc": "^0.5.3",
|
|
82
|
-
"pigeonrtc": "^0.0.
|
|
82
|
+
"pigeonrtc": "^0.0.5",
|
|
83
83
|
"unsea": "^1.1.2",
|
|
84
84
|
"ws": "^8.18.0",
|
|
85
85
|
"yamljs": "^0.3.0"
|
package/src/ConnectionManager.js
CHANGED
|
@@ -296,6 +296,22 @@ export class ConnectionManager extends EventEmitter {
|
|
|
296
296
|
this.debug.log('🔄 MEDIA FORWARDING: Disabled to prevent renegotiation conflicts with 3+ peers');
|
|
297
297
|
});
|
|
298
298
|
|
|
299
|
+
// Forward data stream events
|
|
300
|
+
peerConnection.addEventListener('streamReceived', (event) => {
|
|
301
|
+
this.debug.log(`[EVENT] Data stream received from ${event.peerId.substring(0, 8)}...`);
|
|
302
|
+
this.mesh.emit('streamReceived', event);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
peerConnection.addEventListener('streamCompleted', (event) => {
|
|
306
|
+
this.debug.log(`[EVENT] Data stream completed from ${event.peerId.substring(0, 8)}...`);
|
|
307
|
+
this.mesh.emit('streamCompleted', event);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
peerConnection.addEventListener('streamAborted', (event) => {
|
|
311
|
+
this.debug.log(`[EVENT] Data stream aborted from ${event.peerId.substring(0, 8)}...`);
|
|
312
|
+
this.mesh.emit('streamAborted', event);
|
|
313
|
+
});
|
|
314
|
+
|
|
299
315
|
peerConnection.addEventListener('renegotiationNeeded', async (event) => {
|
|
300
316
|
this.debug.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
|
|
301
317
|
|
|
@@ -744,6 +760,20 @@ export class ConnectionManager extends EventEmitter {
|
|
|
744
760
|
return;
|
|
745
761
|
}
|
|
746
762
|
|
|
763
|
+
// Handle binary messages first
|
|
764
|
+
if (message.type === 'binary' && message.data instanceof Uint8Array) {
|
|
765
|
+
this.debug.log(`📦 Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
|
|
766
|
+
|
|
767
|
+
// Emit binary message directly to application
|
|
768
|
+
this.mesh.emit('binaryMessageReceived', {
|
|
769
|
+
from: fromPeerId,
|
|
770
|
+
data: message.data,
|
|
771
|
+
size: message.size,
|
|
772
|
+
timestamp: Date.now()
|
|
773
|
+
});
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
|
|
747
777
|
// Define message types that should be filtered from peer-readable messages
|
|
748
778
|
// These messages are processed but not emitted as regular messages to UI/applications
|
|
749
779
|
const filteredMessageTypes = new Set([
|
package/src/PeerConnection.js
CHANGED
|
@@ -18,6 +18,14 @@ export class PeerConnection extends EventEmitter {
|
|
|
18
18
|
this.iceTimeoutId = null; // Timeout ID for ICE negotiation
|
|
19
19
|
this._forcedStatus = null; // Track forced status (e.g., failed)
|
|
20
20
|
|
|
21
|
+
// Binary payload coordination (standard + streaming chunks)
|
|
22
|
+
this._pendingBinaryPayloads = [];
|
|
23
|
+
|
|
24
|
+
// Stream handling
|
|
25
|
+
this._activeStreams = new Map(); // streamId -> { reader/writer, type, metadata }
|
|
26
|
+
this._streamChunks = new Map(); // streamId -> chunks array for reassembly
|
|
27
|
+
this._streamMetadata = new Map(); // streamId -> metadata
|
|
28
|
+
|
|
21
29
|
// Media stream support
|
|
22
30
|
this.localStream = options.localStream || null;
|
|
23
31
|
this.remoteStream = null;
|
|
@@ -325,6 +333,13 @@ export class PeerConnection extends EventEmitter {
|
|
|
325
333
|
}
|
|
326
334
|
|
|
327
335
|
setupDataChannel() {
|
|
336
|
+
if (!this.dataChannel) {
|
|
337
|
+
this.debug.error('setupDataChannel called without data channel instance');
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
this.dataChannel.binaryType = 'arraybuffer';
|
|
342
|
+
|
|
328
343
|
this.dataChannel.onopen = () => {
|
|
329
344
|
this.debug.log(`Data channel opened with ${this.peerId}`);
|
|
330
345
|
this.dataChannelReady = true;
|
|
@@ -334,16 +349,75 @@ export class PeerConnection extends EventEmitter {
|
|
|
334
349
|
this.dataChannel.onclose = () => {
|
|
335
350
|
this.debug.log(`Data channel closed with ${this.peerId}`);
|
|
336
351
|
this.dataChannelReady = false;
|
|
352
|
+
this._pendingBinaryPayloads.length = 0;
|
|
337
353
|
|
|
338
|
-
// Only emit disconnection if we're not intentionally closing
|
|
339
354
|
if (!this.isClosing) {
|
|
340
355
|
this.emit('disconnected', { peerId: this.peerId, reason: 'data channel closed' });
|
|
341
356
|
}
|
|
342
357
|
};
|
|
343
358
|
|
|
344
359
|
this.dataChannel.onmessage = (event) => {
|
|
360
|
+
const handleBinaryPayload = (buffer) => {
|
|
361
|
+
if (!buffer) return;
|
|
362
|
+
|
|
363
|
+
if (this._pendingBinaryPayloads.length === 0) {
|
|
364
|
+
this.debug.warn('Received unexpected binary payload without metadata');
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const payload = this._pendingBinaryPayloads.shift();
|
|
369
|
+
const uint8Array = new Uint8Array(buffer);
|
|
370
|
+
|
|
371
|
+
if (payload.type === 'binaryMessage') {
|
|
372
|
+
if (payload.size && payload.size !== uint8Array.byteLength) {
|
|
373
|
+
this.debug.warn(`Binary message size mismatch: expected ${payload.size}, got ${uint8Array.byteLength}`);
|
|
374
|
+
}
|
|
375
|
+
this.debug.log(`📦 Received binary message (${uint8Array.byteLength} bytes) from ${this.peerId.substring(0, 8)}...`);
|
|
376
|
+
this.emit('message', {
|
|
377
|
+
peerId: this.peerId,
|
|
378
|
+
message: {
|
|
379
|
+
type: 'binary',
|
|
380
|
+
data: uint8Array,
|
|
381
|
+
size: uint8Array.byteLength
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (payload.type === 'streamChunk') {
|
|
388
|
+
this._handleStreamChunkBinary(payload.header, uint8Array);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
this.debug.warn(`Received binary payload with unknown handler type: ${payload.type}`);
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
if (event.data instanceof ArrayBuffer) {
|
|
396
|
+
handleBinaryPayload(event.data);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (typeof Blob !== 'undefined' && event.data instanceof Blob) {
|
|
401
|
+
event.data.arrayBuffer()
|
|
402
|
+
.then(handleBinaryPayload)
|
|
403
|
+
.catch(error => this.debug.error('Failed to read binary payload:', error));
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
345
407
|
try {
|
|
346
408
|
const message = JSON.parse(event.data);
|
|
409
|
+
|
|
410
|
+
if (message.type === '__BINARY__') {
|
|
411
|
+
this._pendingBinaryPayloads.push({ type: 'binaryMessage', size: message.size });
|
|
412
|
+
this.debug.log(`📦 Binary message header received, expecting ${message.size} bytes`);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
if (message.type && message.type.startsWith('__STREAM_')) {
|
|
417
|
+
this._handleStreamMessage(message);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
347
421
|
this.emit('message', { peerId: this.peerId, message });
|
|
348
422
|
} catch (error) {
|
|
349
423
|
this.debug.error('Failed to parse message:', error);
|
|
@@ -354,8 +428,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
354
428
|
this.dataChannel.onerror = (error) => {
|
|
355
429
|
this.debug.error(`Data channel error with ${this.peerId}:`, error);
|
|
356
430
|
this.dataChannelReady = false;
|
|
431
|
+
this._pendingBinaryPayloads.length = 0;
|
|
357
432
|
|
|
358
|
-
// Only emit disconnection if we're not intentionally closing
|
|
359
433
|
if (!this.isClosing) {
|
|
360
434
|
this.emit('disconnected', { peerId: this.peerId, reason: 'data channel error' });
|
|
361
435
|
}
|
|
@@ -636,8 +710,25 @@ export class PeerConnection extends EventEmitter {
|
|
|
636
710
|
sendMessage(message) {
|
|
637
711
|
if (this.dataChannel && this.dataChannel.readyState === 'open') {
|
|
638
712
|
try {
|
|
639
|
-
|
|
640
|
-
|
|
713
|
+
// Check if message is binary data (ArrayBuffer or TypedArray like Uint8Array)
|
|
714
|
+
if (message instanceof ArrayBuffer || ArrayBuffer.isView(message)) {
|
|
715
|
+
this.debug.log(`📦 Sending binary message (${message.byteLength || message.buffer.byteLength} bytes) to ${this.peerId.substring(0, 8)}...`);
|
|
716
|
+
|
|
717
|
+
// For TypedArray views, send the underlying buffer
|
|
718
|
+
const buffer = ArrayBuffer.isView(message) ? message.buffer : message;
|
|
719
|
+
|
|
720
|
+
// Send a small JSON header first to indicate binary message follows
|
|
721
|
+
const header = JSON.stringify({ type: '__BINARY__', size: buffer.byteLength });
|
|
722
|
+
this.dataChannel.send(header);
|
|
723
|
+
|
|
724
|
+
// Then send the actual binary data
|
|
725
|
+
this.dataChannel.send(buffer);
|
|
726
|
+
return true;
|
|
727
|
+
} else {
|
|
728
|
+
// Regular JSON message
|
|
729
|
+
this.dataChannel.send(JSON.stringify(message));
|
|
730
|
+
return true;
|
|
731
|
+
}
|
|
641
732
|
} catch (error) {
|
|
642
733
|
this.debug.error(`Failed to send message to ${this.peerId}:`, error);
|
|
643
734
|
return false;
|
|
@@ -646,6 +737,320 @@ export class PeerConnection extends EventEmitter {
|
|
|
646
737
|
return false;
|
|
647
738
|
}
|
|
648
739
|
|
|
740
|
+
/**
|
|
741
|
+
* Create a WritableStream for sending data to this peer
|
|
742
|
+
* @param {object} options - Stream options
|
|
743
|
+
* @returns {WritableStream} A writable stream for sending data
|
|
744
|
+
*/
|
|
745
|
+
createWritableStream(options = {}) {
|
|
746
|
+
const streamId = options.streamId || this._generateStreamId();
|
|
747
|
+
const metadata = {
|
|
748
|
+
streamId,
|
|
749
|
+
type: options.type || 'binary',
|
|
750
|
+
filename: options.filename,
|
|
751
|
+
mimeType: options.mimeType,
|
|
752
|
+
totalSize: options.totalSize,
|
|
753
|
+
chunkSize: options.chunkSize,
|
|
754
|
+
timestamp: Date.now()
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
this.debug.log(`📤 Creating writable stream ${streamId} to ${this.peerId.substring(0, 8)}...`);
|
|
758
|
+
|
|
759
|
+
const configuredChunkSize = (typeof metadata.chunkSize === 'number' && Number.isFinite(metadata.chunkSize))
|
|
760
|
+
? metadata.chunkSize
|
|
761
|
+
: 16384;
|
|
762
|
+
|
|
763
|
+
const chunkSize = Math.max(4096, Math.min(configuredChunkSize, 65536));
|
|
764
|
+
metadata.chunkSize = chunkSize;
|
|
765
|
+
|
|
766
|
+
const highWaterMark = chunkSize * 32;
|
|
767
|
+
const lowWaterMark = chunkSize * 8;
|
|
768
|
+
|
|
769
|
+
const ensureChannelOpen = () => {
|
|
770
|
+
if (!this.dataChannel || this.dataChannel.readyState !== 'open') {
|
|
771
|
+
throw new Error('Data channel not open');
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
|
|
775
|
+
const waitForBufferDrain = () => {
|
|
776
|
+
if (!this.dataChannel || this.dataChannel.readyState !== 'open') {
|
|
777
|
+
return Promise.resolve();
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
if (this.dataChannel.bufferedAmount <= lowWaterMark) {
|
|
781
|
+
return Promise.resolve();
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
return new Promise((resolve) => {
|
|
785
|
+
const checkBuffer = () => {
|
|
786
|
+
if (!this.dataChannel || this.dataChannel.readyState !== 'open') {
|
|
787
|
+
resolve();
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
if (this.dataChannel.bufferedAmount <= lowWaterMark) {
|
|
792
|
+
resolve();
|
|
793
|
+
} else {
|
|
794
|
+
setTimeout(checkBuffer, 20);
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
checkBuffer();
|
|
799
|
+
});
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
// Send stream initialization message
|
|
803
|
+
this.sendMessage({
|
|
804
|
+
type: '__STREAM_INIT__',
|
|
805
|
+
streamId,
|
|
806
|
+
metadata
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
let chunkIndex = 0;
|
|
810
|
+
const self = this;
|
|
811
|
+
|
|
812
|
+
return new WritableStream({
|
|
813
|
+
async write(chunk) {
|
|
814
|
+
ensureChannelOpen();
|
|
815
|
+
|
|
816
|
+
const data = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
817
|
+
let offset = 0;
|
|
818
|
+
|
|
819
|
+
while (offset < data.byteLength) {
|
|
820
|
+
ensureChannelOpen();
|
|
821
|
+
|
|
822
|
+
const sliceEnd = Math.min(offset + chunkSize, data.byteLength);
|
|
823
|
+
const slice = data.subarray(offset, sliceEnd);
|
|
824
|
+
const sliceBuffer = (slice.byteOffset === 0 && slice.byteLength === slice.buffer.byteLength)
|
|
825
|
+
? slice.buffer
|
|
826
|
+
: slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength);
|
|
827
|
+
|
|
828
|
+
const chunkMessage = {
|
|
829
|
+
type: '__STREAM_CHUNK__',
|
|
830
|
+
streamId,
|
|
831
|
+
chunkIndex: chunkIndex++,
|
|
832
|
+
size: slice.byteLength,
|
|
833
|
+
encoding: 'binary'
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
try {
|
|
837
|
+
self.dataChannel.send(JSON.stringify(chunkMessage));
|
|
838
|
+
self.dataChannel.send(sliceBuffer);
|
|
839
|
+
} catch (error) {
|
|
840
|
+
throw error;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
offset = sliceEnd;
|
|
844
|
+
|
|
845
|
+
if (self.dataChannel && self.dataChannel.bufferedAmount > highWaterMark) {
|
|
846
|
+
await waitForBufferDrain();
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
},
|
|
850
|
+
|
|
851
|
+
async close() {
|
|
852
|
+
if (self.dataChannel && self.dataChannel.readyState === 'open') {
|
|
853
|
+
await waitForBufferDrain();
|
|
854
|
+
self.sendMessage({
|
|
855
|
+
type: '__STREAM_END__',
|
|
856
|
+
streamId,
|
|
857
|
+
totalChunks: chunkIndex
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
self._activeStreams.delete(streamId);
|
|
862
|
+
self.debug.log(`📤 Closed writable stream ${streamId}`);
|
|
863
|
+
},
|
|
864
|
+
|
|
865
|
+
async abort(reason) {
|
|
866
|
+
if (self.dataChannel && self.dataChannel.readyState === 'open') {
|
|
867
|
+
self.sendMessage({
|
|
868
|
+
type: '__STREAM_ABORT__',
|
|
869
|
+
streamId,
|
|
870
|
+
reason: reason?.message || 'Stream aborted'
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
self._activeStreams.delete(streamId);
|
|
875
|
+
self.debug.log(`❌ Aborted writable stream ${streamId}: ${reason}`);
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* Handle incoming stream messages and create ReadableStream
|
|
882
|
+
* @private
|
|
883
|
+
*/
|
|
884
|
+
_handleStreamMessage(message) {
|
|
885
|
+
const { type } = message;
|
|
886
|
+
|
|
887
|
+
switch (type) {
|
|
888
|
+
case '__STREAM_INIT__':
|
|
889
|
+
this._handleStreamInit(message);
|
|
890
|
+
break;
|
|
891
|
+
|
|
892
|
+
case '__STREAM_CHUNK__':
|
|
893
|
+
if (message.encoding === 'binary') {
|
|
894
|
+
this._pendingBinaryPayloads.push({
|
|
895
|
+
type: 'streamChunk',
|
|
896
|
+
header: message
|
|
897
|
+
});
|
|
898
|
+
} else {
|
|
899
|
+
this._handleStreamChunkLegacy(message);
|
|
900
|
+
}
|
|
901
|
+
break;
|
|
902
|
+
|
|
903
|
+
case '__STREAM_END__':
|
|
904
|
+
this._handleStreamEnd(message);
|
|
905
|
+
break;
|
|
906
|
+
|
|
907
|
+
case '__STREAM_ABORT__':
|
|
908
|
+
this._handleStreamAbort(message);
|
|
909
|
+
break;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
_handleStreamInit(message) {
|
|
914
|
+
const { streamId, metadata } = message;
|
|
915
|
+
|
|
916
|
+
this.debug.log(`📥 Receiving stream ${streamId} from ${this.peerId.substring(0, 8)}...`);
|
|
917
|
+
|
|
918
|
+
// Store metadata
|
|
919
|
+
this._streamMetadata.set(streamId, metadata);
|
|
920
|
+
this._streamChunks.set(streamId, []);
|
|
921
|
+
|
|
922
|
+
// Create ReadableStream
|
|
923
|
+
const chunks = this._streamChunks.get(streamId);
|
|
924
|
+
let controller;
|
|
925
|
+
|
|
926
|
+
const readable = new ReadableStream({
|
|
927
|
+
start(ctrl) {
|
|
928
|
+
controller = ctrl;
|
|
929
|
+
},
|
|
930
|
+
cancel: (reason) => {
|
|
931
|
+
this.debug.log(`📥 Stream ${streamId} cancelled: ${reason}`);
|
|
932
|
+
}
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
this._activeStreams.set(streamId, {
|
|
936
|
+
type: 'readable',
|
|
937
|
+
stream: readable,
|
|
938
|
+
controller,
|
|
939
|
+
metadata,
|
|
940
|
+
chunks
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
// Emit stream event
|
|
944
|
+
this.emit('streamReceived', {
|
|
945
|
+
peerId: this.peerId,
|
|
946
|
+
streamId,
|
|
947
|
+
stream: readable,
|
|
948
|
+
metadata
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
_handleStreamChunkLegacy(message) {
|
|
953
|
+
const { streamId, chunkIndex, data } = message;
|
|
954
|
+
const streamData = this._activeStreams.get(streamId);
|
|
955
|
+
|
|
956
|
+
if (!streamData) {
|
|
957
|
+
this.debug.warn(`Received chunk for unknown stream ${streamId}`);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// Convert array back to Uint8Array
|
|
962
|
+
const chunk = new Uint8Array(data);
|
|
963
|
+
|
|
964
|
+
// Enqueue chunk to readable stream
|
|
965
|
+
if (streamData.controller) {
|
|
966
|
+
streamData.controller.enqueue(chunk);
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
if (Array.isArray(streamData.chunks)) {
|
|
970
|
+
streamData.chunks.push(chunk);
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
this.debug.log(`📥 Received chunk ${chunkIndex} for stream ${streamId} (${chunk.length} bytes)`);
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
_handleStreamChunkBinary(header, chunk) {
|
|
977
|
+
const { streamId, chunkIndex, size } = header;
|
|
978
|
+
const streamData = this._activeStreams.get(streamId);
|
|
979
|
+
|
|
980
|
+
if (!streamData) {
|
|
981
|
+
this.debug.warn(`Received binary chunk for unknown stream ${streamId}`);
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
if (size && size !== chunk.byteLength) {
|
|
986
|
+
this.debug.warn(`Stream ${streamId} chunk ${chunkIndex} size mismatch: expected ${size}, got ${chunk.byteLength}`);
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
if (streamData.controller) {
|
|
990
|
+
streamData.controller.enqueue(chunk);
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
if (Array.isArray(streamData.chunks)) {
|
|
994
|
+
streamData.chunks.push(chunk);
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
this.debug.log(`📥 Received chunk ${chunkIndex} for stream ${streamId} (${chunk.byteLength} bytes)`);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
_handleStreamEnd(message) {
|
|
1001
|
+
const { streamId, totalChunks } = message;
|
|
1002
|
+
const streamData = this._activeStreams.get(streamId);
|
|
1003
|
+
|
|
1004
|
+
if (!streamData) {
|
|
1005
|
+
this.debug.warn(`Received end for unknown stream ${streamId}`);
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// Close the readable stream
|
|
1010
|
+
if (streamData.controller) {
|
|
1011
|
+
streamData.controller.close();
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
this.debug.log(`📥 Stream ${streamId} completed (${totalChunks} chunks)`);
|
|
1015
|
+
|
|
1016
|
+
// Cleanup
|
|
1017
|
+
this._activeStreams.delete(streamId);
|
|
1018
|
+
this._streamChunks.delete(streamId);
|
|
1019
|
+
this._streamMetadata.delete(streamId);
|
|
1020
|
+
|
|
1021
|
+
this.emit('streamCompleted', {
|
|
1022
|
+
peerId: this.peerId,
|
|
1023
|
+
streamId,
|
|
1024
|
+
totalChunks
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
_handleStreamAbort(message) {
|
|
1029
|
+
const { streamId, reason } = message;
|
|
1030
|
+
const streamData = this._activeStreams.get(streamId);
|
|
1031
|
+
|
|
1032
|
+
if (streamData && streamData.controller) {
|
|
1033
|
+
streamData.controller.error(new Error(reason));
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
this.debug.log(`❌ Stream ${streamId} aborted: ${reason}`);
|
|
1037
|
+
|
|
1038
|
+
// Cleanup
|
|
1039
|
+
this._activeStreams.delete(streamId);
|
|
1040
|
+
this._streamChunks.delete(streamId);
|
|
1041
|
+
this._streamMetadata.delete(streamId);
|
|
1042
|
+
|
|
1043
|
+
this.emit('streamAborted', {
|
|
1044
|
+
peerId: this.peerId,
|
|
1045
|
+
streamId,
|
|
1046
|
+
reason
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
_generateStreamId() {
|
|
1051
|
+
return `stream-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
649
1054
|
/**
|
|
650
1055
|
* CRITICAL FIX: Manually check for new remote tracks after renegotiation
|
|
651
1056
|
* This is needed because replaceTrack() doesn't trigger ontrack events
|
package/src/PeerPigeonMesh.js
CHANGED
|
@@ -444,7 +444,7 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
444
444
|
this.connected = false;
|
|
445
445
|
this.polling = false;
|
|
446
446
|
this.peerDiscovery.stop();
|
|
447
|
-
|
|
447
|
+
// Don't disconnect peers - WebRTC connections are peer-to-peer and persist without signaling server
|
|
448
448
|
this.emit('statusChanged', { type: 'disconnected' });
|
|
449
449
|
});
|
|
450
450
|
|
|
@@ -815,6 +815,125 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
815
815
|
return await this.gossipManager.broadcastMessage(content, 'chat');
|
|
816
816
|
}
|
|
817
817
|
|
|
818
|
+
/**
|
|
819
|
+
* Send binary data to a specific peer
|
|
820
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
821
|
+
* @param {Uint8Array|ArrayBuffer} binaryData - The binary data to send
|
|
822
|
+
* @returns {boolean} True if sent successfully
|
|
823
|
+
*/
|
|
824
|
+
async sendBinaryData(targetPeerId, binaryData) {
|
|
825
|
+
if (!targetPeerId || typeof targetPeerId !== 'string') {
|
|
826
|
+
this.debug.error('Invalid targetPeerId for binary message');
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
const peerConnection = this.connectionManager.peers.get(targetPeerId);
|
|
831
|
+
if (!peerConnection) {
|
|
832
|
+
this.debug.error(`No connection to peer ${targetPeerId.substring(0, 8)}...`);
|
|
833
|
+
return false;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
return peerConnection.sendMessage(binaryData);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Broadcast binary data to all connected peers
|
|
841
|
+
* @param {Uint8Array|ArrayBuffer} binaryData - The binary data to broadcast
|
|
842
|
+
* @returns {number} Number of peers the data was sent to
|
|
843
|
+
*/
|
|
844
|
+
async broadcastBinaryData(binaryData) {
|
|
845
|
+
const peers = this.getConnectedPeers();
|
|
846
|
+
let sentCount = 0;
|
|
847
|
+
|
|
848
|
+
for (const peer of peers) {
|
|
849
|
+
if (await this.sendBinaryData(peer.peerId, binaryData)) {
|
|
850
|
+
sentCount++;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
this.debug.log(`📦 Binary data broadcasted to ${sentCount}/${peers.length} peers`);
|
|
855
|
+
return sentCount;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* Create a writable stream to send data to a specific peer
|
|
860
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
861
|
+
* @param {object} options - Stream options (filename, mimeType, totalSize, etc.)
|
|
862
|
+
* @returns {WritableStream} A writable stream
|
|
863
|
+
*/
|
|
864
|
+
createStreamToPeer(targetPeerId, options = {}) {
|
|
865
|
+
if (!targetPeerId || typeof targetPeerId !== 'string') {
|
|
866
|
+
throw new Error('Invalid targetPeerId for stream');
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
const peerConnection = this.connectionManager.peers.get(targetPeerId);
|
|
870
|
+
if (!peerConnection) {
|
|
871
|
+
throw new Error(`No connection to peer ${targetPeerId.substring(0, 8)}...`);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
return peerConnection.createWritableStream(options);
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* Send a ReadableStream to a peer
|
|
879
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
880
|
+
* @param {ReadableStream} readableStream - The stream to send
|
|
881
|
+
* @param {object} options - Stream options (filename, mimeType, etc.)
|
|
882
|
+
* @returns {Promise<void>}
|
|
883
|
+
*/
|
|
884
|
+
async sendStream(targetPeerId, readableStream, options = {}) {
|
|
885
|
+
const writableStream = this.createStreamToPeer(targetPeerId, options);
|
|
886
|
+
|
|
887
|
+
try {
|
|
888
|
+
await readableStream.pipeTo(writableStream);
|
|
889
|
+
this.debug.log(`✅ Stream sent successfully to ${targetPeerId.substring(0, 8)}...`);
|
|
890
|
+
} catch (error) {
|
|
891
|
+
this.debug.error(`❌ Failed to send stream to ${targetPeerId.substring(0, 8)}...:`, error);
|
|
892
|
+
throw error;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Send a File to a peer using streams
|
|
898
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
899
|
+
* @param {File} file - The file to send
|
|
900
|
+
* @returns {Promise<void>}
|
|
901
|
+
*/
|
|
902
|
+
async sendFile(targetPeerId, file) {
|
|
903
|
+
this.debug.log(`📁 Sending file "${file.name}" (${file.size} bytes) to ${targetPeerId.substring(0, 8)}...`);
|
|
904
|
+
|
|
905
|
+
const options = {
|
|
906
|
+
filename: file.name,
|
|
907
|
+
mimeType: file.type,
|
|
908
|
+
totalSize: file.size,
|
|
909
|
+
type: 'file'
|
|
910
|
+
};
|
|
911
|
+
|
|
912
|
+
const stream = file.stream();
|
|
913
|
+
await this.sendStream(targetPeerId, stream, options);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Send a Blob to a peer using streams
|
|
918
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
919
|
+
* @param {Blob} blob - The blob to send
|
|
920
|
+
* @param {object} options - Additional options
|
|
921
|
+
* @returns {Promise<void>}
|
|
922
|
+
*/
|
|
923
|
+
async sendBlob(targetPeerId, blob, options = {}) {
|
|
924
|
+
this.debug.log(`📦 Sending blob (${blob.size} bytes) to ${targetPeerId.substring(0, 8)}...`);
|
|
925
|
+
|
|
926
|
+
const streamOptions = {
|
|
927
|
+
...options,
|
|
928
|
+
mimeType: blob.type,
|
|
929
|
+
totalSize: blob.size,
|
|
930
|
+
type: 'blob'
|
|
931
|
+
};
|
|
932
|
+
|
|
933
|
+
const stream = blob.stream();
|
|
934
|
+
await this.sendStream(targetPeerId, stream, streamOptions);
|
|
935
|
+
}
|
|
936
|
+
|
|
818
937
|
// Helper methods for backward compatibility
|
|
819
938
|
canAcceptMorePeers() {
|
|
820
939
|
return this.connectionManager.canAcceptMorePeers();
|
package/src/SignalingClient.js
CHANGED
|
@@ -19,6 +19,7 @@ export class SignalingClient extends EventEmitter {
|
|
|
19
19
|
this.connectionPromise = null;
|
|
20
20
|
this.reconnectTimeout = null;
|
|
21
21
|
this.isReconnecting = false;
|
|
22
|
+
this.deliberateDisconnect = false; // Track if disconnect was intentional
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
setConnectionType(type) {
|
|
@@ -200,15 +201,18 @@ export class SignalingClient extends EventEmitter {
|
|
|
200
201
|
|
|
201
202
|
this.debug.log('WebSocket closed:', event.code, event.reason);
|
|
202
203
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
204
|
+
// Always emit disconnected event
|
|
205
|
+
this.emit('disconnected');
|
|
206
|
+
|
|
207
|
+
// Attempt reconnection unless this was a deliberate disconnect
|
|
208
|
+
if (!this.deliberateDisconnect) {
|
|
208
209
|
this.emit('statusChanged', { type: 'warning', message: 'WebSocket connection lost - reconnecting...' });
|
|
209
210
|
if (!this.isReconnecting) {
|
|
210
211
|
this.attemptReconnect();
|
|
211
212
|
}
|
|
213
|
+
} else {
|
|
214
|
+
// Reset the flag for future connections
|
|
215
|
+
this.deliberateDisconnect = false;
|
|
212
216
|
}
|
|
213
217
|
};
|
|
214
218
|
|
|
@@ -295,6 +299,9 @@ export class SignalingClient extends EventEmitter {
|
|
|
295
299
|
}
|
|
296
300
|
|
|
297
301
|
disconnect() {
|
|
302
|
+
// Mark as deliberate disconnect to prevent automatic reconnection
|
|
303
|
+
this.deliberateDisconnect = true;
|
|
304
|
+
|
|
298
305
|
// Clear reconnection state
|
|
299
306
|
this.isReconnecting = false;
|
|
300
307
|
if (this.reconnectTimeout) {
|