@poolse/sdk 2.9.0 → 2.10.1

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/index.js CHANGED
@@ -104,6 +104,9 @@ var AuthError = class extends ApiError {
104
104
  };
105
105
 
106
106
  // src/voice/calls.ts
107
+ function toMedia(value) {
108
+ return value === "video" ? "video" : "audio";
109
+ }
107
110
  var CallsResource = class {
108
111
  /** Resolves the user channel lazily — it may not be joined yet. */
109
112
  getChannel;
@@ -123,13 +126,18 @@ var CallsResource = class {
123
126
  * has fanned the invite out, with the minted call id and who was rung
124
127
  * — not when anyone answers; that arrives via {@link onAccepted}.
125
128
  */
126
- invite(conversationId) {
129
+ invite(conversationId, media = "audio") {
127
130
  return this.request("call:invite", {
128
- conversation_id: conversationId
131
+ conversation_id: conversationId,
132
+ media
129
133
  }).then((reply) => ({
130
134
  callId: reply.call_id,
131
135
  conversationId: reply.conversation_id,
132
- calleeUserIds: reply.callee_user_ids ?? []
136
+ calleeUserIds: reply.callee_user_ids ?? [],
137
+ // Echoed by the server rather than assumed, so an older deployment
138
+ // that ignores the field is reflected honestly instead of leaving
139
+ // the UI promising video it will not get.
140
+ media: toMedia(reply.media)
133
141
  }));
134
142
  }
135
143
  /**
@@ -236,7 +244,8 @@ var CallsResource = class {
236
244
  const call = {
237
245
  callId: p.call_id,
238
246
  conversationId: p.conversation_id,
239
- callerUserId: p.caller_user_id
247
+ callerUserId: p.caller_user_id,
248
+ media: toMedia(p.media)
240
249
  };
241
250
  this.incoming.forEach((l) => l(call));
242
251
  });
@@ -1620,6 +1629,248 @@ var UsersResource = class {
1620
1629
  }
1621
1630
  };
1622
1631
 
1632
+ // src/resources/call-tokens.ts
1633
+ var CallTokensResource = class {
1634
+ constructor(client) {
1635
+ this.client = client;
1636
+ }
1637
+ client;
1638
+ /**
1639
+ * POST /v1/conversations/:conversationId/call-token
1640
+ *
1641
+ * Resolves `null` when the deployment has no SFU configured (503).
1642
+ * That is deliberately not an error — the caller falls back to the
1643
+ * peer-to-peer mesh, which is how every call worked before the SFU
1644
+ * existed. A 403 still throws: that one really is a refusal.
1645
+ */
1646
+ async create(conversationId, signal) {
1647
+ try {
1648
+ return await this.client.request({
1649
+ method: "POST",
1650
+ path: `/v1/conversations/${encodeURIComponent(conversationId)}/call-token`,
1651
+ ...signal ? { signal } : {}
1652
+ });
1653
+ } catch (err) {
1654
+ if (err instanceof ApiError && err.status === 503) return null;
1655
+ throw err;
1656
+ }
1657
+ }
1658
+ };
1659
+
1660
+ // src/voice/call-room.ts
1661
+ var CallRoom = class {
1662
+ livekit;
1663
+ tokenProvider;
1664
+ startWithVideo;
1665
+ startMuted;
1666
+ room = null;
1667
+ status = "idle";
1668
+ selfId = null;
1669
+ // Reference counted like VoiceRoom: a call screen and a roster can
1670
+ // both hold the same call, and the second holder must not open a
1671
+ // second SFU connection or tear the first one down on leaving.
1672
+ holders = 0;
1673
+ statusListeners = /* @__PURE__ */ new Set();
1674
+ participantListeners = /* @__PURE__ */ new Set();
1675
+ errorListeners = /* @__PURE__ */ new Set();
1676
+ /** Bound once so `off()` in teardown removes the same references. */
1677
+ onRoomChange = () => this.emitParticipants();
1678
+ constructor(opts) {
1679
+ this.livekit = opts.livekit;
1680
+ this.tokenProvider = opts.tokenProvider;
1681
+ this.startWithVideo = opts.video ?? false;
1682
+ this.startMuted = opts.muted ?? false;
1683
+ }
1684
+ // ── observation ─────────────────────────────────────────────────────
1685
+ getStatus() {
1686
+ return this.status;
1687
+ }
1688
+ onStatus(fn) {
1689
+ this.statusListeners.add(fn);
1690
+ return () => this.statusListeners.delete(fn);
1691
+ }
1692
+ onParticipants(fn) {
1693
+ this.participantListeners.add(fn);
1694
+ return () => this.participantListeners.delete(fn);
1695
+ }
1696
+ onError(fn) {
1697
+ this.errorListeners.add(fn);
1698
+ return () => this.errorListeners.delete(fn);
1699
+ }
1700
+ getParticipants() {
1701
+ if (!this.room) return [];
1702
+ const self = this.toParticipant(this.room.localParticipant, true);
1703
+ const others = [...this.room.remoteParticipants.values()].map(
1704
+ (p) => this.toParticipant(p, false)
1705
+ );
1706
+ return [self, ...others];
1707
+ }
1708
+ // ── lifecycle ───────────────────────────────────────────────────────
1709
+ /**
1710
+ * Connect to the SFU.
1711
+ *
1712
+ * Resolves `true` once media is flowing, `false` when the deployment
1713
+ * has no SFU — the caller should fall back to the mesh rather than
1714
+ * treat that as a failed call.
1715
+ */
1716
+ async join() {
1717
+ if (this.room) {
1718
+ this.holders += 1;
1719
+ return true;
1720
+ }
1721
+ this.holders += 1;
1722
+ this.setStatus("connecting");
1723
+ let connection;
1724
+ try {
1725
+ connection = await this.tokenProvider();
1726
+ } catch (err) {
1727
+ this.holders = Math.max(0, this.holders - 1);
1728
+ this.setStatus("error");
1729
+ const error = new Error(`call token unavailable: ${String(err)}`);
1730
+ this.emitError(error);
1731
+ throw error;
1732
+ }
1733
+ if (!connection) {
1734
+ this.holders = Math.max(0, this.holders - 1);
1735
+ this.setStatus("idle");
1736
+ return false;
1737
+ }
1738
+ const room = new this.livekit.Room({
1739
+ // Let LiveKit drop video layers before it drops the call. On a
1740
+ // phone leaving wifi this is the difference between the picture
1741
+ // degrading and the call ending.
1742
+ adaptiveStream: true,
1743
+ dynacast: true
1744
+ });
1745
+ this.room = room;
1746
+ this.bind(room);
1747
+ try {
1748
+ await room.connect(connection.url, connection.token);
1749
+ this.selfId = room.localParticipant.identity;
1750
+ await room.localParticipant.setMicrophoneEnabled(!this.startMuted);
1751
+ if (this.startWithVideo) await room.localParticipant.setCameraEnabled(true);
1752
+ this.setStatus("connected");
1753
+ this.emitParticipants();
1754
+ return true;
1755
+ } catch (err) {
1756
+ this.holders = Math.max(0, this.holders - 1);
1757
+ this.setStatus("error");
1758
+ const error = new Error(`call media failed: ${String(err)}`);
1759
+ this.emitError(error);
1760
+ await this.teardown();
1761
+ throw error;
1762
+ }
1763
+ }
1764
+ /** Release one holder; disconnects once none are left. */
1765
+ leave() {
1766
+ this.holders = Math.max(0, this.holders - 1);
1767
+ if (this.holders > 0) return;
1768
+ void this.teardown();
1769
+ }
1770
+ // ── media controls ──────────────────────────────────────────────────
1771
+ /**
1772
+ * Turn the camera on or off mid-call.
1773
+ *
1774
+ * Off genuinely stops publishing rather than sending black frames, so
1775
+ * the capture indicator goes out and the uplink is freed. LiveKit
1776
+ * renegotiates underneath.
1777
+ */
1778
+ async setCameraEnabled(enabled) {
1779
+ await this.withLocal((local) => local.setCameraEnabled(enabled), "camera");
1780
+ }
1781
+ /** Mute or unmute the microphone. */
1782
+ async setMicrophoneEnabled(enabled) {
1783
+ await this.withLocal((local) => local.setMicrophoneEnabled(enabled), "microphone");
1784
+ }
1785
+ isCameraEnabled() {
1786
+ return this.room?.localParticipant.isCameraEnabled ?? false;
1787
+ }
1788
+ isMicrophoneEnabled() {
1789
+ return this.room?.localParticipant.isMicrophoneEnabled ?? false;
1790
+ }
1791
+ // ── internals ───────────────────────────────────────────────────────
1792
+ async withLocal(fn, what) {
1793
+ const room = this.room;
1794
+ if (!room) return;
1795
+ try {
1796
+ await fn(room.localParticipant);
1797
+ this.emitParticipants();
1798
+ } catch (err) {
1799
+ this.emitError(new Error(`could not change ${what}: ${String(err)}`));
1800
+ }
1801
+ }
1802
+ bind(room) {
1803
+ const { RoomEvent } = this.livekit;
1804
+ for (const event of [
1805
+ RoomEvent["ParticipantConnected"],
1806
+ RoomEvent["ParticipantDisconnected"],
1807
+ RoomEvent["TrackSubscribed"],
1808
+ RoomEvent["TrackUnsubscribed"],
1809
+ RoomEvent["TrackMuted"],
1810
+ RoomEvent["TrackUnmuted"],
1811
+ RoomEvent["LocalTrackPublished"],
1812
+ RoomEvent["LocalTrackUnpublished"],
1813
+ RoomEvent["ActiveSpeakersChanged"],
1814
+ RoomEvent["ParticipantNameChanged"]
1815
+ ]) {
1816
+ if (event) room.on(event, this.onRoomChange);
1817
+ }
1818
+ const disconnected = RoomEvent["Disconnected"];
1819
+ if (disconnected) {
1820
+ room.on(disconnected, () => {
1821
+ this.setStatus("idle");
1822
+ this.emitParticipants();
1823
+ });
1824
+ }
1825
+ }
1826
+ toParticipant(participant, isSelf) {
1827
+ const cameraSource = this.livekit.Track.Source["Camera"] ?? "camera";
1828
+ const publication = participant.getTrackPublication(cameraSource);
1829
+ const live = publication && !publication.isMuted && publication.track ? publication : null;
1830
+ const videoTrack = live?.track ?? null;
1831
+ return {
1832
+ userId: participant.identity,
1833
+ name: participant.name,
1834
+ isSelf,
1835
+ micEnabled: participant.isMicrophoneEnabled ?? false,
1836
+ cameraEnabled: participant.isCameraEnabled ?? false,
1837
+ speaking: participant.isSpeaking ?? false,
1838
+ videoTrack,
1839
+ videoTrackRef: live ? { participant, publication: live, source: cameraSource } : null
1840
+ };
1841
+ }
1842
+ async teardown() {
1843
+ const room = this.room;
1844
+ this.room = null;
1845
+ this.selfId = null;
1846
+ this.holders = 0;
1847
+ if (room) {
1848
+ try {
1849
+ await room.disconnect();
1850
+ } catch {
1851
+ }
1852
+ }
1853
+ this.setStatus("idle");
1854
+ this.emitParticipants();
1855
+ }
1856
+ setStatus(status) {
1857
+ if (this.status === status) return;
1858
+ this.status = status;
1859
+ for (const fn of this.statusListeners) fn(status);
1860
+ }
1861
+ emitParticipants() {
1862
+ const participants = this.getParticipants();
1863
+ for (const fn of this.participantListeners) fn(participants);
1864
+ }
1865
+ emitError(error) {
1866
+ for (const fn of this.errorListeners) fn(error);
1867
+ }
1868
+ /** The local participant's poolse user id, once connected. */
1869
+ getSelfId() {
1870
+ return this.selfId;
1871
+ }
1872
+ };
1873
+
1623
1874
  // src/resources/ice-servers.ts
1624
1875
  var IceServersResource = class {
1625
1876
  constructor(client) {
@@ -1888,6 +2139,8 @@ var Poolse = class {
1888
2139
  realtime;
1889
2140
  /** STUN/TURN servers for WebRTC — see `IceServersResource`. */
1890
2141
  iceServers;
2142
+ /** SFU credentials for a call's media — see `CallTokensResource`. */
2143
+ callTokens;
1891
2144
  resolved;
1892
2145
  tokenCache;
1893
2146
  constructor(config) {
@@ -1905,6 +2158,7 @@ var Poolse = class {
1905
2158
  this.attachments = new AttachmentsResource(this.rest, cachedConfig.fetch);
1906
2159
  this.users = new UsersResource(cachedConfig);
1907
2160
  this.iceServers = new IceServersResource(this.rest);
2161
+ this.callTokens = new CallTokensResource(this.rest);
1908
2162
  this.realtime = new PoolseRealtime(cachedConfig, this.tokenCache, {
1909
2163
  ...this.resolved.wsUrl !== void 0 ? { wsUrl: this.resolved.wsUrl } : {},
1910
2164
  socketPath: this.resolved.socketPath,
@@ -1914,6 +2168,27 @@ var Poolse = class {
1914
2168
  iceServersProvider: async () => (await this.iceServers.list()).ice_servers
1915
2169
  });
1916
2170
  }
2171
+ /**
2172
+ * A call's media, carried by the SFU.
2173
+ *
2174
+ * Media only — ringing, presence, roster and mute state stay on
2175
+ * poolse's own channels, and a client joins both. See {@link CallRoom}.
2176
+ *
2177
+ * `livekit` is your app's `livekit-client` import. This package cannot
2178
+ * import it for you: tsup rewrites `require()` into `__require()`,
2179
+ * which Metro cannot follow, so a dependency required from in here is
2180
+ * absent from every React Native bundle.
2181
+ *
2182
+ * import * as livekit from 'livekit-client';
2183
+ * const call = poolse.call(conversationId, { livekit, video: true });
2184
+ * const usingSfu = await call.join(); // false = no SFU, use the mesh
2185
+ */
2186
+ call(conversationId, opts) {
2187
+ return new CallRoom({
2188
+ ...opts,
2189
+ tokenProvider: opts.tokenProvider ?? (() => this.callTokens.create(conversationId))
2190
+ });
2191
+ }
1917
2192
  /**
1918
2193
  * Tear down the SDK: close the WebSocket, drop all channels.
1919
2194
  * No-op for REST — fetch() doesn't keep persistent state.
@@ -1926,8 +2201,8 @@ var Poolse = class {
1926
2201
  };
1927
2202
 
1928
2203
  // src/version.ts
1929
- var version = "2.9.0";
2204
+ var version = "2.10.1";
1930
2205
 
1931
- export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallsResource, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, DevicesResource, IceServersResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, UserChannel, UsersResource, VoiceRoom, createBrowserWebRtcAdapter, isWebRtcAvailable, safeUuid, version };
2206
+ export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallRoom, CallTokensResource, CallsResource, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, DevicesResource, IceServersResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, UserChannel, UsersResource, VoiceRoom, createBrowserWebRtcAdapter, isWebRtcAvailable, safeUuid, version };
1932
2207
  //# sourceMappingURL=index.js.map
1933
2208
  //# sourceMappingURL=index.js.map