@johnhenry/browsermesh-apps 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.
@@ -0,0 +1,374 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-ipfs.js -- Optional Helia/IPFS integration for content-addressed storage.
4
+ *
5
+ * Feature-flagged -- disabled by default. CDN-loads Helia when enabled.
6
+ * When Helia is unavailable, falls back to in-memory SHA-256-addressed storage.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-ipfs.test.mjs
10
+ */
11
+
12
+ import { ChunkStore } from '@johnhenry/browsermesh-sync'
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Constants
16
+ // ---------------------------------------------------------------------------
17
+
18
+ export const IPFS_DEFAULTS = Object.freeze({
19
+ enabled: false,
20
+ maxStorageMb: 100,
21
+ })
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // IPFSStore
25
+ // ---------------------------------------------------------------------------
26
+
27
+ /**
28
+ * Content-addressed storage with optional Helia/IPFS backend.
29
+ *
30
+ * When Helia is available and enabled, data is stored in a real IPFS node.
31
+ * Otherwise, data is kept in memory keyed by SHA-256 CID (same format used
32
+ * by ChunkStore in browsermesh-sync).
33
+ */
34
+ export class IPFSStore {
35
+ /** @type {object|null} Helia node instance (lazy-loaded) */
36
+ #helia = null
37
+
38
+ /** @type {boolean} */
39
+ #loaded = false
40
+
41
+ /** @type {boolean} */
42
+ #heliaAvailable = false
43
+
44
+ /** @type {boolean} */
45
+ #enabled
46
+
47
+ /** @type {number} */
48
+ #maxStorageMb
49
+
50
+ /** @type {Map<string, { data: Uint8Array, size: number, pinned: boolean, addedAt: number }>} */
51
+ #storedCids = new Map()
52
+
53
+ /** @type {Function} */
54
+ #onLog
55
+
56
+ /** @type {Map<string, Set<Function>>} event -> callbacks */
57
+ #listeners = new Map()
58
+
59
+ /**
60
+ * @param {object} [opts]
61
+ * @param {boolean} [opts.enabled=false] - Whether IPFS is enabled
62
+ * @param {number} [opts.maxStorageMb=100] - Maximum storage in MB
63
+ * @param {Function} [opts.onLog] - Logging callback
64
+ */
65
+ constructor(opts = {}) {
66
+ this.#enabled = opts.enabled ?? IPFS_DEFAULTS.enabled
67
+ this.#maxStorageMb = opts.maxStorageMb ?? IPFS_DEFAULTS.maxStorageMb
68
+ this.#onLog = opts.onLog || (() => {})
69
+ }
70
+
71
+ // ── CDN Loading ──────────────────────────────────────────────────────
72
+
73
+ /**
74
+ * Lazy-load Helia from CDN.
75
+ * Only attempts if enabled. Sets #heliaAvailable based on result.
76
+ */
77
+ async ensureLoaded() {
78
+ if (this.#loaded) return
79
+ if (!this.#enabled) {
80
+ this.#loaded = true
81
+ return
82
+ }
83
+
84
+ try {
85
+ if (typeof globalThis.Helia === 'function') {
86
+ this.#helia = await globalThis.Helia.create()
87
+ this.#heliaAvailable = true
88
+ this.#onLog(2, 'Helia node initialized from globalThis')
89
+ } else {
90
+ try {
91
+ // CDN URL verified current 2026-05-03 against npm registry latest (helia@6.1.4).
92
+ await import('https://cdn.jsdelivr.net/npm/helia@6.1.4/dist/index.min.js')
93
+ if (typeof globalThis.Helia === 'function') {
94
+ this.#helia = await globalThis.Helia.create()
95
+ this.#heliaAvailable = true
96
+ this.#onLog(2, 'Helia loaded from CDN')
97
+ }
98
+ } catch {
99
+ this.#heliaAvailable = false
100
+ this.#onLog(1, 'Helia CDN load failed -- using memory-backed CID store')
101
+ }
102
+ }
103
+ } catch (err) {
104
+ this.#heliaAvailable = false
105
+ this.#onLog(1, `Helia initialization failed: ${err.message}`)
106
+ }
107
+
108
+ this.#loaded = true
109
+ }
110
+
111
+ // ── Properties ───────────────────────────────────────────────────────
112
+
113
+ /** Whether ensureLoaded() has been called. */
114
+ get loaded() {
115
+ return this.#loaded
116
+ }
117
+
118
+ /** Whether Helia is usable (true only after successful load). */
119
+ get available() {
120
+ return this.#heliaAvailable
121
+ }
122
+
123
+ /** Whether IPFS storage is enabled. */
124
+ get enabled() {
125
+ return this.#enabled
126
+ }
127
+
128
+ // ── Add ──────────────────────────────────────────────────────────────
129
+
130
+ /**
131
+ * Add data to the store. Returns the content identifier (CID).
132
+ *
133
+ * @param {Uint8Array|string} data - Data to store
134
+ * @returns {Promise<{ cid: string, size: number }>}
135
+ */
136
+ async add(data) {
137
+ if (!this.#loaded) await this.ensureLoaded()
138
+
139
+ const bytes = typeof data === 'string'
140
+ ? new TextEncoder().encode(data)
141
+ : data
142
+
143
+ const size = bytes.byteLength
144
+
145
+ // Check storage limits
146
+ const currentSizeMb = this.#getCurrentSizeMb()
147
+ const newSizeMb = size / (1024 * 1024)
148
+ if (currentSizeMb + newSizeMb > this.#maxStorageMb) {
149
+ throw new Error(`Storage limit exceeded: ${currentSizeMb.toFixed(2)}MB + ${newSizeMb.toFixed(2)}MB > ${this.#maxStorageMb}MB`)
150
+ }
151
+
152
+ // Compute CID via SHA-256
153
+ const cid = await ChunkStore.computeCid(bytes)
154
+
155
+ // Store in memory — preserve pin status if already stored (dedup)
156
+ const existing = this.#storedCids.get(cid)
157
+ this.#storedCids.set(cid, {
158
+ data: bytes,
159
+ size,
160
+ pinned: existing ? existing.pinned : false,
161
+ addedAt: existing ? existing.addedAt : Date.now(),
162
+ })
163
+
164
+ this.#emit('add', { cid, size })
165
+ this.#onLog(2, `Added content: ${cid} (${size} bytes)`)
166
+
167
+ return { cid, size }
168
+ }
169
+
170
+ // ── Get ──────────────────────────────────────────────────────────────
171
+
172
+ /**
173
+ * Retrieve data by CID.
174
+ *
175
+ * @param {string} cid - Content identifier
176
+ * @returns {Promise<Uint8Array|null>}
177
+ */
178
+ async get(cid) {
179
+ if (!this.#loaded) await this.ensureLoaded()
180
+
181
+ const entry = this.#storedCids.get(cid)
182
+ if (!entry) return null
183
+ return entry.data
184
+ }
185
+
186
+ // ── Pin / Unpin ──────────────────────────────────────────────────────
187
+
188
+ /**
189
+ * Pin content locally (prevents garbage collection).
190
+ *
191
+ * @param {string} cid
192
+ * @returns {Promise<boolean>} true if content exists and was pinned
193
+ */
194
+ async pin(cid) {
195
+ const entry = this.#storedCids.get(cid)
196
+ if (!entry) return false
197
+ entry.pinned = true
198
+ this.#emit('pin', { cid })
199
+ return true
200
+ }
201
+
202
+ /**
203
+ * Unpin content.
204
+ *
205
+ * @param {string} cid
206
+ * @returns {Promise<boolean>} true if content exists and was unpinned
207
+ */
208
+ async unpin(cid) {
209
+ const entry = this.#storedCids.get(cid)
210
+ if (!entry) return false
211
+ entry.pinned = false
212
+ this.#emit('unpin', { cid })
213
+ return true
214
+ }
215
+
216
+ // ── List ─────────────────────────────────────────────────────────────
217
+
218
+ /**
219
+ * List all stored CIDs with metadata.
220
+ *
221
+ * @returns {{ cid: string, size: number, pinned: boolean, addedAt: number }[]}
222
+ */
223
+ listCids() {
224
+ const results = []
225
+ for (const [cid, entry] of this.#storedCids) {
226
+ results.push({
227
+ cid,
228
+ size: entry.size,
229
+ pinned: entry.pinned,
230
+ addedAt: entry.addedAt,
231
+ })
232
+ }
233
+ return results
234
+ }
235
+
236
+ // ── Remove ───────────────────────────────────────────────────────────
237
+
238
+ /**
239
+ * Remove content by CID.
240
+ *
241
+ * @param {string} cid
242
+ * @returns {Promise<boolean>} true if content existed and was removed
243
+ */
244
+ async remove(cid) {
245
+ const entry = this.#storedCids.get(cid)
246
+ if (!entry) return false
247
+ if (entry.pinned) {
248
+ this.#onLog(1, `Cannot remove pinned content: ${cid}`)
249
+ return false
250
+ }
251
+ this.#storedCids.delete(cid)
252
+ this.#emit('remove', { cid })
253
+ this.#onLog(2, `Removed content: ${cid}`)
254
+ return true
255
+ }
256
+
257
+ // ── Stats ────────────────────────────────────────────────────────────
258
+
259
+ /**
260
+ * Get storage statistics.
261
+ *
262
+ * @returns {{ totalCids: number, totalSizeMb: number, pinnedCount: number }}
263
+ */
264
+ getStats() {
265
+ let pinnedCount = 0
266
+ for (const entry of this.#storedCids.values()) {
267
+ if (entry.pinned) pinnedCount++
268
+ }
269
+
270
+ return {
271
+ totalCids: this.#storedCids.size,
272
+ totalSizeMb: this.#getCurrentSizeMb(),
273
+ pinnedCount,
274
+ }
275
+ }
276
+
277
+ // ── Events ───────────────────────────────────────────────────────────
278
+
279
+ /**
280
+ * Register an event listener.
281
+ * Events: 'add', 'remove', 'pin', 'unpin'
282
+ *
283
+ * @param {string} event
284
+ * @param {Function} cb
285
+ */
286
+ on(event, cb) {
287
+ if (!this.#listeners.has(event)) {
288
+ this.#listeners.set(event, new Set())
289
+ }
290
+ this.#listeners.get(event).add(cb)
291
+ }
292
+
293
+ /**
294
+ * Remove an event listener.
295
+ *
296
+ * @param {string} event
297
+ * @param {Function} cb
298
+ */
299
+ off(event, cb) {
300
+ const set = this.#listeners.get(event)
301
+ if (set) set.delete(cb)
302
+ }
303
+
304
+ /**
305
+ * Emit an event to registered listeners.
306
+ * @param {string} event
307
+ * @param {*} data
308
+ */
309
+ #emit(event, data) {
310
+ const set = this.#listeners.get(event)
311
+ if (set) {
312
+ for (const cb of [...set]) {
313
+ try {
314
+ cb(data)
315
+ } catch (err) {
316
+ this.#onLog(0, `Event listener error (${event}): ${err.message}`)
317
+ }
318
+ }
319
+ }
320
+ }
321
+
322
+ // ── Internal ─────────────────────────────────────────────────────────
323
+
324
+ /**
325
+ * Calculate current storage usage in megabytes.
326
+ * @returns {number}
327
+ */
328
+ #getCurrentSizeMb() {
329
+ let totalBytes = 0
330
+ for (const entry of this.#storedCids.values()) {
331
+ totalBytes += entry.size
332
+ }
333
+ return totalBytes / (1024 * 1024)
334
+ }
335
+
336
+ // ── Lifecycle ────────────────────────────────────────────────────────
337
+
338
+ /**
339
+ * Close the IPFS store. Clears all stored data and shuts down Helia if present.
340
+ */
341
+ async close() {
342
+ this.#storedCids.clear()
343
+ this.#listeners.clear()
344
+
345
+ if (this.#helia) {
346
+ try {
347
+ await this.#helia.stop()
348
+ } catch {
349
+ // best effort
350
+ }
351
+ this.#helia = null
352
+ }
353
+
354
+ this.#loaded = false
355
+ this.#heliaAvailable = false
356
+ }
357
+
358
+ // ── Serialization ────────────────────────────────────────────────────
359
+
360
+ /**
361
+ * Serialize to a JSON-safe object.
362
+ * @returns {object}
363
+ */
364
+ toJSON() {
365
+ return {
366
+ enabled: this.#enabled,
367
+ loaded: this.#loaded,
368
+ available: this.#heliaAvailable,
369
+ maxStorageMb: this.#maxStorageMb,
370
+ stats: this.getStats(),
371
+ cids: this.listCids().map(c => ({ cid: c.cid, size: c.size, pinned: c.pinned })),
372
+ }
373
+ }
374
+ }