@zapiack/react-native 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/calls.js ADDED
@@ -0,0 +1,793 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/calls.ts
21
+ var calls_exports = {};
22
+ __export(calls_exports, {
23
+ ZapiackCall: () => ZapiackCall
24
+ });
25
+ module.exports = __toCommonJS(calls_exports);
26
+ var import_mediasoup_client = require("mediasoup-client");
27
+ var import_react_native_webrtc = require("react-native-webrtc");
28
+
29
+ // src/realtime.ts
30
+ var ZapiackRealtimeError = class extends Error {
31
+ constructor(message, code = 0, reason) {
32
+ super(message);
33
+ this.code = code;
34
+ this.reason = reason;
35
+ this.name = "ZapiackRealtimeError";
36
+ }
37
+ };
38
+ var DEFAULT_REALTIME_URL = "wss://rt.zapiack.com";
39
+ var OPEN = 1;
40
+ var MAX_OUTBOX = 100;
41
+ var browserRealtimeEnv = () => ({
42
+ socket: (url) => new globalThis.WebSocket(url),
43
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
44
+ clearTimeout: (id) => clearTimeout(id),
45
+ setInterval: (fn, ms) => setInterval(fn, ms),
46
+ clearInterval: (id) => clearInterval(id),
47
+ random: () => Math.random()
48
+ });
49
+ var after = (a, b) => {
50
+ if (!b) return true;
51
+ const [am = 0, as = 0] = a.split("-").map(Number);
52
+ const [bm = 0, bs = 0] = b.split("-").map(Number);
53
+ return am > bm || am === bm && as > bs;
54
+ };
55
+ var ZapiackRealtime = class {
56
+ constructor(options, env = browserRealtimeEnv(), now = Date.now) {
57
+ this.env = env;
58
+ this.now = now;
59
+ this.ws = null;
60
+ this._state = "idle";
61
+ this.subs = /* @__PURE__ */ new Map();
62
+ this.presenceHandlers = /* @__PURE__ */ new Map();
63
+ this.members = /* @__PURE__ */ new Map();
64
+ this.waiting = /* @__PURE__ */ new Map();
65
+ this.pending = /* @__PURE__ */ new Map();
66
+ this.rpcSeq = 0;
67
+ this.stateHandlers = /* @__PURE__ */ new Set();
68
+ this.errorHandlers = /* @__PURE__ */ new Set();
69
+ this.outbox = [];
70
+ this.attempt = 0;
71
+ this.wanted = false;
72
+ this.heard = 0;
73
+ this.ackSeq = 0;
74
+ this.first = null;
75
+ /** Set by an error the server marks fatal, for runtimes that cannot see a custom close code. */
76
+ this.refused = false;
77
+ this._connId = null;
78
+ if (typeof options?.getToken !== "function") throw new ZapiackRealtimeError("getToken is required: a function that asks your server for a token.");
79
+ this.o = { url: DEFAULT_REALTIME_URL, heartbeatMs: 25e3, backoffMs: { min: 1e3, max: 3e4 }, ackTimeoutMs: 1e4, ...options };
80
+ }
81
+ get state() {
82
+ return this._state;
83
+ }
84
+ /** This connection's id, once connected. Other members use it to signal you. */
85
+ get connectionId() {
86
+ return this._connId;
87
+ }
88
+ onState(fn) {
89
+ this.stateHandlers.add(fn);
90
+ return () => this.stateHandlers.delete(fn);
91
+ }
92
+ onError(fn) {
93
+ this.errorHandlers.add(fn);
94
+ return () => this.errorHandlers.delete(fn);
95
+ }
96
+ /** Connects and resolves once the server has said hello. It keeps itself connected afterwards until `disconnect()`. */
97
+ connect() {
98
+ if (this._state === "connected") return Promise.resolve();
99
+ if (this.first) return new Promise((resolve, reject) => this.chain(resolve, reject));
100
+ this.wanted = true;
101
+ return new Promise((resolve, reject) => {
102
+ this.first = { resolve, reject };
103
+ void this.open();
104
+ });
105
+ }
106
+ chain(resolve, reject) {
107
+ const f = this.first;
108
+ this.first = {
109
+ resolve: () => {
110
+ f.resolve();
111
+ resolve();
112
+ },
113
+ reject: (e) => {
114
+ f.reject(e);
115
+ reject(e);
116
+ }
117
+ };
118
+ }
119
+ /** Leaves for good: closes the socket, forgets the pending sends. Subscriptions stay, for a later `connect()`. */
120
+ disconnect() {
121
+ this.wanted = false;
122
+ this.env.clearTimeout(this.retry);
123
+ this.stopBeat();
124
+ const ws = this.ws;
125
+ this.ws = null;
126
+ ws?.close(1e3, "bye");
127
+ this.failAll(new ZapiackRealtimeError("Disconnected."));
128
+ this.outbox = [];
129
+ this.set("closed");
130
+ }
131
+ /** Calls `handler` for every message on the channel, now and after reconnects. Returns how to stop. */
132
+ subscribe(channel, handler, options = {}) {
133
+ let sub = this.subs.get(channel);
134
+ const fresh = !sub;
135
+ if (!sub) this.subs.set(channel, sub = { handlers: /* @__PURE__ */ new Set(), cursor: options.resumeFrom });
136
+ sub.handlers.add(handler);
137
+ if (fresh) this.send({ op: "subscribe", channel, resumeFrom: sub.cursor });
138
+ return () => {
139
+ const s = this.subs.get(channel);
140
+ if (!s) return;
141
+ s.handlers.delete(handler);
142
+ if (s.handlers.size === 0) {
143
+ this.subs.delete(channel);
144
+ this.presenceHandlers.delete(channel);
145
+ this.members.delete(channel);
146
+ this.send({ op: "unsubscribe", channel });
147
+ }
148
+ };
149
+ }
150
+ /** Sends a message. Resolves when the server confirms, unless `ack: false`. */
151
+ publish(channel, data, options = {}) {
152
+ const frame = { op: "publish", channel, event: options.event ?? "message", data, persist: options.persist === true };
153
+ if (options.ack === false) {
154
+ this.send(frame);
155
+ return Promise.resolve();
156
+ }
157
+ const ackId = `a${++this.ackSeq}`;
158
+ frame["ackId"] = ackId;
159
+ return new Promise((resolve, reject) => {
160
+ const timer = this.env.setTimeout(() => {
161
+ this.waiting.delete(ackId);
162
+ reject(new ZapiackRealtimeError("The server did not confirm in time.", 0));
163
+ }, this.o.ackTimeoutMs);
164
+ this.waiting.set(ackId, { resolve, reject, timer });
165
+ if (!this.send(frame)) {
166
+ this.settle(ackId)?.reject(new ZapiackRealtimeError("Could not send: too many messages waiting for a connection.", 429));
167
+ }
168
+ });
169
+ }
170
+ /**
171
+ * Asks a Zapiack service something over this connection and waits for the answer: the way a call client talks to the media server.
172
+ * Needs a token minted for a call. It is never queued for later: if the line is down it fails at once, because an answer to an old
173
+ * question is worse than none.
174
+ */
175
+ request(method, data = {}) {
176
+ if (!this.ws || this.ws.readyState !== OPEN || this._state !== "connected") return Promise.reject(new ZapiackRealtimeError("Not connected.", 0, "no_route"));
177
+ const correlationId = `r${++this.rpcSeq}`;
178
+ return new Promise((resolve, reject) => {
179
+ const timer = this.env.setTimeout(() => {
180
+ this.pending.delete(correlationId);
181
+ reject(new ZapiackRealtimeError("The server did not answer in time.", 0, "timeout"));
182
+ }, this.o.ackTimeoutMs + 2e3);
183
+ this.pending.set(correlationId, { resolve, reject, timer });
184
+ this.ws.send(JSON.stringify({ op: "rpc", method, correlationId, data }));
185
+ });
186
+ }
187
+ /** Sends to one connection in a channel you are subscribed to. Used for peer-to-peer setup such as WebRTC. */
188
+ signal(channel, to, event, data) {
189
+ this.send({ op: "signal", channel, to, event, data });
190
+ }
191
+ /** Presence in a channel you are subscribed to. */
192
+ presence(channel) {
193
+ return {
194
+ enter: (data = null) => this.send({ op: "presence.enter", channel, data }),
195
+ update: (data) => this.send({ op: "presence.update", channel, data }),
196
+ leave: () => this.send({ op: "presence.leave", channel }),
197
+ /** Who is here now, as last told. */
198
+ members: () => [...this.members.get(channel)?.values() ?? []],
199
+ onChange: (fn) => {
200
+ let set = this.presenceHandlers.get(channel);
201
+ if (!set) this.presenceHandlers.set(channel, set = /* @__PURE__ */ new Set());
202
+ set.add(fn);
203
+ return () => set.delete(fn);
204
+ }
205
+ };
206
+ }
207
+ // ───────────────────────────── internals
208
+ set(s) {
209
+ if (this._state === s) return;
210
+ this._state = s;
211
+ for (const fn of this.stateHandlers) fn(s);
212
+ }
213
+ fail(e) {
214
+ for (const fn of this.errorHandlers) fn(e);
215
+ }
216
+ settle(ackId) {
217
+ const w = this.waiting.get(ackId);
218
+ if (!w) return void 0;
219
+ this.waiting.delete(ackId);
220
+ this.env.clearTimeout(w.timer);
221
+ return w;
222
+ }
223
+ failAll(e) {
224
+ for (const id of [...this.waiting.keys()]) this.settle(id)?.reject(e);
225
+ this.failRequests(e);
226
+ }
227
+ failRequests(e) {
228
+ for (const [id, p] of [...this.pending]) {
229
+ this.pending.delete(id);
230
+ this.env.clearTimeout(p.timer);
231
+ p.reject(e);
232
+ }
233
+ }
234
+ /** Writes now if the line is open, otherwise keeps it (a short while) for when it is. False when there is no room. */
235
+ send(frame) {
236
+ const text = JSON.stringify(frame);
237
+ if (this.ws && this.ws.readyState === OPEN && this._state === "connected") {
238
+ this.ws.send(text);
239
+ return true;
240
+ }
241
+ if (frame["op"] === "subscribe" || frame["op"] === "unsubscribe") return true;
242
+ if (this.outbox.length >= MAX_OUTBOX) return false;
243
+ this.outbox.push(text);
244
+ return true;
245
+ }
246
+ async open() {
247
+ if (!this.wanted) return;
248
+ this.set(this.attempt === 0 && this._state !== "reconnecting" ? "connecting" : "reconnecting");
249
+ let token;
250
+ try {
251
+ token = await this.o.getToken();
252
+ if (!token || typeof token !== "string") throw new Error("getToken returned no token.");
253
+ } catch (e) {
254
+ this.fail(new ZapiackRealtimeError(`Could not get a token: ${e instanceof Error ? e.message : String(e)}`, 0));
255
+ return this.later();
256
+ }
257
+ if (!this.wanted) return;
258
+ let ws;
259
+ try {
260
+ ws = this.env.socket(`${this.o.url.replace(/\/+$/, "")}/?token=${encodeURIComponent(token)}`);
261
+ } catch (e) {
262
+ this.fail(new ZapiackRealtimeError(`Could not open the connection: ${e instanceof Error ? e.message : String(e)}`, 0));
263
+ return this.later();
264
+ }
265
+ this.ws = ws;
266
+ ws.onmessage = (ev) => this.onFrame(ws, ev.data);
267
+ ws.onerror = () => void 0;
268
+ ws.onclose = (ev) => this.onClose(ws, ev?.code ?? 1006);
269
+ }
270
+ onFrame(ws, raw) {
271
+ if (ws !== this.ws) return;
272
+ this.heard = this.now();
273
+ let f;
274
+ try {
275
+ f = JSON.parse(String(raw));
276
+ } catch {
277
+ return;
278
+ }
279
+ switch (f["op"]) {
280
+ case "hello":
281
+ this._connId = f["connId"];
282
+ this.attempt = 0;
283
+ this.set("connected");
284
+ this.rejoin();
285
+ for (const text of this.outbox.splice(0)) ws.send(text);
286
+ this.startBeat(ws);
287
+ this.first?.resolve();
288
+ this.first = null;
289
+ return;
290
+ case "message":
291
+ return this.onMessage(f);
292
+ case "ack": {
293
+ this.settle(f["ackId"])?.resolve({ msgId: f["msgId"], delivered: f["delivered"] ?? 0 });
294
+ return;
295
+ }
296
+ case "rpc.result":
297
+ case "rpc.error": {
298
+ const id = String(f["correlationId"]);
299
+ const p = this.pending.get(id);
300
+ if (!p) return;
301
+ this.pending.delete(id);
302
+ this.env.clearTimeout(p.timer);
303
+ if (f["op"] === "rpc.result") p.resolve(f["data"]);
304
+ else p.reject(new ZapiackRealtimeError(String(f["message"] ?? "The request failed."), 0, String(f["code"] ?? "internal")));
305
+ return;
306
+ }
307
+ case "error": {
308
+ if (f["fatal"] === true) this.refused = true;
309
+ const err = new ZapiackRealtimeError(String(f["message"] ?? "Error"), Number(f["code"] ?? 0));
310
+ const ref = typeof f["ref"] === "string" ? f["ref"] : void 0;
311
+ if (ref && this.settle(ref)?.reject(err)) return;
312
+ return this.fail(err);
313
+ }
314
+ case "presence.members": {
315
+ const map = /* @__PURE__ */ new Map();
316
+ for (const m of f["members"] ?? []) map.set(m.connId, m);
317
+ this.members.set(f["channel"], map);
318
+ return;
319
+ }
320
+ case "resume.failed":
321
+ return this.fail(new ZapiackRealtimeError(`Missed messages on ${f["channel"]} could not be replayed. Reload its history.`, 410));
322
+ }
323
+ }
324
+ onMessage(m) {
325
+ if (m.event.startsWith("presence.")) return this.onPresence(m);
326
+ const sub = this.subs.get(m.channel);
327
+ if (!sub) return;
328
+ if (m.persisted) {
329
+ if (!after(m.msgId, sub.cursor)) return;
330
+ sub.cursor = m.msgId;
331
+ }
332
+ for (const h of [...sub.handlers]) {
333
+ try {
334
+ h(m);
335
+ } catch {
336
+ }
337
+ }
338
+ }
339
+ onPresence(m) {
340
+ const d = m.data;
341
+ const action = m.event.slice("presence.".length);
342
+ const map = this.members.get(m.channel) ?? /* @__PURE__ */ new Map();
343
+ this.members.set(m.channel, map);
344
+ if (action === "leave") map.delete(d.connId);
345
+ else map.set(d.connId, { connId: d.connId, user: d.user, data: d.data, at: m.ts });
346
+ for (const fn of this.presenceHandlers.get(m.channel) ?? []) fn({ action, member: { connId: d.connId, user: d.user, data: d.data } });
347
+ }
348
+ rejoin() {
349
+ for (const [channel, sub] of this.subs) this.ws?.send(JSON.stringify({ op: "subscribe", channel, resumeFrom: sub.cursor }));
350
+ }
351
+ startBeat(ws) {
352
+ this.stopBeat();
353
+ this.heard = this.now();
354
+ this.beat = this.env.setInterval(() => {
355
+ if (ws !== this.ws) return;
356
+ if (this.now() - this.heard > this.o.heartbeatMs * 2) return void ws.close(4e3, "no heartbeat");
357
+ if (ws.readyState === OPEN) ws.send('{"op":"ping"}');
358
+ }, this.o.heartbeatMs);
359
+ }
360
+ stopBeat() {
361
+ this.env.clearInterval(this.beat);
362
+ this.beat = void 0;
363
+ }
364
+ onClose(ws, code) {
365
+ if (ws !== this.ws) return;
366
+ this.ws = null;
367
+ this.stopBeat();
368
+ this._connId = null;
369
+ this.failRequests(new ZapiackRealtimeError("The connection dropped.", 0, "no_route"));
370
+ if (!this.wanted) return;
371
+ if (code === 4403 || this.refused) {
372
+ this.refused = false;
373
+ this.wanted = false;
374
+ this.failAll(new ZapiackRealtimeError("The project does not allow this connection.", 403));
375
+ this.first?.reject(new ZapiackRealtimeError("The project does not allow this connection.", 403));
376
+ this.first = null;
377
+ this.set("closed");
378
+ return;
379
+ }
380
+ this.set("reconnecting");
381
+ this.later(code === 4401 || code === 1012 ? 0 : void 0);
382
+ }
383
+ later(force) {
384
+ this.env.clearTimeout(this.retry);
385
+ this.attempt += 1;
386
+ const { min, max } = this.o.backoffMs;
387
+ const ceiling = Math.min(max, min * 2 ** (this.attempt - 1));
388
+ const wait = force ?? Math.round(min + this.env.random() * (ceiling - min));
389
+ this.set("reconnecting");
390
+ this.retry = this.env.setTimeout(() => void this.open(), wait);
391
+ }
392
+ };
393
+
394
+ // src/calls.ts
395
+ var ZapiackCall = class {
396
+ constructor(options, env = {}) {
397
+ this.options = options;
398
+ this.env = env;
399
+ this.listeners = /* @__PURE__ */ new Map();
400
+ this.sendT = null;
401
+ this.recvT = null;
402
+ this.producers = /* @__PURE__ */ new Map();
403
+ /** Everything being received, by the sender's track id. */
404
+ this.consumers = /* @__PURE__ */ new Map();
405
+ this.peers = /* @__PURE__ */ new Map();
406
+ this.joinedReply = null;
407
+ this.roomChannel = null;
408
+ this.stopRoom = null;
409
+ this.stopState = null;
410
+ this._state = "idle";
411
+ /** Tracks being fetched right now, so two events for the same track do not make two consumers. */
412
+ this.fetching = /* @__PURE__ */ new Set();
413
+ this.wasConnected = false;
414
+ this.resyncing = false;
415
+ this.resyncTimer = null;
416
+ this.speaker = false;
417
+ /** A transport that went `disconnected` gets a few seconds to recover by itself before its path is restarted. */
418
+ this.lapse = /* @__PURE__ */ new Map();
419
+ this.facing = options?.camera ?? "user";
420
+ if (typeof options?.getToken !== "function") throw new ZapiackRealtimeError("getToken is required: a function that asks your server for a call token.");
421
+ this.rt = env.realtime ?? new ZapiackRealtime({ getToken: options.getToken, url: options.url }, env.realtimeEnv);
422
+ if (!env.device && typeof globalThis.RTCPeerConnection === "undefined") (0, import_react_native_webrtc.registerGlobals)();
423
+ this.device = env.device ? env.device() : new import_mediasoup_client.Device({ handlerName: "ReactNative106" });
424
+ }
425
+ get state() {
426
+ return this._state;
427
+ }
428
+ /** What this person may do in the room: `listener` can only receive. */
429
+ get role() {
430
+ return this.joinedReply?.role ?? null;
431
+ }
432
+ get roomId() {
433
+ return this.joinedReply?.roomId ?? null;
434
+ }
435
+ /** Who else is in the room now. */
436
+ get members() {
437
+ return [...this.peers.values()];
438
+ }
439
+ /** The tracks this person is sending now. */
440
+ get sending() {
441
+ return [...this.producers.keys()];
442
+ }
443
+ on(event, fn) {
444
+ let set = this.listeners.get(event);
445
+ if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
446
+ set.add(fn);
447
+ return () => set.delete(fn);
448
+ }
449
+ emit(event, data) {
450
+ for (const fn of [...this.listeners.get(event) ?? []]) {
451
+ try {
452
+ fn(data);
453
+ } catch {
454
+ }
455
+ }
456
+ }
457
+ /** Connects, joins the room the token is for, and starts receiving what the others are sending. */
458
+ async join() {
459
+ if (this._state === "joined") return { role: this.joinedReply.role, roomId: this.joinedReply.roomId, members: this.members };
460
+ this._state = "joining";
461
+ try {
462
+ await this.rt.connect();
463
+ const reply = await this.rt.request("media.join", {});
464
+ this.joinedReply = reply;
465
+ if (!this.device.loaded) await this.device.load({ routerRtpCapabilities: reply.routerRtpCapabilities });
466
+ this.roomChannel = `call:${reply.roomId}`;
467
+ this.stopRoom = this.rt.subscribe(this.roomChannel, (m) => this.onRoomEvent(m));
468
+ this.stopState = this.rt.onState((s) => void this.onLine(s));
469
+ this.wasConnected = true;
470
+ this.options.audioSession?.start({ media: "video" });
471
+ if (this.speaker) this.options.audioSession?.setSpeaker(true);
472
+ const fresh = await this.rt.request("media.join", {});
473
+ await this.reconcile(fresh.peers);
474
+ this._state = "joined";
475
+ this.startResync();
476
+ return { role: reply.role, roomId: reply.roomId, members: this.members };
477
+ } catch (e) {
478
+ await this.teardown();
479
+ this._state = "closed";
480
+ throw e;
481
+ }
482
+ }
483
+ /** Turns the microphone on and sends it. Pass your own track to send something else. */
484
+ async enableMicrophone(track) {
485
+ const t = track ?? (await this.userMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } })).getAudioTracks()[0];
486
+ if (!t) throw new ZapiackRealtimeError("No microphone was found.");
487
+ await this.send("audio", t);
488
+ return t;
489
+ }
490
+ /** Turns the camera on and sends it. Opens the camera set by the `camera` option, front by default. */
491
+ async enableCamera(track) {
492
+ const t = track ?? (await this.userMedia({ video: { facingMode: this.facing, width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } } })).getVideoTracks()[0];
493
+ if (!t) throw new ZapiackRealtimeError("No camera was found.");
494
+ await this.send("video", t);
495
+ return t;
496
+ }
497
+ /**
498
+ * Shares the phone's screen. Android needs a foreground service for screen capture and iOS needs a broadcast extension: see
499
+ * react-native-webrtc's screen sharing guide. Stops by itself when the person stops sharing.
500
+ */
501
+ async shareScreen(track) {
502
+ const t = track ?? (await this.displayMedia()).getVideoTracks()[0];
503
+ if (!t) throw new ZapiackRealtimeError("No screen was chosen.");
504
+ t.addEventListener("ended", () => void this.stop("screen"));
505
+ await this.send("screen", t);
506
+ return t;
507
+ }
508
+ /** Mutes or unmutes what is being sent. Nothing is sent while muted, and the others are told. */
509
+ async setMuted(source, muted) {
510
+ const p = this.producers.get(source);
511
+ if (!p) return;
512
+ if (muted) p.pause();
513
+ else p.resume();
514
+ await this.rt.request(muted ? "media.pauseProducer" : "media.resumeProducer", { producerId: p.id });
515
+ }
516
+ /** Flips between the front and back camera while the camera is on, without interrupting what is being sent. */
517
+ switchCamera() {
518
+ const p = this.producers.get("video");
519
+ if (!p?.track) throw new ZapiackRealtimeError("The camera is not on.");
520
+ p.track._switchCamera();
521
+ this.facing = this.facing === "user" ? "environment" : "user";
522
+ }
523
+ /** Plays sound through the loudspeaker (true) or the earpiece (false). Needs an `audioSession` option; remembered across a reconnect. */
524
+ setSpeaker(on) {
525
+ this.speaker = on;
526
+ this.options.audioSession?.setSpeaker(on);
527
+ }
528
+ isMuted(source) {
529
+ return this.producers.get(source)?.paused ?? false;
530
+ }
531
+ /** Stops sending a track and lets go of the device (the camera light goes off). */
532
+ async stop(source) {
533
+ const p = this.producers.get(source);
534
+ if (!p) return;
535
+ this.producers.delete(source);
536
+ const track = p.track;
537
+ p.close();
538
+ track?.stop();
539
+ await this.rt.request("media.closeProducer", { producerId: p.id }).catch(() => void 0);
540
+ }
541
+ /**
542
+ * What is arriving now, one entry per track being received: how many bytes and packets, how many were lost, and the jitter in
543
+ * seconds. For a quality indicator, or to see that media is really flowing.
544
+ */
545
+ async stats() {
546
+ const out = [];
547
+ for (const [, c] of this.consumers) {
548
+ const report = await c.consumer.getStats();
549
+ let bytes = 0, packets = 0, lost = 0, jitter = 0;
550
+ report.forEach((r) => {
551
+ if (r["type"] !== "inbound-rtp") return;
552
+ bytes += Number(r["bytesReceived"] ?? 0);
553
+ packets += Number(r["packetsReceived"] ?? 0);
554
+ lost += Number(r["packetsLost"] ?? 0);
555
+ jitter = Math.max(jitter, Number(r["jitter"] ?? 0));
556
+ });
557
+ out.push({ identity: c.identity, source: c.source, bytesReceived: bytes, packetsReceived: packets, packetsLost: lost, jitter });
558
+ }
559
+ return out;
560
+ }
561
+ /** Leaves the room and lets go of the camera, the microphone and the connection. */
562
+ async leave() {
563
+ if (this._state === "closed" || this._state === "idle") return;
564
+ await this.rt.request("media.leave", {}).catch(() => void 0);
565
+ await this.teardown();
566
+ this._state = "closed";
567
+ }
568
+ // ───────────────────────────── sending
569
+ userMedia(c) {
570
+ const fn = this.env.getUserMedia ?? ((x) => import_react_native_webrtc.mediaDevices.getUserMedia(x));
571
+ return fn(c);
572
+ }
573
+ displayMedia() {
574
+ const fn = this.env.getDisplayMedia ?? (() => import_react_native_webrtc.mediaDevices.getDisplayMedia({}));
575
+ return fn();
576
+ }
577
+ async transport(direction) {
578
+ const held = direction === "send" ? this.sendT : this.recvT;
579
+ if (held && !held.closed) return held;
580
+ const info = await this.rt.request("media.createTransport", { direction });
581
+ const opts = { ...info, iceServers: this.joinedReply?.iceServers ?? [], iceTransportPolicy: this.options.forceTcp ? "relay" : "all" };
582
+ const t = direction === "send" ? this.device.createSendTransport(opts) : this.device.createRecvTransport(opts);
583
+ t.on("connect", ({ dtlsParameters }, ok, fail) => {
584
+ this.rt.request("media.connectTransport", { transportId: t.id, dtlsParameters }).then(() => ok(), fail);
585
+ });
586
+ if (direction === "send") {
587
+ t.on("produce", ({ kind, rtpParameters, appData }, ok, fail) => {
588
+ const source = appData.source ?? kind;
589
+ this.rt.request("media.produce", { transportId: t.id, kind: source, rtpParameters }).then((r) => ok({ id: r.id }), fail);
590
+ });
591
+ }
592
+ t.on("connectionstatechange", (s) => {
593
+ const timers = { set: this.env.setTimeout ?? ((fn, ms) => setTimeout(fn, ms)), clear: this.env.clearTimeout ?? ((id) => clearTimeout(id)) };
594
+ const pending = this.lapse.get(t.id);
595
+ if (pending !== void 0) {
596
+ timers.clear(pending);
597
+ this.lapse.delete(t.id);
598
+ }
599
+ if (s === "failed") void this.restartIce(t);
600
+ else if (s === "disconnected") {
601
+ this.lapse.set(t.id, timers.set(() => {
602
+ this.lapse.delete(t.id);
603
+ if (!t.closed) void this.restartIce(t);
604
+ }, 4e3));
605
+ }
606
+ });
607
+ if (direction === "send") this.sendT = t;
608
+ else this.recvT = t;
609
+ return t;
610
+ }
611
+ async restartIce(t) {
612
+ try {
613
+ const { iceParameters } = await this.rt.request("media.restartIce", { transportId: t.id });
614
+ await t.restartIce({ iceParameters });
615
+ } catch (e) {
616
+ this.emit("error", e instanceof ZapiackRealtimeError ? e : new ZapiackRealtimeError(String(e)));
617
+ }
618
+ }
619
+ async send(source, track) {
620
+ if (this._state !== "joined") throw new ZapiackRealtimeError("Join the call first.");
621
+ if (this.joinedReply?.role === "listener") throw new ZapiackRealtimeError("Your role in this call can only listen.", 0, "forbidden");
622
+ if (this.producers.has(source)) await this.stop(source);
623
+ const t = await this.transport("send");
624
+ const encodings = source === "audio" ? [{ maxBitrate: 64e3 }] : source === "screen" ? [{ maxBitrate: 25e5 }] : [{ maxBitrate: 12e5 }];
625
+ const producer = await t.produce({ track, encodings, appData: { source }, ...source === "audio" ? { codecOptions: { opusDtx: true, opusFec: true } } : {} });
626
+ producer.on("trackended", () => void this.stop(source));
627
+ this.producers.set(source, producer);
628
+ }
629
+ // ───────────────────────────── receiving
630
+ async reconcile(peers) {
631
+ const here = new Set(peers.map((p) => p.identity));
632
+ for (const p of peers) {
633
+ if (!this.peers.has(p.identity)) {
634
+ this.peers.set(p.identity, { identity: p.identity, role: p.role });
635
+ this.emit("peerJoined", { identity: p.identity, role: p.role });
636
+ }
637
+ }
638
+ for (const id of [...this.peers.keys()]) {
639
+ if (!here.has(id)) {
640
+ this.peers.delete(id);
641
+ this.dropFrom(id);
642
+ this.emit("peerLeft", { identity: id });
643
+ }
644
+ }
645
+ const live = new Set(peers.flatMap((p) => p.producers.map((x) => x.id)));
646
+ for (const [producerId, c] of [...this.consumers]) {
647
+ if (!live.has(producerId)) this.endTrack(producerId, c.identity, c.source);
648
+ }
649
+ for (const p of peers) for (const pr of p.producers) await this.consume(pr.id, p.identity, pr.kind, pr.paused);
650
+ }
651
+ async consume(producerId, identity, kind, paused = false) {
652
+ if (this.consumers.has(producerId) || this.fetching.has(producerId)) return;
653
+ this.fetching.add(producerId);
654
+ try {
655
+ const t = await this.transport("recv");
656
+ const r = await this.rt.request("media.consume", { producerId, rtpCapabilities: this.device.rtpCapabilities });
657
+ const consumer = await t.consume({ id: r.id, producerId: r.producerId, kind: r.kind, rtpParameters: r.rtpParameters, appData: { source: r.source } });
658
+ this.consumers.set(producerId, { consumer, identity: r.identity, source: r.source });
659
+ await this.rt.request("media.resumeConsumer", { consumerId: consumer.id });
660
+ const stream = this.env.newStream ? this.env.newStream([consumer.track]) : new import_react_native_webrtc.MediaStream([consumer.track]);
661
+ this.emit("track", { identity: r.identity, source: r.source, track: consumer.track, stream, producerId });
662
+ if (paused) this.emit("paused", { identity: r.identity, source: r.source, producerId, paused: true });
663
+ consumer.on("transportclose", () => this.endTrack(producerId, r.identity, r.source));
664
+ } catch (e) {
665
+ this.emit("error", e instanceof ZapiackRealtimeError ? e : new ZapiackRealtimeError(`Could not play ${identity}'s ${kind}: ${e instanceof Error ? e.message : String(e)}`));
666
+ } finally {
667
+ this.fetching.delete(producerId);
668
+ }
669
+ }
670
+ endTrack(producerId, identity, source) {
671
+ const c = this.consumers.get(producerId);
672
+ if (!c) return;
673
+ this.consumers.delete(producerId);
674
+ c.consumer.close();
675
+ this.emit("trackEnded", { identity, source, producerId });
676
+ }
677
+ dropFrom(identity) {
678
+ for (const [producerId, c] of [...this.consumers]) if (c.identity === identity) this.endTrack(producerId, c.identity, c.source);
679
+ }
680
+ onRoomEvent(m) {
681
+ const d = m.data ?? {};
682
+ switch (m.event) {
683
+ case "peerJoined":
684
+ if (d["identity"] && d["identity"] !== this.identity() && !this.peers.has(d["identity"])) {
685
+ this.peers.set(d["identity"], { identity: d["identity"], role: d["role"] });
686
+ this.emit("peerJoined", { identity: d["identity"], role: d["role"] });
687
+ }
688
+ return;
689
+ case "peerLeft":
690
+ if (this.peers.delete(d["identity"])) {
691
+ this.dropFrom(d["identity"]);
692
+ this.emit("peerLeft", { identity: d["identity"] });
693
+ }
694
+ return;
695
+ case "newProducer":
696
+ if (d["identity"] !== this.identity()) void this.consume(d["producerId"], d["identity"], d["kind"]);
697
+ return;
698
+ case "producerClosed": {
699
+ const c = this.consumers.get(d["producerId"]);
700
+ if (c) this.endTrack(d["producerId"], c.identity, c.source);
701
+ return;
702
+ }
703
+ case "producerPaused": {
704
+ const c = this.consumers.get(d["producerId"]);
705
+ if (c) this.emit("paused", { identity: c.identity, source: c.source, producerId: d["producerId"], paused: d["paused"] === true });
706
+ return;
707
+ }
708
+ case "roomEnded":
709
+ case "roomEnding":
710
+ void this.teardown().then(() => {
711
+ this._state = "closed";
712
+ this.emit("ended", { reason: String(d["reason"] ?? "ended") });
713
+ });
714
+ return;
715
+ }
716
+ }
717
+ /** Who this person is in the room, as the server knows them: events about this name are about us. */
718
+ identity() {
719
+ return this.joinedReply?.identity ?? null;
720
+ }
721
+ // ───────────────────────────── the line coming and going
722
+ /**
723
+ * Room events travel over best-effort publish and subscribe, so a client does not rely on every one arriving: now and then it asks the
724
+ * server who is in the room and what they are sending, and catches up on anything it missed.
725
+ */
726
+ startResync() {
727
+ const every = this.options.resyncMs ?? 3e4;
728
+ if (this.resyncTimer || every <= 0) return;
729
+ this.resyncTimer = setInterval(() => void this.resync(), every);
730
+ }
731
+ async resync() {
732
+ if (this._state !== "joined" || this.resyncing) return;
733
+ this.resyncing = true;
734
+ try {
735
+ const fresh = await this.rt.request("media.join", {});
736
+ if (this._state === "joined") await this.reconcile(fresh.peers);
737
+ } catch {
738
+ } finally {
739
+ this.resyncing = false;
740
+ }
741
+ }
742
+ /** The socket dropped and came back: take the place in the room again and see what changed while away. */
743
+ async onLine(s) {
744
+ if (s === "reconnecting" && this._state === "joined") this._state = "reconnecting";
745
+ if (s === "closed" && this._state !== "closed" && this._state !== "idle") {
746
+ await this.teardown();
747
+ this._state = "closed";
748
+ this.emit("ended", { reason: "disconnected" });
749
+ return;
750
+ }
751
+ if (s !== "connected" || !this.wasConnected || this._state !== "reconnecting" || this.resyncing) return;
752
+ this.resyncing = true;
753
+ try {
754
+ const fresh = await this.rt.request("media.join", {});
755
+ this._state = "joined";
756
+ for (const t of [this.sendT, this.recvT]) if (t && !t.closed) await this.restartIce(t);
757
+ await this.reconcile(fresh.peers);
758
+ } catch (e) {
759
+ await this.teardown();
760
+ this._state = "closed";
761
+ this.emit("ended", { reason: e instanceof ZapiackRealtimeError && e.reason ? e.reason : "rejoin_failed" });
762
+ } finally {
763
+ this.resyncing = false;
764
+ }
765
+ }
766
+ async teardown() {
767
+ if (this.resyncTimer) clearInterval(this.resyncTimer);
768
+ this.resyncTimer = null;
769
+ const clear = this.env.clearTimeout ?? ((id) => clearTimeout(id));
770
+ for (const id of this.lapse.values()) clear(id);
771
+ this.lapse.clear();
772
+ this.options.audioSession?.stop();
773
+ this.stopState?.();
774
+ this.stopRoom?.();
775
+ this.stopState = this.stopRoom = null;
776
+ for (const p of this.producers.values()) {
777
+ p.track?.stop();
778
+ p.close();
779
+ }
780
+ this.producers.clear();
781
+ for (const c of this.consumers.values()) c.consumer.close();
782
+ this.consumers.clear();
783
+ this.sendT?.close();
784
+ this.recvT?.close();
785
+ this.sendT = this.recvT = null;
786
+ this.peers.clear();
787
+ this.rt.disconnect();
788
+ }
789
+ };
790
+ // Annotate the CommonJS export names for ESM import in node:
791
+ 0 && (module.exports = {
792
+ ZapiackCall
793
+ });