sabha-meetings-react 0.1.5 → 0.1.9

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
@@ -166,6 +166,59 @@ function toSabhaError(error, fallback = "Sabha request failed") {
166
166
  // src/session.ts
167
167
  var SABHA_SESSION_HEADER = "x-sabha-session";
168
168
  var SABHA_SESSION_STORAGE_KEY = "sabha_vm_session";
169
+ var SABHA_TOKENS_STORAGE_KEY = "sabha_auth_tokens";
170
+ function readJson(key) {
171
+ try {
172
+ if (typeof localStorage === "undefined") return null;
173
+ const raw = localStorage.getItem(key);
174
+ if (!raw) return null;
175
+ return JSON.parse(raw);
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+ function writeJson(key, value) {
181
+ try {
182
+ if (typeof localStorage === "undefined") return;
183
+ if (value == null) localStorage.removeItem(key);
184
+ else localStorage.setItem(key, JSON.stringify(value));
185
+ } catch {
186
+ }
187
+ }
188
+ function readStoredTokens() {
189
+ const parsed = readJson(SABHA_TOKENS_STORAGE_KEY);
190
+ if (parsed && typeof parsed === "object") {
191
+ const record = parsed;
192
+ const tokens = {
193
+ accessToken: typeof record.accessToken === "string" ? record.accessToken : void 0,
194
+ refreshToken: typeof record.refreshToken === "string" ? record.refreshToken : void 0,
195
+ sessionCookie: typeof record.sessionCookie === "string" ? record.sessionCookie : void 0
196
+ };
197
+ if (tokens.accessToken || tokens.refreshToken || tokens.sessionCookie) {
198
+ return tokens;
199
+ }
200
+ }
201
+ const legacy = readStoredSessionCookie();
202
+ if (legacy) {
203
+ const migrated = { sessionCookie: legacy };
204
+ writeStoredTokens(migrated);
205
+ return migrated;
206
+ }
207
+ return null;
208
+ }
209
+ function writeStoredTokens(tokens) {
210
+ if (!tokens || !tokens.accessToken && !tokens.refreshToken && !tokens.sessionCookie) {
211
+ writeJson(SABHA_TOKENS_STORAGE_KEY, null);
212
+ writeStoredSessionCookie(null);
213
+ return;
214
+ }
215
+ writeJson(SABHA_TOKENS_STORAGE_KEY, {
216
+ accessToken: tokens.accessToken,
217
+ refreshToken: tokens.refreshToken,
218
+ sessionCookie: tokens.sessionCookie
219
+ });
220
+ writeStoredSessionCookie(tokens.sessionCookie ?? null);
221
+ }
169
222
  function readStoredSessionCookie() {
170
223
  try {
171
224
  if (typeof localStorage === "undefined") return null;
@@ -628,6 +681,11 @@ var DEFAULT_EVENTS = {
628
681
  error: "meeting:error",
629
682
  mediaState: "meeting:media-state"
630
683
  };
684
+ var SIGNAL_EVENT = "meeting:signal";
685
+ var ICE_SERVERS = [
686
+ { urls: "stun:stun.l.google.com:19302" },
687
+ { urls: "stun:stun1.l.google.com:19302" }
688
+ ];
631
689
  var MeetingConnection = class {
632
690
  constructor(options) {
633
691
  this.options = options;
@@ -636,20 +694,37 @@ var MeetingConnection = class {
636
694
  this.listeners = /* @__PURE__ */ new Map();
637
695
  this.mediaUnsub = null;
638
696
  this.captureUnsub = null;
697
+ this.peers = /* @__PURE__ */ new Map();
698
+ this.remoteStream = null;
639
699
  this.events = { ...DEFAULT_EVENTS, ...options.events };
640
- this.mediaPolicy = { ...DEFAULT_MEDIA_POLICY, ...options.mediaPolicy };
700
+ this.role = options.role ?? "host";
701
+ this.selfId = options.selfId || `anon-${Math.random().toString(36).slice(2, 10)}`;
702
+ this.mediaPolicy = this.role === "participant" ? {
703
+ ...DEFAULT_MEDIA_POLICY,
704
+ ...options.mediaPolicy,
705
+ audio: false,
706
+ video: false,
707
+ allowScreenShare: false,
708
+ screenOff: true
709
+ } : { ...DEFAULT_MEDIA_POLICY, ...options.mediaPolicy };
641
710
  this.media = new MediaController(this.mediaPolicy);
642
711
  this.protection = new ContentProtection(this.mediaPolicy);
643
712
  }
644
713
  get meetingId() {
645
714
  return this.options.meetingId;
646
715
  }
716
+ get meetingRole() {
717
+ return this.role;
718
+ }
647
719
  get connectionState() {
648
720
  return this.state;
649
721
  }
650
722
  getMediaState() {
651
723
  return this.media.getMediaState();
652
724
  }
725
+ getRemoteStream() {
726
+ return this.remoteStream;
727
+ }
653
728
  on(event, listener) {
654
729
  const set = this.listeners.get(event) ?? /* @__PURE__ */ new Set();
655
730
  set.add(listener);
@@ -681,7 +756,9 @@ var MeetingConnection = class {
681
756
  withCredentials: this.options.withCredentials !== false,
682
757
  auth,
683
758
  extraHeaders,
684
- autoConnect: true
759
+ autoConnect: true,
760
+ // Leave must stay left — do not let socket.io reconnect the room.
761
+ reconnection: false
685
762
  });
686
763
  this.socket = socket;
687
764
  const onConnect = () => {
@@ -696,11 +773,22 @@ var MeetingConnection = class {
696
773
  meetingId: this.options.meetingId,
697
774
  ...mediaState
698
775
  });
776
+ if (this.role === "host") {
777
+ void this.refreshHostTracks();
778
+ }
699
779
  });
700
780
  this.captureUnsub = this.protection.onCaptureAttempt((event) => {
701
781
  this.emit("captureAttempt", event);
702
782
  });
703
- await this.media.start(this.mediaPolicy);
783
+ if (this.role === "host") {
784
+ await this.media.start(this.mediaPolicy);
785
+ } else {
786
+ this.sendSignal({
787
+ type: "request-offer",
788
+ from: this.selfId,
789
+ role: "participant"
790
+ });
791
+ }
704
792
  resolve();
705
793
  }).catch(reject);
706
794
  };
@@ -724,24 +812,56 @@ var MeetingConnection = class {
724
812
  });
725
813
  }
726
814
  async setAudioEnabled(enabled) {
815
+ if (this.role !== "host") {
816
+ throw new SabhaError("Only the host can control the microphone", {
817
+ code: "HOST_ONLY"
818
+ });
819
+ }
727
820
  return this.media.setAudioEnabled(enabled);
728
821
  }
729
822
  async setVideoEnabled(enabled) {
823
+ if (this.role !== "host") {
824
+ throw new SabhaError("Only the host can control the camera", {
825
+ code: "HOST_ONLY"
826
+ });
827
+ }
730
828
  return this.media.setVideoEnabled(enabled);
731
829
  }
732
830
  async setScreenOff(off) {
831
+ if (this.role !== "host") {
832
+ throw new SabhaError("Only the host can change screen settings", {
833
+ code: "HOST_ONLY"
834
+ });
835
+ }
733
836
  return this.media.setScreenOff(off);
734
837
  }
735
838
  async startScreenShare() {
839
+ if (this.role !== "host") {
840
+ throw new SabhaError("Only the host can share screen", {
841
+ code: "HOST_ONLY"
842
+ });
843
+ }
736
844
  return this.media.startScreenShare();
737
845
  }
738
846
  async stopScreenShare() {
847
+ if (this.role !== "host") {
848
+ throw new SabhaError("Only the host can stop screen share", {
849
+ code: "HOST_ONLY"
850
+ });
851
+ }
739
852
  return this.media.stopScreenShare();
740
853
  }
741
854
  async leave() {
742
855
  const socket = this.socket;
743
856
  this.teardownMedia();
744
- if (!socket) return;
857
+ if (!socket) {
858
+ this.setState("disconnected");
859
+ return;
860
+ }
861
+ try {
862
+ socket.io.reconnection(false);
863
+ } catch {
864
+ }
745
865
  await new Promise((resolve) => {
746
866
  socket.timeout(5e3).emit(
747
867
  this.events.leave,
@@ -750,13 +870,22 @@ var MeetingConnection = class {
750
870
  );
751
871
  setTimeout(() => resolve(), 500);
752
872
  });
873
+ socket.removeAllListeners();
753
874
  socket.disconnect();
754
875
  this.socket = null;
755
876
  this.setState("disconnected");
756
877
  }
757
878
  disconnect() {
758
879
  this.teardownMedia();
759
- this.socket?.disconnect();
880
+ const socket = this.socket;
881
+ if (socket) {
882
+ try {
883
+ socket.io.reconnection(false);
884
+ } catch {
885
+ }
886
+ socket.removeAllListeners();
887
+ socket.disconnect();
888
+ }
760
889
  this.socket = null;
761
890
  this.setState("disconnected");
762
891
  }
@@ -773,6 +902,10 @@ var MeetingConnection = class {
773
902
  this.captureUnsub?.();
774
903
  this.mediaUnsub = null;
775
904
  this.captureUnsub = null;
905
+ for (const peer of this.peers.values()) peer.close();
906
+ this.peers.clear();
907
+ this.remoteStream = null;
908
+ this.emit("remoteStream", null);
776
909
  this.media.stopAll();
777
910
  this.protection.disable();
778
911
  }
@@ -793,7 +926,11 @@ var MeetingConnection = class {
793
926
  };
794
927
  socket.timeout(5e3).emit(
795
928
  this.events.join,
796
- { meetingId: this.options.meetingId },
929
+ {
930
+ meetingId: this.options.meetingId,
931
+ role: this.role,
932
+ peerId: this.selfId
933
+ },
797
934
  () => done()
798
935
  );
799
936
  setTimeout(done, 600);
@@ -803,10 +940,19 @@ var MeetingConnection = class {
803
940
  socket.on(this.events.participantJoined, (payload) => {
804
941
  this.emit("participantJoined", payload);
805
942
  this.emit("raw", { event: this.events.participantJoined, payload });
943
+ if (this.role === "host") {
944
+ const peerId = payload.id;
945
+ if (peerId && peerId !== this.selfId) {
946
+ void this.createHostOffer(peerId).catch((error) => {
947
+ this.emit("error", toError(error, "Failed to create host offer"));
948
+ });
949
+ }
950
+ }
806
951
  });
807
952
  socket.on(this.events.participantLeft, (payload) => {
808
953
  this.emit("participantLeft", payload);
809
954
  this.emit("raw", { event: this.events.participantLeft, payload });
955
+ this.closePeer(payload.id);
810
956
  });
811
957
  socket.on(
812
958
  this.events.meetingEnded,
@@ -828,10 +974,135 @@ var MeetingConnection = class {
828
974
  this.emit("error", error);
829
975
  this.emit("raw", { event: this.events.error, payload });
830
976
  });
977
+ socket.on(SIGNAL_EVENT, (payload) => {
978
+ void this.handleSignal(payload).catch((error) => {
979
+ this.emit("error", toError(error, "WebRTC signal failed"));
980
+ });
981
+ });
831
982
  socket.on("disconnect", () => {
832
983
  this.setState("disconnected");
833
984
  });
834
985
  }
986
+ sendSignal(partial) {
987
+ if (!this.socket?.connected) return;
988
+ this.socket.emit(SIGNAL_EVENT, {
989
+ meetingId: this.options.meetingId,
990
+ ...partial
991
+ });
992
+ }
993
+ async handleSignal(payload) {
994
+ if (!payload || payload.meetingId !== this.options.meetingId) return;
995
+ if (payload.from === this.selfId) return;
996
+ if (payload.to && payload.to !== this.selfId) return;
997
+ if (payload.type === "request-offer" && this.role === "host") {
998
+ await this.createHostOffer(payload.from);
999
+ return;
1000
+ }
1001
+ if (payload.type === "offer" && this.role === "participant") {
1002
+ const peer = this.getOrCreatePeer(payload.from, false);
1003
+ await peer.setRemoteDescription(payload.sdp);
1004
+ const answer = await peer.createAnswer();
1005
+ await peer.setLocalDescription(answer);
1006
+ this.sendSignal({
1007
+ type: "answer",
1008
+ from: this.selfId,
1009
+ to: payload.from,
1010
+ sdp: answer,
1011
+ role: "participant"
1012
+ });
1013
+ return;
1014
+ }
1015
+ if (payload.type === "answer" && this.role === "host") {
1016
+ const peer = this.peers.get(payload.from);
1017
+ if (!peer) return;
1018
+ await peer.setRemoteDescription(payload.sdp);
1019
+ return;
1020
+ }
1021
+ if (payload.type === "ice") {
1022
+ const peer = this.peers.get(payload.from);
1023
+ if (!peer || !payload.candidate) return;
1024
+ await peer.addIceCandidate(payload.candidate);
1025
+ }
1026
+ }
1027
+ async createHostOffer(peerId) {
1028
+ const peer = this.getOrCreatePeer(peerId, true);
1029
+ await this.attachLocalTracks(peer);
1030
+ const offer = await peer.createOffer({
1031
+ offerToReceiveAudio: false,
1032
+ offerToReceiveVideo: false
1033
+ });
1034
+ await peer.setLocalDescription(offer);
1035
+ this.sendSignal({
1036
+ type: "offer",
1037
+ from: this.selfId,
1038
+ to: peerId,
1039
+ sdp: offer,
1040
+ role: "host"
1041
+ });
1042
+ }
1043
+ getOrCreatePeer(peerId, isHost) {
1044
+ const existing = this.peers.get(peerId);
1045
+ if (existing) return existing;
1046
+ const peer = new RTCPeerConnection({ iceServers: ICE_SERVERS });
1047
+ this.peers.set(peerId, peer);
1048
+ peer.onicecandidate = (event) => {
1049
+ this.sendSignal({
1050
+ type: "ice",
1051
+ from: this.selfId,
1052
+ to: peerId,
1053
+ candidate: event.candidate ? event.candidate.toJSON() : null,
1054
+ role: this.role
1055
+ });
1056
+ };
1057
+ peer.onconnectionstatechange = () => {
1058
+ if (peer.connectionState === "failed" || peer.connectionState === "closed" || peer.connectionState === "disconnected") ;
1059
+ };
1060
+ if (!isHost) {
1061
+ peer.ontrack = (event) => {
1062
+ const stream = event.streams[0] ?? new MediaStream([event.track]);
1063
+ this.remoteStream = stream;
1064
+ this.emit("remoteStream", stream);
1065
+ };
1066
+ }
1067
+ return peer;
1068
+ }
1069
+ async attachLocalTracks(peer) {
1070
+ const local = new MediaStream();
1071
+ const cam = this.media.getCameraStream();
1072
+ const mic = this.media.getMicrophoneStream();
1073
+ const screen = this.media.getScreenStream();
1074
+ mic?.getAudioTracks().forEach((track) => local.addTrack(track));
1075
+ const videoSource = screen ?? cam;
1076
+ videoSource?.getVideoTracks().forEach((track) => local.addTrack(track));
1077
+ const senders = peer.getSenders();
1078
+ for (const track of local.getTracks()) {
1079
+ const already = senders.some((s) => s.track?.id === track.id);
1080
+ if (!already) peer.addTrack(track, local);
1081
+ }
1082
+ }
1083
+ async refreshHostTracks() {
1084
+ for (const [peerId, peer] of this.peers) {
1085
+ try {
1086
+ await this.attachLocalTracks(peer);
1087
+ const offer = await peer.createOffer();
1088
+ await peer.setLocalDescription(offer);
1089
+ this.sendSignal({
1090
+ type: "offer",
1091
+ from: this.selfId,
1092
+ to: peerId,
1093
+ sdp: offer,
1094
+ role: "host"
1095
+ });
1096
+ } catch {
1097
+ }
1098
+ }
1099
+ }
1100
+ closePeer(peerId) {
1101
+ const peer = this.peers.get(peerId);
1102
+ if (!peer) return;
1103
+ peer.close();
1104
+ this.peers.delete(peerId);
1105
+ }
835
1106
  setState(state) {
836
1107
  this.state = state;
837
1108
  this.emit("state", state);
@@ -842,6 +1113,10 @@ var MeetingConnection = class {
842
1113
  for (const listener of set) listener(payload);
843
1114
  }
844
1115
  };
1116
+ function toError(error, fallback) {
1117
+ if (error instanceof Error) return error;
1118
+ return new Error(fallback);
1119
+ }
845
1120
 
846
1121
  // src/SabhaClient.ts
847
1122
  var SabhaClient = class {
@@ -872,16 +1147,19 @@ var SabhaClient = class {
872
1147
  ...DEFAULT_MEDIA_POLICY,
873
1148
  ...this.config.mediaPolicy
874
1149
  };
875
- const stored = this.config.persistSession !== false ? readStoredSessionCookie() : null;
1150
+ const stored = this.config.persistSession !== false ? readStoredTokens() : null;
876
1151
  this.tokens = {
877
- accessToken: config.accessToken ?? this.tokens?.accessToken,
878
- refreshToken: config.refreshToken ?? this.tokens?.refreshToken,
879
- sessionCookie: config.sessionCookie ?? this.tokens?.sessionCookie ?? stored ?? void 0
1152
+ accessToken: config.accessToken ?? this.tokens?.accessToken ?? stored?.accessToken,
1153
+ refreshToken: config.refreshToken ?? this.tokens?.refreshToken ?? stored?.refreshToken,
1154
+ sessionCookie: config.sessionCookie ?? this.tokens?.sessionCookie ?? stored?.sessionCookie ?? void 0
880
1155
  };
881
1156
  const hasAnyToken = Boolean(
882
1157
  this.tokens.accessToken || this.tokens.sessionCookie || this.tokens.refreshToken
883
1158
  );
884
1159
  if (!hasAnyToken) this.tokens = null;
1160
+ else if (this.config.persistSession !== false) {
1161
+ this.persistTokens(this.tokens);
1162
+ }
885
1163
  this.http = new HttpClient({
886
1164
  baseUrl,
887
1165
  withCredentials: this.config.withCredentials !== false,
@@ -889,6 +1167,9 @@ var SabhaClient = class {
889
1167
  getTokens: () => this.tokens,
890
1168
  setTokens: (tokens) => {
891
1169
  this.tokens = tokens;
1170
+ if (this.config.persistSession !== false) {
1171
+ this.persistTokens(tokens);
1172
+ }
892
1173
  },
893
1174
  onSessionCookie: (cookie) => {
894
1175
  this.persistSessionCookie(cookie);
@@ -928,27 +1209,24 @@ var SabhaClient = class {
928
1209
  }
929
1210
  setTokens(tokens) {
930
1211
  this.ensureConfigured();
931
- this.tokens = tokens;
1212
+ this.persistTokens(tokens);
932
1213
  }
933
1214
  clearSession() {
934
1215
  this.tokens = null;
935
1216
  this.user = null;
936
- this.persistSessionCookie(null);
1217
+ this.persistTokens(null);
937
1218
  this.activeConnection?.disconnect();
938
1219
  this.activeConnection = null;
939
1220
  }
940
1221
  async login(input) {
941
1222
  const session = await this.auth().login(input);
942
1223
  this.applySession(session);
943
- if (session.accessToken) {
944
- this.persistSessionCookie(this.tokens?.sessionCookie ?? null);
945
- } else if (session.sessionCookie || this.tokens?.sessionCookie) {
946
- this.persistSessionCookie(session.sessionCookie ?? this.tokens?.sessionCookie ?? null);
947
- }
948
1224
  try {
949
1225
  const me = await this.auth().me();
950
1226
  this.user = me;
951
1227
  session.user = me;
1228
+ session.accessToken = this.tokens?.accessToken;
1229
+ session.refreshToken = this.tokens?.refreshToken;
952
1230
  session.sessionCookie = this.tokens?.sessionCookie;
953
1231
  return session;
954
1232
  } catch (error) {
@@ -958,7 +1236,7 @@ var SabhaClient = class {
958
1236
  if (!hasCredential) {
959
1237
  this.clearSession();
960
1238
  throw new SabhaError(
961
- "Login returned a user profile but no auth credential. Need JWT `token` from /api/auth/login (Postman) or Set-Cookie vm_session (exposed to the app as x-sabha-session via /sabha proxy). Without that, POST /api/meetings returns 401 Sign in first.",
1239
+ "Login returned a user profile but no auth credential. Need JWT `token` (+ optional `refreshToken`) from /api/auth/login as in Sabha-API Postman (Auth \u2192 Login). Without that, POST /api/meetings returns 401 Sign in first.",
962
1240
  {
963
1241
  code: "SESSION_NOT_ESTABLISHED",
964
1242
  status: 401,
@@ -975,7 +1253,7 @@ var SabhaClient = class {
975
1253
  return await this.me();
976
1254
  } catch (error) {
977
1255
  throw new SabhaError(
978
- "Not signed in to Sabha. Call login() first, and ensure the `vm_session` cookie is sent (credentials: 'include', CORS allow-credentials, allow-listed Origin).",
1256
+ "Not signed in to Sabha. Call login() first so Authorization: Bearer <accessToken> is sent (Postman Auth \u2192 Login stores json.token).",
979
1257
  {
980
1258
  code: "UNAUTHENTICATED",
981
1259
  status: 401,
@@ -1054,15 +1332,16 @@ var SabhaClient = class {
1054
1332
  groupId: input?.groupId
1055
1333
  });
1056
1334
  }
1057
- const connection = await this.connect(meeting.id);
1335
+ const connection = await this.connect(meeting.id, { role: "host" });
1058
1336
  return { meeting, connection };
1059
1337
  }
1060
- async connect(meetingId) {
1338
+ async connect(meetingId, options) {
1061
1339
  this.ensureConfigured();
1062
1340
  if (this.activeConnection) {
1063
1341
  this.activeConnection.disconnect();
1064
1342
  this.activeConnection = null;
1065
1343
  }
1344
+ const role = options?.role ?? "host";
1066
1345
  const connection = new MeetingConnection({
1067
1346
  baseUrl: this.config.baseUrl ?? DEFAULT_BASE_URL,
1068
1347
  meetingId,
@@ -1071,7 +1350,10 @@ var SabhaClient = class {
1071
1350
  withCredentials: this.config.withCredentials !== false,
1072
1351
  socketPath: this.config.socketPath,
1073
1352
  events: this.config.socketEvents,
1074
- mediaPolicy: this.mediaPolicy
1353
+ mediaPolicy: this.mediaPolicy,
1354
+ role,
1355
+ // Per-browser id so same Sabha account can host on one device and view on another.
1356
+ selfId: getDevicePeerId(this.user?.userId)
1075
1357
  });
1076
1358
  try {
1077
1359
  await connection.connect();
@@ -1097,30 +1379,36 @@ var SabhaClient = class {
1097
1379
  refreshToken: session.refreshToken ?? this.tokens?.refreshToken,
1098
1380
  sessionCookie: session.sessionCookie ?? this.tokens?.sessionCookie
1099
1381
  };
1100
- if (this.tokens.sessionCookie) {
1101
- this.persistSessionCookie(this.tokens.sessionCookie);
1382
+ this.persistTokens(this.tokens);
1383
+ }
1384
+ persistTokens(tokens) {
1385
+ this.tokens = tokens;
1386
+ if (this.config.persistSession !== false) {
1387
+ writeStoredTokens(tokens);
1102
1388
  }
1103
1389
  }
1104
1390
  persistSessionCookie(cookie) {
1105
1391
  if (cookie) {
1106
- this.tokens = {
1392
+ this.persistTokens({
1107
1393
  ...this.tokens ?? {},
1108
1394
  sessionCookie: cookie
1109
- };
1110
- } else if (this.tokens) {
1111
- const { sessionCookie: _removed, ...rest } = this.tokens;
1112
- this.tokens = Object.keys(rest).length ? rest : null;
1395
+ });
1396
+ return;
1113
1397
  }
1114
- if (this.config.persistSession !== false) {
1115
- writeStoredSessionCookie(cookie ?? null);
1398
+ if (!this.tokens) {
1399
+ this.persistTokens(null);
1400
+ return;
1116
1401
  }
1402
+ const { sessionCookie: _removed, ...rest } = this.tokens;
1403
+ this.persistTokens(Object.keys(rest).length ? rest : null);
1117
1404
  }
1118
1405
  async tryRefresh() {
1119
1406
  if (!this.tokens?.refreshToken) return false;
1120
1407
  if (this.refreshPromise) return this.refreshPromise;
1121
1408
  this.refreshPromise = (async () => {
1122
1409
  try {
1123
- await this.refreshSession();
1410
+ const tokens = await this.refreshSession();
1411
+ this.persistTokens({ ...this.tokens ?? {}, ...tokens });
1124
1412
  return true;
1125
1413
  } catch {
1126
1414
  return false;
@@ -1160,6 +1448,18 @@ function createSabhaClient(config) {
1160
1448
  client.configure(config ?? { baseUrl: DEFAULT_BASE_URL });
1161
1449
  return client;
1162
1450
  }
1451
+ function getDevicePeerId(userId) {
1452
+ const key = "sabha_device_peer_id";
1453
+ try {
1454
+ const existing = typeof sessionStorage !== "undefined" ? sessionStorage.getItem(key) : null;
1455
+ if (existing) return existing;
1456
+ const next = `${userId || "user"}-${Math.random().toString(36).slice(2, 10)}`;
1457
+ if (typeof sessionStorage !== "undefined") sessionStorage.setItem(key, next);
1458
+ return next;
1459
+ } catch {
1460
+ return `${userId || "user"}-${Math.random().toString(36).slice(2, 10)}`;
1461
+ }
1462
+ }
1163
1463
  var SabhaContext = react.createContext(null);
1164
1464
  var idleMedia = {
1165
1465
  audioEnabled: false,
@@ -1201,8 +1501,10 @@ function SabhaProvider({
1201
1501
  const [error, setError] = react.useState(null);
1202
1502
  react.useEffect(() => {
1203
1503
  client.configure(resolvedConfig);
1204
- setAuthenticated(client.getStatus().authenticated);
1205
- setUser(client.getUser());
1504
+ setAuthenticated(false);
1505
+ setUser(null);
1506
+ setError(null);
1507
+ setMeetings([]);
1206
1508
  setReady(true);
1207
1509
  }, [
1208
1510
  client,
@@ -1220,7 +1522,13 @@ function SabhaProvider({
1220
1522
  }
1221
1523
  setConnectionState(connection.connectionState);
1222
1524
  setMediaState(connection.getMediaState());
1223
- const offState = connection.on("state", setConnectionState);
1525
+ const offState = connection.on("state", (state) => {
1526
+ setConnectionState(state);
1527
+ if (state === "disconnected" || state === "error") {
1528
+ setConnection(null);
1529
+ setMediaState(idleMedia);
1530
+ }
1531
+ });
1224
1532
  const offMedia = connection.on("mediaState", setMediaState);
1225
1533
  return () => {
1226
1534
  offState();
@@ -1245,12 +1553,26 @@ function SabhaProvider({
1245
1553
  }, [client]);
1246
1554
  react.useEffect(() => {
1247
1555
  if (!ready || !autoLoadMeetings) return;
1248
- void client.me().then((me) => {
1556
+ let cancelled = false;
1557
+ void client.me().then(async (me) => {
1558
+ if (cancelled) return;
1249
1559
  setUser(me);
1250
1560
  setAuthenticated(true);
1251
- return refreshMeetings();
1561
+ try {
1562
+ await refreshMeetings();
1563
+ } catch {
1564
+ }
1252
1565
  }).catch(() => {
1566
+ if (cancelled) return;
1567
+ client.clearSession();
1568
+ setAuthenticated(false);
1569
+ setUser(null);
1570
+ setMeetings([]);
1571
+ setError(null);
1253
1572
  });
1573
+ return () => {
1574
+ cancelled = true;
1575
+ };
1254
1576
  }, [ready, autoLoadMeetings, client, refreshMeetings]);
1255
1577
  const createMeeting = react.useCallback(
1256
1578
  async (input) => {
@@ -1300,10 +1622,10 @@ function SabhaProvider({
1300
1622
  [client, connection]
1301
1623
  );
1302
1624
  const connect = react.useCallback(
1303
- async (meetingId) => {
1625
+ async (meetingId, options) => {
1304
1626
  setError(null);
1305
1627
  try {
1306
- const next = await client.connect(meetingId);
1628
+ const next = await client.connect(meetingId, options);
1307
1629
  setConnection(next);
1308
1630
  return next;
1309
1631
  } catch (err) {
@@ -1516,15 +1838,18 @@ exports.MediaController = MediaController;
1516
1838
  exports.MeetingConnection = MeetingConnection;
1517
1839
  exports.SABHA_SESSION_HEADER = SABHA_SESSION_HEADER;
1518
1840
  exports.SABHA_SESSION_STORAGE_KEY = SABHA_SESSION_STORAGE_KEY;
1841
+ exports.SABHA_TOKENS_STORAGE_KEY = SABHA_TOKENS_STORAGE_KEY;
1519
1842
  exports.SabhaClient = SabhaClient;
1520
1843
  exports.SabhaError = SabhaError;
1521
1844
  exports.SabhaProvider = SabhaProvider;
1522
1845
  exports.createSabhaClient = createSabhaClient;
1523
1846
  exports.normalizeMeeting = normalizeMeeting;
1524
1847
  exports.readStoredSessionCookie = readStoredSessionCookie;
1848
+ exports.readStoredTokens = readStoredTokens;
1525
1849
  exports.toSabhaError = toSabhaError;
1526
1850
  exports.useSabha = useSabha;
1527
1851
  exports.useSabhaMeetings = useSabhaMeetings;
1528
1852
  exports.writeStoredSessionCookie = writeStoredSessionCookie;
1853
+ exports.writeStoredTokens = writeStoredTokens;
1529
1854
  //# sourceMappingURL=index.js.map
1530
1855
  //# sourceMappingURL=index.js.map