@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,727 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-health.js — Automatic health monitoring with self-healing.
4
+ *
5
+ * Watches heartbeats, detects failures, triggers workload migration.
6
+ * Enables "self-healing personal mesh infrastructure" scenario.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-health.test.mjs
10
+ */
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Constants
14
+ // ---------------------------------------------------------------------------
15
+
16
+ /** Default health monitoring thresholds. */
17
+ export const HEALTH_DEFAULTS = Object.freeze({
18
+ heartbeatIntervalMs: 10000,
19
+ heartbeatTimeoutMs: 5000,
20
+ maxMissedHeartbeats: 3,
21
+ degradedThresholdMs: 2000,
22
+ })
23
+
24
+ /** Possible peer health statuses. */
25
+ export const HEALTH_STATUSES = Object.freeze(['healthy', 'degraded', 'failed', 'unknown'])
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // PeerHealth — snapshot of a single peer's health state
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /**
32
+ * Immutable snapshot of health data for a single peer.
33
+ */
34
+ export class PeerHealth {
35
+ /** @type {string} */
36
+ podId
37
+
38
+ /** @type {'healthy'|'degraded'|'failed'|'unknown'} */
39
+ status
40
+
41
+ /** @type {number} */
42
+ lastHeartbeat
43
+
44
+ /** @type {number} */
45
+ missedHeartbeats
46
+
47
+ /** @type {number} */
48
+ latencyMs
49
+
50
+ /** @type {number} */
51
+ uptimeMs
52
+
53
+ /**
54
+ * @param {object} opts
55
+ * @param {string} opts.podId - Peer pod identifier
56
+ * @param {'healthy'|'degraded'|'failed'|'unknown'} [opts.status='unknown']
57
+ * @param {number} [opts.lastHeartbeat=0]
58
+ * @param {number} [opts.missedHeartbeats=0]
59
+ * @param {number} [opts.latencyMs=0]
60
+ * @param {number} [opts.uptimeMs=0]
61
+ */
62
+ constructor({
63
+ podId,
64
+ status = 'unknown',
65
+ lastHeartbeat = 0,
66
+ missedHeartbeats = 0,
67
+ latencyMs = 0,
68
+ uptimeMs = 0,
69
+ }) {
70
+ this.podId = podId
71
+ this.status = status
72
+ this.lastHeartbeat = lastHeartbeat
73
+ this.missedHeartbeats = missedHeartbeats
74
+ this.latencyMs = latencyMs
75
+ this.uptimeMs = uptimeMs
76
+ }
77
+
78
+ /**
79
+ * Serialize to a JSON-safe object.
80
+ * @returns {object}
81
+ */
82
+ toJSON() {
83
+ return {
84
+ podId: this.podId,
85
+ status: this.status,
86
+ lastHeartbeat: this.lastHeartbeat,
87
+ missedHeartbeats: this.missedHeartbeats,
88
+ latencyMs: this.latencyMs,
89
+ uptimeMs: this.uptimeMs,
90
+ }
91
+ }
92
+ }
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // MigrationResult — outcome of a workload migration
96
+ // ---------------------------------------------------------------------------
97
+
98
+ /**
99
+ * Result of a workload migration operation.
100
+ */
101
+ export class MigrationResult {
102
+ /** @type {boolean} */
103
+ success
104
+
105
+ /** @type {string} */
106
+ fromPod
107
+
108
+ /** @type {string} */
109
+ toPod
110
+
111
+ /** @type {string|null} */
112
+ workload
113
+
114
+ /** @type {number} */
115
+ durationMs
116
+
117
+ /** @type {string|null} */
118
+ error
119
+
120
+ /**
121
+ * @param {object} opts
122
+ * @param {boolean} opts.success
123
+ * @param {string} opts.fromPod
124
+ * @param {string} opts.toPod
125
+ * @param {string} [opts.workload=null]
126
+ * @param {number} [opts.durationMs=0]
127
+ * @param {string} [opts.error=null]
128
+ */
129
+ constructor({
130
+ success,
131
+ fromPod,
132
+ toPod,
133
+ workload = null,
134
+ durationMs = 0,
135
+ error = null,
136
+ }) {
137
+ this.success = success
138
+ this.fromPod = fromPod
139
+ this.toPod = toPod
140
+ this.workload = workload
141
+ this.durationMs = durationMs
142
+ this.error = error
143
+ }
144
+
145
+ /**
146
+ * Serialize to a JSON-safe object.
147
+ * @returns {object}
148
+ */
149
+ toJSON() {
150
+ return {
151
+ success: this.success,
152
+ fromPod: this.fromPod,
153
+ toPod: this.toPod,
154
+ workload: this.workload,
155
+ durationMs: this.durationMs,
156
+ error: this.error,
157
+ }
158
+ }
159
+ }
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // HealthMonitor — periodic heartbeat checks with status tracking
163
+ // ---------------------------------------------------------------------------
164
+
165
+ /**
166
+ * Monitors peer health via periodic heartbeat pings.
167
+ *
168
+ * Each tick:
169
+ * 1. Increments missedHeartbeats for all tracked peers
170
+ * 2. Sends a heartbeat ping to each active session
171
+ * 3. Updates status based on missed count and latency
172
+ *
173
+ * When `recordHeartbeat(podId, latencyMs)` is called (externally, when a
174
+ * heartbeat response arrives), it resets the missed count and updates latency.
175
+ *
176
+ * Status transitions:
177
+ * - unknown -> healthy (on first heartbeat)
178
+ * - healthy -> degraded (high latency OR 1 miss)
179
+ * - degraded -> failed (>= maxMissedHeartbeats)
180
+ * - failed -> healthy (on heartbeat after failure, emits 'recovered')
181
+ */
182
+ export class HealthMonitor {
183
+ /** @type {object} sessions provider with listSessions() */
184
+ #sessions
185
+
186
+ /** @type {object|null} trust provider with getReputation(podId) */
187
+ #trust
188
+
189
+ /** @type {Function} */
190
+ #onLog
191
+
192
+ /** @type {Map<string, PeerHealth>} podId -> PeerHealth */
193
+ #peers = new Map()
194
+
195
+ /** @type {Map<string, number>} podId -> timestamp when first tracked */
196
+ #firstSeen = new Map()
197
+
198
+ /** @type {object} current thresholds (mutable copy of HEALTH_DEFAULTS) */
199
+ #thresholds = { ...HEALTH_DEFAULTS }
200
+
201
+ /** @type {*} interval timer ID */
202
+ #intervalId = null
203
+
204
+ /** @type {Map<string, Set<Function>>} event -> listeners */
205
+ #listeners = new Map()
206
+
207
+ /**
208
+ * @param {object} opts
209
+ * @param {object} opts.sessions - Object with listSessions() -> array of { remotePodId, send(type, payload), sessionId }
210
+ * @param {object} [opts.trust] - Object with getReputation(podId) -> number
211
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
212
+ */
213
+ constructor({ sessions, trust, onLog }) {
214
+ if (!sessions || typeof sessions.listSessions !== 'function') {
215
+ throw new Error('sessions with listSessions() method is required')
216
+ }
217
+ this.#sessions = sessions
218
+ this.#trust = trust || null
219
+ this.#onLog = onLog || (() => {})
220
+ }
221
+
222
+ // -- Lifecycle ------------------------------------------------------------
223
+
224
+ /**
225
+ * Start periodic heartbeat checks.
226
+ *
227
+ * @param {number} [intervalMs] - Override default heartbeat interval
228
+ */
229
+ start(intervalMs) {
230
+ this.stop()
231
+ const ms = intervalMs ?? this.#thresholds.heartbeatIntervalMs
232
+ this.#intervalId = globalThis.setInterval(() => this.#tick(), ms)
233
+ this.#onLog(2, `Health monitor started (interval=${ms}ms)`)
234
+ }
235
+
236
+ /**
237
+ * Stop periodic heartbeat checks.
238
+ */
239
+ stop() {
240
+ if (this.#intervalId !== null) {
241
+ globalThis.clearInterval(this.#intervalId)
242
+ this.#intervalId = null
243
+ this.#onLog(2, 'Health monitor stopped')
244
+ }
245
+ }
246
+
247
+ // -- Heartbeat recording --------------------------------------------------
248
+
249
+ /**
250
+ * Record a heartbeat response from a peer.
251
+ * Called externally when a heartbeat pong is received.
252
+ *
253
+ * @param {string} podId - Peer pod identifier
254
+ * @param {number} [latencyMs=0] - Round-trip latency in milliseconds
255
+ */
256
+ recordHeartbeat(podId, latencyMs = 0) {
257
+ const now = Date.now()
258
+ const existing = this.#peers.get(podId)
259
+ const previousStatus = existing ? existing.status : 'unknown'
260
+
261
+ if (!this.#firstSeen.has(podId)) {
262
+ this.#firstSeen.set(podId, now)
263
+ }
264
+ const uptimeMs = now - this.#firstSeen.get(podId)
265
+
266
+ // Determine new status based on latency
267
+ let newStatus = 'healthy'
268
+ if (latencyMs > this.#thresholds.degradedThresholdMs) {
269
+ newStatus = 'degraded'
270
+ }
271
+
272
+ const health = new PeerHealth({
273
+ podId,
274
+ status: newStatus,
275
+ lastHeartbeat: now,
276
+ missedHeartbeats: 0,
277
+ latencyMs,
278
+ uptimeMs,
279
+ })
280
+
281
+ this.#peers.set(podId, health)
282
+
283
+ // Emit status transition events
284
+ if (previousStatus === 'failed') {
285
+ this.#emit('recovered', health)
286
+ this.#onLog(2, `Peer ${podId} recovered`)
287
+ }
288
+ if (newStatus === 'healthy' && previousStatus !== 'healthy') {
289
+ this.#emit('healthy', health)
290
+ }
291
+ if (newStatus === 'degraded') {
292
+ this.#emit('degraded', health)
293
+ }
294
+ }
295
+
296
+ // -- Status queries -------------------------------------------------------
297
+
298
+ /**
299
+ * Get health status for all tracked peers.
300
+ *
301
+ * @returns {Map<string, PeerHealth>}
302
+ */
303
+ getStatus() {
304
+ return new Map(this.#peers)
305
+ }
306
+
307
+ /**
308
+ * Get health data for a single peer.
309
+ *
310
+ * @param {string} podId - Peer pod identifier
311
+ * @returns {PeerHealth|null}
312
+ */
313
+ getPeerHealth(podId) {
314
+ return this.#peers.get(podId) || null
315
+ }
316
+
317
+ // -- Configuration --------------------------------------------------------
318
+
319
+ /**
320
+ * Override default health monitoring thresholds.
321
+ *
322
+ * @param {object} thresholds - Partial threshold overrides
323
+ */
324
+ setThresholds(thresholds) {
325
+ if (thresholds && typeof thresholds === 'object') {
326
+ Object.assign(this.#thresholds, thresholds)
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Return current threshold configuration.
332
+ * @returns {object}
333
+ */
334
+ getThresholds() {
335
+ return { ...this.#thresholds }
336
+ }
337
+
338
+ /**
339
+ * Reset heartbeat history for a specific peer.
340
+ * @param {string} podId
341
+ */
342
+ clearHeartbeat(podId) {
343
+ const peer = this.#peers.get(podId)
344
+ if (peer) {
345
+ peer.lastHeartbeat = null
346
+ peer.missedHeartbeats = 0
347
+ peer.latencyMs = null
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Completely remove a peer from monitoring.
353
+ * @param {string} podId
354
+ * @returns {boolean}
355
+ */
356
+ untrack(podId) {
357
+ return this.#peers.delete(podId)
358
+ }
359
+
360
+ // -- Events ---------------------------------------------------------------
361
+
362
+ /**
363
+ * Register a listener for a health event.
364
+ * Events: 'healthy', 'degraded', 'failed', 'recovered'
365
+ *
366
+ * @param {string} event - Event name
367
+ * @param {Function} cb - Callback function
368
+ */
369
+ on(event, cb) {
370
+ if (!this.#listeners.has(event)) {
371
+ this.#listeners.set(event, new Set())
372
+ }
373
+ this.#listeners.get(event).add(cb)
374
+ }
375
+
376
+ /**
377
+ * Remove a listener for a health event.
378
+ *
379
+ * @param {string} event - Event name
380
+ * @param {Function} cb - Callback function
381
+ */
382
+ off(event, cb) {
383
+ const set = this.#listeners.get(event)
384
+ if (set) set.delete(cb)
385
+ }
386
+
387
+ // -- Serialization --------------------------------------------------------
388
+
389
+ /**
390
+ * Serialize the monitor state.
391
+ * @returns {object}
392
+ */
393
+ toJSON() {
394
+ const peers = {}
395
+ for (const [podId, health] of this.#peers) {
396
+ peers[podId] = health.toJSON()
397
+ }
398
+ return {
399
+ peers,
400
+ thresholds: { ...this.#thresholds },
401
+ running: this.#intervalId !== null,
402
+ }
403
+ }
404
+
405
+ // -- Internal -------------------------------------------------------------
406
+
407
+ /**
408
+ * Single heartbeat tick: increment missed counts, send pings, update statuses.
409
+ */
410
+ #tick() {
411
+ const sessions = this.#sessions.listSessions()
412
+
413
+ // Ensure all session peers are tracked
414
+ for (const session of sessions) {
415
+ if (!this.#peers.has(session.remotePodId)) {
416
+ this.#peers.set(session.remotePodId, new PeerHealth({
417
+ podId: session.remotePodId,
418
+ }))
419
+ if (!this.#firstSeen.has(session.remotePodId)) {
420
+ this.#firstSeen.set(session.remotePodId, Date.now())
421
+ }
422
+ }
423
+ }
424
+
425
+ // Increment missed heartbeats for all tracked peers
426
+ for (const [podId, health] of this.#peers) {
427
+ const newMissed = health.missedHeartbeats + 1
428
+ const uptimeMs = Date.now() - (this.#firstSeen.get(podId) || Date.now())
429
+
430
+ let newStatus = health.status
431
+ if (newMissed >= this.#thresholds.maxMissedHeartbeats) {
432
+ newStatus = 'failed'
433
+ } else if (newMissed >= 1 && health.status !== 'failed') {
434
+ newStatus = 'degraded'
435
+ }
436
+
437
+ const previousStatus = health.status
438
+ const updated = new PeerHealth({
439
+ podId,
440
+ status: newStatus,
441
+ lastHeartbeat: health.lastHeartbeat,
442
+ missedHeartbeats: newMissed,
443
+ latencyMs: health.latencyMs,
444
+ uptimeMs,
445
+ })
446
+ this.#peers.set(podId, updated)
447
+
448
+ // Emit status transition events
449
+ if (newStatus === 'degraded' && previousStatus !== 'degraded' && previousStatus !== 'failed') {
450
+ this.#emit('degraded', updated)
451
+ this.#onLog(1, `Peer ${podId} degraded (missed=${newMissed})`)
452
+ }
453
+ if (newStatus === 'failed' && previousStatus !== 'failed') {
454
+ this.#emit('failed', updated)
455
+ this.#onLog(0, `Peer ${podId} failed (missed=${newMissed})`)
456
+ }
457
+ }
458
+
459
+ // Send heartbeat pings to all sessions
460
+ for (const session of sessions) {
461
+ try {
462
+ session.send('heartbeat:ping', { timestamp: Date.now() })
463
+ } catch (err) {
464
+ this.#onLog(0, `Failed to send heartbeat to ${session.remotePodId}: ${err.message}`)
465
+ }
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Emit an event to all registered listeners, swallowing errors.
471
+ *
472
+ * @param {string} event - Event name
473
+ * @param {*} data - Event data
474
+ */
475
+ #emit(event, data) {
476
+ const set = this.#listeners.get(event)
477
+ if (!set) return
478
+ for (const cb of [...set]) {
479
+ try {
480
+ cb(data)
481
+ } catch {
482
+ /* listener errors do not propagate */
483
+ }
484
+ }
485
+ }
486
+ }
487
+
488
+ // ---------------------------------------------------------------------------
489
+ // AutoMigrator — automatic workload migration on peer failure
490
+ // ---------------------------------------------------------------------------
491
+
492
+ /**
493
+ * Listens to HealthMonitor failure events and automatically migrates
494
+ * workloads away from failed peers.
495
+ */
496
+ export class AutoMigrator {
497
+ /** @type {HealthMonitor} */
498
+ #healthMonitor
499
+
500
+ /** @type {object} orchestrator with drainPod(), listPods(), deploySkill() */
501
+ #orchestrator
502
+
503
+ /** @type {Function} */
504
+ #onLog
505
+
506
+ /** @type {boolean} */
507
+ #enabled = false
508
+
509
+ /** @type {string[]|null} services to migrate (null = all) */
510
+ #services = null
511
+
512
+ /** @type {string[]|null} preferred failover targets in priority order */
513
+ #failoverPriority = null
514
+
515
+ /** @type {Function|null} bound handler reference for cleanup */
516
+ #failedHandler = null
517
+
518
+ /** @type {Map<string, Set<Function>>} event -> listeners */
519
+ #listeners = new Map()
520
+
521
+ /**
522
+ * @param {object} opts
523
+ * @param {HealthMonitor} opts.healthMonitor - Health monitor to listen to
524
+ * @param {object} opts.orchestrator - Object with drainPod(podId), listPods(), deploySkill(podId, skill)
525
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
526
+ */
527
+ constructor({ healthMonitor, orchestrator, onLog }) {
528
+ if (!healthMonitor) {
529
+ throw new Error('healthMonitor is required')
530
+ }
531
+ if (!orchestrator || typeof orchestrator.drainPod !== 'function') {
532
+ throw new Error('orchestrator with drainPod() method is required')
533
+ }
534
+ this.#healthMonitor = healthMonitor
535
+ this.#orchestrator = orchestrator
536
+ this.#onLog = onLog || (() => {})
537
+ }
538
+
539
+ // -- Lifecycle ------------------------------------------------------------
540
+
541
+ /**
542
+ * Enable automatic migration on peer failure.
543
+ *
544
+ * @param {object} [opts]
545
+ * @param {string[]} [opts.services] - Only migrate these services (null = all)
546
+ * @param {string[]} [opts.failoverPriority] - Preferred target pods in order
547
+ */
548
+ enable(opts) {
549
+ if (this.#enabled) return
550
+
551
+ this.#services = opts?.services || null
552
+ this.#failoverPriority = opts?.failoverPriority || null
553
+
554
+ this.#failedHandler = (health) => this.#onPeerFailed(health.podId)
555
+ this.#healthMonitor.on('failed', this.#failedHandler)
556
+ this.#enabled = true
557
+
558
+ this.#onLog(2, 'AutoMigrator enabled')
559
+ }
560
+
561
+ /**
562
+ * Disable automatic migration.
563
+ */
564
+ disable() {
565
+ if (!this.#enabled) return
566
+
567
+ if (this.#failedHandler) {
568
+ this.#healthMonitor.off('failed', this.#failedHandler)
569
+ this.#failedHandler = null
570
+ }
571
+ this.#enabled = false
572
+
573
+ this.#onLog(2, 'AutoMigrator disabled')
574
+ }
575
+
576
+ // -- Manual migration -----------------------------------------------------
577
+
578
+ /**
579
+ * Manually trigger migration from one pod to another.
580
+ *
581
+ * @param {string} fromPodId - Pod to drain workload from
582
+ * @param {string} [toPodId] - Target pod (auto-selected if omitted)
583
+ * @returns {Promise<MigrationResult>}
584
+ */
585
+ async migrateNow(fromPodId, toPodId) {
586
+ const startTime = Date.now()
587
+ const target = toPodId || this.#selectTarget(fromPodId)
588
+
589
+ if (!target) {
590
+ const result = new MigrationResult({
591
+ success: false,
592
+ fromPod: fromPodId,
593
+ toPod: '',
594
+ error: 'No healthy target pod available',
595
+ durationMs: Date.now() - startTime,
596
+ })
597
+ this.#emit('migration-failed', result)
598
+ return result
599
+ }
600
+
601
+ this.#emit('migrating', { fromPod: fromPodId, toPod: target })
602
+ this.#onLog(2, `Migrating workload from ${fromPodId} to ${target}`)
603
+
604
+ try {
605
+ await this.#orchestrator.drainPod(fromPodId)
606
+
607
+ const result = new MigrationResult({
608
+ success: true,
609
+ fromPod: fromPodId,
610
+ toPod: target,
611
+ workload: 'all',
612
+ durationMs: Date.now() - startTime,
613
+ })
614
+ this.#emit('migrated', result)
615
+ this.#onLog(2, `Migration complete: ${fromPodId} -> ${target} (${result.durationMs}ms)`)
616
+ return result
617
+ } catch (err) {
618
+ const result = new MigrationResult({
619
+ success: false,
620
+ fromPod: fromPodId,
621
+ toPod: target,
622
+ error: err.message,
623
+ durationMs: Date.now() - startTime,
624
+ })
625
+ this.#emit('migration-failed', result)
626
+ this.#onLog(0, `Migration failed: ${fromPodId} -> ${target}: ${err.message}`)
627
+ return result
628
+ }
629
+ }
630
+
631
+ // -- Events ---------------------------------------------------------------
632
+
633
+ /**
634
+ * Register a listener for a migration event.
635
+ * Events: 'migrating', 'migrated', 'migration-failed'
636
+ *
637
+ * @param {string} event - Event name
638
+ * @param {Function} cb - Callback function
639
+ */
640
+ on(event, cb) {
641
+ if (!this.#listeners.has(event)) {
642
+ this.#listeners.set(event, new Set())
643
+ }
644
+ this.#listeners.get(event).add(cb)
645
+ }
646
+
647
+ /**
648
+ * Remove a listener for a migration event.
649
+ *
650
+ * @param {string} event - Event name
651
+ * @param {Function} cb - Callback function
652
+ */
653
+ off(event, cb) {
654
+ const set = this.#listeners.get(event)
655
+ if (set) set.delete(cb)
656
+ }
657
+
658
+ // -- Internal -------------------------------------------------------------
659
+
660
+ /**
661
+ * Select the best target pod for migration.
662
+ * Prefers failoverPriority list, then picks the healthiest peer.
663
+ *
664
+ * @param {string} fromPodId - Pod being drained (excluded from candidates)
665
+ * @returns {string|null}
666
+ */
667
+ #selectTarget(fromPodId) {
668
+ const status = this.#healthMonitor.getStatus()
669
+
670
+ // Try failover priority list first
671
+ if (this.#failoverPriority) {
672
+ for (const podId of this.#failoverPriority) {
673
+ if (podId === fromPodId) continue
674
+ const health = status.get(podId)
675
+ if (health && (health.status === 'healthy' || health.status === 'degraded')) {
676
+ return podId
677
+ }
678
+ }
679
+ }
680
+
681
+ // Fall back to healthiest available peer
682
+ let bestPod = null
683
+ let bestScore = -Infinity
684
+
685
+ for (const [podId, health] of status) {
686
+ if (podId === fromPodId) continue
687
+ if (health.status === 'failed') continue
688
+
689
+ // Score: lower missed heartbeats and lower latency is better
690
+ const score = -(health.missedHeartbeats * 1000 + health.latencyMs)
691
+ if (score > bestScore) {
692
+ bestScore = score
693
+ bestPod = podId
694
+ }
695
+ }
696
+
697
+ return bestPod
698
+ }
699
+
700
+ /**
701
+ * Handler for peer failure events from the health monitor.
702
+ *
703
+ * @param {string} podId - Failed peer pod identifier
704
+ */
705
+ async #onPeerFailed(podId) {
706
+ this.#onLog(1, `Auto-migration triggered for failed peer: ${podId}`)
707
+ await this.migrateNow(podId)
708
+ }
709
+
710
+ /**
711
+ * Emit an event to all registered listeners, swallowing errors.
712
+ *
713
+ * @param {string} event - Event name
714
+ * @param {*} data - Event data
715
+ */
716
+ #emit(event, data) {
717
+ const set = this.#listeners.get(event)
718
+ if (!set) return
719
+ for (const cb of [...set]) {
720
+ try {
721
+ cb(data)
722
+ } catch {
723
+ /* listener errors do not propagate */
724
+ }
725
+ }
726
+ }
727
+ }