@dimchansky/meshpost 0.2.0 → 0.3.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/README.md +86 -12
- package/dist/combine.d.ts +12 -1
- package/dist/combine.js +304 -213
- package/dist/index.d.ts +5 -1
- package/dist/index.js +3 -1
- package/dist/room.d.ts +6 -0
- package/dist/room.js +75 -6
- package/dist/signaling.d.ts +5 -0
- package/dist/tabs.js +8 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +81 -0
- package/dist/voice.js +838 -0
- package/docs/behavior.md +20 -5
- package/package.json +1 -1
package/dist/room.js
CHANGED
|
@@ -1,4 +1,24 @@
|
|
|
1
1
|
import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
|
|
2
|
+
const roomInternals = new WeakMap();
|
|
3
|
+
/** @internal */
|
|
4
|
+
export function isRoomClosed(room) {
|
|
5
|
+
const internal = roomInternals.get(room);
|
|
6
|
+
return internal ? internal.isClosed() : room.signalingState === 'closed';
|
|
7
|
+
}
|
|
8
|
+
/** @internal */
|
|
9
|
+
export function onRoomClose(room, fn) {
|
|
10
|
+
const internal = roomInternals.get(room);
|
|
11
|
+
if (!internal) {
|
|
12
|
+
if (room.signalingState === 'closed')
|
|
13
|
+
fn();
|
|
14
|
+
return () => { };
|
|
15
|
+
}
|
|
16
|
+
return internal.onClose(fn);
|
|
17
|
+
}
|
|
18
|
+
/** @internal */
|
|
19
|
+
export function getRoomRemoteStreams(room) {
|
|
20
|
+
return roomInternals.get(room)?.getRemoteStreams() ?? [];
|
|
21
|
+
}
|
|
2
22
|
/** Built-in Cloudflare and Google public STUN servers used by default. */
|
|
3
23
|
export const defaultIceServers = Object.freeze([
|
|
4
24
|
Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
|
|
@@ -381,8 +401,13 @@ export function joinRoom(name, options) {
|
|
|
381
401
|
}
|
|
382
402
|
});
|
|
383
403
|
};
|
|
404
|
+
const canReachPeer = (id) => {
|
|
405
|
+
if (!signaling)
|
|
406
|
+
return false;
|
|
407
|
+
return typeof signaling.canReach === 'function' ? signaling.canReach(id) : state === 'online';
|
|
408
|
+
};
|
|
384
409
|
function retry(peer) {
|
|
385
|
-
if (stopped ||
|
|
410
|
+
if (stopped || !canReachPeer(peer.id) || !peer.advertised || peer.retry || peer.link)
|
|
386
411
|
return;
|
|
387
412
|
const base = Math.min(8000, 350 * 2 ** Math.min(peer.failures++, 5));
|
|
388
413
|
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
@@ -776,7 +801,12 @@ export function joinRoom(name, options) {
|
|
|
776
801
|
}
|
|
777
802
|
}
|
|
778
803
|
function discover(peer) {
|
|
779
|
-
if (stopped ||
|
|
804
|
+
if (stopped ||
|
|
805
|
+
!signaling ||
|
|
806
|
+
!peer.advertised ||
|
|
807
|
+
!canReachPeer(peer.id) ||
|
|
808
|
+
peer.link ||
|
|
809
|
+
peer.retry)
|
|
780
810
|
return;
|
|
781
811
|
if (self < peer.id)
|
|
782
812
|
void negotiate(peer, ++nextAttempt);
|
|
@@ -895,14 +925,16 @@ export function joinRoom(name, options) {
|
|
|
895
925
|
state = next;
|
|
896
926
|
if (next !== 'online') {
|
|
897
927
|
for (const peer of peers.values()) {
|
|
898
|
-
|
|
899
|
-
|
|
928
|
+
if (!canReachPeer(peer.id)) {
|
|
929
|
+
clearTimeout(peer.retry);
|
|
930
|
+
delete peer.retry;
|
|
931
|
+
}
|
|
900
932
|
}
|
|
901
933
|
}
|
|
902
934
|
status.fire(next, reason);
|
|
903
935
|
if (!stopped && state === 'online') {
|
|
904
936
|
for (const peer of peers.values()) {
|
|
905
|
-
if (peer.advertised && !peer.link) {
|
|
937
|
+
if (peer.advertised && !peer.link && !peer.retry) {
|
|
906
938
|
peer.failures = 0;
|
|
907
939
|
discover(peer);
|
|
908
940
|
}
|
|
@@ -965,8 +997,9 @@ export function joinRoom(name, options) {
|
|
|
965
997
|
useTrickle = signaling.trickle === true;
|
|
966
998
|
for (const peer of peers.values())
|
|
967
999
|
discover(peer);
|
|
1000
|
+
const closeHooks = new Set();
|
|
968
1001
|
const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
|
|
969
|
-
|
|
1002
|
+
const room = {
|
|
970
1003
|
id: self,
|
|
971
1004
|
get peers() {
|
|
972
1005
|
return connected();
|
|
@@ -1100,6 +1133,15 @@ export function joinRoom(name, options) {
|
|
|
1100
1133
|
stopped = true;
|
|
1101
1134
|
const wasClosed = state === 'closed';
|
|
1102
1135
|
state = 'closed';
|
|
1136
|
+
for (const fn of [...closeHooks]) {
|
|
1137
|
+
closeHooks.delete(fn);
|
|
1138
|
+
try {
|
|
1139
|
+
fn();
|
|
1140
|
+
}
|
|
1141
|
+
catch (error) {
|
|
1142
|
+
globalThis.reportError?.(error);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1103
1145
|
signaling?.close();
|
|
1104
1146
|
for (const peer of peers.values()) {
|
|
1105
1147
|
peer.advertised = false;
|
|
@@ -1127,4 +1169,31 @@ export function joinRoom(name, options) {
|
|
|
1127
1169
|
group.clear();
|
|
1128
1170
|
}
|
|
1129
1171
|
};
|
|
1172
|
+
roomInternals.set(room, {
|
|
1173
|
+
isClosed: () => stopped,
|
|
1174
|
+
onClose(fn) {
|
|
1175
|
+
if (stopped) {
|
|
1176
|
+
fn();
|
|
1177
|
+
return () => { };
|
|
1178
|
+
}
|
|
1179
|
+
closeHooks.add(fn);
|
|
1180
|
+
return () => {
|
|
1181
|
+
closeHooks.delete(fn);
|
|
1182
|
+
};
|
|
1183
|
+
},
|
|
1184
|
+
getRemoteStreams() {
|
|
1185
|
+
const out = [];
|
|
1186
|
+
if (stopped)
|
|
1187
|
+
return out;
|
|
1188
|
+
for (const peer of peers.values()) {
|
|
1189
|
+
if (!peer.link?.ready)
|
|
1190
|
+
continue;
|
|
1191
|
+
for (const stream of peer.link.remoteStreams.values()) {
|
|
1192
|
+
out.push([peer.id, stream]);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
return out;
|
|
1196
|
+
}
|
|
1197
|
+
});
|
|
1198
|
+
return room;
|
|
1130
1199
|
}
|
package/dist/signaling.d.ts
CHANGED
|
@@ -47,6 +47,11 @@ export interface Discovery {
|
|
|
47
47
|
export interface SignalingSession {
|
|
48
48
|
/** Set `true` if this adapter supports incremental Trickle ICE (`{ kind: 'ice' }`) messages. */
|
|
49
49
|
readonly trickle?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Optional per-peer reachability check for composite adapters (such as `withLocalTabs`) whose
|
|
52
|
+
* outer `SignalingState` reflects a primary transport while secondary local transports remain online.
|
|
53
|
+
*/
|
|
54
|
+
canReach?(peerId: string): boolean;
|
|
50
55
|
/** Send a signal to a peer. Return `true` if accepted, or `false` if signaling is unavailable. */
|
|
51
56
|
send(to: string, signal: Signal): boolean;
|
|
52
57
|
/** Shut down the signaling adapter and release all sockets/timers. */
|
package/dist/tabs.js
CHANGED
|
@@ -10,7 +10,14 @@ export function tabSignaling() {
|
|
|
10
10
|
const channel = new BroadcastChannel('meshpost/1/' + namespaceHash(scope));
|
|
11
11
|
const seen = new Map();
|
|
12
12
|
let closed = false;
|
|
13
|
-
const post = (body) =>
|
|
13
|
+
const post = (body) => {
|
|
14
|
+
try {
|
|
15
|
+
channel.postMessage({ ...body, from: discovery.self });
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
// Ignore asynchronous partition or bfcache restrictions.
|
|
19
|
+
}
|
|
20
|
+
};
|
|
14
21
|
const roster = () => discovery.roster([...seen.keys()]);
|
|
15
22
|
const touch = (id) => {
|
|
16
23
|
const known = seen.has(id);
|
package/dist/turn.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface FetchTurnOptions {
|
|
2
|
+
/** Optional shared Bearer token sent in the `Authorization` header. */
|
|
3
|
+
accessKey?: string;
|
|
4
|
+
/** Optional external AbortSignal to cancel the request. */
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
/** Request timeout in milliseconds. Pass `0` to disable timeout. @default 5000 */
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Fetch short-lived TURN credentials from an HTTPS broker (`POST` returning `{ iceServers }`),
|
|
11
|
+
* such as Meshpost's reference Cloudflare Worker (`examples/turn-worker/worker.js`).
|
|
12
|
+
*/
|
|
13
|
+
export declare function fetchTurnCredentials(url: string, options?: FetchTurnOptions): Promise<RTCIceServer[]>;
|
package/dist/turn.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
const maxTimeoutMs = 2_147_483_647;
|
|
2
|
+
const defaultTimeoutMs = 5_000;
|
|
3
|
+
const maxAccessKeyLength = 1024;
|
|
4
|
+
const maxResponseBytes = 64 * 1024;
|
|
5
|
+
const maxIceServers = 16;
|
|
6
|
+
const maxUrlsPerServer = 8;
|
|
7
|
+
const maxIceUrlLength = 256;
|
|
8
|
+
const maxCredentialLength = 512;
|
|
9
|
+
const iceUrlPattern = /^(stuns?|turns?):[^\s]+$/i;
|
|
10
|
+
const headerControlPattern = /[\r\n\0]/;
|
|
11
|
+
const decoder = new TextDecoder();
|
|
12
|
+
function validateBrokerUrl(rawUrl) {
|
|
13
|
+
if (typeof rawUrl !== 'string') {
|
|
14
|
+
throw new TypeError('TURN broker URL must be a string');
|
|
15
|
+
}
|
|
16
|
+
const trimmed = rawUrl.trim();
|
|
17
|
+
if (!trimmed) {
|
|
18
|
+
throw new TypeError('TURN broker URL must not be empty');
|
|
19
|
+
}
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = new URL(trimmed);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new TypeError('TURN broker URL must be a valid https:// URL');
|
|
26
|
+
}
|
|
27
|
+
const isLoopbackHttp = parsed.protocol === 'http:' &&
|
|
28
|
+
(parsed.hostname === 'localhost' ||
|
|
29
|
+
parsed.hostname === '127.0.0.1' ||
|
|
30
|
+
parsed.hostname === '[::1]');
|
|
31
|
+
if (parsed.protocol !== 'https:' && !isLoopbackHttp) {
|
|
32
|
+
throw new TypeError('TURN broker URL must use https:// (or http://localhost for local testing)');
|
|
33
|
+
}
|
|
34
|
+
if (parsed.username || parsed.password) {
|
|
35
|
+
throw new TypeError('TURN broker URL must not include embedded credentials');
|
|
36
|
+
}
|
|
37
|
+
return parsed.href;
|
|
38
|
+
}
|
|
39
|
+
function validateAccessKey(accessKey) {
|
|
40
|
+
if (accessKey === undefined)
|
|
41
|
+
return null;
|
|
42
|
+
if (typeof accessKey !== 'string') {
|
|
43
|
+
throw new TypeError('TURN access key must be a string');
|
|
44
|
+
}
|
|
45
|
+
if (accessKey.length > maxAccessKeyLength || headerControlPattern.test(accessKey)) {
|
|
46
|
+
throw new TypeError('Invalid TURN access key');
|
|
47
|
+
}
|
|
48
|
+
const trimmed = accessKey.trim();
|
|
49
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
50
|
+
}
|
|
51
|
+
async function readBoundedText(response) {
|
|
52
|
+
const contentLength = response.headers.get('content-length');
|
|
53
|
+
if (contentLength !== null) {
|
|
54
|
+
const declared = Number(contentLength);
|
|
55
|
+
if (Number.isFinite(declared) && declared > maxResponseBytes) {
|
|
56
|
+
void response.body?.cancel().catch(() => { });
|
|
57
|
+
throw new Error('TURN broker response exceeded 64 KiB limit');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const reader = response.body?.getReader();
|
|
61
|
+
if (!reader) {
|
|
62
|
+
const buf = new Uint8Array(await response.arrayBuffer());
|
|
63
|
+
if (buf.byteLength > maxResponseBytes) {
|
|
64
|
+
throw new Error('TURN broker response exceeded 64 KiB limit');
|
|
65
|
+
}
|
|
66
|
+
return decoder.decode(buf);
|
|
67
|
+
}
|
|
68
|
+
const chunks = [];
|
|
69
|
+
let total = 0;
|
|
70
|
+
for (;;) {
|
|
71
|
+
const { done, value } = await reader.read();
|
|
72
|
+
if (done)
|
|
73
|
+
break;
|
|
74
|
+
if (!value || value.byteLength === 0)
|
|
75
|
+
continue;
|
|
76
|
+
total += value.byteLength;
|
|
77
|
+
if (total > maxResponseBytes) {
|
|
78
|
+
void reader.cancel().catch(() => { });
|
|
79
|
+
throw new Error('TURN broker response exceeded 64 KiB limit');
|
|
80
|
+
}
|
|
81
|
+
chunks.push(value);
|
|
82
|
+
}
|
|
83
|
+
if (chunks.length === 0)
|
|
84
|
+
return '';
|
|
85
|
+
if (chunks.length === 1)
|
|
86
|
+
return decoder.decode(chunks[0]);
|
|
87
|
+
const merged = new Uint8Array(total);
|
|
88
|
+
let offset = 0;
|
|
89
|
+
for (const chunk of chunks) {
|
|
90
|
+
merged.set(chunk, offset);
|
|
91
|
+
offset += chunk.byteLength;
|
|
92
|
+
}
|
|
93
|
+
return decoder.decode(merged);
|
|
94
|
+
}
|
|
95
|
+
function sanitizeIceServers(raw) {
|
|
96
|
+
if (!Array.isArray(raw))
|
|
97
|
+
return [];
|
|
98
|
+
const valid = [];
|
|
99
|
+
for (const item of raw) {
|
|
100
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
101
|
+
continue;
|
|
102
|
+
const entry = item;
|
|
103
|
+
const rawUrls = Array.isArray(entry.urls) ? entry.urls : [entry.urls];
|
|
104
|
+
const urls = [];
|
|
105
|
+
for (const candidate of rawUrls) {
|
|
106
|
+
if (typeof candidate !== 'string')
|
|
107
|
+
continue;
|
|
108
|
+
const trimmed = candidate.trim();
|
|
109
|
+
if (trimmed.length > 0 && trimmed.length <= maxIceUrlLength && iceUrlPattern.test(trimmed)) {
|
|
110
|
+
urls.push(trimmed);
|
|
111
|
+
if (urls.length >= maxUrlsPerServer)
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (urls.length === 0)
|
|
116
|
+
continue;
|
|
117
|
+
const server = { urls: urls.length === 1 ? urls[0] : urls };
|
|
118
|
+
if (typeof entry.username === 'string' &&
|
|
119
|
+
entry.username.length > 0 &&
|
|
120
|
+
entry.username.length <= maxCredentialLength) {
|
|
121
|
+
server.username = entry.username;
|
|
122
|
+
}
|
|
123
|
+
if (typeof entry.credential === 'string' &&
|
|
124
|
+
entry.credential.length > 0 &&
|
|
125
|
+
entry.credential.length <= maxCredentialLength) {
|
|
126
|
+
server.credential = entry.credential;
|
|
127
|
+
}
|
|
128
|
+
valid.push(server);
|
|
129
|
+
if (valid.length >= maxIceServers)
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
return valid;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Fetch short-lived TURN credentials from an HTTPS broker (`POST` returning `{ iceServers }`),
|
|
136
|
+
* such as Meshpost's reference Cloudflare Worker (`examples/turn-worker/worker.js`).
|
|
137
|
+
*/
|
|
138
|
+
export async function fetchTurnCredentials(url, options) {
|
|
139
|
+
const validatedUrl = validateBrokerUrl(url);
|
|
140
|
+
const token = validateAccessKey(options?.accessKey);
|
|
141
|
+
const timeoutMs = options?.timeoutMs ?? defaultTimeoutMs;
|
|
142
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > maxTimeoutMs) {
|
|
143
|
+
throw new RangeError('Expected a safe integer timeoutMs between 0 and 2147483647');
|
|
144
|
+
}
|
|
145
|
+
const externalSignal = options?.signal;
|
|
146
|
+
if (externalSignal?.aborted) {
|
|
147
|
+
throw externalSignal.reason ?? new DOMException('The operation was aborted.', 'AbortError');
|
|
148
|
+
}
|
|
149
|
+
const controller = new AbortController();
|
|
150
|
+
let timedOut = false;
|
|
151
|
+
let timer;
|
|
152
|
+
const onExternalAbort = () => {
|
|
153
|
+
controller.abort(externalSignal?.reason ?? new DOMException('The operation was aborted.', 'AbortError'));
|
|
154
|
+
};
|
|
155
|
+
if (externalSignal) {
|
|
156
|
+
externalSignal.addEventListener('abort', onExternalAbort, { once: true });
|
|
157
|
+
}
|
|
158
|
+
if (timeoutMs > 0) {
|
|
159
|
+
timer = setTimeout(() => {
|
|
160
|
+
timedOut = true;
|
|
161
|
+
controller.abort(new DOMException('TURN credential request timed out', 'TimeoutError'));
|
|
162
|
+
}, timeoutMs);
|
|
163
|
+
}
|
|
164
|
+
const headers = {};
|
|
165
|
+
if (token !== null) {
|
|
166
|
+
headers.Authorization = `Bearer ${token}`;
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
const response = await fetch(validatedUrl, {
|
|
170
|
+
method: 'POST',
|
|
171
|
+
headers,
|
|
172
|
+
signal: controller.signal,
|
|
173
|
+
redirect: 'error',
|
|
174
|
+
credentials: 'omit',
|
|
175
|
+
cache: 'no-store'
|
|
176
|
+
});
|
|
177
|
+
if (!response.ok) {
|
|
178
|
+
void response.body?.cancel().catch(() => { });
|
|
179
|
+
if (response.status === 401)
|
|
180
|
+
throw new Error('TURN access key rejected (401)');
|
|
181
|
+
if (response.status === 403)
|
|
182
|
+
throw new Error('TURN broker rejected this origin (403)');
|
|
183
|
+
throw new Error(`TURN broker failed with HTTP ${response.status}`);
|
|
184
|
+
}
|
|
185
|
+
const rawText = await readBoundedText(response);
|
|
186
|
+
let parsed;
|
|
187
|
+
try {
|
|
188
|
+
parsed = JSON.parse(rawText);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
throw new Error('TURN broker returned invalid JSON');
|
|
192
|
+
}
|
|
193
|
+
const servers = sanitizeIceServers(parsed && typeof parsed === 'object' ? parsed.iceServers : null);
|
|
194
|
+
if (servers.length === 0) {
|
|
195
|
+
throw new Error('TURN broker returned no valid ICE servers');
|
|
196
|
+
}
|
|
197
|
+
return servers;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (timedOut) {
|
|
201
|
+
throw new DOMException('TURN credential request timed out', 'TimeoutError');
|
|
202
|
+
}
|
|
203
|
+
if (externalSignal?.aborted) {
|
|
204
|
+
throw externalSignal.reason ?? new DOMException('The operation was aborted.', 'AbortError');
|
|
205
|
+
}
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
if (timer !== undefined)
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
externalSignal?.removeEventListener('abort', onExternalAbort);
|
|
212
|
+
}
|
|
213
|
+
}
|
package/dist/voice.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type ListenOptions, type Room } from './room.js';
|
|
2
|
+
/** Current state of the local microphone managed by `createVoice()`. */
|
|
3
|
+
export type MicStatus = 'off' | 'requesting' | 'live' | 'muted' | 'error';
|
|
4
|
+
/** Structured error codes describing why local microphone capture failed. */
|
|
5
|
+
export type MicErrorCode = 'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown';
|
|
6
|
+
/** Structured microphone capture error exposed on `voice.micError`. */
|
|
7
|
+
export interface MicError {
|
|
8
|
+
readonly code: MicErrorCode;
|
|
9
|
+
readonly message: string;
|
|
10
|
+
}
|
|
11
|
+
/** Immutable state snapshot emitted by `voice.getSnapshot()` and `voice.onChange()`. */
|
|
12
|
+
export interface VoiceSnapshot {
|
|
13
|
+
readonly micStatus: MicStatus;
|
|
14
|
+
readonly micError: MicError | null;
|
|
15
|
+
readonly autoplayBlocked: boolean;
|
|
16
|
+
readonly deafened: boolean;
|
|
17
|
+
readonly volume: number;
|
|
18
|
+
readonly selfSpeaking: boolean;
|
|
19
|
+
readonly remotePeers: readonly string[];
|
|
20
|
+
readonly speakingPeers: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
/** Configuration options for `createVoice()`. */
|
|
23
|
+
export interface VoiceOptions {
|
|
24
|
+
/** Initial playback volume for incoming peer audio (`0` to `1`). @default 1 */
|
|
25
|
+
volume?: number;
|
|
26
|
+
/** Start with incoming peer audio muted locally (`audio.muted = true`). @default false */
|
|
27
|
+
deafened?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Custom audio track constraints passed to `getUserMedia`.
|
|
30
|
+
* @default { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
|
|
31
|
+
*/
|
|
32
|
+
audioConstraints?: MediaTrackConstraints | true;
|
|
33
|
+
/** Automatically attach global capture-phase gesture & visibility listeners to unlock blocked playback. @default true */
|
|
34
|
+
autoUnlock?: boolean;
|
|
35
|
+
/** Enable shared lazy AudioContext + AnalyserNode speaking detection (`selfSpeaking` & `speakingPeers`). @default true */
|
|
36
|
+
speakingDetection?: boolean;
|
|
37
|
+
/** RMS amplitude threshold (`0` to `1`) for speaking detection. @default 0.03 */
|
|
38
|
+
speakingThreshold?: number;
|
|
39
|
+
/** Polling interval in milliseconds (`50` to `60000`) for speaking detection. @default 180 */
|
|
40
|
+
speakingIntervalMs?: number;
|
|
41
|
+
/** Optional target peer ID scoping outgoing microphone audio only (`room.addStream(stream, to)`). Incoming audio from all peers still plays. */
|
|
42
|
+
to?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Headless P2P voice chat controller built on top of a `Room`. */
|
|
45
|
+
export interface Voice extends VoiceSnapshot {
|
|
46
|
+
/** Return an immutable snapshot of all current voice states. */
|
|
47
|
+
getSnapshot(): VoiceSnapshot;
|
|
48
|
+
/**
|
|
49
|
+
* Acquire microphone on first call (`'off' | 'error'` -> `'requesting'` -> `'live'`),
|
|
50
|
+
* or toggle instant soft-mute (`track.enabled`) without WebRTC renegotiation (`'live'` <-> `'muted'`).
|
|
51
|
+
* Concurrent calls while `'requesting'` coalesce onto the in-flight request. Resolves to `'off'` if closed.
|
|
52
|
+
*/
|
|
53
|
+
toggleMic(): Promise<MicStatus>;
|
|
54
|
+
/**
|
|
55
|
+
* Acquire microphone if not active, or unmute if currently soft-muted.
|
|
56
|
+
* Concurrent calls while `'requesting'` coalesce onto the in-flight request. Resolves to `'off'` if closed.
|
|
57
|
+
*/
|
|
58
|
+
startMic(): Promise<MicStatus>;
|
|
59
|
+
/** Soft-mute (`true`) or unmute (`false`) an already-acquired local microphone (`'live' | 'muted'`). No-op otherwise. */
|
|
60
|
+
setMuted(muted: boolean): void;
|
|
61
|
+
/** Detach local stream from the room (`room.removeStream`), cancel any in-flight `getUserMedia`, and stop hardware microphone tracks (`track.stop()`). */
|
|
62
|
+
stopMic(): void;
|
|
63
|
+
/** Set playback volume (`0` to `1`, clamped) on all current and future remote `<audio>` elements. */
|
|
64
|
+
setVolume(volume: number): void;
|
|
65
|
+
/** Mute (`true`) or unmute (`false`) all incoming remote `<audio>` elements locally. Unmuting also triggers `unlockAudio()`. */
|
|
66
|
+
setDeafened(deafened: boolean): void;
|
|
67
|
+
/** Manually trigger synchronous `AudioContext.resume()` + `audio.play()` retry. */
|
|
68
|
+
unlockAudio(): void;
|
|
69
|
+
/** Subscribe to any state change in `VoiceSnapshot`. Supports `ListenOptions` (`{ once, signal }`). */
|
|
70
|
+
onChange(fn: (snapshot: VoiceSnapshot) => void, options?: ListenOptions): () => void;
|
|
71
|
+
/** Release microphone tracks, remove hidden `<audio>` elements, close `AudioContext`, restore `audioSession`, and detach all listeners. */
|
|
72
|
+
close(): void;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Create a headless P2P voice chat controller attached to a `Room`.
|
|
76
|
+
*
|
|
77
|
+
* Automatically plays incoming peer audio streams, manages local microphone capture with instant
|
|
78
|
+
* soft-mute (`track.enabled`) vs full hardware release, tracks speaking peers via a shared lazy
|
|
79
|
+
* `AudioContext`, and handles browser Autoplay Policy & iOS Safari audio unlocking.
|
|
80
|
+
*/
|
|
81
|
+
export declare function createVoice(room: Room, options?: VoiceOptions): Voice;
|