@luma-ai/react 0.1.0 → 2.0.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +18 -12
  3. package/dist/chunks/src-CI0MDOrd.js +7643 -0
  4. package/dist/chunks/src-CI0MDOrd.js.map +1 -0
  5. package/dist/chunks/support-cursor-pCpYa13-.js +131 -0
  6. package/dist/chunks/support-cursor-pCpYa13-.js.map +1 -0
  7. package/dist/chunks/visitor-call-CDpkyeoR.js +1129 -0
  8. package/dist/chunks/visitor-call-CDpkyeoR.js.map +1 -0
  9. package/dist/chunks/visitor-cobrowse-BIyfnFu3.js +1352 -0
  10. package/dist/chunks/visitor-cobrowse-BIyfnFu3.js.map +1 -0
  11. package/dist/index.js +1 -2
  12. package/dist/next.js +2 -3
  13. package/dist/next.js.map +1 -1
  14. package/dist/react-router.js +2 -3
  15. package/dist/react-router.js.map +1 -1
  16. package/dist/server.js +8 -11
  17. package/dist/server.js.map +1 -1
  18. package/dist/tanstack.js +2 -3
  19. package/dist/tanstack.js.map +1 -1
  20. package/docs/ai-agents.md +5 -5
  21. package/docs/appearance.md +92 -0
  22. package/docs/data-sources.md +18 -18
  23. package/docs/features.md +62 -0
  24. package/docs/hooks.md +22 -8
  25. package/docs/index.md +17 -7
  26. package/docs/options.md +58 -51
  27. package/docs/privacy.md +29 -6
  28. package/docs/server.md +11 -7
  29. package/docs/troubleshooting.md +14 -6
  30. package/package.json +27 -20
  31. package/skills/luma-ai-react/SKILL.md +32 -13
  32. package/dist/chunks/src-dnp1waFV.js +0 -3100
  33. package/dist/chunks/src-dnp1waFV.js.map +0 -1
  34. package/dist/config-CCT7m9eE.d.ts +0 -102
  35. package/dist/index-BdkoFDyP.d.ts +0 -189
  36. package/dist/index.d.ts +0 -3
  37. package/dist/next.d.ts +0 -7
  38. package/dist/react-router.d.ts +0 -10
  39. package/dist/server.d.ts +0 -33
  40. package/dist/tanstack.d.ts +0 -7
@@ -0,0 +1,1129 @@
1
+ "use client";
2
+ import { f as CALL_FAILURE_TEXT, m as callDuration, p as CALL_TIMING } from "./src-CI0MDOrd.js";
3
+ import { t as createSupportCursor } from "./support-cursor-pCpYa13-.js";
4
+ // ../assistant-contract/src/call-peer.ts
5
+ var MEDIA = {
6
+ audio: {
7
+ echoCancellation: true,
8
+ noiseSuppression: true,
9
+ autoGainControl: true
10
+ },
11
+ video: {
12
+ width: 640,
13
+ height: 360,
14
+ frameRate: 15
15
+ },
16
+ audioMaxBitrate: 4e4,
17
+ videoMaxBitrate: 5e5,
18
+ /** A shared screen: text stays readable at a low frame rate. */
19
+ screen: {
20
+ width: 1920,
21
+ height: 1080,
22
+ frameRate: 8
23
+ },
24
+ screenMaxBitrate: 9e5
25
+ };
26
+ /** The transceivers in the order the owner's offer makes them. */
27
+ var SCREEN_INDEX = 2;
28
+ /** Within this long a dropped connection retries before the UI says so. */
29
+ var RESTART_AFTER_MS = 3e3;
30
+ /** Whether this page can make a call at all, or why not. */
31
+ function callSupport() {
32
+ if (typeof window === "undefined") return "unsupported";
33
+ if (!window.isSecureContext) return "insecure";
34
+ if (typeof RTCPeerConnection === "undefined" || !navigator.mediaDevices?.getUserMedia) return "unsupported";
35
+ const policy = document.permissionsPolicy ?? document.featurePolicy;
36
+ if (policy && !policy.allowsFeature("microphone")) return "blocked_by_site";
37
+ return null;
38
+ }
39
+ /** A getUserMedia error as a failure a person can act on. */
40
+ function mediaFailure(error) {
41
+ const name = error?.name;
42
+ if (name === "NotAllowedError" || name === "SecurityError") return "mic_denied";
43
+ if (name === "NotFoundError" || name === "OverconstrainedError") return "no_mic";
44
+ if (name === "NotReadableError" || name === "AbortError") return "mic_busy";
45
+ return "unsupported";
46
+ }
47
+ /** The microphone, or the failure. */
48
+ async function openMicrophone() {
49
+ const unsupported = callSupport();
50
+ if (unsupported) return { failure: unsupported };
51
+ try {
52
+ return { stream: await navigator.mediaDevices.getUserMedia({
53
+ audio: MEDIA.audio,
54
+ video: false
55
+ }) };
56
+ } catch (error) {
57
+ return { failure: mediaFailure(error) };
58
+ }
59
+ }
60
+ var CallPeer = class {
61
+ remote = new MediaStream();
62
+ /** The visitor's shared screen, on the owner's side. */
63
+ remoteScreen = new MediaStream();
64
+ pc;
65
+ pending = [];
66
+ camera = null;
67
+ screen = null;
68
+ muted = false;
69
+ restartTimer = null;
70
+ closed = false;
71
+ state = "connecting";
72
+ options;
73
+ constructor(options) {
74
+ this.options = options;
75
+ this.pc = new RTCPeerConnection({
76
+ iceServers: options.rtc.iceServers,
77
+ iceTransportPolicy: options.rtc.iceTransportPolicy
78
+ });
79
+ this.pc.onicecandidate = (event) => {
80
+ if (!event.candidate) return;
81
+ options.send({
82
+ kind: "candidate",
83
+ candidate: event.candidate.candidate,
84
+ sdpMid: event.candidate.sdpMid,
85
+ sdpMLineIndex: event.candidate.sdpMLineIndex,
86
+ usernameFragment: event.candidate.usernameFragment
87
+ });
88
+ };
89
+ this.pc.ontrack = (event) => {
90
+ const stream = this.pc.getTransceivers().indexOf(event.transceiver) === SCREEN_INDEX ? this.remoteScreen : this.remote;
91
+ for (const track of stream.getTracks()) if (track.kind === event.track.kind) stream.removeTrack(track);
92
+ stream.addTrack(event.track);
93
+ options.onRemoteTrack();
94
+ };
95
+ this.pc.onconnectionstatechange = () => this.connectionChanged();
96
+ if (options.role === "offerer") {
97
+ const audio = options.microphone.getAudioTracks()[0];
98
+ if (audio) this.pc.addTransceiver(audio, {
99
+ direction: "sendrecv",
100
+ streams: [options.microphone]
101
+ });
102
+ else this.pc.addTransceiver("audio", { direction: "sendrecv" });
103
+ this.pc.addTransceiver("video", { direction: "sendrecv" });
104
+ this.pc.addTransceiver("video", { direction: "recvonly" });
105
+ }
106
+ }
107
+ /** The owner's side: make the first offer. */
108
+ async start() {
109
+ if (this.options.role !== "offerer") return;
110
+ await this.offer(false);
111
+ }
112
+ async offer(iceRestart) {
113
+ if (this.closed) return;
114
+ const offer = await this.pc.createOffer({ iceRestart });
115
+ await this.pc.setLocalDescription(offer);
116
+ this.options.send({
117
+ kind: "offer",
118
+ sdp: offer.sdp ?? ""
119
+ });
120
+ }
121
+ set(state) {
122
+ if (this.state === state || this.closed) return;
123
+ this.state = state;
124
+ this.options.onState(state);
125
+ }
126
+ connectionChanged() {
127
+ const state = this.pc.connectionState;
128
+ if (state === "connected") {
129
+ if (this.restartTimer) clearTimeout(this.restartTimer);
130
+ this.restartTimer = null;
131
+ this.set("connected");
132
+ this.limitBitrates();
133
+ return;
134
+ }
135
+ if (state === "disconnected" || state === "failed") {
136
+ this.set("reconnecting");
137
+ if (this.restartTimer) return;
138
+ this.restartTimer = setTimeout(() => {
139
+ this.restartTimer = null;
140
+ if (this.closed || this.pc.connectionState === "connected") return;
141
+ if (this.options.role === "offerer") this.offer(true);
142
+ else this.options.send({ kind: "restart" });
143
+ }, state === "failed" ? 0 : RESTART_AFTER_MS);
144
+ }
145
+ }
146
+ async handle(signal) {
147
+ if (this.closed) return;
148
+ switch (signal.kind) {
149
+ case "offer": {
150
+ if (this.options.role !== "answerer") return;
151
+ await this.pc.setRemoteDescription({
152
+ type: "offer",
153
+ sdp: signal.sdp
154
+ });
155
+ await this.attachLocalMedia();
156
+ const answer = await this.pc.createAnswer();
157
+ await this.pc.setLocalDescription(answer);
158
+ this.options.send({
159
+ kind: "answer",
160
+ sdp: answer.sdp ?? ""
161
+ });
162
+ await this.flushCandidates();
163
+ break;
164
+ }
165
+ case "answer":
166
+ if (this.options.role !== "offerer") return;
167
+ if (this.pc.signalingState !== "have-local-offer") return;
168
+ await this.pc.setRemoteDescription({
169
+ type: "answer",
170
+ sdp: signal.sdp
171
+ });
172
+ await this.flushCandidates();
173
+ break;
174
+ case "candidate": {
175
+ const candidate = {
176
+ candidate: signal.candidate,
177
+ sdpMid: signal.sdpMid,
178
+ sdpMLineIndex: signal.sdpMLineIndex,
179
+ usernameFragment: signal.usernameFragment ?? void 0
180
+ };
181
+ if (this.pc.remoteDescription) await this.pc.addIceCandidate(candidate).catch(() => void 0);
182
+ else this.pending.push(candidate);
183
+ break;
184
+ }
185
+ case "media":
186
+ this.options.onRemoteMedia({
187
+ camera: signal.camera,
188
+ muted: signal.muted
189
+ });
190
+ break;
191
+ case "restart":
192
+ if (this.options.role === "offerer") await this.offer(true);
193
+ break;
194
+ case "screen": this.options.onRemoteScreen?.(signal.state);
195
+ }
196
+ }
197
+ /** The answering side sends on the offer's transceivers, both ways. */
198
+ async attachLocalMedia() {
199
+ for (const [index, transceiver] of this.pc.getTransceivers().entries()) {
200
+ const kind = transceiver.receiver.track.kind;
201
+ if (index === SCREEN_INDEX) {
202
+ transceiver.direction = "sendonly";
203
+ if (this.screen && !transceiver.sender.track) await transceiver.sender.replaceTrack(this.screen);
204
+ continue;
205
+ }
206
+ transceiver.direction = "sendrecv";
207
+ if (kind === "audio" && !transceiver.sender.track) {
208
+ const audio = this.options.microphone.getAudioTracks()[0];
209
+ if (audio) await transceiver.sender.replaceTrack(audio);
210
+ }
211
+ if (kind === "video" && this.camera && !transceiver.sender.track) await transceiver.sender.replaceTrack(this.camera);
212
+ }
213
+ }
214
+ async flushCandidates() {
215
+ for (const candidate of this.pending.splice(0)) await this.pc.addIceCandidate(candidate).catch(() => void 0);
216
+ }
217
+ sender(kind) {
218
+ return this.pc.getTransceivers().find((transceiver) => transceiver.receiver.track.kind === kind)?.sender;
219
+ }
220
+ screenSender() {
221
+ const transceiver = this.pc.getTransceivers()[SCREEN_INDEX];
222
+ return transceiver?.receiver.track.kind === "video" ? transceiver.sender : void 0;
223
+ }
224
+ /**
225
+ * Whether this connection can carry a screen share: the owner's offer
226
+ * had its transceiver (an inbox from before phase 14 does not).
227
+ */
228
+ get canShareScreen() {
229
+ return this.options.role === "answerer" && this.screenSender() !== void 0;
230
+ }
231
+ /**
232
+ * The visitor's side: shares a screen track, or stops (null). The track
233
+ * is the caller's: closing this connection does not stop it, so a new
234
+ * connection in the same call (a rejoin) carries it on.
235
+ */
236
+ async setScreen(track) {
237
+ this.screen = track;
238
+ const sender = this.screenSender();
239
+ if (!sender) return false;
240
+ await sender.replaceTrack(track);
241
+ if (track) await this.limitScreen(sender);
242
+ return true;
243
+ }
244
+ async limitScreen(sender) {
245
+ const parameters = sender.getParameters();
246
+ if (!parameters.encodings?.length) return;
247
+ for (const encoding of parameters.encodings) {
248
+ encoding.maxBitrate = MEDIA.screenMaxBitrate;
249
+ encoding.maxFramerate = MEDIA.screen.frameRate;
250
+ }
251
+ await sender.setParameters(parameters).catch(() => void 0);
252
+ }
253
+ async limitBitrates() {
254
+ for (const [kind, maxBitrate] of [["audio", MEDIA.audioMaxBitrate], ["video", MEDIA.videoMaxBitrate]]) {
255
+ const sender = this.sender(kind);
256
+ if (!sender) continue;
257
+ const parameters = sender.getParameters();
258
+ if (!parameters.encodings?.length) continue;
259
+ for (const encoding of parameters.encodings) {
260
+ encoding.maxBitrate = maxBitrate;
261
+ if (kind === "video") encoding.maxFramerate = MEDIA.video.frameRate;
262
+ }
263
+ await sender.setParameters(parameters).catch(() => void 0);
264
+ }
265
+ const screen = this.screenSender();
266
+ if (screen?.track) await this.limitScreen(screen);
267
+ }
268
+ announce() {
269
+ this.options.send({
270
+ kind: "media",
271
+ camera: Boolean(this.camera),
272
+ muted: this.muted
273
+ });
274
+ }
275
+ /** The local camera track while it is on, for a preview. */
276
+ get cameraTrack() {
277
+ return this.camera;
278
+ }
279
+ get isMuted() {
280
+ return this.muted;
281
+ }
282
+ setMuted(muted) {
283
+ this.muted = muted;
284
+ for (const track of this.options.microphone.getAudioTracks()) track.enabled = !muted;
285
+ this.announce();
286
+ }
287
+ /** Switches the camera on (asks for it) or off; the failure if it cannot. */
288
+ async setCamera(on) {
289
+ const sender = this.sender("video");
290
+ if (!on) {
291
+ this.camera?.stop();
292
+ this.camera = null;
293
+ await sender?.replaceTrack(null);
294
+ this.announce();
295
+ return null;
296
+ }
297
+ if (this.camera) return null;
298
+ try {
299
+ const stream = await navigator.mediaDevices.getUserMedia({
300
+ video: MEDIA.video,
301
+ audio: false
302
+ });
303
+ this.camera = stream.getVideoTracks()[0] ?? null;
304
+ } catch (error) {
305
+ const failure = mediaFailure(error);
306
+ return failure === "mic_denied" ? "mic_denied" : failure;
307
+ }
308
+ if (this.closed) {
309
+ this.camera?.stop();
310
+ return null;
311
+ }
312
+ await sender?.replaceTrack(this.camera);
313
+ await this.limitBitrates();
314
+ this.announce();
315
+ return null;
316
+ }
317
+ async stats() {
318
+ const report = await this.pc.getStats();
319
+ const all = [...report.values()];
320
+ const audio = all.find((s) => s.type === "inbound-rtp" && s.kind === "audio");
321
+ const video = all.find((s) => s.type === "inbound-rtp" && s.kind === "video");
322
+ const transport = all.find((s) => s.type === "transport");
323
+ const pair = all.find((s) => s.type === "candidate-pair" && s.id === transport?.selectedCandidatePairId);
324
+ const local = pair ? report.get(pair.localCandidateId) : void 0;
325
+ const number = (value) => typeof value === "number" ? value : 0;
326
+ return {
327
+ state: this.pc.connectionState,
328
+ audioPacketsReceived: number(audio?.packetsReceived),
329
+ audioBytesReceived: number(audio?.bytesReceived),
330
+ audioLevel: number(audio?.audioLevel),
331
+ videoFramesDecoded: number(video?.framesDecoded),
332
+ bytesSent: number(transport?.bytesSent),
333
+ bytesReceived: number(transport?.bytesReceived),
334
+ relayProtocol: typeof local?.relayProtocol === "string" ? local.relayProtocol : null,
335
+ roundTripMs: typeof pair?.currentRoundTripTime === "number" ? Math.round(pair.currentRoundTripTime * 1e3) : null
336
+ };
337
+ }
338
+ close() {
339
+ if (this.closed) return;
340
+ this.state = "closed";
341
+ this.closed = true;
342
+ if (this.restartTimer) clearTimeout(this.restartTimer);
343
+ this.camera?.stop();
344
+ for (const track of this.options.microphone.getTracks()) track.stop();
345
+ this.pc.close();
346
+ }
347
+ };
348
+ // src/core/screen-share.ts
349
+ /**
350
+ * Whether this page can share its screen into a call (phase 14), or why
351
+ * not: phones and some browsers have no getDisplayMedia; a site's
352
+ * Permissions Policy can refuse `display-capture`. Where it cannot, support's
353
+ * request falls back to co-browsing.
354
+ */
355
+ function screenShareSupport() {
356
+ if (typeof window === "undefined" || typeof navigator === "undefined") return "unsupported";
357
+ if (!window.isSecureContext) return "insecure";
358
+ if (typeof navigator.mediaDevices?.getDisplayMedia !== "function") return "unsupported";
359
+ const policy = document;
360
+ const rules = policy.permissionsPolicy ?? policy.featurePolicy;
361
+ if (rules && !rules.allowsFeature("display-capture")) return "blocked_by_site";
362
+ return null;
363
+ }
364
+ // src/call/visitor-call.ts
365
+ var TEXT = {
366
+ fa: {
367
+ ringing: "پشتیبانی می‌خواهد با شما تماس صوتی بگیرد",
368
+ notice: "با پاسخ دادن، مرورگر برای میکروفون اجازه می‌خواهد. فقط صدای شما به پشتیبانی می‌رسد و دوربین خاموش است تا خودتان روشنش کنید. تماس ضبط نمی‌شود.",
369
+ answer: "پاسخ",
370
+ decline: "رد تماس",
371
+ connecting: "در حال اتصال…",
372
+ askingMic: "منتظر اجازهٔ میکروفون…",
373
+ inCall: "در تماس با پشتیبانی",
374
+ reconnecting: "اتصال ضعیف شد؛ در حال اتصال دوباره…",
375
+ mute: "قطع صدا",
376
+ unmute: "وصل صدا",
377
+ cameraOn: "روشن کردن دوربین",
378
+ cameraOff: "خاموش کردن دوربین",
379
+ hangup: "پایان تماس",
380
+ otherTab: "این تماس در زبانهٔ دیگری از همین سایت باز است.",
381
+ moveHere: "ادامه در این زبانه",
382
+ rejoinText: "تماس هنوز برقرار است. با رفتن به این صفحه صدا قطع شد.",
383
+ rejoin: "وصل شدن دوباره",
384
+ supportCamera: "دوربین پشتیبانی",
385
+ yourCamera: "دوربین شما",
386
+ supportMuted: "صدای پشتیبانی قطع است",
387
+ unsupported: "تماس در این صفحه ممکن نیست: ",
388
+ close: "بستن",
389
+ ended: {
390
+ hangup: "تماس پایان یافت",
391
+ declined: "تماس را رد کردید",
392
+ no_answer: "تماس بی‌پاسخ ماند",
393
+ cancelled: "پشتیبانی تماس را لغو کرد",
394
+ failed: "تماس برقرار نشد",
395
+ connection_lost: "اتصال تماس قطع شد",
396
+ support_ended: "گفتگو به دستیار برگشت و تماس پایان یافت",
397
+ resolved: "گفتگو بسته شد و تماس پایان یافت",
398
+ max_duration: "تماس به بیشترین زمان مجاز رسید",
399
+ credits: "اعتبار تماس این کسب‌وکار تمام شد",
400
+ withdrawn: "درخواست تماس را لغو کردید"
401
+ },
402
+ noCredits: "اعتبار تماس این کسب‌وکار تمام شده است.",
403
+ failedToStart: "تماس برقرار نشد. دوباره تلاش کنید.",
404
+ shareScreen: "نمایش صفحهٔ من",
405
+ shareAsked: "پشتیبانی می‌خواهد صفحهٔ شما را ببیند",
406
+ shareNotice: "پشتیبانی هر چیزی را که روی صفحهٔ نمایش‌داده‌شده است می‌بیند، حتی آنچه می‌نویسید. نمایش ضبط نمی‌شود. مرورگر می‌پرسد کدام صفحه را نشان دهید؛ برای اینکه نشانگر پشتیبانی را ببینید، همین زبانه را انتخاب کنید.",
407
+ shareNo: "نه",
408
+ shareCancel: "انصراف",
409
+ sharing: "صفحهٔ شما به پشتیبانی نشان داده می‌شود.",
410
+ sharingOther: "پشتیبانی صفحهٔ دیگری را می‌بیند؛ نشانگر پشتیبانی فقط وقتی روی صفحه دیده می‌شود که همین زبانه را نشان دهید.",
411
+ shareThisTab: "نمایش همین زبانه",
412
+ stopShare: "توقف نمایش",
413
+ shareBanner: "پشتیبانی صفحهٔ شما را می‌بیند",
414
+ stop: "توقف",
415
+ shareFailed: "نمایش صفحه شروع نشد."
416
+ },
417
+ en: {
418
+ ringing: "Support would like to call you",
419
+ notice: "If you answer, your browser asks for the microphone. Only your voice reaches support; the camera stays off until you turn it on. The call is not recorded.",
420
+ answer: "Answer",
421
+ decline: "Decline",
422
+ connecting: "Connecting…",
423
+ askingMic: "Waiting for microphone permission…",
424
+ inCall: "In a call with support",
425
+ reconnecting: "Connection is weak; reconnecting…",
426
+ mute: "Mute",
427
+ unmute: "Unmute",
428
+ cameraOn: "Turn camera on",
429
+ cameraOff: "Turn camera off",
430
+ hangup: "Hang up",
431
+ otherTab: "This call is open in another tab of this site.",
432
+ moveHere: "Continue in this tab",
433
+ rejoinText: "The call is still on. Sound stopped when this page opened.",
434
+ rejoin: "Rejoin",
435
+ supportCamera: "Support's camera",
436
+ yourCamera: "Your camera",
437
+ supportMuted: "Support is muted",
438
+ unsupported: "Calls are not possible on this page: ",
439
+ close: "Close",
440
+ ended: {
441
+ hangup: "The call ended",
442
+ declined: "You declined the call",
443
+ no_answer: "The call was not answered",
444
+ cancelled: "Support cancelled the call",
445
+ failed: "The call failed",
446
+ connection_lost: "The call's connection was lost",
447
+ support_ended: "The assistant took the conversation back; the call ended",
448
+ resolved: "The conversation was closed; the call ended",
449
+ max_duration: "The call reached its time limit",
450
+ credits: "This business's call credit ran out",
451
+ withdrawn: "You withdrew your call request"
452
+ },
453
+ noCredits: "This business's call credit has run out.",
454
+ failedToStart: "The call could not start. Try again.",
455
+ shareScreen: "Show my screen",
456
+ shareAsked: "Support would like to see your screen",
457
+ shareNotice: "Support sees everything on the screen you share, including what you type. It is not recorded. Your browser asks which screen to show; choose this tab to see support's cursor.",
458
+ shareNo: "No",
459
+ shareCancel: "Cancel",
460
+ sharing: "Your screen is being shown to support.",
461
+ sharingOther: "Support sees another screen; support's cursor shows on your page only when you share this tab.",
462
+ shareThisTab: "Share this tab",
463
+ stopShare: "Stop sharing",
464
+ shareBanner: "Support is viewing your screen",
465
+ stop: "Stop",
466
+ shareFailed: "Screen sharing did not start."
467
+ }
468
+ };
469
+ var STYLE = `
470
+ .luma-call{display:flex;flex-direction:column;gap:10px;margin:6px 4px 8px;padding:12px;border:1px solid var(--border);border-radius:12px;background:var(--background);color:var(--foreground);font-size:14px;line-height:1.6}
471
+ .luma-call-head{display:flex;align-items:center;gap:8px;font-weight:600}
472
+ .luma-call-dot{width:10px;height:10px;border-radius:50%;background:#16a34a;flex-shrink:0}
473
+ .luma-call[data-state=ringing] .luma-call-dot{animation:luma-call-pulse 1.2s infinite}
474
+ .luma-call[data-state=reconnecting] .luma-call-dot,.luma-call[data-state=connecting] .luma-call-dot{background:#d97706}
475
+ .luma-call[data-state=ended] .luma-call-dot,.luma-call[data-state=failed] .luma-call-dot{background:var(--muted-foreground)}
476
+ .luma-call-time{margin-inline-start:auto;font-variant-numeric:tabular-nums;color:var(--muted-foreground);font-weight:400}
477
+ .luma-call-text{margin:0;font-size:13px;color:var(--muted-foreground)}
478
+ .luma-call-text[data-tone=error]{color:var(--destructive)}
479
+ .luma-call-videos{display:flex;gap:6px}
480
+ .luma-call-videos video{width:100%;max-height:140px;border-radius:8px;background:#000;object-fit:cover}
481
+ .luma-call-videos video.luma-call-self{width:34%}
482
+ .luma-call-actions{display:flex;flex-wrap:wrap;gap:6px}
483
+ .luma-call button{display:inline-flex;align-items:center;gap:6px;min-height:36px;padding:6px 12px;border-radius:999px;border:1px solid var(--border);background:var(--background);color:var(--foreground);font:inherit;font-size:13px;cursor:pointer}
484
+ .luma-call button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}
485
+ .luma-call button[data-kind=accept]{background:#16a34a;border-color:#16a34a;color:#fff}
486
+ .luma-call button[data-kind=hangup]{background:var(--destructive);border-color:var(--destructive);color:#fff}
487
+ .luma-call button[aria-pressed=true]{background:var(--muted)}
488
+ .luma-call svg{width:16px;height:16px;flex-shrink:0}
489
+ .luma-call-share{display:flex;flex-direction:column;gap:6px;padding:8px 10px;border-radius:10px;background:var(--muted)}
490
+ .luma-call-share strong{font-size:13px}
491
+ @keyframes luma-call-pulse{50%{opacity:.35}}
492
+ @media (prefers-reduced-motion:reduce){.luma-call[data-state=ringing] .luma-call-dot{animation:none}}
493
+ `;
494
+ var ICON = {
495
+ phone: "<path d=\"M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z\"/>",
496
+ hangup: "<path d=\"M10.7 13.3a16 16 0 0 0 3 2.4l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2v3a2 2 0 0 1-2.2 2A19.8 19.8 0 0 1 3.1 5.2 2 2 0 0 1 5.1 3h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L9 10.8\"/><path d=\"m22 2-20 20\"/>",
497
+ mic: "<path d=\"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z\"/><path d=\"M19 10v2a7 7 0 0 1-14 0v-2\"/><path d=\"M12 19v3\"/>",
498
+ micOff: "<path d=\"m2 2 20 20\"/><path d=\"M18.9 13.4A7 7 0 0 0 19 12v-2\"/><path d=\"M5 10v2a7 7 0 0 0 12 5\"/><path d=\"M15 9.3V5a3 3 0 0 0-5.7-1.3\"/><path d=\"M9 9v3a3 3 0 0 0 5.1 2.1\"/><path d=\"M12 19v3\"/>",
499
+ video: "<path d=\"m16 13 5.2 3.1a.5.5 0 0 0 .8-.4V8.3a.5.5 0 0 0-.8-.4L16 11\"/><rect x=\"2\" y=\"6\" width=\"14\" height=\"12\" rx=\"2\"/>",
500
+ screen: "<rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\"/><path d=\"M8 21h8\"/><path d=\"M12 17v4\"/>",
501
+ videoOff: "<path d=\"M10.7 5H14a2 2 0 0 1 2 2v3.3l1 1L22 8v8\"/><path d=\"M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2\"/><path d=\"m2 2 20 20\"/>"
502
+ };
503
+ function element(tag, attributes = {}, text) {
504
+ const node = document.createElement(tag);
505
+ for (const [name, value] of Object.entries(attributes)) node.setAttribute(name, value);
506
+ if (text !== void 0) node.textContent = text;
507
+ return node;
508
+ }
509
+ function button(label, icon, kind, onClick) {
510
+ const node = element("button", {
511
+ type: "button",
512
+ "data-kind": kind
513
+ });
514
+ node.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICON[icon] ?? ""}</svg>`;
515
+ node.append(document.createTextNode(label));
516
+ node.addEventListener("click", onClick);
517
+ return node;
518
+ }
519
+ /** A soft two-tone ring while the call rings; silent if audio is blocked. */
520
+ function ringer() {
521
+ let context = null;
522
+ let timer = null;
523
+ const beep = () => {
524
+ if (!context || context.state !== "running") return;
525
+ for (const [frequency, at] of [[660, 0], [880, .25]]) {
526
+ const oscillator = context.createOscillator();
527
+ const gain = context.createGain();
528
+ oscillator.frequency.value = frequency;
529
+ gain.gain.setValueAtTime(1e-4, context.currentTime + at);
530
+ gain.gain.exponentialRampToValueAtTime(.08, context.currentTime + at + .02);
531
+ gain.gain.exponentialRampToValueAtTime(1e-4, context.currentTime + at + .22);
532
+ oscillator.connect(gain).connect(context.destination);
533
+ oscillator.start(context.currentTime + at);
534
+ oscillator.stop(context.currentTime + at + .25);
535
+ }
536
+ };
537
+ return {
538
+ start() {
539
+ try {
540
+ context = new AudioContext();
541
+ context.resume().catch(() => void 0);
542
+ } catch {
543
+ context = null;
544
+ }
545
+ beep();
546
+ timer = setInterval(beep, 2e3);
547
+ },
548
+ stop() {
549
+ if (timer) clearInterval(timer);
550
+ timer = null;
551
+ context?.close().catch(() => void 0);
552
+ context = null;
553
+ }
554
+ };
555
+ }
556
+ /**
557
+ * Which surface a screen track shows: this very tab, or something else.
558
+ * Only a tab can be this tab (`displaySurface` "browser"), and Region
559
+ * Capture's `cropTo` accepts a crop target only from the captured tab, so a
560
+ * crop to this page that succeeds proves it. Browsers without Region
561
+ * Capture (Firefox, Safari) cannot tell, so they count as "other".
562
+ */
563
+ async function sharedSurface(track, doc = document) {
564
+ if (track.getSettings().displaySurface !== "browser") return "other";
565
+ const crop = globalThis;
566
+ const capture = track;
567
+ if (!crop.CropTarget?.fromElement || typeof capture.cropTo !== "function") return "other";
568
+ try {
569
+ const target = await crop.CropTarget.fromElement(doc.documentElement);
570
+ await capture.cropTo(target);
571
+ await capture.cropTo(null);
572
+ return "tab";
573
+ } catch {
574
+ return "other";
575
+ }
576
+ }
577
+ /** Asks the browser for a screen, offering this tab first. */
578
+ function askForScreen() {
579
+ return navigator.mediaDevices.getDisplayMedia({
580
+ video: {
581
+ displaySurface: "browser",
582
+ width: { max: 1920 },
583
+ height: { max: 1080 },
584
+ frameRate: { max: 8 }
585
+ },
586
+ audio: false,
587
+ preferCurrentTab: true,
588
+ selfBrowserSurface: "include",
589
+ surfaceSwitching: "exclude",
590
+ monitorTypeSurfaces: "include"
591
+ });
592
+ }
593
+ function mountVisitorCall(target, initial, options) {
594
+ const text = TEXT[options.lang];
595
+ const root = element("div", {
596
+ class: "luma-call",
597
+ dir: options.lang === "fa" ? "rtl" : "ltr",
598
+ lang: options.lang,
599
+ role: "region",
600
+ "aria-label": text.inCall,
601
+ "data-luma-call": ""
602
+ });
603
+ const style = element("style", {}, STYLE);
604
+ target.replaceChildren(style, root);
605
+ let view = initial;
606
+ let phase = "ringing";
607
+ let message = null;
608
+ let peer = null;
609
+ let peerSession = null;
610
+ let microphone = null;
611
+ let remoteMedia = {
612
+ camera: false,
613
+ muted: false
614
+ };
615
+ let heartbeat = null;
616
+ let clock = null;
617
+ let doneTimer = null;
618
+ let destroyed = false;
619
+ const pending = /* @__PURE__ */ new Map();
620
+ const ring = ringer();
621
+ let screenTrack = null;
622
+ let screenShare = null;
623
+ /** The notice before sharing: the visitor's own click, or support asked. */
624
+ let sharePrompt = null;
625
+ let shareMessage = null;
626
+ let cursor = null;
627
+ let banner = null;
628
+ const audio = element("audio", { autoplay: "" });
629
+ const remoteVideo = element("video", {
630
+ autoplay: "",
631
+ playsinline: "",
632
+ "aria-label": text.supportCamera
633
+ });
634
+ remoteVideo.muted = true;
635
+ const selfVideo = element("video", {
636
+ autoplay: "",
637
+ playsinline: "",
638
+ class: "luma-call-self",
639
+ "aria-label": text.yourCamera
640
+ });
641
+ selfVideo.muted = true;
642
+ const stopTimers = () => {
643
+ if (heartbeat) clearInterval(heartbeat);
644
+ if (clock) clearInterval(clock);
645
+ heartbeat = null;
646
+ clock = null;
647
+ };
648
+ const closePeer = (keepMicrophone = false) => {
649
+ if (peer) {
650
+ if (keepMicrophone && microphone) microphone = new MediaStream(microphone.getAudioTracks().map((track) => track.clone()));
651
+ peer.close();
652
+ }
653
+ peer = null;
654
+ peerSession = null;
655
+ if (!keepMicrophone) {
656
+ for (const track of microphone?.getTracks() ?? []) track.stop();
657
+ microphone = null;
658
+ }
659
+ };
660
+ const elapsed = () => view.answeredAt ? callDuration((Date.now() - Date.parse(view.answeredAt)) / 1e3, options.lang) : "";
661
+ function render() {
662
+ if (destroyed) return;
663
+ root.dataset.state = phase;
664
+ const head = element("div", { class: "luma-call-head" });
665
+ head.append(element("span", {
666
+ class: "luma-call-dot",
667
+ "aria-hidden": "true"
668
+ }));
669
+ const title = phase === "ringing" ? text.ringing : phase === "asking" ? text.askingMic : phase === "connecting" ? text.connecting : phase === "reconnecting" ? text.reconnecting : phase === "ended" || phase === "failed" ? message?.text ?? text.ended.hangup : text.inCall;
670
+ head.append(element("span", {
671
+ role: "status",
672
+ "aria-live": "polite"
673
+ }, title));
674
+ if (phase === "connected" || phase === "reconnecting") head.append(element("span", { class: "luma-call-time" }, elapsed()));
675
+ const parts = [head];
676
+ const note = (value, tone) => parts.push(element("p", {
677
+ class: "luma-call-text",
678
+ ...tone ? { "data-tone": tone } : {}
679
+ }, value));
680
+ const actions = element("div", { class: "luma-call-actions" });
681
+ switch (phase) {
682
+ case "ringing":
683
+ note(text.notice);
684
+ actions.append(button(text.answer, "phone", "accept", () => void accept()), button(text.decline, "hangup", "hangup", () => void decline()));
685
+ break;
686
+ case "unsupported":
687
+ note(message?.text ?? text.unsupported, "error");
688
+ actions.append(button(text.close, "hangup", "close", () => options.onDone()));
689
+ break;
690
+ case "asking":
691
+ case "connecting":
692
+ actions.append(button(text.hangup, "hangup", "hangup", () => void hangup()));
693
+ break;
694
+ case "connected":
695
+ case "reconnecting": {
696
+ if (remoteMedia.muted) note(text.supportMuted);
697
+ const videos = element("div", { class: "luma-call-videos" });
698
+ if (remoteMedia.camera) videos.append(remoteVideo);
699
+ if (peer?.cameraTrack) videos.append(selfVideo);
700
+ if (videos.childElementCount) parts.push(videos);
701
+ const muted = peer?.isMuted ?? false;
702
+ const mute = button(muted ? text.unmute : text.mute, muted ? "micOff" : "mic", "mute", () => {
703
+ peer?.setMuted(!muted);
704
+ render();
705
+ });
706
+ mute.setAttribute("aria-pressed", String(muted));
707
+ const cameraOn = Boolean(peer?.cameraTrack);
708
+ const camera = button(cameraOn ? text.cameraOff : text.cameraOn, cameraOn ? "videoOff" : "video", "camera", () => void toggleCamera(!cameraOn));
709
+ camera.setAttribute("aria-pressed", String(cameraOn));
710
+ actions.append(mute, camera);
711
+ if (screenPossible() && !screenTrack && !sharePrompt) actions.append(button(text.shareScreen, "screen", "share", () => {
712
+ sharePrompt = "visitor";
713
+ shareMessage = null;
714
+ render();
715
+ }));
716
+ actions.append(button(text.hangup, "hangup", "hangup", () => void hangup()));
717
+ if (message) note(message.text, message.tone);
718
+ const share = shareSection();
719
+ if (share) parts.push(share);
720
+ break;
721
+ }
722
+ case "rejoin":
723
+ note(text.rejoinText);
724
+ actions.append(button(text.rejoin, "phone", "accept", () => void join()), button(text.hangup, "hangup", "hangup", () => void hangup()));
725
+ break;
726
+ case "elsewhere":
727
+ note(text.otherTab);
728
+ actions.append(button(text.moveHere, "phone", "accept", () => void join()));
729
+ break;
730
+ case "failed": actions.append(button(text.close, "hangup", "close", () => options.onDone()));
731
+ }
732
+ if (actions.childElementCount) parts.push(actions);
733
+ root.replaceChildren(...parts, audio);
734
+ }
735
+ function setPhase(next, value = null) {
736
+ phase = next;
737
+ message = value;
738
+ if (next !== "ringing") ring.stop();
739
+ render();
740
+ }
741
+ /** Whether this call can share a screen here, now. */
742
+ function screenPossible() {
743
+ return Boolean(options.pageLayer && peer?.canShareScreen && screenShareSupport() === null);
744
+ }
745
+ function sendScreen(state) {
746
+ if (!peerSession) return;
747
+ options.request({
748
+ action: "signal",
749
+ callId: view.id,
750
+ session: peerSession,
751
+ signal: {
752
+ kind: "screen",
753
+ state
754
+ }
755
+ });
756
+ }
757
+ /** The notice, the sharing state and its buttons, in the call card. */
758
+ function shareSection() {
759
+ if (!sharePrompt && !screenTrack && !shareMessage) return null;
760
+ const box = element("div", {
761
+ class: "luma-call-share",
762
+ "data-luma-screen": screenTrack ? screenShare ?? "starting" : sharePrompt ? `prompt-${sharePrompt}` : "message"
763
+ });
764
+ const actions = element("div", { class: "luma-call-actions" });
765
+ if (screenTrack) {
766
+ box.append(element("p", { class: "luma-call-text" }, screenShare === "other" ? text.sharingOther : text.sharing));
767
+ if (screenShare === "other") actions.append(button(text.shareThisTab, "screen", "share", () => void shareScreen(true)));
768
+ actions.append(button(text.stopShare, "hangup", "close", () => stopShare(true)));
769
+ } else if (sharePrompt) {
770
+ if (sharePrompt === "owner") box.append(element("strong", {}, text.shareAsked));
771
+ box.append(element("p", { class: "luma-call-text" }, text.shareNotice));
772
+ const asked = sharePrompt === "owner";
773
+ actions.append(button(text.shareScreen, "screen", "accept", () => void shareScreen(false)), button(asked ? text.shareNo : text.shareCancel, "hangup", "close", () => {
774
+ sharePrompt = null;
775
+ if (asked) sendScreen("declined");
776
+ render();
777
+ }));
778
+ } else if (shareMessage) box.append(element("p", {
779
+ class: "luma-call-text",
780
+ "data-tone": "error"
781
+ }, shareMessage));
782
+ if (actions.childElementCount) box.append(actions);
783
+ return box;
784
+ }
785
+ function showBanner() {
786
+ if (!options.pageLayer || banner) return;
787
+ banner = element("div", {
788
+ class: "luma-pointer-banner",
789
+ role: "status",
790
+ lang: options.lang,
791
+ dir: options.lang === "fa" ? "rtl" : "ltr",
792
+ "data-luma-screen-banner": ""
793
+ });
794
+ banner.append(element("span", {}, text.shareBanner));
795
+ const stopButton = element("button", { type: "button" }, text.stop);
796
+ stopButton.addEventListener("click", () => stopShare(true));
797
+ banner.append(stopButton);
798
+ options.pageLayer.append(banner);
799
+ }
800
+ /** Starts sharing (or switches to this tab), after the visitor's click. */
801
+ async function shareScreen(switching) {
802
+ const asked = sharePrompt === "owner";
803
+ let stream;
804
+ try {
805
+ stream = await askForScreen();
806
+ } catch {
807
+ if (destroyed) return;
808
+ sharePrompt = null;
809
+ if (asked) sendScreen("declined");
810
+ shareMessage = switching ? null : text.shareFailed;
811
+ render();
812
+ return;
813
+ }
814
+ const track = stream.getVideoTracks()[0];
815
+ if (destroyed || !track || !peer) {
816
+ for (const each of stream.getTracks()) each.stop();
817
+ return;
818
+ }
819
+ if (switching) stopShare(false);
820
+ track.contentHint = "detail";
821
+ const surface = await sharedSurface(track);
822
+ if (destroyed || track.readyState === "ended") {
823
+ track.stop();
824
+ return;
825
+ }
826
+ screenTrack = track;
827
+ screenShare = surface;
828
+ sharePrompt = null;
829
+ shareMessage = null;
830
+ track.addEventListener("ended", () => {
831
+ if (screenTrack === track) stopShare(true);
832
+ });
833
+ await peer.setScreen(track);
834
+ sendScreen(surface);
835
+ showBanner();
836
+ render();
837
+ }
838
+ /** Stops sharing; `tell` lets support know (not when the call ends). */
839
+ function stopShare(tell) {
840
+ const track = screenTrack;
841
+ screenTrack = null;
842
+ screenShare = null;
843
+ track?.stop();
844
+ peer?.setScreen(null);
845
+ cursor?.destroy();
846
+ cursor = null;
847
+ banner?.remove();
848
+ banner = null;
849
+ if (tell && track) sendScreen("off");
850
+ render();
851
+ }
852
+ /** Support's cursor on the shared tab (only when it is this tab). */
853
+ function screenCursor(command) {
854
+ if (command.type !== "cursor" && command.type !== "ripple") return;
855
+ const at = command.at;
856
+ if (!at) {
857
+ cursor?.move(null);
858
+ return;
859
+ }
860
+ if (!("screen" in at) || screenShare !== "tab" || !options.pageLayer) return;
861
+ cursor ??= createSupportCursor(options.pageLayer, options.lang);
862
+ const target = () => ({
863
+ x: at.fx * window.innerWidth,
864
+ y: at.fy * window.innerHeight
865
+ });
866
+ if (command.type === "ripple") cursor.ripple(target);
867
+ else cursor.move(target);
868
+ }
869
+ function fail(failure) {
870
+ stopShare(false);
871
+ options.request({
872
+ action: "fail",
873
+ callId: view.id,
874
+ failure
875
+ });
876
+ closePeer();
877
+ stopTimers();
878
+ setPhase("failed", {
879
+ text: CALL_FAILURE_TEXT[options.lang][failure],
880
+ tone: "error"
881
+ });
882
+ }
883
+ function startHeartbeat() {
884
+ stopTimers();
885
+ heartbeat = setInterval(() => {
886
+ options.request({
887
+ action: "heartbeat",
888
+ callId: view.id
889
+ });
890
+ }, CALL_TIMING.heartbeatMs);
891
+ clock = setInterval(render, 1e3);
892
+ }
893
+ function createPeer(rtc) {
894
+ if (!microphone) return;
895
+ if (peer) closePeer(true);
896
+ const session = view.session;
897
+ peerSession = session;
898
+ remoteMedia = {
899
+ camera: false,
900
+ muted: false
901
+ };
902
+ peer = new CallPeer({
903
+ role: "answerer",
904
+ rtc,
905
+ microphone,
906
+ send: (signal) => void options.request({
907
+ action: "signal",
908
+ callId: view.id,
909
+ session,
910
+ signal
911
+ }),
912
+ onState: (state) => {
913
+ if (state === "connected") {
914
+ options.request({
915
+ action: "connected",
916
+ callId: view.id,
917
+ camera: Boolean(peer?.cameraTrack)
918
+ });
919
+ if (screenShare) sendScreen(screenShare);
920
+ setPhase("connected");
921
+ } else if (state === "reconnecting") setPhase("reconnecting");
922
+ },
923
+ onRemoteMedia: (media) => {
924
+ remoteMedia = media;
925
+ render();
926
+ },
927
+ onRemoteTrack: () => {
928
+ if (!peer) return;
929
+ audio.srcObject = peer.remote;
930
+ remoteVideo.srcObject = peer.remote;
931
+ audio.play().catch(() => void 0);
932
+ }
933
+ });
934
+ if (screenTrack) peer.setScreen(screenTrack);
935
+ for (const signal of pending.get(session) ?? []) peer.handle(signal);
936
+ pending.delete(session);
937
+ setPhase("connecting");
938
+ startHeartbeat();
939
+ }
940
+ /** A new connection in the same call (the owner rejoined): fresh relay
941
+ * credentials, since the old ones' allocations still count. */
942
+ let reconnecting = null;
943
+ async function reconnect(session) {
944
+ if (reconnecting === session) return;
945
+ reconnecting = session;
946
+ const result = await options.request({
947
+ action: "relay",
948
+ callId: view.id
949
+ });
950
+ reconnecting = null;
951
+ if (destroyed || view.session !== session || !result.rtc) return;
952
+ createPeer(result.rtc);
953
+ }
954
+ async function withMicrophone(then) {
955
+ setPhase("asking");
956
+ const opened = await openMicrophone();
957
+ if (destroyed) {
958
+ if (!("failure" in opened)) for (const track of opened.stream.getTracks()) track.stop();
959
+ return;
960
+ }
961
+ if ("failure" in opened) {
962
+ fail(opened.failure);
963
+ return;
964
+ }
965
+ microphone = opened.stream;
966
+ await then();
967
+ }
968
+ async function accept() {
969
+ await withMicrophone(async () => {
970
+ const result = await options.request({
971
+ action: "accept",
972
+ callId: view.id
973
+ });
974
+ if (!result.call || !result.rtc) {
975
+ closePeer();
976
+ setPhase("failed", {
977
+ text: result.error === "CALL_NO_CREDITS" ? text.noCredits : text.failedToStart,
978
+ tone: "error"
979
+ });
980
+ return;
981
+ }
982
+ view = result.call;
983
+ createPeer(result.rtc);
984
+ });
985
+ }
986
+ async function join() {
987
+ await withMicrophone(async () => {
988
+ const result = await options.request({
989
+ action: "join",
990
+ callId: view.id
991
+ });
992
+ if (!result.call || !result.rtc) {
993
+ closePeer();
994
+ setPhase("failed", {
995
+ text: text.failedToStart,
996
+ tone: "error"
997
+ });
998
+ return;
999
+ }
1000
+ view = result.call;
1001
+ createPeer(result.rtc);
1002
+ });
1003
+ }
1004
+ async function decline() {
1005
+ ring.stop();
1006
+ await options.request({
1007
+ action: "decline",
1008
+ callId: view.id
1009
+ });
1010
+ }
1011
+ async function hangup() {
1012
+ stopShare(false);
1013
+ closePeer();
1014
+ stopTimers();
1015
+ await options.request({
1016
+ action: "hangup",
1017
+ callId: view.id
1018
+ });
1019
+ }
1020
+ async function toggleCamera(on) {
1021
+ const failure = await peer?.setCamera(on);
1022
+ if (failure) message = {
1023
+ text: CALL_FAILURE_TEXT[options.lang][failure],
1024
+ tone: "error"
1025
+ };
1026
+ else message = null;
1027
+ if (peer?.cameraTrack) selfVideo.srcObject = new MediaStream([peer.cameraTrack]);
1028
+ if (on && !failure) options.request({
1029
+ action: "connected",
1030
+ callId: view.id,
1031
+ camera: true
1032
+ });
1033
+ render();
1034
+ }
1035
+ function ended() {
1036
+ stopShare(false);
1037
+ closePeer();
1038
+ stopTimers();
1039
+ const reason = view.endReason ?? "hangup";
1040
+ const declinedByVisitor = reason === "declined";
1041
+ const label = reason === "failed" && view.failure ? CALL_FAILURE_TEXT[options.lang][view.failure] : text.ended[reason];
1042
+ const duration = view.answeredAt && view.endedAt ? ` (${callDuration((Date.parse(view.endedAt) - Date.parse(view.answeredAt)) / 1e3, options.lang)})` : "";
1043
+ if (phase !== "failed") setPhase("ended", { text: `${label}${declinedByVisitor ? "" : duration}` });
1044
+ if (!doneTimer) doneTimer = setTimeout(() => options.onDone(), 8e3);
1045
+ }
1046
+ function apply(next) {
1047
+ view = next;
1048
+ if (next.status === "ended") {
1049
+ ended();
1050
+ return;
1051
+ }
1052
+ if (next.status === "ringing") {
1053
+ if (phase === "ringing") render();
1054
+ return;
1055
+ }
1056
+ if (!next.mine) {
1057
+ stopShare(false);
1058
+ if (peer) closePeer();
1059
+ stopTimers();
1060
+ setPhase("elsewhere");
1061
+ return;
1062
+ }
1063
+ if (!peer) {
1064
+ if (phase !== "asking") setPhase("rejoin");
1065
+ return;
1066
+ }
1067
+ if (peerSession !== next.session) reconnect(next.session);
1068
+ }
1069
+ const unsubscribe = options.onSignal(({ session, signal }) => {
1070
+ if (peer && session === peerSession) {
1071
+ peer.handle(signal);
1072
+ return;
1073
+ }
1074
+ const queued = pending.get(session) ?? [];
1075
+ queued.push(signal);
1076
+ pending.set(session, queued.slice(-50));
1077
+ options.refresh();
1078
+ });
1079
+ const unsupported = callSupport();
1080
+ if (initial.status === "ringing" && unsupported) {
1081
+ phase = "unsupported";
1082
+ message = {
1083
+ text: text.unsupported + CALL_FAILURE_TEXT[options.lang][unsupported],
1084
+ tone: "error"
1085
+ };
1086
+ options.request({
1087
+ action: "fail",
1088
+ callId: initial.id,
1089
+ failure: unsupported
1090
+ });
1091
+ render();
1092
+ } else if (initial.status === "ringing") {
1093
+ render();
1094
+ ring.start();
1095
+ } else {
1096
+ phase = "rejoin";
1097
+ apply(initial);
1098
+ }
1099
+ return {
1100
+ update: (next) => {
1101
+ if (!destroyed) apply(next);
1102
+ },
1103
+ requestScreen: () => {
1104
+ if (destroyed || phase !== "connected" || !screenPossible()) return false;
1105
+ if (!screenTrack) {
1106
+ sharePrompt = "owner";
1107
+ shareMessage = null;
1108
+ render();
1109
+ } else if (screenShare) sendScreen(screenShare);
1110
+ return true;
1111
+ },
1112
+ cursor: (command) => {
1113
+ if (!destroyed) screenCursor(command);
1114
+ },
1115
+ destroy: () => {
1116
+ stopShare(false);
1117
+ destroyed = true;
1118
+ ring.stop();
1119
+ unsubscribe();
1120
+ closePeer();
1121
+ stopTimers();
1122
+ if (doneTimer) clearTimeout(doneTimer);
1123
+ target.replaceChildren();
1124
+ }
1125
+ };
1126
+ }
1127
+ export { mountVisitorCall };
1128
+
1129
+ //# sourceMappingURL=visitor-call-CDpkyeoR.js.map