@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 John Henry
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# browsermesh-pod
|
|
2
|
+
|
|
3
|
+
Pod base class for browser execution contexts with Ed25519 identity, BroadcastChannel discovery, and peer messaging.
|
|
4
|
+
|
|
5
|
+
A Pod is any browser execution context (window, iframe, worker, service worker) that can execute code, receive messages, and be discovered/addressed. This package provides the standalone base class with zero framework dependencies.
|
|
6
|
+
|
|
7
|
+
Pods automatically generate an Ed25519 cryptographic identity, detect their execution context, discover same-origin peers via BroadcastChannel, and establish roles (autonomous, child, peer).
|
|
8
|
+
|
|
9
|
+
## Provenance
|
|
10
|
+
|
|
11
|
+
Previously published as `browsermesh-pod@0.2.1`. Imported into the `@johnhenry` npm scope as part of the browsermesh monorepo consolidation; the version restarts at `0.0.0` per family convention (a new address is a new era).
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @johnhenry/browsermesh-pod @johnhenry/browsermesh-primitives
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`browsermesh-primitives` is a peer dependency (provides Ed25519 identity generation).
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import { Pod } from 'browsermesh-pod'
|
|
25
|
+
|
|
26
|
+
const pod = new Pod()
|
|
27
|
+
await pod.boot()
|
|
28
|
+
|
|
29
|
+
console.log(pod.podId) // base64url Ed25519 public key hash
|
|
30
|
+
console.log(pod.kind) // 'window', 'worker', 'iframe', etc.
|
|
31
|
+
console.log(pod.role) // 'autonomous', 'peer', or 'child'
|
|
32
|
+
console.log(pod.peers.size) // number of discovered peers
|
|
33
|
+
|
|
34
|
+
pod.on('message', (msg) => {
|
|
35
|
+
console.log('Received:', msg.payload)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
// Send to a specific peer
|
|
39
|
+
pod.send(otherPodId, { text: 'hello' })
|
|
40
|
+
|
|
41
|
+
// Broadcast to all peers
|
|
42
|
+
pod.broadcast({ text: 'hello everyone' })
|
|
43
|
+
|
|
44
|
+
await pod.shutdown()
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Boot Sequence
|
|
48
|
+
|
|
49
|
+
The 6-phase boot sequence runs automatically when you call `pod.boot()`:
|
|
50
|
+
|
|
51
|
+
| Phase | Name | Action |
|
|
52
|
+
|-------|------|--------|
|
|
53
|
+
| 0 | Install Runtime | Generate Ed25519 identity, detect kind & capabilities |
|
|
54
|
+
| 1 | Install Listeners | Attach message handlers, call `_onInstallListeners()` hook |
|
|
55
|
+
| 2 | Self-Classification | Detect parent/opener relationships |
|
|
56
|
+
| 3 | Parent Handshake | Send `POD_HELLO` to parent/opener, wait for `POD_HELLO_ACK` |
|
|
57
|
+
| 4 | Peer Discovery | Announce on BroadcastChannel, collect peer responses |
|
|
58
|
+
| 5 | Role Finalization | Determine role, call `_onReady()` hook, emit `'ready'` event |
|
|
59
|
+
|
|
60
|
+
State transitions: `idle -> booting -> ready -> shutdown`
|
|
61
|
+
|
|
62
|
+
## Boot Options
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
await pod.boot({
|
|
66
|
+
identity, // PodIdentity — skip generation, reuse existing
|
|
67
|
+
discoveryChannel, // string — BroadcastChannel name (default: 'pod-discovery')
|
|
68
|
+
handshakeTimeout, // number — ms to wait for parent ACK (default: 1000)
|
|
69
|
+
discoveryTimeout, // number — ms to wait for peer responses (default: 2000)
|
|
70
|
+
globalThis, // object — override globalThis (for testing)
|
|
71
|
+
})
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## API
|
|
75
|
+
|
|
76
|
+
### Getters
|
|
77
|
+
|
|
78
|
+
| Getter | Type | Description |
|
|
79
|
+
|--------|------|-------------|
|
|
80
|
+
| `podId` | `string \| null` | Base64url Ed25519 public key hash |
|
|
81
|
+
| `identity` | `PodIdentity \| null` | Ed25519 key pair wrapper |
|
|
82
|
+
| `capabilities` | `PodCapabilities \| null` | Detected runtime capabilities |
|
|
83
|
+
| `kind` | `PodKind \| null` | Execution context classification |
|
|
84
|
+
| `role` | `PodRole` | `'autonomous'`, `'child'`, or `'peer'` |
|
|
85
|
+
| `state` | `PodState` | `'idle'`, `'booting'`, `'ready'`, or `'shutdown'` |
|
|
86
|
+
| `peers` | `Map<string, object>` | Copy of known peers (podId -> info) |
|
|
87
|
+
|
|
88
|
+
### Methods
|
|
89
|
+
|
|
90
|
+
| Method | Signature | Description |
|
|
91
|
+
|--------|-----------|-------------|
|
|
92
|
+
| `boot` | `async boot(opts?)` | Run 6-phase boot sequence |
|
|
93
|
+
| `shutdown` | `async shutdown(opts?)` | Broadcast goodbye, close channels, clear peers |
|
|
94
|
+
| `send` | `send(targetPodId, payload)` | Send message to a specific peer |
|
|
95
|
+
| `broadcast` | `broadcast(payload)` | Send message to all peers (address: `'*'`) |
|
|
96
|
+
| `on` | `on(event, cb)` | Register event listener |
|
|
97
|
+
| `off` | `off(event, cb)` | Remove event listener |
|
|
98
|
+
| `toJSON` | `toJSON()` | Serializable snapshot of pod state |
|
|
99
|
+
|
|
100
|
+
### Events
|
|
101
|
+
|
|
102
|
+
| Event | Data | When |
|
|
103
|
+
|-------|------|------|
|
|
104
|
+
| `phase` | `{ phase, name }` | Each boot phase starts |
|
|
105
|
+
| `ready` | `{ podId, kind, role }` | Boot completes |
|
|
106
|
+
| `shutdown` | `{ podId }` | Pod shuts down |
|
|
107
|
+
| `error` | `{ phase, error }` | Boot phase fails |
|
|
108
|
+
| `peer:found` | `{ podId, kind }` | New peer discovered |
|
|
109
|
+
| `peer:lost` | `{ podId }` | Peer departed |
|
|
110
|
+
| `message` | `{ type, from, to, payload, ts }` | Incoming message |
|
|
111
|
+
|
|
112
|
+
### Subclass Hooks
|
|
113
|
+
|
|
114
|
+
| Hook | Phase | Description |
|
|
115
|
+
|------|-------|-------------|
|
|
116
|
+
| `_onInstallListeners(g)` | 1 | Install additional message handlers |
|
|
117
|
+
| `_onReady()` | 5 | Boot complete callback |
|
|
118
|
+
| `_onMessage(msg)` | -- | Handle incoming targeted message |
|
|
119
|
+
|
|
120
|
+
## Runtime Convenience Functions
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
import { installPodRuntime, createRuntime, createClient, createServer } from 'browsermesh-pod'
|
|
124
|
+
|
|
125
|
+
// Create and boot a pod (createRuntime is an alias)
|
|
126
|
+
const pod = await installPodRuntime({ context: globalThis })
|
|
127
|
+
|
|
128
|
+
// Lightweight client with short discovery timeout
|
|
129
|
+
const client = await createClient({ discoveryTimeout: 500 })
|
|
130
|
+
|
|
131
|
+
// Server-oriented pod with longer timeouts
|
|
132
|
+
const server = await createServer({ discoveryTimeout: 5000 })
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Pod Kinds
|
|
136
|
+
|
|
137
|
+
`detectPodKind(globalThis)` returns one of:
|
|
138
|
+
|
|
139
|
+
| Kind | Detection |
|
|
140
|
+
|------|-----------|
|
|
141
|
+
| `service-worker` | `instanceof ServiceWorkerGlobalScope` |
|
|
142
|
+
| `shared-worker` | `instanceof SharedWorkerGlobalScope` |
|
|
143
|
+
| `worker` | `instanceof WorkerGlobalScope` |
|
|
144
|
+
| `worklet` | `instanceof AudioWorkletGlobalScope` |
|
|
145
|
+
| `server` | No `window` or `document` |
|
|
146
|
+
| `iframe` | `window !== window.parent` |
|
|
147
|
+
| `spawned` | `window.opener` is set |
|
|
148
|
+
| `window` | Default (top-level window) |
|
|
149
|
+
|
|
150
|
+
## Capabilities
|
|
151
|
+
|
|
152
|
+
`detectCapabilities(globalThis)` returns:
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
{
|
|
156
|
+
messaging: { postMessage, messageChannel, broadcastChannel, sharedWorker, serviceWorker },
|
|
157
|
+
network: { fetch, webSocket, webTransport, webRTC },
|
|
158
|
+
storage: { indexedDB, cacheAPI, opfs },
|
|
159
|
+
compute: { wasm, sharedArrayBuffer, offscreenCanvas },
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Wire Protocol
|
|
164
|
+
|
|
165
|
+
| Constant | Value | Purpose |
|
|
166
|
+
|----------|-------|---------|
|
|
167
|
+
| `POD_HELLO` | `'pod:hello'` | Discovery announcement |
|
|
168
|
+
| `POD_HELLO_ACK` | `'pod:hello-ack'` | Discovery response |
|
|
169
|
+
| `POD_GOODBYE` | `'pod:goodbye'` | Graceful departure |
|
|
170
|
+
| `POD_MESSAGE` | `'pod:message'` | Inter-pod message |
|
|
171
|
+
| `POD_RPC_REQUEST` | `'pod:rpc-request'` | RPC call |
|
|
172
|
+
| `POD_RPC_RESPONSE` | `'pod:rpc-response'` | RPC result |
|
|
173
|
+
|
|
174
|
+
Message factories: `createHello()`, `createHelloAck()`, `createGoodbye()`, `createMessage()`, `createRpcRequest()`, `createRpcResponse()`.
|
|
175
|
+
|
|
176
|
+
## InjectedPod
|
|
177
|
+
|
|
178
|
+
Lightweight subclass for Chrome extension injection or bookmarklet use. Adds page text extraction, structured data extraction, and a visual overlay indicator.
|
|
179
|
+
|
|
180
|
+
```js
|
|
181
|
+
import { InjectedPod } from 'browsermesh-pod'
|
|
182
|
+
|
|
183
|
+
const pod = new InjectedPod({ extensionBridge: chrome.runtime.connect() })
|
|
184
|
+
await pod.boot()
|
|
185
|
+
|
|
186
|
+
console.log(pod.pageContext) // { url, title, origin, favicon }
|
|
187
|
+
console.log(pod.extractText()) // visible page text
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Peer Dependency
|
|
191
|
+
|
|
192
|
+
This package requires `browsermesh-primitives` as a peer dependency for Ed25519 identity generation (`PodIdentity`). Install it alongside:
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
npm install @johnhenry/browsermesh-pod @johnhenry/browsermesh-primitives
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@johnhenry/browsermesh-pod",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Pod base class for browser execution contexts with Ed25519 identity, BroadcastChannel discovery, and peer messaging",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"LICENSE",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pod",
|
|
17
|
+
"mesh",
|
|
18
|
+
"p2p",
|
|
19
|
+
"identity",
|
|
20
|
+
"browser",
|
|
21
|
+
"webrtc"
|
|
22
|
+
],
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/johnhenry/browsermesh",
|
|
27
|
+
"directory": "packages/browsermesh-pod"
|
|
28
|
+
},
|
|
29
|
+
"homepage": "https://opensource.johnhenry.me/browsermesh/",
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "node --test test/*.test.mjs"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@johnhenry/browsermesh-primitives": ">=0.0.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@johnhenry/browsermesh-primitives": "^0.0.0"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=24.0.0"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* capabilities.mjs — Detect available browser/runtime capabilities.
|
|
3
|
+
*
|
|
4
|
+
* Returns a PodCapabilities object describing what messaging, network,
|
|
5
|
+
* storage, and compute primitives are available in the current context.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {object} PodCapabilities
|
|
10
|
+
* @property {object} messaging
|
|
11
|
+
* @property {boolean} messaging.postMessage
|
|
12
|
+
* @property {boolean} messaging.messageChannel
|
|
13
|
+
* @property {boolean} messaging.broadcastChannel
|
|
14
|
+
* @property {boolean} messaging.sharedWorker
|
|
15
|
+
* @property {boolean} messaging.serviceWorker
|
|
16
|
+
* @property {object} network
|
|
17
|
+
* @property {boolean} network.fetch
|
|
18
|
+
* @property {boolean} network.webSocket
|
|
19
|
+
* @property {boolean} network.webTransport
|
|
20
|
+
* @property {boolean} network.webRTC
|
|
21
|
+
* @property {object} storage
|
|
22
|
+
* @property {boolean} storage.indexedDB
|
|
23
|
+
* @property {boolean} storage.cacheAPI
|
|
24
|
+
* @property {boolean} storage.opfs
|
|
25
|
+
* @property {object} compute
|
|
26
|
+
* @property {boolean} compute.wasm
|
|
27
|
+
* @property {boolean} compute.sharedArrayBuffer
|
|
28
|
+
* @property {boolean} compute.offscreenCanvas
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Detect capabilities available in the current execution context.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} [g=globalThis] - The global scope to inspect
|
|
35
|
+
* @returns {PodCapabilities}
|
|
36
|
+
*/
|
|
37
|
+
export function detectCapabilities(g = globalThis) {
|
|
38
|
+
return {
|
|
39
|
+
messaging: {
|
|
40
|
+
postMessage: typeof g.postMessage === 'function',
|
|
41
|
+
messageChannel: typeof g.MessageChannel === 'function',
|
|
42
|
+
broadcastChannel: typeof g.BroadcastChannel === 'function',
|
|
43
|
+
sharedWorker: typeof g.SharedWorker === 'function',
|
|
44
|
+
serviceWorker: !!(g.navigator && g.navigator.serviceWorker),
|
|
45
|
+
},
|
|
46
|
+
network: {
|
|
47
|
+
fetch: typeof g.fetch === 'function',
|
|
48
|
+
webSocket: typeof g.WebSocket === 'function',
|
|
49
|
+
webTransport: typeof g.WebTransport === 'function',
|
|
50
|
+
webRTC: typeof g.RTCPeerConnection === 'function',
|
|
51
|
+
},
|
|
52
|
+
storage: {
|
|
53
|
+
indexedDB: typeof g.indexedDB !== 'undefined',
|
|
54
|
+
cacheAPI: typeof g.caches !== 'undefined',
|
|
55
|
+
opfs: !!(g.navigator && g.navigator.storage && typeof g.navigator.storage.getDirectory === 'function'),
|
|
56
|
+
},
|
|
57
|
+
compute: {
|
|
58
|
+
wasm: typeof g.WebAssembly !== 'undefined',
|
|
59
|
+
sharedArrayBuffer: typeof g.SharedArrayBuffer === 'function',
|
|
60
|
+
offscreenCanvas: typeof g.OffscreenCanvas === 'function',
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* detect-kind.mjs — Classify the current execution context.
|
|
3
|
+
*
|
|
4
|
+
* Inspects globalThis to determine what kind of browser (or non-browser)
|
|
5
|
+
* environment this code is running in. Returns one of 8 pod kinds.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** @typedef {'service-worker'|'shared-worker'|'worker'|'worklet'|'server'|'iframe'|'spawned'|'window'} PodKind */
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Detect the pod kind for the current execution context.
|
|
12
|
+
*
|
|
13
|
+
* @param {object} [g=globalThis] - The global scope to inspect
|
|
14
|
+
* @returns {PodKind}
|
|
15
|
+
*/
|
|
16
|
+
export function detectPodKind(g = globalThis) {
|
|
17
|
+
// Service worker (extends WorkerGlobalScope, check first)
|
|
18
|
+
if (typeof g.ServiceWorkerGlobalScope !== 'undefined' && g instanceof g.ServiceWorkerGlobalScope) {
|
|
19
|
+
return 'service-worker'
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Shared worker
|
|
23
|
+
if (typeof g.SharedWorkerGlobalScope !== 'undefined' && g instanceof g.SharedWorkerGlobalScope) {
|
|
24
|
+
return 'shared-worker'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Dedicated worker (generic WorkerGlobalScope — after SW/SharedWorker checks)
|
|
28
|
+
if (typeof g.WorkerGlobalScope !== 'undefined' && g instanceof g.WorkerGlobalScope) {
|
|
29
|
+
return 'worker'
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Audio worklet
|
|
33
|
+
if (typeof g.AudioWorkletGlobalScope !== 'undefined' && g instanceof g.AudioWorkletGlobalScope) {
|
|
34
|
+
return 'worklet'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// No window or document → server / Node.js / Deno
|
|
38
|
+
if (typeof g.window === 'undefined' || typeof g.document === 'undefined') {
|
|
39
|
+
return 'server'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Window exists — check framing
|
|
43
|
+
try {
|
|
44
|
+
if (g.window !== g.window.parent) return 'iframe'
|
|
45
|
+
} catch {
|
|
46
|
+
// Cross-origin parent access throws — must be an iframe
|
|
47
|
+
return 'iframe'
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Spawned window (window.open)
|
|
51
|
+
if (g.window.opener) return 'spawned'
|
|
52
|
+
|
|
53
|
+
// Default: top-level window
|
|
54
|
+
return 'window'
|
|
55
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* discovery.mjs — Pluggable discovery adapters for Pod peer discovery.
|
|
3
|
+
*
|
|
4
|
+
* A DiscoveryAdapter uses a TransportAdapter to announce this pod and
|
|
5
|
+
* discover peers. It filters discovery-related messages (hello/ack/goodbye)
|
|
6
|
+
* from the transport stream.
|
|
7
|
+
*
|
|
8
|
+
* Two built-in implementations:
|
|
9
|
+
* TransportDiscovery — runs the hello/ack/goodbye protocol over any transport
|
|
10
|
+
* NullDiscovery — no-op (discovery disabled)
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
POD_HELLO, POD_HELLO_ACK, POD_GOODBYE,
|
|
15
|
+
createHello, createHelloAck, createGoodbye,
|
|
16
|
+
} from './messages.mjs'
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// TransportDiscovery
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Discovery protocol that runs over any TransportAdapter.
|
|
24
|
+
* Sends hello/ack/goodbye messages and fires callbacks for peer events.
|
|
25
|
+
*
|
|
26
|
+
* This replaces the hardcoded BroadcastChannel discovery in Pod.
|
|
27
|
+
* It works with BroadcastChannelTransport, EventEmitterTransport, or any
|
|
28
|
+
* custom transport.
|
|
29
|
+
*/
|
|
30
|
+
export class TransportDiscovery {
|
|
31
|
+
#transport
|
|
32
|
+
#localPodId
|
|
33
|
+
#localKind
|
|
34
|
+
#capabilities
|
|
35
|
+
#timeout
|
|
36
|
+
#onPeerFound = null
|
|
37
|
+
#onPeerLost = null
|
|
38
|
+
#onNonDiscoveryMessage = null
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {object} opts
|
|
42
|
+
* @param {import('./transport.mjs').BroadcastChannelTransport|import('./transport.mjs').EventEmitterTransport} opts.transport
|
|
43
|
+
* @param {string} opts.localPodId
|
|
44
|
+
* @param {string} opts.localKind
|
|
45
|
+
* @param {object} [opts.capabilities]
|
|
46
|
+
* @param {number} [opts.timeout=2000]
|
|
47
|
+
*/
|
|
48
|
+
constructor({ transport, localPodId, localKind, capabilities, timeout = 2000 }) {
|
|
49
|
+
this.#transport = transport
|
|
50
|
+
this.#localPodId = localPodId
|
|
51
|
+
this.#localKind = localKind
|
|
52
|
+
this.#capabilities = capabilities || null
|
|
53
|
+
this.#timeout = timeout
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {(peerInfo: { podId: string, kind?: string }) => void} handler
|
|
58
|
+
*/
|
|
59
|
+
onPeerDiscovered(handler) {
|
|
60
|
+
this.#onPeerFound = handler
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @param {(peerInfo: { podId: string }) => void} handler
|
|
65
|
+
*/
|
|
66
|
+
onPeerLost(handler) {
|
|
67
|
+
this.#onPeerLost = handler
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Register handler for non-discovery messages that come through the transport.
|
|
72
|
+
* @param {(msg: object) => void} handler
|
|
73
|
+
*/
|
|
74
|
+
onMessage(handler) {
|
|
75
|
+
this.#onNonDiscoveryMessage = handler
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Start discovery: announce ourselves and listen for peers.
|
|
80
|
+
* Returns a promise that resolves after the discovery timeout.
|
|
81
|
+
*/
|
|
82
|
+
async start() {
|
|
83
|
+
// Wire message routing
|
|
84
|
+
this.#transport.onMessage((msg) => {
|
|
85
|
+
if (!msg || !msg.type) return
|
|
86
|
+
this.#handleMessage(msg)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
// Open transport if not already open
|
|
90
|
+
if (!this.#transport.ready) {
|
|
91
|
+
await this.#transport.open()
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Announce ourselves
|
|
95
|
+
this.#transport.send(
|
|
96
|
+
createHello({
|
|
97
|
+
podId: this.#localPodId,
|
|
98
|
+
kind: this.#localKind,
|
|
99
|
+
capabilities: this.#capabilities,
|
|
100
|
+
})
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
// Wait for discovery period
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
setTimeout(resolve, this.#timeout)
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Stop discovery: send goodbye and close transport.
|
|
111
|
+
* @param {object} [opts]
|
|
112
|
+
* @param {boolean} [opts.silent] - Skip sending goodbye
|
|
113
|
+
*/
|
|
114
|
+
async stop(opts = {}) {
|
|
115
|
+
if (!opts.silent) {
|
|
116
|
+
try {
|
|
117
|
+
this.#transport.send(createGoodbye({ podId: this.#localPodId }))
|
|
118
|
+
} catch { /* transport may already be closed */ }
|
|
119
|
+
}
|
|
120
|
+
await this.#transport.close()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
#handleMessage(msg) {
|
|
124
|
+
switch (msg.type) {
|
|
125
|
+
case POD_HELLO: {
|
|
126
|
+
if (msg.podId === this.#localPodId) return
|
|
127
|
+
if (this.#onPeerFound) {
|
|
128
|
+
this.#onPeerFound({ podId: msg.podId, kind: msg.kind })
|
|
129
|
+
}
|
|
130
|
+
// Respond with ACK
|
|
131
|
+
this.#transport.send(
|
|
132
|
+
createHelloAck({
|
|
133
|
+
podId: this.#localPodId,
|
|
134
|
+
kind: this.#localKind,
|
|
135
|
+
targetPodId: msg.podId,
|
|
136
|
+
})
|
|
137
|
+
)
|
|
138
|
+
break
|
|
139
|
+
}
|
|
140
|
+
case POD_HELLO_ACK: {
|
|
141
|
+
if (msg.targetPodId !== this.#localPodId) return
|
|
142
|
+
if (this.#onPeerFound) {
|
|
143
|
+
this.#onPeerFound({ podId: msg.podId, kind: msg.kind })
|
|
144
|
+
}
|
|
145
|
+
break
|
|
146
|
+
}
|
|
147
|
+
case POD_GOODBYE: {
|
|
148
|
+
if (this.#onPeerLost) {
|
|
149
|
+
this.#onPeerLost({ podId: msg.podId })
|
|
150
|
+
}
|
|
151
|
+
break
|
|
152
|
+
}
|
|
153
|
+
default: {
|
|
154
|
+
// Non-discovery message — pass through
|
|
155
|
+
if (this.#onNonDiscoveryMessage) {
|
|
156
|
+
this.#onNonDiscoveryMessage(msg)
|
|
157
|
+
}
|
|
158
|
+
break
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
// NullDiscovery
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* No-op discovery adapter. No peers will be discovered.
|
|
170
|
+
*/
|
|
171
|
+
export class NullDiscovery {
|
|
172
|
+
onPeerDiscovered(_handler) {}
|
|
173
|
+
onPeerLost(_handler) {}
|
|
174
|
+
onMessage(_handler) {}
|
|
175
|
+
async start() {}
|
|
176
|
+
async stop() {}
|
|
177
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pod package — barrel exports.
|
|
3
|
+
*/
|
|
4
|
+
export { Pod } from './pod.mjs'
|
|
5
|
+
export { detectPodKind } from './detect-kind.mjs'
|
|
6
|
+
export { detectCapabilities } from './capabilities.mjs'
|
|
7
|
+
export {
|
|
8
|
+
POD_HELLO, POD_HELLO_ACK, POD_GOODBYE, POD_MESSAGE,
|
|
9
|
+
POD_RPC_REQUEST, POD_RPC_RESPONSE,
|
|
10
|
+
createHello, createHelloAck, createGoodbye, createMessage,
|
|
11
|
+
createRpcRequest, createRpcResponse,
|
|
12
|
+
} from './messages.mjs'
|
|
13
|
+
export { InjectedPod } from './injected-pod.mjs'
|
|
14
|
+
export { installPodRuntime, createRuntime, createClient, createServer } from './runtime.mjs'
|
|
15
|
+
export { BroadcastChannelTransport, EventEmitterTransport, NullTransport } from './transport.mjs'
|
|
16
|
+
export { TransportDiscovery, NullDiscovery } from './discovery.mjs'
|