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.
Files changed (35) hide show
  1. package/README.md +60 -1
  2. package/dist/peerpigeon-browser.js +439 -6
  3. package/dist/peerpigeon-browser.js.map +3 -3
  4. package/docs/BINARY_IMPLEMENTATION_SUMMARY.md +304 -0
  5. package/docs/BINARY_MESSAGES.md +332 -0
  6. package/docs/STREAMING_API.md +542 -0
  7. package/docs/STREAMING_IMPLEMENTATION_SUMMARY.md +286 -0
  8. package/examples/binary-message-demo.html +496 -0
  9. package/examples/browser-2/EXPRESS_SOLUTION.md +183 -0
  10. package/examples/browser-2/ICE_DEBUG.md +171 -0
  11. package/examples/browser-2/IMPLEMENTATION.md +218 -0
  12. package/examples/browser-2/QUICK_START.md +149 -0
  13. package/examples/browser-2/README.md +303 -0
  14. package/examples/browser-2/dist/assets/index-Cck_6WJV.css +1 -0
  15. package/examples/browser-2/dist/assets/index-D8-cNlWQ.js +57 -0
  16. package/examples/browser-2/dist/index.html +32 -0
  17. package/examples/browser-2/dist/peerpigeon-browser.js +12483 -0
  18. package/examples/browser-2/index.html +2 -1
  19. package/examples/browser-2/package-lock.json +1276 -0
  20. package/examples/browser-2/package.json +5 -3
  21. package/examples/browser-2/public/peerpigeon-browser.js +12483 -0
  22. package/examples/browser-2/src/App.vue +7 -4
  23. package/examples/browser-2/src/components/CryptoView.vue +4 -4
  24. package/examples/browser-2/src/components/TestingView.vue +794 -0
  25. package/examples/browser-2/src/main.js +7 -1
  26. package/examples/browser-2/src/router.js +63 -0
  27. package/examples/browser-2/src/stores/peerpigeon.js +68 -7
  28. package/examples/browser-2/vite.config.js +15 -1
  29. package/examples/stream-file-transfer-demo.html +935 -0
  30. package/package.json +2 -2
  31. package/src/ConnectionManager.js +30 -0
  32. package/src/PeerConnection.js +409 -4
  33. package/src/PeerPigeonMesh.js +120 -1
  34. package/src/SignalingClient.js +12 -5
  35. package/src/browser-entry.js +5 -1
@@ -0,0 +1,542 @@
1
+ # Streaming API Documentation
2
+
3
+ PeerPigeon now supports efficient data streaming using the standard Web Streams API (ReadableStream/WritableStream). This enables large file transfers, progressive data transmission, and proper backpressure handling.
4
+
5
+ ## Overview
6
+
7
+ The streaming API allows you to:
8
+ - Transfer large files efficiently
9
+ - Stream data progressively without loading entire files in memory
10
+ - Handle backpressure automatically
11
+ - Cancel or abort streams mid-transfer
12
+ - Track transfer progress
13
+
14
+ ## Why Streams?
15
+
16
+ **Traditional Binary Messages** (sendBinaryData):
17
+ - Good for small data (<16MB)
18
+ - Loads entire data into memory
19
+ - No built-in progress tracking
20
+ - No backpressure handling
21
+
22
+ **Streams** (sendFile, sendStream):
23
+ - Perfect for large files (GBs+)
24
+ - Memory-efficient (chunks processed incrementally)
25
+ - Built-in backpressure and flow control
26
+ - Progress tracking and cancellation
27
+ - Standards-compliant (Web Streams API)
28
+
29
+ ## Quick Start
30
+
31
+ ### Send a File
32
+
33
+ ```javascript
34
+ // Simple file transfer
35
+ const fileInput = document.getElementById('file-input');
36
+ const file = fileInput.files[0];
37
+
38
+ await mesh.sendFile(targetPeerId, file);
39
+ ```
40
+
41
+ ### Receive a File
42
+
43
+ ```javascript
44
+ mesh.addEventListener('streamReceived', async (event) => {
45
+ const { stream, metadata } = event;
46
+
47
+ // Read stream chunks
48
+ const chunks = [];
49
+ const reader = stream.getReader();
50
+
51
+ while (true) {
52
+ const { done, value } = await reader.read();
53
+ if (done) break;
54
+ chunks.push(value);
55
+ }
56
+
57
+ // Create downloadable blob
58
+ const blob = new Blob(chunks, { type: metadata.mimeType });
59
+ const url = URL.createObjectURL(blob);
60
+
61
+ // Trigger download
62
+ const a = document.createElement('a');
63
+ a.href = url;
64
+ a.download = metadata.filename;
65
+ a.click();
66
+ });
67
+ ```
68
+
69
+ ## API Reference
70
+
71
+ ### High-Level Methods
72
+
73
+ #### `sendFile(targetPeerId, file)`
74
+
75
+ Send a File object to a peer.
76
+
77
+ ```javascript
78
+ const file = fileInput.files[0];
79
+ await mesh.sendFile(targetPeerId, file);
80
+ ```
81
+
82
+ **Parameters:**
83
+ - `targetPeerId` (string): Destination peer ID
84
+ - `file` (File): File object to send
85
+
86
+ **Returns:** Promise<void>
87
+
88
+ ---
89
+
90
+ #### `sendBlob(targetPeerId, blob, options)`
91
+
92
+ Send a Blob to a peer.
93
+
94
+ ```javascript
95
+ const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
96
+ await mesh.sendBlob(targetPeerId, blob, {
97
+ filename: 'message.txt'
98
+ });
99
+ ```
100
+
101
+ **Parameters:**
102
+ - `targetPeerId` (string): Destination peer ID
103
+ - `blob` (Blob): Blob to send
104
+ - `options` (object): Optional metadata
105
+ - `filename` (string): Filename
106
+ - `mimeType` (string): MIME type (defaults to blob.type)
107
+
108
+ **Returns:** Promise<void>
109
+
110
+ ---
111
+
112
+ #### `sendStream(targetPeerId, readableStream, options)`
113
+
114
+ Send any ReadableStream to a peer.
115
+
116
+ ```javascript
117
+ const response = await fetch('/large-file.bin');
118
+ await mesh.sendStream(targetPeerId, response.body, {
119
+ filename: 'large-file.bin',
120
+ totalSize: response.headers.get('content-length')
121
+ });
122
+ ```
123
+
124
+ **Parameters:**
125
+ - `targetPeerId` (string): Destination peer ID
126
+ - `readableStream` (ReadableStream): Stream to send
127
+ - `options` (object): Stream metadata
128
+ - `filename` (string): Filename
129
+ - `mimeType` (string): MIME type
130
+ - `totalSize` (number): Total size in bytes
131
+ - `type` (string): Stream type ('file', 'blob', 'binary')
132
+
133
+ **Returns:** Promise<void>
134
+
135
+ ---
136
+
137
+ ### Low-Level Methods
138
+
139
+ #### `createStreamToPeer(targetPeerId, options)`
140
+
141
+ Create a WritableStream to a peer for manual control.
142
+
143
+ ```javascript
144
+ const writable = mesh.createStreamToPeer(targetPeerId, {
145
+ filename: 'data.bin',
146
+ totalSize: 1024000,
147
+ chunkSize: 16384 // 16KB chunks
148
+ });
149
+
150
+ const writer = writable.getWriter();
151
+
152
+ // Write chunks
153
+ await writer.write(chunk1);
154
+ await writer.write(chunk2);
155
+
156
+ // Close stream
157
+ await writer.close();
158
+ ```
159
+
160
+ **Parameters:**
161
+ - `targetPeerId` (string): Destination peer ID
162
+ - `options` (object): Stream options
163
+ - `streamId` (string): Optional stream ID (auto-generated if not provided)
164
+ - `filename` (string): Filename
165
+ - `mimeType` (string): MIME type
166
+ - `totalSize` (number): Total size in bytes
167
+ - `chunkSize` (number): Chunk size (default: 16384 bytes)
168
+ - `type` (string): Stream type
169
+
170
+ **Returns:** WritableStream
171
+
172
+ ---
173
+
174
+ ## Events
175
+
176
+ ### `streamReceived`
177
+
178
+ Fired when a stream starts being received from a peer.
179
+
180
+ ```javascript
181
+ mesh.addEventListener('streamReceived', (event) => {
182
+ const { peerId, streamId, stream, metadata } = event;
183
+
184
+ console.log(`Receiving ${metadata.filename} from ${peerId}`);
185
+ console.log(`Size: ${metadata.totalSize} bytes`);
186
+ console.log(`Type: ${metadata.mimeType}`);
187
+
188
+ // Process the stream...
189
+ });
190
+ ```
191
+
192
+ **Event Data:**
193
+ - `peerId` (string): Sender's peer ID
194
+ - `streamId` (string): Unique stream identifier
195
+ - `stream` (ReadableStream): The incoming stream
196
+ - `metadata` (object): Stream metadata
197
+ - `filename` (string)
198
+ - `mimeType` (string)
199
+ - `totalSize` (number)
200
+ - `type` (string)
201
+ - `timestamp` (number)
202
+
203
+ ---
204
+
205
+ ### `streamCompleted`
206
+
207
+ Fired when a stream transfer completes successfully.
208
+
209
+ ```javascript
210
+ mesh.addEventListener('streamCompleted', (event) => {
211
+ const { peerId, streamId, totalChunks } = event;
212
+ console.log(`Stream ${streamId} completed (${totalChunks} chunks)`);
213
+ });
214
+ ```
215
+
216
+ **Event Data:**
217
+ - `peerId` (string): Peer ID
218
+ - `streamId` (string): Stream identifier
219
+ - `totalChunks` (number): Number of chunks transferred
220
+
221
+ ---
222
+
223
+ ### `streamAborted`
224
+
225
+ Fired when a stream is aborted or fails.
226
+
227
+ ```javascript
228
+ mesh.addEventListener('streamAborted', (event) => {
229
+ const { peerId, streamId, reason } = event;
230
+ console.error(`Stream ${streamId} aborted: ${reason}`);
231
+ });
232
+ ```
233
+
234
+ **Event Data:**
235
+ - `peerId` (string): Peer ID
236
+ - `streamId` (string): Stream identifier
237
+ - `reason` (string): Abort reason
238
+
239
+ ---
240
+
241
+ ## Examples
242
+
243
+ ### Example 1: File Transfer with Progress
244
+
245
+ ```javascript
246
+ async function sendFileWithProgress(peerId, file) {
247
+ const totalSize = file.size;
248
+ let transferred = 0;
249
+
250
+ // Create custom stream with progress tracking
251
+ const fileStream = file.stream();
252
+ const progressStream = new TransformStream({
253
+ transform(chunk, controller) {
254
+ transferred += chunk.length;
255
+ const progress = (transferred / totalSize) * 100;
256
+ updateProgressBar(progress);
257
+ controller.enqueue(chunk);
258
+ }
259
+ });
260
+
261
+ await mesh.sendStream(
262
+ peerId,
263
+ fileStream.pipeThrough(progressStream),
264
+ {
265
+ filename: file.name,
266
+ totalSize: file.size,
267
+ mimeType: file.type
268
+ }
269
+ );
270
+ }
271
+ ```
272
+
273
+ ### Example 2: Receiving and Saving Files
274
+
275
+ ```javascript
276
+ mesh.addEventListener('streamReceived', async (event) => {
277
+ const { stream, metadata } = event;
278
+
279
+ // Create blob from stream
280
+ const chunks = [];
281
+ const reader = stream.getReader();
282
+
283
+ try {
284
+ while (true) {
285
+ const { done, value } = await reader.read();
286
+ if (done) break;
287
+ chunks.push(value);
288
+ }
289
+
290
+ const blob = new Blob(chunks, { type: metadata.mimeType });
291
+
292
+ // Auto-download
293
+ const url = URL.createObjectURL(blob);
294
+ const a = document.createElement('a');
295
+ a.href = url;
296
+ a.download = metadata.filename || 'download';
297
+ document.body.appendChild(a);
298
+ a.click();
299
+ document.body.removeChild(a);
300
+ URL.revokeObjectURL(url);
301
+
302
+ console.log(`Saved ${metadata.filename}`);
303
+ } catch (error) {
304
+ console.error('Failed to receive file:', error);
305
+ }
306
+ });
307
+ ```
308
+
309
+ ### Example 3: Streaming from URL
310
+
311
+ ```javascript
312
+ async function streamFromURL(peerId, url) {
313
+ const response = await fetch(url);
314
+ const filename = url.split('/').pop();
315
+ const totalSize = response.headers.get('content-length');
316
+
317
+ await mesh.sendStream(peerId, response.body, {
318
+ filename,
319
+ totalSize: parseInt(totalSize),
320
+ mimeType: response.headers.get('content-type')
321
+ });
322
+ }
323
+
324
+ // Usage
325
+ await streamFromURL(peerId, 'https://example.com/video.mp4');
326
+ ```
327
+
328
+ ### Example 4: Transform Stream (Compression)
329
+
330
+ ```javascript
331
+ async function sendCompressedFile(peerId, file) {
332
+ const compressionStream = new CompressionStream('gzip');
333
+
334
+ await mesh.sendStream(
335
+ peerId,
336
+ file.stream().pipeThrough(compressionStream),
337
+ {
338
+ filename: file.name + '.gz',
339
+ mimeType: 'application/gzip',
340
+ type: 'compressed'
341
+ }
342
+ );
343
+ }
344
+
345
+ // Receiving side
346
+ mesh.addEventListener('streamReceived', async (event) => {
347
+ const { stream, metadata } = event;
348
+
349
+ if (metadata.type === 'compressed') {
350
+ const decompressionStream = new DecompressionStream('gzip');
351
+ const decompressedStream = stream.pipeThrough(decompressionStream);
352
+
353
+ // Process decompressed stream...
354
+ }
355
+ });
356
+ ```
357
+
358
+ ### Example 5: Multiple File Transfer
359
+
360
+ ```javascript
361
+ async function sendMultipleFiles(peerId, files) {
362
+ for (const file of files) {
363
+ console.log(`Sending ${file.name}...`);
364
+ await mesh.sendFile(peerId, file);
365
+ console.log(`Sent ${file.name}`);
366
+ }
367
+ }
368
+
369
+ // Usage
370
+ const fileInput = document.getElementById('file-input');
371
+ await sendMultipleFiles(peerId, fileInput.files);
372
+ ```
373
+
374
+ ### Example 6: Cancel Stream Transfer
375
+
376
+ ```javascript
377
+ async function sendWithCancellation(peerId, file) {
378
+ const abortController = new AbortController();
379
+
380
+ // Show cancel button
381
+ showCancelButton(() => abortController.abort());
382
+
383
+ try {
384
+ const writable = mesh.createStreamToPeer(peerId, {
385
+ filename: file.name,
386
+ totalSize: file.size
387
+ });
388
+
389
+ // Pipe with abort signal
390
+ await file.stream().pipeTo(writable, {
391
+ signal: abortController.signal
392
+ });
393
+
394
+ console.log('Transfer completed');
395
+ } catch (error) {
396
+ if (error.name === 'AbortError') {
397
+ console.log('Transfer cancelled by user');
398
+ } else {
399
+ console.error('Transfer failed:', error);
400
+ }
401
+ }
402
+ }
403
+ ```
404
+
405
+ ### Example 7: Stream Video Playback
406
+
407
+ ```javascript
408
+ // Sender: Stream video file
409
+ await mesh.sendFile(peerId, videoFile);
410
+
411
+ // Receiver: Play as it streams
412
+ mesh.addEventListener('streamReceived', async (event) => {
413
+ const { stream, metadata } = event;
414
+
415
+ if (metadata.mimeType.startsWith('video/')) {
416
+ const mediaSource = new MediaSource();
417
+ const video = document.getElementById('video-player');
418
+ video.src = URL.createObjectURL(mediaSource);
419
+
420
+ mediaSource.addEventListener('sourceopen', async () => {
421
+ const sourceBuffer = mediaSource.addSourceBuffer(metadata.mimeType);
422
+ const reader = stream.getReader();
423
+
424
+ while (true) {
425
+ const { done, value } = await reader.read();
426
+ if (done) {
427
+ mediaSource.endOfStream();
428
+ break;
429
+ }
430
+
431
+ // Wait for buffer to be ready
432
+ await new Promise(resolve => {
433
+ if (sourceBuffer.updating) {
434
+ sourceBuffer.addEventListener('updateend', resolve, { once: true });
435
+ } else {
436
+ resolve();
437
+ }
438
+ });
439
+
440
+ sourceBuffer.appendBuffer(value);
441
+ }
442
+ });
443
+ }
444
+ });
445
+ ```
446
+
447
+ ## Performance Considerations
448
+
449
+ ### Chunk Size
450
+
451
+ Default chunk size is 16KB (16384 bytes). Adjust based on use case:
452
+
453
+ ```javascript
454
+ // Small chunks for low latency
455
+ const writable = mesh.createStreamToPeer(peerId, {
456
+ chunkSize: 8192 // 8KB
457
+ });
458
+
459
+ // Large chunks for throughput
460
+ const writable = mesh.createStreamToPeer(peerId, {
461
+ chunkSize: 65536 // 64KB
462
+ });
463
+ ```
464
+
465
+ **Guidelines:**
466
+ - **Small files (<1MB)**: 8-16KB chunks
467
+ - **Medium files (1-100MB)**: 16-32KB chunks
468
+ - **Large files (>100MB)**: 32-64KB chunks
469
+ - **Real-time data**: 4-8KB chunks
470
+
471
+ ### Backpressure
472
+
473
+ The Streams API automatically handles backpressure. If the receiver is slow:
474
+
475
+ 1. Writer blocks on `.write()` calls
476
+ 2. Buffer fills up
477
+ 3. Transfer pauses until buffer drains
478
+ 4. Transfer resumes automatically
479
+
480
+ No manual throttling needed!
481
+
482
+ ### Memory Usage
483
+
484
+ Streams are memory-efficient:
485
+
486
+ - Only active chunks in memory
487
+ - Garbage collected after processing
488
+ - Total memory ≈ chunk size × buffered chunks
489
+ - Typically <1MB even for GB files
490
+
491
+ ## Error Handling
492
+
493
+ ```javascript
494
+ try {
495
+ await mesh.sendFile(peerId, file);
496
+ console.log('✅ File sent successfully');
497
+ } catch (error) {
498
+ if (error.message.includes('Data channel not open')) {
499
+ console.error('❌ Peer disconnected');
500
+ } else if (error.name === 'AbortError') {
501
+ console.error('❌ Transfer cancelled');
502
+ } else {
503
+ console.error('❌ Transfer failed:', error);
504
+ }
505
+ }
506
+ ```
507
+
508
+ ## Browser Compatibility
509
+
510
+ Requires support for:
511
+ - Web Streams API (ReadableStream/WritableStream)
512
+ - WebRTC RTCDataChannel
513
+ - Typed Arrays (Uint8Array)
514
+
515
+ **Supported:** Chrome 89+, Firefox 102+, Safari 14.1+, Edge 89+
516
+
517
+ ## Comparison with Binary Messages
518
+
519
+ | Feature | Binary Messages | Streams |
520
+ |---------|----------------|---------|
521
+ | Max Size | ~16MB (practical) | Unlimited |
522
+ | Memory Usage | Full file in RAM | Chunks only |
523
+ | Progress Tracking | Manual | Built-in |
524
+ | Backpressure | Manual | Automatic |
525
+ | Cancellation | Not supported | Built-in |
526
+ | Use Case | Small data | Large files |
527
+
528
+ ## Demo
529
+
530
+ Run the interactive demo:
531
+
532
+ ```bash
533
+ npm run dev
534
+ # Open http://localhost:8080/examples/stream-file-transfer-demo.html
535
+ # Open in multiple tabs to test file transfers
536
+ ```
537
+
538
+ ## Related Documentation
539
+
540
+ - [Binary Messages](./BINARY_MESSAGES.md)
541
+ - [API Documentation](./API_DOCUMENTATION.md)
542
+ - [Web Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API)