@poolse/sdk 2.25.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/LICENSE +206 -21
- package/README.md +2 -2
- package/dist/index.cjs +6 -691
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -431
- package/dist/index.d.ts +22 -431
- package/dist/index.js +7 -687
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/index.cjs
CHANGED
|
@@ -105,640 +105,21 @@ var AuthError = class extends ApiError {
|
|
|
105
105
|
}
|
|
106
106
|
};
|
|
107
107
|
|
|
108
|
-
// src/voice/calls.ts
|
|
109
|
-
function toMedia(value) {
|
|
110
|
-
return value === "video" ? "video" : "audio";
|
|
111
|
-
}
|
|
112
|
-
var CallsResource = class {
|
|
113
|
-
/** Resolves the user channel lazily — it may not be joined yet. */
|
|
114
|
-
getChannel;
|
|
115
|
-
incoming = /* @__PURE__ */ new Set();
|
|
116
|
-
accepted = /* @__PURE__ */ new Set();
|
|
117
|
-
declined = /* @__PURE__ */ new Set();
|
|
118
|
-
busy = /* @__PURE__ */ new Set();
|
|
119
|
-
cancelled = /* @__PURE__ */ new Set();
|
|
120
|
-
ended = /* @__PURE__ */ new Set();
|
|
121
|
-
bound = false;
|
|
122
|
-
constructor(getChannel) {
|
|
123
|
-
this.getChannel = getChannel;
|
|
124
|
-
}
|
|
125
|
-
// ── placing and answering ──────────────────────────────────────────
|
|
126
|
-
/**
|
|
127
|
-
* Ring every other member of a conversation. Resolves once the server
|
|
128
|
-
* has fanned the invite out, with the minted call id and who was rung
|
|
129
|
-
* — not when anyone answers; that arrives via {@link onAccepted}.
|
|
130
|
-
*/
|
|
131
|
-
invite(conversationId, media = "audio") {
|
|
132
|
-
return this.request("call:invite", {
|
|
133
|
-
conversation_id: conversationId,
|
|
134
|
-
media
|
|
135
|
-
}).then((reply) => ({
|
|
136
|
-
callId: reply.call_id,
|
|
137
|
-
conversationId: reply.conversation_id,
|
|
138
|
-
calleeUserIds: reply.callee_user_ids ?? [],
|
|
139
|
-
// Echoed by the server rather than assumed, so an older deployment
|
|
140
|
-
// that ignores the field is reflected honestly instead of leaving
|
|
141
|
-
// the UI promising video it will not get.
|
|
142
|
-
media: toMedia(reply.media)
|
|
143
|
-
}));
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Answer a ringing call. This only tells the caller you picked up —
|
|
147
|
-
* join the voice room yourself to actually connect audio.
|
|
148
|
-
*/
|
|
149
|
-
async accept(call) {
|
|
150
|
-
await this.request("call:accept", {
|
|
151
|
-
call_id: call.callId,
|
|
152
|
-
conversation_id: call.conversationId,
|
|
153
|
-
caller_user_id: call.callerUserId
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
/** Reject a ringing call without joining the room. */
|
|
157
|
-
async decline(call) {
|
|
158
|
-
await this.request("call:decline", {
|
|
159
|
-
call_id: call.callId,
|
|
160
|
-
conversation_id: call.conversationId,
|
|
161
|
-
caller_user_id: call.callerUserId
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
/**
|
|
165
|
-
* Tell the caller you are already on another call.
|
|
166
|
-
*
|
|
167
|
-
* Distinct from {@link decline}: nobody chose anything, so clients
|
|
168
|
-
* send this automatically when a ring arrives mid-call. `useCalls`
|
|
169
|
-
* does it for you.
|
|
170
|
-
*/
|
|
171
|
-
async markBusy(call) {
|
|
172
|
-
await this.request("call:busy", {
|
|
173
|
-
call_id: call.callId,
|
|
174
|
-
conversation_id: call.conversationId,
|
|
175
|
-
caller_user_id: call.callerUserId
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* End a call that is already connected.
|
|
180
|
-
*
|
|
181
|
-
* Distinct from {@link cancel}, which withdraws an unanswered invite.
|
|
182
|
-
* Without this a connected call has no end signal, so hanging up
|
|
183
|
-
* leaves the other side sitting in the room with a call screen it has
|
|
184
|
-
* no reason to close.
|
|
185
|
-
*/
|
|
186
|
-
async hangUp(call) {
|
|
187
|
-
await this.request("call:hangup", {
|
|
188
|
-
call_id: call.callId,
|
|
189
|
-
conversation_id: call.conversationId
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
/** Withdraw an invite you placed — hung up before anyone answered. */
|
|
193
|
-
async cancel(call) {
|
|
194
|
-
await this.request("call:cancel", {
|
|
195
|
-
call_id: call.callId,
|
|
196
|
-
conversation_id: call.conversationId
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
// ── subscriptions ──────────────────────────────────────────────────
|
|
200
|
-
/** Somebody is ringing you. */
|
|
201
|
-
onIncoming(fn) {
|
|
202
|
-
this.bind();
|
|
203
|
-
this.incoming.add(fn);
|
|
204
|
-
return () => this.incoming.delete(fn);
|
|
205
|
-
}
|
|
206
|
-
/** Your outbound call was answered — join the room now. */
|
|
207
|
-
onAccepted(fn) {
|
|
208
|
-
this.bind();
|
|
209
|
-
this.accepted.add(fn);
|
|
210
|
-
return () => this.accepted.delete(fn);
|
|
211
|
-
}
|
|
212
|
-
/** Your outbound call was rejected. */
|
|
213
|
-
onDeclined(fn) {
|
|
214
|
-
this.bind();
|
|
215
|
-
this.declined.add(fn);
|
|
216
|
-
return () => this.declined.delete(fn);
|
|
217
|
-
}
|
|
218
|
-
/** The person you called is already on another call. */
|
|
219
|
-
onBusy(fn) {
|
|
220
|
-
this.bind();
|
|
221
|
-
this.busy.add(fn);
|
|
222
|
-
return () => this.busy.delete(fn);
|
|
223
|
-
}
|
|
224
|
-
/** The other side ended a connected call. */
|
|
225
|
-
onEnded(fn) {
|
|
226
|
-
this.bind();
|
|
227
|
-
this.ended.add(fn);
|
|
228
|
-
return () => this.ended.delete(fn);
|
|
229
|
-
}
|
|
230
|
-
/** An inbound ring was withdrawn before you answered. */
|
|
231
|
-
onCancelled(fn) {
|
|
232
|
-
this.bind();
|
|
233
|
-
this.cancelled.add(fn);
|
|
234
|
-
return () => this.cancelled.delete(fn);
|
|
235
|
-
}
|
|
236
|
-
// ── internals ──────────────────────────────────────────────────────
|
|
237
|
-
/**
|
|
238
|
-
* One Phoenix binding per event regardless of listener count; we fan
|
|
239
|
-
* out ourselves, matching how the conversation channels do it.
|
|
240
|
-
*/
|
|
241
|
-
bind() {
|
|
242
|
-
if (this.bound) return;
|
|
243
|
-
this.bound = true;
|
|
244
|
-
const channel = this.getChannel();
|
|
245
|
-
channel.on("call:incoming", (p) => {
|
|
246
|
-
const call = {
|
|
247
|
-
callId: p.call_id,
|
|
248
|
-
conversationId: p.conversation_id,
|
|
249
|
-
callerUserId: p.caller_user_id,
|
|
250
|
-
media: toMedia(p.media)
|
|
251
|
-
};
|
|
252
|
-
this.incoming.forEach((l) => l(call));
|
|
253
|
-
});
|
|
254
|
-
channel.on("call:accepted", (p) => {
|
|
255
|
-
const call = {
|
|
256
|
-
callId: p.call_id,
|
|
257
|
-
conversationId: p.conversation_id,
|
|
258
|
-
userId: p.user_id
|
|
259
|
-
};
|
|
260
|
-
this.accepted.forEach((l) => l(call));
|
|
261
|
-
});
|
|
262
|
-
channel.on("call:declined", (p) => {
|
|
263
|
-
const call = {
|
|
264
|
-
callId: p.call_id,
|
|
265
|
-
conversationId: p.conversation_id,
|
|
266
|
-
userId: p.user_id
|
|
267
|
-
};
|
|
268
|
-
this.declined.forEach((l) => l(call));
|
|
269
|
-
});
|
|
270
|
-
channel.on("call:busy", (p) => {
|
|
271
|
-
const call = {
|
|
272
|
-
callId: p.call_id,
|
|
273
|
-
conversationId: p.conversation_id,
|
|
274
|
-
userId: p.user_id
|
|
275
|
-
};
|
|
276
|
-
this.busy.forEach((l) => l(call));
|
|
277
|
-
});
|
|
278
|
-
channel.on("call:ended", (p) => {
|
|
279
|
-
const call = {
|
|
280
|
-
callId: p.call_id,
|
|
281
|
-
conversationId: p.conversation_id,
|
|
282
|
-
userId: p.user_id
|
|
283
|
-
};
|
|
284
|
-
this.ended.forEach((l) => l(call));
|
|
285
|
-
});
|
|
286
|
-
channel.on("call:cancelled", (p) => {
|
|
287
|
-
const call = {
|
|
288
|
-
callId: p.call_id,
|
|
289
|
-
conversationId: p.conversation_id,
|
|
290
|
-
callerUserId: p.caller_user_id
|
|
291
|
-
};
|
|
292
|
-
this.cancelled.forEach((l) => l(call));
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
request(event, payload) {
|
|
296
|
-
return new Promise((resolve, reject) => {
|
|
297
|
-
this.getChannel().push(event, payload).receive("ok", (reply) => resolve(reply)).receive(
|
|
298
|
-
"error",
|
|
299
|
-
(reply) => reject(new PoolseError(`${event} rejected: ${reply?.reason ?? "unknown"}`))
|
|
300
|
-
).receive("timeout", () => reject(new PoolseError(`${event} timed out`)));
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
};
|
|
304
|
-
|
|
305
|
-
// src/voice/webrtc-browser.ts
|
|
306
|
-
function isWebRtcAvailable() {
|
|
307
|
-
return typeof globalThis !== "undefined" && typeof globalThis.RTCPeerConnection === "function";
|
|
308
|
-
}
|
|
309
|
-
function createBrowserWebRtcAdapter() {
|
|
310
|
-
return {
|
|
311
|
-
createPeerConnection(iceServers) {
|
|
312
|
-
return new RTCPeerConnection({
|
|
313
|
-
iceServers
|
|
314
|
-
});
|
|
315
|
-
},
|
|
316
|
-
async getUserMedia() {
|
|
317
|
-
const stream = await navigator.mediaDevices.getUserMedia({
|
|
318
|
-
audio: { echoCancellation: true, noiseSuppression: true }
|
|
319
|
-
});
|
|
320
|
-
return stream;
|
|
321
|
-
},
|
|
322
|
-
playRemoteStream(_peerId, stream) {
|
|
323
|
-
const el = document.createElement("audio");
|
|
324
|
-
el.autoplay = true;
|
|
325
|
-
el.style.display = "none";
|
|
326
|
-
el.srcObject = stream;
|
|
327
|
-
document.body.appendChild(el);
|
|
328
|
-
void el.play().catch(() => {
|
|
329
|
-
});
|
|
330
|
-
return () => {
|
|
331
|
-
el.srcObject = null;
|
|
332
|
-
el.remove();
|
|
333
|
-
};
|
|
334
|
-
}
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
// src/voice/voice-room.ts
|
|
339
|
-
var DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }];
|
|
340
|
-
var SPEAKING_THRESHOLD = 0.02;
|
|
341
|
-
var SPEAKING_RELEASE_MS = 350;
|
|
342
|
-
var SPEAKING_POLL_MS = 100;
|
|
343
|
-
var VoiceRoom = class {
|
|
344
|
-
conversationId;
|
|
345
|
-
socket;
|
|
346
|
-
webrtc;
|
|
347
|
-
iceServers;
|
|
348
|
-
iceServersProvider;
|
|
349
|
-
detectSpeaking;
|
|
350
|
-
channel = null;
|
|
351
|
-
localStream = null;
|
|
352
|
-
selfId = null;
|
|
353
|
-
status = "idle";
|
|
354
|
-
muted = false;
|
|
355
|
-
peers = /* @__PURE__ */ new Map();
|
|
356
|
-
sinks = /* @__PURE__ */ new Map();
|
|
357
|
-
/** Candidates that landed before their offer/answer did. */
|
|
358
|
-
pendingIce = /* @__PURE__ */ new Map();
|
|
359
|
-
roster = /* @__PURE__ */ new Map();
|
|
360
|
-
/**
|
|
361
|
-
* How many callers currently hold this room open.
|
|
362
|
-
*
|
|
363
|
-
* `PoolseRealtime` hands out ONE room per conversation, so a call
|
|
364
|
-
* screen and an always-on voice bar for the same conversation share
|
|
365
|
-
* this instance — which is correct, since a user is in one audio
|
|
366
|
-
* session, not two. Without counting, whichever of them tore down
|
|
367
|
-
* first would cut the audio out from under the other.
|
|
368
|
-
*/
|
|
369
|
-
holders = 0;
|
|
370
|
-
speakingTimer = null;
|
|
371
|
-
stopSpeakingDetection = null;
|
|
372
|
-
statusListeners = /* @__PURE__ */ new Set();
|
|
373
|
-
rosterListeners = /* @__PURE__ */ new Set();
|
|
374
|
-
errorListeners = /* @__PURE__ */ new Set();
|
|
375
|
-
constructor(conversationId, socket, opts = {}) {
|
|
376
|
-
this.conversationId = conversationId;
|
|
377
|
-
this.socket = socket;
|
|
378
|
-
this.webrtc = opts.webrtc ?? createBrowserWebRtcAdapter();
|
|
379
|
-
this.iceServers = opts.iceServers ?? DEFAULT_ICE_SERVERS;
|
|
380
|
-
this.iceServersProvider = opts.iceServersProvider ?? null;
|
|
381
|
-
this.detectSpeaking = opts.detectSpeaking ?? true;
|
|
382
|
-
}
|
|
383
|
-
// ── observation ────────────────────────────────────────────────────
|
|
384
|
-
getStatus() {
|
|
385
|
-
return this.status;
|
|
386
|
-
}
|
|
387
|
-
isMuted() {
|
|
388
|
-
return this.muted;
|
|
389
|
-
}
|
|
390
|
-
/** Everyone in the room, oldest join first. */
|
|
391
|
-
getParticipants() {
|
|
392
|
-
return [...this.roster.values()].map((p) => ({ ...p, isSelf: p.userId === this.selfId })).sort((a, b) => a.joinedAt - b.joinedAt || a.userId.localeCompare(b.userId));
|
|
393
|
-
}
|
|
394
|
-
onStatus(fn) {
|
|
395
|
-
this.statusListeners.add(fn);
|
|
396
|
-
return () => this.statusListeners.delete(fn);
|
|
397
|
-
}
|
|
398
|
-
onParticipants(fn) {
|
|
399
|
-
this.rosterListeners.add(fn);
|
|
400
|
-
return () => this.rosterListeners.delete(fn);
|
|
401
|
-
}
|
|
402
|
-
onError(fn) {
|
|
403
|
-
this.errorListeners.add(fn);
|
|
404
|
-
return () => this.errorListeners.delete(fn);
|
|
405
|
-
}
|
|
406
|
-
// ── lifecycle ──────────────────────────────────────────────────────
|
|
407
|
-
/** Acquire the mic, join the channel, and start negotiating. */
|
|
408
|
-
async join() {
|
|
409
|
-
if (this.channel) {
|
|
410
|
-
this.holders += 1;
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
this.holders += 1;
|
|
414
|
-
this.setStatus("connecting");
|
|
415
|
-
await this.resolveIceServers();
|
|
416
|
-
try {
|
|
417
|
-
this.localStream = await this.webrtc.getUserMedia();
|
|
418
|
-
} catch (err) {
|
|
419
|
-
this.holders = Math.max(0, this.holders - 1);
|
|
420
|
-
this.setStatus("error");
|
|
421
|
-
this.emitError(new Error(`microphone unavailable: ${String(err)}`));
|
|
422
|
-
throw err;
|
|
423
|
-
}
|
|
424
|
-
const channel = this.socket.channel(`voice:conversation:${this.conversationId}`, {});
|
|
425
|
-
this.channel = channel;
|
|
426
|
-
this.bindChannel(channel);
|
|
427
|
-
await new Promise((resolve, reject) => {
|
|
428
|
-
channel.join().receive("ok", () => {
|
|
429
|
-
channel.push("voice:join", { muted: false, speaking: false });
|
|
430
|
-
resolve();
|
|
431
|
-
}).receive("error", (reply) => {
|
|
432
|
-
const err = new Error(`voice join rejected: ${reply?.reason ?? "unknown"}`);
|
|
433
|
-
this.setStatus("error");
|
|
434
|
-
this.emitError(err);
|
|
435
|
-
this.teardown();
|
|
436
|
-
reject(err);
|
|
437
|
-
}).receive("timeout", () => {
|
|
438
|
-
const err = new Error("voice join timed out");
|
|
439
|
-
this.setStatus("error");
|
|
440
|
-
this.emitError(err);
|
|
441
|
-
this.teardown();
|
|
442
|
-
reject(err);
|
|
443
|
-
});
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
/** Announce departure, then drop every peer connection and the mic. */
|
|
447
|
-
leave() {
|
|
448
|
-
if (this.holders > 0) this.holders -= 1;
|
|
449
|
-
if (this.holders > 0) return;
|
|
450
|
-
this.channel?.push("voice:leave", {});
|
|
451
|
-
this.teardown();
|
|
452
|
-
this.setStatus("idle");
|
|
453
|
-
}
|
|
454
|
-
/** Mute or unmute the local mic. Returns the new muted state. */
|
|
455
|
-
setMuted(muted) {
|
|
456
|
-
this.muted = muted;
|
|
457
|
-
for (const track of this.localStream?.getAudioTracks() ?? []) {
|
|
458
|
-
track.enabled = !muted;
|
|
459
|
-
}
|
|
460
|
-
this.channel?.push(muted ? "voice:mute" : "voice:unmute", { muted });
|
|
461
|
-
if (this.selfId) {
|
|
462
|
-
const self = this.roster.get(this.selfId);
|
|
463
|
-
if (self) this.roster.set(this.selfId, { ...self, muted, speaking: false });
|
|
464
|
-
this.emitRoster();
|
|
465
|
-
}
|
|
466
|
-
return this.muted;
|
|
467
|
-
}
|
|
468
|
-
toggleMute() {
|
|
469
|
-
return this.setMuted(!this.muted);
|
|
470
|
-
}
|
|
471
|
-
// ── channel wiring ─────────────────────────────────────────────────
|
|
472
|
-
bindChannel(channel) {
|
|
473
|
-
channel.on("voice:presence_state", (state) => {
|
|
474
|
-
this.roster.clear();
|
|
475
|
-
for (const [userId, entry] of Object.entries(state ?? {})) {
|
|
476
|
-
const meta = entry?.metas?.[0] ?? {};
|
|
477
|
-
this.roster.set(userId, {
|
|
478
|
-
userId,
|
|
479
|
-
muted: meta.mute_state ?? false,
|
|
480
|
-
speaking: meta.speaking_state ?? false,
|
|
481
|
-
joinedAt: meta.joined_at ?? 0
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
this.emitRoster();
|
|
485
|
-
for (const userId of this.roster.keys()) {
|
|
486
|
-
if (userId !== this.selfId) this.startNegotiation(userId);
|
|
487
|
-
}
|
|
488
|
-
});
|
|
489
|
-
channel.on("voice:joined", (payload) => {
|
|
490
|
-
const userId = payload?.user_id;
|
|
491
|
-
if (!userId) return;
|
|
492
|
-
if (!this.selfId) {
|
|
493
|
-
this.selfId = userId;
|
|
494
|
-
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
495
|
-
this.setStatus("connected");
|
|
496
|
-
if (this.detectSpeaking && this.localStream) {
|
|
497
|
-
this.startSpeakingDetection(this.localStream);
|
|
498
|
-
}
|
|
499
|
-
this.emitRoster();
|
|
500
|
-
return;
|
|
501
|
-
}
|
|
502
|
-
if (userId === this.selfId) return;
|
|
503
|
-
if (!this.roster.has(userId)) {
|
|
504
|
-
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
505
|
-
this.emitRoster();
|
|
506
|
-
}
|
|
507
|
-
this.startNegotiation(userId);
|
|
508
|
-
});
|
|
509
|
-
channel.on("voice:left", (payload) => {
|
|
510
|
-
const userId = payload?.user_id;
|
|
511
|
-
if (!userId) return;
|
|
512
|
-
this.closePeer(userId);
|
|
513
|
-
this.roster.delete(userId);
|
|
514
|
-
this.emitRoster();
|
|
515
|
-
});
|
|
516
|
-
channel.on("voice:mute", (payload) => {
|
|
517
|
-
this.patchParticipant(payload?.user_id, { muted: payload?.muted ?? false });
|
|
518
|
-
});
|
|
519
|
-
channel.on("voice:active_speaker", (payload) => {
|
|
520
|
-
this.patchParticipant(payload?.user_id, { speaking: payload?.speaking ?? false });
|
|
521
|
-
});
|
|
522
|
-
channel.on("voice:signal", (payload) => {
|
|
523
|
-
void this.handleSignal(payload);
|
|
524
|
-
});
|
|
525
|
-
channel.on("voice:error", (payload) => {
|
|
526
|
-
this.emitError(new Error(`voice error: ${payload?.reason ?? "unknown"}`));
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
/**
|
|
530
|
-
* Refresh ICE servers from the provider, if there is one.
|
|
531
|
-
*
|
|
532
|
-
* Never throws. A room that refused to connect because the ICE
|
|
533
|
-
* endpoint was briefly unreachable would be a worse outcome than one
|
|
534
|
-
* that connects without TURN — which is exactly how calls behaved
|
|
535
|
-
* before TURN existed, and works on most networks.
|
|
536
|
-
*/
|
|
537
|
-
async resolveIceServers() {
|
|
538
|
-
if (!this.iceServersProvider) return;
|
|
539
|
-
try {
|
|
540
|
-
const servers = await this.iceServersProvider();
|
|
541
|
-
if (servers.length > 0) this.iceServers = servers;
|
|
542
|
-
} catch (err) {
|
|
543
|
-
this.emitError(new Error(`ice servers unavailable, continuing without: ${String(err)}`));
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
// ── negotiation ────────────────────────────────────────────────────
|
|
547
|
-
/**
|
|
548
|
-
* Glare control: both sides learn about each other simultaneously, so
|
|
549
|
-
* without a rule both would offer at once. The lexicographically lower
|
|
550
|
-
* user id offers and the higher answers — deterministic, no extra
|
|
551
|
-
* round trip.
|
|
552
|
-
*/
|
|
553
|
-
shouldOffer(peerId) {
|
|
554
|
-
return this.selfId != null && this.selfId < peerId;
|
|
555
|
-
}
|
|
556
|
-
startNegotiation(peerId) {
|
|
557
|
-
const pc = this.ensurePeer(peerId);
|
|
558
|
-
if (!this.shouldOffer(peerId)) return;
|
|
559
|
-
void (async () => {
|
|
560
|
-
try {
|
|
561
|
-
const offer = await pc.createOffer();
|
|
562
|
-
await pc.setLocalDescription(offer);
|
|
563
|
-
this.sendSignal("offer", peerId, { sdp: offer.sdp });
|
|
564
|
-
} catch (err) {
|
|
565
|
-
this.emitError(new Error(`offer to ${peerId} failed: ${String(err)}`));
|
|
566
|
-
}
|
|
567
|
-
})();
|
|
568
|
-
}
|
|
569
|
-
ensurePeer(peerId) {
|
|
570
|
-
const existing = this.peers.get(peerId);
|
|
571
|
-
if (existing) return existing;
|
|
572
|
-
const pc = this.webrtc.createPeerConnection(this.iceServers);
|
|
573
|
-
if (this.localStream) {
|
|
574
|
-
for (const track of this.localStream.getTracks()) {
|
|
575
|
-
pc.addTrack(track, this.localStream);
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
pc.onicecandidate = (event) => {
|
|
579
|
-
if (!event.candidate) return;
|
|
580
|
-
this.sendSignal("ice-candidate", peerId, event.candidate);
|
|
581
|
-
};
|
|
582
|
-
pc.ontrack = (event) => {
|
|
583
|
-
const stream = event.streams[0];
|
|
584
|
-
if (!stream) return;
|
|
585
|
-
this.sinks.get(peerId)?.();
|
|
586
|
-
this.sinks.set(peerId, this.webrtc.playRemoteStream(peerId, stream));
|
|
587
|
-
};
|
|
588
|
-
this.peers.set(peerId, pc);
|
|
589
|
-
return pc;
|
|
590
|
-
}
|
|
591
|
-
async handleSignal(payload) {
|
|
592
|
-
const from = payload["from_user_id"];
|
|
593
|
-
const type = payload["type"];
|
|
594
|
-
if (!from || !type || from === this.selfId) return;
|
|
595
|
-
const target = payload["target_user_id"];
|
|
596
|
-
if (target && target !== this.selfId) return;
|
|
597
|
-
const data = payload["data"] ?? {};
|
|
598
|
-
const pc = this.ensurePeer(from);
|
|
599
|
-
try {
|
|
600
|
-
if (type === "offer") {
|
|
601
|
-
await pc.setRemoteDescription({ type: "offer", sdp: data["sdp"] });
|
|
602
|
-
await this.flushIce(pc, from);
|
|
603
|
-
const answer = await pc.createAnswer();
|
|
604
|
-
await pc.setLocalDescription(answer);
|
|
605
|
-
this.sendSignal("answer", from, { sdp: answer.sdp });
|
|
606
|
-
} else if (type === "answer") {
|
|
607
|
-
await pc.setRemoteDescription({ type: "answer", sdp: data["sdp"] });
|
|
608
|
-
await this.flushIce(pc, from);
|
|
609
|
-
} else if (type === "ice-candidate") {
|
|
610
|
-
const candidate = data;
|
|
611
|
-
if (!pc.remoteDescription) {
|
|
612
|
-
const queued = this.pendingIce.get(from) ?? [];
|
|
613
|
-
queued.push(candidate);
|
|
614
|
-
this.pendingIce.set(from, queued);
|
|
615
|
-
} else {
|
|
616
|
-
await pc.addIceCandidate(candidate);
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
} catch (err) {
|
|
620
|
-
this.emitError(new Error(`signal (${type}) from ${from} failed: ${String(err)}`));
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
async flushIce(pc, peerId) {
|
|
624
|
-
const queued = this.pendingIce.get(peerId);
|
|
625
|
-
if (!queued?.length) return;
|
|
626
|
-
this.pendingIce.delete(peerId);
|
|
627
|
-
for (const candidate of queued) {
|
|
628
|
-
try {
|
|
629
|
-
await pc.addIceCandidate(candidate);
|
|
630
|
-
} catch {
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
/**
|
|
635
|
-
* Every signal body travels under `data` — the server's
|
|
636
|
-
* `validate_signal_data/1` rejects the push outright when that key is
|
|
637
|
-
* missing or empty, and a rejected signal is never relayed.
|
|
638
|
-
*/
|
|
639
|
-
sendSignal(type, targetUserId, data) {
|
|
640
|
-
this.channel?.push("voice:signal", { type, target_user_id: targetUserId, data });
|
|
641
|
-
}
|
|
642
|
-
// ── speaking detection ─────────────────────────────────────────────
|
|
643
|
-
startSpeakingDetection(stream) {
|
|
644
|
-
const Ctor = globalThis.AudioContext;
|
|
645
|
-
if (!Ctor) return;
|
|
646
|
-
const ctx = new Ctor();
|
|
647
|
-
const source = ctx.createMediaStreamSource(stream);
|
|
648
|
-
const analyser = ctx.createAnalyser();
|
|
649
|
-
analyser.fftSize = 512;
|
|
650
|
-
source.connect(analyser);
|
|
651
|
-
const buf = new Float32Array(analyser.fftSize);
|
|
652
|
-
let speaking = false;
|
|
653
|
-
let lastLoud = 0;
|
|
654
|
-
this.speakingTimer = setInterval(() => {
|
|
655
|
-
analyser.getFloatTimeDomainData(buf);
|
|
656
|
-
let sum = 0;
|
|
657
|
-
for (const v of buf) sum += v * v;
|
|
658
|
-
const rms = Math.sqrt(sum / buf.length);
|
|
659
|
-
const now = Date.now();
|
|
660
|
-
if (!this.muted && rms > SPEAKING_THRESHOLD) lastLoud = now;
|
|
661
|
-
const next = !this.muted && now - lastLoud < SPEAKING_RELEASE_MS;
|
|
662
|
-
if (next === speaking) return;
|
|
663
|
-
speaking = next;
|
|
664
|
-
this.channel?.push("voice:active_speaker", { speaking });
|
|
665
|
-
this.patchParticipant(this.selfId ?? void 0, { speaking });
|
|
666
|
-
}, SPEAKING_POLL_MS);
|
|
667
|
-
this.stopSpeakingDetection = () => {
|
|
668
|
-
void ctx.close().catch(() => {
|
|
669
|
-
});
|
|
670
|
-
};
|
|
671
|
-
}
|
|
672
|
-
// ── teardown & emit ────────────────────────────────────────────────
|
|
673
|
-
closePeer(peerId) {
|
|
674
|
-
const pc = this.peers.get(peerId);
|
|
675
|
-
if (pc) {
|
|
676
|
-
pc.onicecandidate = null;
|
|
677
|
-
pc.ontrack = null;
|
|
678
|
-
pc.onconnectionstatechange = null;
|
|
679
|
-
pc.close();
|
|
680
|
-
this.peers.delete(peerId);
|
|
681
|
-
}
|
|
682
|
-
this.sinks.get(peerId)?.();
|
|
683
|
-
this.sinks.delete(peerId);
|
|
684
|
-
this.pendingIce.delete(peerId);
|
|
685
|
-
}
|
|
686
|
-
teardown() {
|
|
687
|
-
this.holders = 0;
|
|
688
|
-
for (const peerId of [...this.peers.keys()]) this.closePeer(peerId);
|
|
689
|
-
if (this.speakingTimer) clearInterval(this.speakingTimer);
|
|
690
|
-
this.speakingTimer = null;
|
|
691
|
-
this.stopSpeakingDetection?.();
|
|
692
|
-
this.stopSpeakingDetection = null;
|
|
693
|
-
for (const track of this.localStream?.getTracks() ?? []) track.stop();
|
|
694
|
-
this.localStream = null;
|
|
695
|
-
this.channel?.leave();
|
|
696
|
-
this.channel = null;
|
|
697
|
-
this.selfId = null;
|
|
698
|
-
this.muted = false;
|
|
699
|
-
this.roster.clear();
|
|
700
|
-
this.emitRoster();
|
|
701
|
-
}
|
|
702
|
-
patchParticipant(userId, patch) {
|
|
703
|
-
if (!userId) return;
|
|
704
|
-
const current = this.roster.get(userId);
|
|
705
|
-
if (!current) return;
|
|
706
|
-
this.roster.set(userId, { ...current, ...patch });
|
|
707
|
-
this.emitRoster();
|
|
708
|
-
}
|
|
709
|
-
setStatus(status) {
|
|
710
|
-
if (this.status === status) return;
|
|
711
|
-
this.status = status;
|
|
712
|
-
this.statusListeners.forEach((l) => l(status));
|
|
713
|
-
}
|
|
714
|
-
emitRoster() {
|
|
715
|
-
const snapshot = this.getParticipants();
|
|
716
|
-
this.rosterListeners.forEach((l) => l(snapshot));
|
|
717
|
-
}
|
|
718
|
-
emitError(err) {
|
|
719
|
-
this.errorListeners.forEach((l) => l(err));
|
|
720
|
-
}
|
|
721
|
-
};
|
|
722
|
-
|
|
723
108
|
// src/realtime/realtime.ts
|
|
724
109
|
var PoolseRealtime = class {
|
|
725
110
|
config;
|
|
726
111
|
tokenCache;
|
|
727
112
|
socketPath;
|
|
728
|
-
iceServersProvider;
|
|
729
113
|
wsUrl;
|
|
730
114
|
socket = null;
|
|
731
115
|
conversations = /* @__PURE__ */ new Map();
|
|
732
|
-
voiceRooms = /* @__PURE__ */ new Map();
|
|
733
116
|
userChannel = null;
|
|
734
|
-
callsResource = null;
|
|
735
117
|
status = "idle";
|
|
736
118
|
statusListeners = /* @__PURE__ */ new Set();
|
|
737
119
|
constructor(config, tokenCache, opts = {}) {
|
|
738
120
|
this.config = config;
|
|
739
121
|
this.tokenCache = tokenCache;
|
|
740
122
|
this.socketPath = opts.socketPath ?? "/socket";
|
|
741
|
-
this.iceServersProvider = opts.iceServersProvider ?? null;
|
|
742
123
|
this.wsUrl = opts.wsUrl ?? deriveWsUrl(config.apiUrl);
|
|
743
124
|
}
|
|
744
125
|
/** Current connection status. */
|
|
@@ -802,8 +183,6 @@ var PoolseRealtime = class {
|
|
|
802
183
|
}
|
|
803
184
|
/** Close the socket and tear down every joined channel. */
|
|
804
185
|
disconnect() {
|
|
805
|
-
for (const room of this.voiceRooms.values()) room.leave();
|
|
806
|
-
this.voiceRooms.clear();
|
|
807
186
|
this.setStatus("closed");
|
|
808
187
|
this.conversations.forEach((c) => c._destroy());
|
|
809
188
|
this.conversations.clear();
|
|
@@ -848,42 +227,6 @@ var PoolseRealtime = class {
|
|
|
848
227
|
handle._join();
|
|
849
228
|
return handle;
|
|
850
229
|
}
|
|
851
|
-
/**
|
|
852
|
-
* Voice room for a conversation — the Discord-style surface. Call
|
|
853
|
-
* `join()` on the returned handle to acquire the mic and connect;
|
|
854
|
-
* reusing the same id returns the same room rather than opening a
|
|
855
|
-
* second one.
|
|
856
|
-
*
|
|
857
|
-
* Ringing somebody who hasn't joined is a separate concern; see
|
|
858
|
-
* `poolse.calls`.
|
|
859
|
-
*/
|
|
860
|
-
voice(conversationId, opts = {}) {
|
|
861
|
-
const existing = this.voiceRooms.get(conversationId);
|
|
862
|
-
if (existing) return existing;
|
|
863
|
-
this.connect();
|
|
864
|
-
if (!this.socket) {
|
|
865
|
-
throw new PoolseError("socket not initialised \u2014 call connect() first");
|
|
866
|
-
}
|
|
867
|
-
const room = new VoiceRoom(conversationId, this.socket, {
|
|
868
|
-
...this.iceServersProvider ? { iceServersProvider: this.iceServersProvider } : {},
|
|
869
|
-
...opts
|
|
870
|
-
});
|
|
871
|
-
this.voiceRooms.set(conversationId, room);
|
|
872
|
-
return room;
|
|
873
|
-
}
|
|
874
|
-
/**
|
|
875
|
-
* Call invitations for a user — the WhatsApp-style surface. Rides the
|
|
876
|
-
* `user:<id>` topic, the one channel a client is always joined to, so
|
|
877
|
-
* a ring reaches somebody who hasn't opened a voice room yet.
|
|
878
|
-
*
|
|
879
|
-
* Takes the user id explicitly, mirroring `user(userId)`; the SDK
|
|
880
|
-
* never assumes whose token it is holding.
|
|
881
|
-
*/
|
|
882
|
-
calls(userId) {
|
|
883
|
-
if (this.callsResource) return this.callsResource;
|
|
884
|
-
this.callsResource = new CallsResource(() => this.user(userId)._channel());
|
|
885
|
-
return this.callsResource;
|
|
886
|
-
}
|
|
887
230
|
/** Drop a conversation handle and leave the channel. */
|
|
888
231
|
leave(conversationId) {
|
|
889
232
|
const handle = this.conversations.get(conversationId);
|
|
@@ -1036,8 +379,9 @@ var UserChannel = class {
|
|
|
1036
379
|
this.channel = channel;
|
|
1037
380
|
}
|
|
1038
381
|
/**
|
|
1039
|
-
* The underlying Phoenix channel, for
|
|
1040
|
-
*
|
|
382
|
+
* The underlying Phoenix channel, for hosts that listen to events the
|
|
383
|
+
* handle has no method for (a native call host forwards
|
|
384
|
+
* `call:ring_ended` / `call:finished` to its call core).
|
|
1041
385
|
*
|
|
1042
386
|
* @internal
|
|
1043
387
|
*/
|
|
@@ -1816,8 +1160,7 @@ var CallRoom = class {
|
|
|
1816
1160
|
* livekit-client does NOT play remote audio for you on the web — that
|
|
1817
1161
|
* is what `@livekit/components-react`'s `<RoomAudioRenderer />` exists
|
|
1818
1162
|
* to do. Without this a call connects, the roster is right, video
|
|
1819
|
-
* flows, and nobody hears anything.
|
|
1820
|
-
* this (see `webrtc-browser.ts`); the SFU path has to as well.
|
|
1163
|
+
* flows, and nobody hears anything.
|
|
1821
1164
|
*
|
|
1822
1165
|
* Empty on React Native, where there is no DOM and LiveKit routes
|
|
1823
1166
|
* audio through the native audio session instead.
|
|
@@ -2232,22 +1575,6 @@ var CallRoom = class {
|
|
|
2232
1575
|
}
|
|
2233
1576
|
};
|
|
2234
1577
|
|
|
2235
|
-
// src/resources/ice-servers.ts
|
|
2236
|
-
var IceServersResource = class {
|
|
2237
|
-
constructor(client) {
|
|
2238
|
-
this.client = client;
|
|
2239
|
-
}
|
|
2240
|
-
client;
|
|
2241
|
-
/** GET /v1/ice-servers */
|
|
2242
|
-
list(signal) {
|
|
2243
|
-
return this.client.request({
|
|
2244
|
-
method: "GET",
|
|
2245
|
-
path: "/v1/ice-servers",
|
|
2246
|
-
...signal ? { signal } : {}
|
|
2247
|
-
});
|
|
2248
|
-
}
|
|
2249
|
-
};
|
|
2250
|
-
|
|
2251
1578
|
// src/rest-client.ts
|
|
2252
1579
|
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET"]);
|
|
2253
1580
|
var RestClient = class {
|
|
@@ -2503,8 +1830,6 @@ var Poolse = class {
|
|
|
2503
1830
|
* `config.wsUrl`.
|
|
2504
1831
|
*/
|
|
2505
1832
|
realtime;
|
|
2506
|
-
/** STUN/TURN servers for WebRTC — see `IceServersResource`. */
|
|
2507
|
-
iceServers;
|
|
2508
1833
|
/** SFU credentials for a call's media — see `CallTokensResource`. */
|
|
2509
1834
|
callTokens;
|
|
2510
1835
|
/** Whether a call is running on a conversation — for a Join banner. */
|
|
@@ -2527,17 +1852,12 @@ var Poolse = class {
|
|
|
2527
1852
|
this.messages = new MessagesResource(this.rest);
|
|
2528
1853
|
this.attachments = new AttachmentsResource(this.rest, cachedConfig.fetch);
|
|
2529
1854
|
this.users = new UsersResource(cachedConfig);
|
|
2530
|
-
this.iceServers = new IceServersResource(this.rest);
|
|
2531
1855
|
this.callTokens = new CallTokensResource(this.rest);
|
|
2532
1856
|
this.liveCalls = new LiveCallsResource(this.rest);
|
|
2533
1857
|
this.rooms = new RoomsResource(this.rest);
|
|
2534
1858
|
this.realtime = new PoolseRealtime(cachedConfig, this.tokenCache, {
|
|
2535
1859
|
...this.resolved.wsUrl !== void 0 ? { wsUrl: this.resolved.wsUrl } : {},
|
|
2536
|
-
socketPath: this.resolved.socketPath
|
|
2537
|
-
// Re-fetched on every room join rather than cached here: TURN
|
|
2538
|
-
// credentials expire, and a stale one is rejected silently — the
|
|
2539
|
-
// call connects and carries no media.
|
|
2540
|
-
iceServersProvider: async () => (await this.iceServers.list()).ice_servers
|
|
1860
|
+
socketPath: this.resolved.socketPath
|
|
2541
1861
|
});
|
|
2542
1862
|
}
|
|
2543
1863
|
/**
|
|
@@ -2573,7 +1893,7 @@ var Poolse = class {
|
|
|
2573
1893
|
};
|
|
2574
1894
|
|
|
2575
1895
|
// src/version.ts
|
|
2576
|
-
var version = "
|
|
1896
|
+
var version = "3.0.0";
|
|
2577
1897
|
|
|
2578
1898
|
// src/call-log.ts
|
|
2579
1899
|
function parseCallLogBody(body) {
|
|
@@ -2744,13 +2064,11 @@ exports.AttachmentsResource = AttachmentsResource;
|
|
|
2744
2064
|
exports.AuthError = AuthError;
|
|
2745
2065
|
exports.CallRoom = CallRoom;
|
|
2746
2066
|
exports.CallTokensResource = CallTokensResource;
|
|
2747
|
-
exports.CallsResource = CallsResource;
|
|
2748
2067
|
exports.ConversationChannel = ConversationChannel;
|
|
2749
2068
|
exports.ConversationHandle = ConversationHandle;
|
|
2750
2069
|
exports.ConversationMessages = ConversationMessages;
|
|
2751
2070
|
exports.ConversationsResource = ConversationsResource;
|
|
2752
2071
|
exports.DevicesResource = DevicesResource;
|
|
2753
|
-
exports.IceServersResource = IceServersResource;
|
|
2754
2072
|
exports.LiveCallsResource = LiveCallsResource;
|
|
2755
2073
|
exports.MeResource = MeResource;
|
|
2756
2074
|
exports.MessageHandle = MessageHandle;
|
|
@@ -2764,15 +2082,12 @@ exports.RateLimitedError = RateLimitedError;
|
|
|
2764
2082
|
exports.RoomsResource = RoomsResource;
|
|
2765
2083
|
exports.UserChannel = UserChannel;
|
|
2766
2084
|
exports.UsersResource = UsersResource;
|
|
2767
|
-
exports.VoiceRoom = VoiceRoom;
|
|
2768
2085
|
exports.callLogDisplayFor = callLogDisplayFor;
|
|
2769
|
-
exports.createBrowserWebRtcAdapter = createBrowserWebRtcAdapter;
|
|
2770
2086
|
exports.describeCallLog = describeCallLog;
|
|
2771
2087
|
exports.formatCallDuration = formatCallDuration;
|
|
2772
2088
|
exports.formatCallLogPreview = formatCallLogPreview;
|
|
2773
2089
|
exports.isCallLogMessage = isCallLogMessage;
|
|
2774
2090
|
exports.isMessageVisibleTo = isMessageVisibleTo;
|
|
2775
|
-
exports.isWebRtcAvailable = isWebRtcAvailable;
|
|
2776
2091
|
exports.parseCallLog = parseCallLog;
|
|
2777
2092
|
exports.parseCallLogBody = parseCallLogBody;
|
|
2778
2093
|
exports.safeUuid = safeUuid;
|