@dimchansky/meshpost 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +355 -2
- package/dist/blob.d.ts +45 -0
- package/dist/blob.js +364 -0
- package/dist/channel.d.ts +26 -0
- package/dist/channel.js +51 -0
- package/dist/combine.d.ts +7 -0
- package/dist/combine.js +249 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +9 -0
- package/dist/manual.d.ts +13 -0
- package/dist/manual.js +109 -0
- package/dist/mqtt.d.ts +20 -0
- package/dist/mqtt.js +610 -0
- package/dist/room.d.ts +99 -0
- package/dist/room.js +1130 -0
- package/dist/signaling.d.ts +70 -0
- package/dist/signaling.js +118 -0
- package/dist/tabs.d.ts +3 -0
- package/dist/tabs.js +94 -0
- package/dist/ws.d.ts +14 -0
- package/dist/ws.js +272 -0
- package/docs/behavior.md +237 -0
- package/package.json +65 -4
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Individual ICE candidate entry carried inside a Trickle ICE `'ice'` signal. */
|
|
2
|
+
export interface IceCandidatePayload {
|
|
3
|
+
/** SDP candidate attribute string (`''` signals end-of-candidates). */
|
|
4
|
+
readonly candidate: string;
|
|
5
|
+
/** Optional media stream identification tag. */
|
|
6
|
+
readonly sdpMid?: string | null;
|
|
7
|
+
/** Optional zero-based media description index. */
|
|
8
|
+
readonly sdpMLineIndex?: number | null;
|
|
9
|
+
}
|
|
10
|
+
/** Discovery supplies peer IDs. Only the two endpoints interpret the signal payload. */
|
|
11
|
+
export type Signal = {
|
|
12
|
+
kind: 'need';
|
|
13
|
+
previous: number | null;
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'offer' | 'answer';
|
|
16
|
+
attempt: number;
|
|
17
|
+
sdp: string;
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'ice';
|
|
20
|
+
attempt: number;
|
|
21
|
+
candidates: readonly IceCandidatePayload[];
|
|
22
|
+
};
|
|
23
|
+
/** Connection state reported by a signaling adapter. */
|
|
24
|
+
export type SignalingState = 'connecting' | 'online' | 'offline' | 'closed';
|
|
25
|
+
/** Structured error codes that a signaling adapter may report via `Discovery.error`. */
|
|
26
|
+
export type SignalingErrorCode = 'decrypt-failed' | 'signaling-error';
|
|
27
|
+
/** Callbacks and room metadata passed by `joinRoom()` into a `Signaling` adapter factory. */
|
|
28
|
+
export interface Discovery {
|
|
29
|
+
/** Application namespace isolating rooms across apps. */
|
|
30
|
+
readonly appId: string;
|
|
31
|
+
/** Room name. */
|
|
32
|
+
readonly room: string;
|
|
33
|
+
/** Local peer ID (UUID v4). */
|
|
34
|
+
readonly self: string;
|
|
35
|
+
/** Optional shared room password, if configured in `joinRoom()`. */
|
|
36
|
+
readonly password?: string;
|
|
37
|
+
/** Publish the current list of remote peer IDs present in the room. */
|
|
38
|
+
roster(ids: readonly string[]): void;
|
|
39
|
+
/** Deliver an incoming signaling message from a peer already in the roster. */
|
|
40
|
+
receive(from: string, signal: Signal): void;
|
|
41
|
+
/** Report a signaling state transition (with an optional human-readable reason). */
|
|
42
|
+
status(state: SignalingState, reason?: string): void;
|
|
43
|
+
/** Optional: report a structured signaling error (e.g. `'decrypt-failed'` or `'signaling-error'`). */
|
|
44
|
+
error?(code: SignalingErrorCode, message?: string): void;
|
|
45
|
+
}
|
|
46
|
+
/** Active signaling handle returned by a `Signaling` adapter factory. */
|
|
47
|
+
export interface SignalingSession {
|
|
48
|
+
/** Set `true` if this adapter supports incremental Trickle ICE (`{ kind: 'ice' }`) messages. */
|
|
49
|
+
readonly trickle?: boolean;
|
|
50
|
+
/** Send a signal to a peer. Return `true` if accepted, or `false` if signaling is unavailable. */
|
|
51
|
+
send(to: string, signal: Signal): boolean;
|
|
52
|
+
/** Shut down the signaling adapter and release all sockets/timers. */
|
|
53
|
+
close(): void;
|
|
54
|
+
}
|
|
55
|
+
/** Factory function that connects a room to a discovery and SDP exchange transport. */
|
|
56
|
+
export type Signaling = (discovery: Discovery) => SignalingSession;
|
|
57
|
+
export declare const uuidPattern: RegExp;
|
|
58
|
+
export declare const maxAttemptNumber = 2147483647;
|
|
59
|
+
/** Check whether a value is a lowercase hyphenated UUID string. */
|
|
60
|
+
export declare function isUuid(value: unknown): value is string;
|
|
61
|
+
/** Generate an RFC 4122 v4 UUID even in non-secure contexts (e.g. plain HTTP LAN) where crypto.randomUUID is absent. */
|
|
62
|
+
export declare function randomUuid(): string;
|
|
63
|
+
/** Deterministic 64-bit hex hash (works even in non-secure contexts such as file://). */
|
|
64
|
+
export declare function namespaceHash(input: string): string;
|
|
65
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
66
|
+
export declare function isSignal(value: unknown): value is Signal;
|
|
67
|
+
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
68
|
+
* Preserve the original candidate and its priority. Never transmit this local hint.
|
|
69
|
+
*/
|
|
70
|
+
export declare function withLoopbackFallback<T extends Signal>(signal: T): T;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
export const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
2
|
+
export const maxAttemptNumber = 0x7fffffff;
|
|
3
|
+
/** Check whether a value is a lowercase hyphenated UUID string. */
|
|
4
|
+
export function isUuid(value) {
|
|
5
|
+
return typeof value === 'string' && uuidPattern.test(value);
|
|
6
|
+
}
|
|
7
|
+
/** Generate an RFC 4122 v4 UUID even in non-secure contexts (e.g. plain HTTP LAN) where crypto.randomUUID is absent. */
|
|
8
|
+
export function randomUuid() {
|
|
9
|
+
if (typeof crypto.randomUUID === 'function')
|
|
10
|
+
return crypto.randomUUID();
|
|
11
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
12
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
13
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
14
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
15
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
16
|
+
}
|
|
17
|
+
/** Deterministic 64-bit hex hash (works even in non-secure contexts such as file://). */
|
|
18
|
+
export function namespaceHash(input) {
|
|
19
|
+
let h1 = 0xdeadbeef ^ input.length;
|
|
20
|
+
let h2 = 0x41c6ce57 ^ input.length;
|
|
21
|
+
for (let i = 0; i < input.length; i++) {
|
|
22
|
+
const ch = input.charCodeAt(i);
|
|
23
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
24
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
25
|
+
}
|
|
26
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
27
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
28
|
+
return (h2 >>> 0).toString(16).padStart(8, '0') + (h1 >>> 0).toString(16).padStart(8, '0');
|
|
29
|
+
}
|
|
30
|
+
function isIceCandidatePayload(value) {
|
|
31
|
+
if (!value || typeof value !== 'object')
|
|
32
|
+
return false;
|
|
33
|
+
const c = value;
|
|
34
|
+
if (typeof c.candidate !== 'string' || c.candidate.length > 1024)
|
|
35
|
+
return false;
|
|
36
|
+
if (c.sdpMid !== undefined &&
|
|
37
|
+
c.sdpMid !== null &&
|
|
38
|
+
(typeof c.sdpMid !== 'string' || c.sdpMid.length > 64))
|
|
39
|
+
return false;
|
|
40
|
+
if (c.sdpMLineIndex !== undefined &&
|
|
41
|
+
c.sdpMLineIndex !== null &&
|
|
42
|
+
(typeof c.sdpMLineIndex !== 'number' ||
|
|
43
|
+
!Number.isSafeInteger(c.sdpMLineIndex) ||
|
|
44
|
+
c.sdpMLineIndex < 0 ||
|
|
45
|
+
c.sdpMLineIndex > 65535))
|
|
46
|
+
return false;
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
50
|
+
export function isSignal(value) {
|
|
51
|
+
if (!value || typeof value !== 'object')
|
|
52
|
+
return false;
|
|
53
|
+
if (!('kind' in value))
|
|
54
|
+
return false;
|
|
55
|
+
if (value.kind === 'need') {
|
|
56
|
+
return ('previous' in value &&
|
|
57
|
+
(value.previous === null ||
|
|
58
|
+
(typeof value.previous === 'number' &&
|
|
59
|
+
Number.isSafeInteger(value.previous) &&
|
|
60
|
+
value.previous > 0 &&
|
|
61
|
+
value.previous <= maxAttemptNumber)));
|
|
62
|
+
}
|
|
63
|
+
if (value.kind === 'ice') {
|
|
64
|
+
return ('attempt' in value &&
|
|
65
|
+
typeof value.attempt === 'number' &&
|
|
66
|
+
Number.isSafeInteger(value.attempt) &&
|
|
67
|
+
value.attempt > 0 &&
|
|
68
|
+
value.attempt <= maxAttemptNumber &&
|
|
69
|
+
'candidates' in value &&
|
|
70
|
+
Array.isArray(value.candidates) &&
|
|
71
|
+
value.candidates.length > 0 &&
|
|
72
|
+
value.candidates.length <= 32 &&
|
|
73
|
+
value.candidates.every(isIceCandidatePayload));
|
|
74
|
+
}
|
|
75
|
+
return ((value.kind === 'offer' || value.kind === 'answer') &&
|
|
76
|
+
'attempt' in value &&
|
|
77
|
+
typeof value.attempt === 'number' &&
|
|
78
|
+
Number.isSafeInteger(value.attempt) &&
|
|
79
|
+
value.attempt > 0 &&
|
|
80
|
+
value.attempt <= maxAttemptNumber &&
|
|
81
|
+
'sdp' in value &&
|
|
82
|
+
typeof value.sdp === 'string' &&
|
|
83
|
+
value.sdp.length <= 64 * 1024);
|
|
84
|
+
}
|
|
85
|
+
const localMdnsCandidatePattern = /^(?:a=)?candidate:\S+ (\d+) udp \d+ [a-z0-9.-]+\.local (\d+) typ host(?: |$)/i;
|
|
86
|
+
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
87
|
+
* Preserve the original candidate and its priority. Never transmit this local hint.
|
|
88
|
+
*/
|
|
89
|
+
export function withLoopbackFallback(signal) {
|
|
90
|
+
if (signal.kind === 'need')
|
|
91
|
+
return signal;
|
|
92
|
+
if (signal.kind === 'ice') {
|
|
93
|
+
let index = 0;
|
|
94
|
+
const out = [];
|
|
95
|
+
for (const item of signal.candidates) {
|
|
96
|
+
out.push(item);
|
|
97
|
+
const match = localMdnsCandidatePattern.exec(item.candidate);
|
|
98
|
+
if (match) {
|
|
99
|
+
out.push({
|
|
100
|
+
candidate: `candidate:mp${++index} ${match[1]} udp 1 127.0.0.1 ${match[2]} typ host`,
|
|
101
|
+
...(item.sdpMid !== undefined ? { sdpMid: item.sdpMid } : {}),
|
|
102
|
+
...(item.sdpMLineIndex !== undefined ? { sdpMLineIndex: item.sdpMLineIndex } : {})
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return index ? { ...signal, candidates: out } : signal;
|
|
107
|
+
}
|
|
108
|
+
const eol = signal.sdp.includes('\r\n') ? '\r\n' : '\n';
|
|
109
|
+
let index = 0;
|
|
110
|
+
const lines = [];
|
|
111
|
+
for (const line of signal.sdp.split(eol)) {
|
|
112
|
+
lines.push(line);
|
|
113
|
+
const match = /^a=candidate:\S+ (\d+) udp \d+ [a-z0-9.-]+\.local (\d+) typ host(?: |$)/i.exec(line);
|
|
114
|
+
if (match)
|
|
115
|
+
lines.push(`a=candidate:mp${++index} ${match[1]} udp 1 127.0.0.1 ${match[2]} typ host`);
|
|
116
|
+
}
|
|
117
|
+
return index ? { ...signal, sdp: lines.join(eol) } : signal;
|
|
118
|
+
}
|
package/dist/tabs.d.ts
ADDED
package/dist/tabs.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
2
|
+
const maxSeenPeers = 256;
|
|
3
|
+
/** Discover tabs in the same origin and storage partition. Carries signaling only. */
|
|
4
|
+
export function tabSignaling() {
|
|
5
|
+
return (discovery) => {
|
|
6
|
+
const scope = discovery.appId +
|
|
7
|
+
':' +
|
|
8
|
+
discovery.room +
|
|
9
|
+
(discovery.password !== undefined ? ':' + discovery.password : '');
|
|
10
|
+
const channel = new BroadcastChannel('meshpost/1/' + namespaceHash(scope));
|
|
11
|
+
const seen = new Map();
|
|
12
|
+
let closed = false;
|
|
13
|
+
const post = (body) => channel.postMessage({ ...body, from: discovery.self });
|
|
14
|
+
const roster = () => discovery.roster([...seen.keys()]);
|
|
15
|
+
const touch = (id) => {
|
|
16
|
+
const known = seen.has(id);
|
|
17
|
+
if (!known && seen.size >= maxSeenPeers) {
|
|
18
|
+
const oldest = seen.keys().next().value;
|
|
19
|
+
if (oldest !== undefined)
|
|
20
|
+
seen.delete(oldest);
|
|
21
|
+
}
|
|
22
|
+
seen.delete(id);
|
|
23
|
+
seen.set(id, Date.now());
|
|
24
|
+
if (!known)
|
|
25
|
+
roster();
|
|
26
|
+
return known;
|
|
27
|
+
};
|
|
28
|
+
channel.onmessage = ({ data }) => {
|
|
29
|
+
if (closed || !data || !isUuid(data.from) || data.from === discovery.self)
|
|
30
|
+
return;
|
|
31
|
+
if (data.to !== undefined && data.to !== discovery.self)
|
|
32
|
+
return;
|
|
33
|
+
switch (data.type) {
|
|
34
|
+
case 'hello':
|
|
35
|
+
touch(data.from);
|
|
36
|
+
post({ type: 'present', to: data.from });
|
|
37
|
+
break;
|
|
38
|
+
case 'heartbeat':
|
|
39
|
+
if (!touch(data.from))
|
|
40
|
+
post({ type: 'present', to: data.from });
|
|
41
|
+
break;
|
|
42
|
+
case 'present':
|
|
43
|
+
touch(data.from);
|
|
44
|
+
break;
|
|
45
|
+
case 'bye':
|
|
46
|
+
if (seen.delete(data.from))
|
|
47
|
+
roster();
|
|
48
|
+
break;
|
|
49
|
+
case 'signal':
|
|
50
|
+
if (isSignal(data.signal)) {
|
|
51
|
+
touch(data.from);
|
|
52
|
+
discovery.receive(data.from, data.signal);
|
|
53
|
+
}
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const timer = setInterval(() => {
|
|
58
|
+
let changed = false;
|
|
59
|
+
for (const [id, last] of seen) {
|
|
60
|
+
if (Date.now() - last > 30_000) {
|
|
61
|
+
seen.delete(id);
|
|
62
|
+
changed = true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (changed)
|
|
66
|
+
roster();
|
|
67
|
+
if (!closed)
|
|
68
|
+
post({ type: 'heartbeat' });
|
|
69
|
+
}, 5000);
|
|
70
|
+
queueMicrotask(() => {
|
|
71
|
+
if (closed)
|
|
72
|
+
return;
|
|
73
|
+
discovery.status('online');
|
|
74
|
+
post({ type: 'hello' });
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
trickle: true,
|
|
78
|
+
send(to, signal) {
|
|
79
|
+
if (closed)
|
|
80
|
+
return false;
|
|
81
|
+
post({ type: 'signal', to, signal });
|
|
82
|
+
return true;
|
|
83
|
+
},
|
|
84
|
+
close() {
|
|
85
|
+
if (closed)
|
|
86
|
+
return;
|
|
87
|
+
closed = true;
|
|
88
|
+
clearInterval(timer);
|
|
89
|
+
post({ type: 'bye' });
|
|
90
|
+
channel.close();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
}
|
package/dist/ws.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Signaling } from './signaling.js';
|
|
2
|
+
export interface WsSignalingOptions {
|
|
3
|
+
/** Automatically reconnect with jittered backoff when disconnected. @default true */
|
|
4
|
+
reconnect?: boolean;
|
|
5
|
+
/** Maximum time in milliseconds to wait for WebSocket open before retrying/failing. @default 10000 */
|
|
6
|
+
handshakeTimeoutMs?: number;
|
|
7
|
+
/** Interval in milliseconds for client keepalive pings (`{ type: 'ping' }`). @default 25000 */
|
|
8
|
+
pingIntervalMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
12
|
+
* Rooms are isolated by a hash of `(appId, room, password)` so raw passwords are never sent.
|
|
13
|
+
*/
|
|
14
|
+
export declare function wsSignaling(url: string, options?: WsSignalingOptions): Signaling;
|
package/dist/ws.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
2
|
+
const maxFrameBytes = 128 * 1024;
|
|
3
|
+
const maxPeers = 256;
|
|
4
|
+
const defaultHandshakeTimeoutMs = 10_000;
|
|
5
|
+
const defaultPingIntervalMs = 25_000;
|
|
6
|
+
/**
|
|
7
|
+
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
8
|
+
* Rooms are isolated by a hash of `(appId, room, password)` so raw passwords are never sent.
|
|
9
|
+
*/
|
|
10
|
+
export function wsSignaling(url, options = {}) {
|
|
11
|
+
let parsed;
|
|
12
|
+
try {
|
|
13
|
+
parsed = new URL(url);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new TypeError('Invalid WebSocket signaling URL');
|
|
17
|
+
}
|
|
18
|
+
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
|
|
19
|
+
throw new TypeError('WebSocket signaling URL must use ws: or wss:');
|
|
20
|
+
}
|
|
21
|
+
const normalizedUrl = parsed.toString();
|
|
22
|
+
const shouldReconnect = options.reconnect ?? true;
|
|
23
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultHandshakeTimeoutMs;
|
|
24
|
+
if (!Number.isSafeInteger(handshakeTimeoutMs) ||
|
|
25
|
+
handshakeTimeoutMs <= 0 ||
|
|
26
|
+
handshakeTimeoutMs > 2_147_483_647) {
|
|
27
|
+
throw new RangeError('Invalid WebSocket handshake timeout');
|
|
28
|
+
}
|
|
29
|
+
const pingIntervalMs = options.pingIntervalMs ?? defaultPingIntervalMs;
|
|
30
|
+
if (!Number.isSafeInteger(pingIntervalMs) ||
|
|
31
|
+
pingIntervalMs <= 0 ||
|
|
32
|
+
pingIntervalMs > 2_147_483_647) {
|
|
33
|
+
throw new RangeError('Invalid WebSocket ping interval');
|
|
34
|
+
}
|
|
35
|
+
return (discovery) => {
|
|
36
|
+
const roomKey = namespaceHash(discovery.appId +
|
|
37
|
+
':' +
|
|
38
|
+
discovery.room +
|
|
39
|
+
(discovery.password !== undefined ? ':' + discovery.password : ''));
|
|
40
|
+
const knownPeers = new Set();
|
|
41
|
+
let ws;
|
|
42
|
+
let closed = false;
|
|
43
|
+
let reportedOnline = false;
|
|
44
|
+
let reportedOffline = false;
|
|
45
|
+
let awaitingPong = false;
|
|
46
|
+
let attempt = 0;
|
|
47
|
+
let handshakeTimer;
|
|
48
|
+
let pingTimer;
|
|
49
|
+
let reconnectTimer;
|
|
50
|
+
const clearTimers = () => {
|
|
51
|
+
clearTimeout(handshakeTimer);
|
|
52
|
+
handshakeTimer = undefined;
|
|
53
|
+
clearInterval(pingTimer);
|
|
54
|
+
pingTimer = undefined;
|
|
55
|
+
};
|
|
56
|
+
const sendJson = (payload) => {
|
|
57
|
+
if (closed || !ws || ws.readyState !== WebSocket.OPEN)
|
|
58
|
+
return false;
|
|
59
|
+
try {
|
|
60
|
+
ws.send(JSON.stringify(payload));
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const reportOffline = (reason) => {
|
|
68
|
+
if (closed)
|
|
69
|
+
return;
|
|
70
|
+
if (reportedOnline || !reportedOffline) {
|
|
71
|
+
reportedOnline = false;
|
|
72
|
+
reportedOffline = true;
|
|
73
|
+
discovery.status('offline', reason);
|
|
74
|
+
discovery.error?.('signaling-error', reason);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const scheduleReconnect = () => {
|
|
78
|
+
if (closed || !shouldReconnect || reconnectTimer)
|
|
79
|
+
return;
|
|
80
|
+
const base = Math.min(10_000, 500 * 2 ** Math.min(attempt++, 5));
|
|
81
|
+
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
82
|
+
reconnectTimer = setTimeout(() => {
|
|
83
|
+
reconnectTimer = undefined;
|
|
84
|
+
connect();
|
|
85
|
+
}, delay);
|
|
86
|
+
};
|
|
87
|
+
const connect = () => {
|
|
88
|
+
if (closed)
|
|
89
|
+
return;
|
|
90
|
+
clearTimers();
|
|
91
|
+
let socket;
|
|
92
|
+
try {
|
|
93
|
+
socket = new WebSocket(normalizedUrl);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
reportOffline('WebSocket signaling connection failed');
|
|
97
|
+
scheduleReconnect();
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
ws = socket;
|
|
101
|
+
awaitingPong = false;
|
|
102
|
+
let settled = false;
|
|
103
|
+
handshakeTimer = setTimeout(() => {
|
|
104
|
+
if (closed || ws !== socket || settled)
|
|
105
|
+
return;
|
|
106
|
+
try {
|
|
107
|
+
socket.close();
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// Ignore close errors.
|
|
111
|
+
}
|
|
112
|
+
}, handshakeTimeoutMs);
|
|
113
|
+
socket.onopen = () => {
|
|
114
|
+
if (closed || ws !== socket) {
|
|
115
|
+
try {
|
|
116
|
+
socket.close();
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Ignore close errors.
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
settled = true;
|
|
124
|
+
clearTimeout(handshakeTimer);
|
|
125
|
+
handshakeTimer = undefined;
|
|
126
|
+
attempt = 0;
|
|
127
|
+
awaitingPong = false;
|
|
128
|
+
if (!sendJson({ type: 'join', room: roomKey, id: discovery.self })) {
|
|
129
|
+
try {
|
|
130
|
+
socket.close();
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Ignore close errors.
|
|
134
|
+
}
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!reportedOnline) {
|
|
138
|
+
reportedOnline = true;
|
|
139
|
+
reportedOffline = false;
|
|
140
|
+
discovery.status('online');
|
|
141
|
+
}
|
|
142
|
+
pingTimer = setInterval(() => {
|
|
143
|
+
if (closed || ws !== socket)
|
|
144
|
+
return;
|
|
145
|
+
if (awaitingPong) {
|
|
146
|
+
try {
|
|
147
|
+
socket.close();
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// Ignore close errors.
|
|
151
|
+
}
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
awaitingPong = true;
|
|
155
|
+
if (!sendJson({ type: 'ping' })) {
|
|
156
|
+
try {
|
|
157
|
+
socket.close();
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// Ignore close errors.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}, pingIntervalMs);
|
|
164
|
+
};
|
|
165
|
+
socket.onmessage = ({ data }) => {
|
|
166
|
+
if (closed || ws !== socket)
|
|
167
|
+
return;
|
|
168
|
+
if (typeof data !== 'string' || data.length > maxFrameBytes)
|
|
169
|
+
return;
|
|
170
|
+
let msg;
|
|
171
|
+
try {
|
|
172
|
+
const parsedMsg = JSON.parse(data);
|
|
173
|
+
msg =
|
|
174
|
+
parsedMsg && typeof parsedMsg === 'object'
|
|
175
|
+
? parsedMsg
|
|
176
|
+
: null;
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (!msg || typeof msg.type !== 'string')
|
|
182
|
+
return;
|
|
183
|
+
awaitingPong = false;
|
|
184
|
+
if (msg.type === 'pong')
|
|
185
|
+
return;
|
|
186
|
+
if (msg.type === 'roster' && Array.isArray(msg.peers)) {
|
|
187
|
+
knownPeers.clear();
|
|
188
|
+
for (const id of msg.peers) {
|
|
189
|
+
if (isUuid(id) && id !== discovery.self) {
|
|
190
|
+
knownPeers.add(id);
|
|
191
|
+
if (knownPeers.size >= maxPeers)
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
discovery.roster([...knownPeers]);
|
|
196
|
+
}
|
|
197
|
+
else if (msg.type === 'signal' &&
|
|
198
|
+
isUuid(msg.from) &&
|
|
199
|
+
msg.from !== discovery.self &&
|
|
200
|
+
isSignal(msg.signal)) {
|
|
201
|
+
if (!knownPeers.has(msg.from)) {
|
|
202
|
+
if (knownPeers.size >= maxPeers) {
|
|
203
|
+
const oldest = knownPeers.values().next().value;
|
|
204
|
+
if (oldest !== undefined)
|
|
205
|
+
knownPeers.delete(oldest);
|
|
206
|
+
}
|
|
207
|
+
knownPeers.add(msg.from);
|
|
208
|
+
discovery.roster([...knownPeers]);
|
|
209
|
+
}
|
|
210
|
+
discovery.receive(msg.from, msg.signal);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
socket.onerror = () => {
|
|
214
|
+
if (ws !== socket)
|
|
215
|
+
return;
|
|
216
|
+
try {
|
|
217
|
+
socket.close();
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// Ignore close errors.
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
socket.onclose = () => {
|
|
224
|
+
if (ws !== socket)
|
|
225
|
+
return;
|
|
226
|
+
ws = undefined;
|
|
227
|
+
clearTimers();
|
|
228
|
+
if (closed)
|
|
229
|
+
return;
|
|
230
|
+
const reason = settled
|
|
231
|
+
? 'WebSocket signaling disconnected'
|
|
232
|
+
: 'WebSocket signaling connection failed';
|
|
233
|
+
reportOffline(reason);
|
|
234
|
+
scheduleReconnect();
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
// Defer initial connect so synchronous errors never fire before callers attach listeners.
|
|
238
|
+
queueMicrotask(connect);
|
|
239
|
+
return {
|
|
240
|
+
trickle: true,
|
|
241
|
+
send(to, signal) {
|
|
242
|
+
return sendJson({ type: 'signal', to, signal });
|
|
243
|
+
},
|
|
244
|
+
close() {
|
|
245
|
+
if (closed)
|
|
246
|
+
return;
|
|
247
|
+
closed = true;
|
|
248
|
+
clearTimers();
|
|
249
|
+
clearTimeout(reconnectTimer);
|
|
250
|
+
reconnectTimer = undefined;
|
|
251
|
+
const current = ws;
|
|
252
|
+
ws = undefined;
|
|
253
|
+
if (current) {
|
|
254
|
+
if (current.readyState === WebSocket.OPEN) {
|
|
255
|
+
try {
|
|
256
|
+
current.send(JSON.stringify({ type: 'leave' }));
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// Ignore send errors during close.
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
try {
|
|
263
|
+
current.close();
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
// Ignore close errors.
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
};
|
|
272
|
+
}
|