@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,470 @@
1
+ /**
2
+ // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
+ * clawser-peer-files.js -- Remote file access over peer sessions.
4
+ *
5
+ * Provides browsing, reading, writing, and deleting files on a remote
6
+ * peer's OPFS through FileHost (serves local filesystem) and FileClient
7
+ * (sends requests and awaits results). Built on top of PeerSession's
8
+ * service handler system using the 'files' service type.
9
+ *
10
+ * Dependencies are injected (PeerSession, fs interface).
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-files.test.mjs
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Constants
19
+ // ---------------------------------------------------------------------------
20
+
21
+ export const FILE_DEFAULTS = Object.freeze({
22
+ maxFileSize: 10 * 1024 * 1024, // 10MB
23
+ timeout: 30000, // 30s
24
+ })
25
+
26
+ export const FILE_ACTIONS = Object.freeze({
27
+ LIST: 'list',
28
+ READ: 'read',
29
+ WRITE: 'write',
30
+ DELETE: 'delete',
31
+ STAT: 'stat',
32
+ })
33
+
34
+ export const FILE_CAPABILITIES = Object.freeze({
35
+ READ: 'fs:read',
36
+ WRITE: 'fs:write',
37
+ DELETE: 'fs:delete',
38
+ })
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Internal — map actions to required capabilities
42
+ // ---------------------------------------------------------------------------
43
+
44
+ const ACTION_CAPABILITY = Object.freeze({
45
+ [FILE_ACTIONS.LIST]: FILE_CAPABILITIES.READ,
46
+ [FILE_ACTIONS.READ]: FILE_CAPABILITIES.READ,
47
+ [FILE_ACTIONS.STAT]: FILE_CAPABILITIES.READ,
48
+ [FILE_ACTIONS.WRITE]: FILE_CAPABILITIES.WRITE,
49
+ [FILE_ACTIONS.DELETE]: FILE_CAPABILITIES.DELETE,
50
+ })
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // FileHost
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /**
57
+ * Serves file operations from the local filesystem to remote peers.
58
+ *
59
+ * Registers a handler on the PeerSession for the 'files' service type.
60
+ * Incoming requests are validated against capability requirements and
61
+ * file size limits before execution. The remote peer must hold the
62
+ * appropriate capability on the session (fs:read, fs:write, fs:delete).
63
+ */
64
+ export class FileHost {
65
+ /** @type {object} PeerSession */
66
+ #session
67
+
68
+ /**
69
+ * @type {object} File system interface (duck-typed)
70
+ * async list(path) -> { name, type, size }[]
71
+ * async read(path) -> { data: string|Uint8Array, size: number }
72
+ * async write(path, data) -> { success, size }
73
+ * async delete(path) -> { success }
74
+ * async stat(path) -> { name, type, size, modified }|null
75
+ */
76
+ #fs
77
+
78
+ /** @type {number} */
79
+ #maxFileSize
80
+
81
+ /** @type {Function} */
82
+ #onLog
83
+
84
+ /**
85
+ * @param {object} opts
86
+ * @param {object} opts.session - PeerSession instance
87
+ * @param {object} opts.fs - File system interface with list/read/write/delete/stat
88
+ * @param {number} [opts.maxFileSize=10485760] - Maximum file size for writes (bytes)
89
+ * @param {Function} [opts.onLog] - Logging callback
90
+ */
91
+ constructor({ session, fs, maxFileSize, onLog }) {
92
+ if (!session) {
93
+ throw new Error('session is required')
94
+ }
95
+ if (!fs || typeof fs.list !== 'function' || typeof fs.read !== 'function') {
96
+ throw new Error('fs with list() and read() methods is required')
97
+ }
98
+
99
+ this.#session = session
100
+ this.#fs = fs
101
+ this.#maxFileSize = maxFileSize ?? FILE_DEFAULTS.maxFileSize
102
+ this.#onLog = onLog || (() => {})
103
+
104
+ // Register handler on session for 'files' service type
105
+ this.#session.registerHandler('files', (envelope) => this.#handleRequest(envelope))
106
+ }
107
+
108
+ // -- Request handling (private) -------------------------------------------
109
+
110
+ /**
111
+ * Handle an incoming file operation request.
112
+ *
113
+ * 1. Validates the action and path
114
+ * 2. Checks the required capability on the session
115
+ * 3. Dispatches to the appropriate fs method
116
+ * 4. Enforces maxFileSize on writes
117
+ * 5. Sends the response back via session
118
+ *
119
+ * @param {object} envelope - Session envelope with payload
120
+ */
121
+ async #handleRequest(envelope) {
122
+ const payload = envelope.payload || envelope
123
+ const { action, path, data, requestId } = payload
124
+
125
+ // Build base response
126
+ const response = {
127
+ requestId: requestId || null,
128
+ action: action || null,
129
+ success: false,
130
+ }
131
+
132
+ try {
133
+ // 1. Validate action
134
+ if (!action || !Object.values(FILE_ACTIONS).includes(action)) {
135
+ response.error = `Unknown action: ${action}`
136
+ this.#session.send('files', response)
137
+ return
138
+ }
139
+
140
+ // 2. Validate path
141
+ if (!path || typeof path !== 'string') {
142
+ response.error = 'path must be a non-empty string'
143
+ this.#session.send('files', response)
144
+ return
145
+ }
146
+
147
+ // 3. Check capability
148
+ const requiredCap = ACTION_CAPABILITY[action]
149
+ if (requiredCap) {
150
+ this.#session.requireCapability(requiredCap)
151
+ }
152
+
153
+ // 4. Dispatch to the appropriate fs method
154
+ let result
155
+ switch (action) {
156
+ case FILE_ACTIONS.LIST: {
157
+ this.#onLog(2, `File list request from ${this.#session.remotePodId}: ${path}`)
158
+ result = await this.#fs.list(path)
159
+ response.success = true
160
+ response.result = result
161
+ break
162
+ }
163
+
164
+ case FILE_ACTIONS.READ: {
165
+ this.#onLog(2, `File read request from ${this.#session.remotePodId}: ${path}`)
166
+ result = await this.#fs.read(path)
167
+ response.success = true
168
+ response.result = result
169
+ break
170
+ }
171
+
172
+ case FILE_ACTIONS.WRITE: {
173
+ // Reject null/undefined data
174
+ if (data == null) {
175
+ response.error = 'Write data is required'
176
+ this.#session.send('files', response)
177
+ return
178
+ }
179
+
180
+ // Enforce maxFileSize
181
+ const size = typeof data === 'string'
182
+ ? new TextEncoder().encode(data).byteLength
183
+ : (data.byteLength ?? data.length ?? 0)
184
+ if (size > this.#maxFileSize) {
185
+ response.error = `File size ${size} exceeds maximum ${this.#maxFileSize} bytes`
186
+ this.#session.send('files', response)
187
+ return
188
+ }
189
+
190
+ this.#onLog(2, `File write request from ${this.#session.remotePodId}: ${path}`)
191
+ result = await this.#fs.write(path, data)
192
+ response.success = result.success !== false
193
+ response.result = result
194
+ break
195
+ }
196
+
197
+ case FILE_ACTIONS.DELETE: {
198
+ this.#onLog(2, `File delete request from ${this.#session.remotePodId}: ${path}`)
199
+ result = await this.#fs.delete(path)
200
+ response.success = result.success !== false
201
+ response.result = result
202
+ break
203
+ }
204
+
205
+ case FILE_ACTIONS.STAT: {
206
+ this.#onLog(2, `File stat request from ${this.#session.remotePodId}: ${path}`)
207
+ result = await this.#fs.stat(path)
208
+ response.success = true
209
+ response.result = result
210
+ break
211
+ }
212
+ }
213
+ } catch (err) {
214
+ response.error = err.message
215
+ this.#onLog(0, `File operation error (${action}): ${err.message}`)
216
+ }
217
+
218
+ // Send response back
219
+ this.#session.send('files', response)
220
+ }
221
+
222
+ // -- Lifecycle ------------------------------------------------------------
223
+
224
+ /**
225
+ * Close the file host. Removes the handler from the session.
226
+ */
227
+ close() {
228
+ this.#session.removeHandler('files')
229
+ }
230
+
231
+ // -- Serialization --------------------------------------------------------
232
+
233
+ /**
234
+ * Serialize to a JSON-safe object.
235
+ *
236
+ * @returns {object}
237
+ */
238
+ toJSON() {
239
+ return {
240
+ sessionId: this.#session.sessionId,
241
+ localPodId: this.#session.localPodId,
242
+ remotePodId: this.#session.remotePodId,
243
+ maxFileSize: this.#maxFileSize,
244
+ }
245
+ }
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // FileClient
250
+ // ---------------------------------------------------------------------------
251
+
252
+ /**
253
+ * Client-side interface for accessing a remote peer's files.
254
+ *
255
+ * Sends file operation requests via the PeerSession and waits for
256
+ * responses matched by requestId. Supports configurable timeout per
257
+ * request and provides promise-based methods for each file operation.
258
+ */
259
+ export class FileClient {
260
+ /** @type {object} PeerSession */
261
+ #session
262
+
263
+ /** @type {Map<string, { resolve: Function, reject: Function, timer: * }>} */
264
+ #pendingRequests = new Map()
265
+
266
+ /** @type {number} default timeout in ms */
267
+ #timeout
268
+
269
+ /** @type {Function} */
270
+ #onLog
271
+
272
+ /**
273
+ * @param {object} opts
274
+ * @param {object} opts.session - PeerSession instance
275
+ * @param {number} [opts.timeout=30000] - Default timeout for requests in ms
276
+ * @param {Function} [opts.onLog] - Logging callback
277
+ */
278
+ constructor({ session, timeout, onLog }) {
279
+ if (!session) {
280
+ throw new Error('session is required')
281
+ }
282
+
283
+ this.#session = session
284
+ this.#timeout = timeout ?? FILE_DEFAULTS.timeout
285
+ this.#onLog = onLog || (() => {})
286
+
287
+ // Register handler on session for 'files' response messages
288
+ this.#session.registerHandler('files', (envelope) => this.#handleResponse(envelope))
289
+ }
290
+
291
+ // -- File operations ------------------------------------------------------
292
+
293
+ /**
294
+ * List files at a path on the remote peer.
295
+ *
296
+ * @param {string} path - Directory path to list
297
+ * @returns {Promise<{ name: string, type: string, size: number }[]>}
298
+ */
299
+ async listFiles(path) {
300
+ const response = await this.#request(FILE_ACTIONS.LIST, path)
301
+ return response.result
302
+ }
303
+
304
+ /**
305
+ * Read a file from the remote peer.
306
+ *
307
+ * @param {string} path - File path to read
308
+ * @returns {Promise<{ data: string|Uint8Array, size: number }>}
309
+ */
310
+ async readFile(path) {
311
+ const response = await this.#request(FILE_ACTIONS.READ, path)
312
+ return response.result
313
+ }
314
+
315
+ /**
316
+ * Write data to a file on the remote peer.
317
+ *
318
+ * @param {string} path - File path to write
319
+ * @param {string|Uint8Array} data - File content to write
320
+ * @returns {Promise<{ success: boolean, size: number }>}
321
+ */
322
+ async writeFile(path, data) {
323
+ const response = await this.#request(FILE_ACTIONS.WRITE, path, data)
324
+ return response.result
325
+ }
326
+
327
+ /**
328
+ * Delete a file on the remote peer.
329
+ *
330
+ * @param {string} path - File path to delete
331
+ * @returns {Promise<{ success: boolean }>}
332
+ */
333
+ async deleteFile(path) {
334
+ const response = await this.#request(FILE_ACTIONS.DELETE, path)
335
+ return response.result
336
+ }
337
+
338
+ /**
339
+ * Get file metadata from the remote peer.
340
+ *
341
+ * @param {string} path - File path to stat
342
+ * @returns {Promise<{ name: string, type: string, size: number, modified: number }|null>}
343
+ */
344
+ async stat(path) {
345
+ const response = await this.#request(FILE_ACTIONS.STAT, path)
346
+ return response.result
347
+ }
348
+
349
+ // -- Internal request handling --------------------------------------------
350
+
351
+ /**
352
+ * Send a file operation request and wait for the matching response.
353
+ *
354
+ * Creates a unique requestId, sends the request via the session,
355
+ * and returns a promise that resolves when the response arrives
356
+ * or rejects on timeout.
357
+ *
358
+ * @param {string} action - File action (list, read, write, delete, stat)
359
+ * @param {string} path - File path
360
+ * @param {*} [data] - Optional data payload (for write)
361
+ * @returns {Promise<{ requestId, action, success, result?, error? }>}
362
+ */
363
+ async #request(action, path, data) {
364
+ if (!path || typeof path !== 'string') {
365
+ throw new Error('path must be a non-empty string')
366
+ }
367
+
368
+ const requestId = crypto.randomUUID()
369
+ const timeoutMs = this.#timeout
370
+
371
+ return new Promise((resolve, reject) => {
372
+ // Set up timeout
373
+ const timer = setTimeout(() => {
374
+ const pending = this.#pendingRequests.get(requestId)
375
+ if (pending) {
376
+ this.#pendingRequests.delete(requestId)
377
+ const err = new Error(`File request timed out after ${timeoutMs}ms`)
378
+ err.code = 'FILE_TIMEOUT'
379
+ reject(err)
380
+ }
381
+ }, timeoutMs)
382
+
383
+ // Register pending request
384
+ this.#pendingRequests.set(requestId, { resolve, reject, timer })
385
+
386
+ // Build and send request payload
387
+ const payload = { action, path, requestId }
388
+ if (data !== undefined) {
389
+ payload.data = data
390
+ }
391
+
392
+ try {
393
+ this.#session.send('files', payload)
394
+ this.#onLog(2, `Sent file ${action} request to ${this.#session.remotePodId}: ${path}`)
395
+ } catch (err) {
396
+ clearTimeout(timer)
397
+ this.#pendingRequests.delete(requestId)
398
+ reject(err)
399
+ }
400
+ })
401
+ }
402
+
403
+ // -- Response handling (private) ------------------------------------------
404
+
405
+ /**
406
+ * Handle an incoming file response from the remote host.
407
+ * Matches by requestId and resolves or rejects the pending promise.
408
+ *
409
+ * @param {object} envelope - Session envelope with payload
410
+ */
411
+ #handleResponse(envelope) {
412
+ const payload = envelope.payload || envelope
413
+ const { requestId } = payload
414
+
415
+ if (!requestId) return
416
+
417
+ const pending = this.#pendingRequests.get(requestId)
418
+ if (!pending) return
419
+
420
+ // Clean up
421
+ clearTimeout(pending.timer)
422
+ this.#pendingRequests.delete(requestId)
423
+
424
+ // Check for errors
425
+ if (payload.error) {
426
+ const err = new Error(payload.error)
427
+ err.code = 'FILE_REMOTE_ERROR'
428
+ pending.reject(err)
429
+ return
430
+ }
431
+
432
+ // Resolve with the full response
433
+ pending.resolve(payload)
434
+ }
435
+
436
+ // -- Lifecycle ------------------------------------------------------------
437
+
438
+ /**
439
+ * Close the file client. Removes the handler from the session
440
+ * and rejects all pending requests.
441
+ */
442
+ close() {
443
+ // Reject all pending requests
444
+ for (const [requestId, pending] of this.#pendingRequests) {
445
+ clearTimeout(pending.timer)
446
+ pending.reject(new Error('FileClient closed'))
447
+ }
448
+ this.#pendingRequests.clear()
449
+
450
+ // Remove handler from session
451
+ this.#session.removeHandler('files')
452
+ }
453
+
454
+ // -- Serialization --------------------------------------------------------
455
+
456
+ /**
457
+ * Serialize to a JSON-safe object.
458
+ *
459
+ * @returns {object}
460
+ */
461
+ toJSON() {
462
+ return {
463
+ sessionId: this.#session.sessionId,
464
+ localPodId: this.#session.localPodId,
465
+ remotePodId: this.#session.remotePodId,
466
+ pendingRequests: this.#pendingRequests.size,
467
+ timeout: this.#timeout,
468
+ }
469
+ }
470
+ }