@johnhenry/browsermesh-core 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/peer.mjs ADDED
@@ -0,0 +1,391 @@
1
+ /**
2
+ // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
+ * clawser-mesh-peer.js -- Peer Connection Manager.
4
+ *
5
+ * Discovers, connects to, and maintains connections with mesh peers.
6
+ * Does not handle the actual transport -- delegates to MeshTransportManager.
7
+ *
8
+ * Peer status lifecycle: disconnected -> connecting -> connected -> authenticated
9
+ *
10
+ * Run tests:
11
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-peer.test.mjs
12
+ */
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Constants
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /** @type {readonly string[]} */
19
+ const PEER_STATUSES = Object.freeze([
20
+ 'disconnected',
21
+ 'connecting',
22
+ 'connected',
23
+ 'authenticated',
24
+ ]);
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // PeerState
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * Immutable-ish snapshot of a single peer's connection state.
32
+ */
33
+ export class PeerState {
34
+ /**
35
+ * @param {object} opts
36
+ * @param {string} opts.fingerprint - Unique peer identifier (public key hash)
37
+ * @param {string} [opts.label] - Human-readable name
38
+ * @param {string} [opts.status] - One of PEER_STATUSES
39
+ * @param {string|null} [opts.transport] - 'webrtc' | 'wsh-wt' | 'wsh-ws' | 'relay' | null
40
+ * @param {string|null} [opts.endpoint] - Connection endpoint URL
41
+ * @param {number|null} [opts.latency] - Last measured latency in ms
42
+ * @param {number} [opts.lastSeen] - Unix timestamp (ms)
43
+ * @param {string[]} [opts.capabilities] - Advertised capabilities
44
+ * @param {number} [opts.trustLevel] - 0 = untrusted, higher = more trust
45
+ */
46
+ constructor({
47
+ fingerprint,
48
+ label = null,
49
+ status = 'disconnected',
50
+ transport = null,
51
+ endpoint = null,
52
+ latency = null,
53
+ lastSeen = Date.now(),
54
+ capabilities = [],
55
+ trustLevel = 0,
56
+ }) {
57
+ if (!fingerprint || typeof fingerprint !== 'string') {
58
+ throw new Error('fingerprint is required and must be a non-empty string');
59
+ }
60
+ this.fingerprint = fingerprint;
61
+ this.label = label;
62
+ this.status = status;
63
+ this.transport = transport;
64
+ this.endpoint = endpoint;
65
+ this.latency = latency;
66
+ this.lastSeen = lastSeen;
67
+ this.capabilities = [...capabilities];
68
+ this.trustLevel = trustLevel;
69
+ }
70
+
71
+ /**
72
+ * Serialize to a plain JSON-safe object.
73
+ * @returns {object}
74
+ */
75
+ toJSON() {
76
+ return {
77
+ fingerprint: this.fingerprint,
78
+ label: this.label,
79
+ status: this.status,
80
+ transport: this.transport,
81
+ endpoint: this.endpoint,
82
+ latency: this.latency,
83
+ lastSeen: this.lastSeen,
84
+ capabilities: [...this.capabilities],
85
+ trustLevel: this.trustLevel,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Re-hydrate from a plain object.
91
+ * @param {object} data
92
+ * @returns {PeerState}
93
+ */
94
+ static fromJSON(data) {
95
+ return new PeerState(data);
96
+ }
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // MeshPeerManager
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /**
104
+ * Manages a registry of known mesh peers and their lifecycle.
105
+ *
106
+ * Fires callbacks on status transitions:
107
+ * - connect: peer transitioned to 'connected' or 'authenticated'
108
+ * - disconnect: peer transitioned to 'disconnected'
109
+ * - discovered: new peer discovered (via relay or mDNS)
110
+ */
111
+ export class MeshPeerManager {
112
+ /** @type {Map<string, PeerState>} fingerprint -> PeerState */
113
+ #peers = new Map();
114
+
115
+ /** @type {{ connect: Function[], disconnect: Function[], discovered: Function[] }} */
116
+ #callbacks = { connect: [], disconnect: [], discovered: [] };
117
+
118
+ /** @type {string[]} */
119
+ #ownCapabilities = [];
120
+
121
+ /** @type {Function} */
122
+ #onLog;
123
+
124
+ /**
125
+ * @param {object} [opts]
126
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
127
+ */
128
+ constructor(opts = {}) {
129
+ this.#onLog = opts.onLog || (() => {});
130
+ }
131
+
132
+ // -- Peer CRUD ----------------------------------------------------------
133
+
134
+ /**
135
+ * Add a new peer or update an existing one.
136
+ *
137
+ * @param {string} fingerprint
138
+ * @param {object} [info] - Partial PeerState fields
139
+ * @returns {PeerState}
140
+ */
141
+ addPeer(fingerprint, info = {}) {
142
+ if (this.#peers.has(fingerprint)) {
143
+ const existing = this.#peers.get(fingerprint);
144
+ Object.assign(existing, info);
145
+ return existing;
146
+ }
147
+ const peer = new PeerState({ fingerprint, ...info });
148
+ this.#peers.set(fingerprint, peer);
149
+ this.#onLog(2, `Peer added: ${fingerprint}`);
150
+ return peer;
151
+ }
152
+
153
+ /**
154
+ * Update fields on an existing peer, firing lifecycle callbacks as needed.
155
+ *
156
+ * @param {string} fingerprint
157
+ * @param {object} updates - Fields to merge
158
+ * @returns {PeerState|null}
159
+ */
160
+ updatePeer(fingerprint, updates) {
161
+ const peer = this.#peers.get(fingerprint);
162
+ if (!peer) return null;
163
+
164
+ const oldStatus = peer.status;
165
+ Object.assign(peer, updates);
166
+ peer.lastSeen = Date.now();
167
+
168
+ // Fire callbacks on status transitions
169
+ if (
170
+ oldStatus !== 'connected' &&
171
+ oldStatus !== 'authenticated' &&
172
+ (peer.status === 'connected' || peer.status === 'authenticated')
173
+ ) {
174
+ this.#fire('connect', peer);
175
+ } else if (oldStatus !== 'disconnected' && peer.status === 'disconnected') {
176
+ this.#fire('disconnect', peer);
177
+ }
178
+
179
+ return peer;
180
+ }
181
+
182
+ /**
183
+ * Mark a peer as connected with optional transport/endpoint metadata.
184
+ *
185
+ * @param {string} fingerprint
186
+ * @param {object} [opts]
187
+ * @param {string} [opts.transport]
188
+ * @param {string} [opts.endpoint]
189
+ * @returns {PeerState}
190
+ */
191
+ connect(fingerprint, opts = {}) {
192
+ if (!this.#peers.has(fingerprint)) {
193
+ this.addPeer(fingerprint, opts);
194
+ }
195
+ this.updatePeer(fingerprint, {
196
+ status: 'connected',
197
+ transport: opts.transport || null,
198
+ endpoint: opts.endpoint || null,
199
+ });
200
+ return this.#peers.get(fingerprint);
201
+ }
202
+
203
+ /**
204
+ * Mark a peer as disconnected and clear its transport.
205
+ *
206
+ * @param {string} fingerprint
207
+ */
208
+ disconnect(fingerprint) {
209
+ const peer = this.#peers.get(fingerprint);
210
+ if (!peer) return;
211
+ this.updatePeer(fingerprint, { status: 'disconnected', transport: null });
212
+ }
213
+
214
+ /**
215
+ * Disconnect every known peer.
216
+ */
217
+ disconnectAll() {
218
+ for (const fingerprint of this.#peers.keys()) {
219
+ this.disconnect(fingerprint);
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Remove a peer from the registry entirely.
225
+ *
226
+ * @param {string} fingerprint
227
+ * @returns {boolean} true if the peer existed
228
+ */
229
+ removePeer(fingerprint) {
230
+ return this.#peers.delete(fingerprint);
231
+ }
232
+
233
+ // -- Queries ------------------------------------------------------------
234
+
235
+ /**
236
+ * List peers, optionally filtering by status or minimum trust level.
237
+ *
238
+ * @param {object} [filter]
239
+ * @param {string} [filter.status]
240
+ * @param {number} [filter.minTrust]
241
+ * @returns {PeerState[]}
242
+ */
243
+ listPeers(filter = {}) {
244
+ let peers = [...this.#peers.values()];
245
+ if (filter.status) {
246
+ peers = peers.filter(p => p.status === filter.status);
247
+ }
248
+ if (filter.minTrust !== undefined) {
249
+ peers = peers.filter(p => p.trustLevel >= filter.minTrust);
250
+ }
251
+ return peers;
252
+ }
253
+
254
+ /**
255
+ * Get a specific peer by fingerprint.
256
+ *
257
+ * @param {string} fingerprint
258
+ * @returns {PeerState|null}
259
+ */
260
+ getPeer(fingerprint) {
261
+ return this.#peers.get(fingerprint) || null;
262
+ }
263
+
264
+ // -- Lifecycle callbacks ------------------------------------------------
265
+
266
+ /**
267
+ * Register a callback for when a peer becomes connected/authenticated.
268
+ * @param {Function} cb - Receives PeerState
269
+ */
270
+ onPeerConnect(cb) {
271
+ this.#callbacks.connect.push(cb);
272
+ }
273
+
274
+ /**
275
+ * Register a callback for when a peer disconnects.
276
+ * @param {Function} cb - Receives PeerState
277
+ */
278
+ onPeerDisconnect(cb) {
279
+ this.#callbacks.disconnect.push(cb);
280
+ }
281
+
282
+ /**
283
+ * Register a callback for when a new peer is discovered.
284
+ * @param {Function} cb - Receives PeerState
285
+ */
286
+ onPeerDiscovered(cb) {
287
+ this.#callbacks.discovered.push(cb);
288
+ }
289
+
290
+ // -- Discovery ----------------------------------------------------------
291
+
292
+ /**
293
+ * Process a batch of discovered peers (e.g. from relay or mDNS).
294
+ * Adds them to the registry and fires 'discovered' callbacks.
295
+ *
296
+ * @param {object[]} peers - Array of { fingerprint, ...info }
297
+ */
298
+ discovered(peers) {
299
+ for (const info of peers) {
300
+ const peer = this.addPeer(info.fingerprint, info);
301
+ this.#fire('discovered', peer);
302
+ }
303
+ }
304
+
305
+ // -- Capabilities -------------------------------------------------------
306
+
307
+ /**
308
+ * Set the capabilities this node advertises to peers.
309
+ *
310
+ * @param {string[]} capabilities
311
+ */
312
+ advertise(capabilities) {
313
+ this.#ownCapabilities = [...capabilities];
314
+ }
315
+
316
+ /**
317
+ * Get the currently advertised capabilities.
318
+ *
319
+ * @returns {string[]}
320
+ */
321
+ getAdvertisedCapabilities() {
322
+ return [...this.#ownCapabilities];
323
+ }
324
+
325
+ // -- Statistics ---------------------------------------------------------
326
+
327
+ /**
328
+ * Get aggregate connection statistics.
329
+ *
330
+ * @returns {{ total: number, connected: number, disconnected: number, connecting: number }}
331
+ */
332
+ getStats() {
333
+ const peers = [...this.#peers.values()];
334
+ return {
335
+ total: peers.length,
336
+ connected: peers.filter(
337
+ p => p.status === 'connected' || p.status === 'authenticated',
338
+ ).length,
339
+ disconnected: peers.filter(p => p.status === 'disconnected').length,
340
+ connecting: peers.filter(p => p.status === 'connecting').length,
341
+ };
342
+ }
343
+
344
+ /** @returns {number} */
345
+ get size() {
346
+ return this.#peers.size;
347
+ }
348
+
349
+ // -- Serialization ------------------------------------------------------
350
+
351
+ /**
352
+ * Serialize all peers to a JSON-safe array.
353
+ * @returns {object[]}
354
+ */
355
+ toJSON() {
356
+ return [...this.#peers.values()].map(p => p.toJSON());
357
+ }
358
+
359
+ /**
360
+ * Re-hydrate a MeshPeerManager from serialized data.
361
+ *
362
+ * @param {object[]} data
363
+ * @returns {MeshPeerManager}
364
+ */
365
+ static fromJSON(data) {
366
+ const mgr = new MeshPeerManager();
367
+ for (const item of data) {
368
+ mgr.#peers.set(item.fingerprint, PeerState.fromJSON(item));
369
+ }
370
+ return mgr;
371
+ }
372
+
373
+ // -- Internal -----------------------------------------------------------
374
+
375
+ /**
376
+ * Fire all callbacks for a given event, swallowing listener errors.
377
+ * @param {string} event
378
+ * @param {*} data
379
+ */
380
+ #fire(event, data) {
381
+ for (const cb of this.#callbacks[event] || []) {
382
+ try {
383
+ cb(data);
384
+ } catch {
385
+ /* listener errors do not propagate */
386
+ }
387
+ }
388
+ }
389
+ }
390
+
391
+ export { PEER_STATUSES };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * silent-catch.mjs — debug-gated structured logger for the
3
+ * `try { … } catch { /* ignore *\/ }` pattern.
4
+ *
5
+ * Vendored from clawser-silent-catch.mjs (fully standalone, no other
6
+ * clawser-app imports) so this package doesn't need to reach into web/.
7
+ *
8
+ * Replaces silent catches with an opt-in inspectable record. Default
9
+ * behaviour is unchanged (silent), so this is a drop-in replacement.
10
+ * Users surface the events by enabling debug mode:
11
+ *
12
+ * localStorage.setItem('clawser_debug', 'true') // persistent
13
+ * // or, in DevTools: clawserDebug.enable()
14
+ */
15
+
16
+ let enabled = false;
17
+ try {
18
+ if (typeof localStorage !== 'undefined') {
19
+ enabled = localStorage.getItem('clawser_debug') === 'true';
20
+ }
21
+ } catch {
22
+ // localStorage may throw in privacy / sandbox contexts — treat as disabled
23
+ }
24
+
25
+ /** Re-check the localStorage flag; called by clawserDebug.enable/disable. */
26
+ export function refreshSilentCatchState() {
27
+ try {
28
+ if (typeof localStorage !== 'undefined') {
29
+ enabled = localStorage.getItem('clawser_debug') === 'true';
30
+ }
31
+ } catch {
32
+ enabled = false;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Log a silent-catch event. No-op unless debug mode is enabled.
38
+ *
39
+ * @param {string} module — file/component (e.g. 'clawser-pod')
40
+ * @param {string} operation — what was attempted (e.g. 'relay-disconnect')
41
+ * @param {*} error — the caught value
42
+ * @param {object} [context] — extra structured fields
43
+ */
44
+ export function silentCatch(module, operation, error, context) {
45
+ // Re-read the flag each call so toggles in DevTools take effect without
46
+ // restart. Cheap (one localStorage hit per silent catch in debug mode;
47
+ // catches happen rarely on hot paths).
48
+ if (!enabled) {
49
+ refreshSilentCatchState();
50
+ if (!enabled) return;
51
+ }
52
+ const entry = { module, operation, error: error?.message || String(error) };
53
+ if (context) Object.assign(entry, context);
54
+ console.warn('[clawser:silent-catch]', entry);
55
+ }