@elevenlabs/convai-widget-embed 0.5.1 → 0.5.2

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
@@ -35,7 +35,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
35
35
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
36
36
  `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function Er(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Pr(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var av=Object.freeze({__proto__:null,removeExtmapAllowMixed:bo,shimAddIceCandidateNullOrEmpty:Er,shimConnectionState:vo,shimMaxMessageSize:Tr,shimParameterlessSetLocalDescription:Pr,shimRTCIceCandidate:Sr,shimRTCIceCandidateRelayProtocol:go,shimSendThrowTypeError:xr});function cv(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Td,i=iv(t),r={browserDetails:i,commonShim:av,extractVersion:Oi,disableLog:tv,disableWarnings:nv,sdp:ov};switch(i.browser){case"chrome":if(!Fd||!fo||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Fd,Er(t,i),Pr(t),Id(t,i),Od(t),fo(t,i),Dd(t),Ld(t,i),Ad(t),Md(t),Ud(t,i),Sr(t),go(t),vo(t),Tr(t,i),xr(t),bo(t,i);break;case"firefox":if(!Jd||!po||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Jd,Er(t,i),Pr(t),Bd(t,i),po(t,i),jd(t),$d(t),Vd(t),qd(t),zd(t),Wd(t),Hd(t),Gd(t),Kd(t),Sr(t),vo(t),Tr(t,i),xr(t);break;case"safari":if(!su||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=su,Er(t,i),Pr(t),tu(t),iu(t),Qd(t),Yd(t),Xd(t),nu(t),Zd(t),ru(t),Sr(t),go(t),Tr(t,i),xr(t),bo(t,i);break;default:n("Unsupported browser!");break}return r}cv({window:typeof window>"u"?void 0:window});const lv=10,Di="lk_e2ee",dv={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:lv,keyringSize:16};var dn;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(dn||(dn={}));var cu;(function(t){t.KeyRatcheted="keyRatcheted"})(cu||(cu={}));var un;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(un||(un={}));var lu;(function(t){t.Error="cryptorError"})(lu||(lu={}));function uv(){return hv()||yo()}function yo(){return typeof window.RTCRtpScriptTransform<"u"}function hv(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class w_ extends St.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{Z.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},dv),e),this.on(dn.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(dn.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(dn.RatchetRequest,e,n)}}class Ht extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var te;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(te||(te={}));class de extends Ht{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=te[n]}}class ko extends Ht{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Gt extends Ht{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class fv extends Ht{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class De extends Ht{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Co extends Ht{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class du extends Ht{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class uu extends Ht{constructor(e,n){super(15,e),this.reason=n,this.reasonName=typeof n=="string"?n:co[n]}}var dt;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"})(dt||(dt={}));class hn extends Ht{constructor(e,n){super(16,e),this.name="DataStreamError",this.reason=n,this.reasonName=dt[n]}}var Rr;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Rr||(Rr={})),(function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e})(Rr||(Rr={}));var hu;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(hu||(hu={}));var O;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(O||(O={}));var L;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(L||(L={}));var N;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(N||(N={}));var A;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(A||(A={}));function pv(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const mv=/version\/(\d+(\.?_?\d+)+)/i;let wo;function Qe(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(wo===void 0||e){const i=gv.find(r=>{let{test:s}=r;return s.test(n)});wo=i==null?void 0:i.describe(n)}return wo}const gv=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:Ir(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:_o(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:Ir(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:_o(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:Ir(mv,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:_o(t)}}}];function Ir(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function _o(t){return t.includes("mac os")?Ir(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var vv="2.15.5";const bv=vv,yv=16;class Ue{}Ue.setTimeout=function(){return setTimeout(...arguments)},Ue.setInterval=function(){return setInterval(...arguments)},Ue.clearTimeout=function(){return clearTimeout(...arguments)},Ue.clearInterval=function(){return clearInterval(...arguments)};const kv=5e3,Ai=[];var Ze;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(Ze||(Ze={}));class E extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=E.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Z,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),kv):this.handleAppVisibilityChanged()},this.log=zt((r=i.loggerName)!==null&&r!==void 0?r:lt.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=E.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===E.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===E.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(Ai.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Ai.splice(Ai.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),Xn(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?A.AudioPlaybackStarted:A.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?A.AudioPlaybackFailed:A.VideoPlaybackFailed,s):s.name==="AbortError"?Z.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Z.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(A.ElementAttached,e),e}detach(e){try{if(e){Qn(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(A.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Qn(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(A.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=zt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),Ai.forEach(i=>{i.parentElement||(n=!1)}),n&&Ai.push(e)}}handleAppVisibilityChanged(){return C(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===E.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){He()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){He()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Xn(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!On()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(On()||Zn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Qn(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(l){switch(l){case e.Audio:return ot.AUDIO;case e.Video:return ot.VIDEO;default:return ot.DATA}}t.kindToProto=r;function s(l){switch(l){case ot.AUDIO:return e.Audio;case ot.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=s;function o(l){switch(l){case n.Camera:return xe.CAMERA;case n.Microphone:return xe.MICROPHONE;case n.ScreenShare:return xe.SCREEN_SHARE;case n.ScreenShareAudio:return xe.SCREEN_SHARE_AUDIO;default:return xe.UNKNOWN}}t.sourceToProto=o;function a(l){switch(l){case xe.CAMERA:return n.Camera;case xe.MICROPHONE:return n.Microphone;case xe.SCREEN_SHARE:return n.ScreenShare;case xe.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=a;function c(l){switch(l){case to.ACTIVE:return i.Active;case to.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=c})(E||(E={}));class ce{constructor(e,n,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Cv=["vp8","h264"],wv=["vp8","h264","vp9","av1","h265"];function _v(t){return!!Cv.find(e=>e===t)}var fu;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(fu||(fu={}));var So;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(So||(So={}));const Mi={h90:new ce(160,90,9e4,20),h180:new ce(320,180,16e4,20),h216:new ce(384,216,18e4,20),h360:new ce(640,360,45e4,20),h540:new ce(960,540,8e5,25),h720:new ce(1280,720,17e5,30),h1080:new ce(1920,1080,3e6,30),h1440:new ce(2560,1440,5e6,30),h2160:new ce(3840,2160,8e6,30)},To={h120:new ce(160,120,7e4,20),h180:new ce(240,180,125e3,20),h240:new ce(320,240,14e4,20),h360:new ce(480,360,33e4,20),h480:new ce(640,480,5e5,20),h540:new ce(720,540,6e5,25),h720:new ce(960,720,13e5,30),h1080:new ce(1440,1080,23e5,30),h1440:new ce(1920,1440,38e5,30)},xo={h360fps3:new ce(640,360,2e5,3,"medium"),h360fps15:new ce(640,360,4e5,15,"medium"),h720fps5:new ce(1280,720,8e5,5,"medium"),h720fps15:new ce(1280,720,15e5,15,"medium"),h720fps30:new ce(1280,720,2e6,30,"medium"),h1080fps15:new ce(1920,1080,25e5,15,"medium"),h1080fps30:new ce(1920,1080,5e6,30,"medium"),original:new ce(0,0,7e6,30,"medium")},Sv="|",pu="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Tv(t){const e=t.split(Sv);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function We(t){return C(this,void 0,void 0,function*(){return new Promise(e=>Ue.setTimeout(e,t))})}function Eo(){return"addTransceiver"in RTCPeerConnection.prototype}function Po(){return"addTrack"in RTCPeerConnection.prototype}function xv(){if(!("getCapabilities"in RTCRtpSender)||On())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/AV1"){e=!0;break}}return e}function Ev(){if(!("getCapabilities"in RTCRtpSender)||Zn())return!1;if(On()){const n=Qe();if(n!=null&&n.version&&Et(n.version,"16")<0||(n==null?void 0:n.os)==="iOS"&&(n!=null&&n.osVersion)&&Et(n.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/VP9"){e=!0;break}}return e}function Tt(t){return t==="av1"||t==="vp9"}function Ro(t){return!document||Or()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function Pv(){return typeof RTCPeerConnection>"u"?!1:Eo()||Po()}function Zn(){var t;return((t=Qe())===null||t===void 0?void 0:t.name)==="Firefox"}function On(){var t;return((t=Qe())===null||t===void 0?void 0:t.name)==="Safari"}function Or(){const t=Qe();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function Rv(){const t=Qe();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Et(t.osVersion,"17")>=0}function Iv(t){return t||(t=Qe()),(t==null?void 0:t.name)==="Safari"&&Et(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Et(t.osVersion,"18.3")>0}function mu(){var t,e;return He()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Ov(){const t=Qe(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&Et(e,t.osVersion)>=0?!0:t.name==="Safari"&&Et(e,t.version)>=0}function He(){return typeof document<"u"}function xt(){return navigator.product=="ReactNative"}function Io(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function gu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function vu(){if(!xt())return;let t=gu();if(t)return t.platform}function bu(){if(He())return window.devicePixelRatio;if(xt()){let t=gu();if(t)return t.devicePixelRatio}return 1}function Et(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function Dv(t){for(const e of t)e.target.handleResize(e)}function Av(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Oo=null;const yu=()=>(Oo||(Oo=new ResizeObserver(Dv)),Oo);let Do=null;const ku=()=>(Do||(Do=new IntersectionObserver(Av,{root:null,rootMargin:"0px"})),Do);function Mv(){var t;const e=new wg({sdk:nd.JS,protocol:yv,version:bv});return xt()&&(e.os=(t=vu())!==null&&t!==void 0?t:""),e}function Cu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=t,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(t/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Ni;function Ao(){if(!Ni){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[Ni]=i.stream.getAudioTracks(),!Ni)throw Error("Could not get empty media stream audio track");Ni.enabled=!1}return Ni.clone()}class Pt{get isResolved(){return this._isResolved}constructor(e,n){this._isResolved=!1,this.onFinally=n,this.promise=new Promise((i,r)=>C(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function Nv(t){return wv.includes(t)}function fn(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Lv(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function Mo(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function Uv(t,e){return t.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const d=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,d),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:d,lastReceivedTime:u}})}function Fv(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function wu(t){switch(t.reason){case te.LeaveRequest:return t.context;case te.Cancelled:return at.CLIENT_INITIATED;case te.NotAllowed:return at.USER_REJECTED;case te.ServerUnreachable:return at.JOIN_FAILURE;default:return at.UNKNOWN_REASON}}function Dr(t){return t!==void 0?Number(t):void 0}function Dn(t){return t!==void 0?BigInt(t):void 0}function ei(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Rt(t){return!!t&&t.kind==E.Kind.Audio}function An(t){return!!t&&t.kind==E.Kind.Video}function pn(t){return ei(t)&&An(t)}function Kt(t){return ei(t)&&Rt(t)}function No(t){return!!t&&!t.isLocal}function Bv(t){return!!t&&!t.isLocal}function Lo(t){return No(t)&&An(t)}function jv(t){return t.isLocal}function Vv(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function _u(t,e,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=xu(t??{}),d=e==null?void 0:e.processor,u=n==null?void 0:n.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Uo(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(Uo(h.video,n),(r=(o=h.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function Uo(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function Fo(t){var e,n,i,r;const s={};if(t.video)if(typeof t.video=="object"){const o={},a=o,c=t.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Uo(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=t.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return t.audio?typeof t.audio=="object"?(s.audio=t.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Su(t){return C(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Tu();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield We(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1})()})}function Tu(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>C(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function qv(t){return t==="audioinput"?E.Source.Microphone:t==="videoinput"?E.Source.Camera:E.Source.Unknown}function Bo(t){return t===E.Source.Microphone?"audioinput":t===E.Source.Camera?"videoinput":void 0}function $v(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,On()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function Ar(t){return t.split("/")[1].toLowerCase()}function zv(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new oo({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function X(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?X(t.track):{})}}function Wv(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Hv(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const s of i)t[s]!==e[s]&&(r[s]=(n=e[s])!==null&&n!==void 0?n:"");return r}function xu(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:pv(e)}}function Gv(t){switch(t){case xe.CAMERA:return E.Source.Camera;case xe.MICROPHONE:return E.Source.Microphone;case xe.SCREEN_SHARE:return E.Source.ScreenShare;case xe.SCREEN_SHARE_AUDIO:return E.Source.ScreenShareAudio;default:return E.Source.Unknown}}function Eu(t,e){return t.width*t.height<e.width*e.height}function Kv(t,e){var n;return(n=t.layers)===null||n===void 0?void 0:n.find(i=>i.quality===e)}class Jv extends St.EventEmitter{constructor(e){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":Z.error(o.error.message),this.emit(un.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(un.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(un.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(dn.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{Z.error("e2ee worker encountered an error:",{error:n.error}),this.emit(un.EncryptionError,n.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!uv())throw new ko("tried to setup end-to-end encryption on an unsupported browser");if(Z.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Yg.getLevel()}};this.worker&&(Z.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){Z.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?Z.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(N.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(O.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Xe.NONE,r.identity)),e.on(O.ConnectionStateChanged,i=>{i===ne.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Xe.NONE,r.identity)})})}).on(O.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(O.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(O.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(L.LocalSenderCreated,(i,r)=>C(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),n.on(dn.SetKey,i=>this.postKey(i)).on(dn.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,n,e.kind==="video"?Ar(i.mimeType):void 0)}}setupE2EESender(e,n){if(!ei(e)||!n){n||Z.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return C(this,void 0,void 0,function*(){if(this.worker){if(yo()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Di in e&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,o=e.readableStream;if(!s||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:Di in e}};this.worker.postMessage(a,[o,s])}e[Di]=!0}})}handleSender(e,n,i){var r;if(!(Di in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(yo()){Z.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{Z.info("initialize encoded streams");const s=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}e[Di]=!0}}}const jo="default";class Ne{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Ne),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=Ne.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){Z.debug("awaiting getUserMedia promise");try{n?yield Ne.userMediaPromiseMap.get(n):yield Promise.all(Ne.userMediaPromiseMap.values())}catch{Z.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(On()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",d=n?c.kind===n:!0;return l&&d}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o})()})}normalizeDeviceId(e,n,i){return C(this,void 0,void 0,function*(){if(n!==jo)return n;const r=yield this.getDevices(e),s=r.find(a=>a.deviceId===jo);if(!s){Z.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==jo&&a.groupId===(i??s.groupId));if(!o){Z.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?Ne.userMediaPromiseMap.has(e):Ne.userMediaPromiseMap.size>0}}Ne.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ne.userMediaPromiseMap=new Map;var Li;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Li||(Li={}));class Yv{constructor(){this.pendingTasks=new Map,this.taskMutex=new qe,this.nextTaskIndex=0}run(e){return C(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Li.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=Li.RUNNING,yield e()}finally{n.status=Li.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return C(this,void 0,void 0,function*(){return this.run(()=>C(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function Xv(t,e){const n=new URL(Lv(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),Pu(n,"rtc")}function Qv(t){const e=new URL(Mo(t));return Pu(e,"validate")}function Zv(t){return t.endsWith("/")?t:"".concat(t,"/")}function Pu(t,e){return t.pathname="".concat(Zv(t.pathname)).concat(e),t.toString()}const e0=["syncState","trickle","offer","answer","simulate","leave"];function t0(t){const e=e0.indexOf(t.case)>=0;return Z.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var he;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(he||(he={}));class Vo{get currentState(){return this.state}get isDisconnected(){return this.state===he.DISCONNECTING||this.state===he.DISCONNECTED}get isEstablishingConnection(){return this.state===he.CONNECTING||this.state===he.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=he.DISCONNECTED,this.log=Z,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=zt((i=n.loggerName)!==null&&i!==void 0?i:lt.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new Yv,this.queuedRequests=[],this.closingLock=new qe,this.connectionLock=new qe,this.state=he.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return C(this,void 0,void 0,function*(){return this.state=he.CONNECTING,this.options=i,yield this.connect(e,n,i,r)})}reconnect(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=he.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,n,i,r){this.connectOptions=i;const s=Mv(),o=n0(n,s,i),a=Xv(e,o),c=Qv(a);return new Promise((l,d)=>C(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>C(this,void 0,void 0,function*(){this.close(),clearTimeout(f),d(new de("room connection has been cancelled (signal)",te.Cancelled))}),f=setTimeout(()=>{this.close(),d(new de("room connection has timed out (signal)",te.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const g=new URL(a);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=p=>C(this,void 0,void 0,function*(){if(this.state!==he.CONNECTED){this.state=he.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(c);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();d(new de(b,te.NotAllowed,v.status))}else d(new de("Encountered unknown websocket error during connection: ".concat(p.toString()),te.InternalError,v.status))}catch(v){d(new de(v instanceof Error?v.message:"server was not reachable",te.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>C(this,void 0,void 0,function*(){var v,b,k;let w;if(typeof p.data=="string"){const y=JSON.parse(p.data);w=cd.fromJson(y,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)w=cd.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==he.CONNECTED){let y=!1;if(((v=w.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=he.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=w.message.value.pingTimeout,this.pingIntervalDuration=w.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(w.message.value)):this.state===he.RECONNECTING&&w.message.case!=="leave"?(this.state=he.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=w.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(w.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),y=!0)):this.isEstablishingConnection&&w.message.case==="leave"?d(new de("Received leave request while trying to (re)connect",te.LeaveRequest,void 0,w.message.value.reason)):i.reconnect||d(new de("did not receive join response, got ".concat((k=w.message)===null||k===void 0?void 0:k.case," instead"),te.InternalError)),!y)return}this.signalLatency&&(yield We(this.signalLatency)),this.handleSignalResponse(w)}),this.ws.onclose=p=>{this.isEstablishingConnection&&d(new de("Websocket got closed during a (re)connection attempt",te.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{u()}}))}close(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=he.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,We(250)])),e.ws=void 0}}finally{n&&(e.state=he.DISCONNECTED),i()}})()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Mr(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Mr(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ro({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new so({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new hd({requestId:a,metadata:i,name:r,attributes:o})}),a})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,n){return this.sendRequest({case:"updateLayers",value:new ud({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new md({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:pe.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new yd({timestamp:pe.parse(Date.now()),rtt:pe.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new dd({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new kr({reason:at.CLIENT_INITIATED,action:Jn.DISCONNECT})})}sendRequest(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!t0(n)&&i.state===he.RECONNECTING){i.queuedRequests.push(()=>C(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield We(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(n.case,") - SignalClient disconnected"));return}if(!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new Tg({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}})()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=Ru(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=Ru(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return C(this,void 0,void 0,function*(){if(this.state===he.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Ue.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Ue.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Ue.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ue.clearInterval(this.pingInterval)}}function Ru(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function Mr(t,e){return new Rn({sdp:t.sdp,type:t.type,id:e})}function n0(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",xt()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class Iu{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class i0{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(e(s,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var ut={},qo={},$o={exports:{}},Ou;function zo(){if(Ou)return $o.exports;Ou=1;var t=$o.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),$o.exports}var Du;function r0(){return Du||(Du=1,(function(t){var e=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},i=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;n(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},r=zo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(r[h]||[]).length;g+=1){var p=r[h][g];if(p.reg.test(f))return i(p,d,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(qo)),qo}var Wo,Au;function s0(){if(Au)return Wo;Au=1;var t=zo(),e=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return n.apply(null,d)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Wo=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,d=[];return c.forEach(function(u){t[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(i(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){d.push(i(u,h,f))})})}),o.media.forEach(function(u){d.push(i("m",t.m[0],u)),l.forEach(function(h){t[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(i(h,f,g))})})})}),d.join(`\r
37
37
  `)+`\r
38
- `},Wo}var Mu;function o0(){if(Mu)return ut;Mu=1;var t=r0(),e=s0(),n=zo();return ut.grammar=n,ut.write=e,ut.parse=t.parse,ut.parseParams=t.parseParams,ut.parseFmtpConfig=t.parseFmtpConfig,ut.parsePayloads=t.parsePayloads,ut.parseRemoteCandidates=t.parseRemoteCandidates,ut.parseImageAttributes=t.parseImageAttributes,ut.parseSimulcastStreamList=t.parseSimulcastStreamList,ut}var mn=o0();function Ho(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(p,v){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var w=t.apply(g,f);a&&a(w),d.forEach(function(y){return(0,y.resolve)(w)}),d=[]}},u()),b){var k=t.apply(g,f);return a&&a(k),p(k)}d.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const a0=.7,c0=20,ti={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Nu extends St.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Z,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ho(r=>C(this,void 0,void 0,function*(){this.emit(ti.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),c0),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=zt((i=n.loggerName)!==null&&i!==void 0?i:lt.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new qe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return C(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return C(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:o}=l0(e);this.remoteStereoMids=s,this.remoteNackMids=o}else if(e.type==="answer"){const s=mn.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=mn.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(ti.NegotiationComplete),e.sdp&&mn.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(ti.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const o=mn.parse((n=s.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(a=>{Uu(a),a.type==="audio"?Lu(a,[],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Tt(c.codec)&&!On()&&this.ensureVideoDDExtensionForSVC(a,o),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*a0);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,mn.write(o)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=mn.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Uu(r),r.type==="audio"&&Lu(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,mn.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new De("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new De("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return C(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return C(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Co(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===pu))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:pu})}}}function Lu(t,e,n){let i=0;t.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(t.mid)&&!t.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&t.rtcpFb.push({payload:i,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function l0(t){var e;const n=[],i=[],r=mn.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function Uu(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const Go="vp8",d0={audioPreset:So.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:xo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Go,backupCodec:!0,preConnectBuffer:!1},Fu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Bu={deviceId:{ideal:"default"},resolution:Mi.h720.resolution},u0={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Qg,disconnectOnPageLeave:!0,webAudioMix:!1},Ko={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ke;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(ke||(ke={}));class h0{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Ko.peerConnectionTimeout,this.log=Z,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=ke.CONNECTED:a.some(c=>c==="failed")?this.state=ke.FAILED:a.some(c=>c==="connecting")?this.state=ke.CONNECTING:a.every(c=>c==="closed")?this.state=ke.CLOSED:a.some(c=>c==="closed")?this.state=ke.CLOSING:a.every(c=>c==="new")&&(this.state=ke.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(ke[o]," to ").concat(ke[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=zt((r=i.loggerName)!==null&&r!==void 0?r:lt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new Nu(e,i),this.subscriber=new Nu(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ct.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ct.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=ke.NEW,this.connectionLock=new qe,this.remoteOfferLock=new qe}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return C(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const n of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return C(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return C(this,void 0,void 0,function*(){n===ct.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return C(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(e,n){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return C(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return C(this,void 0,void 0,function*(){return new Promise((n,i)=>C(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(ti.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(ti.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===ct.PUBLISHER?this.publisher.getConnectedAddress():e===ct.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>C(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Ue.clearTimeout(u),l(new de("room connection has been cancelled",te.Cancelled))};r!=null&&r.signal.aborted&&d(),r==null||r.signal.addEventListener("abort",d);const u=Ue.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",d),l(new de("could not establish pc connection",te.InternalError))},o);for(;this.state!==ke.CONNECTED;)if(yield We(50),r!=null&&r.signal.aborted){l(new de("room connection has been cancelled",te.Cancelled));return}Ue.clearTimeout(u),r==null||r.signal.removeEventListener("abort",d),c()}))})()})}}class Ce extends Error{constructor(e,n,i){super(n),this.code=e,this.message=Vu(n,Ce.MAX_MESSAGE_BYTES),this.data=i?Vu(i,Ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ce(e.code,e.message,e.data)}toProto(){return new Ql({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Ce(Ce.ErrorCode[e],Ce.ErrorMessage[e],n)}}Ce.MAX_MESSAGE_BYTES=256,Ce.MAX_DATA_BYTES=15360,Ce.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ce.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ju=15360;function Jo(t){return new TextEncoder().encode(t).length}function Vu(t,e){if(Jo(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const Yo=2e3;function Nr(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const Xo=typeof MediaRecorder<"u";class f0{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const p0=Xo?MediaRecorder:f0;class m0 extends p0{constructor(e,n){if(!Xo)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>C(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(d)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function g0(){return Xo}const v0=1e3,b0=1e4;class qu extends E{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Ho(()=>C(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>C(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(A.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new qe,this.pauseUpstreamLock=new qe,this.trackChangeLock=new qe,this.trackChangeLock.lock().then(o=>C(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==E.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return C(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Qn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Xn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Xn(r??e,s)}))})}waitForDimensions(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:v0;return(function*(){var i;if(e.kind===E.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Qe())===null||i===void 0?void 0:i.os)==="iOS"&&(yield We(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield We(50)}throw new Gt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return C(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===E.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===E.Kind.Audio?"audioinput":"videoinput";return n?Ne.getInstance().normalizeDeviceId(s,i,r):i})()})}mute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return C(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Gt("unable to replace an unpublished track");let r,s;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,s=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return C(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Zg(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===E.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Qn(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(A.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),mu()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(A.UpstreamPaused,this);const i=Qe();if((i==null?void 0:i.name)==="Safari"&&Et(i.version,"12.0")<0)throw new ko("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(A.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Xn(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:d}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Qn(i._mediaStreamTrack,l),Xn(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(A.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}})()})}internalStopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(A.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!g0()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new m0(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},b0)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Lr extends qu{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,E.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,Me.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,Me.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fn(this._constraints.deviceId);return this.source===E.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return C(this,void 0,void 0,function*(){let n;if(e){const i=Fo({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return C(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){He()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Yo)))}setProcessor(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(A.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return C(this,void 0,void 0,function*(){const e=yield Su(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(A.AudioSilenceDetected)),e})}}function y0(t,e,n){switch(t.kind){case"audio":return new Lr(t,e,!1,void 0,n);case"video":return new Ur(t,e,!1,n);default:throw new Gt("unsupported track type: ".concat(t.kind))}}const k0=Object.values(Mi),C0=Object.values(To),w0=Object.values(xo),_0=[Mi.h180,Mi.h360],S0=[To.h180,To.h360],T0=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ce(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Qo=["q","h","f"];function Zo(t,e,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!n)return[{}];o||(o=E0(t,e,n,l),Z.debug("using video encoding",o));const d=o.maxFramerate,u=new ce(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Tt(l)){const g=new Wu(c),p=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Qe();if(Or()||xt()||(v==null?void 0:v.name)==="Chrome"&&Et(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3,k=Iv(v);for(let w=0;w<g.spatial;w+=1)p.push({rid:Qo[2-w],maxBitrate:o.maxBitrate/Math.pow(b,w),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:k?Math.pow(2,w):void 0});p[0].scalabilityMode=c}else p.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(p[0].priority=u.encoding.priority,p[0].networkPriority=u.encoding.priority),Z.debug("using svc encoding",{encodings:p}),p}if(!a)return[o];let h=[];t?h=(r=zu(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:$u(t,u):h=(s=zu(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:$u(t,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const p=Math.max(e,n);if(p>=960&&f)return ea(e,n,[g,f,u],d);if(p>=480)return ea(e,n,[g,u],d)}return ea(e,n,[u])}function x0(t,e,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Z.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===E.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Zo(t.source===E.Source.ScreenShare,c,l,n)}function E0(t,e,n,i){const r=P0(t,e,n);let{encoding:s}=r[0];const o=Math.max(e,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function P0(t,e,n){if(t)return w0;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?k0:C0}function $u(t,e){if(t)return T0(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?_0:S0}function ea(t,e,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=Qo.length)return;const a=Math.min(t,e),l={rid:Qo[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=Zn()||o===0;s.encoding.priority&&u&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),xt()&&vu()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,Z.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Z.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function zu(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Wu{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function R0(t){return t.source===E.Source.ScreenShare||t.constraints.height&&fn(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const I0=5e3;class Ur extends qu{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,E.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(s.map(c=>[c.rid,c])),a=s.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(A.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=Nr(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new qe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!He())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Yo))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Wt(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Wt(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const d=s;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(e){const n=[];for(let i=Ze.LOW;i<=Ze.HIGH;i+=1)n.push(new ao({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Tt(this.codec),n)}restartTrack(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(e){const u=Fo({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=Wt(this.simulcastCodecs.values()),d;d=yield l.next(),n=d.done,!n;c=!0){s=d.value,c=!1;const u=s;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return C(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield n.setProcessor.call(r,i,s),!((d=r.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=Wt(r.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(p){a={error:p}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return C(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},I0))}setPublishingCodecs(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Tt(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=Wt(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Tt(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield Hu(u.sender,u.encodings,d.qualities,this.senderLock,Tt(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,n){return C(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield Hu(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return C(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&Tt(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),mu()&&this.isInBackground&&this.source===E.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Hu(t,e,n,i,r,s,o){return C(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(r&&n.some(f=>f.enabled)&&n.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let p=(g=h.rid)!==null&&g!==void 0?g:"";p===""&&(p="q");const v=Gu(p),b=n.find(k=>k.quality===v);b&&h.active!==b.enabled&&(d=!0,h.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),o),Zn()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield t.setParameters(c))}finally{a()}})}function Gu(t){switch(t){case"f":return Ze.HIGH;case"h":return Ze.MEDIUM;case"q":return Ze.LOW;default:return Ze.HIGH}}function Ku(t,e,n,i){if(!n)return[new Pn({quality:Ze.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new Wu(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new Pn({quality:Math.min(Ze.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Gu((o=r.rid)!==null&&o!==void 0?o:"");return new Pn({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Ju="_lossy",Yu="_reliable",O0=2*1e3,ta="leave-reconnect",D0=3e4;var ht;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(ht||(ht={}));class A0 extends St.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ko.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ht.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Z,this.reliableDataSequence=1,this.reliableMessageBuffer=new Iu,this.reliableReceivedState=new i0(D0),this.handleDataChannel=i=>C(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return(function*(){if(o){if(o.label===Yu)s.reliableDCSub=o;else if(o.label===Ju)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}})()}),this.handleDataMessage=i=>C(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ze.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&N0(c,c.value.value),this.emit(N.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?J.LOSSY:J.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(N.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===ta&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ue.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ht.Connected&&i();const s=()=>{this.off(N.Disconnected,o),i()},o=()=>{this.off(N.Restarted,s),r()};this.once(N.Restarted,s),this.once(N.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(N.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===J.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===he.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Hn.RR_SIGNAL_DISCONNECTED))},this.log=zt((n=e.loggerName)!==null&&n!==void 0?n:lt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Vo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new qe,this.dataProcessLock=new qe,this.dcBufferStatus=new Map([[J.LOSSY,!0],[J.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(N.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(N.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(N.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(N.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(N.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(N.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(N.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(N.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return C(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(N.SignalConnected,s),s}catch(s){if(s instanceof de&&s.reason===te.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw s}})}close(){return C(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(N.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return C(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Iu,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return C(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Gt("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new de("publication of local track timed out, no response from server",te.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return C(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return C(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==ke.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new h0(r,e.subscriberPrimary,this.loggerOptions),this.emit(N.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>C(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===ke.CONNECTED){const d=this.pcState===ht.New;this.pcState=ht.Connected,d&&this.emit(N.Connected,e)}else s===ke.FAILED&&this.pcState===ht.Connected&&(this.pcState=ht.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Hn.RR_SUBSCRIBER_FAILED:Hn.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===he.RECONNECTING,l=[ke.FAILED,ke.CLOSING,ke.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(N.Offline)}),this.pcManager.onTrack=s=>{this.emit(N.MediaTrackAdded,s.track,s.streams[0],s.receiver)},M0((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n)=>C(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n)=>C(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(N.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(N.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(N.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(N.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(N.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Hn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Jn.DISCONNECT:this.emit(N.Disconnected,e==null?void 0:e.reason),this.close();break;case Jn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ta);break;case Jn.RESUME:this.handleDisconnect(ta)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Pi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ju,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Yu,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,n,i){return C(this,void 0,void 0,function*(){if(Eo())return yield this.createTransceiverRTCRtpSender(e,n,i);if(Po())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new De("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(Eo())return this.createSimulcastTransceiverSender(e,n,i,r);if(Po())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new De("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),An(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return C(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Z.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===Pi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:ke.NEW)===ke.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof De?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof ni||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Hn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(N.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return C(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new De("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ni;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof de&&o.reason===te.NotAllowed?new De("could not reconnect, token might be expired"):new ni}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(N.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==he.CONNECTED)throw new ni("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(N.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return C(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new De("could not reconnect, url or token not saved");if(!this.pcManager)throw new De("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof de&&r.reason===te.NotAllowed?new De("could not reconnect, token might be expired"):r instanceof de&&r.reason===te.LeaveRequest?r:new ni(s)}if(this.emit(N.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==he.CONNECTED)throw new ni("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(N.Resumed)})}waitForPCInitialConnection(e,n){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return C(this,void 0,void 0,function*(){this.pcState=ht.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield We(O0),!this.pcManager)throw new De("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ht.Connected}catch(e){throw this.pcState=ht.Disconnected,new de("could not establish PC connection, ".concat(e.message),te.InternalError)}})}publishRpcResponse(e,n,i,r){return C(this,void 0,void 0,function*(){const s=new ze({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcResponse",value:new Xl({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,J.RELIABLE)})}publishRpcAck(e,n){return C(this,void 0,void 0,function*(){const i=new ze({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcAck",value:new Yl({requestId:n})}});yield this.sendDataPacket(i,J.RELIABLE)})}sendDataPacket(e,n){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===J.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===J.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(J.RELIABLE);const n=this.dataChannelForKind(J.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(J.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>C(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(N.Closing,r);!this.dcBufferStatus.get(e);)yield We(10);this.off(N.Closing,r),n()}}))}ensureDataTransportConnected(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new De("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new de("".concat(a," connection not set"),te.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield We(50)}throw new de("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),te.InternalError)})()})}ensurePublisherConnected(e){return C(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ke.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return C(this,void 0,void 0,function*(){return new Promise((e,n)=>C(this,void 0,void 0,function*(){if(!this.pcManager){n(new Co("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(N.Closing,r),this.pcManager.publisher.once(ti.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();Nv(c)&&o.set(a.payload,c)}),this.emit(N.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Co&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Hn.RR_UNKNOWN),n(s)}finally{this.off(N.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===J.LOSSY)return this.lossyDCSub;if(e===J.RELIABLE)return this.reliableDCSub}else{if(e===J.LOSSY)return this.lossyDC;if(e===J.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==a&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new gd({answer:s?Mr({sdp:s.sdp,type:s.type}):void 0,offer:o?Mr({sdp:o.sdp,type:o.type}):void 0,subscription:new yr({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:zv(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new vd({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new bd({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(J.LOSSY),ct.PUBLISHER),n(this.dataChannelForKind(J.RELIABLE),ct.PUBLISHER),n(this.dataChannelForKind(J.LOSSY,!0),ct.SUBSCRIBER),n(this.dataChannelForKind(J.RELIABLE,!0),ct.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ue.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){He()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){He()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ni extends Error{}function M0(t){return t!==void 0&&t>13}function N0(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class na{constructor(e,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Io(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return C(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),Z.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return C(this,void 0,void 0,function*(){const n=yield fetch("".concat(L0(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new de("Could not fetch region settings: ".concat(n.statusText),n.status===401?te.NotAllowed:te.InternalError,n.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function L0(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class Xu{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new hn("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),dt.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new hn("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),dt.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class U0 extends Xu{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new Pt,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var a;(a=n.reject)===null||a===void 0||a.call(n,o.reason)},o.addEventListener("abort",r),i=o}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),n.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw s(),c}}),return(){return C(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a=new Set;const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=Wt(c),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return Array.from(a)})()})}}class F0 extends Xu{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=Dr(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new Pt,r=null,s=null;if(this.signal){const a=this.signal;s=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,a.reason)},a.addEventListener("abort",s),r=a}const o=()=>{e.releaseLock(),r&&s&&r.removeEventListener("abort",s),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),i.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=n.decode(d.content)}catch(h){throw new hn("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),dt.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return C(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a="";const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=Wt(c),u;u=yield d.next(),i=u.done,!i;l=!0)o=u.value,l=!1,a+=o}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return a})()})}}class B0{constructor(){this.log=Z,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new hn('A text stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new hn('A byte stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,s;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new hn("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),dt.AbnormalEnd);for(const[l,d]of a)(i=(n=d.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(s=(r=d.outOfBandFailureRejectingFuture).reject)===null||s===void 0||s.call(r,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e){return C(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n){return C(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const o=new Pt,a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Dr(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new hn("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new U0(a,c,Dr(e.totalLength),o),{identity:n})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const o=new Pt,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new hn("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new F0(a,c,Dr(e.totalLength),o),{identity:n})}})}handleStreamChunk(e){const n=this.byteStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class Qu{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return C(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class j0 extends Qu{}class V0 extends Qu{}const Zu=15e3;class q0{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return C(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((p,v)=>p+v,0);(f=n==null?void 0:n.onProgress)===null||f===void 0||f.call(n,g)},d=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield d.write(e),l(1,0),yield d.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((u,h)=>C(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:n.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return C(this,void 0,void 0,function*(){var n,i;const r=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new Qs({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Dn(s.timestamp),totalLength:Dn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new od({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Xs.UPDATE:Xs.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new ze({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,J.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(g){return C(this,void 0,void 0,function*(){for(const p of Vv(g,Zu)){yield d.waitForBufferStatusLow(J.RELIABLE);const v=new Zs({content:p,streamId:r,chunkIndex:Dn(l)}),b=new ze({destinationIdentities:a,value:{case:"streamChunk",value:v}});yield d.sendDataPacket(b,J.RELIABLE),l+=1}})},close(){return C(this,void 0,void 0,function*(){const g=new eo({streamId:r}),p=new ze({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield d.sendDataPacket(p,J.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>C(this,void 0,void 0,function*(){yield f.close()});d.once(N.Closing,h);const f=new j0(u,s,()=>this.engine.off(N.Closing,h));return f})}sendFile(e,n){return C(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return C(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:a,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},d=new Qs({totalLength:Dn((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:Dn(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new ad({name:l.name})}}),u=new ze({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,J.RELIABLE);let h=0;const f=new qe,g=this.engine,p=this.log,v=new WritableStream({write(k){return C(this,void 0,void 0,function*(){const w=yield f.lock();let y=0;try{for(;y<k.byteLength;){const _=k.slice(y,y+Zu);yield g.waitForBufferStatusLow(J.RELIABLE);const S=new ze({destinationIdentities:c,value:{case:"streamChunk",value:new Zs({content:_,streamId:a,chunkIndex:Dn(h)})}});yield g.sendDataPacket(S,J.RELIABLE),h+=1,y+=_.byteLength}}finally{w()}})},close(){return C(this,void 0,void 0,function*(){const k=new eo({streamId:a}),w=new ze({destinationIdentities:c,value:{case:"streamTrailer",value:k}});yield g.sendDataPacket(w,J.RELIABLE)})},abort(k){p.error("Sink error:",k)}});return new V0(v,l)})}}class eh extends E{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(A.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Yo)),Wv()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(A.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class $0 extends eh{constructor(e,n,i,r,s,o){super(e,n,E.Kind.Audio,i,o),this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(xt())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return C(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(Ro(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ro(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(A.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(A.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const ia=100;class z0 extends eh{constructor(e,n,i,r,s){super(e,n,E.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Ho(()=>{this.updateDimensions()},ia),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Qn(this._mediaStreamTrack,n):Xn(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new W0(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<ia){Ue.setTimeout(()=>{this.updateVisibility()},ia);return}this.lastVisible=o,this.emit(A.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(A.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?bu():n||(bu()>2?2:1)}}class W0{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=Ui(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ui(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ui(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??ra(e),this.isPiP=He()&&Ui(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=ra(this.element),this.isPiP=Ui(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ku().observe(this.element),yu().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=ku())===null||e===void 0||e.unobserve(this.element),(n=yu())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ui(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ra(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function ra(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class Jt extends St.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Xe.NONE,this.log=Z,this.handleMuted=()=>{this.emit(A.Muted)},this.handleUnmuted=()=>{this.emit(A.Unmuted)},this.log=zt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:lt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=E.Source.Unknown}setTrack(e){this.track&&(this.track.off(A.Muted,this.handleMuted),this.track.off(A.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(A.Muted,this.handleMuted),e.on(A.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Xe.NONE}get audioTrack(){if(Rt(this.track))return this.track}get videoTrack(){if(An(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=E.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===E.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(t.PermissionStatus||(t.PermissionStatus={}))})(Jt||(Jt={}));class sa extends Jt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(A.Ended)},this.handleCpuConstrained=()=>{this.track&&An(this.track)&&this.emit(A.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(A.Ended,this.handleTrackEnded),this.track.off(A.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(A.Ended,this.handleTrackEnded),e.on(A.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Rt(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(Me.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(Me.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(Me.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(Me.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Me.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Me.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Fr(t,e){return C(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=xu(t);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const u=s.audio.deviceId;s.audio.deviceId={exact:u},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:u}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const u=s.video.deviceId;s.video.deviceId={exact:u},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:u}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=_u(s,Fu,Bu),l=Fo(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(Ne.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Ne.userMediaPromiseMap.delete("audioinput"))),s.video&&(Ne.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Ne.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>C(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&fn(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const k=y0(h,p,e);return k.kind===E.Kind.Video?k.source=E.Source.Camera:k.kind===E.Kind.Audio&&(k.source=E.Source.Microphone),k.mediaStream=u,Rt(k)&&i?yield k.setProcessor(i):An(k)&&r&&(yield k.setProcessor(r)),k})))}catch(u){if(!n)throw u;return Fr(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}})}function H0(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:!1,video:!0}))[0]})}function th(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:t??!0,video:!1}))[0]})}var gn;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(gn||(gn={}));function G0(t){switch(t){case Ei.EXCELLENT:return gn.Excellent;case Ei.GOOD:return gn.Good;case Ei.POOR:return gn.Poor;case Ei.LOST:return gn.Lost;default:return gn.Unknown}}class nh extends St.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ri.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Gn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ri.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=gn.Unknown,this.log=Z,this.log=zt((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:lt.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Pt,this.once(L.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(E.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(E.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(E.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Gn.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Gn.ACTIVE&&this.emit(L.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(L.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(L.ParticipantNameChanged,e)}_setAttributes(e){const n=Hv(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(L.AttributesChanged,n)}setPermissions(e){var n,i,r,s,o,a;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(L.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(L.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=G0(e),n!==this._connectionQuality&&this.emit(L.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Rt(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(A.Muted,()=>{this.emit(L.TrackMuted,e)}),e.on(A.Unmuted,()=>{this.emit(L.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case E.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case E.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function K0(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new pd({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class J0 extends nh{constructor(e,n,i,r,s,o){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Xe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Pt)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Pt),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==co.OK&&u.reject(new uu(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=Ce.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>K0(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),X(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),X(c))),this.emit(L.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>C(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var p=!0,v=Wt(g),b;b=yield v.next(),c=b.done,!c;p=!0){u=b.value,p=!1;const k=u;_v(k)&&(this.log.debug("publish ".concat(k," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),X(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,k,f.options))}}catch(k){l={error:k}}finally{try{!p&&!c&&(d=v.return)&&(yield d.call(v))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>C(this,void 0,void 0,function*(){if(a.source===E.Source.ScreenShare||a.source===E.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),X(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Kt(a)||pn(a))try{if(He())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===E.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),X(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),X(a))),Kt(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),X(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Xe.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(N.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(N.Connected,this.handleReconnected).on(N.SignalConnected,this.handleSignalConnected).on(N.SignalRestarted,this.handleReconnected).on(N.SignalResumed,this.handleReconnected).on(N.Restarting,this.handleReconnecting).on(N.Resuming,this.handleReconnecting).on(N.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(N.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(N.Closing,this.handleClosing).on(N.SignalRequestResponse,this.handleSignalRequestResponse).on(N.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return C(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return(function*(){return new Promise((a,c)=>C(i,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(d=s??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-f<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[p,v]=g;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),a();return}yield We(50)}c(new uu("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))})()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(E.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(E.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(E.Source.ScreenShare,e,n,i)}setPermissions(e){const n=this.permissions,i=super.setPermissions(e);return i&&n&&this.emit(L.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){this.encryptionType=e?Xe.GCM:Xe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return C(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case E.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case E.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case E.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Gt(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(L.MediaDevicesError,l,Bo(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===E.Source.Microphone&&Rt(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),X(u))),l.push(this.publishTrack(u,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===E.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(E.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return C(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(E.Source.Camera)||this.pendingPublishing.has(E.Source.Microphone))){this.pendingPublishing.add(E.Source.Camera),this.pendingPublishing.add(E.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(E.Source.Camera),this.pendingPublishing.delete(E.Source.Microphone)}}})}createTracks(e){return C(this,void 0,void 0,function*(){var n,i;e??(e={});const r=_u(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Fr(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Rt(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=E.Source.Microphone,this.emit(L.AudioStreamAcquired)),An(a)&&(this.cameraError=void 0,a.source=E.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return C(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new ko("getDisplayMedia not supported");e.resolution===void 0&&!Rv()&&(e.resolution=xo.h1080fps30.resolution);const n=$v(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Gt("no video track found");const s=new Ur(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=E.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(L.AudioStreamAcquired);const a=new Lr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=E.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,n){return C(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;Kt(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),ei(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case E.Source.Microphone:b="audioinput";break;case E.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Lr(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ur(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Gt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),X(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),X(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(d=r.red)!==null&&d!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!Ov()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,k)=>C(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==he.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:X(i)}));const w=setTimeout(()=>{k(new du("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(w);const y=yield this.publish(i,p,g);b(y)}else try{const w=yield this.publish(i,p,g);b(w)}catch(w){k(w)}}catch(w){k(w)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Pt),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),X(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>Gv(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),X(e))),!1)}publish(e,n,i){return C(this,void 0,void 0,function*(){var r,s,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new du("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(R=>ei(e)&&R.source===e.source)&&e.source!==E.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),X(e))),n.stopMicTrackOnMute&&Rt(e)&&(e.stopOnMute=!0),e.source===E.Source.ScreenShare&&Zn()&&(n.simulcast=!1),n.videoCodec==="av1"&&!xv()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!Ev()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Go),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(R=>n.videoCodec===Ar(R.mime))||(n.videoCodec=Ar(this.enabledPublishVideoCodecs[0].mime)));const p=n.videoCodec;e.on(A.Muted,this.onTrackMuted),e.on(A.Unmuted,this.onTrackUnmuted),e.on(A.Ended,this.handleTrackEnded),e.on(A.UpstreamPaused,this.onTrackUpstreamPaused),e.on(A.UpstreamResumed,this.onTrackUpstreamResumed),e.on(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),k=e.getSourceTrackSettings();k.autoGainControl&&v.push(Me.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&v.push(Me.TF_ECHO_CANCELLATION),k.noiseSuppression&&v.push(Me.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&v.push(Me.TF_STEREO),b&&v.push(Me.TF_NO_DTX),Kt(e)&&e.hasPreConnectBuffer&&v.push(Me.TF_PRECONNECT_BUFFER);const w=new io({cid:e.mediaStreamTrack.id,name:n.name,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:v});let y;if(e.kind===E.Kind.Video){let R={width:0,height:0};try{R=yield e.waitForDimensions()}catch{const M=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Mi.h720.resolution;R={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{dims:R}))}w.width=R.width,w.height=R.height,pn(e)&&(Tt(p)&&(e.source===E.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),X(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),w.simulcastCodecs=[new no({codec:p,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Go}),n.backupCodec&&p!==n.backupCodec.codec&&w.encryption===Xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),w.simulcastCodecs.push(new no({codec:n.backupCodec.codec,cid:""})))),y=Zo(e.source===E.Source.ScreenShare,w.width,w.height,n),w.layers=Ku(w.width,w.height,y,Tt(n.videoCodec))}else e.kind===E.Kind.Audio&&(y=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=n.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new De("cannot publish track when not connected");const _=()=>C(this,void 0,void 0,function*(){var R,D,M;if(!this.engine.pcManager)throw new De("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,y),this.emit(L.LocalSenderCreated,e.sender,e),pn(e)&&((R=n.degradationPreference)!==null&&R!==void 0||(n.degradationPreference=R0(e)),e.setDegradationPreference(n.degradationPreference)),y)if(Zn()&&e.kind===E.Kind.Audio){let U;for(const j of this.engine.pcManager.publisher.getTransceivers())if(j.sender===e.sender){U=j;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((D=y[0])===null||D===void 0)&&D.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Tt(e.codec)&&(!((M=y[0])===null||M===void 0)&&M.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:w.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const x=new Promise((R,D)=>C(this,void 0,void 0,function*(){var M;try{S=yield this.engine.addTrack(w),R(S)}catch(U){e.sender&&(!((M=this.engine.pcManager)===null||M===void 0)&&M.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(j=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{error:j}))})),D(U)}}));if(this.enabledPublishVideoCodecs.length>0)S=(yield Promise.all([x,_()]))[0];else{S=yield x;let R;if(S.codecs.forEach(D=>{R===void 0&&(R=D.mimeType)}),R&&e.kind===E.Kind.Video){const D=Ar(R);D!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{codec:D})),n.videoCodec=D,y=Zo(e.source===E.Source.ScreenShare,w.width,w.height,n))}yield _()}const I=new sa(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(I.on(A.CpuConstrained,R=>this.onTrackCpuConstrained(R,I)),I.options=n,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:S})),pn(e)?e.startMonitor(this.engine.client):Kt(e)&&e.startMonitor(),this.addTrackPublication(I),this.emit(L.LocalTrackPublished,I),Kt(e)&&S.audioFeatures.includes(Me.TF_PRECONNECT_BUFFER)){const R=e.getPreConnectBuffer(),D=e.getPreConnectBufferMimeType();this.on(L.LocalTrackSubscribed,M=>{if(M.trackSid===S.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),X(e))),e.stopPreConnectBuffer()}}),R&&new Promise((U,j)=>C(this,void 0,void 0,function*(){var $,F,G,Y,W,ee;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),X(e)));const st=setTimeout(()=>{j(new Error("agent not active within 10 seconds"))},1e4),Ve=yield this.waitUntilActiveAgentPresent();clearTimeout(st),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),X(e)));const Lt=yield this.streamBytes({name:"preconnect-buffer",mimeType:D,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ve.identity],attributes:{trackId:I.trackSid,sampleRate:String((W=k.sampleRate)!==null&&W!==void 0?W:"48000"),channels:String((ee=k.channelCount)!==null&&ee!==void 0?ee:"1")}});try{for(var we=!0,bt=Wt(R),nn;nn=yield bt.next(),$=nn.done,!$;we=!0){Y=nn.value,we=!1;const yt=Y;yield Lt.write(yt)}}catch(yt){F={error:yt}}finally{try{!we&&!$&&(G=bt.return)&&(yield G.call(bt))}finally{if(F)throw F.error}}yield Lt.close(),U()}catch(st){j(st)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),X(e)))}).catch(U=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{error:U}))})}return I})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return C(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Xe.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new Gt("track is not published");if(!pn(e))throw new Gt("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=x0(e,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),X(e)));return}const c=e.addSimulcastTrack(n,a);if(!c)return;const l=new io({cid:c.mediaStreamTrack.id,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Ku(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new De("cannot publish track when not connected");const d=()=>C(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,n){return C(this,void 0,void 0,function*(){var i,r;if(ei(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),X(e))),yield l)}const s=this.getPublicationForTrack(e),o=s?X(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=s.track,e.off(A.Muted,this.onTrackMuted),e.off(A.Unmuted,this.onTrackUnmuted),e.off(A.Ended,this.handleTrackEnded),e.off(A.UpstreamPaused,this.onTrackUpstreamPaused),e.off(A.UpstreamResumed,this.onTrackUpstreamResumed),e.off(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ke.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),pn(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case E.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case E.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(L.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return C(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>C(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>C(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==E.Source.ScreenShare&&l.source!==E.Source.ScreenShareAudio&&(Kt(l)||pn(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?J.RELIABLE:J.LOSSY,o=r.destinationIdentities,a=r.topic,c=new ze({kind:s,value:{case:"user",value:new Gl({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)})()})}publishDtmf(e,n){return C(this,void 0,void 0,function*(){const i=new ze({kind:J.RELIABLE,value:{case:"sipDtmf",value:new Kl({code:e,digit:n})}});yield this.engine.sendDataPacket(i,J.RELIABLE)})}sendChatMessage(e,n){return C(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new ze({value:{case:"chatMessage",value:new Ys(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(L.ChatMessage,i),i})}editChatMessage(e,n){return C(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new ze({value:{case:"chatMessage",value:new Ys(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp),editTimestamp:pe.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(L.ChatMessage,i),i})}sendText(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return C(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return(function*(){return new Promise((l,d)=>C(i,void 0,void 0,function*(){var u,h,f,g;if(Jo(o)>ju){d(Ce.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Et((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(Ce.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,o,a-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),d(Ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),d(Ce.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(p,{resolve:(k,w)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),w?d(w):l(k??"")},participantIdentity:r})}))})()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return C(this,void 0,void 0,function*(){const o=new ze({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcRequest",value:new Jl({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,J.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),X(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Pt),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Kt(r)||pn(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return C(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===e});if(r)return r[1];yield We(20)}})}}class Y0 extends Jt{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(A.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new yr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Zl({participantSid:"",trackSids:[this.trackSid]})]});this.emit(A.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Jt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Jt.SubscriptionStatus.Subscribed:Jt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Jt.PermissionStatus.Allowed:Jt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Lo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Lo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ze.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(A.VisibilityChanged,this.handleVisibilityChange),r.off(A.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(A.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(A.VisibilityChanged,this.handleVisibilityChange),e.on(A.Ended,this.handleEnded),this.emit(A.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(A.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?A.Muted:A.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(A.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(A.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Lo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ld({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===E.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)Eu(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Kv(this.trackInfo,this.requestedMaxQuality);i&&Eu(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Ze.HIGH})),e.quality=Ze.HIGH)}this.emit(A.UpdateSettings,e)}}class Br extends nh{static fromParticipantInfo(e,n,i){return new Br(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ri.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(A.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(A.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(A.SubscriptionPermissionChanged,n=>{this.emit(L.TrackSubscriptionPermissionChanged,e,n)}),e.on(A.SubscriptionStatusChanged,n=>{this.emit(L.TrackSubscriptionStatusChanged,e,n)}),e.on(A.Subscribed,n=>{this.emit(L.TrackSubscribed,n,e)}),e.on(A.Unsubscribed,n=>{this.emit(L.TrackUnsubscribed,n,e)}),e.on(A.SubscriptionFailed,n=>{this.emit(L.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(L.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),X(a))),this.emit(L.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new z0(e,n,r,s):l=new $0(e,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&No(l)&&Rt(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=E.kindFromProto(r.type);if(!c)return;a=new Y0(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==E.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:X(l),newTrack:X(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),X(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(L.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case E.Kind.Audio:this.audioTrackPublications.delete(e);break;case E.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(L.TrackUnpublished,i)}setAudioOutput(e){return C(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Rt(i.track)&&No(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ne;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(ne||(ne={}));const X0=4*1e3;class ii extends St.EventEmitter{constructor(e){var n,i,r,s;if(super(),n=this,this.state=ne.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Z,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,a,c)=>C(this,void 0,void 0,function*(){var l;if(!Pv())throw xt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===ne.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ne.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Io(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new na(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const u=(f,g,p)=>C(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const k=new AbortController;this.abortController=k,d==null||d();try{yield this.attemptConnection(p??o,a,c,k),this.abortController=void 0,f()}catch(w){if(this.regionUrlProvider&&w instanceof de&&w.reason!==te.Cancelled&&w.reason!==te.NotAllowed){let y=null;try{y=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(_){if(_ instanceof de&&(_.status===401||_.reason===te.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(_);return}}y&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield u(f,g,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,wu(w)),g(w))}else{let y=at.UNKNOWN_REASON;w instanceof de&&(y=wu(w)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),g(w)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Pt((f,g)=>{u(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,d,u)=>C(this,void 0,void 0,function*(){var h,f,g;const p=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[k,w]=b;return"".concat(k,": ").concat(w)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(g=p.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new fv("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),p}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>C(this,void 0,void 0,function*(){var d,u;this.state===ne.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ko),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new de("could not establish signal connection",te.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof de&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new de("Connection attempt aborted",te.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}He()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),He()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ne.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return C(n,[...a],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var u,h,f,g;const p=yield l.disconnectLock.lock();try{if(l.state===ne.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ne.Connecting||l.state===ne.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new de("Client initiated disconnect",te.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,at.CLIENT_INITIATED),l.engine=void 0}finally{p()}})()})},this.onPageLeave=()=>C(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>C(this,void 0,void 0,function*(){const o=[],a=Qe();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Ao();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(O.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>C(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(ne.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=o=>C(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(ne.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===Gn.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),a.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(O.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?a.set(l.sid,d):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(O.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const d=E.streamStateFromProto(a.state);d!==l.track.streamState&&(l.track.streamState=d,c.emit(L.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(O.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(L.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(O.SipDTMFReceived,a,o),o==null||o.emit(L.SipDTMFReceived,a)},this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),d=Uv(a,this.transcriptionReceivedTimes);l==null||l.emit(A.TranscriptionReceived,d),c==null||c.emit(L.TranscriptionReceived,d,l),this.emit(O.TranscriptionReceived,d,c,l)},this.handleChatMessage=(o,a)=>{const c=Fv(a);this.emit(O.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(O.MetricsReceived,o,a)},this.handleDataStream=o=>{this.incomingDataStreamManager.handleDataStreamPacket(o)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>C(this,void 0,void 0,function*(){var o;((o=Qe())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(O.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(O.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(O.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(O.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(O.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>C(this,void 0,void 0,function*(){var a,c,l,d,u,h;(a=o.track)===null||a===void 0||a.on(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(A.Restarted,this.onLocalTrackRestarted),(u=(d=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(O.LocalTrackPublished,o,this.localParticipant),Kt(o.track)&&(yield o.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,o);const f=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Bo(o.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(O.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(A.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>C(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Bo(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(O.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(O.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(O.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(O.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(O.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},u0),e),this.log=zt((i=this.options.loggerName)!==null&&i!==void 0?i:lt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Fu),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Bu),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},d0),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new B0,this.outgoingDataStreamManager=new q0(this.engine,this.log),this.disconnectLock=new qe,this.localParticipant=new J0("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",fn(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),He()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),ii.cleanupRegistry&&ii.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Jv(this.options.e2ee),this.e2eeManager.on(un.ParticipantEncryptionStatusChanged,(n,i)=>{jv(i)&&(this.isE2EEEnabled=n),this.emit(O.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(un.EncryptionError,n=>this.emit(O.EncryptionError,n)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return C(this,void 0,void 0,function*(){return this.state===ne.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(N.RoomUpdate,i),e(r.sid))};this.engine.on(N.RoomUpdate,i),this.once(O.Disconnected,()=>{this.engine.off(N.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new A0(this.options),this.engine.on(N.ParticipantUpdate,this.handleParticipantUpdates).on(N.RoomUpdate,this.handleRoomUpdate).on(N.SpeakersChanged,this.handleSpeakersChanged).on(N.StreamStateChanged,this.handleStreamStateUpdate).on(N.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(N.SubscriptionError,this.handleSubscriptionError).on(N.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(N.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ne.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(N.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ne.Connected)&&this.emit(O.Reconnected)}).on(N.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ne.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.Offline,()=>{this.setAndEmitConnectionState(ne.Reconnecting)&&this.emit(O.Reconnecting)}).on(N.DCBufferStatusChanged,(e,n)=>{this.emit(O.DCBufferStatusChanged,e,n)}).on(N.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(L.LocalTrackSubscribed,n),this.emitWhenConnected(O.LocalTrackSubscribed,n,this.localParticipant)}).on(N.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(O.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ne.getInstance().getDevices(e,n)}prepareConnection(e,n){return C(this,void 0,void 0,function*(){if(this.state===ne.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Io(new URL(e))&&n){this.regionUrlProvider=new na(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ne.Disconnected&&(this.regionUrl=i,yield fetch(Mo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Mo(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return C(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new _t({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new _t({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new _t({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new _t({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new _t({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new _t({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new _t({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>C(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new kr({reason:at.CLIENT_INITIATED,action:Jn.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new _t({scenario:{case:"subscriberBandwidth",value:Dn(n)}});break;case"leave-full-reconnect":r=new _t({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let g=!0,p=!1;const v=o?{exact:r}:r;if(i==="audioinput"){p=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=v;const k=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===E.Source.Microphone);try{g=(yield Promise.all(k.map(y=>{var _;return(_=y.audioTrack)===null||_===void 0?void 0:_.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=b,y}const w=k.some(y=>{var _,S;return(S=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&S!==void 0?S:!1});g&&w&&(p=!0)}else if(i==="videoinput"){p=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=v;const k=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===E.Source.Camera);try{g=(yield Promise.all(k.map(y=>{var _;return(_=y.videoTrack)===null||_===void 0?void 0:_.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=b,y}const w=k.some(y=>{var _,S;return(S=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&S!==void 0?S:!1});g&&w&&(p=!0)}else if(i==="audiooutput"){if(p=!0,!Ro()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(l=yield Ne.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(d=(f=s.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const b=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(k=>k.setAudioOutput({deviceId:r})))}catch(k){throw s.options.audioOutput.deviceId=b,k}}return p&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(O.ActiveDeviceChanged,i,r)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(L.AttributesChanged,this.onLocalAttributesChanged).on(L.TrackMuted,this.onLocalTrackMuted).on(L.TrackUnmuted,this.onLocalTrackUnmuted).on(L.LocalTrackPublished,this.onLocalTrackPublished).on(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(L.MediaDevicesError,this.onMediaDevicesError).on(L.AudioStreamAcquired,this.startAudio).on(L.ChatMessage,this.onLocalChatMessageSent).on(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===ne.Connecting||this.state===ne.Reconnecting){const d=()=>{this.onTrackAdded(e,n,i),u()},u=()=>{this.off(O.Reconnected,d),this.off(O.Connected,d),this.off(O.Disconnected,u)};this.once(O.Reconnected,d),this.once(O.Connected,d),this.once(O.Disconnected,u);return}if(this.state===ne.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=Tv(n.id),s=r[0];let o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,a,n,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ne.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(L.AttributesChanged,this.onLocalAttributesChanged).off(L.TrackMuted,this.onLocalTrackMuted).off(L.TrackUnmuted,this.onLocalTrackUnmuted).off(L.LocalTrackPublished,this.onLocalTrackPublished).off(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(L.MediaDevicesError,this.onMediaDevicesError).off(L.AudioStreamAcquired,this.startAudio).off(L.ChatMessage,this.onLocalChatMessageSent).off(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),He()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ne.Disconnected),this.emit(O.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(O.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,s,o){return C(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Jo(d)>ju?(c=Ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=d}catch(d){d instanceof Ce?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),c=Ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}selectDefaultDevices(){return C(this,void 0,void 0,function*(){var e,n,i;const r=Ne.getInstance().previousDevices,s=yield Ne.getInstance().getDevices(void 0,!1),o=Qe();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(O.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=qv(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(f=>f.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Or()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Or())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return C(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Tu())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),We(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(O.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Br.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Br(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(O.ParticipantConnected,i),i.on(L.TrackPublished,r=>{this.emitWhenConnected(O.TrackPublished,r,i)}).on(L.TrackSubscribed,(r,s)=>{r.kind===E.Kind.Audio?(r.on(A.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(A.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===E.Kind.Video&&(r.on(A.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(A.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,r,s,i)}).on(L.TrackUnpublished,r=>{this.emit(O.TrackUnpublished,r,i)}).on(L.TrackUnsubscribed,(r,s)=>{this.emit(O.TrackUnsubscribed,r,s,i)}).on(L.TrackMuted,r=>{this.emitWhenConnected(O.TrackMuted,r,i)}).on(L.TrackUnmuted,r=>{this.emitWhenConnected(O.TrackUnmuted,r,i)}).on(L.ParticipantMetadataChanged,r=>{this.emitWhenConnected(O.ParticipantMetadataChanged,r,i)}).on(L.ParticipantNameChanged,r=>{this.emitWhenConnected(O.ParticipantNameChanged,r,i)}).on(L.AttributesChanged,r=>{this.emitWhenConnected(O.ParticipantAttributesChanged,r,i)}).on(L.ConnectionQualityChanged,r=>{this.emitWhenConnected(O.ConnectionQualityChanged,r,i)}).on(L.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,r,i)}).on(L.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,r,s,i)}).on(L.TrackSubscriptionFailed,(r,s)=>{this.emit(O.TrackSubscriptionFailed,r,i,s)}).on(L.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,r,s,i)}).on(L.Active,()=>{this.emitWhenConnected(O.ParticipantActive,i),i.kind===Ri.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&Bv(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ue.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,at.STATE_MISMATCH))):e=0},X0)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ue.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===ne.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ne.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return C(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new vr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:pe.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new En({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(ne.Connected),r.video){const o=new sa(E.Kind.Video,new Kn({source:xe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO,name:"video-dummy"}),new Ur(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Cu(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(L.LocalTrackPublished,o)}if(r.audio){const o=new sa(E.Kind.Audio,new Kn({source:xe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO}),new Lr(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ao(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(L.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new En({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Gn.ACTIVE,tracks:[],joinedAt:pe.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=Cu(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),d=new Kn({source:xe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}if(s.audio){const l=Ao(),d=new Kn({source:xe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}c.updateInfo(a)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const s=ih(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}ii.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ih(t){return t.map(e=>{if(e)return Array.isArray(e)?ih(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var ft;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(ft||(ft={}));class vn extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=ft.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new ii(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return C(this,void 0,void 0,function*(){if(this.status!==ft.IDLE)throw Error("check is running already");this.setStatus(ft.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==ft.SKIPPED&&this.setStatus(this.isSuccess()?ft.SUCCESS:ft.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return C(this,void 0,void 0,function*(){return this.room.state===ne.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return C(this,void 0,void 0,function*(){this.room&&this.room.state!==ne.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(ft.SKIPPED)}switchProtocol(e){return C(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(O.Reconnecting,()=>{n=!0}),this.room.once(O.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield We(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Q0 extends vn{get description(){return"Cloud regions"}perform(){return C(this,void 0,void 0,function*(){const e=new na(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return C(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const oa=1e4;class Z0 extends vn{get description(){return"Connection via UDP vs TCP"}perform(){return C(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(oa/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(oa/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return C(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>C(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,oa)),clearInterval(u),a.stop(),n.remove(),yield this.disconnect(),d})}}class eb extends vn{get description(){return"Can publish audio"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield th();if(yield Su(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class tb extends vn{get description(){return"Can publish video"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield H0();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return C(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(s=d.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class nb extends vn{get description(){return"Resuming connection after interruption"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(O.SignalReconnecting,a).on(O.Reconnecting,a).on(O.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==ne.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class ib extends vn{get description(){return"Can connect via TURN"}perform(){return C(this,void 0,void 0,function*(){var e,n;const i=new Vo,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class rb extends vn{get description(){return"Establishing WebRTC connection"}perform(){return C(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(O.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(sb(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),Z.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function sb(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class ob extends vn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return C(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Vo;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===td.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class __ extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:ft.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==ft.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return C(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ob)})}checkWebRTC(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(rb)})}checkTURN(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ib)})}checkReconnect(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(nb)})}checkPublishAudio(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(eb)})}checkPublishVideo(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(tb)})}checkConnectionProtocol(){return C(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Z0);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(Q0)})}}function Yt(){return Yt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Yt.apply(null,arguments)}const rh=new Uint8Array(0);let Fi=class{static getFullOptions(e){return Yt({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,n){var i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(r){i.status!=="connected"&&i.status!=="connecting"||(i.updateStatus("disconnecting"),await i.handleEndSession(),i.updateStatus("disconnected"),i.options.onDisconnect&&i.options.onDisconnect(r))},this.onMessage=async function(r){switch(r.type){case"interruption":return void i.handleInterruption(r);case"agent_response":return void i.handleAgentResponse(r);case"user_transcript":return void i.handleUserTranscript(r);case"internal_tentative_agent_response":return void i.handleTentativeAgentResponse(r);case"client_tool_call":try{await i.handleClientToolCall(r)}catch(s){i.onError(`Unexpected error in client tool call handling: ${s instanceof Error?s.message:String(s)}`,{clientToolName:r.client_tool_call.tool_name,toolCallId:r.client_tool_call.tool_call_id})}return;case"audio":return void i.handleAudio(r);case"vad_score":return void i.handleVadScore(r);case"ping":return void i.connection.sendMessage({type:"pong",event_id:r.ping_event.event_id});case"mcp_tool_call":return void i.handleMCPToolCall(r);case"mcp_connection_status":return void i.handleMCPConnectionStatus(r);case"agent_tool_response":return void i.handleAgentToolResponse(r);case"conversation_initiation_metadata":return void i.handleConversationMetadata(r);case"asr_initiation_metadata":return void i.handleAsrInitiationMetadata(r);case"agent_chat_response_part":return void i.handleAgentChatResponsePart(r);case"error":return void i.handleErrorEvent(r);default:return void(i.options.onDebug&&i.options.onDebug(r))}},this.setVolume=({volume:r})=>{this.volume=r},this.options=e,this.connection=n,this.options.onConnect&&this.options.onConnect({conversationId:n.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(r=>this.updateMode(r)),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){const e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:"ai",message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{var n;const i=(n=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters))!=null?n:"Client tool execution successful.",r=typeof i=="object"?JSON.stringify(i):String(i);this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:r,is_error:!1})}catch(i){this.onError(`Client tool execution failed with following error: ${i==null?void 0:i.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${i==null?void 0:i.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolResponse(e){e.agent_tool_response.tool_name==="end_call"&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){const n=e.error_event.error_type,i=e.error_event.message||e.error_event.reason||"Unknown error";n!=="max_duration_exceeded"?this.onError(`Server error: ${i}`,{errorType:n,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details}):this.endSessionWithDetails({reason:"error",message:i,context:new Event("max_duration_exceeded")})}onError(e,n){console.error(e,n),this.options.onError&&this.options.onError(e,n)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return rh}getOutputByteFrequencyData(){return rh}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(e){this.connection.sendMessage({type:"contextual_update",text:e})}sendUserMessage(e){this.connection.sendMessage({type:"user_message",text:e})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(e,n){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:n})}};class sh{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;const n=this.queue;this.queue=[],n.length>0&&queueMicrotask(()=>{n.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;const n=this.disconnectionDetails;n&&queueMicrotask(()=>{e(n)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var n;(n=this.onModeChangeCallback)==null||n.call(this,e)}disconnect(e){var n;this.disconnectionDetails||(this.disconnectionDetails=e,(n=this.onDisconnectCallback)==null||n.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function jr(t){const[e,n]=t.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${t}`);const i=Number.parseInt(n);if(Number.isNaN(i))throw new Error(`Invalid sample rate: ${n}`);return{format:e,sampleRate:i}}const oh="0.9.2";function aa(t){return!!t.type}const ah="conversation_initiation_client_data";function ch(t){var e;const n={type:ah};var i,r,s,o,a;return t.overrides&&(n.conversation_config_override={agent:{prompt:(i=t.overrides.agent)==null?void 0:i.prompt,first_message:(r=t.overrides.agent)==null?void 0:r.firstMessage,language:(s=t.overrides.agent)==null?void 0:s.language},tts:{voice_id:(o=t.overrides.tts)==null?void 0:o.voiceId},conversation:{text_only:(a=t.overrides.conversation)==null?void 0:a.textOnly}}),t.customLlmExtraBody&&(n.custom_llm_extra_body=t.customLlmExtraBody),t.dynamicVariables&&(n.dynamic_variables=t.dynamicVariables),t.userId&&(n.user_id=t.userId),(e=t.overrides)!=null&&e.client&&(n.source_info={source:t.overrides.client.source,version:t.overrides.client.version}),n}class Bi extends sh{constructor(e,n,i,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=n,this.inputFormat=i,this.outputFormat=r,this.socket.addEventListener("error",s=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:s}),0)}),this.socket.addEventListener("close",s=>{this.disconnect(s.code===1e3?{reason:"agent",context:s}:{reason:"error",message:s.reason||"The connection was closed by the server.",context:s})}),this.socket.addEventListener("message",s=>{try{const o=JSON.parse(s.data);if(!aa(o))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:s.data});this.handleMessage(o)}catch(o){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:o instanceof Error?o.message:String(o),data:s.data})}})}static async create(e){let n=null;try{var i,r,s;const a=(i=e.origin)!=null?i:"wss://api.elevenlabs.io";let c;const l=((r=e.overrides)==null||(r=r.client)==null?void 0:r.version)||oh,d=((s=e.overrides)==null||(s=s.client)==null?void 0:s.source)||"js_sdk";if(e.signedUrl){const k=e.signedUrl.includes("?")?"&":"?";c=`${e.signedUrl}${k}source=${d}&version=${l}`}else c=`${a}/v1/convai/conversation?agent_id=${e.agentId}&source=${d}&version=${l}`;const u=["convai"];e.authorization&&u.push(`bearer.${e.authorization}`),n=new WebSocket(c,u);const h=await new Promise((k,w)=>{n.addEventListener("open",()=>{var y;const _=ch(e);(y=n)==null||y.send(JSON.stringify(_))},{once:!0}),n.addEventListener("error",y=>{setTimeout(()=>w(y),0)}),n.addEventListener("close",w),n.addEventListener("message",y=>{const _=JSON.parse(y.data);aa(_)&&(_.type==="conversation_initiation_metadata"?k(_.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:f,agent_output_audio_format:g,user_input_audio_format:p}=h,v=jr(p??"pcm_16000"),b=jr(g);return new Bi(n,f,v,b)}catch(a){var o;throw(o=n)==null||o.close(),a}}close(){this.socket.close()}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}}function lh(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function ab(t){const e=window.atob(t),n=e.length,i=new Uint8Array(n);for(let r=0;r<n;r++)i[r]=e.charCodeAt(r);return i.buffer}const Vr=new Map;function dh(t,e){return async(n,i)=>{const r=Vr.get(t);if(r)return n.addModule(r);if(i)try{return await n.addModule(i),void Vr.set(t,i)}catch(a){throw new Error(`Failed to load the ${t} worklet module from path: ${i}. Error: ${a}`)}const s=new Blob([e],{type:"application/javascript"}),o=URL.createObjectURL(s);try{return await n.addModule(o),void Vr.set(t,o)}catch{URL.revokeObjectURL(o)}try{const a=`data:application/javascript;base64,${btoa(e)}`;await n.addModule(a),Vr.set(t,a)}catch{throw new Error(`Failed to load the ${t} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const uh=dh("rawAudioProcessor",`/*
38
+ `},Wo}var Mu;function o0(){if(Mu)return ut;Mu=1;var t=r0(),e=s0(),n=zo();return ut.grammar=n,ut.write=e,ut.parse=t.parse,ut.parseParams=t.parseParams,ut.parseFmtpConfig=t.parseFmtpConfig,ut.parsePayloads=t.parsePayloads,ut.parseRemoteCandidates=t.parseRemoteCandidates,ut.parseImageAttributes=t.parseImageAttributes,ut.parseSimulcastStreamList=t.parseSimulcastStreamList,ut}var mn=o0();function Ho(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(p,v){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var w=t.apply(g,f);a&&a(w),d.forEach(function(y){return(0,y.resolve)(w)}),d=[]}},u()),b){var k=t.apply(g,f);return a&&a(k),p(k)}d.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const a0=.7,c0=20,ti={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Nu extends St.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Z,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ho(r=>C(this,void 0,void 0,function*(){this.emit(ti.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),c0),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=zt((i=n.loggerName)!==null&&i!==void 0?i:lt.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new qe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return C(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return C(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:o}=l0(e);this.remoteStereoMids=s,this.remoteNackMids=o}else if(e.type==="answer"){const s=mn.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=mn.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(ti.NegotiationComplete),e.sdp&&mn.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(ti.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const o=mn.parse((n=s.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(a=>{Uu(a),a.type==="audio"?Lu(a,[],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Tt(c.codec)&&!On()&&this.ensureVideoDDExtensionForSVC(a,o),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*a0);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,mn.write(o)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=mn.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Uu(r),r.type==="audio"&&Lu(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,mn.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new De("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new De("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return C(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return C(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Co(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===pu))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:pu})}}}function Lu(t,e,n){let i=0;t.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(t.mid)&&!t.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&t.rtcpFb.push({payload:i,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function l0(t){var e;const n=[],i=[],r=mn.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function Uu(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const Go="vp8",d0={audioPreset:So.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:xo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Go,backupCodec:!0,preConnectBuffer:!1},Fu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Bu={deviceId:{ideal:"default"},resolution:Mi.h720.resolution},u0={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Qg,disconnectOnPageLeave:!0,webAudioMix:!1},Ko={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ke;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(ke||(ke={}));class h0{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Ko.peerConnectionTimeout,this.log=Z,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=ke.CONNECTED:a.some(c=>c==="failed")?this.state=ke.FAILED:a.some(c=>c==="connecting")?this.state=ke.CONNECTING:a.every(c=>c==="closed")?this.state=ke.CLOSED:a.some(c=>c==="closed")?this.state=ke.CLOSING:a.every(c=>c==="new")&&(this.state=ke.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(ke[o]," to ").concat(ke[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=zt((r=i.loggerName)!==null&&r!==void 0?r:lt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new Nu(e,i),this.subscriber=new Nu(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ct.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ct.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=ke.NEW,this.connectionLock=new qe,this.remoteOfferLock=new qe}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return C(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const n of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return C(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return C(this,void 0,void 0,function*(){n===ct.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return C(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(e,n){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return C(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return C(this,void 0,void 0,function*(){return new Promise((n,i)=>C(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(ti.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(ti.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===ct.PUBLISHER?this.publisher.getConnectedAddress():e===ct.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>C(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Ue.clearTimeout(u),l(new de("room connection has been cancelled",te.Cancelled))};r!=null&&r.signal.aborted&&d(),r==null||r.signal.addEventListener("abort",d);const u=Ue.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",d),l(new de("could not establish pc connection",te.InternalError))},o);for(;this.state!==ke.CONNECTED;)if(yield We(50),r!=null&&r.signal.aborted){l(new de("room connection has been cancelled",te.Cancelled));return}Ue.clearTimeout(u),r==null||r.signal.removeEventListener("abort",d),c()}))})()})}}class Ce extends Error{constructor(e,n,i){super(n),this.code=e,this.message=Vu(n,Ce.MAX_MESSAGE_BYTES),this.data=i?Vu(i,Ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ce(e.code,e.message,e.data)}toProto(){return new Ql({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Ce(Ce.ErrorCode[e],Ce.ErrorMessage[e],n)}}Ce.MAX_MESSAGE_BYTES=256,Ce.MAX_DATA_BYTES=15360,Ce.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ce.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ju=15360;function Jo(t){return new TextEncoder().encode(t).length}function Vu(t,e){if(Jo(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const Yo=2e3;function Nr(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const Xo=typeof MediaRecorder<"u";class f0{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const p0=Xo?MediaRecorder:f0;class m0 extends p0{constructor(e,n){if(!Xo)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>C(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(d)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function g0(){return Xo}const v0=1e3,b0=1e4;class qu extends E{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Ho(()=>C(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>C(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(A.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new qe,this.pauseUpstreamLock=new qe,this.trackChangeLock=new qe,this.trackChangeLock.lock().then(o=>C(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==E.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return C(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Qn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Xn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Xn(r??e,s)}))})}waitForDimensions(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:v0;return(function*(){var i;if(e.kind===E.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Qe())===null||i===void 0?void 0:i.os)==="iOS"&&(yield We(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield We(50)}throw new Gt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return C(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===E.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===E.Kind.Audio?"audioinput":"videoinput";return n?Ne.getInstance().normalizeDeviceId(s,i,r):i})()})}mute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return C(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Gt("unable to replace an unpublished track");let r,s;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,s=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return C(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Zg(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===E.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Qn(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(A.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),mu()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(A.UpstreamPaused,this);const i=Qe();if((i==null?void 0:i.name)==="Safari"&&Et(i.version,"12.0")<0)throw new ko("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(A.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Xn(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:d}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Qn(i._mediaStreamTrack,l),Xn(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(A.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}})()})}internalStopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(A.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!g0()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new m0(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},b0)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Lr extends qu{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,E.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,Me.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,Me.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fn(this._constraints.deviceId);return this.source===E.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return C(this,void 0,void 0,function*(){let n;if(e){const i=Fo({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return C(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){He()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Yo)))}setProcessor(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(A.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return C(this,void 0,void 0,function*(){const e=yield Su(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(A.AudioSilenceDetected)),e})}}function y0(t,e,n){switch(t.kind){case"audio":return new Lr(t,e,!1,void 0,n);case"video":return new Ur(t,e,!1,n);default:throw new Gt("unsupported track type: ".concat(t.kind))}}const k0=Object.values(Mi),C0=Object.values(To),w0=Object.values(xo),_0=[Mi.h180,Mi.h360],S0=[To.h180,To.h360],T0=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ce(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Qo=["q","h","f"];function Zo(t,e,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!n)return[{}];o||(o=E0(t,e,n,l),Z.debug("using video encoding",o));const d=o.maxFramerate,u=new ce(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Tt(l)){const g=new Wu(c),p=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Qe();if(Or()||xt()||(v==null?void 0:v.name)==="Chrome"&&Et(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3,k=Iv(v);for(let w=0;w<g.spatial;w+=1)p.push({rid:Qo[2-w],maxBitrate:o.maxBitrate/Math.pow(b,w),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:k?Math.pow(2,w):void 0});p[0].scalabilityMode=c}else p.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(p[0].priority=u.encoding.priority,p[0].networkPriority=u.encoding.priority),Z.debug("using svc encoding",{encodings:p}),p}if(!a)return[o];let h=[];t?h=(r=zu(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:$u(t,u):h=(s=zu(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:$u(t,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const p=Math.max(e,n);if(p>=960&&f)return ea(e,n,[g,f,u],d);if(p>=480)return ea(e,n,[g,u],d)}return ea(e,n,[u])}function x0(t,e,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Z.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===E.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Zo(t.source===E.Source.ScreenShare,c,l,n)}function E0(t,e,n,i){const r=P0(t,e,n);let{encoding:s}=r[0];const o=Math.max(e,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function P0(t,e,n){if(t)return w0;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?k0:C0}function $u(t,e){if(t)return T0(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?_0:S0}function ea(t,e,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=Qo.length)return;const a=Math.min(t,e),l={rid:Qo[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=Zn()||o===0;s.encoding.priority&&u&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),xt()&&vu()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,Z.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Z.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function zu(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Wu{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function R0(t){return t.source===E.Source.ScreenShare||t.constraints.height&&fn(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const I0=5e3;class Ur extends qu{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,E.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(s.map(c=>[c.rid,c])),a=s.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(A.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=Nr(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new qe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!He())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Yo))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Wt(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Wt(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const d=s;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(e){const n=[];for(let i=Ze.LOW;i<=Ze.HIGH;i+=1)n.push(new ao({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Tt(this.codec),n)}restartTrack(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(e){const u=Fo({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=Wt(this.simulcastCodecs.values()),d;d=yield l.next(),n=d.done,!n;c=!0){s=d.value,c=!1;const u=s;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return C(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield n.setProcessor.call(r,i,s),!((d=r.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=Wt(r.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(p){a={error:p}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return C(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},I0))}setPublishingCodecs(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Tt(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=Wt(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Tt(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield Hu(u.sender,u.encodings,d.qualities,this.senderLock,Tt(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,n){return C(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield Hu(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return C(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&Tt(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),mu()&&this.isInBackground&&this.source===E.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Hu(t,e,n,i,r,s,o){return C(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(r&&n.some(f=>f.enabled)&&n.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let p=(g=h.rid)!==null&&g!==void 0?g:"";p===""&&(p="q");const v=Gu(p),b=n.find(k=>k.quality===v);b&&h.active!==b.enabled&&(d=!0,h.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),o),Zn()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield t.setParameters(c))}finally{a()}})}function Gu(t){switch(t){case"f":return Ze.HIGH;case"h":return Ze.MEDIUM;case"q":return Ze.LOW;default:return Ze.HIGH}}function Ku(t,e,n,i){if(!n)return[new Pn({quality:Ze.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new Wu(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new Pn({quality:Math.min(Ze.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Gu((o=r.rid)!==null&&o!==void 0?o:"");return new Pn({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Ju="_lossy",Yu="_reliable",O0=2*1e3,ta="leave-reconnect",D0=3e4;var ht;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(ht||(ht={}));class A0 extends St.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ko.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ht.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Z,this.reliableDataSequence=1,this.reliableMessageBuffer=new Iu,this.reliableReceivedState=new i0(D0),this.handleDataChannel=i=>C(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return(function*(){if(o){if(o.label===Yu)s.reliableDCSub=o;else if(o.label===Ju)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}})()}),this.handleDataMessage=i=>C(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ze.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&N0(c,c.value.value),this.emit(N.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?J.LOSSY:J.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(N.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===ta&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ue.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ht.Connected&&i();const s=()=>{this.off(N.Disconnected,o),i()},o=()=>{this.off(N.Restarted,s),r()};this.once(N.Restarted,s),this.once(N.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(N.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===J.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===he.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Hn.RR_SIGNAL_DISCONNECTED))},this.log=zt((n=e.loggerName)!==null&&n!==void 0?n:lt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Vo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new qe,this.dataProcessLock=new qe,this.dcBufferStatus=new Map([[J.LOSSY,!0],[J.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(N.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(N.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(N.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(N.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(N.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(N.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(N.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(N.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return C(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(N.SignalConnected,s),s}catch(s){if(s instanceof de&&s.reason===te.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw s}})}close(){return C(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(N.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return C(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Iu,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return C(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Gt("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new de("publication of local track timed out, no response from server",te.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return C(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return C(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==ke.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new h0(r,e.subscriberPrimary,this.loggerOptions),this.emit(N.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>C(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===ke.CONNECTED){const d=this.pcState===ht.New;this.pcState=ht.Connected,d&&this.emit(N.Connected,e)}else s===ke.FAILED&&this.pcState===ht.Connected&&(this.pcState=ht.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Hn.RR_SUBSCRIBER_FAILED:Hn.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===he.RECONNECTING,l=[ke.FAILED,ke.CLOSING,ke.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(N.Offline)}),this.pcManager.onTrack=s=>{this.emit(N.MediaTrackAdded,s.track,s.streams[0],s.receiver)},M0((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n)=>C(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n)=>C(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(N.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(N.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(N.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(N.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(N.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Hn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Jn.DISCONNECT:this.emit(N.Disconnected,e==null?void 0:e.reason),this.close();break;case Jn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ta);break;case Jn.RESUME:this.handleDisconnect(ta)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Pi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ju,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Yu,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,n,i){return C(this,void 0,void 0,function*(){if(Eo())return yield this.createTransceiverRTCRtpSender(e,n,i);if(Po())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new De("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(Eo())return this.createSimulcastTransceiverSender(e,n,i,r);if(Po())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new De("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),An(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return C(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Z.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===Pi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:ke.NEW)===ke.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof De?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof ni||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Hn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(N.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return C(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new De("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ni;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof de&&o.reason===te.NotAllowed?new De("could not reconnect, token might be expired"):new ni}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(N.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==he.CONNECTED)throw new ni("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(N.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return C(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new De("could not reconnect, url or token not saved");if(!this.pcManager)throw new De("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof de&&r.reason===te.NotAllowed?new De("could not reconnect, token might be expired"):r instanceof de&&r.reason===te.LeaveRequest?r:new ni(s)}if(this.emit(N.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==he.CONNECTED)throw new ni("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(N.Resumed)})}waitForPCInitialConnection(e,n){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new De("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return C(this,void 0,void 0,function*(){this.pcState=ht.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield We(O0),!this.pcManager)throw new De("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ht.Connected}catch(e){throw this.pcState=ht.Disconnected,new de("could not establish PC connection, ".concat(e.message),te.InternalError)}})}publishRpcResponse(e,n,i,r){return C(this,void 0,void 0,function*(){const s=new ze({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcResponse",value:new Xl({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,J.RELIABLE)})}publishRpcAck(e,n){return C(this,void 0,void 0,function*(){const i=new ze({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcAck",value:new Yl({requestId:n})}});yield this.sendDataPacket(i,J.RELIABLE)})}sendDataPacket(e,n){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===J.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===J.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(J.RELIABLE);const n=this.dataChannelForKind(J.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(J.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>C(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(N.Closing,r);!this.dcBufferStatus.get(e);)yield We(10);this.off(N.Closing,r),n()}}))}ensureDataTransportConnected(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new De("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new de("".concat(a," connection not set"),te.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield We(50)}throw new de("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),te.InternalError)})()})}ensurePublisherConnected(e){return C(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ke.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return C(this,void 0,void 0,function*(){return new Promise((e,n)=>C(this,void 0,void 0,function*(){if(!this.pcManager){n(new Co("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(N.Closing,r),this.pcManager.publisher.once(ti.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();Nv(c)&&o.set(a.payload,c)}),this.emit(N.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Co&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Hn.RR_UNKNOWN),n(s)}finally{this.off(N.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===J.LOSSY)return this.lossyDCSub;if(e===J.RELIABLE)return this.reliableDCSub}else{if(e===J.LOSSY)return this.lossyDC;if(e===J.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==a&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new gd({answer:s?Mr({sdp:s.sdp,type:s.type}):void 0,offer:o?Mr({sdp:o.sdp,type:o.type}):void 0,subscription:new yr({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:zv(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new vd({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new bd({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(J.LOSSY),ct.PUBLISHER),n(this.dataChannelForKind(J.RELIABLE),ct.PUBLISHER),n(this.dataChannelForKind(J.LOSSY,!0),ct.SUBSCRIBER),n(this.dataChannelForKind(J.RELIABLE,!0),ct.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ue.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){He()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){He()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ni extends Error{}function M0(t){return t!==void 0&&t>13}function N0(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class na{constructor(e,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Io(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return C(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),Z.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return C(this,void 0,void 0,function*(){const n=yield fetch("".concat(L0(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new de("Could not fetch region settings: ".concat(n.statusText),n.status===401?te.NotAllowed:te.InternalError,n.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function L0(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class Xu{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new hn("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),dt.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new hn("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),dt.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class U0 extends Xu{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new Pt,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var a;(a=n.reject)===null||a===void 0||a.call(n,o.reason)},o.addEventListener("abort",r),i=o}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),n.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw s(),c}}),return(){return C(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a=new Set;const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=Wt(c),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return Array.from(a)})()})}}class F0 extends Xu{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=Dr(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new Pt,r=null,s=null;if(this.signal){const a=this.signal;s=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,a.reason)},a.addEventListener("abort",s),r=a}const o=()=>{e.releaseLock(),r&&s&&r.removeEventListener("abort",s),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),i.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=n.decode(d.content)}catch(h){throw new hn("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),dt.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return C(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a="";const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=Wt(c),u;u=yield d.next(),i=u.done,!i;l=!0)o=u.value,l=!1,a+=o}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return a})()})}}class B0{constructor(){this.log=Z,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new hn('A text stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new hn('A byte stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,s;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new hn("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),dt.AbnormalEnd);for(const[l,d]of a)(i=(n=d.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(s=(r=d.outOfBandFailureRejectingFuture).reject)===null||s===void 0||s.call(r,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e){return C(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n){return C(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const o=new Pt,a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Dr(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new hn("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new U0(a,c,Dr(e.totalLength),o),{identity:n})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const o=new Pt,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new hn("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new F0(a,c,Dr(e.totalLength),o),{identity:n})}})}handleStreamChunk(e){const n=this.byteStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class Qu{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return C(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class j0 extends Qu{}class V0 extends Qu{}const Zu=15e3;class q0{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return C(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((p,v)=>p+v,0);(f=n==null?void 0:n.onProgress)===null||f===void 0||f.call(n,g)},d=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield d.write(e),l(1,0),yield d.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((u,h)=>C(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:n.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return C(this,void 0,void 0,function*(){var n,i;const r=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new Qs({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Dn(s.timestamp),totalLength:Dn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new od({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Xs.UPDATE:Xs.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new ze({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,J.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(g){return C(this,void 0,void 0,function*(){for(const p of Vv(g,Zu)){yield d.waitForBufferStatusLow(J.RELIABLE);const v=new Zs({content:p,streamId:r,chunkIndex:Dn(l)}),b=new ze({destinationIdentities:a,value:{case:"streamChunk",value:v}});yield d.sendDataPacket(b,J.RELIABLE),l+=1}})},close(){return C(this,void 0,void 0,function*(){const g=new eo({streamId:r}),p=new ze({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield d.sendDataPacket(p,J.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>C(this,void 0,void 0,function*(){yield f.close()});d.once(N.Closing,h);const f=new j0(u,s,()=>this.engine.off(N.Closing,h));return f})}sendFile(e,n){return C(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return C(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:a,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},d=new Qs({totalLength:Dn((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:Dn(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new ad({name:l.name})}}),u=new ze({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,J.RELIABLE);let h=0;const f=new qe,g=this.engine,p=this.log,v=new WritableStream({write(k){return C(this,void 0,void 0,function*(){const w=yield f.lock();let y=0;try{for(;y<k.byteLength;){const _=k.slice(y,y+Zu);yield g.waitForBufferStatusLow(J.RELIABLE);const S=new ze({destinationIdentities:c,value:{case:"streamChunk",value:new Zs({content:_,streamId:a,chunkIndex:Dn(h)})}});yield g.sendDataPacket(S,J.RELIABLE),h+=1,y+=_.byteLength}}finally{w()}})},close(){return C(this,void 0,void 0,function*(){const k=new eo({streamId:a}),w=new ze({destinationIdentities:c,value:{case:"streamTrailer",value:k}});yield g.sendDataPacket(w,J.RELIABLE)})},abort(k){p.error("Sink error:",k)}});return new V0(v,l)})}}class eh extends E{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(A.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Yo)),Wv()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(A.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class $0 extends eh{constructor(e,n,i,r,s,o){super(e,n,E.Kind.Audio,i,o),this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(xt())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return C(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(Ro(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ro(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(A.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(A.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const ia=100;class z0 extends eh{constructor(e,n,i,r,s){super(e,n,E.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Ho(()=>{this.updateDimensions()},ia),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Qn(this._mediaStreamTrack,n):Xn(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new W0(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<ia){Ue.setTimeout(()=>{this.updateVisibility()},ia);return}this.lastVisible=o,this.emit(A.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(A.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?bu():n||(bu()>2?2:1)}}class W0{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=Ui(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ui(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ui(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??ra(e),this.isPiP=He()&&Ui(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=ra(this.element),this.isPiP=Ui(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ku().observe(this.element),yu().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=ku())===null||e===void 0||e.unobserve(this.element),(n=yu())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ui(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ra(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function ra(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class Jt extends St.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Xe.NONE,this.log=Z,this.handleMuted=()=>{this.emit(A.Muted)},this.handleUnmuted=()=>{this.emit(A.Unmuted)},this.log=zt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:lt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=E.Source.Unknown}setTrack(e){this.track&&(this.track.off(A.Muted,this.handleMuted),this.track.off(A.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(A.Muted,this.handleMuted),e.on(A.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Xe.NONE}get audioTrack(){if(Rt(this.track))return this.track}get videoTrack(){if(An(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=E.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===E.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(t.PermissionStatus||(t.PermissionStatus={}))})(Jt||(Jt={}));class sa extends Jt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(A.Ended)},this.handleCpuConstrained=()=>{this.track&&An(this.track)&&this.emit(A.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(A.Ended,this.handleTrackEnded),this.track.off(A.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(A.Ended,this.handleTrackEnded),e.on(A.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Rt(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(Me.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(Me.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(Me.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(Me.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Me.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Me.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Fr(t,e){return C(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=xu(t);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const u=s.audio.deviceId;s.audio.deviceId={exact:u},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:u}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const u=s.video.deviceId;s.video.deviceId={exact:u},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:u}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=_u(s,Fu,Bu),l=Fo(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(Ne.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Ne.userMediaPromiseMap.delete("audioinput"))),s.video&&(Ne.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Ne.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>C(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&fn(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const k=y0(h,p,e);return k.kind===E.Kind.Video?k.source=E.Source.Camera:k.kind===E.Kind.Audio&&(k.source=E.Source.Microphone),k.mediaStream=u,Rt(k)&&i?yield k.setProcessor(i):An(k)&&r&&(yield k.setProcessor(r)),k})))}catch(u){if(!n)throw u;return Fr(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}})}function H0(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:!1,video:!0}))[0]})}function th(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:t??!0,video:!1}))[0]})}var gn;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(gn||(gn={}));function G0(t){switch(t){case Ei.EXCELLENT:return gn.Excellent;case Ei.GOOD:return gn.Good;case Ei.POOR:return gn.Poor;case Ei.LOST:return gn.Lost;default:return gn.Unknown}}class nh extends St.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ri.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Gn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ri.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=gn.Unknown,this.log=Z,this.log=zt((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:lt.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Pt,this.once(L.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(E.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(E.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(E.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Gn.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Gn.ACTIVE&&this.emit(L.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(L.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(L.ParticipantNameChanged,e)}_setAttributes(e){const n=Hv(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(L.AttributesChanged,n)}setPermissions(e){var n,i,r,s,o,a;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(L.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(L.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=G0(e),n!==this._connectionQuality&&this.emit(L.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Rt(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(A.Muted,()=>{this.emit(L.TrackMuted,e)}),e.on(A.Unmuted,()=>{this.emit(L.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case E.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case E.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function K0(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new pd({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class J0 extends nh{constructor(e,n,i,r,s,o){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Xe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Pt)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Pt),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==co.OK&&u.reject(new uu(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=Ce.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>K0(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),X(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),X(c))),this.emit(L.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>C(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var p=!0,v=Wt(g),b;b=yield v.next(),c=b.done,!c;p=!0){u=b.value,p=!1;const k=u;_v(k)&&(this.log.debug("publish ".concat(k," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),X(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,k,f.options))}}catch(k){l={error:k}}finally{try{!p&&!c&&(d=v.return)&&(yield d.call(v))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>C(this,void 0,void 0,function*(){if(a.source===E.Source.ScreenShare||a.source===E.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),X(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Kt(a)||pn(a))try{if(He())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===E.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),X(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),X(a))),Kt(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),X(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Xe.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(N.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(N.Connected,this.handleReconnected).on(N.SignalConnected,this.handleSignalConnected).on(N.SignalRestarted,this.handleReconnected).on(N.SignalResumed,this.handleReconnected).on(N.Restarting,this.handleReconnecting).on(N.Resuming,this.handleReconnecting).on(N.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(N.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(N.Closing,this.handleClosing).on(N.SignalRequestResponse,this.handleSignalRequestResponse).on(N.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return C(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return(function*(){return new Promise((a,c)=>C(i,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(d=s??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-f<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[p,v]=g;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),a();return}yield We(50)}c(new uu("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))})()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(E.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(E.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(E.Source.ScreenShare,e,n,i)}setPermissions(e){const n=this.permissions,i=super.setPermissions(e);return i&&n&&this.emit(L.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){this.encryptionType=e?Xe.GCM:Xe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return C(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case E.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case E.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case E.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Gt(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(L.MediaDevicesError,l,Bo(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===E.Source.Microphone&&Rt(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),X(u))),l.push(this.publishTrack(u,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===E.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(E.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return C(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(E.Source.Camera)||this.pendingPublishing.has(E.Source.Microphone))){this.pendingPublishing.add(E.Source.Camera),this.pendingPublishing.add(E.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(E.Source.Camera),this.pendingPublishing.delete(E.Source.Microphone)}}})}createTracks(e){return C(this,void 0,void 0,function*(){var n,i;e??(e={});const r=_u(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Fr(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Rt(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=E.Source.Microphone,this.emit(L.AudioStreamAcquired)),An(a)&&(this.cameraError=void 0,a.source=E.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return C(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new ko("getDisplayMedia not supported");e.resolution===void 0&&!Rv()&&(e.resolution=xo.h1080fps30.resolution);const n=$v(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Gt("no video track found");const s=new Ur(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=E.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(L.AudioStreamAcquired);const a=new Lr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=E.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,n){return C(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;Kt(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),ei(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case E.Source.Microphone:b="audioinput";break;case E.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Lr(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ur(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Gt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),X(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),X(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(d=r.red)!==null&&d!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!Ov()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,k)=>C(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==he.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:X(i)}));const w=setTimeout(()=>{k(new du("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(w);const y=yield this.publish(i,p,g);b(y)}else try{const w=yield this.publish(i,p,g);b(w)}catch(w){k(w)}}catch(w){k(w)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Pt),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),X(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>Gv(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),X(e))),!1)}publish(e,n,i){return C(this,void 0,void 0,function*(){var r,s,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new du("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(R=>ei(e)&&R.source===e.source)&&e.source!==E.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),X(e))),n.stopMicTrackOnMute&&Rt(e)&&(e.stopOnMute=!0),e.source===E.Source.ScreenShare&&Zn()&&(n.simulcast=!1),n.videoCodec==="av1"&&!xv()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!Ev()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Go),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(R=>n.videoCodec===Ar(R.mime))||(n.videoCodec=Ar(this.enabledPublishVideoCodecs[0].mime)));const p=n.videoCodec;e.on(A.Muted,this.onTrackMuted),e.on(A.Unmuted,this.onTrackUnmuted),e.on(A.Ended,this.handleTrackEnded),e.on(A.UpstreamPaused,this.onTrackUpstreamPaused),e.on(A.UpstreamResumed,this.onTrackUpstreamResumed),e.on(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),k=e.getSourceTrackSettings();k.autoGainControl&&v.push(Me.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&v.push(Me.TF_ECHO_CANCELLATION),k.noiseSuppression&&v.push(Me.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&v.push(Me.TF_STEREO),b&&v.push(Me.TF_NO_DTX),Kt(e)&&e.hasPreConnectBuffer&&v.push(Me.TF_PRECONNECT_BUFFER);const w=new io({cid:e.mediaStreamTrack.id,name:n.name,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:v});let y;if(e.kind===E.Kind.Video){let R={width:0,height:0};try{R=yield e.waitForDimensions()}catch{const M=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Mi.h720.resolution;R={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{dims:R}))}w.width=R.width,w.height=R.height,pn(e)&&(Tt(p)&&(e.source===E.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),X(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),w.simulcastCodecs=[new no({codec:p,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Go}),n.backupCodec&&p!==n.backupCodec.codec&&w.encryption===Xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),w.simulcastCodecs.push(new no({codec:n.backupCodec.codec,cid:""})))),y=Zo(e.source===E.Source.ScreenShare,w.width,w.height,n),w.layers=Ku(w.width,w.height,y,Tt(n.videoCodec))}else e.kind===E.Kind.Audio&&(y=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=n.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new De("cannot publish track when not connected");const _=()=>C(this,void 0,void 0,function*(){var R,D,M;if(!this.engine.pcManager)throw new De("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,y),this.emit(L.LocalSenderCreated,e.sender,e),pn(e)&&((R=n.degradationPreference)!==null&&R!==void 0||(n.degradationPreference=R0(e)),e.setDegradationPreference(n.degradationPreference)),y)if(Zn()&&e.kind===E.Kind.Audio){let U;for(const j of this.engine.pcManager.publisher.getTransceivers())if(j.sender===e.sender){U=j;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((D=y[0])===null||D===void 0)&&D.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Tt(e.codec)&&(!((M=y[0])===null||M===void 0)&&M.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:w.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const x=new Promise((R,D)=>C(this,void 0,void 0,function*(){var M;try{S=yield this.engine.addTrack(w),R(S)}catch(U){e.sender&&(!((M=this.engine.pcManager)===null||M===void 0)&&M.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(j=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{error:j}))})),D(U)}}));if(this.enabledPublishVideoCodecs.length>0)S=(yield Promise.all([x,_()]))[0];else{S=yield x;let R;if(S.codecs.forEach(D=>{R===void 0&&(R=D.mimeType)}),R&&e.kind===E.Kind.Video){const D=Ar(R);D!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{codec:D})),n.videoCodec=D,y=Zo(e.source===E.Source.ScreenShare,w.width,w.height,n))}yield _()}const I=new sa(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(I.on(A.CpuConstrained,R=>this.onTrackCpuConstrained(R,I)),I.options=n,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:S})),pn(e)?e.startMonitor(this.engine.client):Kt(e)&&e.startMonitor(),this.addTrackPublication(I),this.emit(L.LocalTrackPublished,I),Kt(e)&&S.audioFeatures.includes(Me.TF_PRECONNECT_BUFFER)){const R=e.getPreConnectBuffer(),D=e.getPreConnectBufferMimeType();this.on(L.LocalTrackSubscribed,M=>{if(M.trackSid===S.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),X(e))),e.stopPreConnectBuffer()}}),R&&new Promise((U,j)=>C(this,void 0,void 0,function*(){var $,F,G,Y,W,ee;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),X(e)));const st=setTimeout(()=>{j(new Error("agent not active within 10 seconds"))},1e4),Ve=yield this.waitUntilActiveAgentPresent();clearTimeout(st),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),X(e)));const Lt=yield this.streamBytes({name:"preconnect-buffer",mimeType:D,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ve.identity],attributes:{trackId:I.trackSid,sampleRate:String((W=k.sampleRate)!==null&&W!==void 0?W:"48000"),channels:String((ee=k.channelCount)!==null&&ee!==void 0?ee:"1")}});try{for(var we=!0,bt=Wt(R),nn;nn=yield bt.next(),$=nn.done,!$;we=!0){Y=nn.value,we=!1;const yt=Y;yield Lt.write(yt)}}catch(yt){F={error:yt}}finally{try{!we&&!$&&(G=bt.return)&&(yield G.call(bt))}finally{if(F)throw F.error}}yield Lt.close(),U()}catch(st){j(st)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),X(e)))}).catch(U=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{error:U}))})}return I})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return C(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Xe.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new Gt("track is not published");if(!pn(e))throw new Gt("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=x0(e,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),X(e)));return}const c=e.addSimulcastTrack(n,a);if(!c)return;const l=new io({cid:c.mediaStreamTrack.id,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Ku(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new De("cannot publish track when not connected");const d=()=>C(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,n){return C(this,void 0,void 0,function*(){var i,r;if(ei(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),X(e))),yield l)}const s=this.getPublicationForTrack(e),o=s?X(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=s.track,e.off(A.Muted,this.onTrackMuted),e.off(A.Unmuted,this.onTrackUnmuted),e.off(A.Ended,this.handleTrackEnded),e.off(A.UpstreamPaused,this.onTrackUpstreamPaused),e.off(A.UpstreamResumed,this.onTrackUpstreamResumed),e.off(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ke.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),pn(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case E.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case E.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(L.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return C(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>C(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>C(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==E.Source.ScreenShare&&l.source!==E.Source.ScreenShareAudio&&(Kt(l)||pn(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?J.RELIABLE:J.LOSSY,o=r.destinationIdentities,a=r.topic,c=new ze({kind:s,value:{case:"user",value:new Gl({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)})()})}publishDtmf(e,n){return C(this,void 0,void 0,function*(){const i=new ze({kind:J.RELIABLE,value:{case:"sipDtmf",value:new Kl({code:e,digit:n})}});yield this.engine.sendDataPacket(i,J.RELIABLE)})}sendChatMessage(e,n){return C(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new ze({value:{case:"chatMessage",value:new Ys(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(L.ChatMessage,i),i})}editChatMessage(e,n){return C(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new ze({value:{case:"chatMessage",value:new Ys(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp),editTimestamp:pe.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(L.ChatMessage,i),i})}sendText(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return C(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return(function*(){return new Promise((l,d)=>C(i,void 0,void 0,function*(){var u,h,f,g;if(Jo(o)>ju){d(Ce.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Et((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(Ce.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,o,a-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),d(Ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),d(Ce.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(p,{resolve:(k,w)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),w?d(w):l(k??"")},participantIdentity:r})}))})()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return C(this,void 0,void 0,function*(){const o=new ze({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcRequest",value:new Jl({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,J.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),X(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Pt),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Kt(r)||pn(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return C(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===e});if(r)return r[1];yield We(20)}})}}class Y0 extends Jt{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(A.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new yr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Zl({participantSid:"",trackSids:[this.trackSid]})]});this.emit(A.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Jt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Jt.SubscriptionStatus.Subscribed:Jt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Jt.PermissionStatus.Allowed:Jt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Lo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Lo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ze.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(A.VisibilityChanged,this.handleVisibilityChange),r.off(A.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(A.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(A.VisibilityChanged,this.handleVisibilityChange),e.on(A.Ended,this.handleEnded),this.emit(A.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(A.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?A.Muted:A.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(A.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(A.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Lo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ld({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===E.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)Eu(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Kv(this.trackInfo,this.requestedMaxQuality);i&&Eu(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Ze.HIGH})),e.quality=Ze.HIGH)}this.emit(A.UpdateSettings,e)}}class Br extends nh{static fromParticipantInfo(e,n,i){return new Br(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ri.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(A.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(A.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(A.SubscriptionPermissionChanged,n=>{this.emit(L.TrackSubscriptionPermissionChanged,e,n)}),e.on(A.SubscriptionStatusChanged,n=>{this.emit(L.TrackSubscriptionStatusChanged,e,n)}),e.on(A.Subscribed,n=>{this.emit(L.TrackSubscribed,n,e)}),e.on(A.Unsubscribed,n=>{this.emit(L.TrackUnsubscribed,n,e)}),e.on(A.SubscriptionFailed,n=>{this.emit(L.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(L.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),X(a))),this.emit(L.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new z0(e,n,r,s):l=new $0(e,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&No(l)&&Rt(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=E.kindFromProto(r.type);if(!c)return;a=new Y0(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==E.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:X(l),newTrack:X(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),X(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(L.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case E.Kind.Audio:this.audioTrackPublications.delete(e);break;case E.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(L.TrackUnpublished,i)}setAudioOutput(e){return C(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Rt(i.track)&&No(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ne;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(ne||(ne={}));const X0=4*1e3;class ii extends St.EventEmitter{constructor(e){var n,i,r,s;if(super(),n=this,this.state=ne.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Z,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,a,c)=>C(this,void 0,void 0,function*(){var l;if(!Pv())throw xt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===ne.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ne.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Io(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new na(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const u=(f,g,p)=>C(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const k=new AbortController;this.abortController=k,d==null||d();try{yield this.attemptConnection(p??o,a,c,k),this.abortController=void 0,f()}catch(w){if(this.regionUrlProvider&&w instanceof de&&w.reason!==te.Cancelled&&w.reason!==te.NotAllowed){let y=null;try{y=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(_){if(_ instanceof de&&(_.status===401||_.reason===te.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(_);return}}y&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield u(f,g,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,wu(w)),g(w))}else{let y=at.UNKNOWN_REASON;w instanceof de&&(y=wu(w)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),g(w)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Pt((f,g)=>{u(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,d,u)=>C(this,void 0,void 0,function*(){var h,f,g;const p=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[k,w]=b;return"".concat(k,": ").concat(w)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(g=p.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new fv("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),p}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>C(this,void 0,void 0,function*(){var d,u;this.state===ne.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ko),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new de("could not establish signal connection",te.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof de&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new de("Connection attempt aborted",te.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}He()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),He()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ne.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return C(n,[...a],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var u,h,f,g;const p=yield l.disconnectLock.lock();try{if(l.state===ne.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ne.Connecting||l.state===ne.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new de("Client initiated disconnect",te.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,at.CLIENT_INITIATED),l.engine=void 0}finally{p()}})()})},this.onPageLeave=()=>C(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>C(this,void 0,void 0,function*(){const o=[],a=Qe();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Ao();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(O.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>C(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(ne.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=o=>C(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(ne.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===Gn.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),a.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(O.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?a.set(l.sid,d):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(O.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const d=E.streamStateFromProto(a.state);d!==l.track.streamState&&(l.track.streamState=d,c.emit(L.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(O.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(L.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(O.SipDTMFReceived,a,o),o==null||o.emit(L.SipDTMFReceived,a)},this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),d=Uv(a,this.transcriptionReceivedTimes);l==null||l.emit(A.TranscriptionReceived,d),c==null||c.emit(L.TranscriptionReceived,d,l),this.emit(O.TranscriptionReceived,d,c,l)},this.handleChatMessage=(o,a)=>{const c=Fv(a);this.emit(O.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(O.MetricsReceived,o,a)},this.handleDataStream=o=>{this.incomingDataStreamManager.handleDataStreamPacket(o)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>C(this,void 0,void 0,function*(){var o;((o=Qe())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(O.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(O.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(O.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(O.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(O.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>C(this,void 0,void 0,function*(){var a,c,l,d,u,h;(a=o.track)===null||a===void 0||a.on(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(A.Restarted,this.onLocalTrackRestarted),(u=(d=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(O.LocalTrackPublished,o,this.localParticipant),Kt(o.track)&&(yield o.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,o);const f=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Bo(o.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(O.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(A.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>C(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Bo(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(O.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(O.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(O.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(O.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(O.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},u0),e),this.log=zt((i=this.options.loggerName)!==null&&i!==void 0?i:lt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Fu),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Bu),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},d0),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new B0,this.outgoingDataStreamManager=new q0(this.engine,this.log),this.disconnectLock=new qe,this.localParticipant=new J0("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",fn(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),He()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),ii.cleanupRegistry&&ii.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Jv(this.options.e2ee),this.e2eeManager.on(un.ParticipantEncryptionStatusChanged,(n,i)=>{jv(i)&&(this.isE2EEEnabled=n),this.emit(O.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(un.EncryptionError,n=>this.emit(O.EncryptionError,n)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return C(this,void 0,void 0,function*(){return this.state===ne.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(N.RoomUpdate,i),e(r.sid))};this.engine.on(N.RoomUpdate,i),this.once(O.Disconnected,()=>{this.engine.off(N.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new A0(this.options),this.engine.on(N.ParticipantUpdate,this.handleParticipantUpdates).on(N.RoomUpdate,this.handleRoomUpdate).on(N.SpeakersChanged,this.handleSpeakersChanged).on(N.StreamStateChanged,this.handleStreamStateUpdate).on(N.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(N.SubscriptionError,this.handleSubscriptionError).on(N.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(N.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ne.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(N.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ne.Connected)&&this.emit(O.Reconnected)}).on(N.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ne.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.Offline,()=>{this.setAndEmitConnectionState(ne.Reconnecting)&&this.emit(O.Reconnecting)}).on(N.DCBufferStatusChanged,(e,n)=>{this.emit(O.DCBufferStatusChanged,e,n)}).on(N.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(L.LocalTrackSubscribed,n),this.emitWhenConnected(O.LocalTrackSubscribed,n,this.localParticipant)}).on(N.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(O.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ne.getInstance().getDevices(e,n)}prepareConnection(e,n){return C(this,void 0,void 0,function*(){if(this.state===ne.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Io(new URL(e))&&n){this.regionUrlProvider=new na(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ne.Disconnected&&(this.regionUrl=i,yield fetch(Mo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Mo(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return C(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new _t({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new _t({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new _t({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new _t({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new _t({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new _t({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new _t({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>C(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new kr({reason:at.CLIENT_INITIATED,action:Jn.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new _t({scenario:{case:"subscriberBandwidth",value:Dn(n)}});break;case"leave-full-reconnect":r=new _t({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let g=!0,p=!1;const v=o?{exact:r}:r;if(i==="audioinput"){p=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=v;const k=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===E.Source.Microphone);try{g=(yield Promise.all(k.map(y=>{var _;return(_=y.audioTrack)===null||_===void 0?void 0:_.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=b,y}const w=k.some(y=>{var _,S;return(S=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&S!==void 0?S:!1});g&&w&&(p=!0)}else if(i==="videoinput"){p=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=v;const k=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===E.Source.Camera);try{g=(yield Promise.all(k.map(y=>{var _;return(_=y.videoTrack)===null||_===void 0?void 0:_.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=b,y}const w=k.some(y=>{var _,S;return(S=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&S!==void 0?S:!1});g&&w&&(p=!0)}else if(i==="audiooutput"){if(p=!0,!Ro()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(l=yield Ne.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(d=(f=s.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const b=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(k=>k.setAudioOutput({deviceId:r})))}catch(k){throw s.options.audioOutput.deviceId=b,k}}return p&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(O.ActiveDeviceChanged,i,r)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(L.AttributesChanged,this.onLocalAttributesChanged).on(L.TrackMuted,this.onLocalTrackMuted).on(L.TrackUnmuted,this.onLocalTrackUnmuted).on(L.LocalTrackPublished,this.onLocalTrackPublished).on(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(L.MediaDevicesError,this.onMediaDevicesError).on(L.AudioStreamAcquired,this.startAudio).on(L.ChatMessage,this.onLocalChatMessageSent).on(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===ne.Connecting||this.state===ne.Reconnecting){const d=()=>{this.onTrackAdded(e,n,i),u()},u=()=>{this.off(O.Reconnected,d),this.off(O.Connected,d),this.off(O.Disconnected,u)};this.once(O.Reconnected,d),this.once(O.Connected,d),this.once(O.Disconnected,u);return}if(this.state===ne.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=Tv(n.id),s=r[0];let o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,a,n,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ne.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(L.AttributesChanged,this.onLocalAttributesChanged).off(L.TrackMuted,this.onLocalTrackMuted).off(L.TrackUnmuted,this.onLocalTrackUnmuted).off(L.LocalTrackPublished,this.onLocalTrackPublished).off(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(L.MediaDevicesError,this.onMediaDevicesError).off(L.AudioStreamAcquired,this.startAudio).off(L.ChatMessage,this.onLocalChatMessageSent).off(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),He()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ne.Disconnected),this.emit(O.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(O.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,s,o){return C(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Jo(d)>ju?(c=Ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=d}catch(d){d instanceof Ce?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),c=Ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}selectDefaultDevices(){return C(this,void 0,void 0,function*(){var e,n,i;const r=Ne.getInstance().previousDevices,s=yield Ne.getInstance().getDevices(void 0,!1),o=Qe();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(O.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=qv(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(f=>f.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Or()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Or())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return C(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Tu())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),We(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(O.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Br.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Br(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(O.ParticipantConnected,i),i.on(L.TrackPublished,r=>{this.emitWhenConnected(O.TrackPublished,r,i)}).on(L.TrackSubscribed,(r,s)=>{r.kind===E.Kind.Audio?(r.on(A.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(A.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===E.Kind.Video&&(r.on(A.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(A.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,r,s,i)}).on(L.TrackUnpublished,r=>{this.emit(O.TrackUnpublished,r,i)}).on(L.TrackUnsubscribed,(r,s)=>{this.emit(O.TrackUnsubscribed,r,s,i)}).on(L.TrackMuted,r=>{this.emitWhenConnected(O.TrackMuted,r,i)}).on(L.TrackUnmuted,r=>{this.emitWhenConnected(O.TrackUnmuted,r,i)}).on(L.ParticipantMetadataChanged,r=>{this.emitWhenConnected(O.ParticipantMetadataChanged,r,i)}).on(L.ParticipantNameChanged,r=>{this.emitWhenConnected(O.ParticipantNameChanged,r,i)}).on(L.AttributesChanged,r=>{this.emitWhenConnected(O.ParticipantAttributesChanged,r,i)}).on(L.ConnectionQualityChanged,r=>{this.emitWhenConnected(O.ConnectionQualityChanged,r,i)}).on(L.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,r,i)}).on(L.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,r,s,i)}).on(L.TrackSubscriptionFailed,(r,s)=>{this.emit(O.TrackSubscriptionFailed,r,i,s)}).on(L.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,r,s,i)}).on(L.Active,()=>{this.emitWhenConnected(O.ParticipantActive,i),i.kind===Ri.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&Bv(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ue.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,at.STATE_MISMATCH))):e=0},X0)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ue.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===ne.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ne.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return C(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new vr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:pe.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new En({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(ne.Connected),r.video){const o=new sa(E.Kind.Video,new Kn({source:xe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO,name:"video-dummy"}),new Ur(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Cu(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(L.LocalTrackPublished,o)}if(r.audio){const o=new sa(E.Kind.Audio,new Kn({source:xe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO}),new Lr(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ao(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(L.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new En({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Gn.ACTIVE,tracks:[],joinedAt:pe.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=Cu(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),d=new Kn({source:xe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}if(s.audio){const l=Ao(),d=new Kn({source:xe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}c.updateInfo(a)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const s=ih(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}ii.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ih(t){return t.map(e=>{if(e)return Array.isArray(e)?ih(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var ft;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(ft||(ft={}));class vn extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=ft.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new ii(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return C(this,void 0,void 0,function*(){if(this.status!==ft.IDLE)throw Error("check is running already");this.setStatus(ft.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==ft.SKIPPED&&this.setStatus(this.isSuccess()?ft.SUCCESS:ft.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return C(this,void 0,void 0,function*(){return this.room.state===ne.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return C(this,void 0,void 0,function*(){this.room&&this.room.state!==ne.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(ft.SKIPPED)}switchProtocol(e){return C(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(O.Reconnecting,()=>{n=!0}),this.room.once(O.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield We(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Q0 extends vn{get description(){return"Cloud regions"}perform(){return C(this,void 0,void 0,function*(){const e=new na(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return C(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const oa=1e4;class Z0 extends vn{get description(){return"Connection via UDP vs TCP"}perform(){return C(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(oa/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(oa/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return C(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>C(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,oa)),clearInterval(u),a.stop(),n.remove(),yield this.disconnect(),d})}}class eb extends vn{get description(){return"Can publish audio"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield th();if(yield Su(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class tb extends vn{get description(){return"Can publish video"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield H0();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return C(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(s=d.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class nb extends vn{get description(){return"Resuming connection after interruption"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(O.SignalReconnecting,a).on(O.Reconnecting,a).on(O.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==ne.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class ib extends vn{get description(){return"Can connect via TURN"}perform(){return C(this,void 0,void 0,function*(){var e,n;const i=new Vo,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class rb extends vn{get description(){return"Establishing WebRTC connection"}perform(){return C(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(O.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(sb(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),Z.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function sb(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class ob extends vn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return C(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Vo;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===td.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class __ extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:ft.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==ft.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return C(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ob)})}checkWebRTC(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(rb)})}checkTURN(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ib)})}checkReconnect(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(nb)})}checkPublishAudio(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(eb)})}checkPublishVideo(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(tb)})}checkConnectionProtocol(){return C(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Z0);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(Q0)})}}function Yt(){return Yt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Yt.apply(null,arguments)}const rh=new Uint8Array(0);let Fi=class{static getFullOptions(e){return Yt({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,n){var i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(r){i.status!=="connected"&&i.status!=="connecting"||(i.updateStatus("disconnecting"),await i.handleEndSession(),i.updateStatus("disconnected"),i.options.onDisconnect&&i.options.onDisconnect(r))},this.onMessage=async function(r){switch(r.type){case"interruption":return void i.handleInterruption(r);case"agent_response":return void i.handleAgentResponse(r);case"user_transcript":return void i.handleUserTranscript(r);case"internal_tentative_agent_response":return void i.handleTentativeAgentResponse(r);case"client_tool_call":try{await i.handleClientToolCall(r)}catch(s){i.onError(`Unexpected error in client tool call handling: ${s instanceof Error?s.message:String(s)}`,{clientToolName:r.client_tool_call.tool_name,toolCallId:r.client_tool_call.tool_call_id})}return;case"audio":return void i.handleAudio(r);case"vad_score":return void i.handleVadScore(r);case"ping":return void i.connection.sendMessage({type:"pong",event_id:r.ping_event.event_id});case"mcp_tool_call":return void i.handleMCPToolCall(r);case"mcp_connection_status":return void i.handleMCPConnectionStatus(r);case"agent_tool_response":return void i.handleAgentToolResponse(r);case"conversation_initiation_metadata":return void i.handleConversationMetadata(r);case"asr_initiation_metadata":return void i.handleAsrInitiationMetadata(r);case"agent_chat_response_part":return void i.handleAgentChatResponsePart(r);case"error":return void i.handleErrorEvent(r);default:return void(i.options.onDebug&&i.options.onDebug(r))}},this.setVolume=({volume:r})=>{this.volume=r},this.options=e,this.connection=n,this.options.onConnect&&this.options.onConnect({conversationId:n.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(r=>this.updateMode(r)),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){const e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:"ai",message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{var n;const i=(n=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters))!=null?n:"Client tool execution successful.",r=typeof i=="object"?JSON.stringify(i):String(i);this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:r,is_error:!1})}catch(i){this.onError(`Client tool execution failed with following error: ${i==null?void 0:i.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${i==null?void 0:i.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolResponse(e){e.agent_tool_response.tool_name==="end_call"&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){const n=e.error_event.error_type,i=e.error_event.message||e.error_event.reason||"Unknown error";n!=="max_duration_exceeded"?this.onError(`Server error: ${i}`,{errorType:n,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details}):this.endSessionWithDetails({reason:"error",message:i,context:new Event("max_duration_exceeded")})}onError(e,n){console.error(e,n),this.options.onError&&this.options.onError(e,n)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return rh}getOutputByteFrequencyData(){return rh}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(e){this.connection.sendMessage({type:"contextual_update",text:e})}sendUserMessage(e){this.connection.sendMessage({type:"user_message",text:e})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(e,n){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:n})}};class sh{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;const n=this.queue;this.queue=[],n.length>0&&queueMicrotask(()=>{n.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;const n=this.disconnectionDetails;n&&queueMicrotask(()=>{e(n)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var n;(n=this.onModeChangeCallback)==null||n.call(this,e)}disconnect(e){var n;this.disconnectionDetails||(this.disconnectionDetails=e,(n=this.onDisconnectCallback)==null||n.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function jr(t){const[e,n]=t.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${t}`);const i=Number.parseInt(n);if(Number.isNaN(i))throw new Error(`Invalid sample rate: ${n}`);return{format:e,sampleRate:i}}const oh="0.10.0";function aa(t){return!!t.type}const ah="conversation_initiation_client_data";function ch(t){var e;const n={type:ah};var i,r,s,o,a;return t.overrides&&(n.conversation_config_override={agent:{prompt:(i=t.overrides.agent)==null?void 0:i.prompt,first_message:(r=t.overrides.agent)==null?void 0:r.firstMessage,language:(s=t.overrides.agent)==null?void 0:s.language},tts:{voice_id:(o=t.overrides.tts)==null?void 0:o.voiceId},conversation:{text_only:(a=t.overrides.conversation)==null?void 0:a.textOnly}}),t.customLlmExtraBody&&(n.custom_llm_extra_body=t.customLlmExtraBody),t.dynamicVariables&&(n.dynamic_variables=t.dynamicVariables),t.userId&&(n.user_id=t.userId),(e=t.overrides)!=null&&e.client&&(n.source_info={source:t.overrides.client.source,version:t.overrides.client.version}),n}class Bi extends sh{constructor(e,n,i,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=n,this.inputFormat=i,this.outputFormat=r,this.socket.addEventListener("error",s=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:s}),0)}),this.socket.addEventListener("close",s=>{this.disconnect(s.code===1e3?{reason:"agent",context:s}:{reason:"error",message:s.reason||"The connection was closed by the server.",context:s})}),this.socket.addEventListener("message",s=>{try{const o=JSON.parse(s.data);if(!aa(o))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:s.data});this.handleMessage(o)}catch(o){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:o instanceof Error?o.message:String(o),data:s.data})}})}static async create(e){let n=null;try{var i,r,s;const a=(i=e.origin)!=null?i:"wss://api.elevenlabs.io";let c;const l=((r=e.overrides)==null||(r=r.client)==null?void 0:r.version)||oh,d=((s=e.overrides)==null||(s=s.client)==null?void 0:s.source)||"js_sdk";if(e.signedUrl){const k=e.signedUrl.includes("?")?"&":"?";c=`${e.signedUrl}${k}source=${d}&version=${l}`}else c=`${a}/v1/convai/conversation?agent_id=${e.agentId}&source=${d}&version=${l}`;const u=["convai"];e.authorization&&u.push(`bearer.${e.authorization}`),n=new WebSocket(c,u);const h=await new Promise((k,w)=>{n.addEventListener("open",()=>{var y;const _=ch(e);(y=n)==null||y.send(JSON.stringify(_))},{once:!0}),n.addEventListener("error",y=>{setTimeout(()=>w(y),0)}),n.addEventListener("close",w),n.addEventListener("message",y=>{const _=JSON.parse(y.data);aa(_)&&(_.type==="conversation_initiation_metadata"?k(_.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:f,agent_output_audio_format:g,user_input_audio_format:p}=h,v=jr(p??"pcm_16000"),b=jr(g);return new Bi(n,f,v,b)}catch(a){var o;throw(o=n)==null||o.close(),a}}close(){this.socket.close()}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}}function lh(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function ab(t){const e=window.atob(t),n=e.length,i=new Uint8Array(n);for(let r=0;r<n;r++)i[r]=e.charCodeAt(r);return i.buffer}const Vr=new Map;function dh(t,e){return async(n,i)=>{const r=Vr.get(t);if(r)return n.addModule(r);if(i)try{return await n.addModule(i),void Vr.set(t,i)}catch(a){throw new Error(`Failed to load the ${t} worklet module from path: ${i}. Error: ${a}`)}const s=new Blob([e],{type:"application/javascript"}),o=URL.createObjectURL(s);try{return await n.addModule(o),void Vr.set(t,o)}catch{URL.revokeObjectURL(o)}try{const a=`data:application/javascript;base64,${btoa(e)}`;await n.addModule(a),Vr.set(t,a)}catch{throw new Error(`Failed to load the ${t} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const uh=dh("rawAudioProcessor",`/*
39
39
  * ulaw encoding logic taken from the wavefile library
40
40
  * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
41
41
  * USED BY @elevenlabs/client
@@ -251,7 +251,7 @@ class AudioConcatProcessor extends AudioWorkletProcessor {
251
251
  }
252
252
 
253
253
  registerProcessor("audioConcatProcessor", AudioConcatProcessor);
254
- `);class $r{static async create({sampleRate:e,format:n,outputDeviceId:i,workletPaths:r}){let s=null,o=null;try{s=new AudioContext({sampleRate:e});const l=s.createAnalyser(),d=s.createGain();o=new Audio,o.src="",o.load(),o.autoplay=!0,o.style.display="none",document.body.appendChild(o);const u=s.createMediaStreamDestination();o.srcObject=u.stream,d.connect(l),l.connect(u),await cb(s.audioWorklet,r==null?void 0:r.audioConcatProcessor);const h=new AudioWorkletNode(s,"audioConcatProcessor");return h.port.postMessage({type:"setFormat",format:n}),h.connect(d),await s.resume(),i&&o.setSinkId&&await o.setSinkId(i),new $r(s,l,d,h,o)}catch(l){var a,c;throw(a=o)!=null&&a.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),s&&s.state!=="closed"&&await s.close(),l}}constructor(e,n,i,r,s){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=n,this.gain=i,this.worklet=r,this.audioElement=s}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(e||"")}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class la extends Fi{static async startSession(e){var n;const i=Fi.getFullOptions(e);i.onStatusChange&&i.onStatusChange({status:"connecting"}),i.onCanSendFeedbackChange&&i.onCanSendFeedbackChange({canSendFeedback:!1});let r=null,s=null,o=null,a=null,c=null;if((n=e.useWakeLock)==null||n)try{c=await navigator.wakeLock.request("screen")}catch{}try{var l;return a=await navigator.mediaDevices.getUserMedia({audio:!0}),await ph(i.connectionDelay),s=await hh(e),[r,o]=await Promise.all([qr.create(Yt({},s.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId,workletPaths:e.workletPaths,libsampleratePath:e.libsampleratePath})),$r.create(Yt({},s.outputFormat,{outputDeviceId:e.outputDeviceId,workletPaths:e.workletPaths}))]),(l=a)==null||l.getTracks().forEach(p=>{p.stop()}),a=null,new la(i,s,r,o,c)}catch(p){var d,u,h,f;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),(d=a)==null||d.getTracks().forEach(v=>{v.stop()}),(u=s)==null||u.close(),await((h=r)==null?void 0:h.close()),await((f=o)==null?void 0:f.close());try{var g;await((g=c)==null?void 0:g.release()),c=null}catch{}throw p}}constructor(e,n,i,r,s){super(e,n),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=o=>{this.status==="connected"&&this.connection.sendMessage({user_audio_chunk:lh(o.data[0].buffer)})},this.onOutputWorkletMessage=({data:o})=>{o.type==="process"&&this.updateMode(o.finished?"listening":"speaking")},this.addAudioBase64Chunk=o=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:ab(o)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},this.calculateVolume=o=>{if(o.length===0)return 0;let a=0;for(let c=0;c<o.length;c++)a+=o[c]/255;return a/=o.length,a<0?0:a>1?1:a},this.setVolume=({volume:o})=>{const a=Number.isFinite(o)?Math.min(1,Math.max(0,o)):1;this.volume=a,this.connection instanceof Xt?this.connection.setAudioVolume(a):this.output.gain.gain.value=a},this.input=i,this.output=r,this.wakeLock=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{var e;await((e=this.wakeLock)==null?void 0:e.release()),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var n,i;this.lastInterruptTimestamp<=e.audio_event.event_id&&((n=(i=this.options).onAudio)==null||n.call(i,e.audio_event.audio_base_64),this.connection instanceof Xt||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(e){this.connection instanceof Xt?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData!=null||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Xt?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r}){try{if(this.connection instanceof Bi)try{return await this.input.setInputDevice(r),this.input}catch(o){console.warn("Failed to change device on existing input, recreating:",o)}this.connection instanceof Xt&&await this.connection.setAudioInputDevice(r||""),await this.input.close();const s=await qr.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:n??this.connection.inputFormat.format,preferHeadphonesForIosDevices:i,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath});return this.input=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(s){throw console.error("Error changing input device",s),s}}async changeOutputDevice({sampleRate:e,format:n,outputDeviceId:i}){try{if(this.connection instanceof Bi)try{return await this.output.setOutputDevice(i),this.output}catch(s){console.warn("Failed to change device on existing output, recreating:",s)}this.connection instanceof Xt&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const r=await $r.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:n??this.connection.outputFormat.format,outputDeviceId:i,workletPaths:this.options.workletPaths});return this.output=r,this.output}catch(r){throw console.error("Error changing output device",r),r}}}function gh(t,e,n="https://api.elevenlabs.io"){const i={};return typeof e=="boolean"?i.feedback=e?"like":"dislike":(i.rating=e.rating,i.comment=e.comment),fetch(`${n}/v1/convai/conversations/${t}/feedback`,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json"}})}var vh;(function(t){t.SESSION_STARTED="session_started",t.PARTIAL_TRANSCRIPT="partial_transcript",t.FINAL_TRANSCRIPT="final_transcript",t.FINAL_TRANSCRIPT_WITH_TIMESTAMPS="final_transcript_with_timestamps",t.AUTH_ERROR="auth_error",t.ERROR="error",t.OPEN="open",t.CLOSE="close"})(vh||(vh={}));var bh,yh;(function(t){t.PCM_8000="pcm_8000",t.PCM_16000="pcm_16000",t.PCM_22050="pcm_22050",t.PCM_24000="pcm_24000",t.PCM_44100="pcm_44100",t.PCM_48000="pcm_48000",t.ULAW_8000="ulaw_8000"})(bh||(bh={})),(function(t){t.MANUAL="manual",t.VAD="vad"})(yh||(yh={}));class lb extends Fi{static startSession(e){return e.textOnly?ca.startSession(e):la.startSession(e)}}function kh(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var r=t.length;for(e=0;e<r;e++)t[e]&&(n=kh(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function ae(){for(var t,e,n=0,i="",r=arguments.length;n<r;n++)(t=arguments[n])&&(e=kh(t))&&(i&&(i+=" "),i+=e);return i}var db=Object.defineProperty,ub=(t,e,n)=>e in t?db(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ge=(t,e,n)=>ub(t,typeof e!="symbol"?e+"":e,n);function Qt(t){return t?t==="true"?!0:t==="false"?!1:null:null}const da=["variant","placement","override-config","avatar-image-url","avatar-orb-color-1","avatar-orb-color-2","agent-id","signed-url","terms-key","server-location","language","dynamic-variables","show-avatar-when-collapsed","override-prompt","override-first-message","override-language","override-voice-id","override-text-only","mic-muting","transcript","text-input","text-contents","default-expanded","always-expanded","user-id","use-rtc","collect-feedback"],hb='@import"https://fonts.googleapis.com/css2?family=Inter:wght@400,500&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:currentColor}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\\!container{width:100%!important}.container{width:100%}@media (min-width: 640px){.\\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width: 768px){.\\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width: 1024px){.\\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width: 1280px){.\\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width: 1536px){.\\!container{max-width:1536px!important}.container{max-width:1536px}}.pointer-events-auto{pointer-events:auto}.\\!visible{visibility:visible!important}.visible{visibility:visible}.collapse{visibility:collapse}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-3{bottom:-12px}.bottom-0{bottom:0}.bottom-1{bottom:4px}.bottom-20{bottom:80px}.left-0{left:0}.left-1\\/2{left:50%}.left-4{left:16px}.right-0{right:0}.right-1{right:4px}.top-0{top:0}.top-1\\/2{top:50%}.top-20{top:80px}.top-4{top:16px}.top-\\[88px\\]{top:88px}.z-1{z-index:1}.z-10{z-index:10}.m-1{margin:4px}.-mx-0\\.5{margin-left:-2px;margin-right:-2px}.mx-1{margin-left:4px;margin-right:4px}.-mr-1\\.5{margin-right:-6px}.mb-4{margin-bottom:16px}.ml-auto{margin-left:auto}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.block{display:block}.inline{display:inline}.\\!flex{display:flex!important}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.contents{display:contents}.hidden{display:none}.\\!h-8{height:32px!important}.h-11{height:44px}.h-4{height:16px}.h-48{height:192px}.h-5{height:20px}.h-6{height:24px}.h-7{height:28px}.h-8{height:32px}.h-9{height:36px}.h-\\[calc\\(100\\%-80px\\)\\]{height:calc(100% - 80px)}.h-full{height:100%}.h-screen{height:100vh}.max-h-\\[550px\\]{max-height:550px}.max-h-\\[8lh\\]{max-height:8lh}.max-h-\\[min\\(384px\\,var\\(--radix-select-content-available-height\\)\\)\\]{max-height:min(384px,var(--radix-select-content-available-height))}.min-h-0{min-height:0px}.min-h-\\[6lh\\]{min-height:6lh}.min-h-full{min-height:100%}.min-h-min{min-height:-moz-min-content;min-height:min-content}.\\!w-8{width:32px!important}.w-20{width:80px}.w-4{width:16px}.w-48{width:192px}.w-5{width:20px}.w-6{width:24px}.w-64{width:256px}.w-7{width:28px}.w-8{width:32px}.w-9{width:36px}.w-full{width:100%}.w-screen{width:100vw}.\\!min-w-60{min-width:240px!important}.min-w-0{min-width:0px}.min-w-60{min-width:240px}.min-w-9{min-width:36px}.min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.min-w-max{min-width:-moz-max-content;min-width:max-content}.min-w-min{min-width:-moz-min-content;min-width:min-content}.max-w-64{max-width:256px}.max-w-\\[400px\\]{max-width:400px}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-bottom{transform-origin:bottom}.origin-bottom-left{transform-origin:bottom left}.origin-bottom-right{transform-origin:bottom right}.origin-top{transform-origin:top}.origin-top-left{transform-origin:top left}.origin-top-right{transform-origin:top right}.-translate-x-1\\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(calc(var(--el-overlay-padding)) * -1);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-1\\/2{--tw-translate-y: 50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(var(--el-overlay-padding));transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-full{--tw-translate-y: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-180{--tw-rotate: -180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-150{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-75{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-90{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\\[0\\.1667\\]{--tw-scale-x: .1667;--tw-scale-y: .1667;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.place-content-center{place-content:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.gap-1{gap:4px}.gap-2{gap:8px}.gap-2\\.5{gap:10px}.gap-3{gap:12px}.gap-8{gap:32px}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-all{word-break:break-all}.rounded-\\[calc\\(var\\(--el-button-radius\\)\\+4px\\)\\]{border-radius:calc(var(--el-button-radius) + 4px)}.rounded-bubble{border-radius:var(--el-bubble-radius)}.rounded-button{border-radius:var(--el-button-radius)}.rounded-compact-sheet{border-radius:var(--el-compact-sheet-radius)}.rounded-dropdown-sheet{border-radius:var(--el-dropdown-sheet-radius)}.rounded-full{border-radius:9999px}.rounded-input{border-radius:var(--el-input-radius)}.rounded-sheet{border-radius:var(--el-sheet-radius)}.border{border-width:1px}.border-accent{border-color:var(--el-accent)}.border-base{border-color:var(--el-base)}.border-base-border{border-color:var(--el-base-border)}.bg-accent{background-color:var(--el-accent)}.bg-base{background-color:var(--el-base)}.bg-base-active{background-color:var(--el-base-active)}.bg-base-border{background-color:var(--el-base-border)}.bg-base-hover{background-color:var(--el-base-hover)}.bg-cover{background-size:cover}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:4px}.p-1\\.5{padding:6px}.p-2{padding:8px}.p-3{padding:12px}.p-4{padding:16px}.px-1{padding-left:4px;padding-right:4px}.px-1\\.5{padding-left:6px;padding-right:6px}.px-2{padding-left:8px;padding-right:8px}.px-2\\.5{padding-left:10px;padding-right:10px}.px-3{padding-left:12px;padding-right:12px}.px-4{padding-left:16px;padding-right:16px}.px-8{padding-left:32px;padding-right:32px}.py-1\\.5{padding-top:6px;padding-bottom:6px}.py-2\\.5{padding-top:10px;padding-bottom:10px}.py-4{padding-top:16px;padding-bottom:16px}.py-\\[calc\\(theme\\(spacing\\.2\\)-1px\\)\\]{padding-top:7px;padding-bottom:7px}.pb-1{padding-bottom:4px}.pb-2{padding-bottom:8px}.pb-3{padding-bottom:12px}.pl-16{padding-left:64px}.pr-16{padding-right:64px}.pr-3{padding-right:12px}.pr-9{padding-right:36px}.pt-1{padding-top:4px}.pt-3{padding-top:12px}.pt-4{padding-top:16px}.text-center{text-align:center}.text-\\[10px\\]{font-size:10px}.text-lg{font-size:18px;line-height:26px}.text-md{font-size:16px;line-height:24px}.text-sm{font-size:14px;line-height:20px}.text-xl{font-size:20px;line-height:28px}.text-xs{font-size:12px;line-height:16px}.font-medium{font-weight:500}.text-accent-primary{color:var(--el-accent-primary)}.text-base-border{color:var(--el-base-border)}.text-base-error{color:var(--el-base-error)}.text-base-primary{color:var(--el-base-primary)}.text-base-subtle{color:var(--el-base-subtle)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-30{opacity:.3}.shadow-header{--tw-shadow: 0 0 1px 0 rgba(0, 0, 0, .4), 0 2px 2px 0 rgba(0, 0, 0, .04);--tw-shadow-colored: 0 0 1px 0 var(--tw-shadow-color), 0 2px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 2px 40px 1px rgba(0, 0, 0, .12);--tw-shadow-colored: 0 2px 40px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 2px 24px 1px rgba(0, 0, 0, .16);--tw-shadow-colored: 0 2px 24px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[border-radius\\]{transition-property:border-radius;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[margin\\]{transition-property:margin;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,width\\,height\\,transform\\,flex-grow\\]{transition-property:opacity,width,height,transform,flex-grow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,left\\,top\\,opacity\\,scale\\]{transition-property:transform,left,top,opacity,scale;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,opacity\\]{transition-property:transform,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.overlay{position:absolute;inset:var(--el-overlay-padding);right:calc(var(--el-overlay-padding) + var(--removed-body-scroll-bar-size, 0px))}.focus-ring{--tw-ring-color: var(--el-accent);--tw-ring-offset-width: 2px;--tw-ring-offset-color: var(--el-base)}.focus-ring:focus-visible{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.animate-text{background-image:linear-gradient(75deg,var(--el-base-primary),var(--el-base-subtle),var(--el-base-primary),var(--el-base-subtle));background-size:300% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:TextAnimation 2s linear infinite}@keyframes TextAnimation{0%{background-position:0 0}to{background-position:100% 0}}.\\!terms h6,.terms h6{font-size:12px;line-height:16px;font-weight:500;color:var(--el-base-primary)}.\\!terms h5,.terms h5{font-size:14px;line-height:20px;font-weight:500;color:var(--el-base-primary)}.\\!terms h4,.terms h4{font-size:16px;line-height:24px;font-weight:500;color:var(--el-base-primary)}.\\!terms h3,.terms h3{font-size:18px;line-height:26px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:20px;line-height:28px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:24px;line-height:30px;font-weight:500;color:var(--el-base-primary)}.\\[field-sizing\\:content\\]{field-sizing:content}.\\[line-height\\:var\\(--el-overlay-padding\\)\\]{line-height:var(--el-overlay-padding)}.\\[overflow-wrap\\:break-word\\]{overflow-wrap:break-word}.dev-host,:host{pointer-events:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1000;font-size:16px;line-height:24px;color:var(--el-base-primary);font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;scrollbar-color:#e5e7eb transparent}.placeholder\\:text-base-subtle::-moz-placeholder{color:var(--el-base-subtle)}.placeholder\\:text-base-subtle::placeholder{color:var(--el-base-subtle)}.hover\\:border-accent-hover:hover{border-color:var(--el-accent-hover)}.hover\\:border-base-hover:hover{border-color:var(--el-base-hover)}.hover\\:bg-accent-hover:hover{background-color:var(--el-accent-hover)}.hover\\:bg-base-hover:hover{background-color:var(--el-base-hover)}.hover\\:opacity-50:hover{opacity:.5}.focus-visible\\:underline-offset-2:focus-visible{text-underline-offset:2px}.focus-visible\\:opacity-100:focus-visible{opacity:1}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.active\\:border-accent-active:active{border-color:var(--el-accent-active)}.active\\:border-base-active:active{border-color:var(--el-base-active)}.active\\:bg-accent-active:active{background-color:var(--el-accent-active)}.active\\:bg-base-active:active{background-color:var(--el-base-active)}.data-hidden\\:-translate-y-4[data-shown=false]{--tw-translate-y: -16px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-x-full[data-shown=false]{--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-y-2[data-shown=false]{--tw-translate-y: 8px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-100[data-shown=false]{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-75[data-shown=false]{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-90[data-shown=false]{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:opacity-0[data-shown=false]{opacity:0}.data-\\[highlighted\\]\\:bg-base-active[data-highlighted]{background-color:var(--el-base-active)}',Ch=["tiny","compact","full"];function fb(t){return Ch.includes(t)?t:Ch[0]}const pb=["top-left","top","top-right","bottom-left","bottom","bottom-right"];function mb(t){return pb.includes(t)?t:"bottom-right"}const wh={main_label:"Need help?",start_call:"Start a call",start_chat:"Start a chat",send_message:"Send",new_call:"New call",end_call:"End",mute_microphone:"Mute microphone",change_language:"Change language",collapse:"Collapse",expand:"Expand",copied:"Copied!",accept_terms:"Accept",dismiss_terms:"Cancel",listening_status:"Listening",speaking_status:"Talk to interrupt",connecting_status:"Connecting",chatting_status:"Chatting with AI Agent",input_label:"Text message input",input_placeholder:"Send a message",input_placeholder_text_only:"Send a message",input_placeholder_new_conversation:"Start a new conversation",user_ended_conversation:"You ended the conversation",agent_ended_conversation:"The agent ended the conversation",conversation_id:"ID",error_occurred:"An error occurred",copy_id:"Copy ID",initiate_feedback:"How was this conversation?",request_follow_up_feedback:"Tell us more",thanks_for_feedback:"Thank you for your feedback!",thanks_for_feedback_details:"Your feedback helps us improve our service and better support you in the future.",follow_up_feedback_placeholder:"Tell us more about your experience...",submit:"Submit",go_back:"Go back"},gb=Object.keys(wh),_h={base:"#ffffff",base_hover:"#f9fafb",base_active:"#f3f4f6",base_border:"#e5e7eb",base_subtle:"#6b7280",base_primary:"#000000",base_error:"#ef4444",accent:"#000000",accent_hover:"#1f2937",accent_active:"#374151",accent_border:"#4b5563",accent_subtle:"#6b7280",accent_primary:"#ffffff",overlay_padding:32,button_radius:18,input_radius:10,bubble_radius:15,sheet_radius:"calc(var(--el-button-radius) + 6px)",compact_sheet_radius:"calc(var(--el-button-radius) + 12px)",dropdown_sheet_radius:"calc(var(--el-input-radius) + 6px)"},vb=Object.keys(_h);function bb(t="us"){switch(t){case"eu-residency":case"in-residency":case"us":case"global":return t;default:return console.warn(`[ConversationalAI] Invalid server-location: ${t}. Defaulting to "us"`),"us"}}function et(t){const e=sn(t);if(e==null)throw new Error(`${t.displayName} cannot be used outside of provider`);return e}const Sh=Ie(null);function yb({value:t,children:e}){const n=oe(()=>Object.fromEntries(da.map(i=>[i,Je(t[i])])),[]);return da.forEach(i=>{n[i].value=t[i]}),m(Sh.Provider,{value:n,children:e})}function kb(){return et(Sh)}function ie(t){return kb()[t]}const Th=Ie(null);function Cb({children:t}){const e=ie("server-location"),n=oe(()=>{const i=Ye(()=>bb(e.value)),r={us:"https://api.us.elevenlabs.io","eu-residency":"https://api.eu.residency.elevenlabs.io","in-residency":"https://api.in.residency.elevenlabs.io",global:"https://api.elevenlabs.io"},s={us:"wss://api.us.elevenlabs.io","eu-residency":"wss://api.eu.residency.elevenlabs.io","in-residency":"wss://api.in.residency.elevenlabs.io",global:"wss://api.elevenlabs.io"};return{location:i,serverUrl:Ye(()=>r[i.value]),webSocketUrl:Ye(()=>s[i.value])}},[]);return m(Th.Provider,{value:n,children:t})}function ua(){return et(Th)}const ji={en:{name:"English",flagCode:"us",languageCode:"en"},zh:{name:"中文",flagCode:"cn",languageCode:"zh"},es:{name:"Español",flagCode:"es",languageCode:"es"},hi:{name:"हिन्दी",flagCode:"in",languageCode:"hi"},pt:{name:"Português (Portugal)",flagCode:"pt",languageCode:"pt"},"pt-br":{name:"Português (Brasil)",flagCode:"br",languageCode:"pt-br"},fr:{name:"Français",flagCode:"fr",languageCode:"fr"},de:{name:"Deutsch",flagCode:"de",languageCode:"de"},ja:{name:"日本語",flagCode:"jp",languageCode:"ja"},ar:{name:"العربية",flagCode:"ae",languageCode:"ar"},ru:{name:"Русский",flagCode:"ru",languageCode:"ru"},ko:{name:"한국어",flagCode:"kr",languageCode:"ko"},id:{name:"Bahasa Indonesia",flagCode:"id",languageCode:"id"},it:{name:"Italiano",flagCode:"it",languageCode:"it"},nl:{name:"Nederlands",flagCode:"nl",languageCode:"nl"},tr:{name:"Türkçe",flagCode:"tr",languageCode:"tr"},pl:{name:"Polski",flagCode:"pl",languageCode:"pl"},sv:{name:"Svenska",flagCode:"se",languageCode:"sv"},ms:{name:"Bahasa Melayu",flagCode:"my",languageCode:"ms"},ro:{name:"Română",flagCode:"ro",languageCode:"ro"},uk:{name:"Українська",flagCode:"ua",languageCode:"uk"},el:{name:"Ελληνικά",flagCode:"gr",languageCode:"el"},cs:{name:"Čeština",flagCode:"cz",languageCode:"cs"},da:{name:"Dansk",flagCode:"dk",languageCode:"da"},fi:{name:"Suomi",flagCode:"fi",languageCode:"fi"},bg:{name:"Български",flagCode:"bg",languageCode:"bg"},hr:{name:"Hrvatski",flagCode:"hr",languageCode:"hr"},sk:{name:"Slovenčina",flagCode:"sk",languageCode:"sk"},ta:{name:"தமிழ்",flagCode:"in",languageCode:"ta"},hu:{name:"Magyar",flagCode:"hu",languageCode:"hu"},no:{name:"Norsk",flagCode:"no",languageCode:"no"},vi:{name:"Tiếng Việt",flagCode:"vn",languageCode:"vi"},tl:{name:"Filipino",flagCode:"ph",languageCode:"tl"}};function ha(t){return Object.keys(ji).includes(t??"")}const xh=Ie(null);function wb({children:t}){const e=Ae(),n=ie("language"),i=ie("override-language"),r=Oe(n.peek()??e.peek().language),s=ue(()=>(e.value.supported_language_overrides??[]).filter(ha)),o=ue(()=>s.value.map(c=>ji[c]).sort((c,l)=>c.name.localeCompare(l.name))),a=oe(()=>({language:Ye(()=>ha(i.value)?ji[i.value]:ha(r.value)&&s.value.includes(r.value)?ji[r.value]:ji[e.value.language]),setLanguage:c=>{r.value=c},options:o,showPicker:Ye(()=>o.value.length>0)}),[]);return m(xh.Provider,{value:a,children:t})}function ri(){return et(xh)}const _b="0.5.1",Eh=Ie(null);function Sb({children:t}){const e=Ae(),n=ue(()=>e.value.mic_muting_enabled??!1),i=Oe(!1),r=oe(()=>({isMuted:Ye(()=>n.value?i.value:!1),setIsMuted:s=>{i.value=s},isMutingEnabled:n}),[]);return m(Eh.Provider,{value:r,children:t})}function Ph(){return et(Eh)}const Rh=Ie(null);function Tb({children:t}){const{language:e}=ri(),n=ie("override-prompt"),i=ie("override-first-message"),r=ie("override-voice-id"),s=ie("override-text-only"),o=ie("user-id"),a=ue(()=>({agent:{prompt:{prompt:n.value},firstMessage:i.value,language:e.value.languageCode},tts:{voiceId:r.value},conversation:{textOnly:Qt(s.value)??void 0}})),c=ie("dynamic-variables"),l=ue(()=>{if(c.value)try{return JSON.parse(c.value)}catch(v){console.error(`[ConversationalAI] Cannot parse dynamic-variables: ${v==null?void 0:v.message}`)}}),{webSocketUrl:d}=ua(),u=ie("agent-id"),h=ie("signed-url"),f=fa(),g=Db(),p=ue(()=>{const v=g.value,b={dynamicVariables:l.value,overrides:a.value,connectionDelay:{default:300},textOnly:f.value,userId:o.value||void 0};return u.value?v?{agentId:u.value,origin:d.value,connectionType:"webrtc",...b}:{agentId:u.value,origin:d.value,connectionType:"websocket",...b}:h.value?{signedUrl:h.value,connectionType:"websocket",...b}:(console.error("[ConversationalAI] Either agent-id or signed-url is required"),null)});return p.value?m(Rh.Provider,{value:p,children:t}):null}function xb(){return et(Rh)}const Ih=Ie(null);function Eb({children:t}){const e=Ae(),n=oe(()=>{const i=e.peek().terms_key,r=i?!!localStorage.getItem(i):!1,s=Je(!1),o=Je(r),a=Ye(()=>!e.value.terms_html||o.value);let c=[];return{termsShown:s,termsAccepted:a,dismissTerms:()=>{s.value=!1,c.forEach(l=>l.reject()),c=[]},acceptTerms:()=>{o.value=!0,s.value=!1;const l=e.peek().terms_key;l&&localStorage.setItem(l,"true"),c.forEach(d=>d.resolve()),c=[]},requestTerms:async()=>{a.peek()||(s.value=!0,await new Promise((l,d)=>{c.push({resolve:l,reject:d})}))}}},[]);return m(Ih.Provider,{value:n,children:t})}function zr(){return et(Ih)}const Oh=Ie(null);function Pb({children:t}){const e=Rb();return Ct(()=>{if(e.conversationTextOnly.value===!0){e.transcript.value;const n=setTimeout(()=>{e.endSession()},600*1e3);return()=>{clearTimeout(n)}}}),m(Oh.Provider,{value:e,children:t})}function Be(){return et(Oh)}function Rb(){const t=B(null),e=B(null),n=B(!1),i=B(null),r=B(!1),s=Ae(),o=Ah(),a=zr(),c=xb(),{isMuted:l}=Ph();return Ct(()=>{var d;const u=l.value;(d=t==null?void 0:t.current)==null||d.setMicMuted(u)}),K(()=>()=>{var d;(d=t.current)==null||d.endSession()},[]),oe(()=>{const d=Je("disconnected"),u=Ye(()=>d.value==="disconnected"),h=Je("listening"),f=Ye(()=>h.value==="speaking"),g=Je(null),p=Je(null),v=Je(!1),b=Je([]),k=Je(0),w=Je(null);return{status:d,isSpeaking:f,mode:h,isDisconnected:u,lastId:p,error:g,canSendFeedback:v,conversationIndex:k,conversationTextOnly:w,transcript:b,startSession:async(y,_)=>{var S,x,I,R,D,M,U;if(await a.requestTerms(),(S=t.current)!=null&&S.isOpen())return t.current.getId();if(e.current)return(await e.current).getId();let j=structuredClone(c.peek());_&&s.value.supports_text_only&&(j.textOnly=!0,s.value.text_only||(j.overrides??(j.overrides={}),(x=j.overrides).conversation??(x.conversation={}),j.overrides.conversation.textOnly=!0));try{j=Ib(y,j)}catch($){console.error("[ConversationalAI] Error triggering call event:",$)}w.value=j.textOnly??!1,b.value=_?[{type:"message",role:"user",message:_,isText:!0,conversationIndex:k.peek()}]:[];try{if(e.current=lb.startSession({...j,overrides:{...j.overrides,client:{...(I=j.overrides)==null?void 0:I.client,source:((D=(R=j.overrides)==null?void 0:R.client)==null?void 0:D.source)||"widget",version:((U=(M=j.overrides)==null?void 0:M.client)==null?void 0:U.version)||_b}},onModeChange:F=>{h.value=F.mode},onStatusChange:F=>{d.value=F.status},onCanSendFeedbackChange:F=>{v.value=F.canSendFeedback},onMessage:({source:F,message:G})=>{if(o.peek()&&w.peek()===!0&&F==="ai"&&!n.current){n.current=!0;return}else F==="ai"&&(n.current=!0);if(F==="ai"&&r.current){r.current=!1;return}b.value=[...b.value,{type:"message",role:F,message:G,isText:!1,conversationIndex:k.peek()}]},onAgentChatResponsePart:({text:F,type:G})=>{if(o.peek()&&w.peek()===!0&&!n.current)return;const Y=b.peek();if(G==="start")r.current=!0,i.current=Y.length,b.value=[...Y,{type:"message",role:"ai",message:"",isText:!0,conversationIndex:k.peek()}];else if(G==="delta"){const W=i.current;if(W!==null&&Y[W]){const ee=[...Y],we=ee[W];we.type==="message"&&(ee[W]={...we,message:we.message+F},b.value=ee)}}else G==="stop"&&(i.current=null)},onDisconnect:F=>{n.current=!1,w.value=null,i.current=null,r.current=!1,b.value=[...b.value,F.reason==="error"?{type:"error",message:F.message,conversationIndex:k.peek()}:{type:"disconnection",role:F.reason==="user"?"user":"ai",conversationIndex:k.peek()}],k.value++,F.reason==="error"&&(g.value=F.message,console.error("[ConversationalAI] Disconnected due to an error:",F.message))}}),t.current=await e.current,t.current.setMicMuted(l.peek()),_){const F=t.current;setTimeout(()=>F.sendUserMessage(_),100)}const $=t.current.getId();return p.value=$,g.value=null,$}catch($){let F="Could not start a conversation.";$ instanceof CloseEvent?F=$.reason||F:$ instanceof Error&&(F=$.message||F),g.value=F,b.value=[...b.value,{type:"error",message:F,conversationIndex:k.peek()}]}finally{e.current=null}},endSession:async()=>{const y=t.current;t.current=null,await(y==null?void 0:y.endSession())},getInputVolume:()=>{var y;return((y=t.current)==null?void 0:y.getInputVolume())??0},getOutputVolume:()=>{var y;return((y=t.current)==null?void 0:y.getOutputVolume())??0},sendFeedback:y=>{var _;(_=t.current)==null||_.sendFeedback(y)},sendUserMessage:y=>{var _;(_=t.current)==null||_.sendUserMessage(y),b.value=[...b.value,{type:"message",role:"user",message:y,isText:!0,conversationIndex:k.peek()}]},sendUserActivity:()=>{var y;(y=t.current)==null||y.sendUserActivity()}}},[c,l])}function Ib(t,e){try{const n=new CustomEvent("elevenlabs-convai:call",{bubbles:!0,composed:!0,detail:{config:e}});return t.dispatchEvent(n),n.detail.config}catch(n){return console.error("[ConversationalAI] Could not trigger call event:",n),e}}const Dh=Ie(null);function Ob({children:t}){const{serverUrl:e}=ua(),n=ie("agent-id"),i=ie("override-config"),r=ie("signed-url"),s=Oe(null);Ct(()=>{if(i.value)try{const y=JSON.parse(i.value);if(y){s.value=y;return}}catch(y){console.error(`[ConversationalAI] Cannot parse override-config: ${y==null?void 0:y.message}`)}let b=n.value,k;if(r.value){const y=new URL(r.value).searchParams;b=y.get("agent_id")??n.value,k=y.get("conversation_signature")??void 0}if(!b){s.value=null;return}const w=new AbortController;return Mb(b,e.value,w.signal,k).then(y=>{w.signal.aborted||(s.value=y)}).catch(y=>{console.error(`[ConversationalAI] Cannot fetch config for agent ${n.value}: ${y==null?void 0:y.message}`),w.signal.aborted||(s.value=null)}),()=>{w.abort()}});const o=ie("variant"),a=ie("placement"),c=ie("terms-key"),l=ie("mic-muting"),d=ie("transcript"),u=ie("text-input"),h=ie("default-expanded"),f=ie("always-expanded"),g=ie("override-text-only"),p=ie("use-rtc"),v=ue(()=>{if(!s.value)return null;const b=o.value??s.value.variant,k=a.value??s.value.placement,w=c.value??s.value.terms_key,y=Qt(g.value)??s.value.text_only??!1,_=Qt(l.value)??s.value.mic_muting_enabled,S=Qt(d.value)??s.value.transcript_enabled,x=Qt(u.value)??s.value.text_input_enabled,I=Qt(f.value)??s.value.always_expanded??!1,R=Qt(h.value)??s.value.default_expanded??!1,D=Qt(p.value)??s.value.use_rtc??!1;return{...s.value,variant:fb(b),placement:mb(k),terms_key:w,mic_muting_enabled:!y&&_,transcript_enabled:y||S,text_input_enabled:y||x,always_expanded:I,default_expanded:R,use_rtc:D}});return v.value?m(Dh.Provider,{value:v,children:t}):null}function Ae(){return et(Dh)}function fa(){const t=ie("override-text-only"),e=Ae();return ue(()=>Qt(t.value)??e.value.text_only??!1)}function Wr(){const t=fa(),{conversationTextOnly:e}=Be();return ue(()=>e.value??t.value)}function Ah(){const t=ie("override-first-message"),e=Ae(),{language:n}=ri();return ue(()=>{var i,r;return t.value??((r=(i=e.value.language_presets)==null?void 0:i[n.value.languageCode])==null?void 0:r.first_message)??e.value.first_message??null})}function Db(){const t=Ae();return ue(()=>t.value.use_rtc??!1)}function Ab(){const t=Ae();return ue(()=>t.value.end_feedback!==void 0)}async function Mb(t,e,n,i){const r=await(await fetch(`${e}/v1/convai/agents/${t}/widget${i?`?conversation_signature=${encodeURIComponent(i)}`:""}`,{signal:n})).json();if(!r.widget_config)throw new Error("Response does not contain widget_config");return r.widget_config}const Nb=tr(function(){const t=Ae(),e=ue(()=>{const n=t.value.styles;return`:host, :root {
254
+ `);class $r{static async create({sampleRate:e,format:n,outputDeviceId:i,workletPaths:r}){let s=null,o=null;try{s=new AudioContext({sampleRate:e});const l=s.createAnalyser(),d=s.createGain();o=new Audio,o.src="",o.load(),o.autoplay=!0,o.style.display="none",document.body.appendChild(o);const u=s.createMediaStreamDestination();o.srcObject=u.stream,d.connect(l),l.connect(u),await cb(s.audioWorklet,r==null?void 0:r.audioConcatProcessor);const h=new AudioWorkletNode(s,"audioConcatProcessor");return h.port.postMessage({type:"setFormat",format:n}),h.connect(d),await s.resume(),i&&o.setSinkId&&await o.setSinkId(i),new $r(s,l,d,h,o)}catch(l){var a,c;throw(a=o)!=null&&a.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),s&&s.state!=="closed"&&await s.close(),l}}constructor(e,n,i,r,s){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=n,this.gain=i,this.worklet=r,this.audioElement=s}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(e||"")}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class la extends Fi{static async startSession(e){var n;const i=Fi.getFullOptions(e);i.onStatusChange&&i.onStatusChange({status:"connecting"}),i.onCanSendFeedbackChange&&i.onCanSendFeedbackChange({canSendFeedback:!1});let r=null,s=null,o=null,a=null,c=null;if((n=e.useWakeLock)==null||n)try{c=await navigator.wakeLock.request("screen")}catch{}try{var l;return a=await navigator.mediaDevices.getUserMedia({audio:!0}),await ph(i.connectionDelay),s=await hh(e),[r,o]=await Promise.all([qr.create(Yt({},s.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId,workletPaths:e.workletPaths,libsampleratePath:e.libsampleratePath})),$r.create(Yt({},s.outputFormat,{outputDeviceId:e.outputDeviceId,workletPaths:e.workletPaths}))]),(l=a)==null||l.getTracks().forEach(p=>{p.stop()}),a=null,new la(i,s,r,o,c)}catch(p){var d,u,h,f;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),(d=a)==null||d.getTracks().forEach(v=>{v.stop()}),(u=s)==null||u.close(),await((h=r)==null?void 0:h.close()),await((f=o)==null?void 0:f.close());try{var g;await((g=c)==null?void 0:g.release()),c=null}catch{}throw p}}constructor(e,n,i,r,s){super(e,n),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=o=>{this.status==="connected"&&this.connection.sendMessage({user_audio_chunk:lh(o.data[0].buffer)})},this.onOutputWorkletMessage=({data:o})=>{o.type==="process"&&this.updateMode(o.finished?"listening":"speaking")},this.addAudioBase64Chunk=o=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:ab(o)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},this.calculateVolume=o=>{if(o.length===0)return 0;let a=0;for(let c=0;c<o.length;c++)a+=o[c]/255;return a/=o.length,a<0?0:a>1?1:a},this.setVolume=({volume:o})=>{const a=Number.isFinite(o)?Math.min(1,Math.max(0,o)):1;this.volume=a,this.connection instanceof Xt?this.connection.setAudioVolume(a):this.output.gain.gain.value=a},this.input=i,this.output=r,this.wakeLock=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{var e;await((e=this.wakeLock)==null?void 0:e.release()),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var n,i;this.lastInterruptTimestamp<=e.audio_event.event_id&&((n=(i=this.options).onAudio)==null||n.call(i,e.audio_event.audio_base_64),this.connection instanceof Xt||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(e){this.connection instanceof Xt?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData!=null||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Xt?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r}){try{if(this.connection instanceof Bi)try{return await this.input.setInputDevice(r),this.input}catch(o){console.warn("Failed to change device on existing input, recreating:",o)}this.connection instanceof Xt&&await this.connection.setAudioInputDevice(r||""),await this.input.close();const s=await qr.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:n??this.connection.inputFormat.format,preferHeadphonesForIosDevices:i,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath});return this.input=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(s){throw console.error("Error changing input device",s),s}}async changeOutputDevice({sampleRate:e,format:n,outputDeviceId:i}){try{if(this.connection instanceof Bi)try{return await this.output.setOutputDevice(i),this.output}catch(s){console.warn("Failed to change device on existing output, recreating:",s)}this.connection instanceof Xt&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const r=await $r.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:n??this.connection.outputFormat.format,outputDeviceId:i,workletPaths:this.options.workletPaths});return this.output=r,this.output}catch(r){throw console.error("Error changing output device",r),r}}}function gh(t,e,n="https://api.elevenlabs.io"){const i={};return typeof e=="boolean"?i.feedback=e?"like":"dislike":(i.rating=e.rating,i.comment=e.comment),fetch(`${n}/v1/convai/conversations/${t}/feedback`,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json"}})}var vh;(function(t){t.SESSION_STARTED="session_started",t.PARTIAL_TRANSCRIPT="partial_transcript",t.COMMITTED_TRANSCRIPT="committed_transcript",t.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",t.AUTH_ERROR="auth_error",t.ERROR="error",t.OPEN="open",t.CLOSE="close"})(vh||(vh={}));var bh,yh;(function(t){t.PCM_8000="pcm_8000",t.PCM_16000="pcm_16000",t.PCM_22050="pcm_22050",t.PCM_24000="pcm_24000",t.PCM_44100="pcm_44100",t.PCM_48000="pcm_48000",t.ULAW_8000="ulaw_8000"})(bh||(bh={})),(function(t){t.MANUAL="manual",t.VAD="vad"})(yh||(yh={}));class lb extends Fi{static startSession(e){return e.textOnly?ca.startSession(e):la.startSession(e)}}function kh(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var r=t.length;for(e=0;e<r;e++)t[e]&&(n=kh(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function ae(){for(var t,e,n=0,i="",r=arguments.length;n<r;n++)(t=arguments[n])&&(e=kh(t))&&(i&&(i+=" "),i+=e);return i}var db=Object.defineProperty,ub=(t,e,n)=>e in t?db(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ge=(t,e,n)=>ub(t,typeof e!="symbol"?e+"":e,n);function Qt(t){return t?t==="true"?!0:t==="false"?!1:null:null}const da=["variant","placement","override-config","avatar-image-url","avatar-orb-color-1","avatar-orb-color-2","agent-id","signed-url","terms-key","server-location","language","dynamic-variables","show-avatar-when-collapsed","override-prompt","override-first-message","override-language","override-voice-id","override-text-only","mic-muting","transcript","text-input","text-contents","default-expanded","always-expanded","user-id","use-rtc","collect-feedback"],hb='@import"https://fonts.googleapis.com/css2?family=Inter:wght@400,500&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:currentColor}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\\!container{width:100%!important}.container{width:100%}@media (min-width: 640px){.\\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width: 768px){.\\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width: 1024px){.\\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width: 1280px){.\\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width: 1536px){.\\!container{max-width:1536px!important}.container{max-width:1536px}}.pointer-events-auto{pointer-events:auto}.\\!visible{visibility:visible!important}.visible{visibility:visible}.collapse{visibility:collapse}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-3{bottom:-12px}.bottom-0{bottom:0}.bottom-1{bottom:4px}.bottom-20{bottom:80px}.left-0{left:0}.left-1\\/2{left:50%}.left-4{left:16px}.right-0{right:0}.right-1{right:4px}.top-0{top:0}.top-1\\/2{top:50%}.top-20{top:80px}.top-4{top:16px}.top-\\[88px\\]{top:88px}.z-1{z-index:1}.z-10{z-index:10}.m-1{margin:4px}.-mx-0\\.5{margin-left:-2px;margin-right:-2px}.mx-1{margin-left:4px;margin-right:4px}.-mr-1\\.5{margin-right:-6px}.mb-4{margin-bottom:16px}.ml-auto{margin-left:auto}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.block{display:block}.inline{display:inline}.\\!flex{display:flex!important}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.contents{display:contents}.hidden{display:none}.\\!h-8{height:32px!important}.h-11{height:44px}.h-4{height:16px}.h-48{height:192px}.h-5{height:20px}.h-6{height:24px}.h-7{height:28px}.h-8{height:32px}.h-9{height:36px}.h-\\[calc\\(100\\%-80px\\)\\]{height:calc(100% - 80px)}.h-full{height:100%}.h-screen{height:100vh}.max-h-\\[550px\\]{max-height:550px}.max-h-\\[8lh\\]{max-height:8lh}.max-h-\\[min\\(384px\\,var\\(--radix-select-content-available-height\\)\\)\\]{max-height:min(384px,var(--radix-select-content-available-height))}.min-h-0{min-height:0px}.min-h-\\[6lh\\]{min-height:6lh}.min-h-full{min-height:100%}.min-h-min{min-height:-moz-min-content;min-height:min-content}.\\!w-8{width:32px!important}.w-20{width:80px}.w-4{width:16px}.w-48{width:192px}.w-5{width:20px}.w-6{width:24px}.w-64{width:256px}.w-7{width:28px}.w-8{width:32px}.w-9{width:36px}.w-full{width:100%}.w-screen{width:100vw}.\\!min-w-60{min-width:240px!important}.min-w-0{min-width:0px}.min-w-60{min-width:240px}.min-w-9{min-width:36px}.min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.min-w-max{min-width:-moz-max-content;min-width:max-content}.min-w-min{min-width:-moz-min-content;min-width:min-content}.max-w-64{max-width:256px}.max-w-\\[400px\\]{max-width:400px}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-bottom{transform-origin:bottom}.origin-bottom-left{transform-origin:bottom left}.origin-bottom-right{transform-origin:bottom right}.origin-top{transform-origin:top}.origin-top-left{transform-origin:top left}.origin-top-right{transform-origin:top right}.-translate-x-1\\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(calc(var(--el-overlay-padding)) * -1);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-1\\/2{--tw-translate-y: 50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(var(--el-overlay-padding));transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-full{--tw-translate-y: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-180{--tw-rotate: -180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-150{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-75{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-90{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\\[0\\.1667\\]{--tw-scale-x: .1667;--tw-scale-y: .1667;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.place-content-center{place-content:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.gap-1{gap:4px}.gap-2{gap:8px}.gap-2\\.5{gap:10px}.gap-3{gap:12px}.gap-8{gap:32px}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-all{word-break:break-all}.rounded-\\[calc\\(var\\(--el-button-radius\\)\\+4px\\)\\]{border-radius:calc(var(--el-button-radius) + 4px)}.rounded-bubble{border-radius:var(--el-bubble-radius)}.rounded-button{border-radius:var(--el-button-radius)}.rounded-compact-sheet{border-radius:var(--el-compact-sheet-radius)}.rounded-dropdown-sheet{border-radius:var(--el-dropdown-sheet-radius)}.rounded-full{border-radius:9999px}.rounded-input{border-radius:var(--el-input-radius)}.rounded-sheet{border-radius:var(--el-sheet-radius)}.border{border-width:1px}.border-accent{border-color:var(--el-accent)}.border-base{border-color:var(--el-base)}.border-base-border{border-color:var(--el-base-border)}.bg-accent{background-color:var(--el-accent)}.bg-base{background-color:var(--el-base)}.bg-base-active{background-color:var(--el-base-active)}.bg-base-border{background-color:var(--el-base-border)}.bg-base-hover{background-color:var(--el-base-hover)}.bg-cover{background-size:cover}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:4px}.p-1\\.5{padding:6px}.p-2{padding:8px}.p-3{padding:12px}.p-4{padding:16px}.px-1{padding-left:4px;padding-right:4px}.px-1\\.5{padding-left:6px;padding-right:6px}.px-2{padding-left:8px;padding-right:8px}.px-2\\.5{padding-left:10px;padding-right:10px}.px-3{padding-left:12px;padding-right:12px}.px-4{padding-left:16px;padding-right:16px}.px-8{padding-left:32px;padding-right:32px}.py-1\\.5{padding-top:6px;padding-bottom:6px}.py-2\\.5{padding-top:10px;padding-bottom:10px}.py-4{padding-top:16px;padding-bottom:16px}.py-\\[calc\\(theme\\(spacing\\.2\\)-1px\\)\\]{padding-top:7px;padding-bottom:7px}.pb-1{padding-bottom:4px}.pb-2{padding-bottom:8px}.pb-3{padding-bottom:12px}.pl-16{padding-left:64px}.pr-16{padding-right:64px}.pr-3{padding-right:12px}.pr-9{padding-right:36px}.pt-1{padding-top:4px}.pt-3{padding-top:12px}.pt-4{padding-top:16px}.text-center{text-align:center}.text-\\[10px\\]{font-size:10px}.text-lg{font-size:18px;line-height:26px}.text-md{font-size:16px;line-height:24px}.text-sm{font-size:14px;line-height:20px}.text-xl{font-size:20px;line-height:28px}.text-xs{font-size:12px;line-height:16px}.font-medium{font-weight:500}.text-accent-primary{color:var(--el-accent-primary)}.text-base-border{color:var(--el-base-border)}.text-base-error{color:var(--el-base-error)}.text-base-primary{color:var(--el-base-primary)}.text-base-subtle{color:var(--el-base-subtle)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-30{opacity:.3}.shadow-header{--tw-shadow: 0 0 1px 0 rgba(0, 0, 0, .4), 0 2px 2px 0 rgba(0, 0, 0, .04);--tw-shadow-colored: 0 0 1px 0 var(--tw-shadow-color), 0 2px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 2px 40px 1px rgba(0, 0, 0, .12);--tw-shadow-colored: 0 2px 40px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 2px 24px 1px rgba(0, 0, 0, .16);--tw-shadow-colored: 0 2px 24px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[border-radius\\]{transition-property:border-radius;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[margin\\]{transition-property:margin;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,width\\,height\\,transform\\,flex-grow\\]{transition-property:opacity,width,height,transform,flex-grow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,left\\,top\\,opacity\\,scale\\]{transition-property:transform,left,top,opacity,scale;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,opacity\\]{transition-property:transform,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.overlay{position:absolute;inset:var(--el-overlay-padding);right:calc(var(--el-overlay-padding) + var(--removed-body-scroll-bar-size, 0px))}.focus-ring{--tw-ring-color: var(--el-accent);--tw-ring-offset-width: 2px;--tw-ring-offset-color: var(--el-base)}.focus-ring:focus-visible{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.animate-text{background-image:linear-gradient(75deg,var(--el-base-primary),var(--el-base-subtle),var(--el-base-primary),var(--el-base-subtle));background-size:300% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:TextAnimation 2s linear infinite}@keyframes TextAnimation{0%{background-position:0 0}to{background-position:100% 0}}.\\!terms h6,.terms h6{font-size:12px;line-height:16px;font-weight:500;color:var(--el-base-primary)}.\\!terms h5,.terms h5{font-size:14px;line-height:20px;font-weight:500;color:var(--el-base-primary)}.\\!terms h4,.terms h4{font-size:16px;line-height:24px;font-weight:500;color:var(--el-base-primary)}.\\!terms h3,.terms h3{font-size:18px;line-height:26px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:20px;line-height:28px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:24px;line-height:30px;font-weight:500;color:var(--el-base-primary)}.\\[field-sizing\\:content\\]{field-sizing:content}.\\[line-height\\:var\\(--el-overlay-padding\\)\\]{line-height:var(--el-overlay-padding)}.\\[overflow-wrap\\:break-word\\]{overflow-wrap:break-word}.dev-host,:host{pointer-events:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1000;font-size:16px;line-height:24px;color:var(--el-base-primary);font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;scrollbar-color:#e5e7eb transparent}.placeholder\\:text-base-subtle::-moz-placeholder{color:var(--el-base-subtle)}.placeholder\\:text-base-subtle::placeholder{color:var(--el-base-subtle)}.hover\\:border-accent-hover:hover{border-color:var(--el-accent-hover)}.hover\\:border-base-hover:hover{border-color:var(--el-base-hover)}.hover\\:bg-accent-hover:hover{background-color:var(--el-accent-hover)}.hover\\:bg-base-hover:hover{background-color:var(--el-base-hover)}.hover\\:opacity-50:hover{opacity:.5}.focus-visible\\:underline-offset-2:focus-visible{text-underline-offset:2px}.focus-visible\\:opacity-100:focus-visible{opacity:1}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.active\\:border-accent-active:active{border-color:var(--el-accent-active)}.active\\:border-base-active:active{border-color:var(--el-base-active)}.active\\:bg-accent-active:active{background-color:var(--el-accent-active)}.active\\:bg-base-active:active{background-color:var(--el-base-active)}.data-hidden\\:-translate-y-4[data-shown=false]{--tw-translate-y: -16px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-x-full[data-shown=false]{--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-y-2[data-shown=false]{--tw-translate-y: 8px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-100[data-shown=false]{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-75[data-shown=false]{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-90[data-shown=false]{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:opacity-0[data-shown=false]{opacity:0}.data-\\[highlighted\\]\\:bg-base-active[data-highlighted]{background-color:var(--el-base-active)}',Ch=["tiny","compact","full"];function fb(t){return Ch.includes(t)?t:Ch[0]}const pb=["top-left","top","top-right","bottom-left","bottom","bottom-right"];function mb(t){return pb.includes(t)?t:"bottom-right"}const wh={main_label:"Need help?",start_call:"Start a call",start_chat:"Start a chat",send_message:"Send",new_call:"New call",end_call:"End",mute_microphone:"Mute microphone",change_language:"Change language",collapse:"Collapse",expand:"Expand",copied:"Copied!",accept_terms:"Accept",dismiss_terms:"Cancel",listening_status:"Listening",speaking_status:"Talk to interrupt",connecting_status:"Connecting",chatting_status:"Chatting with AI Agent",input_label:"Text message input",input_placeholder:"Send a message",input_placeholder_text_only:"Send a message",input_placeholder_new_conversation:"Start a new conversation",user_ended_conversation:"You ended the conversation",agent_ended_conversation:"The agent ended the conversation",conversation_id:"ID",error_occurred:"An error occurred",copy_id:"Copy ID",initiate_feedback:"How was this conversation?",request_follow_up_feedback:"Tell us more",thanks_for_feedback:"Thank you for your feedback!",thanks_for_feedback_details:"Your feedback helps us improve our service and better support you in the future.",follow_up_feedback_placeholder:"Tell us more about your experience...",submit:"Submit",go_back:"Go back"},gb=Object.keys(wh),_h={base:"#ffffff",base_hover:"#f9fafb",base_active:"#f3f4f6",base_border:"#e5e7eb",base_subtle:"#6b7280",base_primary:"#000000",base_error:"#ef4444",accent:"#000000",accent_hover:"#1f2937",accent_active:"#374151",accent_border:"#4b5563",accent_subtle:"#6b7280",accent_primary:"#ffffff",overlay_padding:32,button_radius:18,input_radius:10,bubble_radius:15,sheet_radius:"calc(var(--el-button-radius) + 6px)",compact_sheet_radius:"calc(var(--el-button-radius) + 12px)",dropdown_sheet_radius:"calc(var(--el-input-radius) + 6px)"},vb=Object.keys(_h);function bb(t="us"){switch(t){case"eu-residency":case"in-residency":case"us":case"global":return t;default:return console.warn(`[ConversationalAI] Invalid server-location: ${t}. Defaulting to "us"`),"us"}}function et(t){const e=sn(t);if(e==null)throw new Error(`${t.displayName} cannot be used outside of provider`);return e}const Sh=Ie(null);function yb({value:t,children:e}){const n=oe(()=>Object.fromEntries(da.map(i=>[i,Je(t[i])])),[]);return da.forEach(i=>{n[i].value=t[i]}),m(Sh.Provider,{value:n,children:e})}function kb(){return et(Sh)}function ie(t){return kb()[t]}const Th=Ie(null);function Cb({children:t}){const e=ie("server-location"),n=oe(()=>{const i=Ye(()=>bb(e.value)),r={us:"https://api.us.elevenlabs.io","eu-residency":"https://api.eu.residency.elevenlabs.io","in-residency":"https://api.in.residency.elevenlabs.io",global:"https://api.elevenlabs.io"},s={us:"wss://api.us.elevenlabs.io","eu-residency":"wss://api.eu.residency.elevenlabs.io","in-residency":"wss://api.in.residency.elevenlabs.io",global:"wss://api.elevenlabs.io"};return{location:i,serverUrl:Ye(()=>r[i.value]),webSocketUrl:Ye(()=>s[i.value])}},[]);return m(Th.Provider,{value:n,children:t})}function ua(){return et(Th)}const ji={en:{name:"English",flagCode:"us",languageCode:"en"},zh:{name:"中文",flagCode:"cn",languageCode:"zh"},es:{name:"Español",flagCode:"es",languageCode:"es"},hi:{name:"हिन्दी",flagCode:"in",languageCode:"hi"},pt:{name:"Português (Portugal)",flagCode:"pt",languageCode:"pt"},"pt-br":{name:"Português (Brasil)",flagCode:"br",languageCode:"pt-br"},fr:{name:"Français",flagCode:"fr",languageCode:"fr"},de:{name:"Deutsch",flagCode:"de",languageCode:"de"},ja:{name:"日本語",flagCode:"jp",languageCode:"ja"},ar:{name:"العربية",flagCode:"ae",languageCode:"ar"},ru:{name:"Русский",flagCode:"ru",languageCode:"ru"},ko:{name:"한국어",flagCode:"kr",languageCode:"ko"},id:{name:"Bahasa Indonesia",flagCode:"id",languageCode:"id"},it:{name:"Italiano",flagCode:"it",languageCode:"it"},nl:{name:"Nederlands",flagCode:"nl",languageCode:"nl"},tr:{name:"Türkçe",flagCode:"tr",languageCode:"tr"},pl:{name:"Polski",flagCode:"pl",languageCode:"pl"},sv:{name:"Svenska",flagCode:"se",languageCode:"sv"},ms:{name:"Bahasa Melayu",flagCode:"my",languageCode:"ms"},ro:{name:"Română",flagCode:"ro",languageCode:"ro"},uk:{name:"Українська",flagCode:"ua",languageCode:"uk"},el:{name:"Ελληνικά",flagCode:"gr",languageCode:"el"},cs:{name:"Čeština",flagCode:"cz",languageCode:"cs"},da:{name:"Dansk",flagCode:"dk",languageCode:"da"},fi:{name:"Suomi",flagCode:"fi",languageCode:"fi"},bg:{name:"Български",flagCode:"bg",languageCode:"bg"},hr:{name:"Hrvatski",flagCode:"hr",languageCode:"hr"},sk:{name:"Slovenčina",flagCode:"sk",languageCode:"sk"},ta:{name:"தமிழ்",flagCode:"in",languageCode:"ta"},hu:{name:"Magyar",flagCode:"hu",languageCode:"hu"},no:{name:"Norsk",flagCode:"no",languageCode:"no"},vi:{name:"Tiếng Việt",flagCode:"vn",languageCode:"vi"},tl:{name:"Filipino",flagCode:"ph",languageCode:"tl"}};function ha(t){return Object.keys(ji).includes(t??"")}const xh=Ie(null);function wb({children:t}){const e=Ae(),n=ie("language"),i=ie("override-language"),r=Oe(n.peek()??e.peek().language),s=ue(()=>(e.value.supported_language_overrides??[]).filter(ha)),o=ue(()=>s.value.map(c=>ji[c]).sort((c,l)=>c.name.localeCompare(l.name))),a=oe(()=>({language:Ye(()=>ha(i.value)?ji[i.value]:ha(r.value)&&s.value.includes(r.value)?ji[r.value]:ji[e.value.language]),setLanguage:c=>{r.value=c},options:o,showPicker:Ye(()=>o.value.length>0)}),[]);return m(xh.Provider,{value:a,children:t})}function ri(){return et(xh)}const _b="0.5.2",Eh=Ie(null);function Sb({children:t}){const e=Ae(),n=ue(()=>e.value.mic_muting_enabled??!1),i=Oe(!1),r=oe(()=>({isMuted:Ye(()=>n.value?i.value:!1),setIsMuted:s=>{i.value=s},isMutingEnabled:n}),[]);return m(Eh.Provider,{value:r,children:t})}function Ph(){return et(Eh)}const Rh=Ie(null);function Tb({children:t}){const{language:e}=ri(),n=ie("override-prompt"),i=ie("override-first-message"),r=ie("override-voice-id"),s=ie("override-text-only"),o=ie("user-id"),a=ue(()=>({agent:{prompt:{prompt:n.value},firstMessage:i.value,language:e.value.languageCode},tts:{voiceId:r.value},conversation:{textOnly:Qt(s.value)??void 0}})),c=ie("dynamic-variables"),l=ue(()=>{if(c.value)try{return JSON.parse(c.value)}catch(v){console.error(`[ConversationalAI] Cannot parse dynamic-variables: ${v==null?void 0:v.message}`)}}),{webSocketUrl:d}=ua(),u=ie("agent-id"),h=ie("signed-url"),f=fa(),g=Db(),p=ue(()=>{const v=g.value,b={dynamicVariables:l.value,overrides:a.value,connectionDelay:{default:300},textOnly:f.value,userId:o.value||void 0};return u.value?v?{agentId:u.value,origin:d.value,connectionType:"webrtc",...b}:{agentId:u.value,origin:d.value,connectionType:"websocket",...b}:h.value?{signedUrl:h.value,connectionType:"websocket",...b}:(console.error("[ConversationalAI] Either agent-id or signed-url is required"),null)});return p.value?m(Rh.Provider,{value:p,children:t}):null}function xb(){return et(Rh)}const Ih=Ie(null);function Eb({children:t}){const e=Ae(),n=oe(()=>{const i=e.peek().terms_key,r=i?!!localStorage.getItem(i):!1,s=Je(!1),o=Je(r),a=Ye(()=>!e.value.terms_html||o.value);let c=[];return{termsShown:s,termsAccepted:a,dismissTerms:()=>{s.value=!1,c.forEach(l=>l.reject()),c=[]},acceptTerms:()=>{o.value=!0,s.value=!1;const l=e.peek().terms_key;l&&localStorage.setItem(l,"true"),c.forEach(d=>d.resolve()),c=[]},requestTerms:async()=>{a.peek()||(s.value=!0,await new Promise((l,d)=>{c.push({resolve:l,reject:d})}))}}},[]);return m(Ih.Provider,{value:n,children:t})}function zr(){return et(Ih)}const Oh=Ie(null);function Pb({children:t}){const e=Rb();return Ct(()=>{if(e.conversationTextOnly.value===!0){e.transcript.value;const n=setTimeout(()=>{e.endSession()},600*1e3);return()=>{clearTimeout(n)}}}),m(Oh.Provider,{value:e,children:t})}function Be(){return et(Oh)}function Rb(){const t=B(null),e=B(null),n=B(!1),i=B(null),r=B(!1),s=Ae(),o=Ah(),a=zr(),c=xb(),{isMuted:l}=Ph();return Ct(()=>{var d;const u=l.value;(d=t==null?void 0:t.current)==null||d.setMicMuted(u)}),K(()=>()=>{var d;(d=t.current)==null||d.endSession()},[]),oe(()=>{const d=Je("disconnected"),u=Ye(()=>d.value==="disconnected"),h=Je("listening"),f=Ye(()=>h.value==="speaking"),g=Je(null),p=Je(null),v=Je(!1),b=Je([]),k=Je(0),w=Je(null);return{status:d,isSpeaking:f,mode:h,isDisconnected:u,lastId:p,error:g,canSendFeedback:v,conversationIndex:k,conversationTextOnly:w,transcript:b,startSession:async(y,_)=>{var S,x,I,R,D,M,U;if(await a.requestTerms(),(S=t.current)!=null&&S.isOpen())return t.current.getId();if(e.current)return(await e.current).getId();let j=structuredClone(c.peek());_&&s.value.supports_text_only&&(j.textOnly=!0,s.value.text_only||(j.overrides??(j.overrides={}),(x=j.overrides).conversation??(x.conversation={}),j.overrides.conversation.textOnly=!0));try{j=Ib(y,j)}catch($){console.error("[ConversationalAI] Error triggering call event:",$)}w.value=j.textOnly??!1,b.value=_?[{type:"message",role:"user",message:_,isText:!0,conversationIndex:k.peek()}]:[];try{if(e.current=lb.startSession({...j,overrides:{...j.overrides,client:{...(I=j.overrides)==null?void 0:I.client,source:((D=(R=j.overrides)==null?void 0:R.client)==null?void 0:D.source)||"widget",version:((U=(M=j.overrides)==null?void 0:M.client)==null?void 0:U.version)||_b}},onModeChange:F=>{h.value=F.mode},onStatusChange:F=>{d.value=F.status},onCanSendFeedbackChange:F=>{v.value=F.canSendFeedback},onMessage:({source:F,message:G})=>{if(o.peek()&&w.peek()===!0&&F==="ai"&&!n.current){n.current=!0;return}else F==="ai"&&(n.current=!0);if(F==="ai"&&r.current){r.current=!1;return}b.value=[...b.value,{type:"message",role:F,message:G,isText:!1,conversationIndex:k.peek()}]},onAgentChatResponsePart:({text:F,type:G})=>{if(o.peek()&&w.peek()===!0&&!n.current)return;const Y=b.peek();if(G==="start")r.current=!0,i.current=Y.length,b.value=[...Y,{type:"message",role:"ai",message:"",isText:!0,conversationIndex:k.peek()}];else if(G==="delta"){const W=i.current;if(W!==null&&Y[W]){const ee=[...Y],we=ee[W];we.type==="message"&&(ee[W]={...we,message:we.message+F},b.value=ee)}}else G==="stop"&&(i.current=null)},onDisconnect:F=>{n.current=!1,w.value=null,i.current=null,r.current=!1,b.value=[...b.value,F.reason==="error"?{type:"error",message:F.message,conversationIndex:k.peek()}:{type:"disconnection",role:F.reason==="user"?"user":"ai",conversationIndex:k.peek()}],k.value++,F.reason==="error"&&(g.value=F.message,console.error("[ConversationalAI] Disconnected due to an error:",F.message))}}),t.current=await e.current,t.current.setMicMuted(l.peek()),_){const F=t.current;setTimeout(()=>F.sendUserMessage(_),100)}const $=t.current.getId();return p.value=$,g.value=null,$}catch($){let F="Could not start a conversation.";$ instanceof CloseEvent?F=$.reason||F:$ instanceof Error&&(F=$.message||F),g.value=F,b.value=[...b.value,{type:"error",message:F,conversationIndex:k.peek()}]}finally{e.current=null}},endSession:async()=>{const y=t.current;t.current=null,await(y==null?void 0:y.endSession())},getInputVolume:()=>{var y;return((y=t.current)==null?void 0:y.getInputVolume())??0},getOutputVolume:()=>{var y;return((y=t.current)==null?void 0:y.getOutputVolume())??0},sendFeedback:y=>{var _;(_=t.current)==null||_.sendFeedback(y)},sendUserMessage:y=>{var _;(_=t.current)==null||_.sendUserMessage(y),b.value=[...b.value,{type:"message",role:"user",message:y,isText:!0,conversationIndex:k.peek()}]},sendUserActivity:()=>{var y;(y=t.current)==null||y.sendUserActivity()}}},[c,l])}function Ib(t,e){try{const n=new CustomEvent("elevenlabs-convai:call",{bubbles:!0,composed:!0,detail:{config:e}});return t.dispatchEvent(n),n.detail.config}catch(n){return console.error("[ConversationalAI] Could not trigger call event:",n),e}}const Dh=Ie(null);function Ob({children:t}){const{serverUrl:e}=ua(),n=ie("agent-id"),i=ie("override-config"),r=ie("signed-url"),s=Oe(null);Ct(()=>{if(i.value)try{const y=JSON.parse(i.value);if(y){s.value=y;return}}catch(y){console.error(`[ConversationalAI] Cannot parse override-config: ${y==null?void 0:y.message}`)}let b=n.value,k;if(r.value){const y=new URL(r.value).searchParams;b=y.get("agent_id")??n.value,k=y.get("conversation_signature")??void 0}if(!b){s.value=null;return}const w=new AbortController;return Mb(b,e.value,w.signal,k).then(y=>{w.signal.aborted||(s.value=y)}).catch(y=>{console.error(`[ConversationalAI] Cannot fetch config for agent ${n.value}: ${y==null?void 0:y.message}`),w.signal.aborted||(s.value=null)}),()=>{w.abort()}});const o=ie("variant"),a=ie("placement"),c=ie("terms-key"),l=ie("mic-muting"),d=ie("transcript"),u=ie("text-input"),h=ie("default-expanded"),f=ie("always-expanded"),g=ie("override-text-only"),p=ie("use-rtc"),v=ue(()=>{if(!s.value)return null;const b=o.value??s.value.variant,k=a.value??s.value.placement,w=c.value??s.value.terms_key,y=Qt(g.value)??s.value.text_only??!1,_=Qt(l.value)??s.value.mic_muting_enabled,S=Qt(d.value)??s.value.transcript_enabled,x=Qt(u.value)??s.value.text_input_enabled,I=Qt(f.value)??s.value.always_expanded??!1,R=Qt(h.value)??s.value.default_expanded??!1,D=Qt(p.value)??s.value.use_rtc??!1;return{...s.value,variant:fb(b),placement:mb(k),terms_key:w,mic_muting_enabled:!y&&_,transcript_enabled:y||S,text_input_enabled:y||x,always_expanded:I,default_expanded:R,use_rtc:D}});return v.value?m(Dh.Provider,{value:v,children:t}):null}function Ae(){return et(Dh)}function fa(){const t=ie("override-text-only"),e=Ae();return ue(()=>Qt(t.value)??e.value.text_only??!1)}function Wr(){const t=fa(),{conversationTextOnly:e}=Be();return ue(()=>e.value??t.value)}function Ah(){const t=ie("override-first-message"),e=Ae(),{language:n}=ri();return ue(()=>{var i,r;return t.value??((r=(i=e.value.language_presets)==null?void 0:i[n.value.languageCode])==null?void 0:r.first_message)??e.value.first_message??null})}function Db(){const t=Ae();return ue(()=>t.value.use_rtc??!1)}function Ab(){const t=Ae();return ue(()=>{var e;return((e=t.value.end_feedback)==null?void 0:e.type)??null})}async function Mb(t,e,n,i){const r=await(await fetch(`${e}/v1/convai/agents/${t}/widget${i?`?conversation_signature=${encodeURIComponent(i)}`:""}`,{signal:n})).json();if(!r.widget_config)throw new Error("Response does not contain widget_config");return r.widget_config}const Nb=tr(function(){const t=Ae(),e=ue(()=>{const n=t.value.styles;return`:host, :root {
255
255
  ${vb.map(i=>`${Lb(i)}: ${Ub((n==null?void 0:n[i])??_h[i])};`).join(`
256
256
  `)}
257
257
  }`});return m("style",{children:[e,hb]})});function Lb(t){return`--el-${t.replace(/_/g,"-")}`}function Ub(t){return typeof t=="number"?`${t}px`:t}const Mh=Ie(null);function Fb({children:t}){const e=Ae(),{language:n}=ri(),i=ie("text-contents"),r=ue(()=>{try{if(i.value){const o=JSON.parse(i.value);if(typeof o=="object")return o}}catch(o){console.error("[ConversationalAI] Cannot parse text-contents:",o)}return{}}),s=oe(()=>Object.fromEntries(gb.map(o=>[o,Ye(()=>{var a,c,l,d;return r.value[o]??((l=(c=(a=e.value.language_presets)==null?void 0:a[n.value.languageCode])==null?void 0:c.text_contents)==null?void 0:l[o])??((d=e.value.text_contents)==null?void 0:d[o])??wh[o]})])),[]);return m(Mh.Provider,{value:s,children:t})}function Ee(){return et(Mh)}const Nh=Ie(null);function Bb({children:t}){const e=Ae(),n=ie("avatar-image-url"),i=ie("avatar-orb-color-1"),r=ie("avatar-orb-color-2"),s=Oe(""),o=ue(()=>n.value?{type:"image",url:n.value}:i.value&&r.value?{type:"orb",color_1:i.value,color_2:r.value}:e.value.avatar),a=ue(()=>{switch(o.value.type){case"url":return o.value.custom_url;case"orb":return s.value;case"image":return o.value.url}}),c=oe(()=>({config:o,previewUrl:a,canvasUrl:s}),[]);return m(Nh.Provider,{value:c,children:t})}function pa(){return et(Nh)}const Lh=Ie(null);function Hr({children:t,...e}){const[n,i]=q(null);return m("div",{ref:i,...e,children:n&&m(Lh.Provider,{value:n,children:t})})}function jb(){return et(Lh)}function ma(t){return t&&typeof t=="object"&&"peek"in t}function Vb(t){const e=ma(t),n=Oe(e?t.peek():t);return e?t:(n.value=t,n)}function Uh(t){return ma(t)?t.value:t}function qb(t){return ma(t)?t.peek():t}function Fh(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Bh(...t){return e=>{let n=!1;const i=t.map(r=>{const s=Fh(r,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let r=0;r<i.length;r++){const s=i[r];typeof s=="function"?s():Fh(t[r],null)}}}}function Fe(...t){return V(Bh(...t),t)}function Vi(t){const e=$b(t),n=Q((i,r)=>{const{children:s,...o}=i,a=on.toArray(s),c=a.find(Wb);if(c){const l=c.props.children,d=a.map(u=>u===c?on.count(l)>1?on.only(null):jt(l)?l.props.children:null:u);return m(e,{...o,ref:r,children:jt(l)?wi(l,void 0,d):null})}return m(e,{...o,ref:r,children:s})});return n.displayName=`${t}.Slot`,n}var jh=Vi("Slot");function $b(t){const e=Q((n,i)=>{const{children:r,...s}=n;if(jt(r)){const o=Gb(r),a=Hb(s,r.props);return r.type!==ge&&(a.ref=i?Bh(i,o):o),wi(r,a)}return on.count(r)>1?on.only(null):null});return e.displayName=`${t}.SlotClone`,e}var zb=Symbol("radix.slottable");function Wb(t){return jt(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===zb}function Hb(t,e){const n={...e};for(const i in e){const r=t[i],s=e[i];/^on[A-Z]/.test(i)?r&&s?n[i]=(...o)=>{const a=s(...o);return r(...o),a}:r&&(n[i]=r):i==="style"?n[i]={...r,...s}:i==="className"&&(n[i]=[r,s].filter(Boolean).join(" "))}return{...t,...n}}function Gb(t){var e,n;let i=(e=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:e.get,r=i&&"isReactWarning"in i&&i.isReactWarning;return r?t.ref:(i=(n=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:n.get,r=i&&"isReactWarning"in i&&i.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}const ga=window.matchMedia("(prefers-reduced-motion: reduce)");function Vh(){const t=Oe(ga.matches);return K(()=>{const e=n=>{t.value=n.matches};return ga.addEventListener("change",e),()=>ga.removeEventListener("change",e)},[]),t}function qh({onStart:t,onEnd:e}){const n=B();n.current??(n.current=new Set);const i=B(t);i.current=t;const r=B(e);r.current=e;const s=Oe(!1),o=V(c=>{var l,d;c.target===c.currentTarget&&((l=n.current)==null||l.add(c.propertyName),s.peek()||(s.value=!0,(d=i.current)==null||d.call(i)))},[]),a=V(c=>{var l,d,u;c.target===c.currentTarget&&((l=n.current)==null||l.delete(c.propertyName),(d=n.current)!=null&&d.size||(s.value=!1,(u=r.current)==null||u.call(r)))},[]);return{transitioning:s,handlers:{onTransitionStart:o,onTransitionEnd:a}}}function je(t){const e=Vh().value?Kb:Jb;return m(e,{...t})}function Kb({active:t,...e}){return Uh(t)?m(jh,{"data-shown":!0,...e}):null}function Jb({active:t,initial:e=t,...n}){const i=Vb(t),r=Oe(qb(e));Ct(()=>{i.value&&(r.value=i.value)});const{handlers:s}=qh({onEnd:()=>{r.value=i.value}});return!i.value&&!r.value?null:m(jh,{"data-shown":i.value&&r.value,...s,...n})}const Yb=`#version 300 es
@@ -429,7 +429,7 @@ void main() {
429
429
  vUv = position * 0.5 + 0.5;
430
430
  gl_Position = vec4(position, 0, 1);
431
431
  }
432
- `,$h=0,Qb=new Float32Array([-1,1,-1,-1,1,1,1,-1]),Zb="https://storage.googleapis.com/eleven-public-cdn/images/perlin-noise.png",zh=class _n{constructor(e){Ge(this,"gl"),Ge(this,"program"),Ge(this,"startTime"),Ge(this,"targetSpeed",0),Ge(this,"speed",.5),Ge(this,"rafId",null),Ge(this,"resizeObserver"),Ge(this,"colorA",[0,0,0]),Ge(this,"colorB",[0,0,0]),Ge(this,"offsets",new Float32Array(7).map(()=>Math.random()*Math.PI*2)),Ge(this,"copyNoiseImage",()=>{this.gl&&(this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,_n.noiseImage),this.gl.generateMipmap(this.gl.TEXTURE_2D))}),Ge(this,"toDataURL",()=>this.gl.canvas.toDataURL("image/png")),Ge(this,"render",()=>{if(!this.gl){this.rafId=null;return}const o=(performance.now()-this.startTime)/1e3;this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uTime"),o),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.rafId=requestAnimationFrame(this.render)});const n=e.getContext("webgl2",{depth:!1,stencil:!1});this.gl=n,this.program=this.setupProgram(Yb,Xb);const i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([128,128,128,255])),_n.noiseImage||(_n.noiseImage=new Image,_n.noiseImage.crossOrigin="anonymous",_n.noiseImage.src=Zb),_n.noiseImage.complete?this.copyNoiseImage():_n.noiseImage.addEventListener("load",this.copyNoiseImage);const r=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,Qb,n.STATIC_DRAW),n.vertexAttribPointer($h,2,n.FLOAT,!1,0,0),n.enableVertexAttribArray($h),this.updateColors("#2792DC","#9CE6E6"),this.resizeObserver=new ResizeObserver(o=>{const a=o[0],c=a.devicePixelContentBoxSize?a.devicePixelContentBoxSize[0]:a.contentBoxSize[0];e.width=Math.min(512,c.inlineSize),e.height=Math.min(512,c.blockSize),this.updateViewport()});const s=e.parentElement;if(s)try{this.resizeObserver.observe(s,{box:"device-pixel-content-box"})}catch{this.resizeObserver.observe(s)}this.startTime=performance.now(),this.rafId=requestAnimationFrame(this.render)}dispose(){var e;this.rafId!==null&&cancelAnimationFrame(this.rafId),(e=this.resizeObserver)==null||e.disconnect(),this.gl=null,this.program=null}updateViewport(){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}updateColors(e,n){this.gl&&(this.colorA=this.updateColor("uColor1",e)??this.colorA,this.colorB=this.updateColor("uColor2",n)??this.colorB)}updateVolume(e,n){this.targetSpeed=.2+(1-Math.pow(n-1,2))*1.8,this.targetSpeed>this.speed&&(this.speed=this.targetSpeed),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uInputVolume"),e),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uOutputVolume"),n)}updateColor(e,n){try{const i=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,o=[Math.pow(i,2.2),Math.pow(r,2.2),Math.pow(s,2.2)];return this.gl.uniform3fv(this.gl.getUniformLocation(this.program,e),o),o}catch(i){console.error(`[ConversationalAI] Failed to parse ${n} as color:`,i)}}setupProgram(e,n){const i=this.getShader(this.gl.FRAGMENT_SHADER,e),r=this.getShader(this.gl.VERTEX_SHADER,n);if(!i||!r)throw new Error("Failed to compile shaders");if(this.program=this.gl.createProgram(),this.gl.attachShader(this.program,i),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),!this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS))throw new Error("Failed to link program");return this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"uPerlinTexture"),0),this.gl.uniform1fv(this.gl.getUniformLocation(this.program,"uOffsets"),this.offsets),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor1"),this.colorA),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor2"),this.colorB),this.program}getShader(e,n){const i=this.gl.createShader(e);return this.gl.shaderSource(i,n),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)?i:(this.gl.deleteShader(i),null)}};Ge(zh,"noiseImage");let ey=zh;const ty={sm:"w-9 h-9",lg:"w-48 h-48"};function si({size:t="sm",className:e}){const{getInputVolume:n,getOutputVolume:i,isSpeaking:r,isDisconnected:s}=Be(),{config:o}=pa(),a=B(null),c=B(null);Ct(()=>{if(s.value){a.current.style.transform="",c.current.style.transform="";return}let d;function u(){const h=n(),f=i(),g=r.peek()?1:1-h*.4,p=r.peek()?1+f*.4:1;a.current.style.transform=`scale(${p})`,c.current.style.transform=`scale(${g})`,d=requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(d)}});const l=ue(()=>({backgroundImage:o.value.type==="image"?`url(${o.value.url})`:o.value.type==="url"?`url(${o.value.custom_url})`:void 0}));return m("div",{className:ae("relative shrink-0",ty[t],e),children:[m("div",{ref:a,className:"absolute inset-0 rounded-full bg-base-border"}),m("div",{ref:c,style:l,className:"absolute inset-0 rounded-full overflow-hidden bg-base bg-cover",children:o.value.type==="orb"&&m(ny,{color1:o.value.color_1,color2:o.value.color_2})})]})}function ny({color1:t,color2:e}){const{canvasUrl:n}=pa(),[i,r]=q(null);K(()=>{i&&(i.updateColors(t,e),i.render(),n.value=i.toDataURL())},[i,t,e]);const s=V(o=>{if(o){const a=new ey(o);return r(a),()=>a.dispose()}else r(null)},[r]);return m("canvas",{className:"w-full h-full",ref:s})}const iy={phone:sy,"phone-off":oy,chat:ay,mic:cy,"mic-off":ly,check:hy,"chevron-down":dy,"chevron-up":uy,send:fy,star:py},ry={sm:"text-xs",md:"text-lg",lg:"text-xl"};function It({name:t,size:e="md",className:n}){const i=iy[t];return m("slot",{name:`icon-${t}`,className:ae("flex",ry[e],n),"aria-hidden":!0,children:m(i,{})})}function sy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{d:"M3.7489 2.25C2.93286 2.25 2.21942 2.92142 2.27338 3.7963C2.6686 10.2041 7.79483 15.3303 14.2026 15.7255C15.0775 15.7795 15.7489 15.066 15.7489 14.25V11.958C15.7489 11.2956 15.3144 10.7116 14.6799 10.5213L12.6435 9.91035C12.1149 9.75179 11.542 9.89623 11.1518 10.2864L10.5901 10.8482C9.15291 10.0389 7.95998 8.84599 7.15074 7.40881L7.71246 6.84709C8.10266 6.45689 8.24711 5.88396 8.08854 5.35541L7.47761 3.31898C7.28727 2.6845 6.70329 2.25 6.04087 2.25H3.7489Z"})})}function oy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M16.0303 3.53033C16.3232 3.23744 16.3232 2.76256 16.0303 2.46967C15.7374 2.17678 15.2626 2.17678 14.9697 2.46967L8.6271 8.81224C8.25925 8.3778 7.93185 7.90804 7.65074 7.40881L8.21246 6.84709C8.60266 6.45689 8.74711 5.88396 8.58854 5.35541L7.97761 3.31898C7.78727 2.6845 7.20329 2.25 6.54087 2.25H4.2489C3.43286 2.25 2.71942 2.92142 2.77338 3.7963C2.95462 6.73468 4.13069 9.40357 5.96899 11.4703L2.96967 14.4697C2.67678 14.7626 2.67678 15.2374 2.96967 15.5303C3.26256 15.8232 3.73744 15.8232 4.03033 15.5303L16.0303 3.53033Z"}),m("path",{d:"M14.7026 15.7255C12.2994 15.5773 10.0765 14.7636 8.21584 13.4665L10.9278 10.7545C10.9815 10.7863 11.0356 10.8175 11.0901 10.8482L11.6518 10.2864C12.042 9.89623 12.6149 9.75179 13.1435 9.91035L15.1799 10.5213C15.8144 10.7116 16.2489 11.2956 16.2489 11.958V14.25C16.2489 15.066 15.5775 15.7795 14.7026 15.7255Z"})]})}function ay(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M1.5 6.75C1.5 4.26472 3.51472 2.25 6 2.25H12C14.4853 2.25 16.5 4.26472 16.5 6.75V11.25C16.5 13.7353 14.4853 15.75 12 15.75H2.25C1.83579 15.75 1.5 15.4142 1.5 15V6.75ZM6 9.9375C5.48223 9.9375 5.0625 9.51777 5.0625 9C5.0625 8.48223 5.48223 8.0625 6 8.0625C6.51777 8.0625 6.9375 8.48223 6.9375 9C6.9375 9.51777 6.51777 9.9375 6 9.9375ZM9 9.9375C8.48223 9.9375 8.0625 9.51777 8.0625 9C8.0625 8.48223 8.48223 8.0625 9 8.0625C9.51777 8.0625 9.9375 8.48223 9.9375 9C9.9375 9.51777 9.51777 9.9375 9 9.9375ZM11.0625 9C11.0625 9.51777 11.4822 9.9375 12 9.9375C12.5178 9.9375 12.9375 9.51777 12.9375 9C12.9375 8.48223 12.5178 8.0625 12 8.0625C11.4822 8.0625 11.0625 8.48223 11.0625 9Z"})})}function cy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M9.50008 1.5C7.42901 1.5 5.75008 3.17893 5.75008 5.25V8.25C5.75008 10.3211 7.42901 12 9.50008 12C11.5712 12 13.2501 10.3211 13.2501 8.25V5.25C13.2501 3.17893 11.5712 1.5 9.50008 1.5Z"}),m("path",{d:"M4.88997 10.8417C4.66448 10.4943 4.20002 10.3954 3.85256 10.6209C3.50509 10.8463 3.40621 11.3108 3.63169 11.6583C4.47442 12.9569 6.08493 14.6838 8.75008 14.9616V15.75C8.75008 16.1642 9.08587 16.5 9.50008 16.5C9.9143 16.5 10.2501 16.1642 10.2501 15.75V14.9616C12.9152 14.6838 14.5257 12.9569 15.3685 11.6583C15.594 11.3108 15.4951 10.8463 15.1476 10.6209C14.8001 10.3954 14.3357 10.4943 14.1102 10.8417C13.3305 12.0432 11.9002 13.5 9.50008 13.5C7.1 13.5 5.66968 12.0432 4.88997 10.8417Z"})]})}function ly(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M13.25 8.25C13.25 8.64791 13.188 9.03135 13.0732 9.39119L6.57947 2.8975C7.26687 2.04521 8.31974 1.5 9.49995 1.5C11.571 1.5 13.25 3.17893 13.25 5.25V8.25Z"}),m("path",{d:"M2.21967 1.71967C2.51256 1.42678 2.98744 1.42678 3.28033 1.71967L16.7803 15.2197C17.0732 15.5126 17.0732 15.9874 16.7803 16.2803C16.4874 16.5732 16.0126 16.5732 15.7197 16.2803L13.2828 13.8435C12.4719 14.4022 11.4678 14.8338 10.25 14.9614V15.75C10.25 16.1642 9.91422 16.5 9.50001 16.5C9.08579 16.5 8.75001 16.1642 8.75001 15.75V14.9616C6.08485 14.6838 4.47434 12.9569 3.63162 11.6583C3.40614 11.3108 3.50502 10.8463 3.85248 10.6209C4.19995 10.3954 4.66441 10.4943 4.88989 10.8417C5.6696 12.0432 7.09993 13.5 9.50001 13.5C10.5978 13.5 11.4845 13.1981 12.1992 12.7598L11.0875 11.6482C10.605 11.8739 10.0667 12 9.50001 12C7.42894 12 5.75001 10.3211 5.75001 8.25V6.31067L2.21967 2.78033C1.92678 2.48744 1.92678 2.01256 2.21967 1.71967Z"})]})}function dy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"m6 9 6 6 6-6"})})}function uy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"m18 15-6-6-6 6"})})}function hy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"M20 6 9 17l-5-5"})})}function fy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 20 20",fill:"currentColor",...t,children:m("path",{d:"M2.59413 5.1485C2.04 3.39377 3.86657 1.83482 5.51245 2.65776L16.47 8.13653C18.0055 8.90429 18.0055 11.0955 16.47 11.8633L5.51245 17.3421C3.86656 18.165 2.04 16.6061 2.59413 14.8513L3.86297 10.8333H7.50006C7.9603 10.8333 8.33339 10.4602 8.33339 10C8.33339 9.53976 7.9603 9.16667 7.50006 9.16667H3.86302L2.59413 5.1485Z"})})}function py(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 21 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{d:"M11.8621 0.854898C11.3145 -0.284967 9.68804 -0.284965 9.1404 0.854899L6.77181 5.78487C6.77181 5.78487 6.76902 5.78867 6.7646 5.78925L1.31499 6.50272C0.0591912 6.66713 -0.452868 8.21568 0.474832 9.09033L4.45896 12.8466C4.46075 12.8483 4.46059 12.8502 4.46059 12.8502L3.46003 18.2169C3.22657 19.4691 4.55184 20.4152 5.66108 19.8172L10.4957 17.2111C10.4991 17.2093 10.5035 17.2093 10.5068 17.2111L15.3415 19.8172C16.4507 20.4152 17.776 19.4691 17.5425 18.2169L16.542 12.8502C16.542 12.8502 16.5418 12.8483 16.5436 12.8466L20.5277 9.09033C21.4554 8.21568 20.9434 6.66713 19.6876 6.50272L14.2379 5.78925C14.2335 5.78867 14.2307 5.78487 14.2307 5.78487L11.8621 0.854898Z"})})}function my({orbColor:t,circleBackgroundColor:e,starColor:n,className:i}){return m("slot",{name:"icon-feedback",className:ae("flex",i),"aria-hidden":!0,children:m("svg",{width:"100%",height:"100%",viewBox:"0 0 82 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[m("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M9 42C9 59.6731 23.3269 74 41 74C58.6731 74 73 59.6731 73 42C73 24.3269 58.6731 10 41 10C23.3269 10 9 24.3269 9 42ZM29.4529 18.5973C31.1347 18.0574 32.8641 17.5023 34.9844 16.6005C42.2533 13.5091 48.3526 11.9217 51.7782 14.094C53.5063 15.1899 54.4051 16.7749 55.6117 18.9024C56.7969 20.9922 58.279 23.6057 61.1358 26.7937C62.2737 28.0636 63.3886 29.2195 64.4371 30.3064C68.7007 34.7263 71.8645 38.0061 70.9949 43.1697C70.2965 47.316 67.9794 49.4559 65.6038 51.65C63.4317 53.656 61.2107 55.7073 60.1332 59.3786C57.8774 67.0653 53.5327 71.9113 48.3526 72.7468C43.1725 73.5823 36.6555 75.1698 29.8043 70.1567C26.1949 67.5157 25.229 64.3182 24.1947 60.894C23.2657 57.8184 22.2814 54.56 19.2768 51.3577C14.1619 45.9062 10.2533 29.6345 19.2768 23.0339C23.736 20.4327 26.5223 19.5382 29.4529 18.5973Z",fill:t,"fill-opacity":"0.15",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M43.5 73.4212C40.4387 73.4212 35.0039 71.1025 37.556 56.4696C40.143 41.6365 42.6582 40.577 44.6991 25.744C46.3318 13.8775 41.1635 8.87964 33 10.9988",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M43.5 73.4212C40.4387 73.4212 35.0039 71.1025 37.556 56.4696C40.143 41.6365 42.6582 40.577 44.6991 25.744C46.3318 13.8775 41.1635 8.87964 33 10.9988",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M21.9366 68.1987C21.3549 66.5119 21.0386 60.9231 28.1376 53.3448C37.0114 43.8719 40.5 43.9579 51.4911 31.7482C59.5691 22.7747 59.1723 17.0524 58.0993 15.4626",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M9.26819 42.161C10.4003 43.5337 15.6951 46.3853 25.7661 44.3926C38.3548 41.9018 52.434 40.307 57.694 41.0287C70.352 42.7655 71.4138 51.3035 71.4138 51.3035",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M22 16.4916C18.815 21.85 19.6451 26.0591 27.9943 32.0828C38.4307 39.6124 50.2985 48.8304 53.5024 53.1027C58.6684 59.9914 59.5 67.928 59.5 67.928",stroke:t,"stroke-opacity":"0.35"}),m("rect",{x:"9.26099",y:"10",width:"63.7129",height:"63.7129",rx:"31.8565",stroke:t,"stroke-opacity":"0.43","stroke-width":"1.5"}),m("g",{"clip-path":"url(#clip0_7006_42127)",children:[m("circle",{cx:"62.4996",cy:"18.2032",r:"15.0195",transform:"rotate(6.27205 62.4996 18.2032)",fill:e}),m("path",{d:"M60.7142 12.1753C62.057 10.0714 65.2294 10.4202 66.0833 12.7654L66.6158 14.2308L68.1251 14.6217C70.5415 15.2484 71.1908 18.3742 69.2237 19.911L67.9944 20.8704L68.0896 22.4262C68.2403 24.9178 65.4681 26.5011 63.3987 25.1056L62.1065 24.2326L60.6555 24.8041C58.3322 25.7172 55.9702 23.5694 56.6585 21.1698L57.0884 19.6717L56.0977 18.4684C54.5112 16.541 55.8231 13.6307 58.318 13.5438L59.8751 13.4899L60.7142 12.1753Z",fill:n,stroke:e,"stroke-width":"3.27381"}),m("path",{d:"M63.925 5.23719C71.0867 6.02431 76.2545 12.4676 75.4676 19.6293C74.6805 26.7911 68.2364 31.959 61.0746 31.1718C53.9129 30.3845 48.7459 23.9406 49.533 16.7789C50.3203 9.61739 56.7634 4.45029 63.925 5.23719ZM63.6957 7.32326C57.6866 6.66302 52.2797 10.9991 51.6191 17.0082C50.9586 23.0174 55.2946 28.4251 61.3038 29.0858C67.3132 29.7462 72.7211 25.4094 73.3816 19.4C74.0418 13.3908 69.705 7.98372 63.6957 7.32326Z",fill:n,stroke:e,"stroke-width":"0.3","stroke-linecap":"round","stroke-linejoin":"round"})]}),m("ellipse",{cx:"41",cy:"85",rx:"15",ry:"3",fill:t,"fill-opacity":"0.35"}),m("defs",{children:m("clipPath",{id:"clip0_7006_42127",children:m("rect",{width:"33",height:"33",fill:"white",transform:"translate(47.9012) rotate(6.27205)"})})})]})})}function Zt(t){const e=Vh().value?gy:vy;return m(e,{...t})}function gy({visible:t,className:e,grow:n,dep:i,...r}){return t?m("div",{className:ae(n&&"grow",e),...r}):null}function vy({visible:t,children:e,className:n,grow:i,dep:r,...s}){const[o,a]=q(t),[c,l]=q(null),[d,u]=q(null),h=B(e);t&&(h.current=e);const f=V(v=>{l(v),v&&!t&&(v.style.width="0px",v.style.height="0px")},[]);K(()=>{d&&(d.style.transition="none",d.style.opacity="0",d.offsetWidth,d.style.transition="",d.style.opacity="")},[r]),oe(()=>{c&&(c.style.width=`${c.offsetWidth}px`,c.style.height=`${c.offsetHeight}px`)},[c,t,r]),K(()=>{if(!c||!d)return;t&&a(!0);const v=t?d.offsetWidth:0,b=t?d.offsetHeight:0;c.style.width=!t||c.offsetWidth!==v?`${v}px`:"",c.style.height=!t||c.offsetHeight!==b?`${b}px`:""},[c,d,t,r]);const{transitioning:g,handlers:p}=qh({onEnd:()=>{t?(c.style.width="",c.style.height=""):a(!1)}});return m("div",{ref:f,className:ae("relative inline-flex shrink-0 justify-center items-center transition-[opacity,width,height,transform,flex-grow] duration-200 min-w-0",!t&&"opacity-0 scale-75",t&&i&&"grow",t&&o&&!g.value&&"z-1"),...p,children:m("div",{ref:u,className:ae("shrink-0 min-h-min min-w-min transition-opacity duration-200",i&&"grow",n),...s,children:(t||o)&&h.current})})}const by={primary:"text-accent-primary border border-accent bg-accent hover:border-accent-hover hover:bg-accent-hover active:border-accent-active active:bg-accent-active",secondary:"text-base-primary border border-base-border bg-base hover:bg-base-hover active:bg-base-active",ghost:"text-base-primary border border-base bg-base hover:bg-base-hover hover:border-base-hover active:bg-base-active active:border-base-active"},pt=Q(function({variant:t="secondary",children:e,icon:n,className:i,iconClassName:r,truncate:s=!0,...o},a){const c=!!n&&!e;return m("button",{ref:a,className:ae("h-9 flex px-2.5 text-sm items-center transition-colors justify-center rounded-button duration-200 focus-ring overflow-hidden select-none",by[t],c&&"min-w-9",i),type:"button",...o,children:[n&&m(It,{className:ae("transition-[margin] duration-200",c&&"-mx-0.5",r),name:n}),m(Zt,{visible:!!e,dep:e,children:m("span",{className:"block whitespace-nowrap max-w-64 truncate px-1.5",children:e})})]})});function va({className:t,...e}){const{status:n,isSpeaking:i}=Be(),r=Wr(),s=Ee(),o=ue(()=>n.value!=="connected"?s.connecting_status.value:r.value?s.chatting_status.value:i.value?s.speaking_status.value:s.listening_status.value),[a,c]=q(o.peek());return Ct(()=>{const l=o.value;if(n.value==="connected"&&i.value)c(l);else{const d=setTimeout(()=>{c(l)},500);return()=>clearTimeout(d)}}),m("div",{className:ae("py-1.5 px-3 bg-base-active overflow-hidden rounded-bubble text-sm",t),...e,children:m(je,{initial:!1,active:!0,children:m("div",{className:"animate-text whitespace-nowrap transition-[opacity,transform] ease-out duration-200 data-hidden:opacity-0 transform data-hidden:translate-y-2",children:a})},a)})}const Wh=Ie(null);function yy({children:t}){const e=Oe(null),n=Oe(""),i=Oe("initial"),{lastId:r}=Be(),s=ie("agent-id"),{serverUrl:o}=ua(),a=V(async u=>{const h=r.value,f=s.value;if(!h||!f){console.warn("[ConversationalAI] Cannot submit rating: missing agent_id or conversation_id");return}try{e.value=u,i.value="submitted-rating",await gh(h,{rating:u},o.value)}catch(g){console.error("[ConversationalAI] Failed to submit rating:",g)}},[]),c=V(async()=>{const u=r.value,h=s.value;if(!u||!h){console.warn("[ConversationalAI] Cannot submit feedback: missing agent_id or conversation_id");return}if(e.value===null){console.warn("[ConversationalAI] Cannot submit feedback: rating not set");return}if(n.value)try{i.value="submitted-follow-up",await gh(u,{rating:e.value,comment:n.value||void 0},o.value)}catch(f){console.error("[ConversationalAI] Failed to submit feedback:",f)}},[]),l=V(()=>{e.value=null,n.value="",i.value="initial"},[]);Ct(()=>{r.value!==null&&l()});const d=oe(()=>({rating:e,feedbackText:n,feedbackProgress:i,submitRating:a,submitFeedback:c,reset:l}),[a,c,l]);return m(Wh.Provider,{value:d,children:t})}function ba(){return et(Wh)}const Hh=Ie(null);function ky({defaultContent:t="transcript",children:e}){const n=Oe(t),i=oe(()=>{const r=n.value==="feedback"?{showHeaderBack:!0,onHeaderBack:()=>{n.value="transcript"}}:{showHeaderBack:!1};return{currentContent:n,currentConfig:r}},[n.value]);return m(Hh.Provider,{value:i,children:e})}function ya(){return et(Hh)}const Gh=(t,e)=>Array.from({length:e-t+1},(n,i)=>i+t),Cy=({isFilled:t,iconName:e})=>m("span",{className:ae("w-8 h-8 grid place-content-center",t?"text-base-primary":"text-base-border"),children:m(It,{name:e,size:"lg"})}),wy=({value:t,rating:e,hoverRating:n,onClick:i,onHover:r,onKeyDown:s,iconName:o})=>{const a=e.value!==null&&t<=e.value,c=n.value!==null&&t<=n.value,l=V(u=>{u.stopPropagation(),i(t)},[i,t]),d=V(u=>{s(u,t)},[s,t]);return m("button",{type:"button",role:"radio","aria-checked":a,"aria-label":t.toString(),onMouseEnter:()=>r(t),onClick:l,onKeyDown:d,className:ae("w-8 h-8 grid place-content-center rounded-full focus-ring transition-colors cursor-pointer",a||c?"text-base-primary":"text-base-border"),children:m(It,{name:o,size:"lg"})})},_y=({onRate:t,min:e=1,max:n=5,ariaLabel:i,icon:r="star"})=>{const s=Oe(null),o=Oe(null),a=Gh(e,n),c=V(h=>{o.value=h},[o]),l=V(()=>{o.value=null},[o]),d=V(h=>{s.value=h,t(h)},[s,t]),u=V((h,f)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),s.value=f,t(f);else if(h.key==="ArrowLeft"||h.key==="ArrowDown"){if(h.preventDefault(),f-1>=e){const g=h.currentTarget,p=g==null?void 0:g.previousElementSibling;p==null||p.focus()}}else if((h.key==="ArrowRight"||h.key==="ArrowUp")&&(h.preventDefault(),f+1<=n)){const g=h.currentTarget,p=g==null?void 0:g.nextElementSibling;p==null||p.focus()}},[s,t,e,n]);return m("div",{role:"radiogroup","aria-label":i,className:"flex no-wrap cursor-pointer",onMouseLeave:l,children:a.map(h=>m(wy,{value:h,rating:s,hoverRating:o,onClick:d,onHover:c,onKeyDown:u,iconName:r},h))})};function Kh({rating:t,min:e=1,max:n=5,icon:i="star"}){const r=Gh(e,n);return m("div",{className:"flex no-wrap",role:"img","aria-label":`Rating: ${t} out of ${n}`,children:r.map(s=>m(Cy,{isFilled:t>=s,iconName:i},s))})}function Sy({icon:t,onRate:e}){const n=Ee();return m("div",{className:"flex flex-col items-center",children:[m("div",{className:"text-sm text-base-primary font-medium",children:n.initiate_feedback}),m("div",{className:"py-4",children:m(_y,{onRate:e,ariaLabel:n.initiate_feedback,icon:t})})]})}function Ty({icon:t,rating:e,showFollowUpButton:n,onFollowUpClick:i}){const r=Ee();return m("div",{className:"flex flex-col items-center gap-3 mb-4",children:[m("div",{className:"text-sm text-base-primary font-medium",children:r.thanks_for_feedback}),m(Kh,{rating:e,min:1,max:5,icon:t}),n&&m(pt,{variant:"secondary",onClick:i,children:r.request_follow_up_feedback})]})}function xy({icon:t="star"}){const{currentContent:e}=ya(),{rating:n,feedbackProgress:i,submitRating:r}=ba(),s=i.value!=="initial"&&n.value!==null,o=V(c=>{r(c),e.value="feedback"},[r]),a=V(()=>{e.value="feedback"},[]);return s?m(Ty,{icon:t,rating:n.value??0,showFollowUpButton:i.value!=="submitted-follow-up",onFollowUpClick:a}):m(Sy,{icon:t,onRate:o})}function Ey({entry:t}){const{previewUrl:e}=pa();return m("div",{className:ae("flex gap-2.5 transition-[opacity,transform] duration-200 data-hidden:opacity-0 data-hidden:scale-75",t.role==="user"?"justify-end pl-16 origin-top-right":"pr-16 origin-top-left"),children:[t.role==="ai"&&m("img",{src:e,alt:"AI agent avatar",className:"bg-base-border shrink-0 w-5 h-5 rounded-full"}),m("div",{dir:"auto",className:ae("px-3 py-2.5 rounded-bubble text-sm min-w-0 [overflow-wrap:break-word]",t.role==="user"?"bg-accent text-accent-primary":"bg-base-active text-base-primary"),children:t.message})]})}function Py({entry:t}){const e=Ee(),{lastId:n}=Be(),i=Ab();return m("div",{className:"mt-3 px-8 flex flex-col",children:[i&&m(xy,{}),m("div",{className:"text-xs text-base-subtle text-center transition-opacity duration-200 data-hidden:opacity-0",children:[t.role==="user"?e.user_ended_conversation:e.agent_ended_conversation,m("br",{}),n.value&&m("span",{className:"break-all",children:[e.conversation_id,": ",n.value]})]})]})}function Ry({entry:t}){const e=Ee(),{lastId:n}=Be();return m("div",{className:"mt-2 px-8 text-xs text-base-error text-center transition-opacity duration-200 data-hidden:opacity-0",children:[e.error_occurred,m("br",{}),t.message,n.value&&m(ge,{children:[m("br",{}),m("span",{className:"text-base-subtle break-all",children:[e.conversation_id,": ",n.value]})]})]})}function Iy({entry:t,animateIn:e}){return m(je,{initial:!e,active:!0,children:t.type==="message"?m(Ey,{entry:t}):t.type==="disconnection"?m(Py,{entry:t}):m(Ry,{entry:t})})}const Oy=16;function Dy({scrollPinned:t,transcript:e}){const n=B(null),i=B(0),r=B(null),s=B(!1),o=B(!1),a=u=>{var h;(h=n.current)==null||h.scrollTo({top:n.current.scrollHeight,behavior:u?"smooth":"instant"})},c=()=>{const u=n.current;if(!u||!s.current||o.current)return;const h=u.scrollTop,f=u.scrollHeight-u.clientHeight,g=f-h;if(Math.abs(g)<1){u.scrollTop=f,r.current=requestAnimationFrame(c);return}const p=g*.2,v=2;u.scrollTop=h+Math.max(p,v),r.current=requestAnimationFrame(c)},l=()=>{!n.current||o.current||s.current||(s.current=!0,r.current=requestAnimationFrame(c))},d=B(!0);return K(()=>(d.current=!1,a(!1),()=>{r.current&&cancelAnimationFrame(r.current)}),[]),Ct(()=>{var u;const h=e.value;if(!t.peek())return;const f=h[h.length-1];if((f==null?void 0:f.type)==="message"&&(f==null?void 0:f.role)==="ai"&&(f==null?void 0:f.isText)===!0){const g=((u=f.message)==null?void 0:u.length)||0;i.current===0&&g>0?(i.current=g,o.current=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{!o.current&&t.peek()&&(a(!1),l())})})):g>i.current&&(i.current=g,l())}else i.current=0,s.current=!1,o.current=!1,r.current&&(cancelAnimationFrame(r.current),r.current=null),a(!0)}),m("div",{ref:n,onScroll:u=>{const h=u.currentTarget.scrollTop>=u.currentTarget.scrollHeight-u.currentTarget.clientHeight-Oy;t.value=h,!h&&s.current&&(o.current=!0,s.current=!1,r.current&&(cancelAnimationFrame(r.current),r.current=null))},className:"px-4 pt-3 pb-3 grow flex flex-col gap-3 overflow-x-hidden overflow-y-auto",children:e.value.map((u,h)=>m(Iy,{entry:u,animateIn:!d.current},`${h}-${u.conversationIndex}`))})}function Jh({className:t,...e}){return m("textarea",{className:ae("px-3 py-[calc(theme(spacing.2)-1px)] border text-sm text-base-primary bg-base border-base-border rounded-input focus-ring resize-none [field-sizing:content] placeholder:text-base-subtle",t),...e})}function ka({visible:t,...e}){const n=Ee(),{isMuted:i,isMutingEnabled:r,setIsMuted:s}=Ph(),o=V(()=>{s(!i.peek())},[s]);return r.value?m(Zt,{visible:t,className:"p-1",children:m(pt,{"aria-label":n.mute_microphone,"aria-pressed":i,icon:i.value?"mic-off":"mic",onClick:o,...e})}):null}function Ca({iconOnly:t,isDisconnected:e,children:n,...i}){const{endSession:r,startSession:s}=Be(),o=Ee();return m(pt,{variant:e?"primary":"secondary",icon:e?"phone":"phone-off",onClick:e?a=>s(a.currentTarget):r,"aria-label":e?o.start_call:o.end_call,...i,children:t?void 0:n??(e?o.start_call:o.end_call)})}function Ay({showTranscript:t,scrollPinned:e}){const n=Oe(""),i=Wr(),{text_input_enabled:r}=Ae().value,s=Ee(),{isDisconnected:o,status:a,startSession:c,sendUserMessage:l,sendUserActivity:d,conversationIndex:u}=Be(),h=V(async v=>{v.preventDefault();const b=n.value.trim();b&&(e.value=!0,n.value="",o.value?await c(v.currentTarget,b):l(b))},[n,e,o,c,l]),f=V(async v=>{v.key==="Enter"&&!v.shiftKey&&await h(v)},[h]),g=V(v=>{n.value=v.currentTarget.value},[n]),p=ue(()=>!!n.value.trim());return m("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:[r&&m("div",{className:"relative grow min-w-0 flex z-1 m-1",children:[m(Jh,{rows:1,"aria-label":s.input_label,value:n,onInput:d,onChange:g,onKeyDown:f,className:"min-w-0 w-full max-h-[8lh] pr-9",placeholder:i.value?o.value&&u.value>0?s.input_placeholder_new_conversation:s.input_placeholder_text_only:s.input_placeholder}),m(je,{active:p,children:m("button",{"aria-label":s.send_message,className:"absolute right-1 bottom-1 w-7 h-7 flex items-center justify-center hover:bg-base-hover active:bg-base-active rounded-button focus-ring transition-[transform,opacity] duration-200 data-hidden:opacity-0 data-hidden:scale-90",onClick:h,children:m(It,{name:"send"})})})]}),m("div",{className:"flex h-11 items-center",children:[m(ka,{visible:!i.value&&!o.value}),m(Zt,{visible:!o.value||t,className:"p-1",children:m(Ca,{iconOnly:!o.value,isDisconnected:o.value,disabled:a.value==="disconnecting"||a.value==="connecting",children:s.new_call})})]})]})}function My(){const t=Ee(),{rating:e,feedbackText:n}=ba(),i=V(r=>{n.value=r.currentTarget.value},[]);return m("div",{className:"grow flex flex-col overflow-y-auto overflow-x-hidden px-4",children:m("div",{className:"flex flex-col gap-8 min-h-full pt-4 pb-2",children:[m("div",{className:"flex flex-col items-center justify-center gap-3",children:[m(my,{orbColor:"var(--el-base-subtle)",circleBackgroundColor:"var(--el-base)",starColor:"var(--el-base-primary)",className:"w-20 h-22"}),e.value!==null&&m(Kh,{rating:e.value,min:1,max:5}),m("div",{className:"text-center",children:[m("p",{className:"text-sm text-base-primary font-medium",children:t.thanks_for_feedback}),m("p",{className:"text-sm text-base-subtle",children:t.thanks_for_feedback_details})]})]}),m(Jh,{className:"w-full min-h-[6lh]",placeholder:t.follow_up_feedback_placeholder,rows:6,value:n,onInput:i})]})})}function Ny(){const t=Ee(),{currentContent:e}=ya(),{submitFeedback:n}=ba(),i=V(()=>{n(),e.value="transcript"},[n]);return m("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:m(pt,{variant:"primary",onClick:i,children:t.submit})})}function Yh(t,[e,n]){return Math.min(n,Math.max(e,t))}function Pe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t==null||t(i),n===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function wa(t,e=[]){let n=[];function i(s,o){const a=Ie(o),c=n.length;n=[...n,o];const l=u=>{var h;const{scope:f,children:g,...p}=u,v=((h=f==null?void 0:f[t])==null?void 0:h[c])||a,b=oe(()=>p,Object.values(p));return m(v.Provider,{value:b,children:g})};l.displayName=s+"Provider";function d(u,h){var f;const g=((f=h==null?void 0:h[t])==null?void 0:f[c])||a,p=sn(g);if(p)return p;if(o!==void 0)return o;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[l,d]}const r=()=>{const s=n.map(o=>Ie(o));return function(o){const a=(o==null?void 0:o[t])||s;return oe(()=>({[`__scope${t}`]:{...o,[t]:a}}),[o,a])}};return r.scopeName=t,[i,Ly(r,...e)]}function Ly(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const i=t.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(r){const s=i.reduce((o,{useScope:a,scopeName:c})=>{const l=a(r)[`__scope${c}`];return{...o,...l}},{});return oe(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}function Uy(t){const e=t+"CollectionProvider",[n,i]=wa(e),[r,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=p=>{const{scope:v,children:b}=p,k=Vt.useRef(null),w=Vt.useRef(new Map).current;return m(r,{scope:v,itemMap:w,collectionRef:k,children:b})};o.displayName=e;const a=t+"CollectionSlot",c=Vi(a),l=Vt.forwardRef((p,v)=>{const{scope:b,children:k}=p,w=s(a,b),y=Fe(v,w.collectionRef);return m(c,{ref:y,children:k})});l.displayName=a;const d=t+"CollectionItemSlot",u="data-radix-collection-item",h=Vi(d),f=Vt.forwardRef((p,v)=>{const{scope:b,children:k,...w}=p,y=Vt.useRef(null),_=Fe(v,y),S=s(d,b);return Vt.useEffect(()=>(S.itemMap.set(y,{ref:y,...w}),()=>void S.itemMap.delete(y))),m(h,{[u]:"",ref:_,children:k})});f.displayName=d;function g(p){const v=s(t+"CollectionConsumer",p);return Vt.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const k=Array.from(b.querySelectorAll(`[${u}]`));return Array.from(v.itemMap.values()).sort((w,y)=>k.indexOf(w.ref.current)-k.indexOf(y.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:o,Slot:l,ItemSlot:f},g,i]}var Fy=Ie(void 0);function By(t){const e=sn(Fy);return t||e||"ltr"}var jy=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Se=jy.reduce((t,e)=>{const n=Vi(`Primitive.${e}`),i=Q((r,s)=>{const{asChild:o,...a}=r,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m(c,{...a,ref:s})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{});function Vy(t,e){t&&ir(()=>t.dispatchEvent(e))}function Mn(t){const e=B(t);return K(()=>{e.current=t}),oe(()=>(...n)=>{var i;return(i=e.current)==null?void 0:i.call(e,...n)},[])}function qy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t);K(()=>{const i=r=>{r.key==="Escape"&&n(r)};return e.addEventListener("keydown",i,{capture:!0}),()=>e.removeEventListener("keydown",i,{capture:!0})},[n,e])}var $y="DismissableLayer",_a="dismissableLayer.update",zy="dismissableLayer.pointerDownOutside",Wy="dismissableLayer.focusOutside",Xh,Qh=Ie({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Zh=Q((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...c}=t,l=sn(Qh),[d,u]=q(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=q({}),g=Fe(e,x=>u(x)),p=Array.from(l.layers),[v]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=p.indexOf(v),k=d?p.indexOf(d):-1,w=l.layersWithOutsidePointerEventsDisabled.size>0,y=k>=b,_=Ky(x=>{const I=x.target,R=[...l.branches].some(D=>D.contains(I));!y||R||(r==null||r(x),o==null||o(x),x.defaultPrevented||a==null||a())},h),S=Jy(x=>{const I=x.target;[...l.branches].some(R=>R.contains(I))||(s==null||s(x),o==null||o(x),x.defaultPrevented||a==null||a())},h);return qy(x=>{k===l.layers.size-1&&(i==null||i(x),!x.defaultPrevented&&a&&(x.preventDefault(),a()))},h),K(()=>{if(d)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(Xh=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(d)),l.layers.add(d),ef(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=Xh)}},[d,h,n,l]),K(()=>()=>{d&&(l.layers.delete(d),l.layersWithOutsidePointerEventsDisabled.delete(d),ef())},[d,l]),K(()=>{const x=()=>f({});return document.addEventListener(_a,x),()=>document.removeEventListener(_a,x)},[]),m(Se.div,{...c,ref:g,style:{pointerEvents:w?y?"auto":"none":void 0,...t.style},onFocusCapture:Pe(t.onFocusCapture,S.onFocusCapture),onBlurCapture:Pe(t.onBlurCapture,S.onBlurCapture),onPointerDownCapture:Pe(t.onPointerDownCapture,_.onPointerDownCapture)})});Zh.displayName=$y;var Hy="DismissableLayerBranch",Gy=Q((t,e)=>{const n=sn(Qh),i=B(null),r=Fe(e,i);return K(()=>{const s=i.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),m(Se.div,{...t,ref:r})});Gy.displayName=Hy;function Ky(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1),r=B(()=>{});return K(()=>{const s=a=>{if(a.target&&!i.current){let c=function(){tf(zy,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",r.current),r.current=c,e.addEventListener("click",r.current,{once:!0})):c()}else e.removeEventListener("click",r.current);i.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",s),e.removeEventListener("click",r.current)}},[e,n]),{onPointerDownCapture:()=>i.current=!0}}function Jy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1);return K(()=>{const r=s=>{s.target&&!i.current&&tf(Wy,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function ef(){const t=new CustomEvent(_a);document.dispatchEvent(t)}function tf(t,e,n,{discrete:i}){const r=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&r.addEventListener(t,e,{once:!0}),i?Vy(r,s):r.dispatchEvent(s)}var Sa=0;function Yy(){K(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??nf()),document.body.insertAdjacentElement("beforeend",t[1]??nf()),Sa++,()=>{Sa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Sa--}},[])}function nf(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Ta="focusScope.autoFocusOnMount",xa="focusScope.autoFocusOnUnmount",rf={bubbles:!1,cancelable:!0},Xy="FocusScope",sf=Q((t,e)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:s,...o}=t,[a,c]=q(null),l=Mn(r),d=Mn(s),u=B(null),h=Fe(e,p=>c(p)),f=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;K(()=>{if(i){let p=function(w){if(f.paused||!a)return;const y=w.target;a.contains(y)?u.current=y:bn(u.current,{select:!0})},v=function(w){if(f.paused||!a)return;const y=w.relatedTarget;y!==null&&(a.contains(y)||bn(u.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const y of w)y.removedNodes.length>0&&bn(a)};document.addEventListener("focusin",p),document.addEventListener("focusout",v);const k=new MutationObserver(b);return a&&k.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",v),k.disconnect()}}},[i,a,f.paused]),K(()=>{if(a){cf.add(f);const p=document.activeElement;if(!a.contains(p)){const v=new CustomEvent(Ta,rf);a.addEventListener(Ta,l),a.dispatchEvent(v),v.defaultPrevented||(Qy(ik(of(a)),{select:!0}),document.activeElement===p&&bn(a))}return()=>{a.removeEventListener(Ta,l),setTimeout(()=>{const v=new CustomEvent(xa,rf);a.addEventListener(xa,d),a.dispatchEvent(v),v.defaultPrevented||bn(p??document.body,{select:!0}),a.removeEventListener(xa,d),cf.remove(f)},0)}}},[a,l,d,f]);const g=V(p=>{if(!n&&!i||f.paused)return;const v=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(v&&b){const k=p.currentTarget,[w,y]=Zy(k);w&&y?!p.shiftKey&&b===y?(p.preventDefault(),n&&bn(w,{select:!0})):p.shiftKey&&b===w&&(p.preventDefault(),n&&bn(y,{select:!0})):b===k&&p.preventDefault()}},[n,i,f.paused]);return m(Se.div,{tabIndex:-1,...o,ref:h,onKeyDown:g})});sf.displayName=Xy;function Qy(t,{select:e=!1}={}){const n=document.activeElement;for(const i of t)if(bn(i,{select:e}),document.activeElement!==n)return}function Zy(t){const e=of(t),n=af(e,t),i=af(e.reverse(),t);return[n,i]}function of(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const r=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||r?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function af(t,e){for(const n of t)if(!ek(n,{upTo:e}))return n}function ek(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function tk(t){return t instanceof HTMLInputElement&&"select"in t}function bn(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&tk(t)&&e&&t.select()}}var cf=nk();function nk(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=lf(t,e),t.unshift(e)},remove(e){var n;t=lf(t,e),(n=t[0])==null||n.resume()}}}function lf(t,e){const n=[...t],i=n.indexOf(e);return i!==-1&&n.splice(i,1),n}function ik(t){return t.filter(e=>e.tagName!=="A")}var Ke=globalThis!=null&&globalThis.document?Bt:()=>{},rk=tl[" useId ".trim().toString()]||(()=>{}),sk=0;function Ea(t){const[e,n]=q(rk());return Ke(()=>{n(i=>i??String(sk++))},[t]),e?`radix-${e}`:""}const ok=["top","right","bottom","left"],yn=Math.min,tt=Math.max,Gr=Math.round,Kr=Math.floor,Ot=t=>({x:t,y:t}),ak={left:"right",right:"left",bottom:"top",top:"bottom"},ck={start:"end",end:"start"};function Pa(t,e,n){return tt(t,yn(e,n))}function en(t,e){return typeof t=="function"?t(e):t}function tn(t){return t.split("-")[0]}function oi(t){return t.split("-")[1]}function Ra(t){return t==="x"?"y":"x"}function Ia(t){return t==="y"?"height":"width"}const lk=new Set(["top","bottom"]);function Dt(t){return lk.has(tn(t))?"y":"x"}function Oa(t){return Ra(Dt(t))}function dk(t,e,n){n===void 0&&(n=!1);const i=oi(t),r=Oa(t),s=Ia(r);let o=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=Jr(o)),[o,Jr(o)]}function uk(t){const e=Jr(t);return[Da(t),e,Da(e)]}function Da(t){return t.replace(/start|end/g,e=>ck[e])}const df=["left","right"],uf=["right","left"],hk=["top","bottom"],fk=["bottom","top"];function pk(t,e,n){switch(t){case"top":case"bottom":return n?e?uf:df:e?df:uf;case"left":case"right":return e?hk:fk;default:return[]}}function mk(t,e,n,i){const r=oi(t);let s=pk(tn(t),n==="start",i);return r&&(s=s.map(o=>o+"-"+r),e&&(s=s.concat(s.map(Da)))),s}function Jr(t){return t.replace(/left|right|bottom|top/g,e=>ak[e])}function gk(t){return{top:0,right:0,bottom:0,left:0,...t}}function hf(t){return typeof t!="number"?gk(t):{top:t,right:t,bottom:t,left:t}}function Yr(t){const{x:e,y:n,width:i,height:r}=t;return{width:i,height:r,top:n,left:e,right:e+i,bottom:n+r,x:e,y:n}}function ff(t,e,n){let{reference:i,floating:r}=t;const s=Dt(e),o=Oa(e),a=Ia(o),c=tn(e),l=s==="y",d=i.x+i.width/2-r.width/2,u=i.y+i.height/2-r.height/2,h=i[a]/2-r[a]/2;let f;switch(c){case"top":f={x:d,y:i.y-r.height};break;case"bottom":f={x:d,y:i.y+i.height};break;case"right":f={x:i.x+i.width,y:u};break;case"left":f={x:i.x-r.width,y:u};break;default:f={x:i.x,y:i.y}}switch(oi(e)){case"start":f[o]-=h*(n&&l?-1:1);break;case"end":f[o]+=h*(n&&l?-1:1);break}return f}const vk=async(t,e,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:s=[],platform:o}=n,a=s.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:t,floating:e,strategy:r}),{x:d,y:u}=ff(l,i,c),h=i,f={},g=0;for(let p=0;p<a.length;p++){const{name:v,fn:b}=a[p],{x:k,y:w,data:y,reset:_}=await b({x:d,y:u,initialPlacement:i,placement:h,strategy:r,middlewareData:f,rects:l,platform:o,elements:{reference:t,floating:e}});d=k??d,u=w??u,f={...f,[v]:{...f[v],...y}},_&&g<=50&&(g++,typeof _=="object"&&(_.placement&&(h=_.placement),_.rects&&(l=_.rects===!0?await o.getElementRects({reference:t,floating:e,strategy:r}):_.rects),{x:d,y:u}=ff(l,h,c)),p=-1)}return{x:d,y:u,placement:h,strategy:r,middlewareData:f}};async function qi(t,e){var n;e===void 0&&(e={});const{x:i,y:r,platform:s,rects:o,elements:a,strategy:c}=t,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:f=0}=en(e,t),g=hf(f),p=a[h?u==="floating"?"reference":"floating":u],v=Yr(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(p)))==null||n?p:p.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),b=u==="floating"?{x:i,y:r,width:o.floating.width,height:o.floating.height}:o.reference,k=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),w=await(s.isElement==null?void 0:s.isElement(k))?await(s.getScale==null?void 0:s.getScale(k))||{x:1,y:1}:{x:1,y:1},y=Yr(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:k,strategy:c}):b);return{top:(v.top-y.top+g.top)/w.y,bottom:(y.bottom-v.bottom+g.bottom)/w.y,left:(v.left-y.left+g.left)/w.x,right:(y.right-v.right+g.right)/w.x}}const bk=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:i,placement:r,rects:s,platform:o,elements:a,middlewareData:c}=e,{element:l,padding:d=0}=en(t,e)||{};if(l==null)return{};const u=hf(d),h={x:n,y:i},f=Oa(r),g=Ia(f),p=await o.getDimensions(l),v=f==="y",b=v?"top":"left",k=v?"bottom":"right",w=v?"clientHeight":"clientWidth",y=s.reference[g]+s.reference[f]-h[f]-s.floating[g],_=h[f]-s.reference[f],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let x=S?S[w]:0;(!x||!await(o.isElement==null?void 0:o.isElement(S)))&&(x=a.floating[w]||s.floating[g]);const I=y/2-_/2,R=x/2-p[g]/2-1,D=yn(u[b],R),M=yn(u[k],R),U=D,j=x-p[g]-M,$=x/2-p[g]/2+I,F=Pa(U,$,j),G=!c.arrow&&oi(r)!=null&&$!==F&&s.reference[g]/2-($<U?D:M)-p[g]/2<0,Y=G?$<U?$-U:$-j:0;return{[f]:h[f]+Y,data:{[f]:F,centerOffset:$-F-Y,...G&&{alignmentOffset:Y}},reset:G}}}),yk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,i;const{placement:r,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:l}=e,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:p=!0,...v}=en(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const b=tn(r),k=Dt(a),w=tn(a)===a,y=await(c.isRTL==null?void 0:c.isRTL(l.floating)),_=h||(w||!p?[Jr(a)]:uk(a)),S=g!=="none";!h&&S&&_.push(...mk(a,p,g,y));const x=[a,..._],I=await qi(e,v),R=[];let D=((i=s.flip)==null?void 0:i.overflows)||[];if(d&&R.push(I[b]),u){const $=dk(r,o,y);R.push(I[$[0]],I[$[1]])}if(D=[...D,{placement:r,overflows:R}],!R.every($=>$<=0)){var M,U;const $=(((M=s.flip)==null?void 0:M.index)||0)+1,F=x[$];if(F&&(!(u==="alignment"&&k!==Dt(F))||D.every(Y=>Dt(Y.placement)===k?Y.overflows[0]>0:!0)))return{data:{index:$,overflows:D},reset:{placement:F}};let G=(U=D.filter(Y=>Y.overflows[0]<=0).sort((Y,W)=>Y.overflows[1]-W.overflows[1])[0])==null?void 0:U.placement;if(!G)switch(f){case"bestFit":{var j;const Y=(j=D.filter(W=>{if(S){const ee=Dt(W.placement);return ee===k||ee==="y"}return!0}).map(W=>[W.placement,W.overflows.filter(ee=>ee>0).reduce((ee,we)=>ee+we,0)]).sort((W,ee)=>W[1]-ee[1])[0])==null?void 0:j[0];Y&&(G=Y);break}case"initialPlacement":G=a;break}if(r!==G)return{reset:{placement:G}}}return{}}}};function pf(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function mf(t){return ok.some(e=>t[e]>=0)}const kk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:i="referenceHidden",...r}=en(t,e);switch(i){case"referenceHidden":{const s=await qi(e,{...r,elementContext:"reference"}),o=pf(s,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:mf(o)}}}case"escaped":{const s=await qi(e,{...r,altBoundary:!0}),o=pf(s,n.floating);return{data:{escapedOffsets:o,escaped:mf(o)}}}default:return{}}}}},gf=new Set(["left","top"]);async function Ck(t,e){const{placement:n,platform:i,elements:r}=t,s=await(i.isRTL==null?void 0:i.isRTL(r.floating)),o=tn(n),a=oi(n),c=Dt(n)==="y",l=gf.has(o)?-1:1,d=s&&c?-1:1,u=en(e,t);let{mainAxis:h,crossAxis:f,alignmentAxis:g}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&typeof g=="number"&&(f=a==="end"?g*-1:g),c?{x:f*d,y:h*l}:{x:h*l,y:f*d}}const wk=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:r,y:s,placement:o,middlewareData:a}=e,c=await Ck(e,t);return o===((n=a.offset)==null?void 0:n.placement)&&(i=a.arrow)!=null&&i.alignmentOffset?{}:{x:r+c.x,y:s+c.y,data:{...c,placement:o}}}}},_k=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:r}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:v=>{let{x:b,y:k}=v;return{x:b,y:k}}},...c}=en(t,e),l={x:n,y:i},d=await qi(e,c),u=Dt(tn(r)),h=Ra(u);let f=l[h],g=l[u];if(s){const v=h==="y"?"top":"left",b=h==="y"?"bottom":"right",k=f+d[v],w=f-d[b];f=Pa(k,f,w)}if(o){const v=u==="y"?"top":"left",b=u==="y"?"bottom":"right",k=g+d[v],w=g-d[b];g=Pa(k,g,w)}const p=a.fn({...e,[h]:f,[u]:g});return{...p,data:{x:p.x-n,y:p.y-i,enabled:{[h]:s,[u]:o}}}}}},Sk=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:r,rects:s,middlewareData:o}=e,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=en(t,e),d={x:n,y:i},u=Dt(r),h=Ra(u);let f=d[h],g=d[u];const p=en(a,e),v=typeof p=="number"?{mainAxis:p,crossAxis:0}:{mainAxis:0,crossAxis:0,...p};if(c){const w=h==="y"?"height":"width",y=s.reference[h]-s.floating[w]+v.mainAxis,_=s.reference[h]+s.reference[w]-v.mainAxis;f<y?f=y:f>_&&(f=_)}if(l){var b,k;const w=h==="y"?"width":"height",y=gf.has(tn(r)),_=s.reference[u]-s.floating[w]+(y&&((b=o.offset)==null?void 0:b[u])||0)+(y?0:v.crossAxis),S=s.reference[u]+s.reference[w]+(y?0:((k=o.offset)==null?void 0:k[u])||0)-(y?v.crossAxis:0);g<_?g=_:g>S&&(g=S)}return{[h]:f,[u]:g}}}},Tk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:r,rects:s,platform:o,elements:a}=e,{apply:c=()=>{},...l}=en(t,e),d=await qi(e,l),u=tn(r),h=oi(r),f=Dt(r)==="y",{width:g,height:p}=s.floating;let v,b;u==="top"||u==="bottom"?(v=u,b=h===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(b=u,v=h==="end"?"top":"bottom");const k=p-d.top-d.bottom,w=g-d.left-d.right,y=yn(p-d[v],k),_=yn(g-d[b],w),S=!e.middlewareData.shift;let x=y,I=_;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(I=w),(i=e.middlewareData.shift)!=null&&i.enabled.y&&(x=k),S&&!h){const D=tt(d.left,0),M=tt(d.right,0),U=tt(d.top,0),j=tt(d.bottom,0);f?I=g-2*(D!==0||M!==0?D+M:tt(d.left,d.right)):x=p-2*(U!==0||j!==0?U+j:tt(d.top,d.bottom))}await c({...e,availableWidth:I,availableHeight:x});const R=await o.getDimensions(a.floating);return g!==R.width||p!==R.height?{reset:{rects:!0}}:{}}}};function Xr(){return typeof window<"u"}function ai(t){return vf(t)?(t.nodeName||"").toLowerCase():"#document"}function nt(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function At(t){var e;return(e=(vf(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function vf(t){return Xr()?t instanceof Node||t instanceof nt(t).Node:!1}function mt(t){return Xr()?t instanceof Element||t instanceof nt(t).Element:!1}function Mt(t){return Xr()?t instanceof HTMLElement||t instanceof nt(t).HTMLElement:!1}function bf(t){return!Xr()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof nt(t).ShadowRoot}const xk=new Set(["inline","contents"]);function $i(t){const{overflow:e,overflowX:n,overflowY:i,display:r}=gt(t);return/auto|scroll|overlay|hidden|clip/.test(e+i+n)&&!xk.has(r)}const Ek=new Set(["table","td","th"]);function Pk(t){return Ek.has(ai(t))}const Rk=[":popover-open",":modal"];function Qr(t){return Rk.some(e=>{try{return t.matches(e)}catch{return!1}})}const Ik=["transform","translate","scale","rotate","perspective"],Ok=["transform","translate","scale","rotate","perspective","filter"],Dk=["paint","layout","strict","content"];function Aa(t){const e=Ma(),n=mt(t)?gt(t):t;return Ik.some(i=>n[i]?n[i]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||Ok.some(i=>(n.willChange||"").includes(i))||Dk.some(i=>(n.contain||"").includes(i))}function Ak(t){let e=kn(t);for(;Mt(e)&&!ci(e);){if(Aa(e))return e;if(Qr(e))return null;e=kn(e)}return null}function Ma(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Mk=new Set(["html","body","#document"]);function ci(t){return Mk.has(ai(t))}function gt(t){return nt(t).getComputedStyle(t)}function Zr(t){return mt(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function kn(t){if(ai(t)==="html")return t;const e=t.assignedSlot||t.parentNode||bf(t)&&t.host||At(t);return bf(e)?e.host:e}function yf(t){const e=kn(t);return ci(e)?t.ownerDocument?t.ownerDocument.body:t.body:Mt(e)&&$i(e)?e:yf(e)}function zi(t,e,n){var i;e===void 0&&(e=[]),n===void 0&&(n=!0);const r=yf(t),s=r===((i=t.ownerDocument)==null?void 0:i.body),o=nt(r);if(s){const a=Na(o);return e.concat(o,o.visualViewport||[],$i(r)?r:[],a&&n?zi(a):[])}return e.concat(r,zi(r,[],n))}function Na(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function kf(t){const e=gt(t);let n=parseFloat(e.width)||0,i=parseFloat(e.height)||0;const r=Mt(t),s=r?t.offsetWidth:n,o=r?t.offsetHeight:i,a=Gr(n)!==s||Gr(i)!==o;return a&&(n=s,i=o),{width:n,height:i,$:a}}function La(t){return mt(t)?t:t.contextElement}function li(t){const e=La(t);if(!Mt(e))return Ot(1);const n=e.getBoundingClientRect(),{width:i,height:r,$:s}=kf(e);let o=(s?Gr(n.width):n.width)/i,a=(s?Gr(n.height):n.height)/r;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const Nk=Ot(0);function Cf(t){const e=nt(t);return!Ma()||!e.visualViewport?Nk:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function Lk(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==nt(t)?!1:e}function Nn(t,e,n,i){e===void 0&&(e=!1),n===void 0&&(n=!1);const r=t.getBoundingClientRect(),s=La(t);let o=Ot(1);e&&(i?mt(i)&&(o=li(i)):o=li(t));const a=Lk(s,n,i)?Cf(s):Ot(0);let c=(r.left+a.x)/o.x,l=(r.top+a.y)/o.y,d=r.width/o.x,u=r.height/o.y;if(s){const h=nt(s),f=i&&mt(i)?nt(i):i;let g=h,p=Na(g);for(;p&&i&&f!==g;){const v=li(p),b=p.getBoundingClientRect(),k=gt(p),w=b.left+(p.clientLeft+parseFloat(k.paddingLeft))*v.x,y=b.top+(p.clientTop+parseFloat(k.paddingTop))*v.y;c*=v.x,l*=v.y,d*=v.x,u*=v.y,c+=w,l+=y,g=nt(p),p=Na(g)}}return Yr({width:d,height:u,x:c,y:l})}function Ua(t,e){const n=Zr(t).scrollLeft;return e?e.left+n:Nn(At(t)).left+n}function wf(t,e,n){n===void 0&&(n=!1);const i=t.getBoundingClientRect(),r=i.left+e.scrollLeft-(n?0:Ua(t,i)),s=i.top+e.scrollTop;return{x:r,y:s}}function Uk(t){let{elements:e,rect:n,offsetParent:i,strategy:r}=t;const s=r==="fixed",o=At(i),a=e?Qr(e.floating):!1;if(i===o||a&&s)return n;let c={scrollLeft:0,scrollTop:0},l=Ot(1);const d=Ot(0),u=Mt(i);if((u||!u&&!s)&&((ai(i)!=="body"||$i(o))&&(c=Zr(i)),Mt(i))){const f=Nn(i);l=li(i),d.x=f.x+i.clientLeft,d.y=f.y+i.clientTop}const h=o&&!u&&!s?wf(o,c,!0):Ot(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+h.x,y:n.y*l.y-c.scrollTop*l.y+d.y+h.y}}function Fk(t){return Array.from(t.getClientRects())}function Bk(t){const e=At(t),n=Zr(t),i=t.ownerDocument.body,r=tt(e.scrollWidth,e.clientWidth,i.scrollWidth,i.clientWidth),s=tt(e.scrollHeight,e.clientHeight,i.scrollHeight,i.clientHeight);let o=-n.scrollLeft+Ua(t);const a=-n.scrollTop;return gt(i).direction==="rtl"&&(o+=tt(e.clientWidth,i.clientWidth)-r),{width:r,height:s,x:o,y:a}}function jk(t,e){const n=nt(t),i=At(t),r=n.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(r){s=r.width,o=r.height;const l=Ma();(!l||l&&e==="fixed")&&(a=r.offsetLeft,c=r.offsetTop)}return{width:s,height:o,x:a,y:c}}const Vk=new Set(["absolute","fixed"]);function qk(t,e){const n=Nn(t,!0,e==="fixed"),i=n.top+t.clientTop,r=n.left+t.clientLeft,s=Mt(t)?li(t):Ot(1),o=t.clientWidth*s.x,a=t.clientHeight*s.y,c=r*s.x,l=i*s.y;return{width:o,height:a,x:c,y:l}}function _f(t,e,n){let i;if(e==="viewport")i=jk(t,n);else if(e==="document")i=Bk(At(t));else if(mt(e))i=qk(e,n);else{const r=Cf(t);i={x:e.x-r.x,y:e.y-r.y,width:e.width,height:e.height}}return Yr(i)}function Sf(t,e){const n=kn(t);return n===e||!mt(n)||ci(n)?!1:gt(n).position==="fixed"||Sf(n,e)}function $k(t,e){const n=e.get(t);if(n)return n;let i=zi(t,[],!1).filter(a=>mt(a)&&ai(a)!=="body"),r=null;const s=gt(t).position==="fixed";let o=s?kn(t):t;for(;mt(o)&&!ci(o);){const a=gt(o),c=Aa(o);!c&&a.position==="fixed"&&(r=null),(s?!c&&!r:!c&&a.position==="static"&&r&&Vk.has(r.position)||$i(o)&&!c&&Sf(t,o))?i=i.filter(l=>l!==o):r=a,o=kn(o)}return e.set(t,i),i}function zk(t){let{element:e,boundary:n,rootBoundary:i,strategy:r}=t;const s=[...n==="clippingAncestors"?Qr(e)?[]:$k(e,this._c):[].concat(n),i],o=s[0],a=s.reduce((c,l)=>{const d=_f(e,l,r);return c.top=tt(d.top,c.top),c.right=yn(d.right,c.right),c.bottom=yn(d.bottom,c.bottom),c.left=tt(d.left,c.left),c},_f(e,o,r));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}}function Wk(t){const{width:e,height:n}=kf(t);return{width:e,height:n}}function Hk(t,e,n){const i=Mt(e),r=At(e),s=n==="fixed",o=Nn(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const c=Ot(0);function l(){c.x=Ua(r)}if(i||!i&&!s)if((ai(e)!=="body"||$i(r))&&(a=Zr(e)),i){const f=Nn(e,!0,s,e);c.x=f.x+e.clientLeft,c.y=f.y+e.clientTop}else r&&l();s&&!i&&r&&l();const d=r&&!i&&!s?wf(r,a):Ot(0),u=o.left+a.scrollLeft-c.x-d.x,h=o.top+a.scrollTop-c.y-d.y;return{x:u,y:h,width:o.width,height:o.height}}function Fa(t){return gt(t).position==="static"}function Tf(t,e){if(!Mt(t)||gt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return At(t)===n&&(n=n.ownerDocument.body),n}function xf(t,e){const n=nt(t);if(Qr(t))return n;if(!Mt(t)){let r=kn(t);for(;r&&!ci(r);){if(mt(r)&&!Fa(r))return r;r=kn(r)}return n}let i=Tf(t,e);for(;i&&Pk(i)&&Fa(i);)i=Tf(i,e);return i&&ci(i)&&Fa(i)&&!Aa(i)?n:i||Ak(t)||n}const Gk=async function(t){const e=this.getOffsetParent||xf,n=this.getDimensions,i=await n(t.floating);return{reference:Hk(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function Kk(t){return gt(t).direction==="rtl"}const Jk={convertOffsetParentRelativeRectToViewportRelativeRect:Uk,getDocumentElement:At,getClippingRect:zk,getOffsetParent:xf,getElementRects:Gk,getClientRects:Fk,getDimensions:Wk,getScale:li,isElement:mt,isRTL:Kk};function Ef(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function Yk(t,e){let n=null,i;const r=At(t);function s(){var a;clearTimeout(i),(a=n)==null||a.disconnect(),n=null}function o(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const l=t.getBoundingClientRect(),{left:d,top:u,width:h,height:f}=l;if(a||e(),!h||!f)return;const g=Kr(u),p=Kr(r.clientWidth-(d+h)),v=Kr(r.clientHeight-(u+f)),b=Kr(d),k={rootMargin:-g+"px "+-p+"px "+-v+"px "+-b+"px",threshold:tt(0,yn(1,c))||1};let w=!0;function y(_){const S=_[0].intersectionRatio;if(S!==c){if(!w)return o();S?o(!1,S):i=setTimeout(()=>{o(!1,1e-7)},1e3)}S===1&&!Ef(l,t.getBoundingClientRect())&&o(),w=!1}try{n=new IntersectionObserver(y,{...k,root:r.ownerDocument})}catch{n=new IntersectionObserver(y,k)}n.observe(t)}return o(!0),s}function Xk(t,e,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=i,l=La(t),d=r||s?[...l?zi(l):[],...zi(e)]:[];d.forEach(b=>{r&&b.addEventListener("scroll",n,{passive:!0}),s&&b.addEventListener("resize",n)});const u=l&&a?Yk(l,n):null;let h=-1,f=null;o&&(f=new ResizeObserver(b=>{let[k]=b;k&&k.target===l&&f&&(f.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(e)})),n()}),l&&!c&&f.observe(l),f.observe(e));let g,p=c?Nn(t):null;c&&v();function v(){const b=Nn(t);p&&!Ef(p,b)&&n(),p=b,g=requestAnimationFrame(v)}return n(),()=>{var b;d.forEach(k=>{r&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),u==null||u(),(b=f)==null||b.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const Qk=wk,Zk=_k,eC=yk,tC=Tk,nC=kk,Pf=bk,iC=Sk,rC=(t,e,n)=>{const i=new Map,r={platform:Jk,...n},s={...r.platform,_c:i};return vk(t,e,{...r,platform:s})};var sC=typeof document<"u",oC=function(){},es=sC?Bt:oC;function ts(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,i,r;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!ts(t[i],e[i]))return!1;return!0}if(r=Object.keys(t),n=r.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!{}.hasOwnProperty.call(e,r[i]))return!1;for(i=n;i--!==0;){const s=r[i];if(!(s==="_owner"&&t.$$typeof)&&!ts(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function Rf(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function If(t,e){const n=Rf(t);return Math.round(e*n)/n}function Ba(t){const e=B(t);return es(()=>{e.current=t}),e}function aC(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:c,open:l}=t,[d,u]=q({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=q(i);ts(h,i)||f(i);const[g,p]=q(null),[v,b]=q(null),k=V(W=>{W!==S.current&&(S.current=W,p(W))},[]),w=V(W=>{W!==x.current&&(x.current=W,b(W))},[]),y=s||g,_=o||v,S=B(null),x=B(null),I=B(d),R=c!=null,D=Ba(c),M=Ba(r),U=Ba(l),j=V(()=>{if(!S.current||!x.current)return;const W={placement:e,strategy:n,middleware:h};M.current&&(W.platform=M.current),rC(S.current,x.current,W).then(ee=>{const we={...ee,isPositioned:U.current!==!1};$.current&&!ts(I.current,we)&&(I.current=we,ir(()=>{u(we)}))})},[h,e,n,M,U]);es(()=>{l===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,u(W=>({...W,isPositioned:!1})))},[l]);const $=B(!1);es(()=>($.current=!0,()=>{$.current=!1}),[]),es(()=>{if(y&&(S.current=y),_&&(x.current=_),y&&_){if(D.current)return D.current(y,_,j);j()}},[y,_,j,D,R]);const F=oe(()=>({reference:S,floating:x,setReference:k,setFloating:w}),[k,w]),G=oe(()=>({reference:y,floating:_}),[y,_]),Y=oe(()=>{const W={position:n,left:0,top:0};if(!G.floating)return W;const ee=If(G.floating,d.x),we=If(G.floating,d.y);return a?{...W,transform:"translate("+ee+"px, "+we+"px)",...Rf(G.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:we}},[n,a,G.floating,d.x,d.y]);return oe(()=>({...d,update:j,refs:F,elements:G,floatingStyles:Y}),[d,j,F,G,Y])}const cC=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:i,padding:r}=typeof t=="function"?t(n):t;return i&&e(i)?i.current!=null?Pf({element:i.current,padding:r}).fn(n):{}:i?Pf({element:i,padding:r}).fn(n):{}}}},lC=(t,e)=>({...Qk(t),options:[t,e]}),dC=(t,e)=>({...Zk(t),options:[t,e]}),uC=(t,e)=>({...iC(t),options:[t,e]}),hC=(t,e)=>({...eC(t),options:[t,e]}),fC=(t,e)=>({...tC(t),options:[t,e]}),pC=(t,e)=>({...nC(t),options:[t,e]}),mC=(t,e)=>({...cC(t),options:[t,e]});var gC="Arrow",Of=Q((t,e)=>{const{children:n,width:i=10,height:r=5,...s}=t;return m(Se.svg,{...s,ref:e,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:m("polygon",{points:"0,0 30,0 15,10"})})});Of.displayName=gC;var vC=Of;function bC(t){const[e,n]=q(void 0);return Ke(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const i=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const s=r[0];let o,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return i.observe(t,{box:"border-box"}),()=>i.unobserve(t)}else n(void 0)},[t]),e}var ja="Popper",[Df,Af]=wa(ja),[yC,Mf]=Df(ja),Nf=t=>{const{__scopePopper:e,children:n}=t,[i,r]=q(null);return m(yC,{scope:e,anchor:i,onAnchorChange:r,children:n})};Nf.displayName=ja;var Lf="PopperAnchor",Uf=Q((t,e)=>{const{__scopePopper:n,virtualRef:i,...r}=t,s=Mf(Lf,n),o=B(null),a=Fe(e,o),c=B(null);return K(()=>{const l=c.current;c.current=(i==null?void 0:i.current)||o.current,l!==c.current&&s.onAnchorChange(c.current)}),i?null:m(Se.div,{...r,ref:a})});Uf.displayName=Lf;var Va="PopperContent",[kC,CC]=Df(Va),Ff=Q((t,e)=>{var n,i,r,s,o,a;const{__scopePopper:c,side:l="bottom",sideOffset:d=0,align:u="center",alignOffset:h=0,arrowPadding:f=0,avoidCollisions:g=!0,collisionBoundary:p=[],collisionPadding:v=0,sticky:b="partial",hideWhenDetached:k=!1,updatePositionStrategy:w="optimized",onPlaced:y,..._}=t,S=Mf(Va,c),[x,I]=q(null),R=Fe(e,it=>I(it)),[D,M]=q(null),U=bC(D),j=(U==null?void 0:U.width)??0,$=(U==null?void 0:U.height)??0,F=l+(u!=="center"?"-"+u:""),G=typeof v=="number"?v:{top:0,right:0,bottom:0,left:0,...v},Y=Array.isArray(p)?p:[p],W=Y.length>0,ee={padding:G,boundary:Y.filter(_C),altBoundary:W},{refs:we,floatingStyles:bt,placement:nn,isPositioned:st,middlewareData:Ve}=aC({strategy:"fixed",placement:F,whileElementsMounted:(...it)=>Xk(...it,{animationFrame:w==="always"}),elements:{reference:S.anchor},middleware:[lC({mainAxis:d+$,alignmentAxis:h}),g&&dC({mainAxis:!0,crossAxis:!1,limiter:b==="partial"?uC():void 0,...ee}),g&&hC({...ee}),fC({...ee,apply:({elements:it,rects:Hi,availableWidth:Gi,availableHeight:Ki})=>{const{width:y_,height:k_}=Hi.reference,ps=it.floating.style;ps.setProperty("--radix-popper-available-width",`${Gi}px`),ps.setProperty("--radix-popper-available-height",`${Ki}px`),ps.setProperty("--radix-popper-anchor-width",`${y_}px`),ps.setProperty("--radix-popper-anchor-height",`${k_}px`)}}),D&&mC({element:D,padding:f}),SC({arrowWidth:j,arrowHeight:$}),k&&pC({strategy:"referenceHidden",...ee})]}),[Lt,yt]=Vf(nn),H=Mn(y);Ke(()=>{st&&(H==null||H())},[st,H]);const me=(n=Ve.arrow)==null?void 0:n.x,Te=(i=Ve.arrow)==null?void 0:i.y,re=((r=Ve.arrow)==null?void 0:r.centerOffset)!==0,[be,Re]=q();return Ke(()=>{x&&Re(window.getComputedStyle(x).zIndex)},[x]),m("div",{ref:we.setFloating,"data-radix-popper-content-wrapper":"",style:{...bt,transform:st?bt.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:be,"--radix-popper-transform-origin":[(s=Ve.transformOrigin)==null?void 0:s.x,(o=Ve.transformOrigin)==null?void 0:o.y].join(" "),...((a=Ve.hide)==null?void 0:a.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:m(kC,{scope:c,placedSide:Lt,onArrowChange:M,arrowX:me,arrowY:Te,shouldHideArrow:re,children:m(Se.div,{"data-side":Lt,"data-align":yt,..._,ref:R,style:{..._.style,animation:st?void 0:"none"}})})})});Ff.displayName=Va;var Bf="PopperArrow",wC={top:"bottom",right:"left",bottom:"top",left:"right"},jf=Q(function(t,e){const{__scopePopper:n,...i}=t,r=CC(Bf,n),s=wC[r.placedSide];return m("span",{ref:r.onArrowChange,style:{position:"absolute",left:r.arrowX,top:r.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[r.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[r.placedSide],visibility:r.shouldHideArrow?"hidden":void 0},children:m(vC,{...i,ref:e,style:{...i.style,display:"block"}})})});jf.displayName=Bf;function _C(t){return t!==null}var SC=t=>({name:"transformOrigin",options:t,fn(e){var n,i,r;const{placement:s,rects:o,middlewareData:a}=e,c=((n=a.arrow)==null?void 0:n.centerOffset)!==0,l=c?0:t.arrowWidth,d=c?0:t.arrowHeight,[u,h]=Vf(s),f={start:"0%",center:"50%",end:"100%"}[h],g=(((i=a.arrow)==null?void 0:i.x)??0)+l/2,p=(((r=a.arrow)==null?void 0:r.y)??0)+d/2;let v="",b="";return u==="bottom"?(v=c?f:`${g}px`,b=`${-d}px`):u==="top"?(v=c?f:`${g}px`,b=`${o.floating.height+d}px`):u==="right"?(v=`${-d}px`,b=c?f:`${p}px`):u==="left"&&(v=`${o.floating.width+d}px`,b=c?f:`${p}px`),{data:{x:v,y:b}}}});function Vf(t){const[e,n="center"]=t.split("-");return[e,n]}var TC=Nf,xC=Uf,EC=Ff,PC=jf,RC="Portal",qf=Q((t,e)=>{var n;const{container:i,...r}=t,[s,o]=q(!1);Ke(()=>o(!0),[]);const a=i||s&&((n=globalThis==null?void 0:globalThis.document)==null?void 0:n.body);return a?Vt.createPortal(m(Se.div,{...r,ref:e}),a):null});qf.displayName=RC;var IC=tl[" useInsertionEffect ".trim().toString()]||Ke;function $f({prop:t,defaultProp:e,onChange:n=()=>{},caller:i}){const[r,s,o]=OC({defaultProp:e,onChange:n}),a=t!==void 0,c=a?t:r;{const d=B(t!==void 0);K(()=>{const u=d.current;u!==a&&console.warn(`${i} is changing from ${u?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,i])}const l=V(d=>{var u;if(a){const h=DC(d)?d(t):d;h!==t&&((u=o.current)==null||u.call(o,h))}else s(d)},[a,t,s,o]);return[c,l]}function OC({defaultProp:t,onChange:e}){const[n,i]=q(t),r=B(n),s=B(e);return IC(()=>{s.current=e},[e]),K(()=>{var o;r.current!==n&&((o=s.current)==null||o.call(s,n),r.current=n)},[n,r]),[n,i,s]}function DC(t){return typeof t=="function"}function AC(t){const e=B({value:t,previous:t});return oe(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var zf=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),MC="VisuallyHidden",NC=Q((t,e)=>m(Se.span,{...t,ref:e,style:{...zf,...t.style}}));NC.displayName=MC;var LC=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},di=new WeakMap,ns=new WeakMap,is={},qa=0,Wf=function(t){return t&&(t.host||Wf(t.parentNode))},UC=function(t,e){return e.map(function(n){if(t.contains(n))return n;var i=Wf(n);return i&&t.contains(i)?i:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},FC=function(t,e,n,i){var r=UC(e,Array.isArray(t)?t:[t]);is[n]||(is[n]=new WeakMap);var s=is[n],o=[],a=new Set,c=new Set(r),l=function(u){!u||a.has(u)||(a.add(u),l(u.parentNode))};r.forEach(l);var d=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(h){if(a.has(h))d(h);else try{var f=h.getAttribute(i),g=f!==null&&f!=="false",p=(di.get(h)||0)+1,v=(s.get(h)||0)+1;di.set(h,p),s.set(h,v),o.push(h),p===1&&g&&ns.set(h,!0),v===1&&h.setAttribute(n,"true"),g||h.setAttribute(i,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return d(e),a.clear(),qa++,function(){o.forEach(function(u){var h=di.get(u)-1,f=s.get(u)-1;di.set(u,h),s.set(u,f),h||(ns.has(u)||u.removeAttribute(i),ns.delete(u)),f||u.removeAttribute(n)}),qa--,qa||(di=new WeakMap,di=new WeakMap,ns=new WeakMap,is={})}},BC=function(t,e,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(t)?t:[t]),r=LC(t);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),FC(i,r,n,"aria-hidden")):function(){return null}},Nt=function(){return Nt=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},Nt.apply(this,arguments)};function Hf(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function jC(t,e,n){for(var i=0,r=e.length,s;i<r;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))}var rs="right-scroll-bar-position",ss="width-before-scroll-bar",VC="with-scroll-bars-hidden",qC="--removed-body-scroll-bar-size";function $a(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function $C(t,e){var n=q(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(i){var r=n.value;r!==i&&(n.value=i,n.callback(i,r))}}}})[0];return n.callback=e,n.facade}var zC=typeof window<"u"?Bt:K,Gf=new WeakMap;function WC(t,e){var n=$C(null,function(i){return t.forEach(function(r){return $a(r,i)})});return zC(function(){var i=Gf.get(n);if(i){var r=new Set(i),s=new Set(t),o=n.current;r.forEach(function(a){s.has(a)||$a(a,null)}),s.forEach(function(a){r.has(a)||$a(a,o)})}Gf.set(n,t)},[t]),n}function HC(t){return t}function GC(t,e){e===void 0&&(e=HC);var n=[],i=!1,r={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var o=e(s,i);return n.push(o),function(){n=n.filter(function(a){return a!==o})}},assignSyncMedium:function(s){for(i=!0;n.length;){var o=n;n=[],o.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){i=!0;var o=[];if(n.length){var a=n;n=[],a.forEach(s),o=n}var c=function(){var d=o;o=[],d.forEach(s)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){o.push(d),l()},filter:function(d){return o=o.filter(d),n}}}};return r}function KC(t){t===void 0&&(t={});var e=GC(null);return e.options=Nt({async:!0,ssr:!1},t),e}var Kf=function(t){var e=t.sideCar,n=Hf(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=e.read();if(!i)throw new Error("Sidecar medium not found");return fe(i,Nt({},n))};Kf.isSideCarExport=!0;function JC(t,e){return t.useMedium(e),Kf}var Jf=KC(),za=function(){},os=Q(function(t,e){var n=B(null),i=q({onScrollCapture:za,onWheelCapture:za,onTouchMoveCapture:za}),r=i[0],s=i[1],o=t.forwardProps,a=t.children,c=t.className,l=t.removeScrollBar,d=t.enabled,u=t.shards,h=t.sideCar,f=t.noRelative,g=t.noIsolation,p=t.inert,v=t.allowPinchZoom,b=t.as,k=b===void 0?"div":b,w=t.gapMode,y=Hf(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=h,S=WC([n,e]),x=Nt(Nt({},y),r);return fe(ge,null,d&&fe(_,{sideCar:Jf,removeScrollBar:l,shards:u,noRelative:f,noIsolation:g,inert:p,setCallbacks:s,allowPinchZoom:!!v,lockRef:n,gapMode:w}),o?wi(on.only(a),Nt(Nt({},x),{ref:S})):fe(k,Nt({},x,{className:c,ref:S}),a))});os.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},os.classNames={fullWidth:ss,zeroRight:rs};var YC=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function XC(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=YC();return e&&t.setAttribute("nonce",e),t}function QC(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function ZC(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var ew=function(){var t=0,e=null;return{add:function(n){t==0&&(e=XC())&&(QC(e,n),ZC(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},tw=function(){var t=ew();return function(e,n){K(function(){return t.add(e),function(){t.remove()}},[e&&n])}},Yf=function(){var t=tw(),e=function(n){var i=n.styles,r=n.dynamic;return t(i,r),null};return e},nw={left:0,top:0,right:0,gap:0},Wa=function(t){return parseInt(t||"",10)||0},iw=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],i=e[t==="padding"?"paddingTop":"marginTop"],r=e[t==="padding"?"paddingRight":"marginRight"];return[Wa(n),Wa(i),Wa(r)]},rw=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return nw;var e=iw(t),n=document.documentElement.clientWidth,i=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,i-n+e[2]-e[0])}},sw=Yf(),ui="data-scroll-locked",ow=function(t,e,n,i){var r=t.left,s=t.top,o=t.right,a=t.gap;return n===void 0&&(n="margin"),`
432
+ `,$h=0,Qb=new Float32Array([-1,1,-1,-1,1,1,1,-1]),Zb="https://storage.googleapis.com/eleven-public-cdn/images/perlin-noise.png",zh=class _n{constructor(e){Ge(this,"gl"),Ge(this,"program"),Ge(this,"startTime"),Ge(this,"targetSpeed",0),Ge(this,"speed",.5),Ge(this,"rafId",null),Ge(this,"resizeObserver"),Ge(this,"colorA",[0,0,0]),Ge(this,"colorB",[0,0,0]),Ge(this,"offsets",new Float32Array(7).map(()=>Math.random()*Math.PI*2)),Ge(this,"copyNoiseImage",()=>{this.gl&&(this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,_n.noiseImage),this.gl.generateMipmap(this.gl.TEXTURE_2D))}),Ge(this,"toDataURL",()=>this.gl.canvas.toDataURL("image/png")),Ge(this,"render",()=>{if(!this.gl){this.rafId=null;return}const o=(performance.now()-this.startTime)/1e3;this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uTime"),o),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.rafId=requestAnimationFrame(this.render)});const n=e.getContext("webgl2",{depth:!1,stencil:!1});this.gl=n,this.program=this.setupProgram(Yb,Xb);const i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([128,128,128,255])),_n.noiseImage||(_n.noiseImage=new Image,_n.noiseImage.crossOrigin="anonymous",_n.noiseImage.src=Zb),_n.noiseImage.complete?this.copyNoiseImage():_n.noiseImage.addEventListener("load",this.copyNoiseImage);const r=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,Qb,n.STATIC_DRAW),n.vertexAttribPointer($h,2,n.FLOAT,!1,0,0),n.enableVertexAttribArray($h),this.updateColors("#2792DC","#9CE6E6"),this.resizeObserver=new ResizeObserver(o=>{const a=o[0],c=a.devicePixelContentBoxSize?a.devicePixelContentBoxSize[0]:a.contentBoxSize[0];e.width=Math.min(512,c.inlineSize),e.height=Math.min(512,c.blockSize),this.updateViewport()});const s=e.parentElement;if(s)try{this.resizeObserver.observe(s,{box:"device-pixel-content-box"})}catch{this.resizeObserver.observe(s)}this.startTime=performance.now(),this.rafId=requestAnimationFrame(this.render)}dispose(){var e;this.rafId!==null&&cancelAnimationFrame(this.rafId),(e=this.resizeObserver)==null||e.disconnect(),this.gl=null,this.program=null}updateViewport(){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}updateColors(e,n){this.gl&&(this.colorA=this.updateColor("uColor1",e)??this.colorA,this.colorB=this.updateColor("uColor2",n)??this.colorB)}updateVolume(e,n){this.targetSpeed=.2+(1-Math.pow(n-1,2))*1.8,this.targetSpeed>this.speed&&(this.speed=this.targetSpeed),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uInputVolume"),e),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uOutputVolume"),n)}updateColor(e,n){try{const i=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,o=[Math.pow(i,2.2),Math.pow(r,2.2),Math.pow(s,2.2)];return this.gl.uniform3fv(this.gl.getUniformLocation(this.program,e),o),o}catch(i){console.error(`[ConversationalAI] Failed to parse ${n} as color:`,i)}}setupProgram(e,n){const i=this.getShader(this.gl.FRAGMENT_SHADER,e),r=this.getShader(this.gl.VERTEX_SHADER,n);if(!i||!r)throw new Error("Failed to compile shaders");if(this.program=this.gl.createProgram(),this.gl.attachShader(this.program,i),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),!this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS))throw new Error("Failed to link program");return this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"uPerlinTexture"),0),this.gl.uniform1fv(this.gl.getUniformLocation(this.program,"uOffsets"),this.offsets),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor1"),this.colorA),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor2"),this.colorB),this.program}getShader(e,n){const i=this.gl.createShader(e);return this.gl.shaderSource(i,n),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)?i:(this.gl.deleteShader(i),null)}};Ge(zh,"noiseImage");let ey=zh;const ty={sm:"w-9 h-9",lg:"w-48 h-48"};function si({size:t="sm",className:e}){const{getInputVolume:n,getOutputVolume:i,isSpeaking:r,isDisconnected:s}=Be(),{config:o}=pa(),a=B(null),c=B(null);Ct(()=>{if(s.value){a.current.style.transform="",c.current.style.transform="";return}let d;function u(){const h=n(),f=i(),g=r.peek()?1:1-h*.4,p=r.peek()?1+f*.4:1;a.current.style.transform=`scale(${p})`,c.current.style.transform=`scale(${g})`,d=requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(d)}});const l=ue(()=>({backgroundImage:o.value.type==="image"?`url(${o.value.url})`:o.value.type==="url"?`url(${o.value.custom_url})`:void 0}));return m("div",{className:ae("relative shrink-0",ty[t],e),children:[m("div",{ref:a,className:"absolute inset-0 rounded-full bg-base-border"}),m("div",{ref:c,style:l,className:"absolute inset-0 rounded-full overflow-hidden bg-base bg-cover",children:o.value.type==="orb"&&m(ny,{color1:o.value.color_1,color2:o.value.color_2})})]})}function ny({color1:t,color2:e}){const{canvasUrl:n}=pa(),[i,r]=q(null);K(()=>{i&&(i.updateColors(t,e),i.render(),n.value=i.toDataURL())},[i,t,e]);const s=V(o=>{if(o){const a=new ey(o);return r(a),()=>a.dispose()}else r(null)},[r]);return m("canvas",{className:"w-full h-full",ref:s})}const iy={phone:sy,"phone-off":oy,chat:ay,mic:cy,"mic-off":ly,check:hy,"chevron-down":dy,"chevron-up":uy,send:fy,star:py},ry={sm:"text-xs",md:"text-lg",lg:"text-xl"};function It({name:t,size:e="md",className:n}){const i=iy[t];return m("slot",{name:`icon-${t}`,className:ae("flex",ry[e],n),"aria-hidden":!0,children:m(i,{})})}function sy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{d:"M3.7489 2.25C2.93286 2.25 2.21942 2.92142 2.27338 3.7963C2.6686 10.2041 7.79483 15.3303 14.2026 15.7255C15.0775 15.7795 15.7489 15.066 15.7489 14.25V11.958C15.7489 11.2956 15.3144 10.7116 14.6799 10.5213L12.6435 9.91035C12.1149 9.75179 11.542 9.89623 11.1518 10.2864L10.5901 10.8482C9.15291 10.0389 7.95998 8.84599 7.15074 7.40881L7.71246 6.84709C8.10266 6.45689 8.24711 5.88396 8.08854 5.35541L7.47761 3.31898C7.28727 2.6845 6.70329 2.25 6.04087 2.25H3.7489Z"})})}function oy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M16.0303 3.53033C16.3232 3.23744 16.3232 2.76256 16.0303 2.46967C15.7374 2.17678 15.2626 2.17678 14.9697 2.46967L8.6271 8.81224C8.25925 8.3778 7.93185 7.90804 7.65074 7.40881L8.21246 6.84709C8.60266 6.45689 8.74711 5.88396 8.58854 5.35541L7.97761 3.31898C7.78727 2.6845 7.20329 2.25 6.54087 2.25H4.2489C3.43286 2.25 2.71942 2.92142 2.77338 3.7963C2.95462 6.73468 4.13069 9.40357 5.96899 11.4703L2.96967 14.4697C2.67678 14.7626 2.67678 15.2374 2.96967 15.5303C3.26256 15.8232 3.73744 15.8232 4.03033 15.5303L16.0303 3.53033Z"}),m("path",{d:"M14.7026 15.7255C12.2994 15.5773 10.0765 14.7636 8.21584 13.4665L10.9278 10.7545C10.9815 10.7863 11.0356 10.8175 11.0901 10.8482L11.6518 10.2864C12.042 9.89623 12.6149 9.75179 13.1435 9.91035L15.1799 10.5213C15.8144 10.7116 16.2489 11.2956 16.2489 11.958V14.25C16.2489 15.066 15.5775 15.7795 14.7026 15.7255Z"})]})}function ay(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M1.5 6.75C1.5 4.26472 3.51472 2.25 6 2.25H12C14.4853 2.25 16.5 4.26472 16.5 6.75V11.25C16.5 13.7353 14.4853 15.75 12 15.75H2.25C1.83579 15.75 1.5 15.4142 1.5 15V6.75ZM6 9.9375C5.48223 9.9375 5.0625 9.51777 5.0625 9C5.0625 8.48223 5.48223 8.0625 6 8.0625C6.51777 8.0625 6.9375 8.48223 6.9375 9C6.9375 9.51777 6.51777 9.9375 6 9.9375ZM9 9.9375C8.48223 9.9375 8.0625 9.51777 8.0625 9C8.0625 8.48223 8.48223 8.0625 9 8.0625C9.51777 8.0625 9.9375 8.48223 9.9375 9C9.9375 9.51777 9.51777 9.9375 9 9.9375ZM11.0625 9C11.0625 9.51777 11.4822 9.9375 12 9.9375C12.5178 9.9375 12.9375 9.51777 12.9375 9C12.9375 8.48223 12.5178 8.0625 12 8.0625C11.4822 8.0625 11.0625 8.48223 11.0625 9Z"})})}function cy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M9.50008 1.5C7.42901 1.5 5.75008 3.17893 5.75008 5.25V8.25C5.75008 10.3211 7.42901 12 9.50008 12C11.5712 12 13.2501 10.3211 13.2501 8.25V5.25C13.2501 3.17893 11.5712 1.5 9.50008 1.5Z"}),m("path",{d:"M4.88997 10.8417C4.66448 10.4943 4.20002 10.3954 3.85256 10.6209C3.50509 10.8463 3.40621 11.3108 3.63169 11.6583C4.47442 12.9569 6.08493 14.6838 8.75008 14.9616V15.75C8.75008 16.1642 9.08587 16.5 9.50008 16.5C9.9143 16.5 10.2501 16.1642 10.2501 15.75V14.9616C12.9152 14.6838 14.5257 12.9569 15.3685 11.6583C15.594 11.3108 15.4951 10.8463 15.1476 10.6209C14.8001 10.3954 14.3357 10.4943 14.1102 10.8417C13.3305 12.0432 11.9002 13.5 9.50008 13.5C7.1 13.5 5.66968 12.0432 4.88997 10.8417Z"})]})}function ly(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M13.25 8.25C13.25 8.64791 13.188 9.03135 13.0732 9.39119L6.57947 2.8975C7.26687 2.04521 8.31974 1.5 9.49995 1.5C11.571 1.5 13.25 3.17893 13.25 5.25V8.25Z"}),m("path",{d:"M2.21967 1.71967C2.51256 1.42678 2.98744 1.42678 3.28033 1.71967L16.7803 15.2197C17.0732 15.5126 17.0732 15.9874 16.7803 16.2803C16.4874 16.5732 16.0126 16.5732 15.7197 16.2803L13.2828 13.8435C12.4719 14.4022 11.4678 14.8338 10.25 14.9614V15.75C10.25 16.1642 9.91422 16.5 9.50001 16.5C9.08579 16.5 8.75001 16.1642 8.75001 15.75V14.9616C6.08485 14.6838 4.47434 12.9569 3.63162 11.6583C3.40614 11.3108 3.50502 10.8463 3.85248 10.6209C4.19995 10.3954 4.66441 10.4943 4.88989 10.8417C5.6696 12.0432 7.09993 13.5 9.50001 13.5C10.5978 13.5 11.4845 13.1981 12.1992 12.7598L11.0875 11.6482C10.605 11.8739 10.0667 12 9.50001 12C7.42894 12 5.75001 10.3211 5.75001 8.25V6.31067L2.21967 2.78033C1.92678 2.48744 1.92678 2.01256 2.21967 1.71967Z"})]})}function dy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"m6 9 6 6 6-6"})})}function uy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"m18 15-6-6-6 6"})})}function hy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"M20 6 9 17l-5-5"})})}function fy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 20 20",fill:"currentColor",...t,children:m("path",{d:"M2.59413 5.1485C2.04 3.39377 3.86657 1.83482 5.51245 2.65776L16.47 8.13653C18.0055 8.90429 18.0055 11.0955 16.47 11.8633L5.51245 17.3421C3.86656 18.165 2.04 16.6061 2.59413 14.8513L3.86297 10.8333H7.50006C7.9603 10.8333 8.33339 10.4602 8.33339 10C8.33339 9.53976 7.9603 9.16667 7.50006 9.16667H3.86302L2.59413 5.1485Z"})})}function py(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 21 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{d:"M11.8621 0.854898C11.3145 -0.284967 9.68804 -0.284965 9.1404 0.854899L6.77181 5.78487C6.77181 5.78487 6.76902 5.78867 6.7646 5.78925L1.31499 6.50272C0.0591912 6.66713 -0.452868 8.21568 0.474832 9.09033L4.45896 12.8466C4.46075 12.8483 4.46059 12.8502 4.46059 12.8502L3.46003 18.2169C3.22657 19.4691 4.55184 20.4152 5.66108 19.8172L10.4957 17.2111C10.4991 17.2093 10.5035 17.2093 10.5068 17.2111L15.3415 19.8172C16.4507 20.4152 17.776 19.4691 17.5425 18.2169L16.542 12.8502C16.542 12.8502 16.5418 12.8483 16.5436 12.8466L20.5277 9.09033C21.4554 8.21568 20.9434 6.66713 19.6876 6.50272L14.2379 5.78925C14.2335 5.78867 14.2307 5.78487 14.2307 5.78487L11.8621 0.854898Z"})})}function my({orbColor:t,circleBackgroundColor:e,starColor:n,className:i}){return m("slot",{name:"icon-feedback",className:ae("flex",i),"aria-hidden":!0,children:m("svg",{width:"100%",height:"100%",viewBox:"0 0 82 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[m("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M9 42C9 59.6731 23.3269 74 41 74C58.6731 74 73 59.6731 73 42C73 24.3269 58.6731 10 41 10C23.3269 10 9 24.3269 9 42ZM29.4529 18.5973C31.1347 18.0574 32.8641 17.5023 34.9844 16.6005C42.2533 13.5091 48.3526 11.9217 51.7782 14.094C53.5063 15.1899 54.4051 16.7749 55.6117 18.9024C56.7969 20.9922 58.279 23.6057 61.1358 26.7937C62.2737 28.0636 63.3886 29.2195 64.4371 30.3064C68.7007 34.7263 71.8645 38.0061 70.9949 43.1697C70.2965 47.316 67.9794 49.4559 65.6038 51.65C63.4317 53.656 61.2107 55.7073 60.1332 59.3786C57.8774 67.0653 53.5327 71.9113 48.3526 72.7468C43.1725 73.5823 36.6555 75.1698 29.8043 70.1567C26.1949 67.5157 25.229 64.3182 24.1947 60.894C23.2657 57.8184 22.2814 54.56 19.2768 51.3577C14.1619 45.9062 10.2533 29.6345 19.2768 23.0339C23.736 20.4327 26.5223 19.5382 29.4529 18.5973Z",fill:t,"fill-opacity":"0.15",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M43.5 73.4212C40.4387 73.4212 35.0039 71.1025 37.556 56.4696C40.143 41.6365 42.6582 40.577 44.6991 25.744C46.3318 13.8775 41.1635 8.87964 33 10.9988",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M43.5 73.4212C40.4387 73.4212 35.0039 71.1025 37.556 56.4696C40.143 41.6365 42.6582 40.577 44.6991 25.744C46.3318 13.8775 41.1635 8.87964 33 10.9988",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M21.9366 68.1987C21.3549 66.5119 21.0386 60.9231 28.1376 53.3448C37.0114 43.8719 40.5 43.9579 51.4911 31.7482C59.5691 22.7747 59.1723 17.0524 58.0993 15.4626",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M9.26819 42.161C10.4003 43.5337 15.6951 46.3853 25.7661 44.3926C38.3548 41.9018 52.434 40.307 57.694 41.0287C70.352 42.7655 71.4138 51.3035 71.4138 51.3035",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M22 16.4916C18.815 21.85 19.6451 26.0591 27.9943 32.0828C38.4307 39.6124 50.2985 48.8304 53.5024 53.1027C58.6684 59.9914 59.5 67.928 59.5 67.928",stroke:t,"stroke-opacity":"0.35"}),m("rect",{x:"9.26099",y:"10",width:"63.7129",height:"63.7129",rx:"31.8565",stroke:t,"stroke-opacity":"0.43","stroke-width":"1.5"}),m("g",{"clip-path":"url(#clip0_7006_42127)",children:[m("circle",{cx:"62.4996",cy:"18.2032",r:"15.0195",transform:"rotate(6.27205 62.4996 18.2032)",fill:e}),m("path",{d:"M60.7142 12.1753C62.057 10.0714 65.2294 10.4202 66.0833 12.7654L66.6158 14.2308L68.1251 14.6217C70.5415 15.2484 71.1908 18.3742 69.2237 19.911L67.9944 20.8704L68.0896 22.4262C68.2403 24.9178 65.4681 26.5011 63.3987 25.1056L62.1065 24.2326L60.6555 24.8041C58.3322 25.7172 55.9702 23.5694 56.6585 21.1698L57.0884 19.6717L56.0977 18.4684C54.5112 16.541 55.8231 13.6307 58.318 13.5438L59.8751 13.4899L60.7142 12.1753Z",fill:n,stroke:e,"stroke-width":"3.27381"}),m("path",{d:"M63.925 5.23719C71.0867 6.02431 76.2545 12.4676 75.4676 19.6293C74.6805 26.7911 68.2364 31.959 61.0746 31.1718C53.9129 30.3845 48.7459 23.9406 49.533 16.7789C50.3203 9.61739 56.7634 4.45029 63.925 5.23719ZM63.6957 7.32326C57.6866 6.66302 52.2797 10.9991 51.6191 17.0082C50.9586 23.0174 55.2946 28.4251 61.3038 29.0858C67.3132 29.7462 72.7211 25.4094 73.3816 19.4C74.0418 13.3908 69.705 7.98372 63.6957 7.32326Z",fill:n,stroke:e,"stroke-width":"0.3","stroke-linecap":"round","stroke-linejoin":"round"})]}),m("ellipse",{cx:"41",cy:"85",rx:"15",ry:"3",fill:t,"fill-opacity":"0.35"}),m("defs",{children:m("clipPath",{id:"clip0_7006_42127",children:m("rect",{width:"33",height:"33",fill:"white",transform:"translate(47.9012) rotate(6.27205)"})})})]})})}function Zt(t){const e=Vh().value?gy:vy;return m(e,{...t})}function gy({visible:t,className:e,grow:n,dep:i,...r}){return t?m("div",{className:ae(n&&"grow",e),...r}):null}function vy({visible:t,children:e,className:n,grow:i,dep:r,...s}){const[o,a]=q(t),[c,l]=q(null),[d,u]=q(null),h=B(e);t&&(h.current=e);const f=V(v=>{l(v),v&&!t&&(v.style.width="0px",v.style.height="0px")},[]);K(()=>{d&&(d.style.transition="none",d.style.opacity="0",d.offsetWidth,d.style.transition="",d.style.opacity="")},[r]),oe(()=>{c&&(c.style.width=`${c.offsetWidth}px`,c.style.height=`${c.offsetHeight}px`)},[c,t,r]),K(()=>{if(!c||!d)return;t&&a(!0);const v=t?d.offsetWidth:0,b=t?d.offsetHeight:0;c.style.width=!t||c.offsetWidth!==v?`${v}px`:"",c.style.height=!t||c.offsetHeight!==b?`${b}px`:""},[c,d,t,r]);const{transitioning:g,handlers:p}=qh({onEnd:()=>{t?(c.style.width="",c.style.height=""):a(!1)}});return m("div",{ref:f,className:ae("relative inline-flex shrink-0 justify-center items-center transition-[opacity,width,height,transform,flex-grow] duration-200 min-w-0",!t&&"opacity-0 scale-75",t&&i&&"grow",t&&o&&!g.value&&"z-1"),...p,children:m("div",{ref:u,className:ae("shrink-0 min-h-min min-w-min transition-opacity duration-200",i&&"grow",n),...s,children:(t||o)&&h.current})})}const by={primary:"text-accent-primary border border-accent bg-accent hover:border-accent-hover hover:bg-accent-hover active:border-accent-active active:bg-accent-active",secondary:"text-base-primary border border-base-border bg-base hover:bg-base-hover active:bg-base-active",ghost:"text-base-primary border border-base bg-base hover:bg-base-hover hover:border-base-hover active:bg-base-active active:border-base-active"},pt=Q(function({variant:t="secondary",children:e,icon:n,className:i,iconClassName:r,truncate:s=!0,...o},a){const c=!!n&&!e;return m("button",{ref:a,className:ae("h-9 flex px-2.5 text-sm items-center transition-colors justify-center rounded-button duration-200 focus-ring overflow-hidden select-none",by[t],c&&"min-w-9",i),type:"button",...o,children:[n&&m(It,{className:ae("transition-[margin] duration-200",c&&"-mx-0.5",r),name:n}),m(Zt,{visible:!!e,dep:e,children:m("span",{className:"block whitespace-nowrap max-w-64 truncate px-1.5",children:e})})]})});function va({className:t,...e}){const{status:n,isSpeaking:i}=Be(),r=Wr(),s=Ee(),o=ue(()=>n.value!=="connected"?s.connecting_status.value:r.value?s.chatting_status.value:i.value?s.speaking_status.value:s.listening_status.value),[a,c]=q(o.peek());return Ct(()=>{const l=o.value;if(n.value==="connected"&&i.value)c(l);else{const d=setTimeout(()=>{c(l)},500);return()=>clearTimeout(d)}}),m("div",{className:ae("py-1.5 px-3 bg-base-active overflow-hidden rounded-bubble text-sm",t),...e,children:m(je,{initial:!1,active:!0,children:m("div",{className:"animate-text whitespace-nowrap transition-[opacity,transform] ease-out duration-200 data-hidden:opacity-0 transform data-hidden:translate-y-2",children:a})},a)})}const Wh=Ie(null);function yy({children:t}){const e=Oe(null),n=Oe(""),i=Oe("initial"),{lastId:r}=Be(),s=ie("agent-id"),{serverUrl:o}=ua(),a=V(async u=>{const h=r.value,f=s.value;if(!h||!f){console.warn("[ConversationalAI] Cannot submit rating: missing agent_id or conversation_id");return}try{e.value=u,i.value="submitted-rating",await gh(h,{rating:u},o.value)}catch(g){console.error("[ConversationalAI] Failed to submit rating:",g)}},[]),c=V(async()=>{const u=r.value,h=s.value;if(!u||!h){console.warn("[ConversationalAI] Cannot submit feedback: missing agent_id or conversation_id");return}if(e.value===null){console.warn("[ConversationalAI] Cannot submit feedback: rating not set");return}if(n.value)try{i.value="submitted-follow-up",await gh(u,{rating:e.value,comment:n.value||void 0},o.value)}catch(f){console.error("[ConversationalAI] Failed to submit feedback:",f)}},[]),l=V(()=>{e.value=null,n.value="",i.value="initial"},[]);Ct(()=>{r.value!==null&&l()});const d=oe(()=>({rating:e,feedbackText:n,feedbackProgress:i,submitRating:a,submitFeedback:c,reset:l}),[a,c,l]);return m(Wh.Provider,{value:d,children:t})}function ba(){return et(Wh)}const Hh=Ie(null);function ky({defaultContent:t="transcript",children:e}){const n=Oe(t),i=oe(()=>{const r=n.value==="feedback"?{showHeaderBack:!0,onHeaderBack:()=>{n.value="transcript"}}:{showHeaderBack:!1};return{currentContent:n,currentConfig:r}},[n.value]);return m(Hh.Provider,{value:i,children:e})}function ya(){return et(Hh)}const Gh=(t,e)=>Array.from({length:e-t+1},(n,i)=>i+t),Cy=({isFilled:t,iconName:e})=>m("span",{className:ae("w-8 h-8 grid place-content-center",t?"text-base-primary":"text-base-border"),children:m(It,{name:e,size:"lg"})}),wy=({value:t,rating:e,hoverRating:n,onClick:i,onHover:r,onKeyDown:s,iconName:o})=>{const a=e.value!==null&&t<=e.value,c=n.value!==null&&t<=n.value,l=V(u=>{u.stopPropagation(),i(t)},[i,t]),d=V(u=>{s(u,t)},[s,t]);return m("button",{type:"button",role:"radio","aria-checked":a,"aria-label":t.toString(),onMouseEnter:()=>r(t),onClick:l,onKeyDown:d,className:ae("w-8 h-8 grid place-content-center rounded-full focus-ring transition-colors cursor-pointer",a||c?"text-base-primary":"text-base-border"),children:m(It,{name:o,size:"lg"})})},_y=({onRate:t,min:e=1,max:n=5,ariaLabel:i,icon:r="star"})=>{const s=Oe(null),o=Oe(null),a=Gh(e,n),c=V(h=>{o.value=h},[o]),l=V(()=>{o.value=null},[o]),d=V(h=>{s.value=h,t(h)},[s,t]),u=V((h,f)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),s.value=f,t(f);else if(h.key==="ArrowLeft"||h.key==="ArrowDown"){if(h.preventDefault(),f-1>=e){const g=h.currentTarget,p=g==null?void 0:g.previousElementSibling;p==null||p.focus()}}else if((h.key==="ArrowRight"||h.key==="ArrowUp")&&(h.preventDefault(),f+1<=n)){const g=h.currentTarget,p=g==null?void 0:g.nextElementSibling;p==null||p.focus()}},[s,t,e,n]);return m("div",{role:"radiogroup","aria-label":i,className:"flex no-wrap cursor-pointer",onMouseLeave:l,children:a.map(h=>m(wy,{value:h,rating:s,hoverRating:o,onClick:d,onHover:c,onKeyDown:u,iconName:r},h))})};function Kh({rating:t,min:e=1,max:n=5,icon:i="star"}){const r=Gh(e,n);return m("div",{className:"flex no-wrap",role:"img","aria-label":`Rating: ${t} out of ${n}`,children:r.map(s=>m(Cy,{isFilled:t>=s,iconName:i},s))})}function Sy({icon:t,onRate:e}){const n=Ee();return m("div",{className:"flex flex-col items-center",children:[m("div",{className:"text-sm text-base-primary font-medium",children:n.initiate_feedback}),m("div",{className:"py-4",children:m(_y,{onRate:e,ariaLabel:n.initiate_feedback,icon:t})})]})}function Ty({icon:t,rating:e,showFollowUpButton:n,onFollowUpClick:i}){const r=Ee();return m("div",{className:"flex flex-col items-center gap-3 mb-4",children:[m("div",{className:"text-sm text-base-primary font-medium",children:r.thanks_for_feedback}),m(Kh,{rating:e,min:1,max:5,icon:t}),n&&m(pt,{variant:"secondary",onClick:i,children:r.request_follow_up_feedback})]})}function xy({icon:t="star"}){const{currentContent:e}=ya(),{rating:n,feedbackProgress:i,submitRating:r}=ba(),s=i.value!=="initial"&&n.value!==null,o=V(c=>{r(c),e.value="feedback"},[r]),a=V(()=>{e.value="feedback"},[]);return s?m(Ty,{icon:t,rating:n.value??0,showFollowUpButton:i.value!=="submitted-follow-up",onFollowUpClick:a}):m(Sy,{icon:t,onRate:o})}function Ey({entry:t}){const{previewUrl:e}=pa();return m("div",{className:ae("flex gap-2.5 transition-[opacity,transform] duration-200 data-hidden:opacity-0 data-hidden:scale-75",t.role==="user"?"justify-end pl-16 origin-top-right":"pr-16 origin-top-left"),children:[t.role==="ai"&&m("img",{src:e,alt:"AI agent avatar",className:"bg-base-border shrink-0 w-5 h-5 rounded-full"}),m("div",{dir:"auto",className:ae("px-3 py-2.5 rounded-bubble text-sm min-w-0 [overflow-wrap:break-word]",t.role==="user"?"bg-accent text-accent-primary":"bg-base-active text-base-primary"),children:t.message})]})}function Py({entry:t}){const e=Ee(),{lastId:n}=Be(),i=Ab();return m("div",{className:"mt-3 px-8 flex flex-col",children:[i.value==="rating"&&m(xy,{}),m("div",{className:"text-xs text-base-subtle text-center transition-opacity duration-200 data-hidden:opacity-0",children:[t.role==="user"?e.user_ended_conversation:e.agent_ended_conversation,m("br",{}),n.value&&m("span",{className:"break-all",children:[e.conversation_id,": ",n.value]})]})]})}function Ry({entry:t}){const e=Ee(),{lastId:n}=Be();return m("div",{className:"mt-2 px-8 text-xs text-base-error text-center transition-opacity duration-200 data-hidden:opacity-0",children:[e.error_occurred,m("br",{}),t.message,n.value&&m(ge,{children:[m("br",{}),m("span",{className:"text-base-subtle break-all",children:[e.conversation_id,": ",n.value]})]})]})}function Iy({entry:t,animateIn:e}){return m(je,{initial:!e,active:!0,children:t.type==="message"?m(Ey,{entry:t}):t.type==="disconnection"?m(Py,{entry:t}):m(Ry,{entry:t})})}const Oy=16;function Dy({scrollPinned:t,transcript:e}){const n=B(null),i=B(0),r=B(null),s=B(!1),o=B(!1),a=u=>{var h;(h=n.current)==null||h.scrollTo({top:n.current.scrollHeight,behavior:u?"smooth":"instant"})},c=()=>{const u=n.current;if(!u||!s.current||o.current)return;const h=u.scrollTop,f=u.scrollHeight-u.clientHeight,g=f-h;if(Math.abs(g)<1){u.scrollTop=f,r.current=requestAnimationFrame(c);return}const p=g*.2,v=2;u.scrollTop=h+Math.max(p,v),r.current=requestAnimationFrame(c)},l=()=>{!n.current||o.current||s.current||(s.current=!0,r.current=requestAnimationFrame(c))},d=B(!0);return K(()=>(d.current=!1,a(!1),()=>{r.current&&cancelAnimationFrame(r.current)}),[]),Ct(()=>{var u;const h=e.value;if(!t.peek())return;const f=h[h.length-1];if((f==null?void 0:f.type)==="message"&&(f==null?void 0:f.role)==="ai"&&(f==null?void 0:f.isText)===!0){const g=((u=f.message)==null?void 0:u.length)||0;i.current===0&&g>0?(i.current=g,o.current=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{!o.current&&t.peek()&&(a(!1),l())})})):g>i.current&&(i.current=g,l())}else i.current=0,s.current=!1,o.current=!1,r.current&&(cancelAnimationFrame(r.current),r.current=null),a(!0)}),m("div",{ref:n,onScroll:u=>{const h=u.currentTarget.scrollTop>=u.currentTarget.scrollHeight-u.currentTarget.clientHeight-Oy;t.value=h,!h&&s.current&&(o.current=!0,s.current=!1,r.current&&(cancelAnimationFrame(r.current),r.current=null))},className:"px-4 pt-3 pb-3 grow flex flex-col gap-3 overflow-x-hidden overflow-y-auto",children:e.value.map((u,h)=>m(Iy,{entry:u,animateIn:!d.current},`${h}-${u.conversationIndex}`))})}function Jh({className:t,...e}){return m("textarea",{className:ae("px-3 py-[calc(theme(spacing.2)-1px)] border text-sm text-base-primary bg-base border-base-border rounded-input focus-ring resize-none [field-sizing:content] placeholder:text-base-subtle",t),...e})}function ka({visible:t,...e}){const n=Ee(),{isMuted:i,isMutingEnabled:r,setIsMuted:s}=Ph(),o=V(()=>{s(!i.peek())},[s]);return r.value?m(Zt,{visible:t,className:"p-1",children:m(pt,{"aria-label":n.mute_microphone,"aria-pressed":i,icon:i.value?"mic-off":"mic",onClick:o,...e})}):null}function Ca({iconOnly:t,isDisconnected:e,children:n,...i}){const{endSession:r,startSession:s}=Be(),o=Ee();return m(pt,{variant:e?"primary":"secondary",icon:e?"phone":"phone-off",onClick:e?a=>s(a.currentTarget):r,"aria-label":e?o.start_call:o.end_call,...i,children:t?void 0:n??(e?o.start_call:o.end_call)})}function Ay({showTranscript:t,scrollPinned:e}){const n=Oe(""),i=Wr(),{text_input_enabled:r}=Ae().value,s=Ee(),{isDisconnected:o,status:a,startSession:c,sendUserMessage:l,sendUserActivity:d,conversationIndex:u}=Be(),h=V(async v=>{v.preventDefault();const b=n.value.trim();b&&(e.value=!0,n.value="",o.value?await c(v.currentTarget,b):l(b))},[n,e,o,c,l]),f=V(async v=>{v.key==="Enter"&&!v.shiftKey&&await h(v)},[h]),g=V(v=>{n.value=v.currentTarget.value},[n]),p=ue(()=>!!n.value.trim());return m("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:[r&&m("div",{className:"relative grow min-w-0 flex z-1 m-1",children:[m(Jh,{rows:1,"aria-label":s.input_label,value:n,onInput:d,onChange:g,onKeyDown:f,className:"min-w-0 w-full max-h-[8lh] pr-9",placeholder:i.value?o.value&&u.value>0?s.input_placeholder_new_conversation:s.input_placeholder_text_only:s.input_placeholder}),m(je,{active:p,children:m("button",{"aria-label":s.send_message,className:"absolute right-1 bottom-1 w-7 h-7 flex items-center justify-center hover:bg-base-hover active:bg-base-active rounded-button focus-ring transition-[transform,opacity] duration-200 data-hidden:opacity-0 data-hidden:scale-90",onClick:h,children:m(It,{name:"send"})})})]}),m("div",{className:"flex h-11 items-center",children:[m(ka,{visible:!i.value&&!o.value}),m(Zt,{visible:!o.value||t,className:"p-1",children:m(Ca,{iconOnly:!o.value,isDisconnected:o.value,disabled:a.value==="disconnecting"||a.value==="connecting",children:s.new_call})})]})]})}function My(){const t=Ee(),{rating:e,feedbackText:n}=ba(),i=V(r=>{n.value=r.currentTarget.value},[]);return m("div",{className:"grow flex flex-col overflow-y-auto overflow-x-hidden px-4",children:m("div",{className:"flex flex-col gap-8 min-h-full pt-4 pb-2",children:[m("div",{className:"flex flex-col items-center justify-center gap-3",children:[m(my,{orbColor:"var(--el-base-subtle)",circleBackgroundColor:"var(--el-base)",starColor:"var(--el-base-primary)",className:"w-20 h-22"}),e.value!==null&&m(Kh,{rating:e.value,min:1,max:5}),m("div",{className:"text-center",children:[m("p",{className:"text-sm text-base-primary font-medium",children:t.thanks_for_feedback}),m("p",{className:"text-sm text-base-subtle",children:t.thanks_for_feedback_details})]})]}),m(Jh,{className:"w-full min-h-[6lh]",placeholder:t.follow_up_feedback_placeholder,rows:6,value:n,onInput:i})]})})}function Ny(){const t=Ee(),{currentContent:e}=ya(),{submitFeedback:n}=ba(),i=V(()=>{n(),e.value="transcript"},[n]);return m("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:m(pt,{variant:"primary",onClick:i,children:t.submit})})}function Yh(t,[e,n]){return Math.min(n,Math.max(e,t))}function Pe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t==null||t(i),n===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function wa(t,e=[]){let n=[];function i(s,o){const a=Ie(o),c=n.length;n=[...n,o];const l=u=>{var h;const{scope:f,children:g,...p}=u,v=((h=f==null?void 0:f[t])==null?void 0:h[c])||a,b=oe(()=>p,Object.values(p));return m(v.Provider,{value:b,children:g})};l.displayName=s+"Provider";function d(u,h){var f;const g=((f=h==null?void 0:h[t])==null?void 0:f[c])||a,p=sn(g);if(p)return p;if(o!==void 0)return o;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[l,d]}const r=()=>{const s=n.map(o=>Ie(o));return function(o){const a=(o==null?void 0:o[t])||s;return oe(()=>({[`__scope${t}`]:{...o,[t]:a}}),[o,a])}};return r.scopeName=t,[i,Ly(r,...e)]}function Ly(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const i=t.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(r){const s=i.reduce((o,{useScope:a,scopeName:c})=>{const l=a(r)[`__scope${c}`];return{...o,...l}},{});return oe(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}function Uy(t){const e=t+"CollectionProvider",[n,i]=wa(e),[r,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=p=>{const{scope:v,children:b}=p,k=Vt.useRef(null),w=Vt.useRef(new Map).current;return m(r,{scope:v,itemMap:w,collectionRef:k,children:b})};o.displayName=e;const a=t+"CollectionSlot",c=Vi(a),l=Vt.forwardRef((p,v)=>{const{scope:b,children:k}=p,w=s(a,b),y=Fe(v,w.collectionRef);return m(c,{ref:y,children:k})});l.displayName=a;const d=t+"CollectionItemSlot",u="data-radix-collection-item",h=Vi(d),f=Vt.forwardRef((p,v)=>{const{scope:b,children:k,...w}=p,y=Vt.useRef(null),_=Fe(v,y),S=s(d,b);return Vt.useEffect(()=>(S.itemMap.set(y,{ref:y,...w}),()=>void S.itemMap.delete(y))),m(h,{[u]:"",ref:_,children:k})});f.displayName=d;function g(p){const v=s(t+"CollectionConsumer",p);return Vt.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const k=Array.from(b.querySelectorAll(`[${u}]`));return Array.from(v.itemMap.values()).sort((w,y)=>k.indexOf(w.ref.current)-k.indexOf(y.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:o,Slot:l,ItemSlot:f},g,i]}var Fy=Ie(void 0);function By(t){const e=sn(Fy);return t||e||"ltr"}var jy=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Se=jy.reduce((t,e)=>{const n=Vi(`Primitive.${e}`),i=Q((r,s)=>{const{asChild:o,...a}=r,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m(c,{...a,ref:s})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{});function Vy(t,e){t&&ir(()=>t.dispatchEvent(e))}function Mn(t){const e=B(t);return K(()=>{e.current=t}),oe(()=>(...n)=>{var i;return(i=e.current)==null?void 0:i.call(e,...n)},[])}function qy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t);K(()=>{const i=r=>{r.key==="Escape"&&n(r)};return e.addEventListener("keydown",i,{capture:!0}),()=>e.removeEventListener("keydown",i,{capture:!0})},[n,e])}var $y="DismissableLayer",_a="dismissableLayer.update",zy="dismissableLayer.pointerDownOutside",Wy="dismissableLayer.focusOutside",Xh,Qh=Ie({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Zh=Q((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...c}=t,l=sn(Qh),[d,u]=q(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=q({}),g=Fe(e,x=>u(x)),p=Array.from(l.layers),[v]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=p.indexOf(v),k=d?p.indexOf(d):-1,w=l.layersWithOutsidePointerEventsDisabled.size>0,y=k>=b,_=Ky(x=>{const I=x.target,R=[...l.branches].some(D=>D.contains(I));!y||R||(r==null||r(x),o==null||o(x),x.defaultPrevented||a==null||a())},h),S=Jy(x=>{const I=x.target;[...l.branches].some(R=>R.contains(I))||(s==null||s(x),o==null||o(x),x.defaultPrevented||a==null||a())},h);return qy(x=>{k===l.layers.size-1&&(i==null||i(x),!x.defaultPrevented&&a&&(x.preventDefault(),a()))},h),K(()=>{if(d)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(Xh=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(d)),l.layers.add(d),ef(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=Xh)}},[d,h,n,l]),K(()=>()=>{d&&(l.layers.delete(d),l.layersWithOutsidePointerEventsDisabled.delete(d),ef())},[d,l]),K(()=>{const x=()=>f({});return document.addEventListener(_a,x),()=>document.removeEventListener(_a,x)},[]),m(Se.div,{...c,ref:g,style:{pointerEvents:w?y?"auto":"none":void 0,...t.style},onFocusCapture:Pe(t.onFocusCapture,S.onFocusCapture),onBlurCapture:Pe(t.onBlurCapture,S.onBlurCapture),onPointerDownCapture:Pe(t.onPointerDownCapture,_.onPointerDownCapture)})});Zh.displayName=$y;var Hy="DismissableLayerBranch",Gy=Q((t,e)=>{const n=sn(Qh),i=B(null),r=Fe(e,i);return K(()=>{const s=i.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),m(Se.div,{...t,ref:r})});Gy.displayName=Hy;function Ky(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1),r=B(()=>{});return K(()=>{const s=a=>{if(a.target&&!i.current){let c=function(){tf(zy,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",r.current),r.current=c,e.addEventListener("click",r.current,{once:!0})):c()}else e.removeEventListener("click",r.current);i.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",s),e.removeEventListener("click",r.current)}},[e,n]),{onPointerDownCapture:()=>i.current=!0}}function Jy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1);return K(()=>{const r=s=>{s.target&&!i.current&&tf(Wy,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function ef(){const t=new CustomEvent(_a);document.dispatchEvent(t)}function tf(t,e,n,{discrete:i}){const r=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&r.addEventListener(t,e,{once:!0}),i?Vy(r,s):r.dispatchEvent(s)}var Sa=0;function Yy(){K(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??nf()),document.body.insertAdjacentElement("beforeend",t[1]??nf()),Sa++,()=>{Sa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Sa--}},[])}function nf(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Ta="focusScope.autoFocusOnMount",xa="focusScope.autoFocusOnUnmount",rf={bubbles:!1,cancelable:!0},Xy="FocusScope",sf=Q((t,e)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:s,...o}=t,[a,c]=q(null),l=Mn(r),d=Mn(s),u=B(null),h=Fe(e,p=>c(p)),f=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;K(()=>{if(i){let p=function(w){if(f.paused||!a)return;const y=w.target;a.contains(y)?u.current=y:bn(u.current,{select:!0})},v=function(w){if(f.paused||!a)return;const y=w.relatedTarget;y!==null&&(a.contains(y)||bn(u.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const y of w)y.removedNodes.length>0&&bn(a)};document.addEventListener("focusin",p),document.addEventListener("focusout",v);const k=new MutationObserver(b);return a&&k.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",v),k.disconnect()}}},[i,a,f.paused]),K(()=>{if(a){cf.add(f);const p=document.activeElement;if(!a.contains(p)){const v=new CustomEvent(Ta,rf);a.addEventListener(Ta,l),a.dispatchEvent(v),v.defaultPrevented||(Qy(ik(of(a)),{select:!0}),document.activeElement===p&&bn(a))}return()=>{a.removeEventListener(Ta,l),setTimeout(()=>{const v=new CustomEvent(xa,rf);a.addEventListener(xa,d),a.dispatchEvent(v),v.defaultPrevented||bn(p??document.body,{select:!0}),a.removeEventListener(xa,d),cf.remove(f)},0)}}},[a,l,d,f]);const g=V(p=>{if(!n&&!i||f.paused)return;const v=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(v&&b){const k=p.currentTarget,[w,y]=Zy(k);w&&y?!p.shiftKey&&b===y?(p.preventDefault(),n&&bn(w,{select:!0})):p.shiftKey&&b===w&&(p.preventDefault(),n&&bn(y,{select:!0})):b===k&&p.preventDefault()}},[n,i,f.paused]);return m(Se.div,{tabIndex:-1,...o,ref:h,onKeyDown:g})});sf.displayName=Xy;function Qy(t,{select:e=!1}={}){const n=document.activeElement;for(const i of t)if(bn(i,{select:e}),document.activeElement!==n)return}function Zy(t){const e=of(t),n=af(e,t),i=af(e.reverse(),t);return[n,i]}function of(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const r=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||r?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function af(t,e){for(const n of t)if(!ek(n,{upTo:e}))return n}function ek(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function tk(t){return t instanceof HTMLInputElement&&"select"in t}function bn(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&tk(t)&&e&&t.select()}}var cf=nk();function nk(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=lf(t,e),t.unshift(e)},remove(e){var n;t=lf(t,e),(n=t[0])==null||n.resume()}}}function lf(t,e){const n=[...t],i=n.indexOf(e);return i!==-1&&n.splice(i,1),n}function ik(t){return t.filter(e=>e.tagName!=="A")}var Ke=globalThis!=null&&globalThis.document?Bt:()=>{},rk=tl[" useId ".trim().toString()]||(()=>{}),sk=0;function Ea(t){const[e,n]=q(rk());return Ke(()=>{n(i=>i??String(sk++))},[t]),e?`radix-${e}`:""}const ok=["top","right","bottom","left"],yn=Math.min,tt=Math.max,Gr=Math.round,Kr=Math.floor,Ot=t=>({x:t,y:t}),ak={left:"right",right:"left",bottom:"top",top:"bottom"},ck={start:"end",end:"start"};function Pa(t,e,n){return tt(t,yn(e,n))}function en(t,e){return typeof t=="function"?t(e):t}function tn(t){return t.split("-")[0]}function oi(t){return t.split("-")[1]}function Ra(t){return t==="x"?"y":"x"}function Ia(t){return t==="y"?"height":"width"}const lk=new Set(["top","bottom"]);function Dt(t){return lk.has(tn(t))?"y":"x"}function Oa(t){return Ra(Dt(t))}function dk(t,e,n){n===void 0&&(n=!1);const i=oi(t),r=Oa(t),s=Ia(r);let o=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=Jr(o)),[o,Jr(o)]}function uk(t){const e=Jr(t);return[Da(t),e,Da(e)]}function Da(t){return t.replace(/start|end/g,e=>ck[e])}const df=["left","right"],uf=["right","left"],hk=["top","bottom"],fk=["bottom","top"];function pk(t,e,n){switch(t){case"top":case"bottom":return n?e?uf:df:e?df:uf;case"left":case"right":return e?hk:fk;default:return[]}}function mk(t,e,n,i){const r=oi(t);let s=pk(tn(t),n==="start",i);return r&&(s=s.map(o=>o+"-"+r),e&&(s=s.concat(s.map(Da)))),s}function Jr(t){return t.replace(/left|right|bottom|top/g,e=>ak[e])}function gk(t){return{top:0,right:0,bottom:0,left:0,...t}}function hf(t){return typeof t!="number"?gk(t):{top:t,right:t,bottom:t,left:t}}function Yr(t){const{x:e,y:n,width:i,height:r}=t;return{width:i,height:r,top:n,left:e,right:e+i,bottom:n+r,x:e,y:n}}function ff(t,e,n){let{reference:i,floating:r}=t;const s=Dt(e),o=Oa(e),a=Ia(o),c=tn(e),l=s==="y",d=i.x+i.width/2-r.width/2,u=i.y+i.height/2-r.height/2,h=i[a]/2-r[a]/2;let f;switch(c){case"top":f={x:d,y:i.y-r.height};break;case"bottom":f={x:d,y:i.y+i.height};break;case"right":f={x:i.x+i.width,y:u};break;case"left":f={x:i.x-r.width,y:u};break;default:f={x:i.x,y:i.y}}switch(oi(e)){case"start":f[o]-=h*(n&&l?-1:1);break;case"end":f[o]+=h*(n&&l?-1:1);break}return f}const vk=async(t,e,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:s=[],platform:o}=n,a=s.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:t,floating:e,strategy:r}),{x:d,y:u}=ff(l,i,c),h=i,f={},g=0;for(let p=0;p<a.length;p++){const{name:v,fn:b}=a[p],{x:k,y:w,data:y,reset:_}=await b({x:d,y:u,initialPlacement:i,placement:h,strategy:r,middlewareData:f,rects:l,platform:o,elements:{reference:t,floating:e}});d=k??d,u=w??u,f={...f,[v]:{...f[v],...y}},_&&g<=50&&(g++,typeof _=="object"&&(_.placement&&(h=_.placement),_.rects&&(l=_.rects===!0?await o.getElementRects({reference:t,floating:e,strategy:r}):_.rects),{x:d,y:u}=ff(l,h,c)),p=-1)}return{x:d,y:u,placement:h,strategy:r,middlewareData:f}};async function qi(t,e){var n;e===void 0&&(e={});const{x:i,y:r,platform:s,rects:o,elements:a,strategy:c}=t,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:f=0}=en(e,t),g=hf(f),p=a[h?u==="floating"?"reference":"floating":u],v=Yr(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(p)))==null||n?p:p.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),b=u==="floating"?{x:i,y:r,width:o.floating.width,height:o.floating.height}:o.reference,k=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),w=await(s.isElement==null?void 0:s.isElement(k))?await(s.getScale==null?void 0:s.getScale(k))||{x:1,y:1}:{x:1,y:1},y=Yr(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:k,strategy:c}):b);return{top:(v.top-y.top+g.top)/w.y,bottom:(y.bottom-v.bottom+g.bottom)/w.y,left:(v.left-y.left+g.left)/w.x,right:(y.right-v.right+g.right)/w.x}}const bk=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:i,placement:r,rects:s,platform:o,elements:a,middlewareData:c}=e,{element:l,padding:d=0}=en(t,e)||{};if(l==null)return{};const u=hf(d),h={x:n,y:i},f=Oa(r),g=Ia(f),p=await o.getDimensions(l),v=f==="y",b=v?"top":"left",k=v?"bottom":"right",w=v?"clientHeight":"clientWidth",y=s.reference[g]+s.reference[f]-h[f]-s.floating[g],_=h[f]-s.reference[f],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let x=S?S[w]:0;(!x||!await(o.isElement==null?void 0:o.isElement(S)))&&(x=a.floating[w]||s.floating[g]);const I=y/2-_/2,R=x/2-p[g]/2-1,D=yn(u[b],R),M=yn(u[k],R),U=D,j=x-p[g]-M,$=x/2-p[g]/2+I,F=Pa(U,$,j),G=!c.arrow&&oi(r)!=null&&$!==F&&s.reference[g]/2-($<U?D:M)-p[g]/2<0,Y=G?$<U?$-U:$-j:0;return{[f]:h[f]+Y,data:{[f]:F,centerOffset:$-F-Y,...G&&{alignmentOffset:Y}},reset:G}}}),yk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,i;const{placement:r,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:l}=e,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:p=!0,...v}=en(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const b=tn(r),k=Dt(a),w=tn(a)===a,y=await(c.isRTL==null?void 0:c.isRTL(l.floating)),_=h||(w||!p?[Jr(a)]:uk(a)),S=g!=="none";!h&&S&&_.push(...mk(a,p,g,y));const x=[a,..._],I=await qi(e,v),R=[];let D=((i=s.flip)==null?void 0:i.overflows)||[];if(d&&R.push(I[b]),u){const $=dk(r,o,y);R.push(I[$[0]],I[$[1]])}if(D=[...D,{placement:r,overflows:R}],!R.every($=>$<=0)){var M,U;const $=(((M=s.flip)==null?void 0:M.index)||0)+1,F=x[$];if(F&&(!(u==="alignment"&&k!==Dt(F))||D.every(Y=>Dt(Y.placement)===k?Y.overflows[0]>0:!0)))return{data:{index:$,overflows:D},reset:{placement:F}};let G=(U=D.filter(Y=>Y.overflows[0]<=0).sort((Y,W)=>Y.overflows[1]-W.overflows[1])[0])==null?void 0:U.placement;if(!G)switch(f){case"bestFit":{var j;const Y=(j=D.filter(W=>{if(S){const ee=Dt(W.placement);return ee===k||ee==="y"}return!0}).map(W=>[W.placement,W.overflows.filter(ee=>ee>0).reduce((ee,we)=>ee+we,0)]).sort((W,ee)=>W[1]-ee[1])[0])==null?void 0:j[0];Y&&(G=Y);break}case"initialPlacement":G=a;break}if(r!==G)return{reset:{placement:G}}}return{}}}};function pf(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function mf(t){return ok.some(e=>t[e]>=0)}const kk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:i="referenceHidden",...r}=en(t,e);switch(i){case"referenceHidden":{const s=await qi(e,{...r,elementContext:"reference"}),o=pf(s,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:mf(o)}}}case"escaped":{const s=await qi(e,{...r,altBoundary:!0}),o=pf(s,n.floating);return{data:{escapedOffsets:o,escaped:mf(o)}}}default:return{}}}}},gf=new Set(["left","top"]);async function Ck(t,e){const{placement:n,platform:i,elements:r}=t,s=await(i.isRTL==null?void 0:i.isRTL(r.floating)),o=tn(n),a=oi(n),c=Dt(n)==="y",l=gf.has(o)?-1:1,d=s&&c?-1:1,u=en(e,t);let{mainAxis:h,crossAxis:f,alignmentAxis:g}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&typeof g=="number"&&(f=a==="end"?g*-1:g),c?{x:f*d,y:h*l}:{x:h*l,y:f*d}}const wk=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:r,y:s,placement:o,middlewareData:a}=e,c=await Ck(e,t);return o===((n=a.offset)==null?void 0:n.placement)&&(i=a.arrow)!=null&&i.alignmentOffset?{}:{x:r+c.x,y:s+c.y,data:{...c,placement:o}}}}},_k=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:r}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:v=>{let{x:b,y:k}=v;return{x:b,y:k}}},...c}=en(t,e),l={x:n,y:i},d=await qi(e,c),u=Dt(tn(r)),h=Ra(u);let f=l[h],g=l[u];if(s){const v=h==="y"?"top":"left",b=h==="y"?"bottom":"right",k=f+d[v],w=f-d[b];f=Pa(k,f,w)}if(o){const v=u==="y"?"top":"left",b=u==="y"?"bottom":"right",k=g+d[v],w=g-d[b];g=Pa(k,g,w)}const p=a.fn({...e,[h]:f,[u]:g});return{...p,data:{x:p.x-n,y:p.y-i,enabled:{[h]:s,[u]:o}}}}}},Sk=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:r,rects:s,middlewareData:o}=e,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=en(t,e),d={x:n,y:i},u=Dt(r),h=Ra(u);let f=d[h],g=d[u];const p=en(a,e),v=typeof p=="number"?{mainAxis:p,crossAxis:0}:{mainAxis:0,crossAxis:0,...p};if(c){const w=h==="y"?"height":"width",y=s.reference[h]-s.floating[w]+v.mainAxis,_=s.reference[h]+s.reference[w]-v.mainAxis;f<y?f=y:f>_&&(f=_)}if(l){var b,k;const w=h==="y"?"width":"height",y=gf.has(tn(r)),_=s.reference[u]-s.floating[w]+(y&&((b=o.offset)==null?void 0:b[u])||0)+(y?0:v.crossAxis),S=s.reference[u]+s.reference[w]+(y?0:((k=o.offset)==null?void 0:k[u])||0)-(y?v.crossAxis:0);g<_?g=_:g>S&&(g=S)}return{[h]:f,[u]:g}}}},Tk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:r,rects:s,platform:o,elements:a}=e,{apply:c=()=>{},...l}=en(t,e),d=await qi(e,l),u=tn(r),h=oi(r),f=Dt(r)==="y",{width:g,height:p}=s.floating;let v,b;u==="top"||u==="bottom"?(v=u,b=h===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(b=u,v=h==="end"?"top":"bottom");const k=p-d.top-d.bottom,w=g-d.left-d.right,y=yn(p-d[v],k),_=yn(g-d[b],w),S=!e.middlewareData.shift;let x=y,I=_;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(I=w),(i=e.middlewareData.shift)!=null&&i.enabled.y&&(x=k),S&&!h){const D=tt(d.left,0),M=tt(d.right,0),U=tt(d.top,0),j=tt(d.bottom,0);f?I=g-2*(D!==0||M!==0?D+M:tt(d.left,d.right)):x=p-2*(U!==0||j!==0?U+j:tt(d.top,d.bottom))}await c({...e,availableWidth:I,availableHeight:x});const R=await o.getDimensions(a.floating);return g!==R.width||p!==R.height?{reset:{rects:!0}}:{}}}};function Xr(){return typeof window<"u"}function ai(t){return vf(t)?(t.nodeName||"").toLowerCase():"#document"}function nt(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function At(t){var e;return(e=(vf(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function vf(t){return Xr()?t instanceof Node||t instanceof nt(t).Node:!1}function mt(t){return Xr()?t instanceof Element||t instanceof nt(t).Element:!1}function Mt(t){return Xr()?t instanceof HTMLElement||t instanceof nt(t).HTMLElement:!1}function bf(t){return!Xr()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof nt(t).ShadowRoot}const xk=new Set(["inline","contents"]);function $i(t){const{overflow:e,overflowX:n,overflowY:i,display:r}=gt(t);return/auto|scroll|overlay|hidden|clip/.test(e+i+n)&&!xk.has(r)}const Ek=new Set(["table","td","th"]);function Pk(t){return Ek.has(ai(t))}const Rk=[":popover-open",":modal"];function Qr(t){return Rk.some(e=>{try{return t.matches(e)}catch{return!1}})}const Ik=["transform","translate","scale","rotate","perspective"],Ok=["transform","translate","scale","rotate","perspective","filter"],Dk=["paint","layout","strict","content"];function Aa(t){const e=Ma(),n=mt(t)?gt(t):t;return Ik.some(i=>n[i]?n[i]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||Ok.some(i=>(n.willChange||"").includes(i))||Dk.some(i=>(n.contain||"").includes(i))}function Ak(t){let e=kn(t);for(;Mt(e)&&!ci(e);){if(Aa(e))return e;if(Qr(e))return null;e=kn(e)}return null}function Ma(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Mk=new Set(["html","body","#document"]);function ci(t){return Mk.has(ai(t))}function gt(t){return nt(t).getComputedStyle(t)}function Zr(t){return mt(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function kn(t){if(ai(t)==="html")return t;const e=t.assignedSlot||t.parentNode||bf(t)&&t.host||At(t);return bf(e)?e.host:e}function yf(t){const e=kn(t);return ci(e)?t.ownerDocument?t.ownerDocument.body:t.body:Mt(e)&&$i(e)?e:yf(e)}function zi(t,e,n){var i;e===void 0&&(e=[]),n===void 0&&(n=!0);const r=yf(t),s=r===((i=t.ownerDocument)==null?void 0:i.body),o=nt(r);if(s){const a=Na(o);return e.concat(o,o.visualViewport||[],$i(r)?r:[],a&&n?zi(a):[])}return e.concat(r,zi(r,[],n))}function Na(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function kf(t){const e=gt(t);let n=parseFloat(e.width)||0,i=parseFloat(e.height)||0;const r=Mt(t),s=r?t.offsetWidth:n,o=r?t.offsetHeight:i,a=Gr(n)!==s||Gr(i)!==o;return a&&(n=s,i=o),{width:n,height:i,$:a}}function La(t){return mt(t)?t:t.contextElement}function li(t){const e=La(t);if(!Mt(e))return Ot(1);const n=e.getBoundingClientRect(),{width:i,height:r,$:s}=kf(e);let o=(s?Gr(n.width):n.width)/i,a=(s?Gr(n.height):n.height)/r;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const Nk=Ot(0);function Cf(t){const e=nt(t);return!Ma()||!e.visualViewport?Nk:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function Lk(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==nt(t)?!1:e}function Nn(t,e,n,i){e===void 0&&(e=!1),n===void 0&&(n=!1);const r=t.getBoundingClientRect(),s=La(t);let o=Ot(1);e&&(i?mt(i)&&(o=li(i)):o=li(t));const a=Lk(s,n,i)?Cf(s):Ot(0);let c=(r.left+a.x)/o.x,l=(r.top+a.y)/o.y,d=r.width/o.x,u=r.height/o.y;if(s){const h=nt(s),f=i&&mt(i)?nt(i):i;let g=h,p=Na(g);for(;p&&i&&f!==g;){const v=li(p),b=p.getBoundingClientRect(),k=gt(p),w=b.left+(p.clientLeft+parseFloat(k.paddingLeft))*v.x,y=b.top+(p.clientTop+parseFloat(k.paddingTop))*v.y;c*=v.x,l*=v.y,d*=v.x,u*=v.y,c+=w,l+=y,g=nt(p),p=Na(g)}}return Yr({width:d,height:u,x:c,y:l})}function Ua(t,e){const n=Zr(t).scrollLeft;return e?e.left+n:Nn(At(t)).left+n}function wf(t,e,n){n===void 0&&(n=!1);const i=t.getBoundingClientRect(),r=i.left+e.scrollLeft-(n?0:Ua(t,i)),s=i.top+e.scrollTop;return{x:r,y:s}}function Uk(t){let{elements:e,rect:n,offsetParent:i,strategy:r}=t;const s=r==="fixed",o=At(i),a=e?Qr(e.floating):!1;if(i===o||a&&s)return n;let c={scrollLeft:0,scrollTop:0},l=Ot(1);const d=Ot(0),u=Mt(i);if((u||!u&&!s)&&((ai(i)!=="body"||$i(o))&&(c=Zr(i)),Mt(i))){const f=Nn(i);l=li(i),d.x=f.x+i.clientLeft,d.y=f.y+i.clientTop}const h=o&&!u&&!s?wf(o,c,!0):Ot(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+h.x,y:n.y*l.y-c.scrollTop*l.y+d.y+h.y}}function Fk(t){return Array.from(t.getClientRects())}function Bk(t){const e=At(t),n=Zr(t),i=t.ownerDocument.body,r=tt(e.scrollWidth,e.clientWidth,i.scrollWidth,i.clientWidth),s=tt(e.scrollHeight,e.clientHeight,i.scrollHeight,i.clientHeight);let o=-n.scrollLeft+Ua(t);const a=-n.scrollTop;return gt(i).direction==="rtl"&&(o+=tt(e.clientWidth,i.clientWidth)-r),{width:r,height:s,x:o,y:a}}function jk(t,e){const n=nt(t),i=At(t),r=n.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(r){s=r.width,o=r.height;const l=Ma();(!l||l&&e==="fixed")&&(a=r.offsetLeft,c=r.offsetTop)}return{width:s,height:o,x:a,y:c}}const Vk=new Set(["absolute","fixed"]);function qk(t,e){const n=Nn(t,!0,e==="fixed"),i=n.top+t.clientTop,r=n.left+t.clientLeft,s=Mt(t)?li(t):Ot(1),o=t.clientWidth*s.x,a=t.clientHeight*s.y,c=r*s.x,l=i*s.y;return{width:o,height:a,x:c,y:l}}function _f(t,e,n){let i;if(e==="viewport")i=jk(t,n);else if(e==="document")i=Bk(At(t));else if(mt(e))i=qk(e,n);else{const r=Cf(t);i={x:e.x-r.x,y:e.y-r.y,width:e.width,height:e.height}}return Yr(i)}function Sf(t,e){const n=kn(t);return n===e||!mt(n)||ci(n)?!1:gt(n).position==="fixed"||Sf(n,e)}function $k(t,e){const n=e.get(t);if(n)return n;let i=zi(t,[],!1).filter(a=>mt(a)&&ai(a)!=="body"),r=null;const s=gt(t).position==="fixed";let o=s?kn(t):t;for(;mt(o)&&!ci(o);){const a=gt(o),c=Aa(o);!c&&a.position==="fixed"&&(r=null),(s?!c&&!r:!c&&a.position==="static"&&r&&Vk.has(r.position)||$i(o)&&!c&&Sf(t,o))?i=i.filter(l=>l!==o):r=a,o=kn(o)}return e.set(t,i),i}function zk(t){let{element:e,boundary:n,rootBoundary:i,strategy:r}=t;const s=[...n==="clippingAncestors"?Qr(e)?[]:$k(e,this._c):[].concat(n),i],o=s[0],a=s.reduce((c,l)=>{const d=_f(e,l,r);return c.top=tt(d.top,c.top),c.right=yn(d.right,c.right),c.bottom=yn(d.bottom,c.bottom),c.left=tt(d.left,c.left),c},_f(e,o,r));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}}function Wk(t){const{width:e,height:n}=kf(t);return{width:e,height:n}}function Hk(t,e,n){const i=Mt(e),r=At(e),s=n==="fixed",o=Nn(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const c=Ot(0);function l(){c.x=Ua(r)}if(i||!i&&!s)if((ai(e)!=="body"||$i(r))&&(a=Zr(e)),i){const f=Nn(e,!0,s,e);c.x=f.x+e.clientLeft,c.y=f.y+e.clientTop}else r&&l();s&&!i&&r&&l();const d=r&&!i&&!s?wf(r,a):Ot(0),u=o.left+a.scrollLeft-c.x-d.x,h=o.top+a.scrollTop-c.y-d.y;return{x:u,y:h,width:o.width,height:o.height}}function Fa(t){return gt(t).position==="static"}function Tf(t,e){if(!Mt(t)||gt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return At(t)===n&&(n=n.ownerDocument.body),n}function xf(t,e){const n=nt(t);if(Qr(t))return n;if(!Mt(t)){let r=kn(t);for(;r&&!ci(r);){if(mt(r)&&!Fa(r))return r;r=kn(r)}return n}let i=Tf(t,e);for(;i&&Pk(i)&&Fa(i);)i=Tf(i,e);return i&&ci(i)&&Fa(i)&&!Aa(i)?n:i||Ak(t)||n}const Gk=async function(t){const e=this.getOffsetParent||xf,n=this.getDimensions,i=await n(t.floating);return{reference:Hk(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function Kk(t){return gt(t).direction==="rtl"}const Jk={convertOffsetParentRelativeRectToViewportRelativeRect:Uk,getDocumentElement:At,getClippingRect:zk,getOffsetParent:xf,getElementRects:Gk,getClientRects:Fk,getDimensions:Wk,getScale:li,isElement:mt,isRTL:Kk};function Ef(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function Yk(t,e){let n=null,i;const r=At(t);function s(){var a;clearTimeout(i),(a=n)==null||a.disconnect(),n=null}function o(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const l=t.getBoundingClientRect(),{left:d,top:u,width:h,height:f}=l;if(a||e(),!h||!f)return;const g=Kr(u),p=Kr(r.clientWidth-(d+h)),v=Kr(r.clientHeight-(u+f)),b=Kr(d),k={rootMargin:-g+"px "+-p+"px "+-v+"px "+-b+"px",threshold:tt(0,yn(1,c))||1};let w=!0;function y(_){const S=_[0].intersectionRatio;if(S!==c){if(!w)return o();S?o(!1,S):i=setTimeout(()=>{o(!1,1e-7)},1e3)}S===1&&!Ef(l,t.getBoundingClientRect())&&o(),w=!1}try{n=new IntersectionObserver(y,{...k,root:r.ownerDocument})}catch{n=new IntersectionObserver(y,k)}n.observe(t)}return o(!0),s}function Xk(t,e,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=i,l=La(t),d=r||s?[...l?zi(l):[],...zi(e)]:[];d.forEach(b=>{r&&b.addEventListener("scroll",n,{passive:!0}),s&&b.addEventListener("resize",n)});const u=l&&a?Yk(l,n):null;let h=-1,f=null;o&&(f=new ResizeObserver(b=>{let[k]=b;k&&k.target===l&&f&&(f.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(e)})),n()}),l&&!c&&f.observe(l),f.observe(e));let g,p=c?Nn(t):null;c&&v();function v(){const b=Nn(t);p&&!Ef(p,b)&&n(),p=b,g=requestAnimationFrame(v)}return n(),()=>{var b;d.forEach(k=>{r&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),u==null||u(),(b=f)==null||b.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const Qk=wk,Zk=_k,eC=yk,tC=Tk,nC=kk,Pf=bk,iC=Sk,rC=(t,e,n)=>{const i=new Map,r={platform:Jk,...n},s={...r.platform,_c:i};return vk(t,e,{...r,platform:s})};var sC=typeof document<"u",oC=function(){},es=sC?Bt:oC;function ts(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,i,r;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!ts(t[i],e[i]))return!1;return!0}if(r=Object.keys(t),n=r.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!{}.hasOwnProperty.call(e,r[i]))return!1;for(i=n;i--!==0;){const s=r[i];if(!(s==="_owner"&&t.$$typeof)&&!ts(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function Rf(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function If(t,e){const n=Rf(t);return Math.round(e*n)/n}function Ba(t){const e=B(t);return es(()=>{e.current=t}),e}function aC(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:c,open:l}=t,[d,u]=q({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=q(i);ts(h,i)||f(i);const[g,p]=q(null),[v,b]=q(null),k=V(W=>{W!==S.current&&(S.current=W,p(W))},[]),w=V(W=>{W!==x.current&&(x.current=W,b(W))},[]),y=s||g,_=o||v,S=B(null),x=B(null),I=B(d),R=c!=null,D=Ba(c),M=Ba(r),U=Ba(l),j=V(()=>{if(!S.current||!x.current)return;const W={placement:e,strategy:n,middleware:h};M.current&&(W.platform=M.current),rC(S.current,x.current,W).then(ee=>{const we={...ee,isPositioned:U.current!==!1};$.current&&!ts(I.current,we)&&(I.current=we,ir(()=>{u(we)}))})},[h,e,n,M,U]);es(()=>{l===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,u(W=>({...W,isPositioned:!1})))},[l]);const $=B(!1);es(()=>($.current=!0,()=>{$.current=!1}),[]),es(()=>{if(y&&(S.current=y),_&&(x.current=_),y&&_){if(D.current)return D.current(y,_,j);j()}},[y,_,j,D,R]);const F=oe(()=>({reference:S,floating:x,setReference:k,setFloating:w}),[k,w]),G=oe(()=>({reference:y,floating:_}),[y,_]),Y=oe(()=>{const W={position:n,left:0,top:0};if(!G.floating)return W;const ee=If(G.floating,d.x),we=If(G.floating,d.y);return a?{...W,transform:"translate("+ee+"px, "+we+"px)",...Rf(G.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:we}},[n,a,G.floating,d.x,d.y]);return oe(()=>({...d,update:j,refs:F,elements:G,floatingStyles:Y}),[d,j,F,G,Y])}const cC=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:i,padding:r}=typeof t=="function"?t(n):t;return i&&e(i)?i.current!=null?Pf({element:i.current,padding:r}).fn(n):{}:i?Pf({element:i,padding:r}).fn(n):{}}}},lC=(t,e)=>({...Qk(t),options:[t,e]}),dC=(t,e)=>({...Zk(t),options:[t,e]}),uC=(t,e)=>({...iC(t),options:[t,e]}),hC=(t,e)=>({...eC(t),options:[t,e]}),fC=(t,e)=>({...tC(t),options:[t,e]}),pC=(t,e)=>({...nC(t),options:[t,e]}),mC=(t,e)=>({...cC(t),options:[t,e]});var gC="Arrow",Of=Q((t,e)=>{const{children:n,width:i=10,height:r=5,...s}=t;return m(Se.svg,{...s,ref:e,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:m("polygon",{points:"0,0 30,0 15,10"})})});Of.displayName=gC;var vC=Of;function bC(t){const[e,n]=q(void 0);return Ke(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const i=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const s=r[0];let o,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return i.observe(t,{box:"border-box"}),()=>i.unobserve(t)}else n(void 0)},[t]),e}var ja="Popper",[Df,Af]=wa(ja),[yC,Mf]=Df(ja),Nf=t=>{const{__scopePopper:e,children:n}=t,[i,r]=q(null);return m(yC,{scope:e,anchor:i,onAnchorChange:r,children:n})};Nf.displayName=ja;var Lf="PopperAnchor",Uf=Q((t,e)=>{const{__scopePopper:n,virtualRef:i,...r}=t,s=Mf(Lf,n),o=B(null),a=Fe(e,o),c=B(null);return K(()=>{const l=c.current;c.current=(i==null?void 0:i.current)||o.current,l!==c.current&&s.onAnchorChange(c.current)}),i?null:m(Se.div,{...r,ref:a})});Uf.displayName=Lf;var Va="PopperContent",[kC,CC]=Df(Va),Ff=Q((t,e)=>{var n,i,r,s,o,a;const{__scopePopper:c,side:l="bottom",sideOffset:d=0,align:u="center",alignOffset:h=0,arrowPadding:f=0,avoidCollisions:g=!0,collisionBoundary:p=[],collisionPadding:v=0,sticky:b="partial",hideWhenDetached:k=!1,updatePositionStrategy:w="optimized",onPlaced:y,..._}=t,S=Mf(Va,c),[x,I]=q(null),R=Fe(e,it=>I(it)),[D,M]=q(null),U=bC(D),j=(U==null?void 0:U.width)??0,$=(U==null?void 0:U.height)??0,F=l+(u!=="center"?"-"+u:""),G=typeof v=="number"?v:{top:0,right:0,bottom:0,left:0,...v},Y=Array.isArray(p)?p:[p],W=Y.length>0,ee={padding:G,boundary:Y.filter(_C),altBoundary:W},{refs:we,floatingStyles:bt,placement:nn,isPositioned:st,middlewareData:Ve}=aC({strategy:"fixed",placement:F,whileElementsMounted:(...it)=>Xk(...it,{animationFrame:w==="always"}),elements:{reference:S.anchor},middleware:[lC({mainAxis:d+$,alignmentAxis:h}),g&&dC({mainAxis:!0,crossAxis:!1,limiter:b==="partial"?uC():void 0,...ee}),g&&hC({...ee}),fC({...ee,apply:({elements:it,rects:Hi,availableWidth:Gi,availableHeight:Ki})=>{const{width:y_,height:k_}=Hi.reference,ps=it.floating.style;ps.setProperty("--radix-popper-available-width",`${Gi}px`),ps.setProperty("--radix-popper-available-height",`${Ki}px`),ps.setProperty("--radix-popper-anchor-width",`${y_}px`),ps.setProperty("--radix-popper-anchor-height",`${k_}px`)}}),D&&mC({element:D,padding:f}),SC({arrowWidth:j,arrowHeight:$}),k&&pC({strategy:"referenceHidden",...ee})]}),[Lt,yt]=Vf(nn),H=Mn(y);Ke(()=>{st&&(H==null||H())},[st,H]);const me=(n=Ve.arrow)==null?void 0:n.x,Te=(i=Ve.arrow)==null?void 0:i.y,re=((r=Ve.arrow)==null?void 0:r.centerOffset)!==0,[be,Re]=q();return Ke(()=>{x&&Re(window.getComputedStyle(x).zIndex)},[x]),m("div",{ref:we.setFloating,"data-radix-popper-content-wrapper":"",style:{...bt,transform:st?bt.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:be,"--radix-popper-transform-origin":[(s=Ve.transformOrigin)==null?void 0:s.x,(o=Ve.transformOrigin)==null?void 0:o.y].join(" "),...((a=Ve.hide)==null?void 0:a.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:m(kC,{scope:c,placedSide:Lt,onArrowChange:M,arrowX:me,arrowY:Te,shouldHideArrow:re,children:m(Se.div,{"data-side":Lt,"data-align":yt,..._,ref:R,style:{..._.style,animation:st?void 0:"none"}})})})});Ff.displayName=Va;var Bf="PopperArrow",wC={top:"bottom",right:"left",bottom:"top",left:"right"},jf=Q(function(t,e){const{__scopePopper:n,...i}=t,r=CC(Bf,n),s=wC[r.placedSide];return m("span",{ref:r.onArrowChange,style:{position:"absolute",left:r.arrowX,top:r.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[r.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[r.placedSide],visibility:r.shouldHideArrow?"hidden":void 0},children:m(vC,{...i,ref:e,style:{...i.style,display:"block"}})})});jf.displayName=Bf;function _C(t){return t!==null}var SC=t=>({name:"transformOrigin",options:t,fn(e){var n,i,r;const{placement:s,rects:o,middlewareData:a}=e,c=((n=a.arrow)==null?void 0:n.centerOffset)!==0,l=c?0:t.arrowWidth,d=c?0:t.arrowHeight,[u,h]=Vf(s),f={start:"0%",center:"50%",end:"100%"}[h],g=(((i=a.arrow)==null?void 0:i.x)??0)+l/2,p=(((r=a.arrow)==null?void 0:r.y)??0)+d/2;let v="",b="";return u==="bottom"?(v=c?f:`${g}px`,b=`${-d}px`):u==="top"?(v=c?f:`${g}px`,b=`${o.floating.height+d}px`):u==="right"?(v=`${-d}px`,b=c?f:`${p}px`):u==="left"&&(v=`${o.floating.width+d}px`,b=c?f:`${p}px`),{data:{x:v,y:b}}}});function Vf(t){const[e,n="center"]=t.split("-");return[e,n]}var TC=Nf,xC=Uf,EC=Ff,PC=jf,RC="Portal",qf=Q((t,e)=>{var n;const{container:i,...r}=t,[s,o]=q(!1);Ke(()=>o(!0),[]);const a=i||s&&((n=globalThis==null?void 0:globalThis.document)==null?void 0:n.body);return a?Vt.createPortal(m(Se.div,{...r,ref:e}),a):null});qf.displayName=RC;var IC=tl[" useInsertionEffect ".trim().toString()]||Ke;function $f({prop:t,defaultProp:e,onChange:n=()=>{},caller:i}){const[r,s,o]=OC({defaultProp:e,onChange:n}),a=t!==void 0,c=a?t:r;{const d=B(t!==void 0);K(()=>{const u=d.current;u!==a&&console.warn(`${i} is changing from ${u?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,i])}const l=V(d=>{var u;if(a){const h=DC(d)?d(t):d;h!==t&&((u=o.current)==null||u.call(o,h))}else s(d)},[a,t,s,o]);return[c,l]}function OC({defaultProp:t,onChange:e}){const[n,i]=q(t),r=B(n),s=B(e);return IC(()=>{s.current=e},[e]),K(()=>{var o;r.current!==n&&((o=s.current)==null||o.call(s,n),r.current=n)},[n,r]),[n,i,s]}function DC(t){return typeof t=="function"}function AC(t){const e=B({value:t,previous:t});return oe(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var zf=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),MC="VisuallyHidden",NC=Q((t,e)=>m(Se.span,{...t,ref:e,style:{...zf,...t.style}}));NC.displayName=MC;var LC=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},di=new WeakMap,ns=new WeakMap,is={},qa=0,Wf=function(t){return t&&(t.host||Wf(t.parentNode))},UC=function(t,e){return e.map(function(n){if(t.contains(n))return n;var i=Wf(n);return i&&t.contains(i)?i:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},FC=function(t,e,n,i){var r=UC(e,Array.isArray(t)?t:[t]);is[n]||(is[n]=new WeakMap);var s=is[n],o=[],a=new Set,c=new Set(r),l=function(u){!u||a.has(u)||(a.add(u),l(u.parentNode))};r.forEach(l);var d=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(h){if(a.has(h))d(h);else try{var f=h.getAttribute(i),g=f!==null&&f!=="false",p=(di.get(h)||0)+1,v=(s.get(h)||0)+1;di.set(h,p),s.set(h,v),o.push(h),p===1&&g&&ns.set(h,!0),v===1&&h.setAttribute(n,"true"),g||h.setAttribute(i,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return d(e),a.clear(),qa++,function(){o.forEach(function(u){var h=di.get(u)-1,f=s.get(u)-1;di.set(u,h),s.set(u,f),h||(ns.has(u)||u.removeAttribute(i),ns.delete(u)),f||u.removeAttribute(n)}),qa--,qa||(di=new WeakMap,di=new WeakMap,ns=new WeakMap,is={})}},BC=function(t,e,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(t)?t:[t]),r=LC(t);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),FC(i,r,n,"aria-hidden")):function(){return null}},Nt=function(){return Nt=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},Nt.apply(this,arguments)};function Hf(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function jC(t,e,n){for(var i=0,r=e.length,s;i<r;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))}var rs="right-scroll-bar-position",ss="width-before-scroll-bar",VC="with-scroll-bars-hidden",qC="--removed-body-scroll-bar-size";function $a(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function $C(t,e){var n=q(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(i){var r=n.value;r!==i&&(n.value=i,n.callback(i,r))}}}})[0];return n.callback=e,n.facade}var zC=typeof window<"u"?Bt:K,Gf=new WeakMap;function WC(t,e){var n=$C(null,function(i){return t.forEach(function(r){return $a(r,i)})});return zC(function(){var i=Gf.get(n);if(i){var r=new Set(i),s=new Set(t),o=n.current;r.forEach(function(a){s.has(a)||$a(a,null)}),s.forEach(function(a){r.has(a)||$a(a,o)})}Gf.set(n,t)},[t]),n}function HC(t){return t}function GC(t,e){e===void 0&&(e=HC);var n=[],i=!1,r={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var o=e(s,i);return n.push(o),function(){n=n.filter(function(a){return a!==o})}},assignSyncMedium:function(s){for(i=!0;n.length;){var o=n;n=[],o.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){i=!0;var o=[];if(n.length){var a=n;n=[],a.forEach(s),o=n}var c=function(){var d=o;o=[],d.forEach(s)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){o.push(d),l()},filter:function(d){return o=o.filter(d),n}}}};return r}function KC(t){t===void 0&&(t={});var e=GC(null);return e.options=Nt({async:!0,ssr:!1},t),e}var Kf=function(t){var e=t.sideCar,n=Hf(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=e.read();if(!i)throw new Error("Sidecar medium not found");return fe(i,Nt({},n))};Kf.isSideCarExport=!0;function JC(t,e){return t.useMedium(e),Kf}var Jf=KC(),za=function(){},os=Q(function(t,e){var n=B(null),i=q({onScrollCapture:za,onWheelCapture:za,onTouchMoveCapture:za}),r=i[0],s=i[1],o=t.forwardProps,a=t.children,c=t.className,l=t.removeScrollBar,d=t.enabled,u=t.shards,h=t.sideCar,f=t.noRelative,g=t.noIsolation,p=t.inert,v=t.allowPinchZoom,b=t.as,k=b===void 0?"div":b,w=t.gapMode,y=Hf(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=h,S=WC([n,e]),x=Nt(Nt({},y),r);return fe(ge,null,d&&fe(_,{sideCar:Jf,removeScrollBar:l,shards:u,noRelative:f,noIsolation:g,inert:p,setCallbacks:s,allowPinchZoom:!!v,lockRef:n,gapMode:w}),o?wi(on.only(a),Nt(Nt({},x),{ref:S})):fe(k,Nt({},x,{className:c,ref:S}),a))});os.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},os.classNames={fullWidth:ss,zeroRight:rs};var YC=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function XC(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=YC();return e&&t.setAttribute("nonce",e),t}function QC(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function ZC(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var ew=function(){var t=0,e=null;return{add:function(n){t==0&&(e=XC())&&(QC(e,n),ZC(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},tw=function(){var t=ew();return function(e,n){K(function(){return t.add(e),function(){t.remove()}},[e&&n])}},Yf=function(){var t=tw(),e=function(n){var i=n.styles,r=n.dynamic;return t(i,r),null};return e},nw={left:0,top:0,right:0,gap:0},Wa=function(t){return parseInt(t||"",10)||0},iw=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],i=e[t==="padding"?"paddingTop":"marginTop"],r=e[t==="padding"?"paddingRight":"marginRight"];return[Wa(n),Wa(i),Wa(r)]},rw=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return nw;var e=iw(t),n=document.documentElement.clientWidth,i=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,i-n+e[2]-e[0])}},sw=Yf(),ui="data-scroll-locked",ow=function(t,e,n,i){var r=t.left,s=t.top,o=t.right,a=t.gap;return n===void 0&&(n="margin"),`
433
433
  .`.concat(VC,` {
434
434
  overflow: hidden `).concat(i,`;
435
435
  padding-right: `).concat(a,"px ").concat(i,`;