@arbidocs/react 0.4.167 → 0.4.169

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.
Files changed (99) hide show
  1. package/dist/artifacts/index.cjs +15 -12
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.js +6 -3
  4. package/dist/artifacts/index.js.map +1 -1
  5. package/dist/calls/livekit/index.cjs +977 -0
  6. package/dist/calls/livekit/index.cjs.map +1 -0
  7. package/dist/calls/livekit/index.d.cts +280 -0
  8. package/dist/calls/livekit/index.d.ts +280 -0
  9. package/dist/calls/livekit/index.js +961 -0
  10. package/dist/calls/livekit/index.js.map +1 -0
  11. package/dist/{chunk-ON4PL6DQ.cjs → chunk-2M4B4FFA.cjs} +48 -4
  12. package/dist/chunk-2M4B4FFA.cjs.map +1 -0
  13. package/dist/chunk-3NVSUYUV.js +528 -0
  14. package/dist/chunk-3NVSUYUV.js.map +1 -0
  15. package/dist/{chunk-QJHCVQ6C.js → chunk-3WIBD44F.js} +4734 -4673
  16. package/dist/chunk-3WIBD44F.js.map +1 -0
  17. package/dist/chunk-5HDC43MF.js +145 -0
  18. package/dist/chunk-5HDC43MF.js.map +1 -0
  19. package/dist/{chunk-D66JCVBB.cjs → chunk-7NHOKV7N.cjs} +4093 -4040
  20. package/dist/chunk-7NHOKV7N.cjs.map +1 -0
  21. package/dist/chunk-7NY2J3TR.js +986 -0
  22. package/dist/chunk-7NY2J3TR.js.map +1 -0
  23. package/dist/chunk-APZZQZ6P.js +147 -0
  24. package/dist/chunk-APZZQZ6P.js.map +1 -0
  25. package/dist/{chunk-I5ZBQ63Y.js → chunk-DGMK3EUN.js} +188 -181
  26. package/dist/chunk-DGMK3EUN.js.map +1 -0
  27. package/dist/chunk-DPYBZDJB.js +18 -0
  28. package/dist/chunk-DPYBZDJB.js.map +1 -0
  29. package/dist/chunk-EEIYXVM4.cjs +181 -0
  30. package/dist/chunk-EEIYXVM4.cjs.map +1 -0
  31. package/dist/chunk-GGYCK5A6.cjs +1035 -0
  32. package/dist/chunk-GGYCK5A6.cjs.map +1 -0
  33. package/dist/{chunk-JSSKEXRR.js → chunk-KGCGA452.js} +2 -2
  34. package/dist/chunk-KGCGA452.js.map +1 -0
  35. package/dist/chunk-N73IMVFF.cjs +21 -0
  36. package/dist/chunk-N73IMVFF.cjs.map +1 -0
  37. package/dist/chunk-NVAIVJID.js +298 -0
  38. package/dist/chunk-NVAIVJID.js.map +1 -0
  39. package/dist/{chunk-GTJ667CP.cjs → chunk-QQ7SCJRY.cjs} +2 -2
  40. package/dist/chunk-QQ7SCJRY.cjs.map +1 -0
  41. package/dist/chunk-S4PCA3ES.cjs +572 -0
  42. package/dist/chunk-S4PCA3ES.cjs.map +1 -0
  43. package/dist/chunk-VAMPYLQ4.cjs +157 -0
  44. package/dist/chunk-VAMPYLQ4.cjs.map +1 -0
  45. package/dist/chunk-VLK52VXC.cjs +307 -0
  46. package/dist/chunk-VLK52VXC.cjs.map +1 -0
  47. package/dist/chunk-VPKFUYGW.cjs +2551 -0
  48. package/dist/chunk-VPKFUYGW.cjs.map +1 -0
  49. package/dist/chunk-W6DYNLA2.js +2362 -0
  50. package/dist/chunk-W6DYNLA2.js.map +1 -0
  51. package/dist/{chunk-SVHGCX25.js → chunk-YWYCEEBF.js} +43 -4
  52. package/dist/chunk-YWYCEEBF.js.map +1 -0
  53. package/dist/{chunk-EUC2BTNS.cjs → chunk-ZI2VJOID.cjs} +206 -199
  54. package/dist/chunk-ZI2VJOID.cjs.map +1 -0
  55. package/dist/document-tools/index.cjs +79 -107
  56. package/dist/document-tools/index.cjs.map +1 -1
  57. package/dist/document-tools/index.d.cts +4 -5
  58. package/dist/document-tools/index.d.ts +4 -5
  59. package/dist/document-tools/index.js +23 -68
  60. package/dist/document-tools/index.js.map +1 -1
  61. package/dist/index.cjs +12650 -9452
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/{index.d-DfCFKora.d.cts → index.d-Bvp6rKNo.d.cts} +139 -1
  64. package/dist/{index.d-DfCFKora.d.ts → index.d-Bvp6rKNo.d.ts} +139 -1
  65. package/dist/{index.d-DCjYj7YK.d.ts → index.d-Dx9sGkW2.d.cts} +20 -8
  66. package/dist/{index.d-DCjYj7YK.d.cts → index.d-Dx9sGkW2.d.ts} +20 -8
  67. package/dist/index.d.cts +5465 -2291
  68. package/dist/index.d.ts +5465 -2291
  69. package/dist/index.js +11047 -8858
  70. package/dist/index.js.map +1 -1
  71. package/dist/query-keys.d-Kw0JMoff.d.cts +308 -0
  72. package/dist/query-keys.d-Kw0JMoff.d.ts +308 -0
  73. package/dist/shell/index.cjs +78 -21
  74. package/dist/shell/index.d.cts +1 -1
  75. package/dist/shell/index.d.ts +1 -1
  76. package/dist/shell/index.js +6 -1
  77. package/dist/ui/index.cjs +191 -186
  78. package/dist/ui/index.d.cts +1 -1
  79. package/dist/ui/index.d.ts +1 -1
  80. package/dist/ui/index.js +3 -2
  81. package/dist/useAudioRecorder.d-CWFDsb_S.d.cts +778 -0
  82. package/dist/useAudioRecorder.d-CWFDsb_S.d.ts +778 -0
  83. package/dist/viewers/index.cjs +22 -13
  84. package/dist/viewers/index.cjs.map +1 -1
  85. package/dist/viewers/index.js +21 -12
  86. package/dist/viewers/index.js.map +1 -1
  87. package/package.json +13 -3
  88. package/dist/chunk-6MTKKT2O.cjs +0 -999
  89. package/dist/chunk-6MTKKT2O.cjs.map +0 -1
  90. package/dist/chunk-CEZCFQ47.js +0 -932
  91. package/dist/chunk-CEZCFQ47.js.map +0 -1
  92. package/dist/chunk-D66JCVBB.cjs.map +0 -1
  93. package/dist/chunk-EUC2BTNS.cjs.map +0 -1
  94. package/dist/chunk-GTJ667CP.cjs.map +0 -1
  95. package/dist/chunk-I5ZBQ63Y.js.map +0 -1
  96. package/dist/chunk-JSSKEXRR.js.map +0 -1
  97. package/dist/chunk-ON4PL6DQ.cjs.map +0 -1
  98. package/dist/chunk-QJHCVQ6C.js.map +0 -1
  99. package/dist/chunk-SVHGCX25.js.map +0 -1
@@ -0,0 +1,961 @@
1
+ import { toProfileView, useCallTranscriptionAvailable, onCallEvent, transcriptPersistRole, persistTranscriptSegment, newSegmentId, encodeCaptionPacket, CALL_CAPTION_TOPIC, ensureMeetingChat, trackUploaderFor, conversationKeyForCall, loadMeetingHistory, CALL_CHAT_MAX_CHARS, newPacketId, encodeCallChatPacket, CALL_CHAT_TOPIC, persistMeetingMessage, mergeChatLines, openQuestion, markRejoining, sealQuestionText, createMutedNotifier, CALL_RECORDING_TOPIC, CALL_TRANSCRIPTION_TOPIC, decodeCaptionPacket, CALL_MODERATION_TOPIC, mutedNoticeFromPacket, decodeCallChatPacket, CALL_WEBINAR_TOPIC, parseWebinarPacket } from '../../chunk-W6DYNLA2.js';
2
+ import '../../chunk-7NY2J3TR.js';
3
+ import '../../chunk-NVAIVJID.js';
4
+ import { notify } from '../../chunk-5HDC43MF.js';
5
+ import '../../chunk-DPYBZDJB.js';
6
+ import '../../chunk-NNWMHMEC.js';
7
+ import '../../chunk-WUTL62MC.js';
8
+ import '../../chunk-APZZQZ6P.js';
9
+ import '../../chunk-QRCMKEE6.js';
10
+ import '../../chunk-SN5YV6FF.js';
11
+ import { useArbi, useArbiHost } from '../../chunk-KGCGA452.js';
12
+ import '../../chunk-CPZ36AQS.js';
13
+ import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
14
+ import { RoomEvent, ExternalE2EEKeyProvider, Room } from 'livekit-client';
15
+ import { useRoomContext, useLocalParticipant, useLocalParticipantPermissions } from '@livekit/components-react';
16
+ import { useQueryClient } from '@tanstack/react-query';
17
+ import { calls, continuityPrompt, CallApiError } from '@arbidocs/sdk/browser';
18
+
19
+ function createE2EEWorker() {
20
+ return new Worker(new URL("livekit-client/e2ee-worker", import.meta.url), { type: "module" });
21
+ }
22
+ function createRoom(e2eeKey, choices, createWorker) {
23
+ const options = {
24
+ adaptiveStream: true,
25
+ dynacast: true,
26
+ audioCaptureDefaults: choices.audioDeviceId ? { deviceId: choices.audioDeviceId } : void 0,
27
+ videoCaptureDefaults: choices.videoDeviceId ? { deviceId: choices.videoDeviceId } : void 0
28
+ };
29
+ let worker = null;
30
+ let keyProvider = null;
31
+ if (e2eeKey) {
32
+ keyProvider = new ExternalE2EEKeyProvider();
33
+ worker = createWorker();
34
+ options.e2ee = { keyProvider, worker };
35
+ }
36
+ const room = new Room(options);
37
+ const ready = (async () => {
38
+ if (!keyProvider || !e2eeKey) return;
39
+ await keyProvider.setKey(e2eeKey.slice().buffer);
40
+ await room.setE2EEEnabled(true);
41
+ })();
42
+ return { bundle: { room, worker }, ready };
43
+ }
44
+ function useCallRoom(e2eeKey, choices, options = {}) {
45
+ const [room, setRoom] = useState(null);
46
+ const [error, setError] = useState(null);
47
+ useEffect(() => {
48
+ let cancelled = false;
49
+ let created = null;
50
+ try {
51
+ const { bundle, ready } = createRoom(
52
+ e2eeKey,
53
+ choices,
54
+ options.createWorker ?? createE2EEWorker
55
+ );
56
+ created = bundle;
57
+ ready.then(() => {
58
+ if (!cancelled) setRoom(bundle.room);
59
+ }).catch((err) => {
60
+ console.error("[calls] E2EE setup failed", err);
61
+ if (!cancelled) setError("This browser cannot encrypt the call (E2EE unsupported).");
62
+ });
63
+ } catch (err) {
64
+ console.error("[calls] room setup failed", err);
65
+ setError("Could not set up the call in this browser.");
66
+ }
67
+ return () => {
68
+ cancelled = true;
69
+ if (created) {
70
+ void created.room.disconnect();
71
+ created.worker?.terminate();
72
+ }
73
+ setRoom(null);
74
+ };
75
+ }, [e2eeKey]);
76
+ return { room, error };
77
+ }
78
+ var MUTE_REQUEST_TOPIC = "arbi.mute-request";
79
+ function useMuteRequests() {
80
+ const room = useRoomContext();
81
+ useEffect(() => {
82
+ const onData = (payload, from, _kind, topic) => {
83
+ if (topic !== MUTE_REQUEST_TOPIC || !from) return;
84
+ const who = from.name || from.identity;
85
+ notify.info(`${who} asks you to mute your microphone`, {
86
+ action: {
87
+ label: "Mute",
88
+ onClick: () => void room.localParticipant.setMicrophoneEnabled(false)
89
+ }
90
+ });
91
+ };
92
+ room.on(RoomEvent.DataReceived, onData);
93
+ return () => {
94
+ room.off(RoomEvent.DataReceived, onData);
95
+ };
96
+ }, [room]);
97
+ return (identity) => void room.localParticipant.publishData(new TextEncoder().encode('{"v":1}'), {
98
+ reliable: true,
99
+ topic: MUTE_REQUEST_TOPIC,
100
+ destinationIdentities: [identity]
101
+ }).then(() => notify.info("Asked to mute")).catch((err) => notify.error(`Could not ask: ${err.message}`));
102
+ }
103
+ var FINAL_SEGMENT_GRACE_MS = 3e4;
104
+ function mayStillSend(params) {
105
+ if (params.sending) return true;
106
+ if (params.stoppedAt === null) return false;
107
+ return params.segmentStartedAt <= params.stoppedAt && params.now - params.stoppedAt <= FINAL_SEGMENT_GRACE_MS;
108
+ }
109
+ function storedSpeakerName(participantName, profileName, identity) {
110
+ return participantName?.trim() || profileName?.trim() || identity;
111
+ }
112
+ function useCallTranscriber({
113
+ callExtId,
114
+ callKey,
115
+ isCreator,
116
+ canPost,
117
+ linkVersion = null
118
+ }) {
119
+ const room = useRoomContext();
120
+ const { localParticipant } = useLocalParticipant();
121
+ const myIdentity = localParticipant.identity;
122
+ const arbi = useArbi();
123
+ const queryClient = useQueryClient();
124
+ const profile = arbi.isLoggedIn ? arbi.user.profile() : null;
125
+ const myProfileName = profile && toProfileView(profile).fullName || null;
126
+ const deploymentAvailable = useCallTranscriptionAvailable();
127
+ const available = deploymentAvailable && !!callKey;
128
+ const [state, setState] = useState(null);
129
+ const [creatorExtId, setCreatorExtId] = useState(null);
130
+ const [busy, setBusy] = useState(false);
131
+ const [muted, setMuted] = useState(false);
132
+ const [indicatorShown, setIndicatorShown] = useState(false);
133
+ const [captions, setCaptions] = useState([]);
134
+ const liveUpdate = useRef(false);
135
+ const persisted = useRef(/* @__PURE__ */ new Set());
136
+ const saveFailureShown = useRef(false);
137
+ const selfPosts = useRef(canPost);
138
+ useEffect(() => {
139
+ selfPosts.current = canPost;
140
+ }, [canPost]);
141
+ const on = available && !!state?.on;
142
+ const shouldSend = on && indicatorShown && !muted;
143
+ const shouldSendRef = useRef(shouldSend);
144
+ const sendStoppedAtRef = useRef(null);
145
+ if (shouldSendRef.current !== shouldSend) {
146
+ sendStoppedAtRef.current = shouldSend ? null : Date.now();
147
+ }
148
+ shouldSendRef.current = shouldSend;
149
+ const myPreviousText = useRef("");
150
+ const applyState = useCallback((next) => {
151
+ liveUpdate.current = true;
152
+ setState(next);
153
+ }, []);
154
+ useEffect(() => {
155
+ if (!available) return;
156
+ let cancelled = false;
157
+ arbi.calls.get(callExtId).then((call) => {
158
+ if (cancelled) return;
159
+ setCreatorExtId(call.creator_ext_id ?? null);
160
+ if (!liveUpdate.current) {
161
+ setState(calls.transcriptionStateFrom(call.transcription));
162
+ }
163
+ }).catch((err) => console.warn("[calls] could not read the transcription state", err));
164
+ return () => {
165
+ cancelled = true;
166
+ };
167
+ }, [available, callExtId]);
168
+ useEffect(
169
+ () => onCallEvent("call.transcription", (message) => {
170
+ if (message.call_ext_id === callExtId) applyState(message);
171
+ }),
172
+ [callExtId, applyState]
173
+ );
174
+ const addCaption = useCallback((line) => {
175
+ setCaptions((prev) => {
176
+ if (prev.some((c) => c.segmentId === line.segmentId && c.identity === line.identity)) {
177
+ return prev;
178
+ }
179
+ return [...prev, line].sort((a, b) => a.t - b.t).slice(-30);
180
+ });
181
+ }, []);
182
+ const persist = useCallback(
183
+ (segment, speakerNeedsProxy) => {
184
+ if (!callKey || persisted.current.has(segment.segmentId)) return;
185
+ const role = transcriptPersistRole({
186
+ myIdentity,
187
+ canPost: canPost && (segment.speakerIdentity !== myIdentity || selfPosts.current),
188
+ hasCallKey: true,
189
+ speakerIdentity: segment.speakerIdentity,
190
+ speakerNeedsProxy
191
+ });
192
+ if (!role) return;
193
+ persisted.current.add(segment.segmentId);
194
+ persistTranscriptSegment(arbi, queryClient, callExtId, callKey, segment).catch(
195
+ (err) => {
196
+ persisted.current.delete(segment.segmentId);
197
+ if (role === "own" && err?.status === 403) {
198
+ selfPosts.current = false;
199
+ }
200
+ console.warn("[calls] could not keep the transcript line", err);
201
+ if (!saveFailureShown.current) {
202
+ saveFailureShown.current = true;
203
+ notify.warning(
204
+ `Transcript lines are not being saved to the meeting chat: ${err?.message ?? "unknown error"}`
205
+ );
206
+ }
207
+ }
208
+ );
209
+ },
210
+ [callExtId, callKey, myIdentity, canPost]
211
+ );
212
+ useEffect(() => {
213
+ const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
214
+ if (topic === CALL_TRANSCRIPTION_TOPIC) {
215
+ if (participant || participantIdentity) return;
216
+ try {
217
+ const next = calls.transcriptionStateFrom(JSON.parse(new TextDecoder().decode(payload)));
218
+ if (next) applyState(next);
219
+ } catch {
220
+ }
221
+ return;
222
+ }
223
+ if (topic !== CALL_CAPTION_TOPIC || !callKey) return;
224
+ const identity = participant?.identity ?? participantIdentity;
225
+ if (!identity || identity === myIdentity) return;
226
+ void decodeCaptionPacket(payload, callKey).then((packet) => {
227
+ if (!packet || packet.identity !== identity) return;
228
+ const name = participant?.name || packet.name || identity;
229
+ const t = Math.min(packet.t, Date.now());
230
+ addCaption({
231
+ segmentId: packet.segment_id,
232
+ identity,
233
+ name,
234
+ text: packet.text,
235
+ t,
236
+ mine: false,
237
+ receivedAt: Date.now()
238
+ });
239
+ persist(
240
+ {
241
+ segmentId: packet.segment_id,
242
+ text: packet.text,
243
+ speakerIdentity: identity,
244
+ speakerName: name,
245
+ startedAt: new Date(t).toISOString()
246
+ },
247
+ packet.proxy === true
248
+ );
249
+ });
250
+ };
251
+ room.on(RoomEvent.DataReceived, onData);
252
+ return () => {
253
+ room.off(RoomEvent.DataReceived, onData);
254
+ };
255
+ }, [room, callKey, myIdentity, addCaption, applyState, persist]);
256
+ const handleSegment = useCallback(
257
+ async (segment) => {
258
+ if (!callKey || !mayStillSend({
259
+ sending: shouldSendRef.current,
260
+ stoppedAt: sendStoppedAtRef.current,
261
+ segmentStartedAt: segment.startedAt,
262
+ now: Date.now()
263
+ })) {
264
+ return;
265
+ }
266
+ const segmentId = newSegmentId();
267
+ const startedAt = new Date(segment.startedAt).toISOString();
268
+ let text;
269
+ try {
270
+ const result = await arbi.calls.transcription.transcribe(callExtId, {
271
+ audio: segment.blob,
272
+ segmentId,
273
+ startedAt,
274
+ linkVersion,
275
+ prompt: continuityPrompt(myPreviousText.current)
276
+ });
277
+ text = result.text.trim();
278
+ } catch (err) {
279
+ if (err instanceof CallApiError && err.status === 409) {
280
+ applyState({ on: false, by_identity: null, by_name: null });
281
+ }
282
+ console.warn("[calls] could not transcribe a segment", err);
283
+ return;
284
+ }
285
+ if (!text) return;
286
+ myPreviousText.current = `${myPreviousText.current} ${text}`.slice(-400);
287
+ const name = storedSpeakerName(localParticipant.name, myProfileName, myIdentity);
288
+ const proxy = !selfPosts.current;
289
+ addCaption({
290
+ segmentId,
291
+ identity: myIdentity,
292
+ name,
293
+ text,
294
+ t: segment.startedAt,
295
+ mine: true,
296
+ receivedAt: Date.now()
297
+ });
298
+ try {
299
+ await localParticipant.publishData(
300
+ await encodeCaptionPacket(
301
+ {
302
+ v: 1,
303
+ segment_id: segmentId,
304
+ text,
305
+ identity: myIdentity,
306
+ name,
307
+ t: segment.startedAt,
308
+ ...proxy ? { proxy: true } : {}
309
+ },
310
+ callKey
311
+ ),
312
+ { reliable: true, topic: CALL_CAPTION_TOPIC }
313
+ );
314
+ } catch (err) {
315
+ console.warn("[calls] could not broadcast a caption", err);
316
+ }
317
+ if (!proxy) {
318
+ persist(
319
+ { segmentId, text, speakerIdentity: myIdentity, speakerName: name, startedAt },
320
+ false
321
+ );
322
+ }
323
+ },
324
+ [
325
+ callExtId,
326
+ callKey,
327
+ linkVersion,
328
+ localParticipant,
329
+ myIdentity,
330
+ myProfileName,
331
+ addCaption,
332
+ applyState,
333
+ persist
334
+ ]
335
+ );
336
+ const startedByMe = !!state?.on && state.by_identity === myIdentity;
337
+ const canToggle = available && (isCreator || !!creatorExtId && creatorExtId === myIdentity);
338
+ const toggle = useCallback(async () => {
339
+ if (!canToggle) return;
340
+ const next = !on;
341
+ setBusy(true);
342
+ try {
343
+ const answer = await arbi.calls.transcription.set(callExtId, next);
344
+ applyState(
345
+ answer ?? (next ? { on: true, by_identity: myIdentity, by_name: localParticipant.name || null } : { on: false, by_identity: null, by_name: null })
346
+ );
347
+ } catch (err) {
348
+ notify.error(`Could not turn transcription ${next ? "on" : "off"}: ${err.message}`);
349
+ } finally {
350
+ setBusy(false);
351
+ }
352
+ }, [on, canToggle, callExtId, myIdentity, localParticipant, applyState]);
353
+ return useMemo(
354
+ () => ({
355
+ available,
356
+ on,
357
+ startedByName: on ? state?.by_name ?? null : null,
358
+ startedByMe,
359
+ canToggle,
360
+ busy,
361
+ muted,
362
+ setMuted,
363
+ toggle,
364
+ setIndicatorShown,
365
+ shouldSend,
366
+ captions,
367
+ handleSegment
368
+ }),
369
+ [
370
+ available,
371
+ on,
372
+ state,
373
+ startedByMe,
374
+ canToggle,
375
+ busy,
376
+ muted,
377
+ toggle,
378
+ shouldSend,
379
+ captions,
380
+ handleSegment
381
+ ]
382
+ );
383
+ }
384
+ function captureAllowed(params) {
385
+ return params.available && !!params.state?.on && !!params.state.recording_ext_id && params.indicatorShown;
386
+ }
387
+ function useCallRecorder({
388
+ callExtId,
389
+ callKey,
390
+ isCreator,
391
+ linkVersion = null
392
+ }) {
393
+ const arbi = useArbi();
394
+ const queryClient = useQueryClient();
395
+ const room = useRoomContext();
396
+ const { localParticipant } = useLocalParticipant();
397
+ const myIdentity = localParticipant.identity;
398
+ const available = !!callKey;
399
+ const [state, setState] = useState(null);
400
+ const [call, setCall] = useState(null);
401
+ const [busy, setBusy] = useState(false);
402
+ const [indicatorShown, setIndicatorShown] = useState(false);
403
+ const [pendingStart, setPendingStart] = useState(null);
404
+ const liveUpdate = useRef(false);
405
+ const stateRef = useRef(null);
406
+ stateRef.current = state;
407
+ const applyState = useCallback((next) => {
408
+ liveUpdate.current = true;
409
+ if (stateRef.current?.on && next && !next.on && next.reason === "storage_quota_exceeded") {
410
+ notify.warning("Recording stopped: the storage is full.");
411
+ }
412
+ stateRef.current = next;
413
+ setState(next);
414
+ }, []);
415
+ useEffect(() => {
416
+ let cancelled = false;
417
+ arbi.calls.get(callExtId).then((row) => {
418
+ if (cancelled) return;
419
+ setCall(row);
420
+ if (!liveUpdate.current) setState(calls.recordingStateOfCall(row));
421
+ }).catch((err) => console.warn("[calls] could not read the recording state", err));
422
+ return () => {
423
+ cancelled = true;
424
+ };
425
+ }, [callExtId]);
426
+ useEffect(
427
+ () => onCallEvent("call.recording", (message) => {
428
+ if (message.call_ext_id === callExtId) applyState(message);
429
+ }),
430
+ [callExtId, applyState]
431
+ );
432
+ useEffect(() => {
433
+ const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
434
+ if (topic !== CALL_RECORDING_TOPIC) return;
435
+ if (participant || participantIdentity) return;
436
+ try {
437
+ const next = calls.recordingStateFrom(JSON.parse(new TextDecoder().decode(payload)));
438
+ if (next) applyState(next);
439
+ } catch {
440
+ }
441
+ };
442
+ room.on(RoomEvent.DataReceived, onData);
443
+ return () => {
444
+ room.off(RoomEvent.DataReceived, onData);
445
+ };
446
+ }, [room, applyState]);
447
+ const canControl = available && (isCreator || !!call && call.creator_ext_id === myIdentity);
448
+ const on = !!state?.on;
449
+ const start = useCallback(
450
+ async (mode) => {
451
+ setBusy(true);
452
+ try {
453
+ const row = call ?? await arbi.calls.get(callExtId);
454
+ if (!row.workspace_locked && !row.chat_ext_id && callKey) {
455
+ const ref = await ensureMeetingChat(arbi, queryClient, callExtId, callKey);
456
+ if (ref.kind === "chat") setCall({ ...row, chat_ext_id: ref.chatExtId });
457
+ }
458
+ const answer = await arbi.calls.recording.start(callExtId, mode);
459
+ if (answer) applyState(answer);
460
+ } catch (err) {
461
+ notify.error(`Could not start recording: ${err.message}`);
462
+ } finally {
463
+ setBusy(false);
464
+ }
465
+ },
466
+ [callExtId, callKey, call, applyState]
467
+ );
468
+ const requestStart = useCallback(
469
+ async (mode) => {
470
+ if (!canControl || on) return;
471
+ setBusy(true);
472
+ let quota = null;
473
+ try {
474
+ quota = await arbi.calls.recording.quota(callExtId);
475
+ } catch (err) {
476
+ console.warn("[calls] could not read the recording quota", err);
477
+ }
478
+ setBusy(false);
479
+ if (quota && calls.quotaNeedsWarning(quota)) {
480
+ setPendingStart({ mode, quota });
481
+ return;
482
+ }
483
+ await start(mode);
484
+ },
485
+ [canControl, on, callExtId, start]
486
+ );
487
+ const confirmStart = useCallback(async () => {
488
+ const pending = pendingStart;
489
+ setPendingStart(null);
490
+ if (pending) await start(pending.mode);
491
+ }, [pendingStart, start]);
492
+ const cancelStart = useCallback(() => setPendingStart(null), []);
493
+ const stop = useCallback(async () => {
494
+ if (!canControl || !on) return;
495
+ setBusy(true);
496
+ try {
497
+ const answer = await arbi.calls.recording.stop(callExtId);
498
+ applyState(answer ?? { ...state, on: false });
499
+ } catch (err) {
500
+ notify.error(`Could not stop recording: ${err.message}`);
501
+ } finally {
502
+ setBusy(false);
503
+ }
504
+ }, [canControl, on, callExtId, state, applyState]);
505
+ const markStopped = useCallback(() => {
506
+ const prev = stateRef.current;
507
+ if (prev?.on) applyState({ ...prev, on: false, reason: "storage_quota_exceeded" });
508
+ }, [applyState]);
509
+ const shouldCapture = captureAllowed({ available, state, indicatorShown });
510
+ return useMemo(
511
+ () => ({
512
+ available,
513
+ on,
514
+ mode: on ? state?.mode ?? "audio" : null,
515
+ recordingExtId: state?.recording_ext_id ?? null,
516
+ startedAt: state?.started_at ?? null,
517
+ startedByName: on ? state?.by_name ?? null : null,
518
+ startedByMe: on && state?.by_identity === myIdentity,
519
+ canControl,
520
+ busy,
521
+ call,
522
+ linkVersion,
523
+ requestStart,
524
+ pendingStart,
525
+ confirmStart,
526
+ cancelStart,
527
+ stop,
528
+ setIndicatorShown,
529
+ shouldCapture,
530
+ markStopped
531
+ }),
532
+ [
533
+ available,
534
+ on,
535
+ state,
536
+ myIdentity,
537
+ canControl,
538
+ busy,
539
+ call,
540
+ linkVersion,
541
+ requestStart,
542
+ pendingStart,
543
+ confirmStart,
544
+ cancelStart,
545
+ stop,
546
+ shouldCapture,
547
+ markStopped
548
+ ]
549
+ );
550
+ }
551
+ function useTrackUploader(recording, callKey, kind, mimeType) {
552
+ const { recordingExtId, call, startedAt, shouldCapture, markStopped, linkVersion } = recording;
553
+ const arbi = useArbi();
554
+ const queryClient = useQueryClient();
555
+ return useMemo(() => {
556
+ if (!shouldCapture || !recordingExtId || !call) return null;
557
+ return trackUploaderFor({
558
+ arbi,
559
+ callExtId: call.external_id,
560
+ recordingExtId,
561
+ kind,
562
+ mimeType,
563
+ recordingStartedAt: startedAt,
564
+ linkVersion,
565
+ conversationKey: () => conversationKeyForCall(arbi, queryClient, call, { callKey }),
566
+ // The server stopped the recording at the quota (its state event says so too).
567
+ onStopped: () => markStopped()
568
+ });
569
+ }, [
570
+ arbi,
571
+ queryClient,
572
+ shouldCapture,
573
+ recordingExtId,
574
+ call,
575
+ startedAt,
576
+ linkVersion,
577
+ kind,
578
+ mimeType,
579
+ callKey,
580
+ markStopped
581
+ ]);
582
+ }
583
+ function useInCallChat({
584
+ callExtId,
585
+ callKey,
586
+ open,
587
+ readOnly = false,
588
+ persist = true
589
+ }) {
590
+ const room = useRoomContext();
591
+ const { localParticipant } = useLocalParticipant();
592
+ const myIdentity = localParticipant.identity;
593
+ const arbi = useArbi();
594
+ const queryClient = useQueryClient();
595
+ const openMeetingChat = useArbiHost().calls?.openMeetingChat;
596
+ const signedIn = arbi.isLoggedIn;
597
+ const persists = !!callKey && signedIn && !readOnly && persist;
598
+ const [live, setLive] = useState([]);
599
+ const [history, setHistory] = useState([]);
600
+ const [historyLoading, setHistoryLoading] = useState(false);
601
+ const [historyError, setHistoryError] = useState(null);
602
+ const [meetingChat, setMeetingChat] = useState(null);
603
+ const [unread, setUnread] = useState(0);
604
+ const openRef = useRef(open);
605
+ openRef.current = open;
606
+ const historyRequested = useRef(false);
607
+ const seen = useRef(/* @__PURE__ */ new Set());
608
+ useEffect(() => {
609
+ if (open) setUnread(0);
610
+ }, [open]);
611
+ useEffect(() => {
612
+ if (!callKey) return;
613
+ const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
614
+ if (topic !== CALL_CHAT_TOPIC) return;
615
+ const identity = participant?.identity ?? participantIdentity;
616
+ if (!identity || identity === myIdentity) return;
617
+ void decodeCallChatPacket(payload, callKey).then((packet) => {
618
+ if (!packet) return;
619
+ const key = `${identity}:${packet.id}`;
620
+ if (seen.current.has(key)) return;
621
+ seen.current.add(key);
622
+ setLive((prev) => [
623
+ ...prev,
624
+ {
625
+ id: packet.id,
626
+ senderIdentity: identity,
627
+ senderName: participant?.name || identity,
628
+ text: packet.text,
629
+ at: Math.min(packet.at, Date.now()),
630
+ mine: false,
631
+ status: "live"
632
+ }
633
+ ]);
634
+ if (!openRef.current) setUnread((n) => n + 1);
635
+ });
636
+ };
637
+ room.on(RoomEvent.DataReceived, onData);
638
+ return () => {
639
+ room.off(RoomEvent.DataReceived, onData);
640
+ };
641
+ }, [room, callKey, myIdentity]);
642
+ const canRead = !!callKey && signedIn && persist;
643
+ useEffect(() => {
644
+ if (!open || !canRead || historyRequested.current) return;
645
+ historyRequested.current = true;
646
+ setHistoryLoading(true);
647
+ loadMeetingHistory(arbi, queryClient, callExtId).then((result) => {
648
+ if (!result) return;
649
+ setMeetingChat(result.ref);
650
+ setHistory(result.messages);
651
+ }).catch((err) => {
652
+ console.warn("[calls] could not load the meeting chat", err);
653
+ setHistoryError("Earlier messages could not be loaded.");
654
+ }).finally(() => setHistoryLoading(false));
655
+ }, [open, canRead, callExtId]);
656
+ const send = useCallback(
657
+ async (raw) => {
658
+ const text = raw.trim().slice(0, CALL_CHAT_MAX_CHARS);
659
+ if (!text || !callKey || readOnly) return;
660
+ const id = newPacketId();
661
+ const at = Date.now();
662
+ await localParticipant.publishData(
663
+ await encodeCallChatPacket({ v: 1, id, text, at }, callKey),
664
+ { reliable: true, topic: CALL_CHAT_TOPIC }
665
+ );
666
+ setLive((prev) => [
667
+ ...prev,
668
+ {
669
+ id,
670
+ senderIdentity: myIdentity,
671
+ senderName: localParticipant.name || "You",
672
+ text,
673
+ at,
674
+ mine: true,
675
+ status: persists ? "saving" : "live"
676
+ }
677
+ ]);
678
+ if (!persists) return;
679
+ const mark = (status) => setLive(
680
+ (prev) => prev.map((l) => l.id === id && l.senderIdentity === myIdentity ? { ...l, status } : l)
681
+ );
682
+ try {
683
+ setMeetingChat(await persistMeetingMessage(arbi, queryClient, callExtId, callKey, text));
684
+ mark("saved");
685
+ } catch (err) {
686
+ console.warn("[calls] could not keep the message in the meeting chat", err);
687
+ mark("unsaved");
688
+ }
689
+ },
690
+ [callKey, callExtId, localParticipant, myIdentity, persists, readOnly]
691
+ );
692
+ const openMeeting = useCallback(async () => {
693
+ if (!callKey) return;
694
+ try {
695
+ const ref = meetingChat ?? await ensureMeetingChat(arbi, queryClient, callExtId, callKey);
696
+ setMeetingChat(ref);
697
+ openMeetingChat?.(ref);
698
+ } catch (err) {
699
+ notify.error(`Could not open the meeting chat: ${err.message}`);
700
+ }
701
+ }, [callExtId, callKey, meetingChat]);
702
+ const lines = useMemo(
703
+ () => mergeChatLines(history, live, {
704
+ myIdentity,
705
+ nameOf: (identity) => identity === myIdentity ? localParticipant.name || "You" : room.remoteParticipants.get(identity)?.name || null
706
+ }),
707
+ [history, live, myIdentity, localParticipant, room]
708
+ );
709
+ return {
710
+ lines,
711
+ unread,
712
+ available: !!callKey,
713
+ persists,
714
+ readOnly,
715
+ historyLoading,
716
+ historyError,
717
+ meetingChat,
718
+ send,
719
+ openMeeting
720
+ };
721
+ }
722
+ var DEMOTE_REJOIN_FALLBACK_MS = 5e3;
723
+ function failed(what) {
724
+ return (err) => {
725
+ notify.error(`Could not ${what}: ${err?.message ?? "unknown error"}`);
726
+ throw err;
727
+ };
728
+ }
729
+ function useWebinar({
730
+ role: roleHint = null,
731
+ callExtId,
732
+ linkVersion = null,
733
+ callKey
734
+ }) {
735
+ const arbi = useArbi();
736
+ const webinarApi = useCallback(() => arbi.calls.webinar, [arbi]);
737
+ const enabled = !!roleHint;
738
+ const room = useRoomContext();
739
+ const { localParticipant } = useLocalParticipant();
740
+ const myIdentity = localParticipant.identity;
741
+ const permissions = useLocalParticipantPermissions();
742
+ const [state, setState] = useState(null);
743
+ const [questions, setQuestions] = useState([]);
744
+ const [stageCheck, setStageCheck] = useState(false);
745
+ const stateRead = useRef(0);
746
+ const questionsRead = useRef(0);
747
+ const refresh = useCallback(async () => {
748
+ if (!enabled) return;
749
+ const n = ++stateRead.current;
750
+ try {
751
+ const next = await webinarApi().get(callExtId, linkVersion);
752
+ if (n === stateRead.current) setState(next);
753
+ } catch (err) {
754
+ console.warn("[calls] could not read the webinar state", err);
755
+ }
756
+ }, [enabled, callExtId, linkVersion]);
757
+ const refreshQuestions = useCallback(async () => {
758
+ if (!enabled || !callKey) return;
759
+ const n = ++questionsRead.current;
760
+ try {
761
+ const rows = await webinarApi().questions.list(callExtId, linkVersion);
762
+ const opened = await Promise.all(rows.map((q) => openQuestion(q, callKey)));
763
+ if (n === questionsRead.current) setQuestions(opened);
764
+ } catch (err) {
765
+ console.warn("[calls] could not load the questions", err);
766
+ }
767
+ }, [enabled, callExtId, linkVersion, callKey]);
768
+ useEffect(() => {
769
+ void refresh();
770
+ void refreshQuestions();
771
+ }, [refresh, refreshQuestions]);
772
+ useEffect(() => {
773
+ if (!enabled) return;
774
+ return onCallEvent("call.webinar", (m) => {
775
+ if (m.call_ext_id !== callExtId) return;
776
+ setState((s) => s ? { ...s, live: m.live, chat: m.chat } : s);
777
+ });
778
+ }, [enabled, callExtId]);
779
+ const fallback = useRef(null);
780
+ useEffect(() => {
781
+ if (!enabled) return;
782
+ const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
783
+ if (topic !== CALL_WEBINAR_TOPIC) return;
784
+ const packet = parseWebinarPacket(payload, !!(participant || participantIdentity));
785
+ if (!packet) return;
786
+ switch (packet.type) {
787
+ case "state":
788
+ setState(
789
+ (s) => s ? { ...s, live: packet.live, live_at: packet.live_at, chat: packet.chat } : s
790
+ );
791
+ void refresh();
792
+ return;
793
+ case "hands":
794
+ setState((s) => s ? { ...s, hands: packet.hands } : s);
795
+ return;
796
+ case "questions":
797
+ void refreshQuestions();
798
+ return;
799
+ case "promoted":
800
+ setStageCheck(true);
801
+ void refresh();
802
+ return;
803
+ case "demoted":
804
+ setStageCheck(false);
805
+ markRejoining(callExtId);
806
+ if (fallback.current) clearTimeout(fallback.current);
807
+ fallback.current = setTimeout(() => void room.disconnect(), DEMOTE_REJOIN_FALLBACK_MS);
808
+ return;
809
+ }
810
+ };
811
+ room.on(RoomEvent.DataReceived, onData);
812
+ return () => {
813
+ room.off(RoomEvent.DataReceived, onData);
814
+ };
815
+ }, [enabled, room, callExtId, refresh, refreshQuestions]);
816
+ useEffect(
817
+ () => () => {
818
+ if (fallback.current) clearTimeout(fallback.current);
819
+ },
820
+ []
821
+ );
822
+ const role = enabled ? state?.my_role ?? null : null;
823
+ const onStage = !enabled || (permissions ? permissions.canPublish : state ? state.on_stage : roleHint !== "attendee");
824
+ const patch = useCallback(
825
+ async (body, what) => {
826
+ const next = await webinarApi().update(callExtId, body, linkVersion).catch(failed(what));
827
+ setState(next);
828
+ },
829
+ [callExtId, linkVersion]
830
+ );
831
+ const stepDown = useCallback(async () => {
832
+ markRejoining(callExtId);
833
+ setStageCheck(false);
834
+ try {
835
+ await webinarApi().demote(callExtId, myIdentity, linkVersion);
836
+ } catch (err) {
837
+ markRejoining(callExtId, false);
838
+ failed("leave the stage")(err);
839
+ }
840
+ }, [callExtId, myIdentity, linkVersion]);
841
+ const joinStage = useCallback(
842
+ async (choices) => {
843
+ const lp = room.localParticipant;
844
+ try {
845
+ await lp.setMicrophoneEnabled(
846
+ choices.audioEnabled,
847
+ choices.audioDeviceId ? { deviceId: choices.audioDeviceId } : void 0
848
+ );
849
+ await lp.setCameraEnabled(
850
+ choices.videoEnabled,
851
+ choices.videoDeviceId ? { deviceId: choices.videoDeviceId } : void 0
852
+ );
853
+ } catch (err) {
854
+ failed("turn on your microphone or camera")(err);
855
+ }
856
+ setStageCheck(false);
857
+ },
858
+ [room]
859
+ );
860
+ const questionAction = useCallback(
861
+ async (run, what) => {
862
+ await run().catch(failed(what));
863
+ void refreshQuestions();
864
+ },
865
+ [refreshQuestions]
866
+ );
867
+ return useMemo(
868
+ () => ({
869
+ enabled,
870
+ role,
871
+ moderator: !!role && calls.WEBINAR_MODERATORS.has(role),
872
+ team: !!role && calls.WEBINAR_TEAM.has(role),
873
+ live: !!state?.live,
874
+ chat: state?.chat ?? "panelists",
875
+ onStage,
876
+ handRaised: !!state?.hand_raised,
877
+ hands: state?.hands ?? [],
878
+ attendees: state?.attendees ?? [],
879
+ questions,
880
+ stageCheck: enabled && stageCheck,
881
+ refresh,
882
+ goLive: () => patch({ live: true }, "go live"),
883
+ end: () => patch({ live: false }, "end the webinar"),
884
+ setChat: (chat) => patch({ chat }, "change who can chat"),
885
+ setHand: async (raised) => {
886
+ const next = await webinarApi().setHand(callExtId, raised, linkVersion).catch(failed(raised ? "raise your hand" : "lower your hand"));
887
+ setState(next);
888
+ },
889
+ promote: (identity) => webinarApi().promote(callExtId, identity, linkVersion).catch(failed("bring them on stage")).then(refresh),
890
+ demote: (identity) => webinarApi().demote(callExtId, identity, linkVersion).catch(failed("move them to the audience")).then(refresh),
891
+ stepDown,
892
+ joinStage,
893
+ ask: (text) => questionAction(async () => {
894
+ if (!callKey) throw new Error("This call has no key.");
895
+ await webinarApi().questions.ask(
896
+ callExtId,
897
+ await sealQuestionText(text, callKey),
898
+ linkVersion
899
+ );
900
+ }, "ask the question"),
901
+ vote: (id, up) => questionAction(() => webinarApi().questions.vote(callExtId, id, up, linkVersion), "vote"),
902
+ setQuestionStatus: (id, status) => questionAction(
903
+ () => webinarApi().questions.update(callExtId, id, { status }, linkVersion),
904
+ "update the question"
905
+ ),
906
+ answer: (id, text) => questionAction(async () => {
907
+ if (!callKey) throw new Error("This call has no key.");
908
+ await webinarApi().questions.update(
909
+ callExtId,
910
+ id,
911
+ { answer: await sealQuestionText(text, callKey) },
912
+ linkVersion
913
+ );
914
+ }, "answer the question"),
915
+ removeQuestion: (id) => questionAction(
916
+ () => webinarApi().questions.delete(callExtId, id, linkVersion),
917
+ "delete the question"
918
+ )
919
+ }),
920
+ [
921
+ enabled,
922
+ role,
923
+ state,
924
+ onStage,
925
+ questions,
926
+ stageCheck,
927
+ refresh,
928
+ patch,
929
+ callExtId,
930
+ linkVersion,
931
+ callKey,
932
+ stepDown,
933
+ joinStage,
934
+ questionAction
935
+ ]
936
+ );
937
+ }
938
+ function useHostMuteNotice(callExtId) {
939
+ const room = useRoomContext();
940
+ useEffect(() => {
941
+ const notifyMuted = createMutedNotifier((text) => notify.info(text));
942
+ const onData = (payload, participant, _kind, topic, _encryption, participantIdentity) => {
943
+ if (topic !== CALL_MODERATION_TOPIC) return;
944
+ if (participant || participantIdentity) return;
945
+ const notice = mutedNoticeFromPacket(payload);
946
+ if (notice) notifyMuted(notice);
947
+ };
948
+ room.on(RoomEvent.DataReceived, onData);
949
+ const offWs = onCallEvent("call.muted", (message) => {
950
+ if (message.callExtId === callExtId) notifyMuted(message);
951
+ });
952
+ return () => {
953
+ room.off(RoomEvent.DataReceived, onData);
954
+ offWs();
955
+ };
956
+ }, [room, callExtId]);
957
+ }
958
+
959
+ export { DEMOTE_REJOIN_FALLBACK_MS, FINAL_SEGMENT_GRACE_MS, captureAllowed, createE2EEWorker, mayStillSend, storedSpeakerName, useCallRecorder, useCallRoom, useCallTranscriber, useHostMuteNotice, useInCallChat, useMuteRequests, useTrackUploader, useWebinar };
960
+ //# sourceMappingURL=index.js.map
961
+ //# sourceMappingURL=index.js.map