@johnhenry/browsermesh-sync 0.2.1 → 0.4.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/README.md +16 -0
- package/package.json +1 -1
- package/src/cidv1.mjs +283 -0
- package/src/files.mjs +72 -4
- package/src/index.mjs +1 -0
- package/src/storage-indexeddb-chunks.mjs +8 -2
package/README.md
CHANGED
|
@@ -26,10 +26,26 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
26
26
|
| delta-sync | `SyncCoordinator`, `DeltaLog`, `DeltaEncoder`, `DeltaDecoder`, `DeltaBranch` |
|
|
27
27
|
| migration | `MigrationEngine`, `MigrationPlan`, `DualActiveWindow` |
|
|
28
28
|
| files | `MeshFileTransfer`, `ChunkStore`, `FileDescriptor`, `TransferOffer` |
|
|
29
|
+
| cidv1 | `computeCidV1`, `buildUnixfsFile`, `buildUnixfsDirectory`, `verifyBlock`, `parseCid`, `cidV1FromSha256Hex`, `sha256HexFromCid` |
|
|
29
30
|
| collab | `CollabSession`, `YjsAdapter`, `AwarenessState` |
|
|
30
31
|
| collab-bridge | `CollabBridge`, `CollabManager` |
|
|
31
32
|
| memory-sync | `AgentMemorySync`, `MemoryEntry`, `ConflictEntry` |
|
|
32
33
|
|
|
34
|
+
## IPFS CIDv1 / UnixFS addressing (opt-in)
|
|
35
|
+
|
|
36
|
+
`ChunkStore.computeCid(data)` still returns a SHA-256 hex digest by default.
|
|
37
|
+
For real IPFS addresses (CIDv1, sha2-256, base32, raw leaves, dag-pb/UnixFS):
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
await ChunkStore.computeCid(bytes, { format: 'cidv1' }); // raw-leaf CIDv1
|
|
41
|
+
const { cid, blocks, files } = await buildUnixfsDirectory({ 'index.html': bytes });
|
|
42
|
+
await verifyBlock(someCid, blockBytes); // accepts SHA-256 hex or CIDv1
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Output matches `ipfs add -r --cid-version=1 --raw-leaves` (256 KiB fixed
|
|
46
|
+
chunks, balanced layout, 174 links max). Directories needing HAMT sharding
|
|
47
|
+
(serialized node over 256 KiB) are rejected.
|
|
48
|
+
|
|
33
49
|
## Install
|
|
34
50
|
|
|
35
51
|
```bash
|
package/package.json
CHANGED
package/src/cidv1.mjs
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real IPFS CIDv1 / UnixFS addressing (opt-in, alongside ChunkStore's
|
|
3
|
+
* SHA-256-hex "cid").
|
|
4
|
+
*
|
|
5
|
+
* Layout parameters match `ipfs add -r --cid-version=1 --raw-leaves` and the
|
|
6
|
+
* defaults of `ipfs-unixfs-importer`: fixed-size 256 KiB chunker, balanced
|
|
7
|
+
* DAG layout with at most 174 links per node, raw leaves (codec 0x55),
|
|
8
|
+
* dag-pb (0x70) for file-interior and directory nodes, sha2-256 multihash,
|
|
9
|
+
* base32 lowercase multibase ("b" prefix). Zero dependencies.
|
|
10
|
+
*
|
|
11
|
+
* Limitation: directories are always flat dag-pb nodes. Directories whose
|
|
12
|
+
* serialized node exceeds 256 KiB (IPFS would HAMT-shard them) are rejected.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const CIDV1_DEFAULTS = Object.freeze({ chunkSize: 262144, maxLinks: 174 });
|
|
16
|
+
|
|
17
|
+
const CODEC_RAW = 0x55;
|
|
18
|
+
const CODEC_DAG_PB = 0x70;
|
|
19
|
+
const MH_SHA256 = 0x12;
|
|
20
|
+
const MAX_DIR_NODE_BYTES = 256 * 1024;
|
|
21
|
+
const B32 = 'abcdefghijklmnopqrstuvwxyz234567';
|
|
22
|
+
const encoder = new TextEncoder();
|
|
23
|
+
|
|
24
|
+
async function sha256(data) {
|
|
25
|
+
if (typeof crypto !== 'undefined' && crypto.subtle) {
|
|
26
|
+
return new Uint8Array(await crypto.subtle.digest('SHA-256', data));
|
|
27
|
+
}
|
|
28
|
+
const { createHash } = await import('node:crypto');
|
|
29
|
+
return new Uint8Array(createHash('sha256').update(data).digest());
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function base32Encode(bytes) {
|
|
33
|
+
let out = '';
|
|
34
|
+
let bits = 0;
|
|
35
|
+
let acc = 0;
|
|
36
|
+
for (const b of bytes) {
|
|
37
|
+
acc = (acc << 8) | b;
|
|
38
|
+
bits += 8;
|
|
39
|
+
while (bits >= 5) {
|
|
40
|
+
out += B32[(acc >>> (bits - 5)) & 31];
|
|
41
|
+
bits -= 5;
|
|
42
|
+
}
|
|
43
|
+
acc &= (1 << bits) - 1;
|
|
44
|
+
}
|
|
45
|
+
if (bits > 0) out += B32[(acc << (5 - bits)) & 31];
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function base32Decode(str) {
|
|
50
|
+
const out = [];
|
|
51
|
+
let bits = 0;
|
|
52
|
+
let acc = 0;
|
|
53
|
+
for (const ch of str) {
|
|
54
|
+
const v = B32.indexOf(ch);
|
|
55
|
+
if (v < 0) throw new Error('invalid base32 character');
|
|
56
|
+
acc = (acc << 5) | v;
|
|
57
|
+
bits += 5;
|
|
58
|
+
if (bits >= 8) {
|
|
59
|
+
out.push((acc >>> (bits - 8)) & 255);
|
|
60
|
+
bits -= 8;
|
|
61
|
+
}
|
|
62
|
+
acc &= (1 << bits) - 1;
|
|
63
|
+
}
|
|
64
|
+
return Uint8Array.from(out);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function cidFromDigest(codec, digest) {
|
|
68
|
+
const bytes = new Uint8Array(4 + digest.length);
|
|
69
|
+
bytes.set([1, codec, MH_SHA256, digest.length]);
|
|
70
|
+
bytes.set(digest, 4);
|
|
71
|
+
return 'b' + base32Encode(bytes);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Parse a base32 CIDv1 string with a sha2-256 multihash.
|
|
76
|
+
* @param {string} cid
|
|
77
|
+
* @returns {{version: 1, codec: 'raw'|'dag-pb', codecCode: number, digest: Uint8Array}}
|
|
78
|
+
*/
|
|
79
|
+
export function parseCid(cid) {
|
|
80
|
+
if (typeof cid !== 'string' || cid[0] !== 'b') throw new Error('unsupported CID: expected base32 CIDv1 ("b" prefix)');
|
|
81
|
+
const bytes = base32Decode(cid.slice(1));
|
|
82
|
+
if (bytes.length !== 36 || bytes[0] !== 1 || bytes[2] !== MH_SHA256 || bytes[3] !== 32) {
|
|
83
|
+
throw new Error('unsupported CID: expected CIDv1 with sha2-256 multihash');
|
|
84
|
+
}
|
|
85
|
+
const codecCode = bytes[1];
|
|
86
|
+
if (codecCode !== CODEC_RAW && codecCode !== CODEC_DAG_PB) throw new Error('unsupported CID codec');
|
|
87
|
+
return { version: 1, codec: codecCode === CODEC_RAW ? 'raw' : 'dag-pb', codecCode, digest: bytes.slice(4) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const toHex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
91
|
+
|
|
92
|
+
/** Raw-leaf CIDv1 (codec raw, sha2-256, base32) of `data`. */
|
|
93
|
+
export async function computeCidV1(data) {
|
|
94
|
+
return cidFromDigest(CODEC_RAW, await sha256(data));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Convert a SHA-256 hex digest (ChunkStore default form) to a raw-leaf CIDv1. */
|
|
98
|
+
export function cidV1FromSha256Hex(hex) {
|
|
99
|
+
if (typeof hex !== 'string' || !/^[0-9a-f]{64}$/.test(hex)) throw new Error('expected a 64-char lowercase sha-256 hex digest');
|
|
100
|
+
return cidFromDigest(CODEC_RAW, Uint8Array.from(hex.match(/../g), (h) => parseInt(h, 16)));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** SHA-256 hex digest of a raw-leaf CIDv1, or null if the CID is not a raw leaf. */
|
|
104
|
+
export function sha256HexFromCid(cid) {
|
|
105
|
+
const p = parseCid(cid);
|
|
106
|
+
return p.codec === 'raw' ? toHex(p.digest) : null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Verify block bytes against either address form: SHA-256 hex or a CIDv1
|
|
111
|
+
* (raw or dag-pb). Never throws; malformed addresses yield false.
|
|
112
|
+
* @returns {Promise<boolean>}
|
|
113
|
+
*/
|
|
114
|
+
export async function verifyBlock(address, bytes) {
|
|
115
|
+
try {
|
|
116
|
+
const digest = await sha256(bytes);
|
|
117
|
+
if (typeof address === 'string' && /^[0-9a-f]{64}$/.test(address)) return toHex(digest) === address;
|
|
118
|
+
const p = parseCid(address);
|
|
119
|
+
return toHex(p.digest) === toHex(digest);
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// --- minimal protobuf / dag-pb / UnixFS encoding ---------------------------
|
|
126
|
+
|
|
127
|
+
function varint(n) {
|
|
128
|
+
const out = [];
|
|
129
|
+
while (n >= 0x80) {
|
|
130
|
+
out.push((n % 0x80) | 0x80);
|
|
131
|
+
n = Math.floor(n / 0x80);
|
|
132
|
+
}
|
|
133
|
+
out.push(n);
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function concat(parts) {
|
|
138
|
+
const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));
|
|
139
|
+
let o = 0;
|
|
140
|
+
for (const p of parts) { out.set(p, o); o += p.length; }
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const lenDelimited = (tag, bytes) => [Uint8Array.from([tag, ...varint(bytes.length)]), bytes];
|
|
145
|
+
|
|
146
|
+
/** dag-pb PBNode: links first (field 2), then Data (field 1). */
|
|
147
|
+
function encodePBNode(links, data) {
|
|
148
|
+
const parts = [];
|
|
149
|
+
for (const l of links) {
|
|
150
|
+
const name = encoder.encode(l.name);
|
|
151
|
+
const hash = l.hash;
|
|
152
|
+
const link = concat([
|
|
153
|
+
...lenDelimited(0x0a, hash),
|
|
154
|
+
...lenDelimited(0x12, name),
|
|
155
|
+
Uint8Array.from([0x18, ...varint(l.tsize)]),
|
|
156
|
+
]);
|
|
157
|
+
parts.push(...lenDelimited(0x12, link));
|
|
158
|
+
}
|
|
159
|
+
if (data) parts.push(...lenDelimited(0x0a, data));
|
|
160
|
+
return concat(parts);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const unixfsDirData = () => Uint8Array.from([0x08, 1]);
|
|
164
|
+
|
|
165
|
+
function unixfsFileData(filesize, blocksizes) {
|
|
166
|
+
const b = [0x08, 2, 0x18, ...varint(filesize)];
|
|
167
|
+
for (const s of blocksizes) b.push(0x20, ...varint(s));
|
|
168
|
+
return Uint8Array.from(b);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function cidBytes(cid) {
|
|
172
|
+
const p = parseCid(cid);
|
|
173
|
+
return concat([Uint8Array.from([1, p.codecCode, MH_SHA256, 32]), p.digest]);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function putBlock(blocks, codec, bytes) {
|
|
177
|
+
const cid = cidFromDigest(codec, await sha256(bytes));
|
|
178
|
+
blocks.set(cid, bytes);
|
|
179
|
+
return cid;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Build a UnixFS file DAG (raw leaves, balanced layout).
|
|
184
|
+
* @param {Uint8Array} bytes
|
|
185
|
+
* @param {{chunkSize?: number, maxLinks?: number, blocks?: Map<string, Uint8Array>}} [opts]
|
|
186
|
+
* @returns {Promise<{cid: string, size: number, blocks: Map<string, Uint8Array>}>}
|
|
187
|
+
* `size` is the cumulative DAG size (dag-pb Tsize).
|
|
188
|
+
*/
|
|
189
|
+
export async function buildUnixfsFile(bytes, opts = {}) {
|
|
190
|
+
const chunkSize = opts.chunkSize ?? CIDV1_DEFAULTS.chunkSize;
|
|
191
|
+
const maxLinks = opts.maxLinks ?? CIDV1_DEFAULTS.maxLinks;
|
|
192
|
+
const blocks = opts.blocks ?? new Map();
|
|
193
|
+
// level entries: { cid, tsize, filesize }
|
|
194
|
+
let level = [];
|
|
195
|
+
if (bytes.length === 0) {
|
|
196
|
+
level.push({ cid: await putBlock(blocks, CODEC_RAW, bytes), tsize: 0, filesize: 0 });
|
|
197
|
+
} else {
|
|
198
|
+
for (let off = 0; off < bytes.length; off += chunkSize) {
|
|
199
|
+
const chunk = bytes.subarray(off, Math.min(off + chunkSize, bytes.length));
|
|
200
|
+
level.push({ cid: await putBlock(blocks, CODEC_RAW, chunk), tsize: chunk.length, filesize: chunk.length });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
while (level.length > 1) {
|
|
204
|
+
const next = [];
|
|
205
|
+
for (let i = 0; i < level.length; i += maxLinks) {
|
|
206
|
+
const group = level.slice(i, i + maxLinks);
|
|
207
|
+
if (group.length === 1) { next.push(group[0]); continue; }
|
|
208
|
+
const filesize = group.reduce((s, g) => s + g.filesize, 0);
|
|
209
|
+
const node = encodePBNode(
|
|
210
|
+
group.map((g) => ({ name: '', hash: cidBytes(g.cid), tsize: g.tsize })),
|
|
211
|
+
unixfsFileData(filesize, group.map((g) => g.filesize)),
|
|
212
|
+
);
|
|
213
|
+
const tsize = node.length + group.reduce((s, g) => s + g.tsize, 0);
|
|
214
|
+
next.push({ cid: await putBlock(blocks, CODEC_DAG_PB, node), tsize, filesize });
|
|
215
|
+
}
|
|
216
|
+
level = next;
|
|
217
|
+
}
|
|
218
|
+
return { cid: level[0].cid, size: level[0].tsize, blocks };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function normalisePath(p) {
|
|
222
|
+
const segs = String(p).split('/').filter((s) => s !== '');
|
|
223
|
+
if (segs.length === 0 || segs.some((s) => s === '.' || s === '..')) throw new Error(`invalid path: ${JSON.stringify(p)}`);
|
|
224
|
+
return segs;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Build a UnixFS directory DAG from a path -> bytes map.
|
|
229
|
+
* @param {Map<string, Uint8Array>|Record<string, Uint8Array>} files
|
|
230
|
+
* @param {{chunkSize?: number, maxLinks?: number}} [opts]
|
|
231
|
+
* @returns {Promise<{cid: string, size: number, blocks: Map<string, Uint8Array>, files: Map<string, string>}>}
|
|
232
|
+
* `cid` is the root directory CID; `blocks` maps every block CID to its bytes
|
|
233
|
+
* (files, interior nodes, directories); `files` maps each (normalised) path to its file CID.
|
|
234
|
+
*/
|
|
235
|
+
export async function buildUnixfsDirectory(files, opts = {}) {
|
|
236
|
+
const entries = files instanceof Map ? [...files] : Object.entries(files);
|
|
237
|
+
if (entries.length === 0) throw new Error('cannot build an empty directory tree');
|
|
238
|
+
const root = new Map();
|
|
239
|
+
const paths = [];
|
|
240
|
+
for (const [path, data] of entries) {
|
|
241
|
+
const segs = normalisePath(path);
|
|
242
|
+
paths.push([segs.join('/'), data]);
|
|
243
|
+
let dir = root;
|
|
244
|
+
for (let i = 0; i < segs.length - 1; i++) {
|
|
245
|
+
let next = dir.get(segs[i]);
|
|
246
|
+
if (next === undefined) { next = new Map(); dir.set(segs[i], next); }
|
|
247
|
+
if (!(next instanceof Map)) throw new Error(`path conflict at ${segs.slice(0, i + 1).join('/')}`);
|
|
248
|
+
dir = next;
|
|
249
|
+
}
|
|
250
|
+
const leaf = segs[segs.length - 1];
|
|
251
|
+
if (dir.has(leaf)) throw new Error(`path conflict at ${segs.join('/')}`);
|
|
252
|
+
dir.set(leaf, { data, path: segs.join('/') });
|
|
253
|
+
}
|
|
254
|
+
const blocks = new Map();
|
|
255
|
+
const fileCids = new Map();
|
|
256
|
+
|
|
257
|
+
async function build(dir) {
|
|
258
|
+
const links = [];
|
|
259
|
+
const names = [...dir.keys()].sort((a, b) => {
|
|
260
|
+
const x = encoder.encode(a), y = encoder.encode(b);
|
|
261
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
262
|
+
return x.length - y.length;
|
|
263
|
+
});
|
|
264
|
+
for (const name of names) {
|
|
265
|
+
const child = dir.get(name);
|
|
266
|
+
let r;
|
|
267
|
+
if (child instanceof Map) {
|
|
268
|
+
r = await build(child);
|
|
269
|
+
} else {
|
|
270
|
+
r = await buildUnixfsFile(child.data, { ...opts, blocks });
|
|
271
|
+
fileCids.set(child.path, r.cid);
|
|
272
|
+
}
|
|
273
|
+
links.push({ name, hash: cidBytes(r.cid), tsize: r.size });
|
|
274
|
+
}
|
|
275
|
+
const node = encodePBNode(links, unixfsDirData());
|
|
276
|
+
if (node.length > MAX_DIR_NODE_BYTES) throw new Error('directory too large: HAMT sharding is not supported');
|
|
277
|
+
const cid = await putBlock(blocks, CODEC_DAG_PB, node);
|
|
278
|
+
return { cid, size: node.length + links.reduce((s, l) => s + l.tsize, 0) };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const r = await build(root);
|
|
282
|
+
return { cid: r.cid, size: r.size, blocks, files: fileCids };
|
|
283
|
+
}
|
package/src/files.mjs
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { MESH_TYPE, MESH_ERROR } from '@johnhenry/browsermesh-primitives';
|
|
12
|
+
import { computeCidV1 } from './cidv1.mjs';
|
|
12
13
|
|
|
13
14
|
// ── Constants ────────────────────────────────────────────────────────
|
|
14
15
|
|
|
@@ -103,11 +104,17 @@ export class ChunkStore {
|
|
|
103
104
|
#chunks = new Map();
|
|
104
105
|
|
|
105
106
|
/**
|
|
106
|
-
* Compute a content ID
|
|
107
|
+
* Compute a content ID for data. Default: SHA-256 hex. Pass
|
|
108
|
+
* `{ format: 'cidv1' }` for a real IPFS raw-leaf CIDv1 (base32); see
|
|
109
|
+
* `cidv1.mjs` for directory / multi-chunk UnixFS DAGs.
|
|
107
110
|
* @param {Uint8Array} data
|
|
111
|
+
* @param {{format?: 'sha256-hex'|'cidv1'}} [opts]
|
|
108
112
|
* @returns {Promise<string>}
|
|
109
113
|
*/
|
|
110
|
-
static async computeCid(data) {
|
|
114
|
+
static async computeCid(data, opts = {}) {
|
|
115
|
+
const format = opts?.format ?? 'sha256-hex';
|
|
116
|
+
if (format === 'cidv1') return computeCidV1(data);
|
|
117
|
+
if (format !== 'sha256-hex') throw new Error(`unknown CID format: ${format}`);
|
|
111
118
|
let hash;
|
|
112
119
|
if (typeof crypto !== 'undefined' && crypto.subtle) {
|
|
113
120
|
hash = await crypto.subtle.digest('SHA-256', data);
|
|
@@ -301,6 +308,12 @@ export class MeshFileTransfer {
|
|
|
301
308
|
// Callbacks
|
|
302
309
|
#onOffer = null;
|
|
303
310
|
#onProgress = null;
|
|
311
|
+
|
|
312
|
+
/** @type {Set<Function>} multi-listener progress subscribers */
|
|
313
|
+
#progressListeners = new Set();
|
|
314
|
+
|
|
315
|
+
/** @type {Map<string, 'send'|'receive'>} transferId → local role */
|
|
316
|
+
#directions = new Map();
|
|
304
317
|
#onComplete = null;
|
|
305
318
|
#onSend = null;
|
|
306
319
|
|
|
@@ -316,6 +329,28 @@ export class MeshFileTransfer {
|
|
|
316
329
|
onComplete(cb) { this.#onComplete = cb; return this; }
|
|
317
330
|
onSend(cb) { this.#onSend = cb; return this; }
|
|
318
331
|
|
|
332
|
+
/**
|
|
333
|
+
* Subscribe to transfer progress. Unlike the single-slot `onProgress`, any
|
|
334
|
+
* number of listeners may subscribe and none displaces another.
|
|
335
|
+
*
|
|
336
|
+
* Listeners receive `{ transferId, direction, bytesDone, bytesTotal,
|
|
337
|
+
* percentComplete, transferRate, state }` where `direction` is `'send'`
|
|
338
|
+
* (this instance created the offer) or `'receive'` (it accepted one) and
|
|
339
|
+
* `state` is the transfer status. An event fires after every chunk
|
|
340
|
+
* (`'transferring'`) and once more on reaching `'completed'` or
|
|
341
|
+
* `'cancelled'`. Events are NOT throttled; throttle in the consumer.
|
|
342
|
+
* A throwing listener is isolated and does not affect other listeners or
|
|
343
|
+
* the transfer.
|
|
344
|
+
*
|
|
345
|
+
* @param {(event: object) => void} fn
|
|
346
|
+
* @returns {() => void} unsubscribe
|
|
347
|
+
*/
|
|
348
|
+
subscribeProgress(fn) {
|
|
349
|
+
if (typeof fn !== 'function') throw new TypeError('subscribeProgress requires a function');
|
|
350
|
+
this.#progressListeners.add(fn);
|
|
351
|
+
return () => { this.#progressListeners.delete(fn); };
|
|
352
|
+
}
|
|
353
|
+
|
|
319
354
|
/** Access the chunk store. */
|
|
320
355
|
get store() { return this.#store; }
|
|
321
356
|
|
|
@@ -336,6 +371,7 @@ export class MeshFileTransfer {
|
|
|
336
371
|
expires: opts.expires,
|
|
337
372
|
});
|
|
338
373
|
this.#offers.set(offer.transferId, offer);
|
|
374
|
+
this.#directions.set(offer.transferId, 'send');
|
|
339
375
|
const fileSizes = offer.files.map(f => f.size);
|
|
340
376
|
const state = new TransferState({
|
|
341
377
|
transferId: offer.transferId,
|
|
@@ -366,6 +402,7 @@ export class MeshFileTransfer {
|
|
|
366
402
|
throw new Error('Transfer offer has expired');
|
|
367
403
|
}
|
|
368
404
|
this.#offers.set(offer.transferId, offer);
|
|
405
|
+
this.#directions.set(offer.transferId, 'receive');
|
|
369
406
|
const fileSizes = offer.files.map(f => f.size);
|
|
370
407
|
const state = new TransferState({
|
|
371
408
|
transferId: offer.transferId,
|
|
@@ -396,6 +433,7 @@ export class MeshFileTransfer {
|
|
|
396
433
|
const state = this.#states.get(transferId);
|
|
397
434
|
if (state) {
|
|
398
435
|
state.status = 'cancelled';
|
|
436
|
+
this._notifyProgress(transferId, state);
|
|
399
437
|
}
|
|
400
438
|
|
|
401
439
|
this._emit({
|
|
@@ -435,7 +473,9 @@ export class MeshFileTransfer {
|
|
|
435
473
|
}
|
|
436
474
|
|
|
437
475
|
if (state.isComplete()) {
|
|
476
|
+
const wasDone = state.status === 'completed';
|
|
438
477
|
state.status = 'completed';
|
|
478
|
+
if (!wasDone) this._notifyProgress(transferId, state);
|
|
439
479
|
this._emit({
|
|
440
480
|
t: MESH_TYPE.FILE_COMPLETE,
|
|
441
481
|
p: { transferId },
|
|
@@ -470,7 +510,9 @@ export class MeshFileTransfer {
|
|
|
470
510
|
this._emitProgress(transferId, state);
|
|
471
511
|
|
|
472
512
|
if (state.isComplete()) {
|
|
513
|
+
const wasDone = state.status === 'completed';
|
|
473
514
|
state.status = 'completed';
|
|
515
|
+
if (!wasDone) this._notifyProgress(transferId, state);
|
|
474
516
|
this._emit({
|
|
475
517
|
t: MESH_TYPE.FILE_COMPLETE,
|
|
476
518
|
p: { transferId },
|
|
@@ -533,6 +575,7 @@ export class MeshFileTransfer {
|
|
|
533
575
|
const state = this.#states.get(transferId);
|
|
534
576
|
if (state && state.status !== 'completed' && state.status !== 'failed' && state.status !== 'cancelled') {
|
|
535
577
|
state.status = 'cancelled';
|
|
578
|
+
this._notifyProgress(transferId, state);
|
|
536
579
|
}
|
|
537
580
|
|
|
538
581
|
this._emit({
|
|
@@ -571,19 +614,27 @@ export class MeshFileTransfer {
|
|
|
571
614
|
}
|
|
572
615
|
case MESH_TYPE.FILE_REJECT: {
|
|
573
616
|
const state = this.#states.get(msg.p.transferId);
|
|
574
|
-
if (state
|
|
617
|
+
if (state && state.status !== 'cancelled') {
|
|
618
|
+
state.status = 'cancelled';
|
|
619
|
+
this._notifyProgress(msg.p.transferId, state);
|
|
620
|
+
}
|
|
575
621
|
this.#offers.delete(msg.p.transferId);
|
|
576
622
|
break;
|
|
577
623
|
}
|
|
578
624
|
case MESH_TYPE.FILE_COMPLETE: {
|
|
579
625
|
const state = this.#states.get(msg.p.transferId);
|
|
626
|
+
const wasDone = state?.status === 'completed';
|
|
580
627
|
if (state) state.status = 'completed';
|
|
628
|
+
if (state && !wasDone) this._notifyProgress(msg.p.transferId, state);
|
|
581
629
|
if (this.#onComplete) this.#onComplete(msg.p.transferId, state);
|
|
582
630
|
break;
|
|
583
631
|
}
|
|
584
632
|
case MESH_TYPE.FILE_CANCEL: {
|
|
585
633
|
const state = this.#states.get(msg.p.transferId);
|
|
586
|
-
if (state && state.status !== 'completed'
|
|
634
|
+
if (state && state.status !== 'completed' && state.status !== 'cancelled') {
|
|
635
|
+
state.status = 'cancelled';
|
|
636
|
+
this._notifyProgress(msg.p.transferId, state);
|
|
637
|
+
}
|
|
587
638
|
break;
|
|
588
639
|
}
|
|
589
640
|
}
|
|
@@ -595,7 +646,24 @@ export class MeshFileTransfer {
|
|
|
595
646
|
if (this.#onSend) this.#onSend(msg);
|
|
596
647
|
}
|
|
597
648
|
|
|
649
|
+
_notifyProgress(transferId, state) {
|
|
650
|
+
if (this.#progressListeners.size === 0) return;
|
|
651
|
+
const event = {
|
|
652
|
+
transferId,
|
|
653
|
+
direction: this.#directions.get(transferId) ?? 'receive',
|
|
654
|
+
bytesDone: state.bytesTransferred,
|
|
655
|
+
bytesTotal: state.totalSize,
|
|
656
|
+
percentComplete: state.percentComplete,
|
|
657
|
+
transferRate: state.transferRate,
|
|
658
|
+
state: state.status,
|
|
659
|
+
};
|
|
660
|
+
for (const fn of [...this.#progressListeners]) {
|
|
661
|
+
try { fn({ ...event }); } catch { /* listener errors never affect the transfer */ }
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
598
665
|
_emitProgress(transferId, state) {
|
|
666
|
+
this._notifyProgress(transferId, state);
|
|
599
667
|
if (this.#onProgress) {
|
|
600
668
|
this.#onProgress(transferId, {
|
|
601
669
|
bytesTransferred: state.bytesTransferred,
|
package/src/index.mjs
CHANGED
|
@@ -36,6 +36,12 @@
|
|
|
36
36
|
* pointed at the same database — exactly the kind of caveat you'd expect
|
|
37
37
|
* from making a synchronous view onto async storage.
|
|
38
38
|
*
|
|
39
|
+
* Torrent service: this class is a supported `chunkStore` for
|
|
40
|
+
* `createTorrentService()` / `TorrentManager` in `@johnhenry/browsermesh-apps`
|
|
41
|
+
* (those await every store call, so the Promise-returning methods are fine).
|
|
42
|
+
* Pair it with a persistent `manifestStore` so a reloaded seeder keeps serving.
|
|
43
|
+
* Covered by `mesh-torrent-hooks.test.mjs` in that package.
|
|
44
|
+
*
|
|
39
45
|
* Usage:
|
|
40
46
|
* const store = new IndexedDBChunkStore({ dbName: 'my-app-chunks' });
|
|
41
47
|
* const cid = await IndexedDBChunkStore.computeCid(data);
|
|
@@ -90,8 +96,8 @@ export class IndexedDBChunkStore {
|
|
|
90
96
|
* @param {Uint8Array} data
|
|
91
97
|
* @returns {Promise<string>}
|
|
92
98
|
*/
|
|
93
|
-
static computeCid(data) {
|
|
94
|
-
return ChunkStore.computeCid(data);
|
|
99
|
+
static computeCid(data, opts) {
|
|
100
|
+
return ChunkStore.computeCid(data, opts);
|
|
95
101
|
}
|
|
96
102
|
|
|
97
103
|
/**
|