@poolse/sdk 2.1.6 → 2.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/CHANGELOG.md +159 -159
- package/LICENSE +21 -21
- package/README.md +397 -397
- package/dist/index.cjs +590 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +337 -3
- package/dist/index.d.ts +337 -3
- package/dist/index.js +587 -2
- package/dist/index.js.map +1 -1
- package/package.json +10 -10
package/dist/index.js
CHANGED
|
@@ -103,6 +103,545 @@ var AuthError = class extends ApiError {
|
|
|
103
103
|
}
|
|
104
104
|
};
|
|
105
105
|
|
|
106
|
+
// src/voice/calls.ts
|
|
107
|
+
var CallsResource = class {
|
|
108
|
+
/** Resolves the user channel lazily — it may not be joined yet. */
|
|
109
|
+
getChannel;
|
|
110
|
+
incoming = /* @__PURE__ */ new Set();
|
|
111
|
+
accepted = /* @__PURE__ */ new Set();
|
|
112
|
+
declined = /* @__PURE__ */ new Set();
|
|
113
|
+
busy = /* @__PURE__ */ new Set();
|
|
114
|
+
cancelled = /* @__PURE__ */ new Set();
|
|
115
|
+
bound = false;
|
|
116
|
+
constructor(getChannel) {
|
|
117
|
+
this.getChannel = getChannel;
|
|
118
|
+
}
|
|
119
|
+
// ── placing and answering ──────────────────────────────────────────
|
|
120
|
+
/**
|
|
121
|
+
* Ring every other member of a conversation. Resolves once the server
|
|
122
|
+
* has fanned the invite out, with the minted call id and who was rung
|
|
123
|
+
* — not when anyone answers; that arrives via {@link onAccepted}.
|
|
124
|
+
*/
|
|
125
|
+
invite(conversationId) {
|
|
126
|
+
return this.request("call:invite", {
|
|
127
|
+
conversation_id: conversationId
|
|
128
|
+
}).then((reply) => ({
|
|
129
|
+
callId: reply.call_id,
|
|
130
|
+
conversationId: reply.conversation_id,
|
|
131
|
+
calleeUserIds: reply.callee_user_ids ?? []
|
|
132
|
+
}));
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Answer a ringing call. This only tells the caller you picked up —
|
|
136
|
+
* join the voice room yourself to actually connect audio.
|
|
137
|
+
*/
|
|
138
|
+
async accept(call) {
|
|
139
|
+
await this.request("call:accept", {
|
|
140
|
+
call_id: call.callId,
|
|
141
|
+
conversation_id: call.conversationId,
|
|
142
|
+
caller_user_id: call.callerUserId
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
/** Reject a ringing call without joining the room. */
|
|
146
|
+
async decline(call) {
|
|
147
|
+
await this.request("call:decline", {
|
|
148
|
+
call_id: call.callId,
|
|
149
|
+
conversation_id: call.conversationId,
|
|
150
|
+
caller_user_id: call.callerUserId
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Tell the caller you are already on another call.
|
|
155
|
+
*
|
|
156
|
+
* Distinct from {@link decline}: nobody chose anything, so clients
|
|
157
|
+
* send this automatically when a ring arrives mid-call. `useCalls`
|
|
158
|
+
* does it for you.
|
|
159
|
+
*/
|
|
160
|
+
async markBusy(call) {
|
|
161
|
+
await this.request("call:busy", {
|
|
162
|
+
call_id: call.callId,
|
|
163
|
+
conversation_id: call.conversationId,
|
|
164
|
+
caller_user_id: call.callerUserId
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/** Withdraw an invite you placed — hung up before anyone answered. */
|
|
168
|
+
async cancel(call) {
|
|
169
|
+
await this.request("call:cancel", {
|
|
170
|
+
call_id: call.callId,
|
|
171
|
+
conversation_id: call.conversationId
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
// ── subscriptions ──────────────────────────────────────────────────
|
|
175
|
+
/** Somebody is ringing you. */
|
|
176
|
+
onIncoming(fn) {
|
|
177
|
+
this.bind();
|
|
178
|
+
this.incoming.add(fn);
|
|
179
|
+
return () => this.incoming.delete(fn);
|
|
180
|
+
}
|
|
181
|
+
/** Your outbound call was answered — join the room now. */
|
|
182
|
+
onAccepted(fn) {
|
|
183
|
+
this.bind();
|
|
184
|
+
this.accepted.add(fn);
|
|
185
|
+
return () => this.accepted.delete(fn);
|
|
186
|
+
}
|
|
187
|
+
/** Your outbound call was rejected. */
|
|
188
|
+
onDeclined(fn) {
|
|
189
|
+
this.bind();
|
|
190
|
+
this.declined.add(fn);
|
|
191
|
+
return () => this.declined.delete(fn);
|
|
192
|
+
}
|
|
193
|
+
/** The person you called is already on another call. */
|
|
194
|
+
onBusy(fn) {
|
|
195
|
+
this.bind();
|
|
196
|
+
this.busy.add(fn);
|
|
197
|
+
return () => this.busy.delete(fn);
|
|
198
|
+
}
|
|
199
|
+
/** An inbound ring was withdrawn before you answered. */
|
|
200
|
+
onCancelled(fn) {
|
|
201
|
+
this.bind();
|
|
202
|
+
this.cancelled.add(fn);
|
|
203
|
+
return () => this.cancelled.delete(fn);
|
|
204
|
+
}
|
|
205
|
+
// ── internals ──────────────────────────────────────────────────────
|
|
206
|
+
/**
|
|
207
|
+
* One Phoenix binding per event regardless of listener count; we fan
|
|
208
|
+
* out ourselves, matching how the conversation channels do it.
|
|
209
|
+
*/
|
|
210
|
+
bind() {
|
|
211
|
+
if (this.bound) return;
|
|
212
|
+
this.bound = true;
|
|
213
|
+
const channel = this.getChannel();
|
|
214
|
+
channel.on("call:incoming", (p) => {
|
|
215
|
+
const call = {
|
|
216
|
+
callId: p.call_id,
|
|
217
|
+
conversationId: p.conversation_id,
|
|
218
|
+
callerUserId: p.caller_user_id
|
|
219
|
+
};
|
|
220
|
+
this.incoming.forEach((l) => l(call));
|
|
221
|
+
});
|
|
222
|
+
channel.on("call:accepted", (p) => {
|
|
223
|
+
const call = {
|
|
224
|
+
callId: p.call_id,
|
|
225
|
+
conversationId: p.conversation_id,
|
|
226
|
+
userId: p.user_id
|
|
227
|
+
};
|
|
228
|
+
this.accepted.forEach((l) => l(call));
|
|
229
|
+
});
|
|
230
|
+
channel.on("call:declined", (p) => {
|
|
231
|
+
const call = {
|
|
232
|
+
callId: p.call_id,
|
|
233
|
+
conversationId: p.conversation_id,
|
|
234
|
+
userId: p.user_id
|
|
235
|
+
};
|
|
236
|
+
this.declined.forEach((l) => l(call));
|
|
237
|
+
});
|
|
238
|
+
channel.on("call:busy", (p) => {
|
|
239
|
+
const call = {
|
|
240
|
+
callId: p.call_id,
|
|
241
|
+
conversationId: p.conversation_id,
|
|
242
|
+
userId: p.user_id
|
|
243
|
+
};
|
|
244
|
+
this.busy.forEach((l) => l(call));
|
|
245
|
+
});
|
|
246
|
+
channel.on("call:cancelled", (p) => {
|
|
247
|
+
const call = {
|
|
248
|
+
callId: p.call_id,
|
|
249
|
+
conversationId: p.conversation_id,
|
|
250
|
+
callerUserId: p.caller_user_id
|
|
251
|
+
};
|
|
252
|
+
this.cancelled.forEach((l) => l(call));
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
request(event, payload) {
|
|
256
|
+
return new Promise((resolve, reject) => {
|
|
257
|
+
this.getChannel().push(event, payload).receive("ok", (reply) => resolve(reply)).receive(
|
|
258
|
+
"error",
|
|
259
|
+
(reply) => reject(new PoolseError(`${event} rejected: ${reply?.reason ?? "unknown"}`))
|
|
260
|
+
).receive("timeout", () => reject(new PoolseError(`${event} timed out`)));
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// src/voice/webrtc-browser.ts
|
|
266
|
+
function isWebRtcAvailable() {
|
|
267
|
+
return typeof globalThis !== "undefined" && typeof globalThis.RTCPeerConnection === "function";
|
|
268
|
+
}
|
|
269
|
+
function createBrowserWebRtcAdapter() {
|
|
270
|
+
return {
|
|
271
|
+
createPeerConnection(iceServers) {
|
|
272
|
+
return new RTCPeerConnection({
|
|
273
|
+
iceServers
|
|
274
|
+
});
|
|
275
|
+
},
|
|
276
|
+
async getUserMedia() {
|
|
277
|
+
const stream = await navigator.mediaDevices.getUserMedia({
|
|
278
|
+
audio: { echoCancellation: true, noiseSuppression: true }
|
|
279
|
+
});
|
|
280
|
+
return stream;
|
|
281
|
+
},
|
|
282
|
+
playRemoteStream(_peerId, stream) {
|
|
283
|
+
const el = document.createElement("audio");
|
|
284
|
+
el.autoplay = true;
|
|
285
|
+
el.style.display = "none";
|
|
286
|
+
el.srcObject = stream;
|
|
287
|
+
document.body.appendChild(el);
|
|
288
|
+
void el.play().catch(() => {
|
|
289
|
+
});
|
|
290
|
+
return () => {
|
|
291
|
+
el.srcObject = null;
|
|
292
|
+
el.remove();
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/voice/voice-room.ts
|
|
299
|
+
var DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }];
|
|
300
|
+
var SPEAKING_THRESHOLD = 0.02;
|
|
301
|
+
var SPEAKING_RELEASE_MS = 350;
|
|
302
|
+
var SPEAKING_POLL_MS = 100;
|
|
303
|
+
var VoiceRoom = class {
|
|
304
|
+
conversationId;
|
|
305
|
+
socket;
|
|
306
|
+
webrtc;
|
|
307
|
+
iceServers;
|
|
308
|
+
detectSpeaking;
|
|
309
|
+
channel = null;
|
|
310
|
+
localStream = null;
|
|
311
|
+
selfId = null;
|
|
312
|
+
status = "idle";
|
|
313
|
+
muted = false;
|
|
314
|
+
peers = /* @__PURE__ */ new Map();
|
|
315
|
+
sinks = /* @__PURE__ */ new Map();
|
|
316
|
+
/** Candidates that landed before their offer/answer did. */
|
|
317
|
+
pendingIce = /* @__PURE__ */ new Map();
|
|
318
|
+
roster = /* @__PURE__ */ new Map();
|
|
319
|
+
speakingTimer = null;
|
|
320
|
+
stopSpeakingDetection = null;
|
|
321
|
+
statusListeners = /* @__PURE__ */ new Set();
|
|
322
|
+
rosterListeners = /* @__PURE__ */ new Set();
|
|
323
|
+
errorListeners = /* @__PURE__ */ new Set();
|
|
324
|
+
constructor(conversationId, socket, opts = {}) {
|
|
325
|
+
this.conversationId = conversationId;
|
|
326
|
+
this.socket = socket;
|
|
327
|
+
this.webrtc = opts.webrtc ?? createBrowserWebRtcAdapter();
|
|
328
|
+
this.iceServers = opts.iceServers ?? DEFAULT_ICE_SERVERS;
|
|
329
|
+
this.detectSpeaking = opts.detectSpeaking ?? true;
|
|
330
|
+
}
|
|
331
|
+
// ── observation ────────────────────────────────────────────────────
|
|
332
|
+
getStatus() {
|
|
333
|
+
return this.status;
|
|
334
|
+
}
|
|
335
|
+
isMuted() {
|
|
336
|
+
return this.muted;
|
|
337
|
+
}
|
|
338
|
+
/** Everyone in the room, oldest join first. */
|
|
339
|
+
getParticipants() {
|
|
340
|
+
return [...this.roster.values()].map((p) => ({ ...p, isSelf: p.userId === this.selfId })).sort((a, b) => a.joinedAt - b.joinedAt || a.userId.localeCompare(b.userId));
|
|
341
|
+
}
|
|
342
|
+
onStatus(fn) {
|
|
343
|
+
this.statusListeners.add(fn);
|
|
344
|
+
return () => this.statusListeners.delete(fn);
|
|
345
|
+
}
|
|
346
|
+
onParticipants(fn) {
|
|
347
|
+
this.rosterListeners.add(fn);
|
|
348
|
+
return () => this.rosterListeners.delete(fn);
|
|
349
|
+
}
|
|
350
|
+
onError(fn) {
|
|
351
|
+
this.errorListeners.add(fn);
|
|
352
|
+
return () => this.errorListeners.delete(fn);
|
|
353
|
+
}
|
|
354
|
+
// ── lifecycle ──────────────────────────────────────────────────────
|
|
355
|
+
/** Acquire the mic, join the channel, and start negotiating. */
|
|
356
|
+
async join() {
|
|
357
|
+
if (this.channel) return;
|
|
358
|
+
this.setStatus("connecting");
|
|
359
|
+
try {
|
|
360
|
+
this.localStream = await this.webrtc.getUserMedia();
|
|
361
|
+
} catch (err) {
|
|
362
|
+
this.setStatus("error");
|
|
363
|
+
this.emitError(new Error(`microphone unavailable: ${String(err)}`));
|
|
364
|
+
throw err;
|
|
365
|
+
}
|
|
366
|
+
const channel = this.socket.channel(`voice:conversation:${this.conversationId}`, {});
|
|
367
|
+
this.channel = channel;
|
|
368
|
+
this.bindChannel(channel);
|
|
369
|
+
await new Promise((resolve, reject) => {
|
|
370
|
+
channel.join().receive("ok", () => {
|
|
371
|
+
channel.push("voice:join", { muted: false, speaking: false });
|
|
372
|
+
resolve();
|
|
373
|
+
}).receive("error", (reply) => {
|
|
374
|
+
const err = new Error(`voice join rejected: ${reply?.reason ?? "unknown"}`);
|
|
375
|
+
this.setStatus("error");
|
|
376
|
+
this.emitError(err);
|
|
377
|
+
this.teardown();
|
|
378
|
+
reject(err);
|
|
379
|
+
}).receive("timeout", () => {
|
|
380
|
+
const err = new Error("voice join timed out");
|
|
381
|
+
this.setStatus("error");
|
|
382
|
+
this.emitError(err);
|
|
383
|
+
this.teardown();
|
|
384
|
+
reject(err);
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
/** Announce departure, then drop every peer connection and the mic. */
|
|
389
|
+
leave() {
|
|
390
|
+
this.channel?.push("voice:leave", {});
|
|
391
|
+
this.teardown();
|
|
392
|
+
this.setStatus("idle");
|
|
393
|
+
}
|
|
394
|
+
/** Mute or unmute the local mic. Returns the new muted state. */
|
|
395
|
+
setMuted(muted) {
|
|
396
|
+
this.muted = muted;
|
|
397
|
+
for (const track of this.localStream?.getAudioTracks() ?? []) {
|
|
398
|
+
track.enabled = !muted;
|
|
399
|
+
}
|
|
400
|
+
this.channel?.push(muted ? "voice:mute" : "voice:unmute", { muted });
|
|
401
|
+
if (this.selfId) {
|
|
402
|
+
const self = this.roster.get(this.selfId);
|
|
403
|
+
if (self) this.roster.set(this.selfId, { ...self, muted, speaking: false });
|
|
404
|
+
this.emitRoster();
|
|
405
|
+
}
|
|
406
|
+
return this.muted;
|
|
407
|
+
}
|
|
408
|
+
toggleMute() {
|
|
409
|
+
return this.setMuted(!this.muted);
|
|
410
|
+
}
|
|
411
|
+
// ── channel wiring ─────────────────────────────────────────────────
|
|
412
|
+
bindChannel(channel) {
|
|
413
|
+
channel.on("voice:presence_state", (state) => {
|
|
414
|
+
this.roster.clear();
|
|
415
|
+
for (const [userId, entry] of Object.entries(state ?? {})) {
|
|
416
|
+
const meta = entry?.metas?.[0] ?? {};
|
|
417
|
+
this.roster.set(userId, {
|
|
418
|
+
userId,
|
|
419
|
+
muted: meta.mute_state ?? false,
|
|
420
|
+
speaking: meta.speaking_state ?? false,
|
|
421
|
+
joinedAt: meta.joined_at ?? 0
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
this.emitRoster();
|
|
425
|
+
for (const userId of this.roster.keys()) {
|
|
426
|
+
if (userId !== this.selfId) this.startNegotiation(userId);
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
channel.on("voice:joined", (payload) => {
|
|
430
|
+
const userId = payload?.user_id;
|
|
431
|
+
if (!userId) return;
|
|
432
|
+
if (!this.selfId) {
|
|
433
|
+
this.selfId = userId;
|
|
434
|
+
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
435
|
+
this.setStatus("connected");
|
|
436
|
+
if (this.detectSpeaking && this.localStream) {
|
|
437
|
+
this.startSpeakingDetection(this.localStream);
|
|
438
|
+
}
|
|
439
|
+
this.emitRoster();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (userId === this.selfId) return;
|
|
443
|
+
if (!this.roster.has(userId)) {
|
|
444
|
+
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
445
|
+
this.emitRoster();
|
|
446
|
+
}
|
|
447
|
+
this.startNegotiation(userId);
|
|
448
|
+
});
|
|
449
|
+
channel.on("voice:left", (payload) => {
|
|
450
|
+
const userId = payload?.user_id;
|
|
451
|
+
if (!userId) return;
|
|
452
|
+
this.closePeer(userId);
|
|
453
|
+
this.roster.delete(userId);
|
|
454
|
+
this.emitRoster();
|
|
455
|
+
});
|
|
456
|
+
channel.on("voice:mute", (payload) => {
|
|
457
|
+
this.patchParticipant(payload?.user_id, { muted: payload?.muted ?? false });
|
|
458
|
+
});
|
|
459
|
+
channel.on("voice:active_speaker", (payload) => {
|
|
460
|
+
this.patchParticipant(payload?.user_id, { speaking: payload?.speaking ?? false });
|
|
461
|
+
});
|
|
462
|
+
channel.on("voice:signal", (payload) => {
|
|
463
|
+
void this.handleSignal(payload);
|
|
464
|
+
});
|
|
465
|
+
channel.on("voice:error", (payload) => {
|
|
466
|
+
this.emitError(new Error(`voice error: ${payload?.reason ?? "unknown"}`));
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
// ── negotiation ────────────────────────────────────────────────────
|
|
470
|
+
/**
|
|
471
|
+
* Glare control: both sides learn about each other simultaneously, so
|
|
472
|
+
* without a rule both would offer at once. The lexicographically lower
|
|
473
|
+
* user id offers and the higher answers — deterministic, no extra
|
|
474
|
+
* round trip.
|
|
475
|
+
*/
|
|
476
|
+
shouldOffer(peerId) {
|
|
477
|
+
return this.selfId != null && this.selfId < peerId;
|
|
478
|
+
}
|
|
479
|
+
startNegotiation(peerId) {
|
|
480
|
+
const pc = this.ensurePeer(peerId);
|
|
481
|
+
if (!this.shouldOffer(peerId)) return;
|
|
482
|
+
void (async () => {
|
|
483
|
+
try {
|
|
484
|
+
const offer = await pc.createOffer();
|
|
485
|
+
await pc.setLocalDescription(offer);
|
|
486
|
+
this.sendSignal("offer", peerId, { sdp: offer.sdp });
|
|
487
|
+
} catch (err) {
|
|
488
|
+
this.emitError(new Error(`offer to ${peerId} failed: ${String(err)}`));
|
|
489
|
+
}
|
|
490
|
+
})();
|
|
491
|
+
}
|
|
492
|
+
ensurePeer(peerId) {
|
|
493
|
+
const existing = this.peers.get(peerId);
|
|
494
|
+
if (existing) return existing;
|
|
495
|
+
const pc = this.webrtc.createPeerConnection(this.iceServers);
|
|
496
|
+
if (this.localStream) {
|
|
497
|
+
for (const track of this.localStream.getTracks()) {
|
|
498
|
+
pc.addTrack(track, this.localStream);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
pc.onicecandidate = (event) => {
|
|
502
|
+
if (!event.candidate) return;
|
|
503
|
+
this.sendSignal("ice-candidate", peerId, event.candidate);
|
|
504
|
+
};
|
|
505
|
+
pc.ontrack = (event) => {
|
|
506
|
+
const stream = event.streams[0];
|
|
507
|
+
if (!stream) return;
|
|
508
|
+
this.sinks.get(peerId)?.();
|
|
509
|
+
this.sinks.set(peerId, this.webrtc.playRemoteStream(peerId, stream));
|
|
510
|
+
};
|
|
511
|
+
this.peers.set(peerId, pc);
|
|
512
|
+
return pc;
|
|
513
|
+
}
|
|
514
|
+
async handleSignal(payload) {
|
|
515
|
+
const from = payload["from_user_id"];
|
|
516
|
+
const type = payload["type"];
|
|
517
|
+
if (!from || !type || from === this.selfId) return;
|
|
518
|
+
const target = payload["target_user_id"];
|
|
519
|
+
if (target && target !== this.selfId) return;
|
|
520
|
+
const data = payload["data"] ?? {};
|
|
521
|
+
const pc = this.ensurePeer(from);
|
|
522
|
+
try {
|
|
523
|
+
if (type === "offer") {
|
|
524
|
+
await pc.setRemoteDescription({ type: "offer", sdp: data["sdp"] });
|
|
525
|
+
await this.flushIce(pc, from);
|
|
526
|
+
const answer = await pc.createAnswer();
|
|
527
|
+
await pc.setLocalDescription(answer);
|
|
528
|
+
this.sendSignal("answer", from, { sdp: answer.sdp });
|
|
529
|
+
} else if (type === "answer") {
|
|
530
|
+
await pc.setRemoteDescription({ type: "answer", sdp: data["sdp"] });
|
|
531
|
+
await this.flushIce(pc, from);
|
|
532
|
+
} else if (type === "ice-candidate") {
|
|
533
|
+
const candidate = data;
|
|
534
|
+
if (!pc.remoteDescription) {
|
|
535
|
+
const queued = this.pendingIce.get(from) ?? [];
|
|
536
|
+
queued.push(candidate);
|
|
537
|
+
this.pendingIce.set(from, queued);
|
|
538
|
+
} else {
|
|
539
|
+
await pc.addIceCandidate(candidate);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
} catch (err) {
|
|
543
|
+
this.emitError(new Error(`signal (${type}) from ${from} failed: ${String(err)}`));
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
async flushIce(pc, peerId) {
|
|
547
|
+
const queued = this.pendingIce.get(peerId);
|
|
548
|
+
if (!queued?.length) return;
|
|
549
|
+
this.pendingIce.delete(peerId);
|
|
550
|
+
for (const candidate of queued) {
|
|
551
|
+
try {
|
|
552
|
+
await pc.addIceCandidate(candidate);
|
|
553
|
+
} catch {
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Every signal body travels under `data` — the server's
|
|
559
|
+
* `validate_signal_data/1` rejects the push outright when that key is
|
|
560
|
+
* missing or empty, and a rejected signal is never relayed.
|
|
561
|
+
*/
|
|
562
|
+
sendSignal(type, targetUserId, data) {
|
|
563
|
+
this.channel?.push("voice:signal", { type, target_user_id: targetUserId, data });
|
|
564
|
+
}
|
|
565
|
+
// ── speaking detection ─────────────────────────────────────────────
|
|
566
|
+
startSpeakingDetection(stream) {
|
|
567
|
+
const Ctor = globalThis.AudioContext;
|
|
568
|
+
if (!Ctor) return;
|
|
569
|
+
const ctx = new Ctor();
|
|
570
|
+
const source = ctx.createMediaStreamSource(stream);
|
|
571
|
+
const analyser = ctx.createAnalyser();
|
|
572
|
+
analyser.fftSize = 512;
|
|
573
|
+
source.connect(analyser);
|
|
574
|
+
const buf = new Float32Array(analyser.fftSize);
|
|
575
|
+
let speaking = false;
|
|
576
|
+
let lastLoud = 0;
|
|
577
|
+
this.speakingTimer = setInterval(() => {
|
|
578
|
+
analyser.getFloatTimeDomainData(buf);
|
|
579
|
+
let sum = 0;
|
|
580
|
+
for (const v of buf) sum += v * v;
|
|
581
|
+
const rms = Math.sqrt(sum / buf.length);
|
|
582
|
+
const now = Date.now();
|
|
583
|
+
if (!this.muted && rms > SPEAKING_THRESHOLD) lastLoud = now;
|
|
584
|
+
const next = !this.muted && now - lastLoud < SPEAKING_RELEASE_MS;
|
|
585
|
+
if (next === speaking) return;
|
|
586
|
+
speaking = next;
|
|
587
|
+
this.channel?.push("voice:active_speaker", { speaking });
|
|
588
|
+
this.patchParticipant(this.selfId ?? void 0, { speaking });
|
|
589
|
+
}, SPEAKING_POLL_MS);
|
|
590
|
+
this.stopSpeakingDetection = () => {
|
|
591
|
+
void ctx.close().catch(() => {
|
|
592
|
+
});
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
// ── teardown & emit ────────────────────────────────────────────────
|
|
596
|
+
closePeer(peerId) {
|
|
597
|
+
const pc = this.peers.get(peerId);
|
|
598
|
+
if (pc) {
|
|
599
|
+
pc.onicecandidate = null;
|
|
600
|
+
pc.ontrack = null;
|
|
601
|
+
pc.onconnectionstatechange = null;
|
|
602
|
+
pc.close();
|
|
603
|
+
this.peers.delete(peerId);
|
|
604
|
+
}
|
|
605
|
+
this.sinks.get(peerId)?.();
|
|
606
|
+
this.sinks.delete(peerId);
|
|
607
|
+
this.pendingIce.delete(peerId);
|
|
608
|
+
}
|
|
609
|
+
teardown() {
|
|
610
|
+
for (const peerId of [...this.peers.keys()]) this.closePeer(peerId);
|
|
611
|
+
if (this.speakingTimer) clearInterval(this.speakingTimer);
|
|
612
|
+
this.speakingTimer = null;
|
|
613
|
+
this.stopSpeakingDetection?.();
|
|
614
|
+
this.stopSpeakingDetection = null;
|
|
615
|
+
for (const track of this.localStream?.getTracks() ?? []) track.stop();
|
|
616
|
+
this.localStream = null;
|
|
617
|
+
this.channel?.leave();
|
|
618
|
+
this.channel = null;
|
|
619
|
+
this.selfId = null;
|
|
620
|
+
this.muted = false;
|
|
621
|
+
this.roster.clear();
|
|
622
|
+
this.emitRoster();
|
|
623
|
+
}
|
|
624
|
+
patchParticipant(userId, patch) {
|
|
625
|
+
if (!userId) return;
|
|
626
|
+
const current = this.roster.get(userId);
|
|
627
|
+
if (!current) return;
|
|
628
|
+
this.roster.set(userId, { ...current, ...patch });
|
|
629
|
+
this.emitRoster();
|
|
630
|
+
}
|
|
631
|
+
setStatus(status) {
|
|
632
|
+
if (this.status === status) return;
|
|
633
|
+
this.status = status;
|
|
634
|
+
this.statusListeners.forEach((l) => l(status));
|
|
635
|
+
}
|
|
636
|
+
emitRoster() {
|
|
637
|
+
const snapshot = this.getParticipants();
|
|
638
|
+
this.rosterListeners.forEach((l) => l(snapshot));
|
|
639
|
+
}
|
|
640
|
+
emitError(err) {
|
|
641
|
+
this.errorListeners.forEach((l) => l(err));
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
|
|
106
645
|
// src/realtime/realtime.ts
|
|
107
646
|
var PoolseRealtime = class {
|
|
108
647
|
config;
|
|
@@ -111,7 +650,9 @@ var PoolseRealtime = class {
|
|
|
111
650
|
wsUrl;
|
|
112
651
|
socket = null;
|
|
113
652
|
conversations = /* @__PURE__ */ new Map();
|
|
653
|
+
voiceRooms = /* @__PURE__ */ new Map();
|
|
114
654
|
userChannel = null;
|
|
655
|
+
callsResource = null;
|
|
115
656
|
status = "idle";
|
|
116
657
|
statusListeners = /* @__PURE__ */ new Set();
|
|
117
658
|
constructor(config, tokenCache, opts = {}) {
|
|
@@ -181,6 +722,8 @@ var PoolseRealtime = class {
|
|
|
181
722
|
}
|
|
182
723
|
/** Close the socket and tear down every joined channel. */
|
|
183
724
|
disconnect() {
|
|
725
|
+
for (const room of this.voiceRooms.values()) room.leave();
|
|
726
|
+
this.voiceRooms.clear();
|
|
184
727
|
this.setStatus("closed");
|
|
185
728
|
this.conversations.forEach((c) => c._destroy());
|
|
186
729
|
this.conversations.clear();
|
|
@@ -225,6 +768,39 @@ var PoolseRealtime = class {
|
|
|
225
768
|
handle._join();
|
|
226
769
|
return handle;
|
|
227
770
|
}
|
|
771
|
+
/**
|
|
772
|
+
* Voice room for a conversation — the Discord-style surface. Call
|
|
773
|
+
* `join()` on the returned handle to acquire the mic and connect;
|
|
774
|
+
* reusing the same id returns the same room rather than opening a
|
|
775
|
+
* second one.
|
|
776
|
+
*
|
|
777
|
+
* Ringing somebody who hasn't joined is a separate concern; see
|
|
778
|
+
* `poolse.calls`.
|
|
779
|
+
*/
|
|
780
|
+
voice(conversationId, opts = {}) {
|
|
781
|
+
const existing = this.voiceRooms.get(conversationId);
|
|
782
|
+
if (existing) return existing;
|
|
783
|
+
this.connect();
|
|
784
|
+
if (!this.socket) {
|
|
785
|
+
throw new PoolseError("socket not initialised \u2014 call connect() first");
|
|
786
|
+
}
|
|
787
|
+
const room = new VoiceRoom(conversationId, this.socket, opts);
|
|
788
|
+
this.voiceRooms.set(conversationId, room);
|
|
789
|
+
return room;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Call invitations for a user — the WhatsApp-style surface. Rides the
|
|
793
|
+
* `user:<id>` topic, the one channel a client is always joined to, so
|
|
794
|
+
* a ring reaches somebody who hasn't opened a voice room yet.
|
|
795
|
+
*
|
|
796
|
+
* Takes the user id explicitly, mirroring `user(userId)`; the SDK
|
|
797
|
+
* never assumes whose token it is holding.
|
|
798
|
+
*/
|
|
799
|
+
calls(userId) {
|
|
800
|
+
if (this.callsResource) return this.callsResource;
|
|
801
|
+
this.callsResource = new CallsResource(() => this.user(userId)._channel());
|
|
802
|
+
return this.callsResource;
|
|
803
|
+
}
|
|
228
804
|
/** Drop a conversation handle and leave the channel. */
|
|
229
805
|
leave(conversationId) {
|
|
230
806
|
const handle = this.conversations.get(conversationId);
|
|
@@ -364,6 +940,15 @@ var UserChannel = class {
|
|
|
364
940
|
this.userId = userId;
|
|
365
941
|
this.channel = channel;
|
|
366
942
|
}
|
|
943
|
+
/**
|
|
944
|
+
* The underlying Phoenix channel, for surfaces that push their own
|
|
945
|
+
* events on this topic (the calls resource does).
|
|
946
|
+
*
|
|
947
|
+
* @internal
|
|
948
|
+
*/
|
|
949
|
+
_channel() {
|
|
950
|
+
return this.channel;
|
|
951
|
+
}
|
|
367
952
|
onMention(fn) {
|
|
368
953
|
if (!this.mentionBound) {
|
|
369
954
|
this.mentionBound = true;
|
|
@@ -1204,8 +1789,8 @@ var Poolse = class {
|
|
|
1204
1789
|
};
|
|
1205
1790
|
|
|
1206
1791
|
// src/version.ts
|
|
1207
|
-
var version = "2.0
|
|
1792
|
+
var version = "2.3.0";
|
|
1208
1793
|
|
|
1209
|
-
export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, UserChannel, UsersResource, safeUuid, version };
|
|
1794
|
+
export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallsResource, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, UserChannel, UsersResource, VoiceRoom, createBrowserWebRtcAdapter, isWebRtcAvailable, safeUuid, version };
|
|
1210
1795
|
//# sourceMappingURL=index.js.map
|
|
1211
1796
|
//# sourceMappingURL=index.js.map
|