@johnhenry/browsermesh-sync 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/files.mjs ADDED
@@ -0,0 +1,640 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * Clawser Mesh Files
4
+ *
5
+ * Content-addressed file transfer with SHA-256 chunking, progress tracking,
6
+ * and resume support. Builds on the streams module for transport.
7
+ *
8
+ * @module clawser-mesh-files
9
+ */
10
+
11
+ import { MESH_TYPE, MESH_ERROR } from '@johnhenry/browsermesh-primitives';
12
+
13
+ // ── Constants ────────────────────────────────────────────────────────
14
+
15
+ export const TRANSFER_STATES = Object.freeze([
16
+ 'offered', 'accepted', 'transferring', 'completed', 'failed', 'cancelled',
17
+ ]);
18
+
19
+ export const TRANSFER_DEFAULTS = Object.freeze({
20
+ chunkSize: 256 * 1024,
21
+ maxConcurrentChunks: 16,
22
+ offerExpiry: 5 * 60 * 1000,
23
+ resumeTimeout: 30 * 60 * 1000,
24
+ });
25
+
26
+ // ── Helpers ──────────────────────────────────────────────────────────
27
+
28
+ let _transferIdCounter = 0;
29
+
30
+ function generateTransferId() {
31
+ return `xfer_${Date.now().toString(36)}_${(++_transferIdCounter).toString(36)}`;
32
+ }
33
+
34
+ // ── FileDescriptor ───────────────────────────────────────────────────
35
+
36
+ /**
37
+ * Describes a file to be transferred.
38
+ */
39
+ export class FileDescriptor {
40
+ constructor({ name, size, mimeType, cid }) {
41
+ if (!name || typeof name !== 'string') throw new Error('FileDescriptor requires a name');
42
+ if (typeof size !== 'number' || size < 0) throw new Error('FileDescriptor requires a non-negative size');
43
+ this.name = name;
44
+ this.size = size;
45
+ this.mimeType = mimeType || null;
46
+ this.cid = cid || null;
47
+ }
48
+
49
+ toJSON() {
50
+ return { name: this.name, size: this.size, mimeType: this.mimeType, cid: this.cid };
51
+ }
52
+
53
+ static fromJSON(json) {
54
+ return new FileDescriptor(json);
55
+ }
56
+ }
57
+
58
+ // ── TransferOffer ────────────────────────────────────────────────────
59
+
60
+ /**
61
+ * A transfer offer from sender to recipient.
62
+ */
63
+ export class TransferOffer {
64
+ constructor({ transferId, sender, recipient, files, totalSize, expires }) {
65
+ this.transferId = transferId || generateTransferId();
66
+ this.sender = sender;
67
+ this.recipient = recipient;
68
+ this.files = (files || []).map(f => f instanceof FileDescriptor ? f : new FileDescriptor(f));
69
+ this.totalSize = totalSize ?? this.files.reduce((sum, f) => sum + f.size, 0);
70
+ this.expires = expires ?? (Date.now() + TRANSFER_DEFAULTS.offerExpiry);
71
+ }
72
+
73
+ isExpired(now) {
74
+ return (now ?? Date.now()) >= this.expires;
75
+ }
76
+
77
+ toJSON() {
78
+ return {
79
+ transferId: this.transferId,
80
+ sender: this.sender,
81
+ recipient: this.recipient,
82
+ files: this.files.map(f => f.toJSON()),
83
+ totalSize: this.totalSize,
84
+ expires: this.expires,
85
+ };
86
+ }
87
+
88
+ static fromJSON(json) {
89
+ return new TransferOffer({
90
+ ...json,
91
+ files: json.files.map(f => FileDescriptor.fromJSON(f)),
92
+ });
93
+ }
94
+ }
95
+
96
+ // ── ChunkStore ───────────────────────────────────────────────────────
97
+
98
+ /**
99
+ * In-memory content-addressed storage for file chunks.
100
+ * CIDs are SHA-256 hex strings.
101
+ */
102
+ export class ChunkStore {
103
+ #chunks = new Map();
104
+
105
+ /**
106
+ * Compute a content ID (SHA-256 hex) for data.
107
+ * @param {Uint8Array} data
108
+ * @returns {Promise<string>}
109
+ */
110
+ static async computeCid(data) {
111
+ let hash;
112
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
113
+ hash = await crypto.subtle.digest('SHA-256', data);
114
+ } else {
115
+ // Node.js fallback
116
+ const { createHash } = await import('node:crypto');
117
+ const h = createHash('sha256');
118
+ h.update(data);
119
+ hash = h.digest().buffer;
120
+ }
121
+ return Array.from(new Uint8Array(hash))
122
+ .map(b => b.toString(16).padStart(2, '0'))
123
+ .join('');
124
+ }
125
+
126
+ /**
127
+ * Store a chunk by its CID.
128
+ * @param {string} cid
129
+ * @param {Uint8Array} data
130
+ */
131
+ save(cid, data) {
132
+ this.#chunks.set(cid, data);
133
+ }
134
+
135
+ /**
136
+ * Retrieve a chunk by CID.
137
+ * @param {string} cid
138
+ * @returns {Uint8Array|undefined}
139
+ */
140
+ get(cid) {
141
+ return this.#chunks.get(cid);
142
+ }
143
+
144
+ /**
145
+ * Check if a chunk exists.
146
+ * @param {string} cid
147
+ * @returns {boolean}
148
+ */
149
+ has(cid) {
150
+ return this.#chunks.has(cid);
151
+ }
152
+
153
+ /**
154
+ * Verify that data matches the expected CID.
155
+ * @param {string} cid
156
+ * @param {Uint8Array} data
157
+ * @returns {Promise<boolean>}
158
+ */
159
+ async verify(cid, data) {
160
+ const computed = await ChunkStore.computeCid(data);
161
+ return computed === cid;
162
+ }
163
+
164
+ /**
165
+ * Remove a chunk by CID.
166
+ * @param {string} cid
167
+ * @returns {boolean}
168
+ */
169
+ remove(cid) {
170
+ return this.#chunks.delete(cid);
171
+ }
172
+
173
+ /** Number of stored chunks. */
174
+ get size() { return this.#chunks.size; }
175
+
176
+ /** Clear all chunks. */
177
+ clear() { this.#chunks.clear(); }
178
+ }
179
+
180
+ // ── TransferState ────────────────────────────────────────────────────
181
+
182
+ /**
183
+ * Progress tracker for a single file transfer.
184
+ */
185
+ export class TransferState {
186
+ #transferId;
187
+ #status;
188
+ #totalSize;
189
+ #bytesTransferred = 0;
190
+ #chunks = []; // { fileIndex, cid, size }
191
+ #startedAt = null;
192
+ #completedAt = null;
193
+ #fileChunks = new Map(); // fileIndex → Set<cid>
194
+ #fileSizes;
195
+
196
+ constructor({ transferId, totalSize, status, fileSizes }) {
197
+ this.#transferId = transferId;
198
+ this.#totalSize = totalSize;
199
+ this.#status = status || 'offered';
200
+ this.#fileSizes = fileSizes || [];
201
+ }
202
+
203
+ get transferId() { return this.#transferId; }
204
+ get status() { return this.#status; }
205
+ set status(s) {
206
+ if (!TRANSFER_STATES.includes(s)) throw new Error(`Invalid transfer status: ${s}`);
207
+ this.#status = s;
208
+ if (s === 'transferring' && !this.#startedAt) this.#startedAt = Date.now();
209
+ if (s === 'completed' || s === 'failed' || s === 'cancelled') this.#completedAt = Date.now();
210
+ }
211
+ get totalSize() { return this.#totalSize; }
212
+ get bytesTransferred() { return this.#bytesTransferred; }
213
+
214
+ get percentComplete() {
215
+ if (this.#totalSize === 0) return 100;
216
+ return Math.min(100, (this.#bytesTransferred / this.#totalSize) * 100);
217
+ }
218
+
219
+ get transferRate() {
220
+ if (!this.#startedAt) return 0;
221
+ const elapsed = ((this.#completedAt || Date.now()) - this.#startedAt) / 1000;
222
+ if (elapsed <= 0) return 0;
223
+ return this.#bytesTransferred / elapsed;
224
+ }
225
+
226
+ /**
227
+ * Record a received chunk.
228
+ * @param {number} fileIndex
229
+ * @param {string} cid
230
+ * @param {number} size
231
+ */
232
+ addChunk(fileIndex, cid, size) {
233
+ if (this.#status !== 'transferring') {
234
+ this.status = 'transferring';
235
+ }
236
+ if (!this.#fileChunks.has(fileIndex)) {
237
+ this.#fileChunks.set(fileIndex, new Set());
238
+ }
239
+ const fileSet = this.#fileChunks.get(fileIndex);
240
+ if (fileSet.has(cid)) return; // Deduplicate
241
+ fileSet.add(cid);
242
+ this.#bytesTransferred += size;
243
+ this.#chunks.push({ fileIndex, cid, size });
244
+ }
245
+
246
+ /**
247
+ * Check if the transfer is complete (all bytes received).
248
+ * @returns {boolean}
249
+ */
250
+ isComplete() {
251
+ return this.#bytesTransferred >= this.#totalSize;
252
+ }
253
+
254
+ /**
255
+ * Get chunk CIDs already received for a specific file.
256
+ * @param {number} fileIndex
257
+ * @returns {Set<string>}
258
+ */
259
+ getReceivedChunks(fileIndex) {
260
+ return this.#fileChunks.get(fileIndex) || new Set();
261
+ }
262
+
263
+ toJSON() {
264
+ const fileChunks = {};
265
+ for (const [idx, cids] of this.#fileChunks) {
266
+ fileChunks[idx] = [...cids];
267
+ }
268
+ return {
269
+ transferId: this.#transferId,
270
+ status: this.#status,
271
+ totalSize: this.#totalSize,
272
+ bytesTransferred: this.#bytesTransferred,
273
+ percentComplete: this.percentComplete,
274
+ transferRate: this.transferRate,
275
+ chunks: this.#chunks,
276
+ fileChunks,
277
+ startedAt: this.#startedAt,
278
+ completedAt: this.#completedAt,
279
+ };
280
+ }
281
+ }
282
+
283
+ // ── MeshFileTransfer ─────────────────────────────────────────────────
284
+
285
+ /**
286
+ * Top-level file transfer manager. Handles offers, acceptance, chunked
287
+ * sending/receiving, and progress tracking.
288
+ */
289
+ export class MeshFileTransfer {
290
+ /** @type {Map<string, TransferOffer>} transferId → offer */
291
+ #offers = new Map();
292
+
293
+ /** @type {Map<string, TransferState>} transferId → state */
294
+ #states = new Map();
295
+
296
+ /** @type {ChunkStore} */
297
+ #store;
298
+
299
+ #chunkSize;
300
+
301
+ // Callbacks
302
+ #onOffer = null;
303
+ #onProgress = null;
304
+ #onComplete = null;
305
+ #onSend = null;
306
+
307
+ constructor(opts = {}) {
308
+ this.#store = opts.store || new ChunkStore();
309
+ this.#chunkSize = opts.chunkSize ?? TRANSFER_DEFAULTS.chunkSize;
310
+ }
311
+
312
+ // ── Callbacks ────────────────────────────────────────────────────
313
+
314
+ onOffer(cb) { this.#onOffer = cb; return this; }
315
+ onProgress(cb) { this.#onProgress = cb; return this; }
316
+ onComplete(cb) { this.#onComplete = cb; return this; }
317
+ onSend(cb) { this.#onSend = cb; return this; }
318
+
319
+ /** Access the chunk store. */
320
+ get store() { return this.#store; }
321
+
322
+ // ── Create / Accept / Reject ─────────────────────────────────────
323
+
324
+ /**
325
+ * Create a transfer offer.
326
+ * @param {string} recipient - Recipient identity
327
+ * @param {Array<{name, size, mimeType?}>} files
328
+ * @param {object} [opts]
329
+ * @returns {TransferOffer}
330
+ */
331
+ createOffer(recipient, files, opts = {}) {
332
+ const offer = new TransferOffer({
333
+ sender: opts.sender || 'local',
334
+ recipient,
335
+ files,
336
+ expires: opts.expires,
337
+ });
338
+ this.#offers.set(offer.transferId, offer);
339
+ const fileSizes = offer.files.map(f => f.size);
340
+ const state = new TransferState({
341
+ transferId: offer.transferId,
342
+ totalSize: offer.totalSize,
343
+ status: 'offered',
344
+ fileSizes,
345
+ });
346
+ this.#states.set(offer.transferId, state);
347
+
348
+ this._emit({
349
+ t: MESH_TYPE.FILE_OFFER,
350
+ p: offer.toJSON(),
351
+ });
352
+
353
+ return offer;
354
+ }
355
+
356
+ /**
357
+ * Accept an incoming transfer offer.
358
+ * @param {TransferOffer|object} offer
359
+ * @returns {TransferState}
360
+ */
361
+ acceptOffer(offer) {
362
+ if (!(offer instanceof TransferOffer)) {
363
+ offer = TransferOffer.fromJSON(offer);
364
+ }
365
+ if (offer.isExpired()) {
366
+ throw new Error('Transfer offer has expired');
367
+ }
368
+ this.#offers.set(offer.transferId, offer);
369
+ const fileSizes = offer.files.map(f => f.size);
370
+ const state = new TransferState({
371
+ transferId: offer.transferId,
372
+ totalSize: offer.totalSize,
373
+ status: 'accepted',
374
+ fileSizes,
375
+ });
376
+ this.#states.set(offer.transferId, state);
377
+
378
+ this._emit({
379
+ t: MESH_TYPE.FILE_ACCEPT,
380
+ p: { transferId: offer.transferId },
381
+ });
382
+
383
+ return state;
384
+ }
385
+
386
+ /**
387
+ * Reject an incoming transfer offer.
388
+ * @param {string} transferId
389
+ * @param {string} [reason]
390
+ */
391
+ rejectOffer(transferId, reason) {
392
+ const offer = this.#offers.get(transferId);
393
+ if (offer) {
394
+ this.#offers.delete(transferId);
395
+ }
396
+ const state = this.#states.get(transferId);
397
+ if (state) {
398
+ state.status = 'cancelled';
399
+ }
400
+
401
+ this._emit({
402
+ t: MESH_TYPE.FILE_REJECT,
403
+ p: { transferId, reason: reason || 'Rejected by recipient' },
404
+ });
405
+ }
406
+
407
+ // ── Sending ──────────────────────────────────────────────────────
408
+
409
+ /**
410
+ * Generate chunks for sending. Yields chunk descriptors.
411
+ * @param {string} transferId
412
+ * @param {Array<Uint8Array>} fileData - File contents in order
413
+ * @returns {Generator<{cid: string, data: Uint8Array, fileIndex: number, offset: number}>}
414
+ */
415
+ async *sendChunks(transferId, fileData) {
416
+ const offer = this.#offers.get(transferId);
417
+ if (!offer) throw new Error(`Unknown transfer: ${transferId}`);
418
+ const state = this.#states.get(transferId);
419
+ if (!state) throw new Error(`No state for transfer: ${transferId}`);
420
+
421
+ state.status = 'transferring';
422
+
423
+ for (let fileIndex = 0; fileIndex < fileData.length; fileIndex++) {
424
+ const data = fileData[fileIndex];
425
+ for (let offset = 0; offset < data.length; offset += this.#chunkSize) {
426
+ const chunk = data.subarray(offset, Math.min(offset + this.#chunkSize, data.length));
427
+ const cid = await ChunkStore.computeCid(chunk);
428
+ this.#store.save(cid, chunk);
429
+ state.addChunk(fileIndex, cid, chunk.length);
430
+
431
+ this._emitProgress(transferId, state);
432
+
433
+ yield { cid, data: chunk, fileIndex, offset };
434
+ }
435
+ }
436
+
437
+ if (state.isComplete()) {
438
+ state.status = 'completed';
439
+ this._emit({
440
+ t: MESH_TYPE.FILE_COMPLETE,
441
+ p: { transferId },
442
+ });
443
+ if (this.#onComplete) this.#onComplete(transferId, state);
444
+ }
445
+ }
446
+
447
+ // ── Receiving ────────────────────────────────────────────────────
448
+
449
+ /**
450
+ * Receive and validate a chunk.
451
+ * @param {string} transferId
452
+ * @param {number} fileIndex
453
+ * @param {string} cid
454
+ * @param {Uint8Array} data
455
+ * @returns {Promise<boolean>}
456
+ */
457
+ async receiveChunk(transferId, fileIndex, cid, data) {
458
+ const state = this.#states.get(transferId);
459
+ if (!state) throw new Error(`Unknown transfer: ${transferId}`);
460
+
461
+ // Verify integrity
462
+ const valid = await this.#store.verify(cid, data);
463
+ if (!valid) {
464
+ return false;
465
+ }
466
+
467
+ this.#store.save(cid, data);
468
+ state.addChunk(fileIndex, cid, data.length);
469
+
470
+ this._emitProgress(transferId, state);
471
+
472
+ if (state.isComplete()) {
473
+ state.status = 'completed';
474
+ this._emit({
475
+ t: MESH_TYPE.FILE_COMPLETE,
476
+ p: { transferId },
477
+ });
478
+ if (this.#onComplete) this.#onComplete(transferId, state);
479
+ }
480
+
481
+ return true;
482
+ }
483
+
484
+ // ── Query ────────────────────────────────────────────────────────
485
+
486
+ /**
487
+ * Get a transfer state by ID.
488
+ * @param {string} transferId
489
+ * @returns {TransferState|undefined}
490
+ */
491
+ getTransfer(transferId) {
492
+ return this.#states.get(transferId);
493
+ }
494
+
495
+ /**
496
+ * Get a transfer offer by ID.
497
+ * @param {string} transferId
498
+ * @returns {TransferOffer|undefined}
499
+ */
500
+ getOffer(transferId) {
501
+ return this.#offers.get(transferId);
502
+ }
503
+
504
+ /**
505
+ * List transfers, optionally filtered.
506
+ * @param {object} [filter]
507
+ * @param {string} [filter.status]
508
+ * @param {string} [filter.peerId]
509
+ * @returns {Array<{offer: object, state: object}>}
510
+ */
511
+ listTransfers(filter) {
512
+ const results = [];
513
+ for (const [id, state] of this.#states) {
514
+ if (filter?.status && state.status !== filter.status) continue;
515
+ const offer = this.#offers.get(id);
516
+ if (filter?.peerId && offer) {
517
+ if (offer.sender !== filter.peerId && offer.recipient !== filter.peerId) continue;
518
+ }
519
+ results.push({
520
+ offer: offer ? offer.toJSON() : null,
521
+ state: state.toJSON(),
522
+ });
523
+ }
524
+ return results;
525
+ }
526
+
527
+ /**
528
+ * Cancel an in-progress transfer.
529
+ * @param {string} transferId
530
+ * @param {string} [reason]
531
+ */
532
+ cancelTransfer(transferId, reason) {
533
+ const state = this.#states.get(transferId);
534
+ if (state && state.status !== 'completed' && state.status !== 'failed' && state.status !== 'cancelled') {
535
+ state.status = 'cancelled';
536
+ }
537
+
538
+ this._emit({
539
+ t: MESH_TYPE.FILE_CANCEL,
540
+ p: { transferId, reason: reason || 'Cancelled' },
541
+ });
542
+ }
543
+
544
+ // ── Dispatch inbound messages ────────────────────────────────────
545
+
546
+ /**
547
+ * Handle an inbound file transfer message.
548
+ * @param {object} msg
549
+ */
550
+ dispatch(msg) {
551
+ if (!msg) return;
552
+
553
+ // Accept envelope format { _mesh: 'file-transfer', payload: {t, p} }
554
+ if (msg._mesh && msg.payload) {
555
+ msg = msg.payload;
556
+ }
557
+
558
+ if (!msg.p) return;
559
+
560
+ switch (msg.t) {
561
+ case MESH_TYPE.FILE_OFFER: {
562
+ const offer = TransferOffer.fromJSON(msg.p);
563
+ this.#offers.set(offer.transferId, offer);
564
+ if (this.#onOffer) this.#onOffer(offer);
565
+ break;
566
+ }
567
+ case MESH_TYPE.FILE_ACCEPT: {
568
+ const state = this.#states.get(msg.p.transferId);
569
+ if (state) state.status = 'accepted';
570
+ break;
571
+ }
572
+ case MESH_TYPE.FILE_REJECT: {
573
+ const state = this.#states.get(msg.p.transferId);
574
+ if (state) state.status = 'cancelled';
575
+ this.#offers.delete(msg.p.transferId);
576
+ break;
577
+ }
578
+ case MESH_TYPE.FILE_COMPLETE: {
579
+ const state = this.#states.get(msg.p.transferId);
580
+ if (state) state.status = 'completed';
581
+ if (this.#onComplete) this.#onComplete(msg.p.transferId, state);
582
+ break;
583
+ }
584
+ case MESH_TYPE.FILE_CANCEL: {
585
+ const state = this.#states.get(msg.p.transferId);
586
+ if (state && state.status !== 'completed') state.status = 'cancelled';
587
+ break;
588
+ }
589
+ }
590
+ }
591
+
592
+ // ── Internal ─────────────────────────────────────────────────────
593
+
594
+ _emit(msg) {
595
+ if (this.#onSend) this.#onSend(msg);
596
+ }
597
+
598
+ _emitProgress(transferId, state) {
599
+ if (this.#onProgress) {
600
+ this.#onProgress(transferId, {
601
+ bytesTransferred: state.bytesTransferred,
602
+ totalSize: state.totalSize,
603
+ percentComplete: state.percentComplete,
604
+ transferRate: state.transferRate,
605
+ });
606
+ }
607
+ this._emit({
608
+ t: MESH_TYPE.FILE_PROGRESS,
609
+ p: {
610
+ transferId,
611
+ bytesTransferred: state.bytesTransferred,
612
+ totalSize: state.totalSize,
613
+ percentComplete: state.percentComplete,
614
+ },
615
+ });
616
+ }
617
+
618
+ // ── Serialization ────────────────────────────────────────────────
619
+
620
+ toJSON() {
621
+ const offers = {};
622
+ for (const [id, offer] of this.#offers) {
623
+ offers[id] = offer.toJSON();
624
+ }
625
+ const states = {};
626
+ for (const [id, state] of this.#states) {
627
+ states[id] = state.toJSON();
628
+ }
629
+ return { offers, states };
630
+ }
631
+
632
+ static fromJSON(json, opts = {}) {
633
+ const ft = new MeshFileTransfer(opts);
634
+ for (const [id, data] of Object.entries(json.offers || {})) {
635
+ ft.#offers.set(id, TransferOffer.fromJSON(data));
636
+ }
637
+ // States need to be reconstructed (TransferState doesn't have fromJSON yet — use toJSON data for reference)
638
+ return ft;
639
+ }
640
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ // browsermesh-sync — CRDT & sync
2
+ export * from './sync.mjs';
3
+ export * from './delta-sync.mjs';
4
+ export * from './migration.mjs';
5
+ export * from './files.mjs';
6
+ export * from './collab.mjs';
7
+ export * from './collab-bridge.mjs';
8
+ export * from './memory-sync.mjs';