@noy-db/by-peer 0.1.0-pre.3 → 0.1.0-pre.5
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/README.md +23 -0
- package/dist/index.cjs +47 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -1
- package/dist/index.d.ts +53 -1
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -49,6 +49,29 @@ servePeerStore({
|
|
|
49
49
|
|
|
50
50
|
Denied methods surface as a remote `Error` at the client.
|
|
51
51
|
|
|
52
|
+
## Leader election (cross-tab coordination)
|
|
53
|
+
|
|
54
|
+
When 3+ tabs share a `BroadcastChannel`-backed `PeerChannel` (typically via `@noy-db/by-tabs`) and each runs `servePeerStore`, every non-sending tab responds to every RPC — producing duplicate responses for the same request id and `O(N²)` channel traffic at scale (issue [#3](https://github.com/vLannaAi/noy-db/issues/3)).
|
|
55
|
+
|
|
56
|
+
Opt in to leader-election semantics via the Web Locks API. Only the lock-holding tab registers an RPC handler; others queue silently and take over when the holder's tab closes (the lock auto-releases).
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { tabsChannel } from '@noy-db/by-tabs'
|
|
60
|
+
import { servePeerStore } from '@noy-db/by-peer'
|
|
61
|
+
|
|
62
|
+
const channel = tabsChannel({ name: 'my-app:vault' })
|
|
63
|
+
|
|
64
|
+
servePeerStore({
|
|
65
|
+
channel,
|
|
66
|
+
store: localStore,
|
|
67
|
+
leaderElection: { lockName: 'noy-db:peer-server:my-app:vault' },
|
|
68
|
+
})
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The same `lockName` MUST be used by every tab participating in the role. Browser support: Chrome 69+, Firefox 96+, Safari 15.4+. For tests or non-browser hosts, pass a stub `MinimalLockManager` via `leaderElection.locks`.
|
|
72
|
+
|
|
73
|
+
The 2-tab case works correctly without `leaderElection` (BroadcastChannel doesn't echo to sender). Enable for any consumer expecting 3+ tabs.
|
|
74
|
+
|
|
52
75
|
## Transport abstraction
|
|
53
76
|
|
|
54
77
|
`PeerChannel` is the only primitive — any reliable in-order string channel works. The same wrapper is reused by every other `by-*` package:
|
package/dist/index.cjs
CHANGED
|
@@ -299,6 +299,12 @@ var CORE_METHODS = /* @__PURE__ */ new Set([
|
|
|
299
299
|
"listVaults"
|
|
300
300
|
]);
|
|
301
301
|
function servePeerStore(opts) {
|
|
302
|
+
if (!opts.leaderElection) {
|
|
303
|
+
return startServing(opts);
|
|
304
|
+
}
|
|
305
|
+
return startServingWithLeaderElection(opts);
|
|
306
|
+
}
|
|
307
|
+
function startServing(opts) {
|
|
302
308
|
const { store, channel, allow } = opts;
|
|
303
309
|
return serveRpc(channel, async (method, args) => {
|
|
304
310
|
if (!CORE_METHODS.has(method)) {
|
|
@@ -357,6 +363,47 @@ function servePeerStore(opts) {
|
|
|
357
363
|
throw new Error(`Unhandled method: ${method}`);
|
|
358
364
|
});
|
|
359
365
|
}
|
|
366
|
+
function startServingWithLeaderElection(opts) {
|
|
367
|
+
const leader = opts.leaderElection;
|
|
368
|
+
const locks = leader.locks ?? getDefaultLocks();
|
|
369
|
+
const ac = new AbortController();
|
|
370
|
+
let stopServing = null;
|
|
371
|
+
let releaseLock = null;
|
|
372
|
+
let disposed = false;
|
|
373
|
+
void locks.request(leader.lockName, { mode: "exclusive", signal: ac.signal }, () => {
|
|
374
|
+
if (disposed) return Promise.resolve();
|
|
375
|
+
stopServing = startServing(opts);
|
|
376
|
+
return new Promise((resolve) => {
|
|
377
|
+
releaseLock = resolve;
|
|
378
|
+
});
|
|
379
|
+
}).catch((err) => {
|
|
380
|
+
if (err?.name === "AbortError") return;
|
|
381
|
+
queueMicrotask(() => {
|
|
382
|
+
throw err;
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
return () => {
|
|
386
|
+
if (disposed) return;
|
|
387
|
+
disposed = true;
|
|
388
|
+
if (stopServing) {
|
|
389
|
+
stopServing();
|
|
390
|
+
stopServing = null;
|
|
391
|
+
}
|
|
392
|
+
if (releaseLock) {
|
|
393
|
+
releaseLock();
|
|
394
|
+
releaseLock = null;
|
|
395
|
+
} else {
|
|
396
|
+
ac.abort();
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function getDefaultLocks() {
|
|
401
|
+
const nav = globalThis.navigator;
|
|
402
|
+
if (nav && nav.locks) return nav.locks;
|
|
403
|
+
throw new Error(
|
|
404
|
+
"leaderElection requires the Web Locks API (navigator.locks). Use Chrome 69+, Firefox 96+, Safari 15.4+, or pass `leaderElection.locks: <stub>` for tests / non-browser hosts."
|
|
405
|
+
);
|
|
406
|
+
}
|
|
360
407
|
|
|
361
408
|
// src/webrtc.ts
|
|
362
409
|
function requireRTC() {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/channel.ts","../src/rpc.ts","../src/peer-store.ts","../src/serve.ts","../src/webrtc.ts"],"sourcesContent":["/**\n * **@noy-db/by-peer** — WebRTC peer-to-peer transport for noy-db.\n *\n * First member of the `by-*` family of session-share transports.\n * Previously published as `@noy-db/p2p`.\n *\n * Ships three pieces:\n *\n * 1. **`peerStore()`** — a `NoydbStore` that RPCs every operation to a\n * remote peer. Slots into `NoydbOptions.sync` as a `SyncTarget`\n * with `role: 'sync-peer'` — the sync engine treats it exactly like\n * any other store.\n *\n * 2. **`servePeerStore()`** — the remote-side listener that funnels\n * incoming RPCs into the local store.\n *\n * 3. **`createOffer()` / `acceptOffer()`** — thin WebRTC handshake\n * helpers. Signaling is out of scope — the caller ferries SDP\n * blobs over QR codes, Matrix rooms, pastebins, or whatever.\n *\n * The transport is abstract: anything that implements `PeerChannel`\n * (reliable, in-order, string messages) works. `pairInMemory()` is the\n * test/dev helper that wires two channels together in one process.\n *\n * ## Threat model\n *\n * - Peer-to-peer DTLS protects the wire.\n * - noy-db already encrypts at rest — the remote peer, any TURN relay,\n * and any on-path observer see only E2E ciphertext envelopes.\n * - The opt-in `allow` whitelist on `servePeerStore` enables read-only\n * or append-only peers (e.g. `allow = ['get', 'list', 'loadAll']`).\n *\n * @packageDocumentation\n */\n\nexport type { PeerChannel } from './channel.js'\nexport { pairInMemory, fromDataChannel } from './channel.js'\nexport type { RpcMessage, RpcRequest, RpcResponse, RpcHandler, RpcClientOptions } from './rpc.js'\nexport { createRpcClient, serveRpc } from './rpc.js'\nexport type { PeerStoreOptions } from './peer-store.js'\nexport { peerStore } from './peer-store.js'\nexport type { ServePeerStoreOptions } from './serve.js'\nexport { servePeerStore } from './serve.js'\nexport type { WebRTCOptions, Initiator, Responder } from './webrtc.js'\nexport { createOffer, acceptOffer } from './webrtc.js'\n","/**\n * `PeerChannel` — the minimal duplex message primitive used by the p2p\n * NoydbStore wrapper. Any transport that can deliver UTF-8 strings\n * reliably and in-order qualifies: WebRTC DataChannel, BroadcastChannel,\n * MessagePort, WebSocket, even postMessage pairs.\n *\n * Keeping the transport abstract has three payoffs:\n *\n * 1. **Tests run without a WebRTC polyfill.** `pairInMemory()` returns\n * two wired channels for conformance tests against `to-memory`.\n * 2. **Consumers pick their signaling story.** Matrix rooms, QR codes,\n * pastebin, Firebase Realtime DB — the handshake is out of scope.\n * 3. **Future transports slot in cheaply.** WebTransport (HTTP/3),\n * libp2p, Iroh, or a plain relay WebSocket become additional\n * bindings without touching the RPC layer.\n *\n * @module\n */\n\n/**\n * Minimal duplex message primitive.\n *\n * Implementations MUST deliver every `send` payload in order exactly\n * once to every live `on('message')` subscriber. `close()` is best-effort\n * — once called, further `send()` calls MAY throw and `on('close')` MUST\n * fire once.\n */\nexport interface PeerChannel {\n /** Enqueue a payload for delivery to the remote end. */\n send(payload: string): void\n /** Subscribe to incoming payloads or lifecycle events. Returns unsubscribe. */\n on(event: 'message', listener: (payload: string) => void): () => void\n on(event: 'close', listener: () => void): () => void\n /** Close the channel. Idempotent. */\n close(): void\n /** True once the channel is ready for `send`. */\n readonly isOpen: boolean\n}\n\n/**\n * Create a pair of in-memory `PeerChannel`s wired to each other.\n * Intended for tests and multi-tab simulations inside a single process.\n */\nexport function pairInMemory(): [PeerChannel, PeerChannel] {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n\n function make(): { ch: PeerChannel; listeners: Listeners; closed: { v: boolean } } {\n const listeners: Listeners = { message: new Set(), close: new Set() }\n const closed = { v: false }\n const ch: PeerChannel = {\n get isOpen() {\n return !closed.v\n },\n send() {\n // Placeholder — wired below.\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed.v) return\n closed.v = true\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n return { ch, listeners, closed }\n }\n\n const a = make()\n const b = make()\n\n function closeBoth(): void {\n if (!a.closed.v) {\n a.closed.v = true\n for (const fn of a.listeners.close) fn()\n }\n if (!b.closed.v) {\n b.closed.v = true\n for (const fn of b.listeners.close) fn()\n }\n }\n\n a.ch.send = (payload) => {\n if (b.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of b.listeners.message) fn(payload)\n })\n }\n b.ch.send = (payload) => {\n if (a.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of a.listeners.message) fn(payload)\n })\n }\n a.ch.close = closeBoth\n b.ch.close = closeBoth\n\n return [a.ch, b.ch]\n}\n\n/**\n * Wrap a WebRTC `RTCDataChannel` as a `PeerChannel`.\n *\n * Browser-only — the caller is responsible for establishing the\n * `RTCPeerConnection`, exchanging SDP offers/answers out of band, and\n * passing the opened DataChannel here. When the remote peer is only\n * reachable via TURN, the relay sees DTLS-wrapped ciphertext (noy-db\n * already encrypts at rest, so even a TURN compromise leaks nothing).\n */\nexport function fromDataChannel(dc: RTCDataChannel): PeerChannel {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n const listeners: Listeners = { message: new Set(), close: new Set() }\n let closed = false\n\n dc.addEventListener('message', (ev: MessageEvent) => {\n if (typeof ev.data !== 'string') return\n for (const fn of listeners.message) fn(ev.data)\n })\n dc.addEventListener('close', () => {\n if (closed) return\n closed = true\n for (const fn of listeners.close) fn()\n })\n\n return {\n get isOpen() {\n return !closed && dc.readyState === 'open'\n },\n send(payload) {\n if (closed || dc.readyState !== 'open') {\n throw new Error(`PeerChannel not open (readyState: ${dc.readyState})`)\n }\n dc.send(payload)\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed) return\n closed = true\n try {\n dc.close()\n } catch {\n // ignore — channel already torn down\n }\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n}\n","/**\n * JSON-RPC protocol over a `PeerChannel`.\n *\n * Request shape:\n * `{ t: 'req', id, method, args }`\n * Response shape (success):\n * `{ t: 'res', id, ok: true, result }`\n * Response shape (error):\n * `{ t: 'res', id, ok: false, error: { name, message, version? } }`\n *\n * Why not reuse msgpack/protobuf? The payloads are already base64-encoded\n * ciphertext — further binary packing saves ~8-12% at a large dependency\n * cost. JSON over UTF-8 is inspectable, fits the zero-dependency ethos,\n * and WebRTC DataChannel string mode already frames for us.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\n\n/** Wire format discriminator for RPC messages. */\nexport type RpcMessage = RpcRequest | RpcResponse\n\nexport interface RpcRequest {\n readonly t: 'req'\n readonly id: string\n readonly method: string\n readonly args: readonly unknown[]\n}\n\nexport interface RpcResponse {\n readonly t: 'res'\n readonly id: string\n readonly ok: boolean\n readonly result?: unknown\n readonly error?: { name: string; message: string; version?: number }\n}\n\n/** Handler invoked when an RPC request arrives. Return value is serialized as `result`. */\nexport type RpcHandler = (method: string, args: readonly unknown[]) => Promise<unknown>\n\n/** Options for a client-side RPC caller. */\nexport interface RpcClientOptions {\n /** Max milliseconds to wait for a response before rejecting. */\n timeoutMs?: number\n}\n\n/** Client: wrap a `PeerChannel` in a `call(method, args)` helper. */\nexport function createRpcClient(channel: PeerChannel, opts: RpcClientOptions = {}) {\n const timeoutMs = opts.timeoutMs ?? 30_000\n type Pending = {\n resolve: (v: unknown) => void\n reject: (err: Error) => void\n timer: ReturnType<typeof setTimeout>\n }\n const pending = new Map<string, Pending>()\n let counter = 0\n\n const offMessage = channel.on('message', (payload) => {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'res') return\n const entry = pending.get(msg.id)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(msg.id)\n if (msg.ok) {\n entry.resolve(msg.result)\n } else {\n const e = msg.error ?? { name: 'Error', message: 'unknown remote error' }\n const err = new Error(e.message)\n err.name = e.name\n if (typeof e.version === 'number') {\n ;(err as Error & { version?: number }).version = e.version\n }\n entry.reject(err)\n }\n })\n\n const offClose = channel.on('close', () => {\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('PeerChannel closed before response'))\n }\n pending.clear()\n })\n\n return {\n async call<T = unknown>(method: string, args: readonly unknown[]): Promise<T> {\n const id = `${Date.now().toString(36)}-${(++counter).toString(36)}`\n const req: RpcRequest = { t: 'req', id, method, args }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n reject(new Error(`RPC ${method} timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n pending.set(id, {\n resolve: resolve as (v: unknown) => void,\n reject,\n timer,\n })\n try {\n channel.send(JSON.stringify(req))\n } catch (err) {\n clearTimeout(timer)\n pending.delete(id)\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n })\n },\n dispose() {\n offMessage()\n offClose()\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('RPC client disposed'))\n }\n pending.clear()\n },\n }\n}\n\n/** Server: dispatch incoming RPC requests through a handler. Returns a dispose fn. */\nexport function serveRpc(channel: PeerChannel, handler: RpcHandler): () => void {\n async function handle(payload: string): Promise<void> {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'req') return\n\n let response: RpcResponse\n try {\n const result = await handler(msg.method, msg.args)\n response = { t: 'res', id: msg.id, ok: true, result }\n } catch (err) {\n const e = err as Error & { version?: number }\n response = {\n t: 'res',\n id: msg.id,\n ok: false,\n error: {\n name: e.name ?? 'Error',\n message: e.message ?? String(err),\n ...(typeof e.version === 'number' && { version: e.version }),\n },\n }\n }\n\n if (!channel.isOpen) return\n try {\n channel.send(JSON.stringify(response))\n } catch {\n // Channel closed mid-response — nothing to do.\n }\n }\n\n const offMessage = channel.on('message', (payload) => {\n void handle(payload)\n })\n\n return () => offMessage()\n}\n","/**\n * `peerStore()` — a `NoydbStore` backed by RPC calls over a `PeerChannel`.\n *\n * The local peer calls `get`/`put`/`delete`/… against this store as if\n * it were any other backend; every call is serialized as an RPC request\n * to the remote peer, which runs `servePeerStore()` to funnel the RPCs\n * into its own local `NoydbStore`.\n *\n * Error re-hydration: the remote handler re-throws `ConflictError` with\n * a `.version` field when a CAS check fails. The RPC layer carries\n * `version` in the error envelope so the local caller can catch\n * `ConflictError` with the same semantics as a direct store call.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { createRpcClient } from './rpc.js'\n\nexport interface PeerStoreOptions {\n /** The duplex channel to the remote peer. */\n readonly channel: PeerChannel\n /** Max ms to wait for any single RPC response. Default 30s. */\n readonly timeoutMs?: number\n /** Optional display name used in diagnostics. Default `'by-peer'`. */\n readonly name?: string\n}\n\n/**\n * Create a `NoydbStore` that forwards every operation to a remote peer\n * over the supplied `PeerChannel`. The remote peer must be running\n * `servePeerStore()` against its own local store.\n */\nexport function peerStore(opts: PeerStoreOptions): NoydbStore & { dispose: () => void } {\n const rpc = createRpcClient(opts.channel, { timeoutMs: opts.timeoutMs ?? 30_000 })\n\n async function call<T>(method: string, args: readonly unknown[]): Promise<T> {\n try {\n return await rpc.call<T>(method, args)\n } catch (err) {\n // Re-hydrate ConflictError so CAS semantics survive the wire hop.\n const e = err as Error & { version?: number }\n if (e.name === 'ConflictError' && typeof e.version === 'number') {\n throw new ConflictError(e.version, e.message)\n }\n throw err\n }\n }\n\n return {\n name: opts.name ?? 'by-peer',\n\n async get(vault, collection, id) {\n return call<EncryptedEnvelope | null>('get', [vault, collection, id])\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n await call<void>('put', [vault, collection, id, envelope, expectedVersion])\n },\n\n async delete(vault, collection, id) {\n await call<void>('delete', [vault, collection, id])\n },\n\n async list(vault, collection) {\n return call<string[]>('list', [vault, collection])\n },\n\n async loadAll(vault) {\n return call<VaultSnapshot>('loadAll', [vault])\n },\n\n async saveAll(vault, data) {\n await call<void>('saveAll', [vault, data])\n },\n\n async ping() {\n try {\n return await call<boolean>('ping', [])\n } catch {\n return false\n }\n },\n\n dispose() {\n rpc.dispose()\n },\n }\n}\n","/**\n * `servePeerStore()` — runs on the peer that owns the data. Listens on\n * a `PeerChannel` for RPC requests from a remote `peerStore()` client\n * and executes each one against the local `NoydbStore`.\n *\n * The 6 core methods plus the optional `ping` / `listSince` / `listPage`\n * extensions are exposed. Unknown methods surface as a remote Error.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { serveRpc } from './rpc.js'\n\nexport interface ServePeerStoreOptions {\n /** The duplex channel from the remote peer. */\n readonly channel: PeerChannel\n /** The local store to serve. */\n readonly store: NoydbStore\n /**\n * Optional method whitelist. When provided, any method not in the set\n * is rejected with \"method not allowed\". Useful for read-only peers.\n */\n readonly allow?: ReadonlySet<string>\n}\n\nconst CORE_METHODS = new Set<string>([\n 'get',\n 'put',\n 'delete',\n 'list',\n 'loadAll',\n 'saveAll',\n 'ping',\n 'listSince',\n 'listPage',\n 'listVaults',\n])\n\n/**\n * Start serving the local store on the channel. Returns a dispose\n * function that stops the RPC listener. The underlying channel is NOT\n * closed by dispose — ownership stays with the caller.\n */\nexport function servePeerStore(opts: ServePeerStoreOptions): () => void {\n const { store, channel, allow } = opts\n\n return serveRpc(channel, async (method, args) => {\n if (!CORE_METHODS.has(method)) {\n throw new Error(`Unknown RPC method: ${method}`)\n }\n if (allow && !allow.has(method)) {\n throw new Error(`Method not allowed: ${method}`)\n }\n\n switch (method) {\n case 'get': {\n const [vault, collection, id] = args as [string, string, string]\n return store.get(vault, collection, id)\n }\n case 'put': {\n const [vault, collection, id, envelope, expectedVersion] = args as [\n string,\n string,\n string,\n EncryptedEnvelope,\n number | undefined,\n ]\n await store.put(vault, collection, id, envelope, expectedVersion)\n return null\n }\n case 'delete': {\n const [vault, collection, id] = args as [string, string, string]\n await store.delete(vault, collection, id)\n return null\n }\n case 'list': {\n const [vault, collection] = args as [string, string]\n return store.list(vault, collection)\n }\n case 'loadAll': {\n const [vault] = args as [string]\n return store.loadAll(vault)\n }\n case 'saveAll': {\n const [vault, data] = args as [string, VaultSnapshot]\n await store.saveAll(vault, data)\n return null\n }\n case 'ping': {\n if (!store.ping) return true\n return store.ping()\n }\n case 'listSince': {\n if (!store.listSince) throw new Error('listSince not supported by remote store')\n const [vault, collection, since] = args as [string, string, string]\n return store.listSince(vault, collection, since)\n }\n case 'listPage': {\n if (!store.listPage) throw new Error('listPage not supported by remote store')\n const [vault, collection, cursor, limit] = args as [\n string,\n string,\n string | undefined,\n number | undefined,\n ]\n return store.listPage(vault, collection, cursor, limit)\n }\n case 'listVaults': {\n if (!store.listVaults) throw new Error('listVaults not supported by remote store')\n return store.listVaults()\n }\n }\n /* istanbul ignore next — CORE_METHODS gate makes this unreachable */\n throw new Error(`Unhandled method: ${method}`)\n })\n}\n","/**\n * WebRTC handshake helper — opinionated wrapper around\n * `RTCPeerConnection` that produces a ready-to-use `PeerChannel`.\n *\n * The handshake is split into two halves so the caller can ferry the\n * SDP blobs over whatever signaling channel they prefer (QR code,\n * Matrix room, pastebin, Firebase, signed URL…). Signaling is\n * intentionally out of scope — noy-db has no opinion on how peers\n * discover each other, only on what flows once they do.\n *\n * ```ts\n * // Peer A (initiator)\n * const a = await createOffer({ iceServers })\n * send(a.offer) // → signaling channel\n * const answer = await receive() // ← signaling channel\n * await a.accept(answer)\n * const channel = await a.channel // ready PeerChannel\n *\n * // Peer B (responder)\n * const offer = await receive() // ← signaling channel\n * const b = await acceptOffer(offer, { iceServers })\n * send(b.answer) // → signaling channel\n * const channel = await b.channel // ready PeerChannel\n * ```\n *\n * Browser-only. Node consumers who want to interconnect with browsers\n * can plug `@roamhq/wrtc` into the global `RTCPeerConnection` slot; this\n * module does not pull it in so the package has zero runtime deps.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\nimport { fromDataChannel } from './channel.js'\n\ntype PeerConnection = RTCPeerConnection\ntype SessionDescription = RTCSessionDescriptionInit\n\nexport interface WebRTCOptions {\n /** Optional ICE servers (STUN / TURN). */\n readonly iceServers?: RTCIceServer[]\n /** Label for the `RTCDataChannel`. Default `'noydb'`. */\n readonly label?: string\n}\n\nexport interface Initiator {\n readonly offer: SessionDescription\n /** Feed in the remote peer's SDP answer to complete the handshake. */\n accept(answer: SessionDescription): Promise<void>\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nexport interface Responder {\n readonly answer: SessionDescription\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nfunction requireRTC(): typeof RTCPeerConnection {\n const g = globalThis as { RTCPeerConnection?: typeof RTCPeerConnection }\n if (!g.RTCPeerConnection) {\n throw new Error(\n '[@noy-db/by-peer] globalThis.RTCPeerConnection is undefined — use this module in a browser, or polyfill with @roamhq/wrtc in Node',\n )\n }\n return g.RTCPeerConnection\n}\n\n/**\n * Build an offer as the initiating peer. Returns the SDP offer to send\n * to the remote peer and a promise for the opened `PeerChannel`.\n */\nexport async function createOffer(opts: WebRTCOptions = {}): Promise<Initiator> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const dc = pc.createDataChannel(opts.label ?? 'noydb', {\n ordered: true,\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n })\n\n const offer = await pc.createOffer()\n await pc.setLocalDescription(offer)\n await waitForIceComplete(pc)\n\n return {\n offer: pc.localDescription ?? offer,\n connection: pc,\n channel: channelPromise,\n async accept(answer) {\n await pc.setRemoteDescription(answer)\n },\n }\n}\n\n/**\n * Accept an incoming offer as the responding peer. Returns the SDP\n * answer to send back to the initiator and a promise for the opened\n * `PeerChannel`.\n */\nexport async function acceptOffer(\n offer: SessionDescription,\n opts: WebRTCOptions = {},\n): Promise<Responder> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n pc.addEventListener('datachannel', (ev) => {\n const dc = ev.channel\n if (dc.readyState === 'open') {\n resolve(fromDataChannel(dc))\n } else {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n }\n })\n })\n\n await pc.setRemoteDescription(offer)\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n await waitForIceComplete(pc)\n\n return {\n answer: pc.localDescription ?? answer,\n connection: pc,\n channel: channelPromise,\n }\n}\n\n/**\n * Resolve once ICE gathering reaches `'complete'`. Using non-trickle ICE\n * keeps the signaling exchange to a single round-trip — at the cost of\n * a slightly longer initial handshake. Consumers that want trickle ICE\n * can bypass this helper and drive `RTCPeerConnection` directly.\n */\nfunction waitForIceComplete(pc: PeerConnection): Promise<void> {\n if (pc.iceGatheringState === 'complete') return Promise.resolve()\n return new Promise((resolve) => {\n const check = () => {\n if (pc.iceGatheringState === 'complete') {\n pc.removeEventListener('icegatheringstatechange', check)\n resolve()\n }\n }\n pc.addEventListener('icegatheringstatechange', check)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2CO,SAAS,eAA2C;AAMzD,WAAS,OAA0E;AACjF,UAAM,YAAuB,EAAE,SAAS,oBAAI,IAAI,GAAG,OAAO,oBAAI,IAAI,EAAE;AACpE,UAAM,SAAS,EAAE,GAAG,MAAM;AAC1B,UAAM,KAAkB;AAAA,MACtB,IAAI,SAAS;AACX,eAAO,CAAC,OAAO;AAAA,MACjB;AAAA,MACA,OAAO;AAAA,MAEP;AAAA,MACA,GAAG,OAA4B,UAAkE;AAC/F,YAAI,UAAU,WAAW;AACvB,oBAAU,QAAQ,IAAI,QAA+B;AACrD,iBAAO,MAAM,UAAU,QAAQ,OAAO,QAA+B;AAAA,QACvE;AACA,kBAAU,MAAM,IAAI,QAAsB;AAC1C,eAAO,MAAM,UAAU,MAAM,OAAO,QAAsB;AAAA,MAC5D;AAAA,MACA,QAAQ;AACN,YAAI,OAAO,EAAG;AACd,eAAO,IAAI;AACX,mBAAW,MAAM,UAAU,MAAO,IAAG;AAAA,MACvC;AAAA,IACF;AACA,WAAO,EAAE,IAAI,WAAW,OAAO;AAAA,EACjC;AAEA,QAAM,IAAI,KAAK;AACf,QAAM,IAAI,KAAK;AAEf,WAAS,YAAkB;AACzB,QAAI,CAAC,EAAE,OAAO,GAAG;AAC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,KAAK,WAAW;AAAA,EACvD,CAAC;AAED,QAAM,iBAAiB,IAAI,QAAqB,CAAC,SAAS,WAAW;AACnE,OAAG,iBAAiB,eAAe,CAAC,OAAO;AACzC,YAAM,KAAK,GAAG;AACd,UAAI,GAAG,eAAe,QAAQ;AAC5B,gBAAQ,gBAAgB,EAAE,CAAC;AAAA,MAC7B,OAAO;AACL,WAAG,iBAAiB,QAAQ,MAAM,QAAQ,gBAAgB,EAAE,CAAC,CAAC;AAC9D,WAAG,iBAAiB,SAAS,MAAM,OAAO,IAAI,MAAM,mBAAmB,CAAC,CAAC;AAAA,MAC3E;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,QAAM,GAAG,qBAAqB,KAAK;AACnC,QAAM,SAAS,MAAM,GAAG,aAAa;AACrC,QAAM,GAAG,oBAAoB,MAAM;AACnC,QAAM,mBAAmB,EAAE;AAE3B,SAAO;AAAA,IACL,QAAQ,GAAG,oBAAoB;AAAA,IAC/B,YAAY;AAAA,IACZ,SAAS;AAAA,EACX;AACF;AAQA,SAAS,mBAAmB,IAAmC;AAC7D,MAAI,GAAG,sBAAsB,WAAY,QAAO,QAAQ,QAAQ;AAChE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,QAAQ,MAAM;AAClB,UAAI,GAAG,sBAAsB,YAAY;AACvC,WAAG,oBAAoB,2BAA2B,KAAK;AACvD,gBAAQ;AAAA,MACV;AAAA,IACF;AACA,OAAG,iBAAiB,2BAA2B,KAAK;AAAA,EACtD,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/channel.ts","../src/rpc.ts","../src/peer-store.ts","../src/serve.ts","../src/webrtc.ts"],"sourcesContent":["/**\n * **@noy-db/by-peer** — WebRTC peer-to-peer transport for noy-db.\n *\n * First member of the `by-*` family of session-share transports.\n * Previously published as `@noy-db/p2p`.\n *\n * Ships three pieces:\n *\n * 1. **`peerStore()`** — a `NoydbStore` that RPCs every operation to a\n * remote peer. Slots into `NoydbOptions.sync` as a `SyncTarget`\n * with `role: 'sync-peer'` — the sync engine treats it exactly like\n * any other store.\n *\n * 2. **`servePeerStore()`** — the remote-side listener that funnels\n * incoming RPCs into the local store.\n *\n * 3. **`createOffer()` / `acceptOffer()`** — thin WebRTC handshake\n * helpers. Signaling is out of scope — the caller ferries SDP\n * blobs over QR codes, Matrix rooms, pastebins, or whatever.\n *\n * The transport is abstract: anything that implements `PeerChannel`\n * (reliable, in-order, string messages) works. `pairInMemory()` is the\n * test/dev helper that wires two channels together in one process.\n *\n * ## Threat model\n *\n * - Peer-to-peer DTLS protects the wire.\n * - noy-db already encrypts at rest — the remote peer, any TURN relay,\n * and any on-path observer see only E2E ciphertext envelopes.\n * - The opt-in `allow` whitelist on `servePeerStore` enables read-only\n * or append-only peers (e.g. `allow = ['get', 'list', 'loadAll']`).\n *\n * @packageDocumentation\n */\n\nexport type { PeerChannel } from './channel.js'\nexport { pairInMemory, fromDataChannel } from './channel.js'\nexport type { RpcMessage, RpcRequest, RpcResponse, RpcHandler, RpcClientOptions } from './rpc.js'\nexport { createRpcClient, serveRpc } from './rpc.js'\nexport type { PeerStoreOptions } from './peer-store.js'\nexport { peerStore } from './peer-store.js'\nexport type { ServePeerStoreOptions, MinimalLockManager } from './serve.js'\nexport { servePeerStore } from './serve.js'\nexport type { WebRTCOptions, Initiator, Responder } from './webrtc.js'\nexport { createOffer, acceptOffer } from './webrtc.js'\n","/**\n * `PeerChannel` — the minimal duplex message primitive used by the p2p\n * NoydbStore wrapper. Any transport that can deliver UTF-8 strings\n * reliably and in-order qualifies: WebRTC DataChannel, BroadcastChannel,\n * MessagePort, WebSocket, even postMessage pairs.\n *\n * Keeping the transport abstract has three payoffs:\n *\n * 1. **Tests run without a WebRTC polyfill.** `pairInMemory()` returns\n * two wired channels for conformance tests against `to-memory`.\n * 2. **Consumers pick their signaling story.** Matrix rooms, QR codes,\n * pastebin, Firebase Realtime DB — the handshake is out of scope.\n * 3. **Future transports slot in cheaply.** WebTransport (HTTP/3),\n * libp2p, Iroh, or a plain relay WebSocket become additional\n * bindings without touching the RPC layer.\n *\n * @module\n */\n\n/**\n * Minimal duplex message primitive.\n *\n * Implementations MUST deliver every `send` payload in order exactly\n * once to every live `on('message')` subscriber. `close()` is best-effort\n * — once called, further `send()` calls MAY throw and `on('close')` MUST\n * fire once.\n */\nexport interface PeerChannel {\n /** Enqueue a payload for delivery to the remote end. */\n send(payload: string): void\n /** Subscribe to incoming payloads or lifecycle events. Returns unsubscribe. */\n on(event: 'message', listener: (payload: string) => void): () => void\n on(event: 'close', listener: () => void): () => void\n /** Close the channel. Idempotent. */\n close(): void\n /** True once the channel is ready for `send`. */\n readonly isOpen: boolean\n}\n\n/**\n * Create a pair of in-memory `PeerChannel`s wired to each other.\n * Intended for tests and multi-tab simulations inside a single process.\n */\nexport function pairInMemory(): [PeerChannel, PeerChannel] {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n\n function make(): { ch: PeerChannel; listeners: Listeners; closed: { v: boolean } } {\n const listeners: Listeners = { message: new Set(), close: new Set() }\n const closed = { v: false }\n const ch: PeerChannel = {\n get isOpen() {\n return !closed.v\n },\n send() {\n // Placeholder — wired below.\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed.v) return\n closed.v = true\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n return { ch, listeners, closed }\n }\n\n const a = make()\n const b = make()\n\n function closeBoth(): void {\n if (!a.closed.v) {\n a.closed.v = true\n for (const fn of a.listeners.close) fn()\n }\n if (!b.closed.v) {\n b.closed.v = true\n for (const fn of b.listeners.close) fn()\n }\n }\n\n a.ch.send = (payload) => {\n if (b.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of b.listeners.message) fn(payload)\n })\n }\n b.ch.send = (payload) => {\n if (a.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of a.listeners.message) fn(payload)\n })\n }\n a.ch.close = closeBoth\n b.ch.close = closeBoth\n\n return [a.ch, b.ch]\n}\n\n/**\n * Wrap a WebRTC `RTCDataChannel` as a `PeerChannel`.\n *\n * Browser-only — the caller is responsible for establishing the\n * `RTCPeerConnection`, exchanging SDP offers/answers out of band, and\n * passing the opened DataChannel here. When the remote peer is only\n * reachable via TURN, the relay sees DTLS-wrapped ciphertext (noy-db\n * already encrypts at rest, so even a TURN compromise leaks nothing).\n */\nexport function fromDataChannel(dc: RTCDataChannel): PeerChannel {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n const listeners: Listeners = { message: new Set(), close: new Set() }\n let closed = false\n\n dc.addEventListener('message', (ev: MessageEvent) => {\n if (typeof ev.data !== 'string') return\n for (const fn of listeners.message) fn(ev.data)\n })\n dc.addEventListener('close', () => {\n if (closed) return\n closed = true\n for (const fn of listeners.close) fn()\n })\n\n return {\n get isOpen() {\n return !closed && dc.readyState === 'open'\n },\n send(payload) {\n if (closed || dc.readyState !== 'open') {\n throw new Error(`PeerChannel not open (readyState: ${dc.readyState})`)\n }\n dc.send(payload)\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed) return\n closed = true\n try {\n dc.close()\n } catch {\n // ignore — channel already torn down\n }\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n}\n","/**\n * JSON-RPC protocol over a `PeerChannel`.\n *\n * Request shape:\n * `{ t: 'req', id, method, args }`\n * Response shape (success):\n * `{ t: 'res', id, ok: true, result }`\n * Response shape (error):\n * `{ t: 'res', id, ok: false, error: { name, message, version? } }`\n *\n * Why not reuse msgpack/protobuf? The payloads are already base64-encoded\n * ciphertext — further binary packing saves ~8-12% at a large dependency\n * cost. JSON over UTF-8 is inspectable, fits the zero-dependency ethos,\n * and WebRTC DataChannel string mode already frames for us.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\n\n/** Wire format discriminator for RPC messages. */\nexport type RpcMessage = RpcRequest | RpcResponse\n\nexport interface RpcRequest {\n readonly t: 'req'\n readonly id: string\n readonly method: string\n readonly args: readonly unknown[]\n}\n\nexport interface RpcResponse {\n readonly t: 'res'\n readonly id: string\n readonly ok: boolean\n readonly result?: unknown\n readonly error?: { name: string; message: string; version?: number }\n}\n\n/** Handler invoked when an RPC request arrives. Return value is serialized as `result`. */\nexport type RpcHandler = (method: string, args: readonly unknown[]) => Promise<unknown>\n\n/** Options for a client-side RPC caller. */\nexport interface RpcClientOptions {\n /** Max milliseconds to wait for a response before rejecting. */\n timeoutMs?: number\n}\n\n/** Client: wrap a `PeerChannel` in a `call(method, args)` helper. */\nexport function createRpcClient(channel: PeerChannel, opts: RpcClientOptions = {}) {\n const timeoutMs = opts.timeoutMs ?? 30_000\n type Pending = {\n resolve: (v: unknown) => void\n reject: (err: Error) => void\n timer: ReturnType<typeof setTimeout>\n }\n const pending = new Map<string, Pending>()\n let counter = 0\n\n const offMessage = channel.on('message', (payload) => {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'res') return\n const entry = pending.get(msg.id)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(msg.id)\n if (msg.ok) {\n entry.resolve(msg.result)\n } else {\n const e = msg.error ?? { name: 'Error', message: 'unknown remote error' }\n const err = new Error(e.message)\n err.name = e.name\n if (typeof e.version === 'number') {\n ;(err as Error & { version?: number }).version = e.version\n }\n entry.reject(err)\n }\n })\n\n const offClose = channel.on('close', () => {\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('PeerChannel closed before response'))\n }\n pending.clear()\n })\n\n return {\n async call<T = unknown>(method: string, args: readonly unknown[]): Promise<T> {\n const id = `${Date.now().toString(36)}-${(++counter).toString(36)}`\n const req: RpcRequest = { t: 'req', id, method, args }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n reject(new Error(`RPC ${method} timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n pending.set(id, {\n resolve: resolve as (v: unknown) => void,\n reject,\n timer,\n })\n try {\n channel.send(JSON.stringify(req))\n } catch (err) {\n clearTimeout(timer)\n pending.delete(id)\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n })\n },\n dispose() {\n offMessage()\n offClose()\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('RPC client disposed'))\n }\n pending.clear()\n },\n }\n}\n\n/** Server: dispatch incoming RPC requests through a handler. Returns a dispose fn. */\nexport function serveRpc(channel: PeerChannel, handler: RpcHandler): () => void {\n async function handle(payload: string): Promise<void> {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'req') return\n\n let response: RpcResponse\n try {\n const result = await handler(msg.method, msg.args)\n response = { t: 'res', id: msg.id, ok: true, result }\n } catch (err) {\n const e = err as Error & { version?: number }\n response = {\n t: 'res',\n id: msg.id,\n ok: false,\n error: {\n name: e.name ?? 'Error',\n message: e.message ?? String(err),\n ...(typeof e.version === 'number' && { version: e.version }),\n },\n }\n }\n\n if (!channel.isOpen) return\n try {\n channel.send(JSON.stringify(response))\n } catch {\n // Channel closed mid-response — nothing to do.\n }\n }\n\n const offMessage = channel.on('message', (payload) => {\n void handle(payload)\n })\n\n return () => offMessage()\n}\n","/**\n * `peerStore()` — a `NoydbStore` backed by RPC calls over a `PeerChannel`.\n *\n * The local peer calls `get`/`put`/`delete`/… against this store as if\n * it were any other backend; every call is serialized as an RPC request\n * to the remote peer, which runs `servePeerStore()` to funnel the RPCs\n * into its own local `NoydbStore`.\n *\n * Error re-hydration: the remote handler re-throws `ConflictError` with\n * a `.version` field when a CAS check fails. The RPC layer carries\n * `version` in the error envelope so the local caller can catch\n * `ConflictError` with the same semantics as a direct store call.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { createRpcClient } from './rpc.js'\n\nexport interface PeerStoreOptions {\n /** The duplex channel to the remote peer. */\n readonly channel: PeerChannel\n /** Max ms to wait for any single RPC response. Default 30s. */\n readonly timeoutMs?: number\n /** Optional display name used in diagnostics. Default `'by-peer'`. */\n readonly name?: string\n}\n\n/**\n * Create a `NoydbStore` that forwards every operation to a remote peer\n * over the supplied `PeerChannel`. The remote peer must be running\n * `servePeerStore()` against its own local store.\n */\nexport function peerStore(opts: PeerStoreOptions): NoydbStore & { dispose: () => void } {\n const rpc = createRpcClient(opts.channel, { timeoutMs: opts.timeoutMs ?? 30_000 })\n\n async function call<T>(method: string, args: readonly unknown[]): Promise<T> {\n try {\n return await rpc.call<T>(method, args)\n } catch (err) {\n // Re-hydrate ConflictError so CAS semantics survive the wire hop.\n const e = err as Error & { version?: number }\n if (e.name === 'ConflictError' && typeof e.version === 'number') {\n throw new ConflictError(e.version, e.message)\n }\n throw err\n }\n }\n\n return {\n name: opts.name ?? 'by-peer',\n\n async get(vault, collection, id) {\n return call<EncryptedEnvelope | null>('get', [vault, collection, id])\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n await call<void>('put', [vault, collection, id, envelope, expectedVersion])\n },\n\n async delete(vault, collection, id) {\n await call<void>('delete', [vault, collection, id])\n },\n\n async list(vault, collection) {\n return call<string[]>('list', [vault, collection])\n },\n\n async loadAll(vault) {\n return call<VaultSnapshot>('loadAll', [vault])\n },\n\n async saveAll(vault, data) {\n await call<void>('saveAll', [vault, data])\n },\n\n async ping() {\n try {\n return await call<boolean>('ping', [])\n } catch {\n return false\n }\n },\n\n dispose() {\n rpc.dispose()\n },\n }\n}\n","/**\n * `servePeerStore()` — runs on the peer that owns the data. Listens on\n * a `PeerChannel` for RPC requests from a remote `peerStore()` client\n * and executes each one against the local `NoydbStore`.\n *\n * The 6 core methods plus the optional `ping` / `listSince` / `listPage`\n * extensions are exposed. Unknown methods surface as a remote Error.\n *\n * **Leader-election (issue #3).** When a `BroadcastChannel`-backed\n * `PeerChannel` is shared by 3+ tabs each running `servePeerStore`,\n * every non-sending tab responds to every RPC — producing duplicate\n * responses for the same request id and O(N²) channel traffic at scale.\n * Pass `leaderElection: { lockName, locks? }` to gate serving on the\n * Web Locks API: only the lock-holding tab registers an RPC handler;\n * others queue and take over when the holder's tab closes (lock auto-\n * releases). Default behaviour (no `leaderElection`) is unchanged for\n * the 2-tab case.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { serveRpc } from './rpc.js'\n\n/**\n * Minimal subset of the Web Locks API used by leader-election. The\n * browser's `navigator.locks` satisfies this; tests inject a stub.\n *\n * @public\n */\nexport interface MinimalLockManager {\n request<T>(\n name: string,\n options: { mode?: 'exclusive' | 'shared'; signal?: AbortSignal },\n callback: (lock: unknown) => Promise<T>,\n ): Promise<T>\n}\n\nexport interface ServePeerStoreOptions {\n /** The duplex channel from the remote peer. */\n readonly channel: PeerChannel\n /** The local store to serve. */\n readonly store: NoydbStore\n /**\n * Optional method whitelist. When provided, any method not in the set\n * is rejected with \"method not allowed\". Useful for read-only peers.\n */\n readonly allow?: ReadonlySet<string>\n /**\n * Opt in to leader-election semantics for cross-tab coordination via\n * the Web Locks API. Required when 3+ tabs share a `BroadcastChannel`-\n * backed `PeerChannel` — without leader election, every non-sending tab\n * responds to every RPC, producing duplicate responses (issue #3).\n *\n * Browser support: Chrome 69+, Firefox 96+, Safari 15.4+.\n *\n * - `lockName` — globally unique lock name. Convention:\n * `noy-db:peer-server:<channel-name>`. The same `lockName` MUST be\n * used by every tab that wants to share the leader role.\n * - `locks` — defaults to `navigator.locks` in browsers. Pass a stub\n * for tests or for non-browser hosts that polyfill the Web Locks API.\n *\n * Behaviour: at most one tab holds the lock at a time. Only that tab\n * registers an RPC handler on the channel; other tabs queue (their\n * `servePeerStore` call returns a working dispose function but does\n * not respond to incoming RPCs). When the holder's tab closes (or its\n * `servePeerStore` is disposed), the next queued tab takes over.\n */\n readonly leaderElection?: {\n readonly lockName: string\n readonly locks?: MinimalLockManager\n }\n}\n\nconst CORE_METHODS = new Set<string>([\n 'get',\n 'put',\n 'delete',\n 'list',\n 'loadAll',\n 'saveAll',\n 'ping',\n 'listSince',\n 'listPage',\n 'listVaults',\n])\n\n/**\n * Start serving the local store on the channel. Returns a dispose\n * function that stops the RPC listener. The underlying channel is NOT\n * closed by dispose — ownership stays with the caller.\n *\n * When `leaderElection` is set, the RPC handler is only registered while\n * this tab holds the named Web Lock. The returned dispose function\n * always works: if called before the lock is acquired, it cancels the\n * wait; if called while holding the lock, it releases the lock and\n * stops serving.\n */\nexport function servePeerStore(opts: ServePeerStoreOptions): () => void {\n if (!opts.leaderElection) {\n return startServing(opts)\n }\n return startServingWithLeaderElection(opts)\n}\n\n/**\n * Register the RPC handler immediately. Used when leader-election is off,\n * and inside the lock callback when on.\n */\nfunction startServing(opts: ServePeerStoreOptions): () => void {\n const { store, channel, allow } = opts\n\n return serveRpc(channel, async (method, args) => {\n if (!CORE_METHODS.has(method)) {\n throw new Error(`Unknown RPC method: ${method}`)\n }\n if (allow && !allow.has(method)) {\n throw new Error(`Method not allowed: ${method}`)\n }\n\n switch (method) {\n case 'get': {\n const [vault, collection, id] = args as [string, string, string]\n return store.get(vault, collection, id)\n }\n case 'put': {\n const [vault, collection, id, envelope, expectedVersion] = args as [\n string,\n string,\n string,\n EncryptedEnvelope,\n number | undefined,\n ]\n await store.put(vault, collection, id, envelope, expectedVersion)\n return null\n }\n case 'delete': {\n const [vault, collection, id] = args as [string, string, string]\n await store.delete(vault, collection, id)\n return null\n }\n case 'list': {\n const [vault, collection] = args as [string, string]\n return store.list(vault, collection)\n }\n case 'loadAll': {\n const [vault] = args as [string]\n return store.loadAll(vault)\n }\n case 'saveAll': {\n const [vault, data] = args as [string, VaultSnapshot]\n await store.saveAll(vault, data)\n return null\n }\n case 'ping': {\n if (!store.ping) return true\n return store.ping()\n }\n case 'listSince': {\n if (!store.listSince) throw new Error('listSince not supported by remote store')\n const [vault, collection, since] = args as [string, string, string]\n return store.listSince(vault, collection, since)\n }\n case 'listPage': {\n if (!store.listPage) throw new Error('listPage not supported by remote store')\n const [vault, collection, cursor, limit] = args as [\n string,\n string,\n string | undefined,\n number | undefined,\n ]\n return store.listPage(vault, collection, cursor, limit)\n }\n case 'listVaults': {\n if (!store.listVaults) throw new Error('listVaults not supported by remote store')\n return store.listVaults()\n }\n }\n /* istanbul ignore next — CORE_METHODS gate makes this unreachable */\n throw new Error(`Unhandled method: ${method}`)\n })\n}\n\n/**\n * Acquire a Web Lock first; only register the RPC listener while\n * holding it. Returns a dispose that cancels the wait (if not yet\n * acquired) or releases the lock (if held).\n */\nfunction startServingWithLeaderElection(opts: ServePeerStoreOptions): () => void {\n // Asserted by the caller branch in `servePeerStore`.\n const leader = opts.leaderElection as { lockName: string; locks?: MinimalLockManager }\n const locks = leader.locks ?? getDefaultLocks()\n const ac = new AbortController()\n let stopServing: (() => void) | null = null\n let releaseLock: (() => void) | null = null\n let disposed = false\n\n void locks\n .request(leader.lockName, { mode: 'exclusive', signal: ac.signal }, () => {\n if (disposed) return Promise.resolve()\n stopServing = startServing(opts)\n // Hold the lock for the lifetime of this tab's leadership. The\n // returned promise stays pending until `releaseLock` is called by\n // the dispose function.\n return new Promise<void>((resolve) => {\n releaseLock = resolve\n })\n })\n .catch((err: unknown) => {\n // AbortError is the expected cancellation when dispose runs before\n // the lock was acquired. Anything else is unexpected — surface it\n // at the next tick so the host can observe it.\n if ((err as { name?: string } | null)?.name === 'AbortError') return\n queueMicrotask(() => {\n throw err\n })\n })\n\n return () => {\n if (disposed) return\n disposed = true\n if (stopServing) {\n stopServing()\n stopServing = null\n }\n if (releaseLock) {\n releaseLock()\n releaseLock = null\n } else {\n ac.abort()\n }\n }\n}\n\nfunction getDefaultLocks(): MinimalLockManager {\n const nav = (globalThis as { navigator?: { locks?: MinimalLockManager } }).navigator\n if (nav && nav.locks) return nav.locks\n throw new Error(\n 'leaderElection requires the Web Locks API (navigator.locks). ' +\n 'Use Chrome 69+, Firefox 96+, Safari 15.4+, or pass `leaderElection.locks: <stub>` ' +\n 'for tests / non-browser hosts.',\n )\n}\n","/**\n * WebRTC handshake helper — opinionated wrapper around\n * `RTCPeerConnection` that produces a ready-to-use `PeerChannel`.\n *\n * The handshake is split into two halves so the caller can ferry the\n * SDP blobs over whatever signaling channel they prefer (QR code,\n * Matrix room, pastebin, Firebase, signed URL…). Signaling is\n * intentionally out of scope — noy-db has no opinion on how peers\n * discover each other, only on what flows once they do.\n *\n * ```ts\n * // Peer A (initiator)\n * const a = await createOffer({ iceServers })\n * send(a.offer) // → signaling channel\n * const answer = await receive() // ← signaling channel\n * await a.accept(answer)\n * const channel = await a.channel // ready PeerChannel\n *\n * // Peer B (responder)\n * const offer = await receive() // ← signaling channel\n * const b = await acceptOffer(offer, { iceServers })\n * send(b.answer) // → signaling channel\n * const channel = await b.channel // ready PeerChannel\n * ```\n *\n * Browser-only. Node consumers who want to interconnect with browsers\n * can plug `@roamhq/wrtc` into the global `RTCPeerConnection` slot; this\n * module does not pull it in so the package has zero runtime deps.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\nimport { fromDataChannel } from './channel.js'\n\ntype PeerConnection = RTCPeerConnection\ntype SessionDescription = RTCSessionDescriptionInit\n\nexport interface WebRTCOptions {\n /** Optional ICE servers (STUN / TURN). */\n readonly iceServers?: RTCIceServer[]\n /** Label for the `RTCDataChannel`. Default `'noydb'`. */\n readonly label?: string\n}\n\nexport interface Initiator {\n readonly offer: SessionDescription\n /** Feed in the remote peer's SDP answer to complete the handshake. */\n accept(answer: SessionDescription): Promise<void>\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nexport interface Responder {\n readonly answer: SessionDescription\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nfunction requireRTC(): typeof RTCPeerConnection {\n const g = globalThis as { RTCPeerConnection?: typeof RTCPeerConnection }\n if (!g.RTCPeerConnection) {\n throw new Error(\n '[@noy-db/by-peer] globalThis.RTCPeerConnection is undefined — use this module in a browser, or polyfill with @roamhq/wrtc in Node',\n )\n }\n return g.RTCPeerConnection\n}\n\n/**\n * Build an offer as the initiating peer. Returns the SDP offer to send\n * to the remote peer and a promise for the opened `PeerChannel`.\n */\nexport async function createOffer(opts: WebRTCOptions = {}): Promise<Initiator> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const dc = pc.createDataChannel(opts.label ?? 'noydb', {\n ordered: true,\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n })\n\n const offer = await pc.createOffer()\n await pc.setLocalDescription(offer)\n await waitForIceComplete(pc)\n\n return {\n offer: pc.localDescription ?? offer,\n connection: pc,\n channel: channelPromise,\n async accept(answer) {\n await pc.setRemoteDescription(answer)\n },\n }\n}\n\n/**\n * Accept an incoming offer as the responding peer. Returns the SDP\n * answer to send back to the initiator and a promise for the opened\n * `PeerChannel`.\n */\nexport async function acceptOffer(\n offer: SessionDescription,\n opts: WebRTCOptions = {},\n): Promise<Responder> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n pc.addEventListener('datachannel', (ev) => {\n const dc = ev.channel\n if (dc.readyState === 'open') {\n resolve(fromDataChannel(dc))\n } else {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n }\n })\n })\n\n await pc.setRemoteDescription(offer)\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n await waitForIceComplete(pc)\n\n return {\n answer: pc.localDescription ?? answer,\n connection: pc,\n channel: channelPromise,\n }\n}\n\n/**\n * Resolve once ICE gathering reaches `'complete'`. Using non-trickle ICE\n * keeps the signaling exchange to a single round-trip — at the cost of\n * a slightly longer initial handshake. Consumers that want trickle ICE\n * can bypass this helper and drive `RTCPeerConnection` directly.\n */\nfunction waitForIceComplete(pc: PeerConnection): Promise<void> {\n if (pc.iceGatheringState === 'complete') return Promise.resolve()\n return new Promise((resolve) => {\n const check = () => {\n if (pc.iceGatheringState === 'complete') {\n pc.removeEventListener('icegatheringstatechange', check)\n resolve()\n }\n }\n pc.addEventListener('icegatheringstatechange', check)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2CO,SAAS,eAA2C;AAMzD,WAAS,OAA0E;AACjF,UAAM,YAAuB,EAAE,SAAS,oBAAI,IAAI,GAAG,OAAO,oBAAI,IAAI,EAAE;AACpE,UAAM,SAAS,EAAE,GAAG,MAAM;AAC1B,UAAM,KAAkB;AAAA,MACtB,IAAI,SAAS;AACX,eAAO,CAAC,OAAO;AAAA,MACjB;AAAA,MACA,OAAO;AAAA,MAEP;AAAA,MACA,GAAG,OAA4B,UAAkE;AAC/F,YAAI,UAAU,WAAW;AACvB,oBAAU,QAAQ,IAAI,QAA+B;AACrD,iBAAO,MAAM,UAAU,QAAQ,OAAO,QAA+B;AAAA,QACvE;AACA,kBAAU,MAAM,IAAI,QAAsB;AAC1C,eAAO,MAAM,UAAU,MAAM,OAAO,QAAsB;AAA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,IAAI,IAAI;AAAA,IACjB,GAAI,KAAK,cAAc,EAAE,YAAY,KAAK,WAAW;AAAA,EACvD,CAAC;AAED,QAAM,iBAAiB,IAAI,QAAqB,CAAC,SAAS,WAAW;AACnE,OAAG,iBAAiB,eAAe,CAAC,OAAO;AACzC,YAAM,KAAK,GAAG;AACd,UAAI,GAAG,eAAe,QAAQ;AAC5B,gBAAQ,gBAAgB,EAAE,CAAC;AAAA,MAC7B,OAAO;AACL,WAAG,iBAAiB,QAAQ,MAAM,QAAQ,gBAAgB,EAAE,CAAC,CAAC;AAC9D,WAAG,iBAAiB,SAAS,MAAM,OAAO,IAAI,MAAM,mBAAmB,CAAC,CAAC;AAAA,MAC3E;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,QAAM,GAAG,qBAAqB,KAAK;AACnC,QAAM,SAAS,MAAM,GAAG,aAAa;AACrC,QAAM,GAAG,oBAAoB,MAAM;AACnC,QAAM,mBAAmB,EAAE;AAE3B,SAAO;AAAA,IACL,QAAQ,GAAG,oBAAoB;AAAA,IAC/B,YAAY;AAAA,IACZ,SAAS;AAAA,EACX;AACF;AAQA,SAAS,mBAAmB,IAAmC;AAC7D,MAAI,GAAG,sBAAsB,WAAY,QAAO,QAAQ,QAAQ;AAChE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,QAAQ,MAAM;AAClB,UAAI,GAAG,sBAAsB,YAAY;AACvC,WAAG,oBAAoB,2BAA2B,KAAK;AACvD,gBAAQ;AAAA,MACV;AAAA,IACF;AACA,OAAG,iBAAiB,2BAA2B,KAAK;AAAA,EACtD,CAAC;AACH;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -146,9 +146,31 @@ declare function peerStore(opts: PeerStoreOptions): NoydbStore & {
|
|
|
146
146
|
* The 6 core methods plus the optional `ping` / `listSince` / `listPage`
|
|
147
147
|
* extensions are exposed. Unknown methods surface as a remote Error.
|
|
148
148
|
*
|
|
149
|
+
* **Leader-election (issue #3).** When a `BroadcastChannel`-backed
|
|
150
|
+
* `PeerChannel` is shared by 3+ tabs each running `servePeerStore`,
|
|
151
|
+
* every non-sending tab responds to every RPC — producing duplicate
|
|
152
|
+
* responses for the same request id and O(N²) channel traffic at scale.
|
|
153
|
+
* Pass `leaderElection: { lockName, locks? }` to gate serving on the
|
|
154
|
+
* Web Locks API: only the lock-holding tab registers an RPC handler;
|
|
155
|
+
* others queue and take over when the holder's tab closes (lock auto-
|
|
156
|
+
* releases). Default behaviour (no `leaderElection`) is unchanged for
|
|
157
|
+
* the 2-tab case.
|
|
158
|
+
*
|
|
149
159
|
* @module
|
|
150
160
|
*/
|
|
151
161
|
|
|
162
|
+
/**
|
|
163
|
+
* Minimal subset of the Web Locks API used by leader-election. The
|
|
164
|
+
* browser's `navigator.locks` satisfies this; tests inject a stub.
|
|
165
|
+
*
|
|
166
|
+
* @public
|
|
167
|
+
*/
|
|
168
|
+
interface MinimalLockManager {
|
|
169
|
+
request<T>(name: string, options: {
|
|
170
|
+
mode?: 'exclusive' | 'shared';
|
|
171
|
+
signal?: AbortSignal;
|
|
172
|
+
}, callback: (lock: unknown) => Promise<T>): Promise<T>;
|
|
173
|
+
}
|
|
152
174
|
interface ServePeerStoreOptions {
|
|
153
175
|
/** The duplex channel from the remote peer. */
|
|
154
176
|
readonly channel: PeerChannel;
|
|
@@ -159,11 +181,41 @@ interface ServePeerStoreOptions {
|
|
|
159
181
|
* is rejected with "method not allowed". Useful for read-only peers.
|
|
160
182
|
*/
|
|
161
183
|
readonly allow?: ReadonlySet<string>;
|
|
184
|
+
/**
|
|
185
|
+
* Opt in to leader-election semantics for cross-tab coordination via
|
|
186
|
+
* the Web Locks API. Required when 3+ tabs share a `BroadcastChannel`-
|
|
187
|
+
* backed `PeerChannel` — without leader election, every non-sending tab
|
|
188
|
+
* responds to every RPC, producing duplicate responses (issue #3).
|
|
189
|
+
*
|
|
190
|
+
* Browser support: Chrome 69+, Firefox 96+, Safari 15.4+.
|
|
191
|
+
*
|
|
192
|
+
* - `lockName` — globally unique lock name. Convention:
|
|
193
|
+
* `noy-db:peer-server:<channel-name>`. The same `lockName` MUST be
|
|
194
|
+
* used by every tab that wants to share the leader role.
|
|
195
|
+
* - `locks` — defaults to `navigator.locks` in browsers. Pass a stub
|
|
196
|
+
* for tests or for non-browser hosts that polyfill the Web Locks API.
|
|
197
|
+
*
|
|
198
|
+
* Behaviour: at most one tab holds the lock at a time. Only that tab
|
|
199
|
+
* registers an RPC handler on the channel; other tabs queue (their
|
|
200
|
+
* `servePeerStore` call returns a working dispose function but does
|
|
201
|
+
* not respond to incoming RPCs). When the holder's tab closes (or its
|
|
202
|
+
* `servePeerStore` is disposed), the next queued tab takes over.
|
|
203
|
+
*/
|
|
204
|
+
readonly leaderElection?: {
|
|
205
|
+
readonly lockName: string;
|
|
206
|
+
readonly locks?: MinimalLockManager;
|
|
207
|
+
};
|
|
162
208
|
}
|
|
163
209
|
/**
|
|
164
210
|
* Start serving the local store on the channel. Returns a dispose
|
|
165
211
|
* function that stops the RPC listener. The underlying channel is NOT
|
|
166
212
|
* closed by dispose — ownership stays with the caller.
|
|
213
|
+
*
|
|
214
|
+
* When `leaderElection` is set, the RPC handler is only registered while
|
|
215
|
+
* this tab holds the named Web Lock. The returned dispose function
|
|
216
|
+
* always works: if called before the lock is acquired, it cancels the
|
|
217
|
+
* wait; if called while holding the lock, it releases the lock and
|
|
218
|
+
* stops serving.
|
|
167
219
|
*/
|
|
168
220
|
declare function servePeerStore(opts: ServePeerStoreOptions): () => void;
|
|
169
221
|
|
|
@@ -233,4 +285,4 @@ declare function createOffer(opts?: WebRTCOptions): Promise<Initiator>;
|
|
|
233
285
|
*/
|
|
234
286
|
declare function acceptOffer(offer: SessionDescription, opts?: WebRTCOptions): Promise<Responder>;
|
|
235
287
|
|
|
236
|
-
export { type Initiator, type PeerChannel, type PeerStoreOptions, type Responder, type RpcClientOptions, type RpcHandler, type RpcMessage, type RpcRequest, type RpcResponse, type ServePeerStoreOptions, type WebRTCOptions, acceptOffer, createOffer, createRpcClient, fromDataChannel, pairInMemory, peerStore, servePeerStore, serveRpc };
|
|
288
|
+
export { type Initiator, type MinimalLockManager, type PeerChannel, type PeerStoreOptions, type Responder, type RpcClientOptions, type RpcHandler, type RpcMessage, type RpcRequest, type RpcResponse, type ServePeerStoreOptions, type WebRTCOptions, acceptOffer, createOffer, createRpcClient, fromDataChannel, pairInMemory, peerStore, servePeerStore, serveRpc };
|
package/dist/index.d.ts
CHANGED
|
@@ -146,9 +146,31 @@ declare function peerStore(opts: PeerStoreOptions): NoydbStore & {
|
|
|
146
146
|
* The 6 core methods plus the optional `ping` / `listSince` / `listPage`
|
|
147
147
|
* extensions are exposed. Unknown methods surface as a remote Error.
|
|
148
148
|
*
|
|
149
|
+
* **Leader-election (issue #3).** When a `BroadcastChannel`-backed
|
|
150
|
+
* `PeerChannel` is shared by 3+ tabs each running `servePeerStore`,
|
|
151
|
+
* every non-sending tab responds to every RPC — producing duplicate
|
|
152
|
+
* responses for the same request id and O(N²) channel traffic at scale.
|
|
153
|
+
* Pass `leaderElection: { lockName, locks? }` to gate serving on the
|
|
154
|
+
* Web Locks API: only the lock-holding tab registers an RPC handler;
|
|
155
|
+
* others queue and take over when the holder's tab closes (lock auto-
|
|
156
|
+
* releases). Default behaviour (no `leaderElection`) is unchanged for
|
|
157
|
+
* the 2-tab case.
|
|
158
|
+
*
|
|
149
159
|
* @module
|
|
150
160
|
*/
|
|
151
161
|
|
|
162
|
+
/**
|
|
163
|
+
* Minimal subset of the Web Locks API used by leader-election. The
|
|
164
|
+
* browser's `navigator.locks` satisfies this; tests inject a stub.
|
|
165
|
+
*
|
|
166
|
+
* @public
|
|
167
|
+
*/
|
|
168
|
+
interface MinimalLockManager {
|
|
169
|
+
request<T>(name: string, options: {
|
|
170
|
+
mode?: 'exclusive' | 'shared';
|
|
171
|
+
signal?: AbortSignal;
|
|
172
|
+
}, callback: (lock: unknown) => Promise<T>): Promise<T>;
|
|
173
|
+
}
|
|
152
174
|
interface ServePeerStoreOptions {
|
|
153
175
|
/** The duplex channel from the remote peer. */
|
|
154
176
|
readonly channel: PeerChannel;
|
|
@@ -159,11 +181,41 @@ interface ServePeerStoreOptions {
|
|
|
159
181
|
* is rejected with "method not allowed". Useful for read-only peers.
|
|
160
182
|
*/
|
|
161
183
|
readonly allow?: ReadonlySet<string>;
|
|
184
|
+
/**
|
|
185
|
+
* Opt in to leader-election semantics for cross-tab coordination via
|
|
186
|
+
* the Web Locks API. Required when 3+ tabs share a `BroadcastChannel`-
|
|
187
|
+
* backed `PeerChannel` — without leader election, every non-sending tab
|
|
188
|
+
* responds to every RPC, producing duplicate responses (issue #3).
|
|
189
|
+
*
|
|
190
|
+
* Browser support: Chrome 69+, Firefox 96+, Safari 15.4+.
|
|
191
|
+
*
|
|
192
|
+
* - `lockName` — globally unique lock name. Convention:
|
|
193
|
+
* `noy-db:peer-server:<channel-name>`. The same `lockName` MUST be
|
|
194
|
+
* used by every tab that wants to share the leader role.
|
|
195
|
+
* - `locks` — defaults to `navigator.locks` in browsers. Pass a stub
|
|
196
|
+
* for tests or for non-browser hosts that polyfill the Web Locks API.
|
|
197
|
+
*
|
|
198
|
+
* Behaviour: at most one tab holds the lock at a time. Only that tab
|
|
199
|
+
* registers an RPC handler on the channel; other tabs queue (their
|
|
200
|
+
* `servePeerStore` call returns a working dispose function but does
|
|
201
|
+
* not respond to incoming RPCs). When the holder's tab closes (or its
|
|
202
|
+
* `servePeerStore` is disposed), the next queued tab takes over.
|
|
203
|
+
*/
|
|
204
|
+
readonly leaderElection?: {
|
|
205
|
+
readonly lockName: string;
|
|
206
|
+
readonly locks?: MinimalLockManager;
|
|
207
|
+
};
|
|
162
208
|
}
|
|
163
209
|
/**
|
|
164
210
|
* Start serving the local store on the channel. Returns a dispose
|
|
165
211
|
* function that stops the RPC listener. The underlying channel is NOT
|
|
166
212
|
* closed by dispose — ownership stays with the caller.
|
|
213
|
+
*
|
|
214
|
+
* When `leaderElection` is set, the RPC handler is only registered while
|
|
215
|
+
* this tab holds the named Web Lock. The returned dispose function
|
|
216
|
+
* always works: if called before the lock is acquired, it cancels the
|
|
217
|
+
* wait; if called while holding the lock, it releases the lock and
|
|
218
|
+
* stops serving.
|
|
167
219
|
*/
|
|
168
220
|
declare function servePeerStore(opts: ServePeerStoreOptions): () => void;
|
|
169
221
|
|
|
@@ -233,4 +285,4 @@ declare function createOffer(opts?: WebRTCOptions): Promise<Initiator>;
|
|
|
233
285
|
*/
|
|
234
286
|
declare function acceptOffer(offer: SessionDescription, opts?: WebRTCOptions): Promise<Responder>;
|
|
235
287
|
|
|
236
|
-
export { type Initiator, type PeerChannel, type PeerStoreOptions, type Responder, type RpcClientOptions, type RpcHandler, type RpcMessage, type RpcRequest, type RpcResponse, type ServePeerStoreOptions, type WebRTCOptions, acceptOffer, createOffer, createRpcClient, fromDataChannel, pairInMemory, peerStore, servePeerStore, serveRpc };
|
|
288
|
+
export { type Initiator, type MinimalLockManager, type PeerChannel, type PeerStoreOptions, type Responder, type RpcClientOptions, type RpcHandler, type RpcMessage, type RpcRequest, type RpcResponse, type ServePeerStoreOptions, type WebRTCOptions, acceptOffer, createOffer, createRpcClient, fromDataChannel, pairInMemory, peerStore, servePeerStore, serveRpc };
|
package/dist/index.js
CHANGED
|
@@ -266,6 +266,12 @@ var CORE_METHODS = /* @__PURE__ */ new Set([
|
|
|
266
266
|
"listVaults"
|
|
267
267
|
]);
|
|
268
268
|
function servePeerStore(opts) {
|
|
269
|
+
if (!opts.leaderElection) {
|
|
270
|
+
return startServing(opts);
|
|
271
|
+
}
|
|
272
|
+
return startServingWithLeaderElection(opts);
|
|
273
|
+
}
|
|
274
|
+
function startServing(opts) {
|
|
269
275
|
const { store, channel, allow } = opts;
|
|
270
276
|
return serveRpc(channel, async (method, args) => {
|
|
271
277
|
if (!CORE_METHODS.has(method)) {
|
|
@@ -324,6 +330,47 @@ function servePeerStore(opts) {
|
|
|
324
330
|
throw new Error(`Unhandled method: ${method}`);
|
|
325
331
|
});
|
|
326
332
|
}
|
|
333
|
+
function startServingWithLeaderElection(opts) {
|
|
334
|
+
const leader = opts.leaderElection;
|
|
335
|
+
const locks = leader.locks ?? getDefaultLocks();
|
|
336
|
+
const ac = new AbortController();
|
|
337
|
+
let stopServing = null;
|
|
338
|
+
let releaseLock = null;
|
|
339
|
+
let disposed = false;
|
|
340
|
+
void locks.request(leader.lockName, { mode: "exclusive", signal: ac.signal }, () => {
|
|
341
|
+
if (disposed) return Promise.resolve();
|
|
342
|
+
stopServing = startServing(opts);
|
|
343
|
+
return new Promise((resolve) => {
|
|
344
|
+
releaseLock = resolve;
|
|
345
|
+
});
|
|
346
|
+
}).catch((err) => {
|
|
347
|
+
if (err?.name === "AbortError") return;
|
|
348
|
+
queueMicrotask(() => {
|
|
349
|
+
throw err;
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
return () => {
|
|
353
|
+
if (disposed) return;
|
|
354
|
+
disposed = true;
|
|
355
|
+
if (stopServing) {
|
|
356
|
+
stopServing();
|
|
357
|
+
stopServing = null;
|
|
358
|
+
}
|
|
359
|
+
if (releaseLock) {
|
|
360
|
+
releaseLock();
|
|
361
|
+
releaseLock = null;
|
|
362
|
+
} else {
|
|
363
|
+
ac.abort();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
function getDefaultLocks() {
|
|
368
|
+
const nav = globalThis.navigator;
|
|
369
|
+
if (nav && nav.locks) return nav.locks;
|
|
370
|
+
throw new Error(
|
|
371
|
+
"leaderElection requires the Web Locks API (navigator.locks). Use Chrome 69+, Firefox 96+, Safari 15.4+, or pass `leaderElection.locks: <stub>` for tests / non-browser hosts."
|
|
372
|
+
);
|
|
373
|
+
}
|
|
327
374
|
|
|
328
375
|
// src/webrtc.ts
|
|
329
376
|
function requireRTC() {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/channel.ts","../src/rpc.ts","../src/peer-store.ts","../src/serve.ts","../src/webrtc.ts"],"sourcesContent":["/**\n * `PeerChannel` — the minimal duplex message primitive used by the p2p\n * NoydbStore wrapper. Any transport that can deliver UTF-8 strings\n * reliably and in-order qualifies: WebRTC DataChannel, BroadcastChannel,\n * MessagePort, WebSocket, even postMessage pairs.\n *\n * Keeping the transport abstract has three payoffs:\n *\n * 1. **Tests run without a WebRTC polyfill.** `pairInMemory()` returns\n * two wired channels for conformance tests against `to-memory`.\n * 2. **Consumers pick their signaling story.** Matrix rooms, QR codes,\n * pastebin, Firebase Realtime DB — the handshake is out of scope.\n * 3. **Future transports slot in cheaply.** WebTransport (HTTP/3),\n * libp2p, Iroh, or a plain relay WebSocket become additional\n * bindings without touching the RPC layer.\n *\n * @module\n */\n\n/**\n * Minimal duplex message primitive.\n *\n * Implementations MUST deliver every `send` payload in order exactly\n * once to every live `on('message')` subscriber. `close()` is best-effort\n * — once called, further `send()` calls MAY throw and `on('close')` MUST\n * fire once.\n */\nexport interface PeerChannel {\n /** Enqueue a payload for delivery to the remote end. */\n send(payload: string): void\n /** Subscribe to incoming payloads or lifecycle events. Returns unsubscribe. */\n on(event: 'message', listener: (payload: string) => void): () => void\n on(event: 'close', listener: () => void): () => void\n /** Close the channel. Idempotent. */\n close(): void\n /** True once the channel is ready for `send`. */\n readonly isOpen: boolean\n}\n\n/**\n * Create a pair of in-memory `PeerChannel`s wired to each other.\n * Intended for tests and multi-tab simulations inside a single process.\n */\nexport function pairInMemory(): [PeerChannel, PeerChannel] {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n\n function make(): { ch: PeerChannel; listeners: Listeners; closed: { v: boolean } } {\n const listeners: Listeners = { message: new Set(), close: new Set() }\n const closed = { v: false }\n const ch: PeerChannel = {\n get isOpen() {\n return !closed.v\n },\n send() {\n // Placeholder — wired below.\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed.v) return\n closed.v = true\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n return { ch, listeners, closed }\n }\n\n const a = make()\n const b = make()\n\n function closeBoth(): void {\n if (!a.closed.v) {\n a.closed.v = true\n for (const fn of a.listeners.close) fn()\n }\n if (!b.closed.v) {\n b.closed.v = true\n for (const fn of b.listeners.close) fn()\n }\n }\n\n a.ch.send = (payload) => {\n if (b.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of b.listeners.message) fn(payload)\n })\n }\n b.ch.send = (payload) => {\n if (a.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of a.listeners.message) fn(payload)\n })\n }\n a.ch.close = closeBoth\n b.ch.close = closeBoth\n\n return [a.ch, b.ch]\n}\n\n/**\n * Wrap a WebRTC `RTCDataChannel` as a `PeerChannel`.\n *\n * Browser-only — the caller is responsible for establishing the\n * `RTCPeerConnection`, exchanging SDP offers/answers out of band, and\n * passing the opened DataChannel here. When the remote peer is only\n * reachable via TURN, the relay sees DTLS-wrapped ciphertext (noy-db\n * already encrypts at rest, so even a TURN compromise leaks nothing).\n */\nexport function fromDataChannel(dc: RTCDataChannel): PeerChannel {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n const listeners: Listeners = { message: new Set(), close: new Set() }\n let closed = false\n\n dc.addEventListener('message', (ev: MessageEvent) => {\n if (typeof ev.data !== 'string') return\n for (const fn of listeners.message) fn(ev.data)\n })\n dc.addEventListener('close', () => {\n if (closed) return\n closed = true\n for (const fn of listeners.close) fn()\n })\n\n return {\n get isOpen() {\n return !closed && dc.readyState === 'open'\n },\n send(payload) {\n if (closed || dc.readyState !== 'open') {\n throw new Error(`PeerChannel not open (readyState: ${dc.readyState})`)\n }\n dc.send(payload)\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed) return\n closed = true\n try {\n dc.close()\n } catch {\n // ignore — channel already torn down\n }\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n}\n","/**\n * JSON-RPC protocol over a `PeerChannel`.\n *\n * Request shape:\n * `{ t: 'req', id, method, args }`\n * Response shape (success):\n * `{ t: 'res', id, ok: true, result }`\n * Response shape (error):\n * `{ t: 'res', id, ok: false, error: { name, message, version? } }`\n *\n * Why not reuse msgpack/protobuf? The payloads are already base64-encoded\n * ciphertext — further binary packing saves ~8-12% at a large dependency\n * cost. JSON over UTF-8 is inspectable, fits the zero-dependency ethos,\n * and WebRTC DataChannel string mode already frames for us.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\n\n/** Wire format discriminator for RPC messages. */\nexport type RpcMessage = RpcRequest | RpcResponse\n\nexport interface RpcRequest {\n readonly t: 'req'\n readonly id: string\n readonly method: string\n readonly args: readonly unknown[]\n}\n\nexport interface RpcResponse {\n readonly t: 'res'\n readonly id: string\n readonly ok: boolean\n readonly result?: unknown\n readonly error?: { name: string; message: string; version?: number }\n}\n\n/** Handler invoked when an RPC request arrives. Return value is serialized as `result`. */\nexport type RpcHandler = (method: string, args: readonly unknown[]) => Promise<unknown>\n\n/** Options for a client-side RPC caller. */\nexport interface RpcClientOptions {\n /** Max milliseconds to wait for a response before rejecting. */\n timeoutMs?: number\n}\n\n/** Client: wrap a `PeerChannel` in a `call(method, args)` helper. */\nexport function createRpcClient(channel: PeerChannel, opts: RpcClientOptions = {}) {\n const timeoutMs = opts.timeoutMs ?? 30_000\n type Pending = {\n resolve: (v: unknown) => void\n reject: (err: Error) => void\n timer: ReturnType<typeof setTimeout>\n }\n const pending = new Map<string, Pending>()\n let counter = 0\n\n const offMessage = channel.on('message', (payload) => {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'res') return\n const entry = pending.get(msg.id)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(msg.id)\n if (msg.ok) {\n entry.resolve(msg.result)\n } else {\n const e = msg.error ?? { name: 'Error', message: 'unknown remote error' }\n const err = new Error(e.message)\n err.name = e.name\n if (typeof e.version === 'number') {\n ;(err as Error & { version?: number }).version = e.version\n }\n entry.reject(err)\n }\n })\n\n const offClose = channel.on('close', () => {\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('PeerChannel closed before response'))\n }\n pending.clear()\n })\n\n return {\n async call<T = unknown>(method: string, args: readonly unknown[]): Promise<T> {\n const id = `${Date.now().toString(36)}-${(++counter).toString(36)}`\n const req: RpcRequest = { t: 'req', id, method, args }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n reject(new Error(`RPC ${method} timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n pending.set(id, {\n resolve: resolve as (v: unknown) => void,\n reject,\n timer,\n })\n try {\n channel.send(JSON.stringify(req))\n } catch (err) {\n clearTimeout(timer)\n pending.delete(id)\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n })\n },\n dispose() {\n offMessage()\n offClose()\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('RPC client disposed'))\n }\n pending.clear()\n },\n }\n}\n\n/** Server: dispatch incoming RPC requests through a handler. Returns a dispose fn. */\nexport function serveRpc(channel: PeerChannel, handler: RpcHandler): () => void {\n async function handle(payload: string): Promise<void> {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'req') return\n\n let response: RpcResponse\n try {\n const result = await handler(msg.method, msg.args)\n response = { t: 'res', id: msg.id, ok: true, result }\n } catch (err) {\n const e = err as Error & { version?: number }\n response = {\n t: 'res',\n id: msg.id,\n ok: false,\n error: {\n name: e.name ?? 'Error',\n message: e.message ?? String(err),\n ...(typeof e.version === 'number' && { version: e.version }),\n },\n }\n }\n\n if (!channel.isOpen) return\n try {\n channel.send(JSON.stringify(response))\n } catch {\n // Channel closed mid-response — nothing to do.\n }\n }\n\n const offMessage = channel.on('message', (payload) => {\n void handle(payload)\n })\n\n return () => offMessage()\n}\n","/**\n * `peerStore()` — a `NoydbStore` backed by RPC calls over a `PeerChannel`.\n *\n * The local peer calls `get`/`put`/`delete`/… against this store as if\n * it were any other backend; every call is serialized as an RPC request\n * to the remote peer, which runs `servePeerStore()` to funnel the RPCs\n * into its own local `NoydbStore`.\n *\n * Error re-hydration: the remote handler re-throws `ConflictError` with\n * a `.version` field when a CAS check fails. The RPC layer carries\n * `version` in the error envelope so the local caller can catch\n * `ConflictError` with the same semantics as a direct store call.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { createRpcClient } from './rpc.js'\n\nexport interface PeerStoreOptions {\n /** The duplex channel to the remote peer. */\n readonly channel: PeerChannel\n /** Max ms to wait for any single RPC response. Default 30s. */\n readonly timeoutMs?: number\n /** Optional display name used in diagnostics. Default `'by-peer'`. */\n readonly name?: string\n}\n\n/**\n * Create a `NoydbStore` that forwards every operation to a remote peer\n * over the supplied `PeerChannel`. The remote peer must be running\n * `servePeerStore()` against its own local store.\n */\nexport function peerStore(opts: PeerStoreOptions): NoydbStore & { dispose: () => void } {\n const rpc = createRpcClient(opts.channel, { timeoutMs: opts.timeoutMs ?? 30_000 })\n\n async function call<T>(method: string, args: readonly unknown[]): Promise<T> {\n try {\n return await rpc.call<T>(method, args)\n } catch (err) {\n // Re-hydrate ConflictError so CAS semantics survive the wire hop.\n const e = err as Error & { version?: number }\n if (e.name === 'ConflictError' && typeof e.version === 'number') {\n throw new ConflictError(e.version, e.message)\n }\n throw err\n }\n }\n\n return {\n name: opts.name ?? 'by-peer',\n\n async get(vault, collection, id) {\n return call<EncryptedEnvelope | null>('get', [vault, collection, id])\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n await call<void>('put', [vault, collection, id, envelope, expectedVersion])\n },\n\n async delete(vault, collection, id) {\n await call<void>('delete', [vault, collection, id])\n },\n\n async list(vault, collection) {\n return call<string[]>('list', [vault, collection])\n },\n\n async loadAll(vault) {\n return call<VaultSnapshot>('loadAll', [vault])\n },\n\n async saveAll(vault, data) {\n await call<void>('saveAll', [vault, data])\n },\n\n async ping() {\n try {\n return await call<boolean>('ping', [])\n } catch {\n return false\n }\n },\n\n dispose() {\n rpc.dispose()\n },\n }\n}\n","/**\n * `servePeerStore()` — runs on the peer that owns the data. Listens on\n * a `PeerChannel` for RPC requests from a remote `peerStore()` client\n * and executes each one against the local `NoydbStore`.\n *\n * The 6 core methods plus the optional `ping` / `listSince` / `listPage`\n * extensions are exposed. Unknown methods surface as a remote Error.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { serveRpc } from './rpc.js'\n\nexport interface ServePeerStoreOptions {\n /** The duplex channel from the remote peer. */\n readonly channel: PeerChannel\n /** The local store to serve. */\n readonly store: NoydbStore\n /**\n * Optional method whitelist. When provided, any method not in the set\n * is rejected with \"method not allowed\". Useful for read-only peers.\n */\n readonly allow?: ReadonlySet<string>\n}\n\nconst CORE_METHODS = new Set<string>([\n 'get',\n 'put',\n 'delete',\n 'list',\n 'loadAll',\n 'saveAll',\n 'ping',\n 'listSince',\n 'listPage',\n 'listVaults',\n])\n\n/**\n * Start serving the local store on the channel. Returns a dispose\n * function that stops the RPC listener. The underlying channel is NOT\n * closed by dispose — ownership stays with the caller.\n */\nexport function servePeerStore(opts: ServePeerStoreOptions): () => void {\n const { store, channel, allow } = opts\n\n return serveRpc(channel, async (method, args) => {\n if (!CORE_METHODS.has(method)) {\n throw new Error(`Unknown RPC method: ${method}`)\n }\n if (allow && !allow.has(method)) {\n throw new Error(`Method not allowed: ${method}`)\n }\n\n switch (method) {\n case 'get': {\n const [vault, collection, id] = args as [string, string, string]\n return store.get(vault, collection, id)\n }\n case 'put': {\n const [vault, collection, id, envelope, expectedVersion] = args as [\n string,\n string,\n string,\n EncryptedEnvelope,\n number | undefined,\n ]\n await store.put(vault, collection, id, envelope, expectedVersion)\n return null\n }\n case 'delete': {\n const [vault, collection, id] = args as [string, string, string]\n await store.delete(vault, collection, id)\n return null\n }\n case 'list': {\n const [vault, collection] = args as [string, string]\n return store.list(vault, collection)\n }\n case 'loadAll': {\n const [vault] = args as [string]\n return store.loadAll(vault)\n }\n case 'saveAll': {\n const [vault, data] = args as [string, VaultSnapshot]\n await store.saveAll(vault, data)\n return null\n }\n case 'ping': {\n if (!store.ping) return true\n return store.ping()\n }\n case 'listSince': {\n if (!store.listSince) throw new Error('listSince not supported by remote store')\n const [vault, collection, since] = args as [string, string, string]\n return store.listSince(vault, collection, since)\n }\n case 'listPage': {\n if (!store.listPage) throw new Error('listPage not supported by remote store')\n const [vault, collection, cursor, limit] = args as [\n string,\n string,\n string | undefined,\n number | undefined,\n ]\n return store.listPage(vault, collection, cursor, limit)\n }\n case 'listVaults': {\n if (!store.listVaults) throw new Error('listVaults not supported by remote store')\n return store.listVaults()\n }\n }\n /* istanbul ignore next — CORE_METHODS gate makes this unreachable */\n throw new Error(`Unhandled method: ${method}`)\n })\n}\n","/**\n * WebRTC handshake helper — opinionated wrapper around\n * `RTCPeerConnection` that produces a ready-to-use `PeerChannel`.\n *\n * The handshake is split into two halves so the caller can ferry the\n * SDP blobs over whatever signaling channel they prefer (QR code,\n * Matrix room, pastebin, Firebase, signed URL…). Signaling is\n * intentionally out of scope — noy-db has no opinion on how peers\n * discover each other, only on what flows once they do.\n *\n * ```ts\n * // Peer A (initiator)\n * const a = await createOffer({ iceServers })\n * send(a.offer) // → signaling channel\n * const answer = await receive() // ← signaling channel\n * await a.accept(answer)\n * const channel = await a.channel // ready PeerChannel\n *\n * // Peer B (responder)\n * const offer = await receive() // ← signaling channel\n * const b = await acceptOffer(offer, { iceServers })\n * send(b.answer) // → signaling channel\n * const channel = await b.channel // ready PeerChannel\n * ```\n *\n * Browser-only. Node consumers who want to interconnect with browsers\n * can plug `@roamhq/wrtc` into the global `RTCPeerConnection` slot; this\n * module does not pull it in so the package has zero runtime deps.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\nimport { fromDataChannel } from './channel.js'\n\ntype PeerConnection = RTCPeerConnection\ntype SessionDescription = RTCSessionDescriptionInit\n\nexport interface WebRTCOptions {\n /** Optional ICE servers (STUN / TURN). */\n readonly iceServers?: RTCIceServer[]\n /** Label for the `RTCDataChannel`. Default `'noydb'`. */\n readonly label?: string\n}\n\nexport interface Initiator {\n readonly offer: SessionDescription\n /** Feed in the remote peer's SDP answer to complete the handshake. */\n accept(answer: SessionDescription): Promise<void>\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nexport interface Responder {\n readonly answer: SessionDescription\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nfunction requireRTC(): typeof RTCPeerConnection {\n const g = globalThis as { RTCPeerConnection?: typeof RTCPeerConnection }\n if (!g.RTCPeerConnection) {\n throw new Error(\n '[@noy-db/by-peer] globalThis.RTCPeerConnection is undefined — use this module in a browser, or polyfill with @roamhq/wrtc in Node',\n )\n }\n return g.RTCPeerConnection\n}\n\n/**\n * Build an offer as the initiating peer. Returns the SDP offer to send\n * to the remote peer and a promise for the opened `PeerChannel`.\n */\nexport async function createOffer(opts: WebRTCOptions = {}): Promise<Initiator> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const dc = pc.createDataChannel(opts.label ?? 'noydb', {\n ordered: true,\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n })\n\n const offer = await pc.createOffer()\n await pc.setLocalDescription(offer)\n await waitForIceComplete(pc)\n\n return {\n offer: pc.localDescription ?? offer,\n connection: pc,\n channel: channelPromise,\n async accept(answer) {\n await pc.setRemoteDescription(answer)\n },\n }\n}\n\n/**\n * Accept an incoming offer as the responding peer. Returns the SDP\n * answer to send back to the initiator and a promise for the opened\n * `PeerChannel`.\n */\nexport async function acceptOffer(\n offer: SessionDescription,\n opts: WebRTCOptions = {},\n): Promise<Responder> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n pc.addEventListener('datachannel', (ev) => {\n const dc = ev.channel\n if (dc.readyState === 'open') {\n resolve(fromDataChannel(dc))\n } else {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n }\n })\n })\n\n await pc.setRemoteDescription(offer)\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n await waitForIceComplete(pc)\n\n return {\n answer: pc.localDescription ?? answer,\n connection: pc,\n channel: channelPromise,\n }\n}\n\n/**\n * Resolve once ICE gathering reaches `'complete'`. Using non-trickle ICE\n * keeps the signaling exchange to a single round-trip — at the cost of\n * a slightly longer initial handshake. Consumers that want trickle ICE\n * can bypass this helper and drive `RTCPeerConnection` directly.\n */\nfunction waitForIceComplete(pc: PeerConnection): Promise<void> {\n if (pc.iceGatheringState === 'complete') return Promise.resolve()\n return new Promise((resolve) => {\n const check = () => {\n if (pc.iceGatheringState === 'complete') {\n pc.removeEventListener('icegatheringstatechange', check)\n resolve()\n }\n }\n pc.addEventListener('icegatheringstatechange', check)\n })\n}\n"],"mappings":";AA2CO,SAAS,eAA2C;AAMzD,WAAS,OAA0E;AACjF,UAAM,YAAuB,EAAE,SAAS,o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,EAAE;AAE3B,SAAO;AAAA,IACL,QAAQ,GAAG,oBAAoB;AAAA,IAC/B,YAAY;AAAA,IACZ,SAAS;AAAA,EACX;AACF;AAQA,SAAS,mBAAmB,IAAmC;AAC7D,MAAI,GAAG,sBAAsB,WAAY,QAAO,QAAQ,QAAQ;AAChE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,QAAQ,MAAM;AAClB,UAAI,GAAG,sBAAsB,YAAY;AACvC,WAAG,oBAAoB,2BAA2B,KAAK;AACvD,gBAAQ;AAAA,MACV;AAAA,IACF;AACA,OAAG,iBAAiB,2BAA2B,KAAK;AAAA,EACtD,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/channel.ts","../src/rpc.ts","../src/peer-store.ts","../src/serve.ts","../src/webrtc.ts"],"sourcesContent":["/**\n * `PeerChannel` — the minimal duplex message primitive used by the p2p\n * NoydbStore wrapper. Any transport that can deliver UTF-8 strings\n * reliably and in-order qualifies: WebRTC DataChannel, BroadcastChannel,\n * MessagePort, WebSocket, even postMessage pairs.\n *\n * Keeping the transport abstract has three payoffs:\n *\n * 1. **Tests run without a WebRTC polyfill.** `pairInMemory()` returns\n * two wired channels for conformance tests against `to-memory`.\n * 2. **Consumers pick their signaling story.** Matrix rooms, QR codes,\n * pastebin, Firebase Realtime DB — the handshake is out of scope.\n * 3. **Future transports slot in cheaply.** WebTransport (HTTP/3),\n * libp2p, Iroh, or a plain relay WebSocket become additional\n * bindings without touching the RPC layer.\n *\n * @module\n */\n\n/**\n * Minimal duplex message primitive.\n *\n * Implementations MUST deliver every `send` payload in order exactly\n * once to every live `on('message')` subscriber. `close()` is best-effort\n * — once called, further `send()` calls MAY throw and `on('close')` MUST\n * fire once.\n */\nexport interface PeerChannel {\n /** Enqueue a payload for delivery to the remote end. */\n send(payload: string): void\n /** Subscribe to incoming payloads or lifecycle events. Returns unsubscribe. */\n on(event: 'message', listener: (payload: string) => void): () => void\n on(event: 'close', listener: () => void): () => void\n /** Close the channel. Idempotent. */\n close(): void\n /** True once the channel is ready for `send`. */\n readonly isOpen: boolean\n}\n\n/**\n * Create a pair of in-memory `PeerChannel`s wired to each other.\n * Intended for tests and multi-tab simulations inside a single process.\n */\nexport function pairInMemory(): [PeerChannel, PeerChannel] {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n\n function make(): { ch: PeerChannel; listeners: Listeners; closed: { v: boolean } } {\n const listeners: Listeners = { message: new Set(), close: new Set() }\n const closed = { v: false }\n const ch: PeerChannel = {\n get isOpen() {\n return !closed.v\n },\n send() {\n // Placeholder — wired below.\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed.v) return\n closed.v = true\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n return { ch, listeners, closed }\n }\n\n const a = make()\n const b = make()\n\n function closeBoth(): void {\n if (!a.closed.v) {\n a.closed.v = true\n for (const fn of a.listeners.close) fn()\n }\n if (!b.closed.v) {\n b.closed.v = true\n for (const fn of b.listeners.close) fn()\n }\n }\n\n a.ch.send = (payload) => {\n if (b.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of b.listeners.message) fn(payload)\n })\n }\n b.ch.send = (payload) => {\n if (a.closed.v) throw new Error('PeerChannel closed')\n queueMicrotask(() => {\n for (const fn of a.listeners.message) fn(payload)\n })\n }\n a.ch.close = closeBoth\n b.ch.close = closeBoth\n\n return [a.ch, b.ch]\n}\n\n/**\n * Wrap a WebRTC `RTCDataChannel` as a `PeerChannel`.\n *\n * Browser-only — the caller is responsible for establishing the\n * `RTCPeerConnection`, exchanging SDP offers/answers out of band, and\n * passing the opened DataChannel here. When the remote peer is only\n * reachable via TURN, the relay sees DTLS-wrapped ciphertext (noy-db\n * already encrypts at rest, so even a TURN compromise leaks nothing).\n */\nexport function fromDataChannel(dc: RTCDataChannel): PeerChannel {\n type Listeners = {\n message: Set<(p: string) => void>\n close: Set<() => void>\n }\n const listeners: Listeners = { message: new Set(), close: new Set() }\n let closed = false\n\n dc.addEventListener('message', (ev: MessageEvent) => {\n if (typeof ev.data !== 'string') return\n for (const fn of listeners.message) fn(ev.data)\n })\n dc.addEventListener('close', () => {\n if (closed) return\n closed = true\n for (const fn of listeners.close) fn()\n })\n\n return {\n get isOpen() {\n return !closed && dc.readyState === 'open'\n },\n send(payload) {\n if (closed || dc.readyState !== 'open') {\n throw new Error(`PeerChannel not open (readyState: ${dc.readyState})`)\n }\n dc.send(payload)\n },\n on(event: 'message' | 'close', listener: ((payload: string) => void) | (() => void)): () => void {\n if (event === 'message') {\n listeners.message.add(listener as (p: string) => void)\n return () => listeners.message.delete(listener as (p: string) => void)\n }\n listeners.close.add(listener as () => void)\n return () => listeners.close.delete(listener as () => void)\n },\n close() {\n if (closed) return\n closed = true\n try {\n dc.close()\n } catch {\n // ignore — channel already torn down\n }\n for (const fn of listeners.close) fn()\n },\n } as PeerChannel\n}\n","/**\n * JSON-RPC protocol over a `PeerChannel`.\n *\n * Request shape:\n * `{ t: 'req', id, method, args }`\n * Response shape (success):\n * `{ t: 'res', id, ok: true, result }`\n * Response shape (error):\n * `{ t: 'res', id, ok: false, error: { name, message, version? } }`\n *\n * Why not reuse msgpack/protobuf? The payloads are already base64-encoded\n * ciphertext — further binary packing saves ~8-12% at a large dependency\n * cost. JSON over UTF-8 is inspectable, fits the zero-dependency ethos,\n * and WebRTC DataChannel string mode already frames for us.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\n\n/** Wire format discriminator for RPC messages. */\nexport type RpcMessage = RpcRequest | RpcResponse\n\nexport interface RpcRequest {\n readonly t: 'req'\n readonly id: string\n readonly method: string\n readonly args: readonly unknown[]\n}\n\nexport interface RpcResponse {\n readonly t: 'res'\n readonly id: string\n readonly ok: boolean\n readonly result?: unknown\n readonly error?: { name: string; message: string; version?: number }\n}\n\n/** Handler invoked when an RPC request arrives. Return value is serialized as `result`. */\nexport type RpcHandler = (method: string, args: readonly unknown[]) => Promise<unknown>\n\n/** Options for a client-side RPC caller. */\nexport interface RpcClientOptions {\n /** Max milliseconds to wait for a response before rejecting. */\n timeoutMs?: number\n}\n\n/** Client: wrap a `PeerChannel` in a `call(method, args)` helper. */\nexport function createRpcClient(channel: PeerChannel, opts: RpcClientOptions = {}) {\n const timeoutMs = opts.timeoutMs ?? 30_000\n type Pending = {\n resolve: (v: unknown) => void\n reject: (err: Error) => void\n timer: ReturnType<typeof setTimeout>\n }\n const pending = new Map<string, Pending>()\n let counter = 0\n\n const offMessage = channel.on('message', (payload) => {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'res') return\n const entry = pending.get(msg.id)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(msg.id)\n if (msg.ok) {\n entry.resolve(msg.result)\n } else {\n const e = msg.error ?? { name: 'Error', message: 'unknown remote error' }\n const err = new Error(e.message)\n err.name = e.name\n if (typeof e.version === 'number') {\n ;(err as Error & { version?: number }).version = e.version\n }\n entry.reject(err)\n }\n })\n\n const offClose = channel.on('close', () => {\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('PeerChannel closed before response'))\n }\n pending.clear()\n })\n\n return {\n async call<T = unknown>(method: string, args: readonly unknown[]): Promise<T> {\n const id = `${Date.now().toString(36)}-${(++counter).toString(36)}`\n const req: RpcRequest = { t: 'req', id, method, args }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n reject(new Error(`RPC ${method} timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n pending.set(id, {\n resolve: resolve as (v: unknown) => void,\n reject,\n timer,\n })\n try {\n channel.send(JSON.stringify(req))\n } catch (err) {\n clearTimeout(timer)\n pending.delete(id)\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n })\n },\n dispose() {\n offMessage()\n offClose()\n for (const [, entry] of pending) {\n clearTimeout(entry.timer)\n entry.reject(new Error('RPC client disposed'))\n }\n pending.clear()\n },\n }\n}\n\n/** Server: dispatch incoming RPC requests through a handler. Returns a dispose fn. */\nexport function serveRpc(channel: PeerChannel, handler: RpcHandler): () => void {\n async function handle(payload: string): Promise<void> {\n let msg: RpcMessage\n try {\n msg = JSON.parse(payload) as RpcMessage\n } catch {\n return\n }\n if (msg.t !== 'req') return\n\n let response: RpcResponse\n try {\n const result = await handler(msg.method, msg.args)\n response = { t: 'res', id: msg.id, ok: true, result }\n } catch (err) {\n const e = err as Error & { version?: number }\n response = {\n t: 'res',\n id: msg.id,\n ok: false,\n error: {\n name: e.name ?? 'Error',\n message: e.message ?? String(err),\n ...(typeof e.version === 'number' && { version: e.version }),\n },\n }\n }\n\n if (!channel.isOpen) return\n try {\n channel.send(JSON.stringify(response))\n } catch {\n // Channel closed mid-response — nothing to do.\n }\n }\n\n const offMessage = channel.on('message', (payload) => {\n void handle(payload)\n })\n\n return () => offMessage()\n}\n","/**\n * `peerStore()` — a `NoydbStore` backed by RPC calls over a `PeerChannel`.\n *\n * The local peer calls `get`/`put`/`delete`/… against this store as if\n * it were any other backend; every call is serialized as an RPC request\n * to the remote peer, which runs `servePeerStore()` to funnel the RPCs\n * into its own local `NoydbStore`.\n *\n * Error re-hydration: the remote handler re-throws `ConflictError` with\n * a `.version` field when a CAS check fails. The RPC layer carries\n * `version` in the error envelope so the local caller can catch\n * `ConflictError` with the same semantics as a direct store call.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { createRpcClient } from './rpc.js'\n\nexport interface PeerStoreOptions {\n /** The duplex channel to the remote peer. */\n readonly channel: PeerChannel\n /** Max ms to wait for any single RPC response. Default 30s. */\n readonly timeoutMs?: number\n /** Optional display name used in diagnostics. Default `'by-peer'`. */\n readonly name?: string\n}\n\n/**\n * Create a `NoydbStore` that forwards every operation to a remote peer\n * over the supplied `PeerChannel`. The remote peer must be running\n * `servePeerStore()` against its own local store.\n */\nexport function peerStore(opts: PeerStoreOptions): NoydbStore & { dispose: () => void } {\n const rpc = createRpcClient(opts.channel, { timeoutMs: opts.timeoutMs ?? 30_000 })\n\n async function call<T>(method: string, args: readonly unknown[]): Promise<T> {\n try {\n return await rpc.call<T>(method, args)\n } catch (err) {\n // Re-hydrate ConflictError so CAS semantics survive the wire hop.\n const e = err as Error & { version?: number }\n if (e.name === 'ConflictError' && typeof e.version === 'number') {\n throw new ConflictError(e.version, e.message)\n }\n throw err\n }\n }\n\n return {\n name: opts.name ?? 'by-peer',\n\n async get(vault, collection, id) {\n return call<EncryptedEnvelope | null>('get', [vault, collection, id])\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n await call<void>('put', [vault, collection, id, envelope, expectedVersion])\n },\n\n async delete(vault, collection, id) {\n await call<void>('delete', [vault, collection, id])\n },\n\n async list(vault, collection) {\n return call<string[]>('list', [vault, collection])\n },\n\n async loadAll(vault) {\n return call<VaultSnapshot>('loadAll', [vault])\n },\n\n async saveAll(vault, data) {\n await call<void>('saveAll', [vault, data])\n },\n\n async ping() {\n try {\n return await call<boolean>('ping', [])\n } catch {\n return false\n }\n },\n\n dispose() {\n rpc.dispose()\n },\n }\n}\n","/**\n * `servePeerStore()` — runs on the peer that owns the data. Listens on\n * a `PeerChannel` for RPC requests from a remote `peerStore()` client\n * and executes each one against the local `NoydbStore`.\n *\n * The 6 core methods plus the optional `ping` / `listSince` / `listPage`\n * extensions are exposed. Unknown methods surface as a remote Error.\n *\n * **Leader-election (issue #3).** When a `BroadcastChannel`-backed\n * `PeerChannel` is shared by 3+ tabs each running `servePeerStore`,\n * every non-sending tab responds to every RPC — producing duplicate\n * responses for the same request id and O(N²) channel traffic at scale.\n * Pass `leaderElection: { lockName, locks? }` to gate serving on the\n * Web Locks API: only the lock-holding tab registers an RPC handler;\n * others queue and take over when the holder's tab closes (lock auto-\n * releases). Default behaviour (no `leaderElection`) is unchanged for\n * the 2-tab case.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport type { PeerChannel } from './channel.js'\nimport { serveRpc } from './rpc.js'\n\n/**\n * Minimal subset of the Web Locks API used by leader-election. The\n * browser's `navigator.locks` satisfies this; tests inject a stub.\n *\n * @public\n */\nexport interface MinimalLockManager {\n request<T>(\n name: string,\n options: { mode?: 'exclusive' | 'shared'; signal?: AbortSignal },\n callback: (lock: unknown) => Promise<T>,\n ): Promise<T>\n}\n\nexport interface ServePeerStoreOptions {\n /** The duplex channel from the remote peer. */\n readonly channel: PeerChannel\n /** The local store to serve. */\n readonly store: NoydbStore\n /**\n * Optional method whitelist. When provided, any method not in the set\n * is rejected with \"method not allowed\". Useful for read-only peers.\n */\n readonly allow?: ReadonlySet<string>\n /**\n * Opt in to leader-election semantics for cross-tab coordination via\n * the Web Locks API. Required when 3+ tabs share a `BroadcastChannel`-\n * backed `PeerChannel` — without leader election, every non-sending tab\n * responds to every RPC, producing duplicate responses (issue #3).\n *\n * Browser support: Chrome 69+, Firefox 96+, Safari 15.4+.\n *\n * - `lockName` — globally unique lock name. Convention:\n * `noy-db:peer-server:<channel-name>`. The same `lockName` MUST be\n * used by every tab that wants to share the leader role.\n * - `locks` — defaults to `navigator.locks` in browsers. Pass a stub\n * for tests or for non-browser hosts that polyfill the Web Locks API.\n *\n * Behaviour: at most one tab holds the lock at a time. Only that tab\n * registers an RPC handler on the channel; other tabs queue (their\n * `servePeerStore` call returns a working dispose function but does\n * not respond to incoming RPCs). When the holder's tab closes (or its\n * `servePeerStore` is disposed), the next queued tab takes over.\n */\n readonly leaderElection?: {\n readonly lockName: string\n readonly locks?: MinimalLockManager\n }\n}\n\nconst CORE_METHODS = new Set<string>([\n 'get',\n 'put',\n 'delete',\n 'list',\n 'loadAll',\n 'saveAll',\n 'ping',\n 'listSince',\n 'listPage',\n 'listVaults',\n])\n\n/**\n * Start serving the local store on the channel. Returns a dispose\n * function that stops the RPC listener. The underlying channel is NOT\n * closed by dispose — ownership stays with the caller.\n *\n * When `leaderElection` is set, the RPC handler is only registered while\n * this tab holds the named Web Lock. The returned dispose function\n * always works: if called before the lock is acquired, it cancels the\n * wait; if called while holding the lock, it releases the lock and\n * stops serving.\n */\nexport function servePeerStore(opts: ServePeerStoreOptions): () => void {\n if (!opts.leaderElection) {\n return startServing(opts)\n }\n return startServingWithLeaderElection(opts)\n}\n\n/**\n * Register the RPC handler immediately. Used when leader-election is off,\n * and inside the lock callback when on.\n */\nfunction startServing(opts: ServePeerStoreOptions): () => void {\n const { store, channel, allow } = opts\n\n return serveRpc(channel, async (method, args) => {\n if (!CORE_METHODS.has(method)) {\n throw new Error(`Unknown RPC method: ${method}`)\n }\n if (allow && !allow.has(method)) {\n throw new Error(`Method not allowed: ${method}`)\n }\n\n switch (method) {\n case 'get': {\n const [vault, collection, id] = args as [string, string, string]\n return store.get(vault, collection, id)\n }\n case 'put': {\n const [vault, collection, id, envelope, expectedVersion] = args as [\n string,\n string,\n string,\n EncryptedEnvelope,\n number | undefined,\n ]\n await store.put(vault, collection, id, envelope, expectedVersion)\n return null\n }\n case 'delete': {\n const [vault, collection, id] = args as [string, string, string]\n await store.delete(vault, collection, id)\n return null\n }\n case 'list': {\n const [vault, collection] = args as [string, string]\n return store.list(vault, collection)\n }\n case 'loadAll': {\n const [vault] = args as [string]\n return store.loadAll(vault)\n }\n case 'saveAll': {\n const [vault, data] = args as [string, VaultSnapshot]\n await store.saveAll(vault, data)\n return null\n }\n case 'ping': {\n if (!store.ping) return true\n return store.ping()\n }\n case 'listSince': {\n if (!store.listSince) throw new Error('listSince not supported by remote store')\n const [vault, collection, since] = args as [string, string, string]\n return store.listSince(vault, collection, since)\n }\n case 'listPage': {\n if (!store.listPage) throw new Error('listPage not supported by remote store')\n const [vault, collection, cursor, limit] = args as [\n string,\n string,\n string | undefined,\n number | undefined,\n ]\n return store.listPage(vault, collection, cursor, limit)\n }\n case 'listVaults': {\n if (!store.listVaults) throw new Error('listVaults not supported by remote store')\n return store.listVaults()\n }\n }\n /* istanbul ignore next — CORE_METHODS gate makes this unreachable */\n throw new Error(`Unhandled method: ${method}`)\n })\n}\n\n/**\n * Acquire a Web Lock first; only register the RPC listener while\n * holding it. Returns a dispose that cancels the wait (if not yet\n * acquired) or releases the lock (if held).\n */\nfunction startServingWithLeaderElection(opts: ServePeerStoreOptions): () => void {\n // Asserted by the caller branch in `servePeerStore`.\n const leader = opts.leaderElection as { lockName: string; locks?: MinimalLockManager }\n const locks = leader.locks ?? getDefaultLocks()\n const ac = new AbortController()\n let stopServing: (() => void) | null = null\n let releaseLock: (() => void) | null = null\n let disposed = false\n\n void locks\n .request(leader.lockName, { mode: 'exclusive', signal: ac.signal }, () => {\n if (disposed) return Promise.resolve()\n stopServing = startServing(opts)\n // Hold the lock for the lifetime of this tab's leadership. The\n // returned promise stays pending until `releaseLock` is called by\n // the dispose function.\n return new Promise<void>((resolve) => {\n releaseLock = resolve\n })\n })\n .catch((err: unknown) => {\n // AbortError is the expected cancellation when dispose runs before\n // the lock was acquired. Anything else is unexpected — surface it\n // at the next tick so the host can observe it.\n if ((err as { name?: string } | null)?.name === 'AbortError') return\n queueMicrotask(() => {\n throw err\n })\n })\n\n return () => {\n if (disposed) return\n disposed = true\n if (stopServing) {\n stopServing()\n stopServing = null\n }\n if (releaseLock) {\n releaseLock()\n releaseLock = null\n } else {\n ac.abort()\n }\n }\n}\n\nfunction getDefaultLocks(): MinimalLockManager {\n const nav = (globalThis as { navigator?: { locks?: MinimalLockManager } }).navigator\n if (nav && nav.locks) return nav.locks\n throw new Error(\n 'leaderElection requires the Web Locks API (navigator.locks). ' +\n 'Use Chrome 69+, Firefox 96+, Safari 15.4+, or pass `leaderElection.locks: <stub>` ' +\n 'for tests / non-browser hosts.',\n )\n}\n","/**\n * WebRTC handshake helper — opinionated wrapper around\n * `RTCPeerConnection` that produces a ready-to-use `PeerChannel`.\n *\n * The handshake is split into two halves so the caller can ferry the\n * SDP blobs over whatever signaling channel they prefer (QR code,\n * Matrix room, pastebin, Firebase, signed URL…). Signaling is\n * intentionally out of scope — noy-db has no opinion on how peers\n * discover each other, only on what flows once they do.\n *\n * ```ts\n * // Peer A (initiator)\n * const a = await createOffer({ iceServers })\n * send(a.offer) // → signaling channel\n * const answer = await receive() // ← signaling channel\n * await a.accept(answer)\n * const channel = await a.channel // ready PeerChannel\n *\n * // Peer B (responder)\n * const offer = await receive() // ← signaling channel\n * const b = await acceptOffer(offer, { iceServers })\n * send(b.answer) // → signaling channel\n * const channel = await b.channel // ready PeerChannel\n * ```\n *\n * Browser-only. Node consumers who want to interconnect with browsers\n * can plug `@roamhq/wrtc` into the global `RTCPeerConnection` slot; this\n * module does not pull it in so the package has zero runtime deps.\n *\n * @module\n */\n\nimport type { PeerChannel } from './channel.js'\nimport { fromDataChannel } from './channel.js'\n\ntype PeerConnection = RTCPeerConnection\ntype SessionDescription = RTCSessionDescriptionInit\n\nexport interface WebRTCOptions {\n /** Optional ICE servers (STUN / TURN). */\n readonly iceServers?: RTCIceServer[]\n /** Label for the `RTCDataChannel`. Default `'noydb'`. */\n readonly label?: string\n}\n\nexport interface Initiator {\n readonly offer: SessionDescription\n /** Feed in the remote peer's SDP answer to complete the handshake. */\n accept(answer: SessionDescription): Promise<void>\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nexport interface Responder {\n readonly answer: SessionDescription\n /** Resolves with the opened `PeerChannel` once the DataChannel is live. */\n readonly channel: Promise<PeerChannel>\n readonly connection: PeerConnection\n}\n\nfunction requireRTC(): typeof RTCPeerConnection {\n const g = globalThis as { RTCPeerConnection?: typeof RTCPeerConnection }\n if (!g.RTCPeerConnection) {\n throw new Error(\n '[@noy-db/by-peer] globalThis.RTCPeerConnection is undefined — use this module in a browser, or polyfill with @roamhq/wrtc in Node',\n )\n }\n return g.RTCPeerConnection\n}\n\n/**\n * Build an offer as the initiating peer. Returns the SDP offer to send\n * to the remote peer and a promise for the opened `PeerChannel`.\n */\nexport async function createOffer(opts: WebRTCOptions = {}): Promise<Initiator> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const dc = pc.createDataChannel(opts.label ?? 'noydb', {\n ordered: true,\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n })\n\n const offer = await pc.createOffer()\n await pc.setLocalDescription(offer)\n await waitForIceComplete(pc)\n\n return {\n offer: pc.localDescription ?? offer,\n connection: pc,\n channel: channelPromise,\n async accept(answer) {\n await pc.setRemoteDescription(answer)\n },\n }\n}\n\n/**\n * Accept an incoming offer as the responding peer. Returns the SDP\n * answer to send back to the initiator and a promise for the opened\n * `PeerChannel`.\n */\nexport async function acceptOffer(\n offer: SessionDescription,\n opts: WebRTCOptions = {},\n): Promise<Responder> {\n const RTC = requireRTC()\n const pc = new RTC({\n ...(opts.iceServers && { iceServers: opts.iceServers }),\n })\n\n const channelPromise = new Promise<PeerChannel>((resolve, reject) => {\n pc.addEventListener('datachannel', (ev) => {\n const dc = ev.channel\n if (dc.readyState === 'open') {\n resolve(fromDataChannel(dc))\n } else {\n dc.addEventListener('open', () => resolve(fromDataChannel(dc)))\n dc.addEventListener('error', () => reject(new Error('DataChannel error')))\n }\n })\n })\n\n await pc.setRemoteDescription(offer)\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n await waitForIceComplete(pc)\n\n return {\n answer: pc.localDescription ?? answer,\n connection: pc,\n channel: channelPromise,\n }\n}\n\n/**\n * Resolve once ICE gathering reaches `'complete'`. Using non-trickle ICE\n * keeps the signaling exchange to a single round-trip — at the cost of\n * a slightly longer initial handshake. Consumers that want trickle ICE\n * can bypass this helper and drive `RTCPeerConnection` directly.\n */\nfunction waitForIceComplete(pc: PeerConnection): Promise<void> {\n if (pc.iceGatheringState === 'complete') return Promise.resolve()\n return new Promise((resolve) => {\n const check = () => {\n if (pc.iceGatheringState === 'complete') {\n pc.removeEventListener('icegatheringstatechange', check)\n resolve()\n }\n }\n pc.addEventListener('icegatheringstatechange', check)\n })\n}\n"],"mappings":";AA2CO,SAAS,eAA2C;AAMzD,WAAS,OAA0E;AACjF,UAAM,YAAuB,EAAE,SAAS,oBAAI,IAAI,GAAG,OAAO,oBAAI,IAAI,EAAE;AACpE,UAAM,SAAS,EAAE,GAAG,MAAM;AAC1B,UAAM,KAAkB;AAAA,MACtB,IAAI,SAAS;AACX,eAAO,CAAC,OAAO;AAAA,MACjB;AAAA,MACA,OAAO;AAAA,MAEP;AAAA,MACA,GAAG,OAA4B,UAAkE;AAC/F,YAAI,UAAU,WAAW;AACvB,oBAAU,QAAQ,IAAI,QAA+B;AACrD,iBAAO,MAAM,UAAU,QAAQ,OAAO,QAA+B;AAAA,QACvE;AACA,kBAAU,MAAM,IAAI,QAAsB;AAC1C,eAAO,MAAM,UAAU,MAAM,OAAO,QAAsB;AAAA,MAC5D;AAAA,MACA,QAAQ;AACN,YAAI,OAAO,EAAG;AACd,eAAO,IAAI;AACX,mBAAW,MAAM,UAAU,MAAO,IAAG;AAAA,MACvC;AAAA,IACF;AACA,WAAO,EAAE,IAAI,WAAW,OAAO;AAAA,EACjC;AAEA,QAAM,IAAI,KAAK;AACf,QAAM,IAAI,KAAK;AAEf,WAAS,YAAkB;AACzB,QAAI,CAAC,EAAE,OAAO,GAAG;AACf,QAAE,OAAO,IAAI;AACb,iBAAW,MAAM,EAAE,UAAU,MAAO,IAAG;AAAA,IACzC;AACA,QAAI,CAAC,EAAE,OAAO,GAAG;AACf,QAAE,OAAO,IAAI;AACb,iBAAW,MAAM,EAAE,UAAU,MAAO,IAAG;AAAA,IACzC;AAAA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AAC;AAED,QAAM,GAAG,qBAAqB,KAAK;AACnC,QAAM,SAAS,MAAM,GAAG,aAAa;AACrC,QAAM,GAAG,oBAAoB,MAAM;AACnC,QAAM,mBAAmB,EAAE;AAE3B,SAAO;AAAA,IACL,QAAQ,GAAG,oBAAoB;AAAA,IAC/B,YAAY;AAAA,IACZ,SAAS;AAAA,EACX;AACF;AAQA,SAAS,mBAAmB,IAAmC;AAC7D,MAAI,GAAG,sBAAsB,WAAY,QAAO,QAAQ,QAAQ;AAChE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,QAAQ,MAAM;AAClB,UAAI,GAAG,sBAAsB,YAAY;AACvC,WAAG,oBAAoB,2BAA2B,KAAK;AACvD,gBAAQ;AAAA,MACV;AAAA,IACF;AACA,OAAG,iBAAiB,2BAA2B,KAAK;AAAA,EACtD,CAAC;AACH;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noy-db/by-peer",
|
|
3
|
-
"version": "0.1.0-pre.
|
|
3
|
+
"version": "0.1.0-pre.5",
|
|
4
4
|
"description": "WebRTC peer-to-peer transport for noy-db — direct browser-to-browser channel with signaling-agnostic handshake",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "vLannaAi <vicio@lanna.ai>",
|
|
@@ -39,11 +39,11 @@
|
|
|
39
39
|
"node": ">=18.0.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
|
-
"@noy-db/hub": "0.1.0-pre.
|
|
42
|
+
"@noy-db/hub": "0.1.0-pre.5"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@noy-db/to-memory": "0.1.0-pre.
|
|
46
|
-
"@noy-db/hub": "0.1.0-pre.
|
|
45
|
+
"@noy-db/to-memory": "0.1.0-pre.5",
|
|
46
|
+
"@noy-db/hub": "0.1.0-pre.5"
|
|
47
47
|
},
|
|
48
48
|
"keywords": [
|
|
49
49
|
"noy-db",
|