@midsummer-ai/sdk 0.1.0-staging.4480 → 0.1.0-staging.4486

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.
@@ -0,0 +1,1131 @@
1
+ import { a as processEnv, i as platformApi, n as here, t as clientHeaders } from "../here-C2jhTheQ.mjs";
2
+ import { CALL_STATUS, TRACK_KINDS } from "./protocol.mjs";
3
+ //#region src/calls/index.ts
4
+ /**
5
+ * Calls: voice and video in an app, for the people who use it and for agents. A call is a room name in one of the
6
+ * project's environments. Whoever has a token the app's server made for that room is in, and the room opens with
7
+ * the first join: there is nothing to create first.
8
+ *
9
+ * In the browser:
10
+ *
11
+ * import { join } from "@midsummer-ai/sdk/calls"
12
+ *
13
+ * const call = await join("support-42", { token })
14
+ * await call.publish({ mic: true, camera: true })
15
+ * call.on("track", ({ participant, name, track }) => show(participant, name, track))
16
+ * await call.screen.share()
17
+ * call.send({ raised: true })
18
+ * await call.leave()
19
+ *
20
+ * On the app's server, a token for the person, made with no key in a deployment on Midsummer and under
21
+ * `midsummer dev`:
22
+ *
23
+ * import { callToken } from "@midsummer-ai/sdk/calls"
24
+ *
25
+ * return Response.json(await callToken({ room: "support-42", as: user.id, name: user.name }))
26
+ *
27
+ * An agent in Node joins the same way, with a token from `midsummer call token create` and any WebRTC library's
28
+ * `RTCPeerConnection` passed as `rtc`:
29
+ *
30
+ * const call = await join(room, { token, rtc: wrtc })
31
+ *
32
+ * `token` may be a function that asks the app's server for one; it's asked again five minutes before each token runs
33
+ * out. An app that signs people in with Auth can hand out tokens from `auth.handler` (`createAuth({ calls: { allow } })`):
34
+ *
35
+ * const call = await join("support-42", { token: () => fetch("/api/auth/call-token?room=support-42").then((r) => r.json()) })
36
+ *
37
+ * A call's `state` is `connecting` while it joins, `waiting` while nobody else is in the room, `in-call` once someone
38
+ * is (whether or not they send anything), `reconnecting` while the connection dropped and the call joins the room again
39
+ * (for up to 30 seconds, as the same participant), `ended` once the room was ended or you left, and `failed` with
40
+ * `error`, a `CallError` whose `code` shows why. Each change is a `state` event.
41
+ *
42
+ * Every audio track in the room is received. Videos are received too, up to 9 at once at the half layer (`h`), unless
43
+ * `autoVideo` is false; a grid that shows fewer tiles asks for what it shows with `receive`, `setLayer` and
44
+ * `stopReceiving`. A camera is sent in three layers: `q` (a quarter of its size, about 150 kbps), `h` (half, 500 kbps)
45
+ * and `f` (full, 1.5 Mbps). A participant receives at most 9 videos, 2 of them at `f`; asking for more is refused.
46
+ *
47
+ * Under `midsummer dev` and in tests there's no media server (`media: "relay"`): each pair of participants connects
48
+ * directly. The participant with the smaller id makes the one offer, with four two-way transceivers in the order mic,
49
+ * camera, screen and screen-audio and one data channel, and each sends it through the room (`signal`), whole, once
50
+ * its addresses are gathered. A track is sent by placing it on its transceiver, so nothing is offered again, and is
51
+ * known by its transceiver's place. Someone who joins again offers to everyone, and an offer always starts a new
52
+ * connection; of two offers that cross, the smaller id's stands.
53
+ */
54
+ /** The most a message sent with `send` carries, as JSON. */
55
+ const MAX_MESSAGE_BYTES = 16384;
56
+ /** The most videos a participant receives at once, and how many of them at the full layer. */
57
+ const MAX_VIDEOS = 9;
58
+ const MAX_FULL_VIDEOS = 2;
59
+ /** How long before a token runs out it is asked for again. */
60
+ const RENEW_BEFORE_MS = 3e5;
61
+ /** How long a dropped call tries to join again before it fails. */
62
+ const REJOIN_FOR_MS = 3e4;
63
+ /** How long one watch waits on the room; the platform returns by then, and the next is asked at once. */
64
+ const WATCH_WAIT_MS = 25e3;
65
+ /** The most tracks one pull asks for. */
66
+ const PULL_MAX = 16;
67
+ /** The tracks' places on a direct connection, in order. */
68
+ const TRACK_ORDER = [
69
+ "mic",
70
+ "camera",
71
+ "screen",
72
+ "screen-audio"
73
+ ];
74
+ /** A camera's three layers, smallest first. */
75
+ const SIMULCAST = [
76
+ {
77
+ rid: "q",
78
+ scaleResolutionDownBy: 4,
79
+ maxBitrate: 15e4
80
+ },
81
+ {
82
+ rid: "h",
83
+ scaleResolutionDownBy: 2,
84
+ maxBitrate: 5e5
85
+ },
86
+ {
87
+ rid: "f",
88
+ scaleResolutionDownBy: 1,
89
+ maxBitrate: 15e5
90
+ }
91
+ ];
92
+ /** Why a call or a call's request failed, in words a person reads; `code` is the one the wire carries. */
93
+ var CallError = class extends Error {
94
+ code;
95
+ constructor(code, why) {
96
+ super(why);
97
+ this.code = code;
98
+ this.name = "CallError";
99
+ }
100
+ };
101
+ /** A request that never reached the call's server, or found it down: what joining again is for. */
102
+ var Unreachable = class extends CallError {
103
+ constructor(why) {
104
+ super("unavailable", why);
105
+ }
106
+ };
107
+ /** Why a name can't be a room's, or undefined: 1 to 64 letters, digits, `-`, `_` and `.`, starting with a letter or digit. */
108
+ function roomProblem(name) {
109
+ if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(name)) return `${JSON.stringify(name)} can't name a room. Use 1 to 64 letters, digits, dots, dashes and underscores, starting with a letter or digit, such as support-42.`;
110
+ }
111
+ /** Why `as` can't name a participant, or undefined: 1 to 128 printable characters. */
112
+ function identityProblem(as) {
113
+ if (typeof as !== "string" || !/^[\x21-\x7e]{1,128}$/u.test(as)) return `${JSON.stringify(as)} can't name a participant. Use 1 to 128 printable characters with no spaces, such as a user id or guest-7.`;
114
+ }
115
+ /**
116
+ * A token for one person in one room, made on the app's server: in a deployment on Midsummer with no key, and under
117
+ * `midsummer dev` by its stand-in. Hand it to the page, which joins with it.
118
+ *
119
+ * const token = await callToken({ room: "support-42", as: user.id, name: user.name })
120
+ */
121
+ async function callToken(input) {
122
+ const problem = roomProblem(input.room) ?? identityProblem(input.as);
123
+ if (problem) throw new CallError("invalid", problem);
124
+ const handle = here()?.calls;
125
+ if (handle) return handle.token(input).catch((error) => {
126
+ throw new CallError("unavailable", error instanceof Error ? error.message : String(error));
127
+ });
128
+ const dev = processEnv().MIDSUMMER_CALLS_URL;
129
+ if (!dev) throw new CallError("unavailable", "callToken makes tokens in a deployment on Midsummer and under midsummer dev. Run it there, or make one with midsummer call token create.");
130
+ const url = `${dev.replace(/\/+$/u, "")}/token`;
131
+ const response = await fetch(url, {
132
+ method: "POST",
133
+ headers: {
134
+ "content-type": "application/json",
135
+ ...clientHeaders("calls")
136
+ },
137
+ body: JSON.stringify(input)
138
+ }).catch(() => void 0);
139
+ if (!response) throw new CallError("unavailable", `midsummer dev's calls couldn't be reached at ${new URL(url).origin}. Is midsummer dev still running?`);
140
+ return await answerOf(response, "token");
141
+ }
142
+ /**
143
+ * Joins a room with a token the app's server made for it, and resolves once you're in: `waiting` or `in-call`. A
144
+ * refusal rejects with a `CallError`: `forbidden` for a token that isn't good, ran out or is for someone removed,
145
+ * `full`, `ended` for a room ended since the token was made, `unavailable` when the call can't be reached.
146
+ */
147
+ async function join(room, options) {
148
+ const problem = roomProblem(room);
149
+ if (problem) throw new CallError("invalid", problem);
150
+ const call = new LiveCall(room, options, options.rtc ?? browserRtc());
151
+ await call.start();
152
+ return call;
153
+ }
154
+ function browserRtc() {
155
+ const found = globalThis;
156
+ if (!found.RTCPeerConnection) throw new CallError("unavailable", "There's no WebRTC here. Outside a browser, pass a WebRTC library: join(room, { token, rtc }).");
157
+ return {
158
+ RTCPeerConnection: found.RTCPeerConnection,
159
+ ...found.MediaStream ? { MediaStream: found.MediaStream } : {}
160
+ };
161
+ }
162
+ async function answerOf(response, op) {
163
+ const body = await response.json().catch(() => void 0);
164
+ if (response.ok && body && typeof body === "object" && !body.error) return body;
165
+ const code = body?.error?.code, message = body?.error?.message;
166
+ if (typeof code === "string" && Object.hasOwn(CALL_STATUS, code) && typeof message === "string") throw new CallError(code, message);
167
+ if (response.status >= 500) throw new Unreachable(`The call returned ${response.status}.`);
168
+ throw new CallError("invalid", `The call returned ${response.status} to ${op}.`);
169
+ }
170
+ /** One op of the call wire, with the token, as JSON. */
171
+ async function request(url, token, op, body) {
172
+ const response = await fetch(`${url}/${op}`, {
173
+ method: "POST",
174
+ headers: {
175
+ authorization: `Bearer ${token}`,
176
+ "content-type": "application/json",
177
+ ...clientHeaders("calls")
178
+ },
179
+ body: JSON.stringify(body)
180
+ }).catch(() => void 0);
181
+ if (!response) throw new Unreachable(`The call couldn't be reached at ${new URL(url).origin}. Check your network.`);
182
+ return await answerOf(response, op);
183
+ }
184
+ /** When a token runs out, from its claims: only a call token's signature is secret (`mcall_<claims>.<signature>`). */
185
+ function claimedExpiry(token) {
186
+ try {
187
+ const body = token.slice(token.indexOf("_") + 1).split(".")[0] ?? "";
188
+ const claims = JSON.parse(atob(body.replace(/-/g, "+").replace(/_/g, "/")));
189
+ return typeof claims.expiresAt === "number" ? claims.expiresAt : void 0;
190
+ } catch {
191
+ return;
192
+ }
193
+ }
194
+ const credentialOf = (given) => {
195
+ if (typeof given === "string") {
196
+ const expiresAt = claimedExpiry(given);
197
+ return {
198
+ token: given,
199
+ ...expiresAt !== void 0 ? { expiresAt } : {}
200
+ };
201
+ }
202
+ return {
203
+ token: given.token,
204
+ url: given.url,
205
+ expiresAt: given.expiresAt
206
+ };
207
+ };
208
+ const sdpOf = (description) => {
209
+ if (!description?.sdp || description.type !== "offer" && description.type !== "answer") throw new CallError("unavailable", "The browser made no offer or answer for the call.");
210
+ return {
211
+ type: description.type,
212
+ sdp: description.sdp
213
+ };
214
+ };
215
+ const configOf = (iceServers) => ({
216
+ iceServers: iceServers.map((server) => ({
217
+ urls: typeof server.urls === "string" ? server.urls : [...server.urls],
218
+ ...server.username !== void 0 ? { username: server.username } : {},
219
+ ...server.credential !== void 0 ? { credential: server.credential } : {}
220
+ })),
221
+ bundlePolicy: "max-bundle"
222
+ });
223
+ /** Resolves once a connection has gathered its addresses, so its offer or answer goes whole, with no trickling. */
224
+ const gathered = (pc) => new Promise((resolve) => {
225
+ if (pc.iceGatheringState === "complete") return resolve();
226
+ const done = () => {
227
+ pc.removeEventListener("icegatheringstatechange", check);
228
+ pc.removeEventListener("icecandidate", last);
229
+ resolve();
230
+ };
231
+ const check = () => {
232
+ if (pc.iceGatheringState === "complete") done();
233
+ };
234
+ const last = (event) => {
235
+ if (!event.candidate) done();
236
+ };
237
+ pc.addEventListener("icegatheringstatechange", check);
238
+ pc.addEventListener("icecandidate", last);
239
+ });
240
+ const sizeProblem = (bytes) => `A message is at most 16 KiB as JSON; this one is ${Math.ceil(bytes / 1024)} KiB.`;
241
+ const videoCapProblem = `A participant receives at most 9 videos at once. Stop receiving one first, as a grid does for tiles out of view.`;
242
+ const fullCapProblem = `A participant receives at most 2 videos at full quality at once. Ask for h or q for the others.`;
243
+ /** Messages sent before a channel opens wait for it, a few at most. */
244
+ function channelSend(channel, outbox, text) {
245
+ if (channel.readyState === "open") channel.send(text);
246
+ else if (channel.readyState === "connecting" && outbox.length < 64) outbox.push(text);
247
+ }
248
+ /** Media through the media server: one connection, a transceiver for each track published and each received. */
249
+ function sfuMedia(ctx, auto, declined) {
250
+ const pc = new ctx.rtc.RTCPeerConnection(configOf(ctx.iceServers));
251
+ const sent = /* @__PURE__ */ new Map();
252
+ const pulled = /* @__PURE__ */ new Map();
253
+ const pending = /* @__PURE__ */ new Set();
254
+ const key = (of, name) => `${of}/${name}`;
255
+ const channels = /* @__PURE__ */ new Map();
256
+ const outbox = [];
257
+ let own;
258
+ let dataAsked = false;
259
+ /** Whose data channels have been asked for, so none is asked for twice. */
260
+ const dataFrom = /* @__PURE__ */ new Set();
261
+ let others = [];
262
+ let closed = false;
263
+ let chain = Promise.resolve();
264
+ const serial = (work) => {
265
+ const next = chain.then(work, work);
266
+ chain = next.catch(() => void 0);
267
+ return next;
268
+ };
269
+ const find = (of, name) => [...pulled].find(([, pull]) => pull.of === of && pull.name === name);
270
+ const videos = () => [...pulled.values()].filter((pull) => TRACK_KINDS[pull.name] === "video");
271
+ const publishes = (of, name) => others.some((other) => other.id === of && other.tracks.some((track) => track.name === name));
272
+ pc.addEventListener("track", (event) => {
273
+ const pull = event.transceiver.mid ? pulled.get(event.transceiver.mid) : void 0;
274
+ if (!pull) return;
275
+ pull.track = event.track;
276
+ ctx.arrived(pull.of, pull.name, event.track);
277
+ });
278
+ pc.addEventListener("connectionstatechange", () => {
279
+ if (!closed && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) ctx.broken();
280
+ });
281
+ async function openData(from) {
282
+ const opened = await ctx.post("data", {
283
+ participant: ctx.me,
284
+ from
285
+ });
286
+ if (opened.own !== void 0 && !own) {
287
+ own = pc.createDataChannel("data", {
288
+ negotiated: true,
289
+ id: opened.own
290
+ });
291
+ const channel = own;
292
+ channel.addEventListener("open", () => {
293
+ for (const text of outbox.splice(0)) channel.send(text);
294
+ });
295
+ }
296
+ for (const { of, id } of opened.from) {
297
+ const channel = pc.createDataChannel(`data:${of}`, {
298
+ negotiated: true,
299
+ id
300
+ });
301
+ channel.addEventListener("message", (event) => ctx.message(of, String(event.data)));
302
+ channels.set(of, channel);
303
+ }
304
+ }
305
+ const pull = (tracks) => {
306
+ for (const track of tracks) pending.add(key(track.of, track.name));
307
+ return serial(async () => {
308
+ try {
309
+ const still = tracks.filter((track) => publishes(track.of, track.name) && !find(track.of, track.name));
310
+ for (let at = 0; at < still.length && !closed; at += PULL_MAX) {
311
+ const chunk = still.slice(at, at + PULL_MAX);
312
+ const answered = await ctx.post("pull", {
313
+ participant: ctx.me,
314
+ tracks: chunk
315
+ });
316
+ for (const track of answered.tracks) {
317
+ const layer = chunk.find((asked) => asked.of === track.of && asked.name === track.name)?.layer;
318
+ pulled.set(track.mid, {
319
+ of: track.of,
320
+ name: track.name,
321
+ ...layer ? { layer } : {}
322
+ });
323
+ }
324
+ await pc.setRemoteDescription(answered.offer);
325
+ await pc.setLocalDescription(await pc.createAnswer());
326
+ await ctx.post("answer", {
327
+ participant: ctx.me,
328
+ answer: sdpOf(pc.localDescription)
329
+ });
330
+ }
331
+ } finally {
332
+ for (const track of tracks) pending.delete(key(track.of, track.name));
333
+ }
334
+ });
335
+ };
336
+ return {
337
+ publish: (tracks) => serial(async () => {
338
+ const made = tracks.map(({ name, track }) => ({
339
+ name,
340
+ transceiver: pc.addTransceiver(track, {
341
+ direction: "sendonly",
342
+ ...name === "camera" ? { sendEncodings: SIMULCAST } : {},
343
+ ...ctx.rtc.MediaStream ? { streams: [new ctx.rtc.MediaStream([track])] } : {}
344
+ })
345
+ }));
346
+ await pc.setLocalDescription(await pc.createOffer());
347
+ try {
348
+ const answered = await ctx.post("publish", {
349
+ participant: ctx.me,
350
+ offer: sdpOf(pc.localDescription),
351
+ tracks: made.map(({ name, transceiver }) => ({
352
+ mid: transceiver.mid ?? "",
353
+ name
354
+ }))
355
+ });
356
+ if (answered.answer) await pc.setRemoteDescription(answered.answer);
357
+ for (const { name, transceiver } of made) sent.set(name, transceiver);
358
+ return answered.room;
359
+ } catch (error) {
360
+ if (pc.signalingState === "have-local-offer") await pc.setLocalDescription({ type: "rollback" });
361
+ for (const { transceiver } of made) transceiver.stop();
362
+ throw error;
363
+ }
364
+ }),
365
+ async replace(name, track) {
366
+ await sent.get(name)?.sender.replaceTrack(track);
367
+ },
368
+ async unpublish(names) {
369
+ const answered = await ctx.post("unpublish", {
370
+ participant: ctx.me,
371
+ names
372
+ });
373
+ for (const name of names) {
374
+ await sent.get(name)?.sender.replaceTrack(null);
375
+ sent.delete(name);
376
+ }
377
+ return answered.room;
378
+ },
379
+ sync(list) {
380
+ others = list;
381
+ const gone = [...pulled].filter(([, pull]) => !publishes(pull.of, pull.name));
382
+ for (const [mid, pull] of gone) {
383
+ pulled.delete(mid);
384
+ if (pull.track) ctx.ended(pull.of, pull.name);
385
+ }
386
+ if (gone.length) ctx.post("unpull", {
387
+ participant: ctx.me,
388
+ mids: gone.map(([mid]) => mid)
389
+ }).catch(ctx.failed);
390
+ for (const of of [...dataFrom]) if (!list.some((other) => other.id === of)) {
391
+ channels.get(of)?.close();
392
+ channels.delete(of);
393
+ dataFrom.delete(of);
394
+ }
395
+ const fresh = list.filter((other) => !dataFrom.has(other.id)).map((other) => other.id);
396
+ for (const of of fresh) dataFrom.add(of);
397
+ if (!dataAsked || fresh.length) {
398
+ dataAsked = true;
399
+ serial(() => openData(fresh)).catch(ctx.failed);
400
+ }
401
+ const wanted = [];
402
+ let video = videos().length + [...pending].filter((each) => TRACK_KINDS[each.slice(each.lastIndexOf("/") + 1)] === "video").length;
403
+ for (const other of list) for (const track of other.tracks) {
404
+ const at = key(other.id, track.name);
405
+ if (find(other.id, track.name) || pending.has(at) || declined.has(at)) continue;
406
+ if (track.kind === "audio") wanted.push({
407
+ of: other.id,
408
+ name: track.name
409
+ });
410
+ else if (auto && video < 9) {
411
+ wanted.push({
412
+ of: other.id,
413
+ name: track.name,
414
+ layer: "h"
415
+ });
416
+ video += 1;
417
+ }
418
+ }
419
+ if (wanted.length) pull(wanted).catch(ctx.failed);
420
+ },
421
+ signals() {},
422
+ async receive(of, name, layer) {
423
+ const found = find(of, name);
424
+ if (found) {
425
+ if (TRACK_KINDS[name] === "video" && layer && layer !== (found[1].layer ?? "h")) await this.setLayer(of, name, layer);
426
+ return;
427
+ }
428
+ if (!publishes(of, name)) throw new CallError("not-found", `${of} publishes no ${name} in this call now.`);
429
+ if (TRACK_KINDS[name] === "video") {
430
+ if (videos().length + 1 > 9) throw new CallError("invalid", videoCapProblem);
431
+ if (layer === "f" && videos().filter((pull) => pull.layer === "f").length + 1 > 2) throw new CallError("invalid", fullCapProblem);
432
+ }
433
+ await pull([{
434
+ of,
435
+ name,
436
+ ...TRACK_KINDS[name] === "video" ? { layer: layer ?? "h" } : {}
437
+ }]);
438
+ },
439
+ async setLayer(of, name, layer) {
440
+ const found = find(of, name);
441
+ if (!found || TRACK_KINDS[name] !== "video") throw new CallError("not-found", `You receive no ${name} from ${of}.`);
442
+ const [mid, pulledTrack] = found;
443
+ if (layer === pulledTrack.layer) return;
444
+ if (layer === "f" && videos().filter((each) => each.layer === "f").length + 1 > 2) throw new CallError("invalid", fullCapProblem);
445
+ await ctx.post("layer", {
446
+ participant: ctx.me,
447
+ mid,
448
+ layer
449
+ });
450
+ pulledTrack.layer = layer;
451
+ },
452
+ async stopReceiving(of, name) {
453
+ declined.add(key(of, name));
454
+ const found = find(of, name);
455
+ if (!found) return;
456
+ const [mid, pulledTrack] = found;
457
+ pulled.delete(mid);
458
+ if (pulledTrack.track) ctx.ended(of, name);
459
+ await ctx.post("unpull", {
460
+ participant: ctx.me,
461
+ mids: [mid]
462
+ });
463
+ },
464
+ send(text) {
465
+ if (own) channelSend(own, outbox, text);
466
+ else if (outbox.length < 64) outbox.push(text);
467
+ },
468
+ close() {
469
+ closed = true;
470
+ for (const channel of channels.values()) channel.close();
471
+ own?.close();
472
+ pc.close();
473
+ }
474
+ };
475
+ }
476
+ /** Media with no media server: a connection to each other participant, made once (see the top of this file). */
477
+ function relayMedia(ctx, rejoined) {
478
+ const peers = /* @__PURE__ */ new Map();
479
+ let others = [];
480
+ let offerAll = rejoined;
481
+ let signalling = Promise.resolve();
482
+ function make(of) {
483
+ const pc = new ctx.rtc.RTCPeerConnection(configOf(ctx.iceServers));
484
+ const channel = pc.createDataChannel("data", {
485
+ negotiated: true,
486
+ id: 0
487
+ });
488
+ const peer = {
489
+ of,
490
+ pc,
491
+ channel,
492
+ outbox: [],
493
+ received: /* @__PURE__ */ new Set()
494
+ };
495
+ channel.addEventListener("message", (event) => ctx.message(of, String(event.data)));
496
+ channel.addEventListener("open", () => {
497
+ for (const text of peer.outbox.splice(0)) channel.send(text);
498
+ });
499
+ pc.addEventListener("connectionstatechange", () => {
500
+ if (peers.get(of) !== peer || pc.connectionState !== "failed") return;
501
+ drop(peer);
502
+ if (ctx.me < of) offer(of).catch(ctx.failed);
503
+ });
504
+ peers.set(of, peer);
505
+ return peer;
506
+ }
507
+ function drop(peer) {
508
+ if (peers.get(peer.of) === peer) peers.delete(peer.of);
509
+ for (const name of peer.received) ctx.ended(peer.of, name);
510
+ peer.received.clear();
511
+ peer.channel.close();
512
+ peer.pc.close();
513
+ }
514
+ async function put(peer) {
515
+ const sending = ctx.sending();
516
+ await Promise.all(TRACK_ORDER.map((name, at) => peer.transceivers?.[at]?.sender.replaceTrack(sending.find((each) => each.name === name)?.track ?? null)));
517
+ }
518
+ /** Hands over each track the other publishes, from its transceiver's place, and ends those they stopped. */
519
+ function match(peer) {
520
+ if (!peer.transceivers || peer.pc.signalingState !== "stable") return;
521
+ const published = others.find((other) => other.id === peer.of)?.tracks ?? [];
522
+ for (const [at, name] of TRACK_ORDER.entries()) {
523
+ const on = published.some((track) => track.name === name);
524
+ const transceiver = peer.transceivers[at];
525
+ if (on && transceiver && !peer.received.has(name)) {
526
+ peer.received.add(name);
527
+ ctx.arrived(peer.of, name, transceiver.receiver.track);
528
+ } else if (!on && peer.received.has(name)) {
529
+ peer.received.delete(name);
530
+ ctx.ended(peer.of, name);
531
+ }
532
+ }
533
+ }
534
+ async function send(peer) {
535
+ await gathered(peer.pc);
536
+ if (peers.get(peer.of) !== peer) return;
537
+ try {
538
+ await ctx.post("signal", {
539
+ participant: ctx.me,
540
+ to: peer.of,
541
+ sdp: sdpOf(peer.pc.localDescription)
542
+ });
543
+ } catch (error) {
544
+ if (error instanceof CallError && error.code === "not-found") return drop(peer);
545
+ throw error;
546
+ }
547
+ }
548
+ async function offer(of) {
549
+ const peer = make(of);
550
+ peer.transceivers = TRACK_ORDER.map((name) => peer.pc.addTransceiver(TRACK_KINDS[name], { direction: "sendrecv" }));
551
+ await put(peer);
552
+ await peer.pc.setLocalDescription(await peer.pc.createOffer());
553
+ await send(peer);
554
+ }
555
+ async function answer(of, sdp) {
556
+ const existing = peers.get(of);
557
+ if (existing && existing.pc.signalingState === "have-local-offer" && ctx.me < of) return;
558
+ if (existing) drop(existing);
559
+ const peer = make(of);
560
+ await peer.pc.setRemoteDescription(sdp);
561
+ const transceivers = peer.pc.getTransceivers();
562
+ if (transceivers.length < TRACK_ORDER.length) throw new CallError("invalid", `${of} offered a connection without the call's ${TRACK_ORDER.length} tracks. Is it on another version of the SDK?`);
563
+ for (const transceiver of transceivers) transceiver.direction = "sendrecv";
564
+ peer.transceivers = transceivers.slice(0, TRACK_ORDER.length);
565
+ await put(peer);
566
+ await peer.pc.setLocalDescription(await peer.pc.createAnswer());
567
+ match(peer);
568
+ await send(peer);
569
+ }
570
+ async function answered(of, sdp) {
571
+ const peer = peers.get(of);
572
+ if (!peer || peer.pc.signalingState !== "have-local-offer") return;
573
+ await peer.pc.setRemoteDescription(sdp);
574
+ match(peer);
575
+ }
576
+ const each = async (work) => {
577
+ await Promise.all([...peers.values()].filter((peer) => peer.transceivers).map(work));
578
+ };
579
+ return {
580
+ async publish(tracks) {
581
+ await each(put);
582
+ return (await ctx.post("publish", {
583
+ participant: ctx.me,
584
+ tracks: tracks.map(({ name }) => ({ name }))
585
+ })).room;
586
+ },
587
+ async replace(name, track) {
588
+ const at = TRACK_ORDER.indexOf(name);
589
+ await each(async (peer) => {
590
+ await peer.transceivers?.[at]?.sender.replaceTrack(track);
591
+ });
592
+ },
593
+ async unpublish(names) {
594
+ const room = (await ctx.post("unpublish", {
595
+ participant: ctx.me,
596
+ names
597
+ })).room;
598
+ for (const name of names) await this.replace(name, null);
599
+ return room;
600
+ },
601
+ sync(list) {
602
+ others = list;
603
+ for (const peer of [...peers.values()]) if (!list.some((other) => other.id === peer.of)) drop(peer);
604
+ for (const other of list) {
605
+ const peer = peers.get(other.id);
606
+ if (peer) match(peer);
607
+ else if (ctx.me < other.id || offerAll) offer(other.id).catch(ctx.failed);
608
+ }
609
+ offerAll = false;
610
+ },
611
+ signals(list) {
612
+ for (const signal of list) signalling = signalling.then(() => signal.sdp.type === "offer" ? answer(signal.from, signal.sdp) : answered(signal.from, signal.sdp)).catch(ctx.failed);
613
+ },
614
+ async receive(of, name) {
615
+ if (!others.some((other) => other.id === of && other.tracks.some((track) => track.name === name))) throw new CallError("not-found", `${of} publishes no ${name} in this call now.`);
616
+ },
617
+ async setLayer() {},
618
+ async stopReceiving() {},
619
+ send(text) {
620
+ for (const peer of peers.values()) channelSend(peer.channel, peer.outbox, text);
621
+ },
622
+ close() {
623
+ for (const peer of [...peers.values()]) drop(peer);
624
+ }
625
+ };
626
+ }
627
+ var LiveCall = class {
628
+ room;
629
+ options;
630
+ rtc;
631
+ state = "connecting";
632
+ error;
633
+ me;
634
+ participants = [];
635
+ local = [];
636
+ screen = {
637
+ share: () => this.share(),
638
+ stop: () => this.unshare()
639
+ };
640
+ listeners = /* @__PURE__ */ new Map();
641
+ sending = /* @__PURE__ */ new Map();
642
+ received = /* @__PURE__ */ new Map();
643
+ declined = /* @__PURE__ */ new Set();
644
+ wire = /* @__PURE__ */ new Map();
645
+ departed = /* @__PURE__ */ new Map();
646
+ meWire;
647
+ session;
648
+ credential;
649
+ renewed = false;
650
+ renewal;
651
+ shown = "";
652
+ left = false;
653
+ constructor(room, options, rtc) {
654
+ this.room = room;
655
+ this.options = options;
656
+ this.rtc = rtc;
657
+ }
658
+ async start() {
659
+ try {
660
+ const source = this.options.token;
661
+ this.credential = credentialOf(typeof source === "function" ? await source() : source);
662
+ await this.connect(false);
663
+ } catch (error) {
664
+ const refused = callErrorOf(error);
665
+ this.error = refused;
666
+ this.state = "failed";
667
+ clearTimeout(this.renewal);
668
+ throw refused;
669
+ }
670
+ }
671
+ on(event, fn) {
672
+ const set = this.listeners.get(event) ?? /* @__PURE__ */ new Set();
673
+ this.listeners.set(event, set);
674
+ set.add(fn);
675
+ return () => {
676
+ set.delete(fn);
677
+ };
678
+ }
679
+ emit(event, value) {
680
+ for (const fn of [...this.listeners.get(event) ?? []]) try {
681
+ fn(value);
682
+ } catch (error) {
683
+ queueMicrotask(() => {
684
+ throw error;
685
+ });
686
+ }
687
+ }
688
+ url() {
689
+ return (this.options.url ?? this.credential.url ?? `${platformApi()}/call/app`).replace(/\/+$/u, "");
690
+ }
691
+ post(op, body) {
692
+ return request(this.url(), this.credential.token, op, body);
693
+ }
694
+ setState(next) {
695
+ if (this.state === next || this.state === "ended" || this.state === "failed") return;
696
+ this.state = next;
697
+ this.emit("state", next);
698
+ }
699
+ /** Joins the room, and publishes again what this call published before it dropped. */
700
+ async connect(rejoining) {
701
+ const joined = await this.post("join", {});
702
+ if (this.left) return void await this.post("leave", { participant: joined.participant.id });
703
+ if (joined.room.name !== this.room) {
704
+ await this.post("leave", { participant: joined.participant.id });
705
+ throw new CallError("invalid", `This token is for the call ${joined.room.name}, not ${this.room}. Ask the app's server for a token for ${this.room}.`);
706
+ }
707
+ this.credential = {
708
+ ...this.credential,
709
+ expiresAt: joined.expiresAt
710
+ };
711
+ this.schedule();
712
+ const session = {
713
+ participant: joined.participant.id,
714
+ alive: true,
715
+ changed: -1,
716
+ ack: 0
717
+ };
718
+ const ctx = this.context(session, joined.iceServers);
719
+ session.media = joined.media === "relay" ? relayMedia(ctx, rejoining) : sfuMedia(ctx, this.options.autoVideo !== false, this.declined);
720
+ this.session = session;
721
+ this.meWire = joined.participant;
722
+ this.apply(session, joined.room);
723
+ const again = [...this.sending].map(([name, { track }]) => ({
724
+ name,
725
+ track
726
+ }));
727
+ if (again.length) {
728
+ const room = await session.media.publish(again);
729
+ for (const [name, sending] of this.sending) if (sending.muted) await session.media.replace(name, null);
730
+ if (room) this.apply(session, room);
731
+ }
732
+ this.watch(session);
733
+ }
734
+ context(session, iceServers) {
735
+ const live = () => this.session === session && session.alive;
736
+ return {
737
+ me: session.participant,
738
+ iceServers,
739
+ rtc: this.rtc,
740
+ post: (op, body) => this.post(op, body),
741
+ sending: () => [...this.sending].map(([name, { track, muted }]) => ({
742
+ name,
743
+ track: muted ? null : track
744
+ })),
745
+ arrived: (of, name, track) => {
746
+ if (!live()) return;
747
+ const tracks = this.received.get(of) ?? /* @__PURE__ */ new Map();
748
+ this.received.set(of, tracks);
749
+ tracks.set(name, track);
750
+ this.refresh();
751
+ const participant = this.snapshotOf(of);
752
+ if (participant) this.emit("track", {
753
+ participant,
754
+ name,
755
+ track
756
+ });
757
+ },
758
+ ended: (of, name) => {
759
+ if (!live()) return;
760
+ const track = this.received.get(of)?.get(name);
761
+ this.received.get(of)?.delete(name);
762
+ if (!track) return;
763
+ this.refresh();
764
+ const participant = this.snapshotOf(of);
765
+ if (participant) this.emit("track-ended", {
766
+ participant,
767
+ name,
768
+ track
769
+ });
770
+ },
771
+ message: (of, text) => {
772
+ if (!live()) return;
773
+ const from = this.snapshotOf(of);
774
+ let data;
775
+ try {
776
+ data = JSON.parse(text);
777
+ } catch {
778
+ return;
779
+ }
780
+ if (from) this.emit("data", {
781
+ from,
782
+ data
783
+ });
784
+ },
785
+ broken: () => {
786
+ if (live()) this.reconnect();
787
+ },
788
+ failed: (error) => {
789
+ if (live()) this.background(error);
790
+ }
791
+ };
792
+ }
793
+ async watch(session) {
794
+ while (session.alive && !this.left) {
795
+ let watched;
796
+ try {
797
+ watched = await this.post("watch", {
798
+ participant: session.participant,
799
+ after: session.changed,
800
+ waitMs: WATCH_WAIT_MS,
801
+ ...session.ack ? { ack: session.ack } : {}
802
+ });
803
+ } catch (error) {
804
+ if (!session.alive || this.left) return;
805
+ if (error instanceof Unreachable) this.reconnect();
806
+ else this.fail(error);
807
+ return;
808
+ }
809
+ if (!session.alive) return;
810
+ if (watched.signals.length) {
811
+ session.ack = Math.max(session.ack, ...watched.signals.map((signal) => signal.seq));
812
+ session.media.signals(watched.signals);
813
+ }
814
+ this.apply(session, watched.room);
815
+ }
816
+ }
817
+ /** Takes the room as the wire gives it: who is in it, what they publish, and the state that proves. */
818
+ apply(session, room) {
819
+ if (!session.alive || room.changed < session.changed) return;
820
+ session.changed = room.changed;
821
+ if (room.state === "ended") return this.finish();
822
+ const mine = room.participants.find((participant) => participant.id === session.participant);
823
+ if (mine) this.meWire = mine;
824
+ const others = room.participants.filter((participant) => participant.id !== session.participant && participant.state !== "left");
825
+ const before = this.wire;
826
+ this.wire = new Map(others.map((participant) => [participant.id, participant]));
827
+ this.departed = new Map([...before].filter(([id]) => !this.wire.has(id)));
828
+ session.media.sync(others);
829
+ for (const id of this.departed.keys()) this.received.delete(id);
830
+ this.departed.clear();
831
+ this.refresh();
832
+ this.setState(others.length ? "in-call" : "waiting");
833
+ }
834
+ snapshotOf(id) {
835
+ const wire = this.wire.get(id) ?? this.departed.get(id);
836
+ return wire && {
837
+ ...wire,
838
+ received: Object.fromEntries(this.received.get(id) ?? [])
839
+ };
840
+ }
841
+ /** Builds the participants anew, and says so, when anything about them changed. */
842
+ refresh() {
843
+ const me = {
844
+ ...this.meWire,
845
+ received: {}
846
+ };
847
+ const participants = [...this.wire.keys()].flatMap((id) => this.snapshotOf(id) ?? []);
848
+ const shown = JSON.stringify([me, participants.map((participant) => ({
849
+ ...participant,
850
+ received: Object.entries(participant.received).map(([name, track]) => [name, track?.id])
851
+ }))]);
852
+ if (shown === this.shown) return;
853
+ this.shown = shown;
854
+ this.me = me;
855
+ this.participants = participants;
856
+ this.emit("participants", participants);
857
+ }
858
+ showLocal() {
859
+ this.local = [...this.sending].map(([name, { track, muted }]) => ({
860
+ name,
861
+ track,
862
+ muted
863
+ }));
864
+ this.emit("local", this.local);
865
+ }
866
+ /** Ends this session's media, keeping what this call publishes for the next. */
867
+ teardown() {
868
+ const session = this.session;
869
+ if (session) {
870
+ session.alive = false;
871
+ session.media.close();
872
+ }
873
+ for (const [of, tracks] of this.received) for (const [name, track] of tracks) {
874
+ const participant = this.snapshotOf(of);
875
+ tracks.delete(name);
876
+ if (participant) this.emit("track-ended", {
877
+ participant,
878
+ name,
879
+ track
880
+ });
881
+ }
882
+ this.received.clear();
883
+ this.refresh();
884
+ }
885
+ /** Joins the room again after a drop, as the same participant, for up to 30 seconds. */
886
+ async reconnect() {
887
+ if (this.left || this.state === "reconnecting" || this.state === "ended" || this.state === "failed") return;
888
+ this.setState("reconnecting");
889
+ this.teardown();
890
+ const until = Date.now() + REJOIN_FOR_MS;
891
+ let wait = 500;
892
+ for (;;) try {
893
+ await this.freshen();
894
+ await this.connect(true);
895
+ return;
896
+ } catch (error) {
897
+ if (this.left) return;
898
+ if (!(error instanceof Unreachable)) return this.fail(error);
899
+ if (Date.now() + wait > until) return this.fail(new CallError("unavailable", "The call's connection dropped and couldn't be made again within 30 seconds. Check your network, then join again."));
900
+ await new Promise((resolve) => setTimeout(resolve, wait));
901
+ wait = Math.min(wait * 2, 4e3);
902
+ }
903
+ }
904
+ /** Asks for a new token now when this one runs out within five minutes. */
905
+ async freshen() {
906
+ const expiresAt = this.credential.expiresAt;
907
+ if (typeof this.options.token === "function" && (expiresAt === void 0 || expiresAt - Date.now() < RENEW_BEFORE_MS)) await this.renew();
908
+ }
909
+ schedule() {
910
+ clearTimeout(this.renewal);
911
+ const expiresAt = this.credential.expiresAt;
912
+ if (typeof this.options.token !== "function" || this.left || expiresAt === void 0) return;
913
+ const remaining = expiresAt - Date.now();
914
+ const delay = remaining > RENEW_BEFORE_MS ? remaining - RENEW_BEFORE_MS : this.renewed ? Math.max(remaining / 2, 0) : 0;
915
+ this.renewal = setTimeout(() => {
916
+ this.renew().catch((error) => this.background(error));
917
+ }, delay);
918
+ }
919
+ async renew() {
920
+ const source = this.options.token;
921
+ if (typeof source !== "function") return;
922
+ const next = credentialOf(await source());
923
+ if (this.left) return;
924
+ this.credential = next;
925
+ this.renewed = true;
926
+ this.schedule();
927
+ }
928
+ /** Something in the background failed: a drop joins again, an ended room ends the call, anything else is an `error` event. */
929
+ background(error) {
930
+ if (this.left || this.state === "ended" || this.state === "failed") return;
931
+ if (error instanceof Unreachable) return void this.reconnect();
932
+ const refused = callErrorOf(error);
933
+ if (refused.code === "ended") return this.finish();
934
+ this.emit("error", refused);
935
+ }
936
+ release() {
937
+ clearTimeout(this.renewal);
938
+ for (const { track, owned } of this.sending.values()) if (owned) track.stop();
939
+ this.sending.clear();
940
+ this.showLocal();
941
+ }
942
+ finish() {
943
+ if (this.state === "ended" || this.state === "failed") return;
944
+ this.teardown();
945
+ this.release();
946
+ this.setState("ended");
947
+ }
948
+ fail(error) {
949
+ const refused = callErrorOf(error);
950
+ if (refused.code === "ended") return this.finish();
951
+ if (this.state === "ended" || this.state === "failed") return;
952
+ this.teardown();
953
+ this.release();
954
+ this.error = refused;
955
+ this.setState("failed");
956
+ }
957
+ ready() {
958
+ if (this.left || this.state === "ended") throw new CallError("ended", "This call has ended.");
959
+ if (this.state === "failed") throw this.error ?? new CallError("unavailable", "This call failed. Join again.");
960
+ return this.session?.alive ? this.session : void 0;
961
+ }
962
+ devices() {
963
+ const devices = this.rtc.mediaDevices ?? globalThis.navigator?.mediaDevices;
964
+ if (!devices) throw new CallError("unavailable", "There's no camera, microphone or screen to capture here. Publish tracks of your own instead.");
965
+ return devices;
966
+ }
967
+ /** Publishes tracks, replacing any already published under the same name. */
968
+ async put(tracks) {
969
+ const session = this.ready();
970
+ const fresh = [];
971
+ for (const { name, track, owned } of tracks) {
972
+ const was = this.sending.get(name);
973
+ if (!was) {
974
+ fresh.push({
975
+ name,
976
+ track,
977
+ owned
978
+ });
979
+ continue;
980
+ }
981
+ this.sending.set(name, {
982
+ track,
983
+ owned,
984
+ muted: was.muted
985
+ });
986
+ if (session && !was.muted) await session.media.replace(name, track);
987
+ if (was.owned && was.track !== track) was.track.stop();
988
+ }
989
+ for (const { name, track, owned } of fresh) this.sending.set(name, {
990
+ track,
991
+ owned,
992
+ muted: false
993
+ });
994
+ if (session && fresh.length) try {
995
+ const room = await session.media.publish(fresh);
996
+ if (room) this.apply(session, room);
997
+ } catch (error) {
998
+ for (const { name, track, owned } of fresh) {
999
+ this.sending.delete(name);
1000
+ if (owned) track.stop();
1001
+ }
1002
+ this.showLocal();
1003
+ throw callErrorOf(error);
1004
+ }
1005
+ this.showLocal();
1006
+ }
1007
+ async publish(asked) {
1008
+ this.ready();
1009
+ const audio = asked.mic === true, video = asked.camera === true;
1010
+ let captured;
1011
+ if (audio || video) captured = await this.devices().getUserMedia({
1012
+ audio,
1013
+ video
1014
+ }).catch((error) => {
1015
+ throw new CallError(deviceRefused(error) ? "forbidden" : "unavailable", deviceRefused(error) ? "The browser didn't allow the microphone or camera. Allow them in the site's settings, then try again." : `The microphone or camera couldn't be started: ${messageOf(error)}`);
1016
+ });
1017
+ const tracks = [];
1018
+ const mic = typeof asked.mic === "object" ? asked.mic : audio ? captured?.getAudioTracks()[0] : void 0;
1019
+ const camera = typeof asked.camera === "object" ? asked.camera : video ? captured?.getVideoTracks()[0] : void 0;
1020
+ if (mic) tracks.push({
1021
+ name: "mic",
1022
+ track: mic,
1023
+ owned: mic !== asked.mic
1024
+ });
1025
+ if (camera) tracks.push({
1026
+ name: "camera",
1027
+ track: camera,
1028
+ owned: camera !== asked.camera
1029
+ });
1030
+ await this.put(tracks);
1031
+ }
1032
+ async unpublish(name) {
1033
+ await this.stop([name]);
1034
+ }
1035
+ async stop(names) {
1036
+ const session = this.ready();
1037
+ const stopping = names.filter((name) => this.sending.has(name));
1038
+ if (!stopping.length) return;
1039
+ if (session) this.apply(session, await session.media.unpublish(stopping));
1040
+ for (const name of stopping) {
1041
+ const was = this.sending.get(name);
1042
+ this.sending.delete(name);
1043
+ if (was?.owned) was.track.stop();
1044
+ }
1045
+ this.showLocal();
1046
+ }
1047
+ async mute(name) {
1048
+ await this.muting(name, true);
1049
+ }
1050
+ async unmute(name) {
1051
+ await this.muting(name, false);
1052
+ }
1053
+ async muting(name, muted) {
1054
+ const session = this.ready();
1055
+ const was = this.sending.get(name);
1056
+ if (!was || was.muted === muted) return;
1057
+ this.sending.set(name, {
1058
+ ...was,
1059
+ muted
1060
+ });
1061
+ if (session) await session.media.replace(name, muted ? null : was.track);
1062
+ this.showLocal();
1063
+ }
1064
+ async share() {
1065
+ this.ready();
1066
+ const stream = await this.devices().getDisplayMedia({
1067
+ video: true,
1068
+ audio: true
1069
+ }).catch((error) => {
1070
+ throw new CallError(deviceRefused(error) ? "forbidden" : "unavailable", deviceRefused(error) ? "Sharing the screen wasn't allowed." : `The screen couldn't be shared: ${messageOf(error)}`);
1071
+ });
1072
+ const screen = stream.getVideoTracks()[0], sound = stream.getAudioTracks()[0];
1073
+ if (!screen) throw new CallError("unavailable", "No screen was picked to share.");
1074
+ screen.addEventListener("ended", () => {
1075
+ if (this.sending.get("screen")?.track === screen) this.unshare().catch((error) => this.background(error));
1076
+ });
1077
+ await this.put([{
1078
+ name: "screen",
1079
+ track: screen,
1080
+ owned: true
1081
+ }, ...sound ? [{
1082
+ name: "screen-audio",
1083
+ track: sound,
1084
+ owned: true
1085
+ }] : []]);
1086
+ }
1087
+ async unshare() {
1088
+ await this.stop(["screen", "screen-audio"]);
1089
+ }
1090
+ media() {
1091
+ const session = this.ready();
1092
+ if (!session) throw new CallError("unavailable", "The call is joining again. Try once it's back.");
1093
+ return session.media;
1094
+ }
1095
+ async receive(participantId, name, options = {}) {
1096
+ const media = this.media();
1097
+ this.declined.delete(`${participantId}/${name}`);
1098
+ await media.receive(participantId, name, options.layer);
1099
+ }
1100
+ async setLayer(participantId, name, layer) {
1101
+ await this.media().setLayer(participantId, name, layer);
1102
+ }
1103
+ async stopReceiving(participantId, name) {
1104
+ await this.media().stopReceiving(participantId, name);
1105
+ }
1106
+ send(data) {
1107
+ const session = this.ready();
1108
+ const text = JSON.stringify(data);
1109
+ const bytes = new TextEncoder().encode(text).length;
1110
+ if (bytes > 16384) throw new CallError("invalid", sizeProblem(bytes));
1111
+ session?.media.send(text);
1112
+ }
1113
+ async leave() {
1114
+ if (this.left) return;
1115
+ const session = this.session;
1116
+ const was = this.state;
1117
+ this.left = true;
1118
+ this.teardown();
1119
+ this.release();
1120
+ this.setState("ended");
1121
+ if (session && was !== "ended" && was !== "failed") await this.post("leave", { participant: session.participant });
1122
+ }
1123
+ };
1124
+ const deviceRefused = (error) => error?.name === "NotAllowedError";
1125
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
1126
+ function callErrorOf(error) {
1127
+ if (error instanceof CallError) return error;
1128
+ return new CallError("unavailable", `The call's connection couldn't be made: ${messageOf(error)}`);
1129
+ }
1130
+ //#endregion
1131
+ export { CallError, MAX_FULL_VIDEOS, MAX_MESSAGE_BYTES, MAX_VIDEOS, callToken, identityProblem, join, roomProblem };