@johnhenry/browsermesh-pod 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/LICENSE +21 -0
- package/README.md +200 -0
- package/package.json +42 -0
- package/src/capabilities.mjs +63 -0
- package/src/detect-kind.mjs +55 -0
- package/src/discovery.mjs +177 -0
- package/src/index.mjs +16 -0
- package/src/injected-pod.mjs +148 -0
- package/src/messages.mjs +135 -0
- package/src/pod.mjs +427 -0
- package/src/runtime.mjs +105 -0
- package/src/transport.mjs +164 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* injected-pod.mjs — Lightweight pod for injection into arbitrary pages.
|
|
3
|
+
*
|
|
4
|
+
* Extends Pod with page-context capabilities: text extraction, structured
|
|
5
|
+
* data extraction, and a visual overlay indicator. Designed for Chrome
|
|
6
|
+
* extension injection or bookmarklet use.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { Pod } from './pod.mjs'
|
|
10
|
+
|
|
11
|
+
const OVERLAY_ID = '__pod_overlay__'
|
|
12
|
+
|
|
13
|
+
export class InjectedPod extends Pod {
|
|
14
|
+
#extensionBridge = null
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} [opts]
|
|
18
|
+
* @param {object} [opts.extensionBridge] - Chrome extension port for relaying
|
|
19
|
+
*/
|
|
20
|
+
constructor(opts = {}) {
|
|
21
|
+
super()
|
|
22
|
+
this.#extensionBridge = opts.extensionBridge || null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Page context: URL, title, origin, favicon */
|
|
26
|
+
get pageContext() {
|
|
27
|
+
const g = this._getGlobal()
|
|
28
|
+
if (!g?.document) return null
|
|
29
|
+
return {
|
|
30
|
+
url: g.location?.href || '',
|
|
31
|
+
title: g.document.title || '',
|
|
32
|
+
origin: g.location?.origin || '',
|
|
33
|
+
favicon: g.document.querySelector('link[rel~="icon"]')?.href || '',
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Extract visible text content from the page.
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
extractText() {
|
|
42
|
+
const g = this._getGlobal()
|
|
43
|
+
if (!g?.document?.body) return ''
|
|
44
|
+
return g.document.body.innerText || ''
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Extract structured page data.
|
|
49
|
+
* @returns {object}
|
|
50
|
+
*/
|
|
51
|
+
extractStructured() {
|
|
52
|
+
const g = this._getGlobal()
|
|
53
|
+
if (!g?.document) return {}
|
|
54
|
+
|
|
55
|
+
const doc = g.document
|
|
56
|
+
const metas = {}
|
|
57
|
+
for (const el of doc.querySelectorAll('meta[name], meta[property]')) {
|
|
58
|
+
const key = el.getAttribute('name') || el.getAttribute('property')
|
|
59
|
+
if (key) metas[key] = el.getAttribute('content') || ''
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const headings = []
|
|
63
|
+
for (const el of doc.querySelectorAll('h1, h2, h3')) {
|
|
64
|
+
headings.push({ tag: el.tagName.toLowerCase(), text: el.textContent?.trim() || '' })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
title: doc.title || '',
|
|
69
|
+
url: g.location?.href || '',
|
|
70
|
+
meta: metas,
|
|
71
|
+
headings,
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Show a floating overlay indicator on the page.
|
|
77
|
+
* Blue circle (48px) fixed at bottom-right with "Pod" label.
|
|
78
|
+
*/
|
|
79
|
+
showOverlay() {
|
|
80
|
+
const g = this._getGlobal()
|
|
81
|
+
if (!g?.document) return
|
|
82
|
+
|
|
83
|
+
if (g.document.getElementById(OVERLAY_ID)) return
|
|
84
|
+
|
|
85
|
+
const el = g.document.createElement('div')
|
|
86
|
+
el.id = OVERLAY_ID
|
|
87
|
+
Object.assign(el.style, {
|
|
88
|
+
position: 'fixed',
|
|
89
|
+
bottom: '16px',
|
|
90
|
+
right: '16px',
|
|
91
|
+
width: '48px',
|
|
92
|
+
height: '48px',
|
|
93
|
+
borderRadius: '50%',
|
|
94
|
+
background: '#3b82f6',
|
|
95
|
+
color: '#fff',
|
|
96
|
+
display: 'flex',
|
|
97
|
+
alignItems: 'center',
|
|
98
|
+
justifyContent: 'center',
|
|
99
|
+
fontSize: '12px',
|
|
100
|
+
fontWeight: 'bold',
|
|
101
|
+
fontFamily: 'system-ui, sans-serif',
|
|
102
|
+
zIndex: '2147483647',
|
|
103
|
+
cursor: 'pointer',
|
|
104
|
+
boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
|
|
105
|
+
userSelect: 'none',
|
|
106
|
+
})
|
|
107
|
+
el.textContent = 'Pod'
|
|
108
|
+
el.title = `Pod: ${this.podId?.slice(0, 8) || 'booting'}`
|
|
109
|
+
g.document.body.appendChild(el)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Hide the overlay indicator. */
|
|
113
|
+
hideOverlay() {
|
|
114
|
+
const g = this._getGlobal()
|
|
115
|
+
if (!g?.document) return
|
|
116
|
+
const el = g.document.getElementById(OVERLAY_ID)
|
|
117
|
+
if (el) el.remove()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
_onReady() {
|
|
121
|
+
this.showOverlay()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
_onMessage(msg) {
|
|
125
|
+
// Forward to extension bridge if available
|
|
126
|
+
if (this.#extensionBridge && typeof this.#extensionBridge.postMessage === 'function') {
|
|
127
|
+
this.#extensionBridge.postMessage(msg)
|
|
128
|
+
}
|
|
129
|
+
this.emit('pod:message', msg)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Emit helper for subclass/external use — dispatches through the same
|
|
133
|
+
* listener registry that on()/off() populate. */
|
|
134
|
+
emit(event, data) {
|
|
135
|
+
this._emit(event, data)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @internal — access the global reference set during boot */
|
|
139
|
+
_getGlobal() {
|
|
140
|
+
// During boot, Pod stores g internally. For InjectedPod pre-boot, use globalThis
|
|
141
|
+
return globalThis
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async shutdown(opts = {}) {
|
|
145
|
+
this.hideOverlay()
|
|
146
|
+
await super.shutdown(opts)
|
|
147
|
+
}
|
|
148
|
+
}
|
package/src/messages.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* messages.mjs — Pod wire protocol message types and factories.
|
|
3
|
+
*
|
|
4
|
+
* Defines the message constants and factory functions used for pod
|
|
5
|
+
* discovery, handshake, and inter-pod communication.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// ── Message type constants ──────────────────────────────────────
|
|
9
|
+
|
|
10
|
+
export const POD_HELLO = 'pod:hello'
|
|
11
|
+
export const POD_HELLO_ACK = 'pod:hello-ack'
|
|
12
|
+
export const POD_GOODBYE = 'pod:goodbye'
|
|
13
|
+
export const POD_MESSAGE = 'pod:message'
|
|
14
|
+
export const POD_RPC_REQUEST = 'pod:rpc-request'
|
|
15
|
+
export const POD_RPC_RESPONSE = 'pod:rpc-response'
|
|
16
|
+
|
|
17
|
+
// ── Message factories ───────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Create a HELLO message for discovery / parent handshake.
|
|
21
|
+
*
|
|
22
|
+
* @param {object} opts
|
|
23
|
+
* @param {string} opts.podId - Sender's pod ID
|
|
24
|
+
* @param {string} opts.kind - Sender's pod kind
|
|
25
|
+
* @param {object} [opts.capabilities] - Sender's capabilities snapshot
|
|
26
|
+
* @returns {object}
|
|
27
|
+
*/
|
|
28
|
+
export function createHello({ podId, kind, capabilities }) {
|
|
29
|
+
return {
|
|
30
|
+
type: POD_HELLO,
|
|
31
|
+
podId,
|
|
32
|
+
kind,
|
|
33
|
+
capabilities: capabilities || null,
|
|
34
|
+
ts: Date.now(),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Create a HELLO_ACK response.
|
|
40
|
+
*
|
|
41
|
+
* @param {object} opts
|
|
42
|
+
* @param {string} opts.podId - Responder's pod ID
|
|
43
|
+
* @param {string} opts.kind - Responder's pod kind
|
|
44
|
+
* @param {string} opts.targetPodId - Original sender's pod ID
|
|
45
|
+
* @returns {object}
|
|
46
|
+
*/
|
|
47
|
+
export function createHelloAck({ podId, kind, targetPodId }) {
|
|
48
|
+
return {
|
|
49
|
+
type: POD_HELLO_ACK,
|
|
50
|
+
podId,
|
|
51
|
+
kind,
|
|
52
|
+
targetPodId,
|
|
53
|
+
ts: Date.now(),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Create a GOODBYE message (graceful shutdown announcement).
|
|
59
|
+
*
|
|
60
|
+
* @param {object} opts
|
|
61
|
+
* @param {string} opts.podId - Departing pod's ID
|
|
62
|
+
* @returns {object}
|
|
63
|
+
*/
|
|
64
|
+
export function createGoodbye({ podId }) {
|
|
65
|
+
return {
|
|
66
|
+
type: POD_GOODBYE,
|
|
67
|
+
podId,
|
|
68
|
+
ts: Date.now(),
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Create a generic inter-pod message.
|
|
74
|
+
*
|
|
75
|
+
* @param {object} opts
|
|
76
|
+
* @param {string} opts.from - Sender pod ID
|
|
77
|
+
* @param {string} opts.to - Target pod ID (or '*' for broadcast)
|
|
78
|
+
* @param {*} opts.payload - Message payload
|
|
79
|
+
* @returns {object}
|
|
80
|
+
*/
|
|
81
|
+
export function createMessage({ from, to, payload }) {
|
|
82
|
+
return {
|
|
83
|
+
type: POD_MESSAGE,
|
|
84
|
+
from,
|
|
85
|
+
to,
|
|
86
|
+
payload,
|
|
87
|
+
ts: Date.now(),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Create an RPC request message.
|
|
93
|
+
*
|
|
94
|
+
* @param {object} opts
|
|
95
|
+
* @param {string} opts.from - Sender pod ID
|
|
96
|
+
* @param {string} opts.to - Target pod ID
|
|
97
|
+
* @param {string} opts.method - RPC method name
|
|
98
|
+
* @param {*} [opts.params] - Method parameters
|
|
99
|
+
* @param {string} opts.requestId - Unique request identifier
|
|
100
|
+
* @returns {object}
|
|
101
|
+
*/
|
|
102
|
+
export function createRpcRequest({ from, to, method, params, requestId }) {
|
|
103
|
+
return {
|
|
104
|
+
type: POD_RPC_REQUEST,
|
|
105
|
+
from,
|
|
106
|
+
to,
|
|
107
|
+
method,
|
|
108
|
+
params: params ?? null,
|
|
109
|
+
requestId,
|
|
110
|
+
ts: Date.now(),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Create an RPC response message.
|
|
116
|
+
*
|
|
117
|
+
* @param {object} opts
|
|
118
|
+
* @param {string} opts.from - Responder pod ID
|
|
119
|
+
* @param {string} opts.to - Original requester pod ID
|
|
120
|
+
* @param {string} opts.requestId - Matching request identifier
|
|
121
|
+
* @param {*} [opts.result] - Success result
|
|
122
|
+
* @param {string} [opts.error] - Error message if failed
|
|
123
|
+
* @returns {object}
|
|
124
|
+
*/
|
|
125
|
+
export function createRpcResponse({ from, to, requestId, result, error }) {
|
|
126
|
+
return {
|
|
127
|
+
type: POD_RPC_RESPONSE,
|
|
128
|
+
from,
|
|
129
|
+
to,
|
|
130
|
+
requestId,
|
|
131
|
+
result: result ?? null,
|
|
132
|
+
error: error ?? null,
|
|
133
|
+
ts: Date.now(),
|
|
134
|
+
}
|
|
135
|
+
}
|
package/src/pod.mjs
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pod.mjs — Pod base class.
|
|
3
|
+
*
|
|
4
|
+
* A Pod is any execution context (browser tab, worker, Node.js process) that
|
|
5
|
+
* can execute code, receive messages, and be discovered/addressed. This base
|
|
6
|
+
* class implements the 6-phase BrowserMesh boot sequence: Install Runtime →
|
|
7
|
+
* Install Listeners → Self-Classification → Parent Handshake → Peer Discovery
|
|
8
|
+
* → Role Finalization.
|
|
9
|
+
*
|
|
10
|
+
* Transport and discovery are pluggable via adapter objects passed to boot().
|
|
11
|
+
* When no adapters are provided, Pod auto-detects: BroadcastChannel in browsers,
|
|
12
|
+
* NullTransport/NullDiscovery in Node.js.
|
|
13
|
+
*
|
|
14
|
+
* Zero Clawser imports — depends only on @johnhenry/browsermesh-primitives for identity.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { PodIdentity } from '@johnhenry/browsermesh-primitives'
|
|
18
|
+
import { detectPodKind } from './detect-kind.mjs'
|
|
19
|
+
import { detectCapabilities } from './capabilities.mjs'
|
|
20
|
+
import {
|
|
21
|
+
POD_HELLO, POD_HELLO_ACK, POD_GOODBYE, POD_MESSAGE,
|
|
22
|
+
POD_RPC_REQUEST, POD_RPC_RESPONSE,
|
|
23
|
+
createHello, createHelloAck, createGoodbye, createMessage,
|
|
24
|
+
} from './messages.mjs'
|
|
25
|
+
import { BroadcastChannelTransport, NullTransport } from './transport.mjs'
|
|
26
|
+
import { TransportDiscovery, NullDiscovery } from './discovery.mjs'
|
|
27
|
+
|
|
28
|
+
const POD_RUNTIME_KEY = Symbol.for('pod.runtime')
|
|
29
|
+
const DEFAULT_HANDSHAKE_TIMEOUT = 1000
|
|
30
|
+
const DEFAULT_DISCOVERY_TIMEOUT = 2000
|
|
31
|
+
const DEFAULT_DISCOVERY_CHANNEL = 'pod-discovery'
|
|
32
|
+
|
|
33
|
+
/** @typedef {'idle'|'booting'|'ready'|'shutdown'} PodState */
|
|
34
|
+
/** @typedef {'autonomous'|'child'|'peer'|'controlled'|'hybrid'} PodRole */
|
|
35
|
+
|
|
36
|
+
export class Pod {
|
|
37
|
+
#identity = null
|
|
38
|
+
#kind = null
|
|
39
|
+
#capabilities = null
|
|
40
|
+
#role = 'autonomous'
|
|
41
|
+
#state = 'idle'
|
|
42
|
+
#peers = new Map()
|
|
43
|
+
#listeners = new Map()
|
|
44
|
+
#transport = null
|
|
45
|
+
#discovery = null
|
|
46
|
+
#messageHandler = null
|
|
47
|
+
#g = null
|
|
48
|
+
|
|
49
|
+
// ── Getters ──────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
/** @returns {string|null} */
|
|
52
|
+
get podId() { return this.#identity?.podId ?? null }
|
|
53
|
+
|
|
54
|
+
/** @returns {PodIdentity|null} */
|
|
55
|
+
get identity() { return this.#identity }
|
|
56
|
+
|
|
57
|
+
/** @returns {import('./capabilities.mjs').PodCapabilities|null} */
|
|
58
|
+
get capabilities() { return this.#capabilities }
|
|
59
|
+
|
|
60
|
+
/** @returns {import('./detect-kind.mjs').PodKind|null} */
|
|
61
|
+
get kind() { return this.#kind }
|
|
62
|
+
|
|
63
|
+
/** @returns {PodRole} */
|
|
64
|
+
get role() { return this.#role }
|
|
65
|
+
|
|
66
|
+
/** @returns {PodState} */
|
|
67
|
+
get state() { return this.#state }
|
|
68
|
+
|
|
69
|
+
/** @returns {Map<string, object>} podId → peer info */
|
|
70
|
+
get peers() { return new Map(this.#peers) }
|
|
71
|
+
|
|
72
|
+
/** @returns {import('./transport.mjs').BroadcastChannelTransport|import('./transport.mjs').EventEmitterTransport|import('./transport.mjs').NullTransport|null} */
|
|
73
|
+
get transport() { return this.#transport }
|
|
74
|
+
|
|
75
|
+
// ── Boot ─────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Run the 6-phase boot sequence.
|
|
79
|
+
*
|
|
80
|
+
* @param {object} [opts]
|
|
81
|
+
* @param {PodIdentity|{podId: string}} [opts.identity] - Pre-existing identity (skips generation)
|
|
82
|
+
* @param {object} [opts.transport] - TransportAdapter instance (auto-detected if omitted)
|
|
83
|
+
* @param {object} [opts.discovery] - DiscoveryAdapter instance (auto-created if omitted)
|
|
84
|
+
* @param {string} [opts.discoveryChannel] - BroadcastChannel name (used by auto-created transport)
|
|
85
|
+
* @param {number} [opts.handshakeTimeout] - ms to wait for parent ACK
|
|
86
|
+
* @param {number} [opts.discoveryTimeout] - ms to wait for peer responses
|
|
87
|
+
* @param {object} [opts.globalThis] - Override globalThis for testing
|
|
88
|
+
*/
|
|
89
|
+
async boot(opts = {}) {
|
|
90
|
+
if (this.#state !== 'idle') {
|
|
91
|
+
throw new Error(`Pod already in state: ${this.#state}`)
|
|
92
|
+
}
|
|
93
|
+
this.#state = 'booting'
|
|
94
|
+
this.#g = opts.globalThis || globalThis
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
// Phase 0: Install Runtime
|
|
98
|
+
this._emit('phase', { phase: 0, name: 'install-runtime' })
|
|
99
|
+
this.#identity = opts.identity || await PodIdentity.generate()
|
|
100
|
+
this.#kind = detectPodKind(this.#g)
|
|
101
|
+
this.#capabilities = detectCapabilities(this.#g)
|
|
102
|
+
this.#g[POD_RUNTIME_KEY] = {
|
|
103
|
+
podId: this.podId,
|
|
104
|
+
kind: this.#kind,
|
|
105
|
+
capabilities: this.#capabilities,
|
|
106
|
+
pod: this,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Phase 1: Install Listeners
|
|
110
|
+
this._emit('phase', { phase: 1, name: 'install-listeners' })
|
|
111
|
+
this.#installMessageHandler()
|
|
112
|
+
this._onInstallListeners(this.#g)
|
|
113
|
+
|
|
114
|
+
// Phase 2: Self-Classification
|
|
115
|
+
this._emit('phase', { phase: 2, name: 'self-classification' })
|
|
116
|
+
|
|
117
|
+
// Phase 3: Parent Handshake
|
|
118
|
+
this._emit('phase', { phase: 3, name: 'parent-handshake' })
|
|
119
|
+
await this.#parentHandshake(opts.handshakeTimeout ?? DEFAULT_HANDSHAKE_TIMEOUT)
|
|
120
|
+
|
|
121
|
+
// Phase 4: Peer Discovery
|
|
122
|
+
this._emit('phase', { phase: 4, name: 'peer-discovery' })
|
|
123
|
+
await this.#peerDiscovery(opts)
|
|
124
|
+
|
|
125
|
+
// Phase 5: Role Finalization
|
|
126
|
+
this._emit('phase', { phase: 5, name: 'role-finalization' })
|
|
127
|
+
this.#finalizeRole()
|
|
128
|
+
this.#state = 'ready'
|
|
129
|
+
this._onReady()
|
|
130
|
+
this._emit('ready', { podId: this.podId, kind: this.#kind, role: this.#role })
|
|
131
|
+
} catch (err) {
|
|
132
|
+
this.#state = 'idle'
|
|
133
|
+
this._emit('error', { phase: 'boot', error: err })
|
|
134
|
+
throw err
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ── Shutdown ─────────────────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Gracefully shut down the pod.
|
|
142
|
+
*
|
|
143
|
+
* @param {object} [opts]
|
|
144
|
+
* @param {boolean} [opts.silent] - Skip broadcasting POD_GOODBYE
|
|
145
|
+
*/
|
|
146
|
+
async shutdown(opts = {}) {
|
|
147
|
+
if (this.#state === 'shutdown' || this.#state === 'idle') return
|
|
148
|
+
|
|
149
|
+
if (this.#discovery) {
|
|
150
|
+
await this.#discovery.stop({ silent: opts.silent })
|
|
151
|
+
this.#discovery = null
|
|
152
|
+
} else if (this.#transport) {
|
|
153
|
+
// No discovery adapter — close transport directly
|
|
154
|
+
if (!opts.silent) {
|
|
155
|
+
try {
|
|
156
|
+
this.#transport.send(createGoodbye({ podId: this.podId }))
|
|
157
|
+
} catch { /* transport may already be closed */ }
|
|
158
|
+
}
|
|
159
|
+
await this.#transport.close()
|
|
160
|
+
}
|
|
161
|
+
this.#transport = null
|
|
162
|
+
|
|
163
|
+
if (this.#messageHandler && this.#g?.removeEventListener) {
|
|
164
|
+
this.#g.removeEventListener('message', this.#messageHandler)
|
|
165
|
+
this.#messageHandler = null
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (this.#g) {
|
|
169
|
+
delete this.#g[POD_RUNTIME_KEY]
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
this.#peers.clear()
|
|
173
|
+
this.#state = 'shutdown'
|
|
174
|
+
this._emit('shutdown', { podId: this.podId })
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ── Messaging ────────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Send a message to a specific peer via the transport.
|
|
181
|
+
*
|
|
182
|
+
* @param {string} targetPodId
|
|
183
|
+
* @param {*} payload
|
|
184
|
+
*/
|
|
185
|
+
send(targetPodId, payload) {
|
|
186
|
+
if (this.#state !== 'ready') {
|
|
187
|
+
throw new Error('Pod is not ready')
|
|
188
|
+
}
|
|
189
|
+
if (!this.#transport) {
|
|
190
|
+
throw new Error('No transport available')
|
|
191
|
+
}
|
|
192
|
+
this.#transport.send(
|
|
193
|
+
createMessage({ from: this.podId, to: targetPodId, payload })
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Broadcast a message to all peers via the transport.
|
|
199
|
+
*
|
|
200
|
+
* @param {*} payload
|
|
201
|
+
*/
|
|
202
|
+
broadcast(payload) {
|
|
203
|
+
this.send('*', payload)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ── Events ───────────────────────────────────────────────────
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Register an event listener.
|
|
210
|
+
* @param {string} event
|
|
211
|
+
* @param {Function} cb
|
|
212
|
+
*/
|
|
213
|
+
on(event, cb) {
|
|
214
|
+
if (!this.#listeners.has(event)) this.#listeners.set(event, [])
|
|
215
|
+
this.#listeners.get(event).push(cb)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Remove an event listener.
|
|
220
|
+
* @param {string} event
|
|
221
|
+
* @param {Function} cb
|
|
222
|
+
*/
|
|
223
|
+
off(event, cb) {
|
|
224
|
+
const list = this.#listeners.get(event)
|
|
225
|
+
if (!list) return
|
|
226
|
+
const idx = list.indexOf(cb)
|
|
227
|
+
if (idx !== -1) list.splice(idx, 1)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ── Serialization ────────────────────────────────────────────
|
|
231
|
+
|
|
232
|
+
/** @returns {object} Serializable snapshot */
|
|
233
|
+
toJSON() {
|
|
234
|
+
return {
|
|
235
|
+
podId: this.podId,
|
|
236
|
+
kind: this.#kind,
|
|
237
|
+
role: this.#role,
|
|
238
|
+
state: this.#state,
|
|
239
|
+
capabilities: this.#capabilities,
|
|
240
|
+
peerCount: this.#peers.size,
|
|
241
|
+
peers: [...this.#peers.keys()],
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ── Subclass hooks ───────────────────────────────────────────
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Called during Phase 1 (Install Listeners). Override in subclasses
|
|
249
|
+
* to install additional message handlers.
|
|
250
|
+
* @param {object} _g - globalThis reference
|
|
251
|
+
*/
|
|
252
|
+
_onInstallListeners(_g) { /* override me */ }
|
|
253
|
+
|
|
254
|
+
/** Called during Phase 5 (Role Finalization) when boot completes. */
|
|
255
|
+
_onReady() { /* override me */ }
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Called for each incoming message that targets this pod.
|
|
259
|
+
* @param {object} _msg
|
|
260
|
+
*/
|
|
261
|
+
_onMessage(_msg) { /* override me */ }
|
|
262
|
+
|
|
263
|
+
// ── Private: boot phases ─────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
#installMessageHandler() {
|
|
266
|
+
if (!this.#g?.addEventListener) return
|
|
267
|
+
this.#messageHandler = (event) => {
|
|
268
|
+
const data = event.data
|
|
269
|
+
if (!data || !data.type) return
|
|
270
|
+
this.#handleIncoming(data)
|
|
271
|
+
}
|
|
272
|
+
this.#g.addEventListener('message', this.#messageHandler)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async #parentHandshake(timeout) {
|
|
276
|
+
const hasParent = this.#kind === 'iframe' || this.#kind === 'spawned'
|
|
277
|
+
if (!hasParent) return
|
|
278
|
+
|
|
279
|
+
const target = this.#kind === 'iframe'
|
|
280
|
+
? this.#g.parent
|
|
281
|
+
: this.#g.opener
|
|
282
|
+
|
|
283
|
+
if (!target || typeof target.postMessage !== 'function') return
|
|
284
|
+
|
|
285
|
+
const hello = createHello({
|
|
286
|
+
podId: this.podId,
|
|
287
|
+
kind: this.#kind,
|
|
288
|
+
capabilities: this.#capabilities,
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
return new Promise((resolve) => {
|
|
292
|
+
const timer = setTimeout(() => resolve(), timeout)
|
|
293
|
+
|
|
294
|
+
const handler = (event) => {
|
|
295
|
+
const data = event.data
|
|
296
|
+
if (data?.type === POD_HELLO_ACK && data.targetPodId === this.podId) {
|
|
297
|
+
clearTimeout(timer)
|
|
298
|
+
this.#g.removeEventListener('message', handler)
|
|
299
|
+
this.#addPeer(data.podId, { kind: data.kind, role: 'parent' })
|
|
300
|
+
this.#role = 'child'
|
|
301
|
+
resolve()
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
this.#g.addEventListener('message', handler)
|
|
305
|
+
target.postMessage(hello, '*')
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async #peerDiscovery(opts) {
|
|
310
|
+
const channelName = opts.discoveryChannel ?? DEFAULT_DISCOVERY_CHANNEL
|
|
311
|
+
const timeout = opts.discoveryTimeout ?? DEFAULT_DISCOVERY_TIMEOUT
|
|
312
|
+
|
|
313
|
+
// Use provided transport or auto-detect
|
|
314
|
+
if (opts.transport) {
|
|
315
|
+
this.#transport = opts.transport
|
|
316
|
+
} else if (this.#capabilities?.messaging?.broadcastChannel) {
|
|
317
|
+
const BC = this.#g.BroadcastChannel || globalThis.BroadcastChannel
|
|
318
|
+
this.#transport = new BroadcastChannelTransport(channelName, BC)
|
|
319
|
+
} else {
|
|
320
|
+
this.#transport = new NullTransport()
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Use provided discovery or create one based on transport
|
|
324
|
+
if (opts.discovery) {
|
|
325
|
+
this.#discovery = opts.discovery
|
|
326
|
+
} else if (!(this.#transport instanceof NullTransport)) {
|
|
327
|
+
this.#discovery = new TransportDiscovery({
|
|
328
|
+
transport: this.#transport,
|
|
329
|
+
localPodId: this.podId,
|
|
330
|
+
localKind: this.#kind,
|
|
331
|
+
capabilities: this.#capabilities,
|
|
332
|
+
timeout,
|
|
333
|
+
})
|
|
334
|
+
} else {
|
|
335
|
+
this.#discovery = new NullDiscovery()
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Wire discovery callbacks
|
|
339
|
+
this.#discovery.onPeerDiscovered((info) => {
|
|
340
|
+
this.#addPeer(info.podId, { kind: info.kind })
|
|
341
|
+
})
|
|
342
|
+
this.#discovery.onPeerLost((info) => {
|
|
343
|
+
this.#removePeer(info.podId)
|
|
344
|
+
})
|
|
345
|
+
this.#discovery.onMessage((msg) => {
|
|
346
|
+
this.#handleIncoming(msg)
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
// Run discovery
|
|
350
|
+
await this.#discovery.start()
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
#finalizeRole() {
|
|
354
|
+
if (this.#role === 'child') return
|
|
355
|
+
|
|
356
|
+
if (this.#peers.size === 0) {
|
|
357
|
+
this.#role = 'autonomous'
|
|
358
|
+
} else {
|
|
359
|
+
this.#role = 'peer'
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ── Private: message routing ─────────────────────────────────
|
|
364
|
+
|
|
365
|
+
#handleIncoming(data) {
|
|
366
|
+
switch (data.type) {
|
|
367
|
+
case POD_HELLO: {
|
|
368
|
+
if (data.podId !== this.podId) {
|
|
369
|
+
this.#addPeer(data.podId, { kind: data.kind })
|
|
370
|
+
if (this.#transport) {
|
|
371
|
+
this.#transport.send(
|
|
372
|
+
createHelloAck({ podId: this.podId, kind: this.#kind, targetPodId: data.podId })
|
|
373
|
+
)
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
break
|
|
377
|
+
}
|
|
378
|
+
case POD_HELLO_ACK: {
|
|
379
|
+
if (data.targetPodId === this.podId) {
|
|
380
|
+
this.#addPeer(data.podId, { kind: data.kind })
|
|
381
|
+
}
|
|
382
|
+
break
|
|
383
|
+
}
|
|
384
|
+
case POD_GOODBYE: {
|
|
385
|
+
this.#removePeer(data.podId)
|
|
386
|
+
break
|
|
387
|
+
}
|
|
388
|
+
case POD_MESSAGE:
|
|
389
|
+
case POD_RPC_REQUEST:
|
|
390
|
+
case POD_RPC_RESPONSE: {
|
|
391
|
+
if (data.to === this.podId || data.to === '*') {
|
|
392
|
+
this._onMessage(data)
|
|
393
|
+
this._emit('message', data)
|
|
394
|
+
}
|
|
395
|
+
break
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
#addPeer(podId, info) {
|
|
401
|
+
if (podId === this.podId) return
|
|
402
|
+
const isNew = !this.#peers.has(podId)
|
|
403
|
+
this.#peers.set(podId, { ...info, podId, lastSeen: Date.now() })
|
|
404
|
+
if (isNew) {
|
|
405
|
+
this._emit('peer:found', { podId, ...info })
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
#removePeer(podId) {
|
|
410
|
+
if (this.#peers.delete(podId)) {
|
|
411
|
+
this._emit('peer:lost', { podId })
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ── Protected: event emitter ─────────────────────────────────
|
|
416
|
+
// Underscore-prefixed by convention, not a JS #private field: subclasses
|
|
417
|
+
// (e.g. InjectedPod) need to dispatch events through the same listener
|
|
418
|
+
// registry that on()/off() populate.
|
|
419
|
+
|
|
420
|
+
_emit(event, data) {
|
|
421
|
+
const list = this.#listeners.get(event)
|
|
422
|
+
if (!list) return
|
|
423
|
+
for (const fn of list) {
|
|
424
|
+
try { fn(data) } catch { /* listener errors don't crash the pod */ }
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|