obi-sdk 0.18.17 → 0.18.18
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 +1 -1
- package/dist/obi-sdk.standalone.iife.js +1 -1
- package/package.json +3 -3
|
@@ -43,7 +43,7 @@ a=extmap-allow-mixed`)!==-1){const r=i.sdp.split(`
|
|
|
43
43
|
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
|
44
44
|
`);t.RTCSessionDescription&&i instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:i.type,sdp:r}):i.sdp=r}return A.apply(this,arguments)}}function nr(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const A=t.RTCPeerConnection.prototype.addIceCandidate;!A||A.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():A.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ir(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const A=t.RTCPeerConnection.prototype.setLocalDescription;!A||A.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return A.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?A.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>A.apply(this,[s]))})}var bw=Object.freeze({__proto__:null,removeExtmapAllowMixed:ia,shimAddIceCandidateNullOrEmpty:nr,shimConnectionState:na,shimMaxMessageSize:Ar,shimParameterlessSetLocalDescription:ir,shimRTCIceCandidate:er,shimRTCIceCandidateRelayProtocol:ta,shimSendThrowTypeError:tr});function yw(){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 A=_u,n=Bw(t),i={browserDetails:n,commonShim:bw,extractVersion:$i,disableLog:pw,disableWarnings:mw,sdp:ww};switch(n.browser){case"chrome":if(!Wu||!$s||!e.shimChrome)return A("Chrome shim is not included in this adapter release."),i;if(n.version===null)return A("Chrome shim can not determine version, not shimming."),i;A("adapter.js shimming chrome."),i.browserShim=Wu,nr(t,n),ir(t),Hu(t,n),Ou(t),$s(t,n),Mu(t),Gu(t,n),Nu(t),Ku(t),ju(t,n),er(t),ta(t),na(t),Ar(t,n),tr(t),ia(t,n);break;case"firefox":if(!nd||!ea||!e.shimFirefox)return A("Firefox shim is not included in this adapter release."),i;A("adapter.js shimming firefox."),i.browserShim=nd,nr(t,n),ir(t),Ju(t,n),ea(t,n),Xu(t),zu(t),qu(t),Yu(t),Zu(t),$u(t),ed(t),Ad(t),td(t),er(t),na(t),Ar(t,n),tr(t);break;case"safari":if(!hd||!e.shimSafari)return A("Safari shim is not included in this adapter release."),i;A("adapter.js shimming safari."),i.browserShim=hd,nr(t,n),ir(t),cd(t),ud(t),sd(t),id(t),rd(t),ld(t),ad(t),dd(t),er(t),ta(t),Ar(t,n),tr(t),ia(t,n);break;default:A("Unsupported browser!");break}return i}yw({window:typeof window>"u"?void 0:window});const Uw=10,rr="lk_e2ee",Qw={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Uw,keyringSize:16};var qA;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(qA||(qA={}));var pd;(function(t){t.KeyRatcheted="keyRatcheted"})(pd||(pd={}));var YA;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(YA||(YA={}));var md;(function(t){t.Error="cryptorError"})(md||(md={}));function Ew(){return Sw()||ra()}function ra(){return typeof window.RTCRtpScriptTransform<"u"}function Sw(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class DU extends yA.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(A,n,i)=>{W.debug("key ratcheted event received",{ratchetResult:A,participantId:n,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Qw),e),this.on(qA.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,A,n){const i={key:e,participantIdentity:A,keyIndex:n};if(!this.options.sharedKey&&!A)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(A??"shared","-").concat(n??0),i),this.emit(qA.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,A){this.emit(qA.RatchetRequest,e,A)}}class zA extends Error{constructor(e,A){super(A||"an error has occured"),this.name="LiveKitError",this.code=e}}var J;(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"})(J||(J={}));class Ae extends zA{constructor(e,A,n,i){super(1,e),this.name="ConnectionError",this.status=n,this.reason=A,this.context=i,this.reasonName=J[A]}}class sa extends zA{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class IA extends zA{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class kw extends zA{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ye extends zA{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class aa extends zA{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class oa extends zA{constructor(e,A){super(15,e),this.name="PublishTrackError",this.status=A}}class Bd extends zA{constructor(e,A){super(15,e),this.reason=A,this.reasonName=typeof A=="string"?A:qs[A]}}var sr;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(sr||(sr={})),function(t){function e(A){if(A&&"name"in A)return A.name==="NotFoundError"||A.name==="DevicesNotFoundError"?t.NotFound:A.name==="NotAllowedError"||A.name==="PermissionDeniedError"?t.PermissionDenied:A.name==="NotReadableError"||A.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e}(sr||(sr={}));var vd;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(vd||(vd={}));var I;(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"})(I||(I={}));var P;(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.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.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(P||(P={}));var _;(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"})(_||(_={}));var x;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",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"})(x||(x={}));function Tw(t){return typeof t>"u"?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Fw=/version\/(\d+(\.?_?\d+)+)/i;let ca;function uA(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof t>"u"&&typeof navigator>"u")return;const A=(t??navigator.userAgent).toLowerCase();if(ca===void 0||e){const n=Iw.find(i=>{let{test:r}=i;return r.test(A)});ca=n==null?void 0:n.describe(A)}return ca}const Iw=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:ar(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:la(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:ar(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:la(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:ar(Fw,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:la(t)}}}];function ar(t,e){let A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(t);return n&&n.length>=A&&n[A]||""}function la(t){return t.includes("mac os")?ar(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var xw="2.13.0";const _w=xw,Pw=16;class Te{}Te.setTimeout=function(){return setTimeout(...arguments)},Te.setInterval=function(){return setInterval(...arguments)},Te.clearTimeout=function(){return clearTimeout(...arguments)},Te.clearInterval=function(){return clearInterval(...arguments)};const Rw=5e3,En=[];var AA;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(AA||(AA={}));class k extends yA.EventEmitter{constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=k.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=W,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Rw):this.handleAppVisibilityChanged()},this.log=FA((i=n.loggerName)!==null&&i!==void 0?i:lA.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=A,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=k.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),z(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let A="audio";this.kind===k.Kind.Video&&(A="video"),this.attachedElements.length===0&&this.kind===k.Kind.Video&&this.addAppVisibilityListener(),e||(A==="audio"&&(En.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&En.splice(En.indexOf(e),1)),e||(e=document.createElement(A))),this.attachedElements.includes(e)||this.attachedElements.push(e),Kt(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),i=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(i?x.AudioPlaybackStarted:x.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(i?x.AudioPlaybackFailed:x.VideoPlaybackFailed,r):r.name==="AbortError"?W.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):W.warn("could not playback ".concat(i?"audio":"video"),r),i&&e&&n.some(s=>s.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(x.ElementAttached,e),e}detach(e){try{if(e){Vt(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(x.ElementDetached,e)),e}const A=[];return this.attachedElements.forEach(n=>{Vt(this.mediaStreamTrack,n),A.push(n),this.recycleElement(n),this.emit(x.ElementDetached,n)}),this.attachedElements=[],A}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=FA(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let A=!0;e.pause(),En.forEach(n=>{n.parentElement||(A=!1)}),A&&En.push(e)}}handleAppVisibilityChanged(){return C(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===k.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ve()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ve()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Kt(t,e){let A;e.srcObject instanceof MediaStream?A=e.srcObject:A=new MediaStream;let n;t.kind==="audio"?n=A.getAudioTracks():n=A.getVideoTracks(),n.includes(t)||(n.forEach(i=>{A.removeTrack(i)}),A.addTrack(t)),(!ZA()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=A.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==A&&(e.srcObject=A,(ZA()||Gt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=A,e.play().catch(()=>{})},0))}function Vt(t,e){if(e.srcObject instanceof MediaStream){const A=e.srcObject;A.removeTrack(t),A.getTracks().length>0?e.srcObject=A:e.srcObject=null}}(function(t){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let A;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(A=t.Source||(t.Source={}));let n;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(n=t.StreamState||(t.StreamState={}));function i(c){switch(c){case e.Audio:return sA.AUDIO;case e.Video:return sA.VIDEO;default:return sA.DATA}}t.kindToProto=i;function r(c){switch(c){case sA.AUDIO:return e.Audio;case sA.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=r;function s(c){switch(c){case A.Camera:return Be.CAMERA;case A.Microphone:return Be.MICROPHONE;case A.ScreenShare:return Be.SCREEN_SHARE;case A.ScreenShareAudio:return Be.SCREEN_SHARE_AUDIO;default:return Be.UNKNOWN}}t.sourceToProto=s;function a(c){switch(c){case Be.CAMERA:return A.Camera;case Be.MICROPHONE:return A.Microphone;case Be.SCREEN_SHARE:return A.ScreenShare;case Be.SCREEN_SHARE_AUDIO:return A.ScreenShareAudio;default:return A.Unknown}}t.sourceFromProto=a;function o(c){switch(c){case Ks.ACTIVE:return n.Active;case Ks.PAUSED:return n.Paused;default:return n.Unknown}}t.streamStateFromProto=o})(k||(k={}));class ee{constructor(e,A,n,i,r){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(A!==void 0&&n!==void 0)this.width=e,this.height=A,this.aspectRatio=e/A,this.encoding={maxBitrate:n,maxFramerate:i,priority:r};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 Lw=["vp8","h264"],Dw=["vp8","h264","vp9","av1"];function Hw(t){return!!Lw.find(e=>e===t)}var Cd;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(Cd||(Cd={}));var ua;(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}})(ua||(ua={}));const Sn={h90:new ee(160,90,9e4,20),h180:new ee(320,180,16e4,20),h216:new ee(384,216,18e4,20),h360:new ee(640,360,45e4,20),h540:new ee(960,540,8e5,25),h720:new ee(1280,720,17e5,30),h1080:new ee(1920,1080,3e6,30),h1440:new ee(2560,1440,5e6,30),h2160:new ee(3840,2160,8e6,30)},da={h120:new ee(160,120,7e4,20),h180:new ee(240,180,125e3,20),h240:new ee(320,240,14e4,20),h360:new ee(480,360,33e4,20),h480:new ee(640,480,5e5,20),h540:new ee(720,540,6e5,25),h720:new ee(960,720,13e5,30),h1080:new ee(1440,1080,23e5,30),h1440:new ee(1920,1440,38e5,30)},ha={h360fps3:new ee(640,360,2e5,3,"medium"),h360fps15:new ee(640,360,4e5,15,"medium"),h720fps5:new ee(1280,720,8e5,5,"medium"),h720fps15:new ee(1280,720,15e5,15,"medium"),h720fps30:new ee(1280,720,2e6,30,"medium"),h1080fps15:new ee(1920,1080,25e5,15,"medium"),h1080fps30:new ee(1920,1080,5e6,30,"medium"),original:new ee(0,0,7e6,30,"medium")},Ow="|",wd="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Mw(t){const e=t.split(Ow);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function Ke(t){return C(this,void 0,void 0,function*(){return new Promise(e=>Te.setTimeout(e,t))})}function fa(){return"addTransceiver"in RTCPeerConnection.prototype}function ga(){return"addTrack"in RTCPeerConnection.prototype}function Nw(){if(!("getCapabilities"in RTCRtpSender)||ZA())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const A of t.codecs)if(A.mimeType==="video/AV1"){e=!0;break}}return e}function Kw(){if(!("getCapabilities"in RTCRtpSender)||Gt())return!1;if(ZA()){const A=uA();if(A!=null&&A.version&&mt(A.version,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const A of t.codecs)if(A.mimeType==="video/VP9"){e=!0;break}}return e}function kn(t){return t==="av1"||t==="vp9"}function pa(t){return document?(t||(t=document.createElement("audio")),"setSinkId"in t):!1}function Vw(){return typeof RTCPeerConnection>"u"?!1:fa()||ga()}function Gt(){var t;return((t=uA())===null||t===void 0?void 0:t.name)==="Firefox"}function ZA(){var t;return((t=uA())===null||t===void 0?void 0:t.name)==="Safari"}function Gw(){const t=uA();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")}function bd(){var t,e;return Ve()?(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 jw(){const t=uA(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&mt(e,t.osVersion)>=0?!0:t.name==="Safari"&&mt(e,t.version)>=0}function Ve(){return typeof document<"u"}function UA(){return navigator.product=="ReactNative"}function ma(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function yd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ud(){if(!UA())return;let t=yd();if(t)return t.platform}function Qd(){if(Ve())return window.devicePixelRatio;if(UA()){let t=yd();if(t)return t.devicePixelRatio}return 1}function mt(t,e){const A=t.split("."),n=e.split("."),i=Math.min(A.length,n.length);for(let r=0;r<i;++r){const s=parseInt(A[r],10),a=parseInt(n[r],10);if(s>a)return 1;if(s<a)return-1;if(r===i-1&&s===a)return 0}return t===""&&e!==""?-1:e===""?1:A.length==n.length?0:A.length<n.length?-1:1}function Ww(t){for(const e of t)e.target.handleResize(e)}function Jw(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Ba=null;const Ed=()=>(Ba||(Ba=new ResizeObserver(Ww)),Ba);let va=null;const Sd=()=>(va||(va=new IntersectionObserver(Jw,{root:null,rootMargin:"0px"})),va);function Xw(){var t;const e=new DC({sdk:uu.JS,protocol:Pw,version:_w});return UA()&&(e.os=(t=Ud())!==null&&t!==void 0?t:""),e}function kd(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=t,i.height=e;const r=i.getContext("2d");r==null||r.fillRect(0,0,i.width,i.height),n&&r&&(r.beginPath(),r.arc(t/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const s=i.captureStream(),[a]=s.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=A,a}let Tn;function Ca(){if(!Tn){const t=new AudioContext,e=t.createOscillator(),A=t.createGain();A.gain.setValueAtTime(0,0);const n=t.createMediaStreamDestination();if(e.connect(A),A.connect(n),e.start(),[Tn]=n.stream.getAudioTracks(),!Tn)throw Error("Could not get empty media stream audio track");Tn.enabled=!1}return Tn.clone()}class wa{constructor(e,A){this.onFinally=A,this.promise=new Promise((n,i)=>C(this,void 0,void 0,function*(){this.resolve=n,this.reject=i,e&&(yield e(n,i))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}function qw(t){return Dw.includes(t)}function $A(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Yw(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function ba(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function zw(t,e){return t.segments.map(A=>{let{id:n,text:i,language:r,startTime:s,endTime:a,final:o}=A;var c;const l=(c=e.get(n))!==null&&c!==void 0?c:Date.now(),u=Date.now();return o?e.delete(n):e.set(n,l),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(a.toString()),final:o,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function Zw(t){const{id:e,timestamp:A,message:n,editTimestamp:i}=t;return{id:e,timestamp:Number.parseInt(A.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:n}}function Td(t){switch(t.reason){case J.LeaveRequest:return t.context;case J.Cancelled:return aA.CLIENT_INITIATED;case J.NotAllowed:return aA.USER_REJECTED;case J.ServerUnreachable:return aA.JOIN_FAILURE;default:return aA.UNKNOWN_REASON}}function or(t){return t!==void 0?Number(t):void 0}function Bt(t){return t!==void 0?BigInt(t):void 0}function jt(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function xA(t){return!!t&&t.kind==k.Kind.Audio}function Wt(t){return!!t&&t.kind==k.Kind.Video}function et(t){return jt(t)&&Wt(t)}function vt(t){return jt(t)&&xA(t)}function ya(t){return!!t&&!t.isLocal}function $w(t){return!!t&&!t.isLocal}function Ua(t){return ya(t)&&Wt(t)}function eb(t){return t.isLocal}function Ab(t,e){const A=[];let n=new TextEncoder().encode(t);for(;n.length>e;){let i=e;for(;i>0;){const r=n[i];if(r!==void 0&&(r&192)!==128)break;i--}A.push(n.slice(0,i)),n=n.slice(i)}return n.length>0&&A.push(n),A}function Fd(t,e,A){var n,i,r,s;const{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:c}=Pd(t??{}),l=e==null?void 0:e.processor,u=A==null?void 0:A.processor,d=a??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(Qa(d.audio,e),(n=(r=d.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(o||l)&&(d.audio.processor=o??l)),d.video&&(Qa(d.video,A),(i=(s=d.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(d.video.processor=c??u)),d}function Qa(t,e){return Object.keys(e).forEach(A=>{t[A]===void 0&&(t[A]=e[A])}),t}function Ea(t){var e,A,n,i;const r={};if(t.video)if(typeof t.video=="object"){const s={},a=s,o=t.video;Object.keys(o).forEach(c=>{switch(c){case"resolution":Qa(a,o.resolution);break;default:a[c]=o[c]}}),r.video=s,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=t.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return t.audio?typeof t.audio=="object"?(r.audio=t.audio,(A=(i=r.audio).deviceId)!==null&&A!==void 0||(i.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Id(t){return C(this,arguments,void 0,function(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=xd();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=i.frequencyBinCount,s=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Ke(A),i.getByteTimeDomainData(s);const o=s.some(c=>c!==128&&c!==0);return n.close(),!o}return!1}()})}function xd(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const A=new e({latencyHint:"interactive"});if(A.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const n=()=>C(this,void 0,void 0,function*(){var i;try{A.state==="suspended"&&(yield A.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",n)});window.document.body.addEventListener("click",n)}return A}}function tb(t){return t==="audioinput"?k.Source.Microphone:t==="videoinput"?k.Source.Camera:k.Source.Unknown}function _d(t){return t===k.Source.Microphone?"audioinput":t===k.Source.Camera?"videoinput":void 0}function nb(t){var e,A;let n=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(n=typeof n=="boolean"?{}:n,ZA()?n=Object.assign(Object.assign({},n),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(A=t.audio)!==null&&A!==void 0?A:!1,video:n,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function cr(t){return t.split("/")[1].toLowerCase()}function ib(t){const e=[];return t.forEach(A=>{A.track!==void 0&&e.push(new Js({cid:A.track.mediaStreamID,track:A.trackInfo}))}),e}function z(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?z(t.track):{})}}function rb(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function sb(t,e){var A;t===void 0&&(t={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(t)],i={};for(const r of n)t[r]!==e[r]&&(i[r]=(A=e[r])!==null&&A!==void 0?A:"");return i}function Pd(t){const e=Object.assign({},t);let A,n;return typeof e.audio=="object"&&e.audio.processor&&(A=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:A,videoProcessor:n,optionsWithoutProcessor:Tw(e)}}function ab(t){switch(t){case Be.CAMERA:return k.Source.Camera;case Be.MICROPHONE:return k.Source.Microphone;case Be.SCREEN_SHARE:return k.Source.ScreenShare;case Be.SCREEN_SHARE_AUDIO:return k.Source.ScreenShareAudio;default:return k.Source.Unknown}}class ob extends yA.EventEmitter{constructor(e){super(),this.onWorkerMessage=A=>{var n,i;const{kind:r,data:s}=A.data;switch(r){case"error":W.error(s.error.message),this.emit(YA.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(YA.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const a=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(YA.ParticipantEncryptionStatusChanged,s.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(qA.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=A=>{W.error("e2ee worker encountered an error:",{error:A.error}),this.emit(YA.EncryptionError,A.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Ew())throw new sa("tried to setup end-to-end encryption on an unsupported browser");if(W.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const A={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:uw.getLevel()}};this.worker&&(W.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(A))}}setParticipantCryptorEnabled(e,A){W.debug("set e2ee to ".concat(e," for participant ").concat(A)),this.postEnable(e,A)}setSifTrailer(e){!e||e.length===0?W.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(_.RTPVideoMapUpdate,A=>{this.postRTPMap(A)})}setupEventListeners(e,A){e.on(I.TrackPublished,(n,i)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==qe.NONE,i.identity)),e.on(I.ConnectionStateChanged,n=>{n===q.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==qe.NONE,i.identity)})})}).on(I.TrackUnsubscribed,(n,i,r)=>{var s;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(a)}).on(I.TrackSubscribed,(n,i,r)=>{this.setupE2EEReceiver(n,r.identity,i.trackInfo)}).on(I.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");A.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(P.LocalTrackPublished,n=>C(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),A.on(qA.SetKey,n=>this.postKey(n)).on(qA.RatchetRequest,(n,i)=>this.postRatchetRequest(n,i))}postRatchetRequest(e,A){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:A}};this.worker.postMessage(n)}postKey(e){let{key:A,participantIdentity:n,keyIndex:i}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:A,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,A){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:A}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var A;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((A=this.room)===null||A===void 0)&&A.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const A={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(A)}setupE2EEReceiver(e,A,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,A,e.kind==="video"?cr(n.mimeType):void 0)}}setupE2EESender(e,A){if(!jt(e)||!A){A||W.warn("early return because sender is not ready");return}this.handleSender(A,e.mediaStreamID,void 0)}handleReceiver(e,A,n,i){return C(this,void 0,void 0,function*(){if(this.worker){if(ra()){const r={kind:"decode",participantIdentity:n,trackId:A,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(rr in e&&i){const o={kind:"updateCodec",data:{trackId:A,codec:i,participantIdentity:n}};this.worker.postMessage(o);return}let r=e.writableStream,s=e.readableStream;if(!r||!s){const o=e.createEncodedStreams();e.writableStream=o.writable,r=o.writable,e.readableStream=o.readable,s=o.readable}const a={kind:"decode",data:{readableStream:s,writableStream:r,trackId:A,codec:i,participantIdentity:n}};this.worker.postMessage(a,[s,r])}e[rr]=!0}})}handleSender(e,A,n){var i;if(!(rr in e||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ra()){W.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:A,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{W.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:A,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[r.readable,r.writable])}e[rr]=!0}}}const Sa="default";class Qe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Qe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;if(((r=Qe.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){W.debug("awaiting getUserMedia promise");try{A?yield Qe.userMediaPromiseMap.get(A):yield Promise.all(Qe.userMediaPromiseMap.values())}catch{W.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(ZA()&&n.hasDeviceInUse(A))&&(s.filter(o=>o.kind===A).length===0||s.some(o=>{const c=o.label==="",l=A?o.kind===A:!0;return c&&l}))){const o={video:A!=="audioinput"&&A!=="audiooutput",audio:A!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(o);s=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return n._previousDevices=s,A&&(s=s.filter(a=>a.kind===A)),s}()})}normalizeDeviceId(e,A,n){return C(this,void 0,void 0,function*(){if(A!==Sa)return A;const i=yield this.getDevices(e),r=i.find(a=>a.deviceId===Sa);if(!r){W.warn("could not reliably determine default device");return}const s=i.find(a=>a.deviceId!==Sa&&a.groupId===(n??r.groupId));if(!s){W.warn("could not reliably determine default device");return}return s==null?void 0:s.deviceId})}hasDeviceInUse(e){return e?Qe.userMediaPromiseMap.has(e):Qe.userMediaPromiseMap.size>0}}Qe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Qe.userMediaPromiseMap=new Map;var Fn;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Fn||(Fn={}));class cb{constructor(){this.pendingTasks=new Map,this.taskMutex=new Oe,this.nextTaskIndex=0}run(e){return C(this,void 0,void 0,function*(){const A={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Fn.WAITING};this.pendingTasks.set(A.id,A);const n=yield this.taskMutex.lock();try{return A.executedAt=Date.now(),A.status=Fn.RUNNING,yield e()}finally{A.status=Fn.COMPLETED,this.pendingTasks.delete(A.id),n()}})}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 lb(t,e){const A=new URL(Yw(t));return e.forEach((n,i)=>{A.searchParams.set(i,n)}),Rd(A,"rtc")}function ub(t){const e=new URL(ba(t));return Rd(e,"validate")}function db(t){return t.endsWith("/")?t:"".concat(t,"/")}function Rd(t,e){return t.pathname="".concat(db(t.pathname)).concat(e),t.toString()}const hb=["syncState","trickle","offer","answer","simulate","leave"];function fb(t){const e=hb.indexOf(t.case)>=0;return W.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var ne;(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"})(ne||(ne={}));class ka{get currentState(){return this.state}get isDisconnected(){return this.state===ne.DISCONNECTING||this.state===ne.DISCONNECTED}get isEstablishingConnection(){return this.state===ne.CONNECTING||this.state===ne.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=ne.DISCONNECTED,this.log=W,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=FA((n=A.loggerName)!==null&&n!==void 0?n:lA.Signal),this.loggerContextCb=A.loggerContextCb,this.useJSON=e,this.requestQueue=new cb,this.queuedRequests=[],this.closingLock=new Oe,this.connectionLock=new Oe,this.state=ne.DISCONNECTED}get logContext(){var e,A;return(A=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&A!==void 0?A:{}}join(e,A,n,i){return C(this,void 0,void 0,function*(){return this.state=ne.CONNECTING,this.options=n,yield this.connect(e,A,n,i)})}reconnect(e,A,n,i){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=ne.RECONNECTING,this.clearPingInterval(),yield this.connect(e,A,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))})}connect(e,A,n,i){this.connectOptions=n;const r=Xw(),s=gb(A,r,n),a=lb(e,s),o=ub(a);return new Promise((c,l)=>C(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const d=()=>C(this,void 0,void 0,function*(){this.close(),clearTimeout(h),l(new Ae("room connection has been cancelled (signal)",J.Cancelled))}),h=setTimeout(()=>{this.close(),l(new Ae("room connection has timed out (signal)",J.ServerUnreachable))},n.websocketTimeout);i!=null&&i.aborted&&d(),i==null||i.addEventListener("abort",d);const p=new URL(a);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(p),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=f=>C(this,void 0,void 0,function*(){if(this.state!==ne.CONNECTED){this.state=ne.DISCONNECTED,clearTimeout(h);try{const m=yield fetch(o);if(m.status.toFixed(0).startsWith("4")){const B=yield m.text();l(new Ae(B,J.NotAllowed,m.status))}else l(new Ae("Encountered unknown websocket error during connection: ".concat(f.toString()),J.InternalError,m.status))}catch(m){l(new Ae(m instanceof Error?m.message:"server was not reachable",J.ServerUnreachable))}return}this.handleWSError(f)}),this.ws.onmessage=f=>C(this,void 0,void 0,function*(){var m,B,b;let U;if(typeof f.data=="string"){const w=JSON.parse(f.data);U=mu.fromJson(w,{ignoreUnknownFields:!0})}else if(f.data instanceof ArrayBuffer)U=mu.fromBinary(new Uint8Array(f.data));else{this.log.error("could not decode websocket message: ".concat(typeof f.data),this.logContext);return}if(this.state!==ne.CONNECTED){let w=!1;if(((m=U.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=ne.CONNECTED,i==null||i.removeEventListener("abort",d),this.pingTimeoutDuration=U.message.value.pingTimeout,this.pingIntervalDuration=U.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()),c(U.message.value)):this.state===ne.RECONNECTING&&U.message.case!=="leave"?(this.state=ne.CONNECTED,i==null||i.removeEventListener("abort",d),this.startPingInterval(),((B=U.message)===null||B===void 0?void 0:B.case)==="reconnect"?c(U.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),w=!0)):this.isEstablishingConnection&&U.message.case==="leave"?l(new Ae("Received leave request while trying to (re)connect",J.LeaveRequest,void 0,U.message.value.reason)):n.reconnect||l(new Ae("did not receive join response, got ".concat((b=U.message)===null||b===void 0?void 0:b.case," instead"),J.InternalError)),!w)return}this.signalLatency&&(yield Ke(this.signalLatency)),this.handleSignalResponse(U)}),this.ws.onclose=f=>{this.isEstablishingConnection&&l(new Ae("Websocket got closed during a (re)connection attempt",J.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:f.reason,code:f.code,wasClean:f.wasClean,state:this.state})),this.handleOnClose(f.reason)}}finally{u()}}))}close(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),A&&(e.state=ne.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,Ke(250)])),e.ws=void 0}}finally{A&&(e.state=ne.DISCONNECTED),n()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:lr(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:lr(e)})}sendIceCandidate(e,A){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new js({candidateInit:JSON.stringify(e),target:A})})}sendMuteTrack(e,A){return this.sendRequest({case:"mute",value:new Ws({sid:e,muted:A})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new wu({requestId:a,metadata:n,name:i,attributes:s})}),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,A){return this.sendRequest({case:"updateLayers",value:new Cu({trackSid:e,layers:A})})}sendUpdateSubscriptionPermissions(e,A){return this.sendRequest({case:"subscriptionPermission",value:new Uu({allParticipants:e,trackPermissions:A})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:re.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Su({timestamp:re.parse(Date.now()),rtt:re.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,A){return this.sendRequest({case:"updateAudioTrack",value:new vu({trackSid:e,features:A})})}sendLeave(){return this.sendRequest({case:"leave",value:new qi({reason:aA.CLIENT_INITIATED,action:Mt.DISCONNECT})})}sendRequest(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!fb(A)&&n.state===ne.RECONNECTING){n.queuedRequests.push(()=>C(n,void 0,void 0,function*(){yield this.sendRequest(A,!0)}));return}if(i||(yield n.requestQueue.flush()),n.signalLatency&&(yield Ke(n.signalLatency)),!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(A==null?void 0:A.case),n.logContext);return}const s=new MC({message:A});try{n.useJSON?n.ws.send(s.toJsonString()):n.ws.send(s.toBinary())}catch(a){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:a}))}}()})}handleSignalResponse(e){var A,n;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(i.case==="answer"){const s=Ld(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=Ld(i.value);this.onOffer&&this.onOffer(s)}else if(i.case==="trickle"){const s=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(s,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((A=i.value.participants)!==null&&A!==void 0?A:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=i.value.speakers)!==null&&n!==void 0?n:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));r||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===ne.DISCONNECTED)return;const A=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),A&&A(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=Te.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&&Te.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=Te.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Te.clearInterval(this.pingInterval)}}function Ld(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 lr(t){return new gt({sdp:t.sdp,type:t.type})}function gb(t,e,A){var n;const i=new URLSearchParams;return i.set("access_token",t),A.reconnect&&(i.set("reconnect","1"),A.sid&&i.set("sid",A.sid)),i.set("auto_subscribe",A.autoSubscribe?"1":"0"),i.set("sdk",UA()?"reactnative":"js"),i.set("version",e.version),i.set("protocol",e.protocol.toString()),e.deviceModel&&i.set("device_model",e.deviceModel),e.os&&i.set("os",e.os),e.osVersion&&i.set("os_version",e.osVersion),e.browser&&i.set("browser",e.browser),e.browserVersion&&i.set("browser_version",e.browserVersion),A.adaptiveStream&&i.set("adaptive_stream","1"),A.reconnectReason&&i.set("reconnect_reason",A.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&i.set("network",navigator.connection.type),i}var dA={},Ta={},Fa={exports:{}},Dd;function Ia(){if(Dd)return Fa.exports;Dd=1;var t=Fa.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 A="candidate:%s %d %s %d %s %d typ %s";return A+=e.raddr!=null?" raddr %s rport %d":"%v%v",A+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(A+=" generation %d"),A+=e["network-id"]!=null?" network-id %d":"%v",A+=e["network-cost"]!=null?" network-cost %d":"%v",A}},{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 A="ssrc:%d";return e.attribute!=null&&(A+=" %s",e.value!=null&&(A+=":%s")),A}},{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 A="mediaclk:";return A+=e.id!=null?"id=%s %s":"%v%s",A+=e.mediaClockValue!=null?"=%s":"",A+=e.rateNumerator!=null?" rate=%s":"",A+=e.rateDenominator!=null?"/%s":"",A}},{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 A=t[e];A.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),Fa.exports}var Hd;function pb(){return Hd||(Hd=1,function(t){var e=function(a){return String(Number(a))===a?Number(a):a},A=function(a,o,c,l){if(l&&!c)o[l]=e(a[1]);else for(var u=0;u<c.length;u+=1)a[u+1]!=null&&(o[c[u]]=e(a[u+1]))},n=function(a,o,c){var l=a.name&&a.names;a.push&&!o[a.push]?o[a.push]=[]:l&&!o[a.name]&&(o[a.name]={});var u=a.push?{}:l?o[a.name]:o;A(c.match(a.reg),u,a.names,a.name),a.push&&o[a.push].push(u)},i=Ia(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var o={},c=[],l=o;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var d=u[0],h=u.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var p=0;p<(i[d]||[]).length;p+=1){var f=i[d][p];if(f.reg.test(h))return n(f,l,h)}}),o.media=c,o};var s=function(a,o){var c=o.split(/=(.+)/,2);return c.length===2?a[c[0]]=e(c[1]):c.length===1&&o.length>1&&(a[c[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var o=[],c=a.split(" ").map(e),l=0;l<c.length;l+=3)o.push({component:c[l],ip:c[l+1],port:c[l+2]});return o},t.parseImageAttributes=function(a){return a.split(" ").map(function(o){return o.substring(1,o.length-1).split(",").reduce(s,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(o){return o.split(",").map(function(c){var l,u=!1;return c[0]!=="~"?l=e(c):(l=e(c.substring(1,c.length)),u=!0),{scid:l,paused:u}})})}}(Ta)),Ta}var xa,Od;function mb(){if(Od)return xa;Od=1;var t=Ia(),e=/%[sdv%]/g,A=function(s){var a=1,o=arguments,c=o.length;return s.replace(e,function(l){if(a>=c)return l;var u=o[a];switch(a+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(s,a,o){var c=a.format instanceof Function?a.format(a.push?o:o[a.name]):a.format,l=[s+"="+c];if(a.names)for(var u=0;u<a.names.length;u+=1){var d=a.names[u];a.name?l.push(o[a.name][d]):l.push(o[a.names[u]])}else l.push(o[a.name]);return A.apply(null,l)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return xa=function(s,a){a=a||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var o=a.outerOrder||i,c=a.innerOrder||r,l=[];return o.forEach(function(u){t[u].forEach(function(d){d.name in s&&s[d.name]!=null?l.push(n(u,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){l.push(n(u,d,h))})})}),s.media.forEach(function(u){l.push(n("m",t.m[0],u)),c.forEach(function(d){t[d].forEach(function(h){h.name in u&&u[h.name]!=null?l.push(n(d,h,u)):h.push in u&&u[h.push]!=null&&u[h.push].forEach(function(p){l.push(n(d,h,p))})})})}),l.join(`\r
|
|
45
45
|
`)+`\r
|
|
46
|
-
`},xa}var Md;function Bb(){if(Md)return dA;Md=1;var t=pb(),e=mb(),A=Ia();return dA.grammar=A,dA.write=e,dA.parse=t.parse,dA.parseParams=t.parseParams,dA.parseFmtpConfig=t.parseFmtpConfig,dA.parsePayloads=t.parsePayloads,dA.parseRemoteCandidates=t.parseRemoteCandidates,dA.parseImageAttributes=t.parseImageAttributes,dA.parseSimulcastStreamList=t.parseSimulcastStreamList,dA}var At=Bb();function _a(t,e,A){var n,i,r;e===void 0&&(e=50),A===void 0&&(A={});var s=(n=A.isImmediate)!=null&&n,a=(i=A.callback)!=null&&i,o=A.maxWait,c=Date.now(),l=[];function u(){if(o!==void 0){var h=Date.now()-c;if(h+e>=o)return o-h}return e}var d=function(){var h=[].slice.call(arguments),p=this;return new Promise(function(f,m){var B=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var U=t.apply(p,h);a&&a(U),l.forEach(function(w){return(0,w.resolve)(U)}),l=[]}},u()),B){var b=t.apply(p,h);return a&&a(b),f(b)}l.push({resolve:f,reject:m})})};return d.cancel=function(h){r!==void 0&&clearTimeout(r),l.forEach(function(p){return(0,p.reject)(h)}),l=[]},d}const vb=.7,Cb=20,Jt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Nd extends yA.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=W,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=_a(i=>C(this,void 0,void 0,function*(){this.emit(Jt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),Cb),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=FA((n=A.loggerName)!==null&&n!==void 0?n:lA.PCTransport),this.loggerOptions=A,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=A=>{var n;A.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,A.candidate))},e.onicecandidateerror=A=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,A)},e.oniceconnectionstatechange=()=>{var A;(A=this.onIceConnectionStateChange)===null||A===void 0||A.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var A;(A=this.onSignalingStatechange)===null||A===void 0||A.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var A;(A=this.onConnectionStateChange)===null||A===void 0||A.call(this,e.connectionState)},e.ondatachannel=A=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,A)},e.ontrack=A=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,A)},e}get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions).loggerContextCb)===null||A===void 0?void 0:A.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){return C(this,void 0,void 0,function*(){var A;let n;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=wb(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=At.parse((A=e.sdp)!==null&&A!==void 0?A:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let a=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(a=c.payload,!0):!1),a===0)return!0;let o=!1;for(const c of r.fmtp)if(c.payload===a){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),o=!0;break}return o||s.maxbr>0&&r.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),n=At.write(i)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Jt.NegotiationComplete),e.sdp&&At.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Jt.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return C(this,void 0,void 0,function*(){var A;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 r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const i=At.parse((A=n.sdp)!==null&&A!==void 0?A:"");i.media.forEach(r=>{Vd(r),r.type==="audio"?Kd(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let a=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(a=c.payload,!0):!1),a===0||(kn(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const o=Math.round(s.maxbr*vb);for(const c of r.fmtp)if(c.payload===a){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(o));break}return!0})}),yield this.setMungedSDP(n,At.write(i)),this.onOffer(n)})}createAndSetAnswer(){return C(this,void 0,void 0,function*(){var e;const A=yield this.pc.createAnswer(),n=At.parse((e=A.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(i=>{Vd(i),i.type==="audio"&&Kd(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(A,At.write(n)),A})}createDataChannel(e,A){return this.pc.createDataChannel(e,A)}addTransceiver(e,A){return this.pc.addTransceiver(e,A)}addTrack(e){if(!this._pc)throw new ye("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var A;if(!this._pc)throw new ye("PC closed, cannot configure");return(A=this._pc)===null||A===void 0?void 0:A.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var A;return(A=this._pc)===null||A===void 0?void 0:A.removeTrack(e)}getConnectionState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&A!==void 0?A:"closed"}getICEConnectionState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&A!==void 0?A:"closed"}getSignallingState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&A!==void 0?A:"closed"}getTransceivers(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&A!==void 0?A:[]}getSenders(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&A!==void 0?A:[]}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 A="";const n=new Map,i=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":A=a.selectedCandidatePairId;break;case"candidate-pair":A===""&&a.selected&&(A=a.id),n.set(a.id,a);break;case"remote-candidate":i.set(a.id,"".concat(a.address,":").concat(a.port));break}}),A==="")return;const s=(e=n.get(A))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,A,n){return C(this,void 0,void 0,function*(){if(A){const i=e.sdp;e.sdp=A;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:A})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new aa(r)}})}ensureVideoDDExtensionForSVC(e,A){var n,i;if(!((n=e.ext)===null||n===void 0?void 0:n.some(s=>s.uri===wd))){if(this.ddExtID===0){let s=0;A.media.forEach(a=>{var o;a.type==="video"&&((o=a.ext)===null||o===void 0||o.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:wd})}}}function Kd(t,e,A){let n=0;t.rtp.some(i=>i.codec==="opus"?(n=i.payload,!0):!1),n>0&&(t.rtcpFb||(t.rtcpFb=[]),A.includes(t.mid)&&!t.rtcpFb.some(i=>i.payload===n&&i.type==="nack")&&t.rtcpFb.push({payload:n,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(i=>i.payload===n?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function wb(t){var e;const A=[],n=[],i=At.parse((e=t.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var a;s.type==="audio"&&(s.rtp.some(o=>o.codec==="opus"?(r=o.payload,!0):!1),!((a=s.rtcpFb)===null||a===void 0)&&a.some(o=>o.payload===r&&o.type==="nack")&&n.push(s.mid),s.fmtp.some(o=>o.payload===r?(o.config.includes("sprop-stereo=1")&&A.push(s.mid),!0):!1))}),{stereoMids:A,nackMids:n}}function Vd(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 Pa="vp8",bb={audioPreset:ua.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ha.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Pa,backupCodec:!0},Gd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},jd={deviceId:{ideal:"default"},resolution:Sn.h720.resolution},yb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new hw,disconnectOnPageLeave:!0,webAudioMix:!1},Ra={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ue;(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"})(ue||(ue={}));class Ub{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,A,n){var i;this.peerConnectionTimeout=Ra.peerConnectionTimeout,this.log=W,this.updateState=()=>{var r;const s=this.state,a=this.requiredTransports.map(o=>o.getConnectionState());a.every(o=>o==="connected")?this.state=ue.CONNECTED:a.some(o=>o==="failed")?this.state=ue.FAILED:a.some(o=>o==="connecting")?this.state=ue.CONNECTING:a.every(o=>o==="closed")?this.state=ue.CLOSED:a.some(o=>o==="closed")?this.state=ue.CLOSING:a.every(o=>o==="new")&&(this.state=ue.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(ue[s]," to ").concat(ue[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=FA((i=n.loggerName)!==null&&i!==void 0?i:lA.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!A,this.isSubscriberConnectionRequired=A,this.publisher=new Nd(e,n),this.subscriber=new Nd(e,n),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=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,cA.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,cA.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=ue.NEW,this.connectionLock=new Oe,this.remoteOfferLock=new Oe}get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions).loggerContextCb)===null||A===void 0?void 0:A.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){return this.publisher.setRemoteDescription(e)}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 A of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(A)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}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,A){return C(this,void 0,void 0,function*(){A===cA.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){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 A=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{A()}})}updateConfiguration(e,A){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),A&&this.triggerIceRestart()}ensurePCTransportConnection(e,A){return C(this,void 0,void 0,function*(){var n;const i=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,A)))}finally{i()}})}negotiate(e){return C(this,void 0,void 0,function*(){return new Promise((A,n)=>C(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Jt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Jt.NegotiationComplete,()=>{clearTimeout(i),A()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),n(s)})}))})}addPublisherTransceiver(e,A){return this.publisher.addTransceiver(e,A)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,A){return this.publisher.createDataChannel(e,A)}getConnectedAddress(e){return e===cA.PUBLISHER?this.publisher.getConnectedAddress():e===cA.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,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((o,c)=>C(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),Te.clearTimeout(u),c(new Ae("room connection has been cancelled",J.Cancelled))};i!=null&&i.signal.aborted&&l(),i==null||i.signal.addEventListener("abort",l);const u=Te.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",l),c(new Ae("could not establish pc connection",J.InternalError))},s);for(;this.state!==ue.CONNECTED;)if(yield Ke(50),i!=null&&i.signal.aborted){c(new Ae("room connection has been cancelled",J.Cancelled));return}Te.clearTimeout(u),i==null||i.signal.removeEventListener("abort",l),o()}))}()})}}class de extends Error{constructor(e,A,n){super(A),this.code=e,this.message=Jd(A,de.MAX_MESSAGE_BYTES),this.data=n?Jd(n,de.MAX_DATA_BYTES):void 0}static fromProto(e){return new de(e.code,e.message,e.data)}toProto(){return new ou({code:this.code,message:this.message,data:this.data})}static builtIn(e,A){return new de(de.ErrorCode[e],de.ErrorMessage[e],A)}}de.MAX_MESSAGE_BYTES=256,de.MAX_DATA_BYTES=15360,de.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},de.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 Wd=15360;function La(t){return new TextEncoder().encode(t).length}function Jd(t,e){if(La(t)<=e)return t;let A=0,n=t.length;const i=new TextEncoder;for(;A<n;){const r=Math.floor((A+n+1)/2);i.encode(t.slice(0,r)).length<=e?A=r:n=r-1}return t.slice(0,A)}const Da=2e3;function ur(t,e){if(!e)return 0;let A,n;return"bytesReceived"in t?(A=t.bytesReceived,n=e.bytesReceived):"bytesSent"in t&&(A=t.bytesSent,n=e.bytesSent),A===void 0||n===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(A-n)*8*1e3/(t.timestamp-e.timestamp)}const Qb=1e3;class Xd extends k{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,A,n){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,A,r),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=_a(()=>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(x.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Oe,this.pauseUpstreamLock=new Oe,this.processorLock=new Oe,this.restartLock=new Oe,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==k.Kind.Video)return;const{width:e,height:A}=this._mediaStreamTrack.getSettings();if(e&&A)return{width:e,height:A}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,A;return(A=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&A!==void 0?A:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,A){return C(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!A)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Vt(this._mediaStreamTrack,r)}),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 i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Kt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Kt(i??e,r)}))})}waitForDimensions(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Qb;return function*(){var n;if(e.kind===k.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=uA())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Ke(10));const i=Date.now();for(;Date.now()-i<A;){const r=e.dimensions;if(r)return r;yield Ke(50)}throw new IA("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===$A(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),$A(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===k.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===k.Kind.Audio?"audioinput":"videoinput";return A?Qe.getInstance().normalizeDeviceId(r,n,i):n}()})}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,A){return C(this,void 0,void 0,function*(){if(!this.sender)throw new IA("unable to replace an unpublished track");let n,i;return typeof A=="boolean"?n=A:A!==void 0&&(n=A.userProvidedTrack,i=A.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return C(this,void 0,void 0,function*(){this.manuallyStopped=!1;const A=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:i}=e,r=fw(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===k.Kind.Video?s.video=n||i?{deviceId:n,facingMode:i}:!0:s.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{Vt(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield o.applyConstraints(r),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=e,this.emit(x.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{A()}})}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?x.Muted:x.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),bd()&&(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 A=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(x.UpstreamPaused,this);const n=uA();if((n==null?void 0:n.name)==="Safari"&&mt(n.version,"12.0")<0)throw new sa("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{A()}})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;const A=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(x.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{A()}})}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(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),o={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield A.init(o),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Kt(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(c=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))),n.processor=A,n.processorElement=a,n.processor.processedTrack){for(const c of n.attachedElements)c!==n.processorElement&&i&&(Vt(n._mediaStreamTrack,c),Kt(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(x.TrackProcessorUpdate,n.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,A||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(x.TrackProcessorUpdate))}()})}}class dr extends Xd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,k.Kind.Audio,A,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!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(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}s&&this.prevStats&&(this._currentBitrate=ur(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(x.AudioTrackFeatureUpdate,this,oA.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(x.AudioTrackFeatureUpdate,this,oA.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===k.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{A()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==$A(this._constraints.deviceId);return this.source===k.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{A()}})}restartTrack(e){return C(this,void 0,void 0,function*(){let A;if(e){const n=Ea({audio:e});typeof n.audio!="boolean"&&(A=n.audio)}yield this.restart(A)})}restart(e){const A=Object.create(null,{restart:{get:()=>super.restart}});return C(this,void 0,void 0,function*(){const n=yield A.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Ve()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Da)))}setProcessor(e){return C(this,void 0,void 0,function*(){var A;const n=yield this.processorLock.lock();try{if(!UA()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield(A=this.sender)===null||A===void 0?void 0:A.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(x.TrackProcessorUpdate,this.processor)}finally{n()}})}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 A=yield this.sender.getStats();let n;return A.forEach(i=>{i.type==="outbound-rtp"&&(n={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),n})}checkForSilence(){return C(this,void 0,void 0,function*(){const e=yield Id(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(x.AudioSilenceDetected)),e})}}function Eb(t,e,A){switch(t.kind){case"audio":return new dr(t,e,!1,void 0,A);case"video":return new fr(t,e,!1,A);default:throw new IA("unsupported track type: ".concat(t.kind))}}const Sb=Object.values(Sn),kb=Object.values(da),Tb=Object.values(ha),Fb=[Sn.h180,Sn.h360],Ib=[da.h180,da.h360],xb=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(A=>{var n,i;return new ee(Math.floor(t.width/A.scaleResolutionDownBy),Math.floor(t.height/A.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(A.scaleResolutionDownBy,2)*(((n=t.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((i=A.fps)!==null&&i!==void 0?i:30))))),A.fps,t.encoding.priority)}),Ha=["q","h","f"];function Oa(t,e,A,n){var i,r;let s=n==null?void 0:n.videoEncoding;t&&(s=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,o=n==null?void 0:n.scalabilityMode,c=n==null?void 0:n.videoCodec;if(!s&&!a&&!o||!e||!A)return[{}];s||(s=Pb(t,e,A,c),W.debug("using video encoding",s));const l=s.maxFramerate,u=new ee(e,A,s.maxBitrate,s.maxFramerate,s.priority);if(o&&kn(c)){const p=new hr(o),f=[];if(p.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(o));const m=uA();if(ZA()||UA()||(m==null?void 0:m.name)==="Chrome"&&mt(m==null?void 0:m.version,"113")<0){const B=p.suffix=="h"?2:3;for(let b=0;b<p.spatial;b+=1)f.push({rid:Ha[2-b],maxBitrate:s.maxBitrate/Math.pow(B,b),maxFramerate:u.encoding.maxFramerate});f[0].scalabilityMode=o}else f.push({maxBitrate:s.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:o});return u.encoding.priority&&(f[0].priority=u.encoding.priority,f[0].networkPriority=u.encoding.priority),W.debug("using svc encoding",{encodings:f}),f}if(!a)return[s];let d=[];t?d=(i=Yd(n==null?void 0:n.screenShareSimulcastLayers))!==null&&i!==void 0?i:qd(t,u):d=(r=Yd(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:qd(t,u);let h;if(d.length>0){const p=d[0];d.length>1&&([,h]=d);const f=Math.max(e,A);if(f>=960&&h)return Ma(e,A,[p,h,u],l);if(f>=480)return Ma(e,A,[p,u],l)}return Ma(e,A,[u])}function _b(t,e,A){var n,i,r,s;if(!A.backupCodec||A.backupCodec===!0||A.backupCodec.codec===A.videoCodec)return;e!==A.backupCodec.codec&&W.warn("requested a different codec than specified as backup",{serverRequested:e,backup:A.backupCodec.codec}),A.videoCodec=e,A.videoEncoding=A.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),o=(n=a.width)!==null&&n!==void 0?n:(i=t.dimensions)===null||i===void 0?void 0:i.width,c=(r=a.height)!==null&&r!==void 0?r:(s=t.dimensions)===null||s===void 0?void 0:s.height;return t.source===k.Source.ScreenShare&&A.simulcast&&(A.simulcast=!1),Oa(t.source===k.Source.ScreenShare,o,c,A)}function Pb(t,e,A,n){const i=Rb(t,e,A);let{encoding:r}=i[0];const s=Math.max(e,A);for(let a=0;a<i.length;a+=1){const o=i[a];if(r=o.encoding,o.width>=s)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Rb(t,e,A){if(t)return Tb;const n=e>A?e/A:A/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Sb:kb}function qd(t,e){if(t)return xb(e);const{width:A,height:n}=e,i=A>n?A/n:n/A;return Math.abs(i-16/9)<Math.abs(i-4/3)?Fb:Ib}function Ma(t,e,A,n){const i=[];if(A.forEach((r,s)=>{if(s>=Ha.length)return;const a=Math.min(t,e),c={rid:Ha[s],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(c.maxFramerate=l);const u=Gt()||s===0;r.encoding.priority&&u&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),UA()&&Ud()==="ios"){let r;i.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let s=!0;i.forEach(a=>{var o;a.maxFramerate!=r&&(s&&(s=!1,W.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),W.info('Setting framerate of encoding "'.concat((o=a.rid)!==null&&o!==void 0?o:"",'" to ').concat(r)),a.maxFramerate=r)})}return i}function Yd(t){if(t)return t.sort((e,A)=>{const{encoding:n}=e,{encoding:i}=A;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class hr{constructor(e){const A=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!A)throw new Error("invalid scalability mode");if(this.spatial=parseInt(A[1]),this.temporal=parseInt(A[2]),A.length>3)switch(A[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=A[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Lb(t){return t.source===k.Source.ScreenShare||t.constraints.height&&$A(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const Db=5e3;class fr extends Xd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,k.Kind.Video,A,n,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const s=new Map(r.map(a=>[a.rid,a]));if(this.prevStats){let a=0;s.forEach((o,c)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(c);a+=ur(o,u)}),this._currentBitrate=a}this.prevStats=s}),this.senderLock=new Oe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var A;if(this.signalClient=e,!Ve())return;const n=(A=this.sender)===null||A===void 0?void 0:A.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Da))}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 A,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var a=!0,o=XA(this.simulcastCodecs.values()),c;c=yield o.next(),A=c.done,!A;a=!0)r=c.value,a=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(l){n={error:l}}finally{try{!a&&!A&&(i=o.return)&&(yield i.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return C(this,void 0,void 0,function*(){var A,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var a=!0,o=XA(this.simulcastCodecs.values()),c;c=yield o.next(),A=c.done,!A;a=!0){r=c.value,a=!1;const l=r;yield(s=l.sender)===null||s===void 0?void 0:s.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!a&&!A&&(i=o.return)&&(yield i.call(o))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===k.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{A()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.source===k.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{A()}})}setTrackMuted(e){super.setTrackMuted(e);for(const A of this.simulcastCodecs.values())A.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 A=[],n=yield this.sender.getStats();return n.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},a=n.get(i.remoteId);a&&(s.jitter=a.jitter,s.packetsLost=a.packetsLost,s.roundTripTime=a.roundTripTime),A.push(s)}}),A.sort((i,r)=>{var s,a;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((a=i.frameWidth)!==null&&a!==void 0?a:0)}),A})}setPublishingQuality(e){const A=[];for(let n=AA.LOW;n<=AA.HIGH;n+=1)A.push(new Xs({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(A)}restartTrack(e){return C(this,void 0,void 0,function*(){var A,n,i,r,s;let a;if(e){const u=Ea({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a);try{for(var o=!0,c=XA(this.simulcastCodecs.values()),l;l=yield c.next(),A=l.done,!A;o=!0){r=l.value,o=!1;const u=r;u.sender&&((s=u.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!o&&!A&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const A=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});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,a,o,c,l,u;if(yield A.setProcessor.call(i,n,r),!((l=i.processor)===null||l===void 0)&&l.processedTrack)try{for(var d=!0,h=XA(i.simulcastCodecs.values()),p;p=yield h.next(),s=p.done,!s;d=!0)c=p.value,d=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(i.processor.processedTrack)}catch(f){a={error:f}}finally{try{!d&&!s&&(o=h.return)&&(yield o.call(h))}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 A=this.sender.getParameters();A.degradationPreference=e,this.sender.setParameters(A)}catch(A){this.log.warn("failed to set degradationPreference",Object.assign({error:A},this.logContext))}})}addSimulcastTrack(e,A){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:A};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,A){const n=this.simulcastCodecs.get(e);n&&(n.sender=A,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Db))}setPublishingCodecs(e){return C(this,void 0,void 0,function*(){var A,n,i,r,s,a,o;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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(A=!0,n=XA(e);i=yield n.next(),r=i.done,!r;A=!0){o=i.value,A=!1;const l=o;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const d of l.qualities)if(d.enabled){c.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield zd(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){s={error:l}}finally{try{!A&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return C(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield zd(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),bd()&&this.isInBackground&&this.source===k.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function zd(t,e,A,n,i,r){return C(this,void 0,void 0,function*(){const s=yield n.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:t,qualities:A,senderEncodings:e}));try{const a=t.getParameters(),{encodings:o}=a;if(!o)return;if(o.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:e}));return}let c=!1;const l=uA();if((l==null?void 0:l.name)==="Chrome"&&mt(l==null?void 0:l.version,"133")>0&&o[0].scalabilityMode){const d=o[0],h=new hr(d.scalabilityMode);let p=Lt.OFF;if(A.forEach(f=>{f.enabled&&(p===Lt.OFF||f.quality>p)&&(p=f.quality)}),p===Lt.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==p+1){c=!0,d.active=!0;const f=new hr(e[0].scalabilityMode);h.spatial=p+1,h.suffix=f.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-p),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else o.forEach((d,h)=>{var p;let f=(p=d.rid)!==null&&p!==void 0?p:"";f===""&&(f="q");const m=Zd(f),B=A.find(b=>b.quality===m);B&&d.active!==B.enabled&&(c=!0,d.active=B.enabled,i.debug("setting layer ".concat(B.quality," to ").concat(d.active?"enabled":"disabled"),r),Gt()&&(B.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(a.encodings=o,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:a.encodings})),yield t.setParameters(a))}finally{s()}})}function Zd(t){switch(t){case"f":return AA.HIGH;case"h":return AA.MEDIUM;case"q":return AA.LOW;default:return AA.HIGH}}function $d(t,e,A,n){if(!A)return[new ft({quality:AA.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(n){const i=A[0].scalabilityMode,r=new hr(i),s=[],a=r.suffix=="h"?1.5:2,o=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new ft({quality:Math.min(AA.HIGH,r.spatial-1)-c,width:Math.ceil(t/Math.pow(a,c)),height:Math.ceil(e/Math.pow(a,c)),bitrate:A[0].maxBitrate?Math.ceil(A[0].maxBitrate/Math.pow(o,c)):0,ssrc:0}));return s}return A.map(i=>{var r,s,a;const o=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=Zd((s=i.rid)!==null&&s!==void 0?s:"");return new ft({quality:c,width:Math.ceil(t/o),height:Math.ceil(e/o),bitrate:(a=i.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const eh="_lossy",Ah="_reliable",Hb=2*1e3,Na="leave-reconnect";var hA;(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"})(hA||(hA={}));class Ob extends yA.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var A;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ra.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=hA.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=W,this.handleDataChannel=n=>C(this,[n],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===Ah)r.reliableDCSub=s;else if(s.label===eh)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>C(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let a;if(n.data instanceof ArrayBuffer)a=n.data;else if(n.data instanceof Blob)a=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const o=Ne.fromBinary(new Uint8Array(a));((i=o.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(_.ActiveSpeakersUpdate,o.value.value.speakers):(((r=o.value)===null||r===void 0?void 0:r.case)==="user"&&Nb(o,o.value.value),this.emit(_.DataPacketReceived,o))}finally{s()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:s}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?X.LOSSY:X.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,i)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=o=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(o,"ms. giving up"),this.logContext),this.emit(_.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(a===null){r(s);return}n===Na&&(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=Te.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,i)=>{this.pcState===hA.Connected&&n();const r=()=>{this.off(_.Disconnected,s),n()},s=()=>{this.off(_.Restarted,r),i()};this.once(_.Restarted,r),this.once(_.Disconnected,s)}),this.updateAndEmitDCBufferStatus=n=>{const i=this.isBufferStatusLow(n);typeof i<"u"&&i!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,i),this.emit(_.DCBufferStatusChanged,i,n))},this.isBufferStatusLow=n=>{const i=this.dataChannelForKind(n);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ne.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Dt.RR_SIGNAL_DISCONNECTED))},this.log=FA((A=e.loggerName)!==null&&A!==void 0?A:lA.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ka(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Oe,this.dataProcessLock=new Oe,this.dcBufferStatus=new Map([[X.LOSSY,!0],[X.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(_.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(_.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(_.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(_.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(_.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(_.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(_.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(_.SignalRequestResponse,n)}get logContext(){var e,A,n,i,r,s,a,o;return{room:(A=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||A===void 0?void 0:A.name,roomID:(i=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(o=(a=this.latestJoinResponse)===null||a===void 0?void 0:a.participant)===null||o===void 0?void 0:o.sid}}join(e,A,n,i){return C(this,void 0,void 0,function*(){this.url=e,this.token=A,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,A,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(_.SignalConnected)},10),r}catch(r){if(r instanceof Ae&&r.reason===J.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,A,n,i);throw r}})}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(_.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 A=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};A(this.lossyDC),A(this.lossyDCSub),A(this.reliableDC),A(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}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 IA("a track with the same ID has already been published");return new Promise((A,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new Ae("publication of local track timed out, no response from server",J.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),A(r)},reject:()=>{clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:A}=this.pendingTrackResolvers[e.track.id];A&&A(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(A){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:A}))}return!1}updateMuteStatus(e,A){this.client.sendMuteTrack(e,A)}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 A,n;if(this.pcManager&&this.pcManager.currentState!==ue.NEW)return;this.participantSid=(A=e.participant)===null||A===void 0?void 0:A.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new Ub(i,e.subscriberPrimary,this.loggerOptions),this.emit(_.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>C(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===ue.CONNECTED){const l=this.pcState===hA.New;this.pcState=hA.Connected,l&&this.emit(_.Connected,e)}else r===ue.FAILED&&this.pcState===hA.Connected&&(this.pcState=hA.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Dt.RR_SUBSCRIBER_FAILED:Dt.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===ne.RECONNECTING,c=[ue.FAILED,ue.CLOSING,ue.CLOSED].includes(r);o&&c&&!this._isClosed&&this.emit(_.Offline)}),this.pcManager.onTrack=r=>{this.emit(_.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Mb((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>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))}),this.client.onTrickle=(e,A)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:A})),this.pcManager.addIceCandidate(e,A))},this.client.onOffer=e=>C(this,void 0,void 0,function*(){if(!this.pcManager)return;const A=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(A)}),this.client.onLocalTrackPublished=e=>{var A;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(A=e.track)===null||A===void 0?void 0:A.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:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(_.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(_.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,A)=>{this.emit(_.RemoteMute,e,A)},this.client.onSubscribedQualityUpdate=e=>{this.emit(_.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var A;this.participantSid=(A=e.participant)===null||A===void 0?void 0:A.sid,this.emit(_.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Dt.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 Mt.DISCONNECT:this.emit(_.Disconnected,e==null?void 0:e.reason),this.close();break;case Mt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Na);break;case Mt.RESUME:this.handleDisconnect(Na)}}}makeRTCConfiguration(e){var A;const n=Object.assign({},this.rtcConfig);if(!((A=this.signalOpts)===null||A===void 0)&&A.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),n.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Un.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}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(eh,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ah,{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,A,n){return C(this,void 0,void 0,function*(){if(fa())return yield this.createTransceiverRTCRtpSender(e,A,n);if(ga())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,A,n,i){return C(this,void 0,void 0,function*(){if(fa())return this.createSimulcastTransceiverSender(e,A,n,i);if(ga())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,A,n){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Wt(e)&&(e.codec=A.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,A,n,i){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(A.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return C(this,void 0,void 0,function*(){var A,n,i;if(!this._isClosed){if(this.attemptingReconnect){W.warn("already attempting reconnect, returning early",this.logContext);return}(((A=this.clientConfiguration)===null||A===void 0?void 0:A.resumeConnection)===Un.DISABLED||((i=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&i!==void 0?i:ue.NEW)===ue.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let s=!0;r instanceof ye?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Xt||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",Dt.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(_.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(A){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:A}))}return null}restartConnection(e){return C(this,void 0,void 0,function*(){var A,n,i;try{if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Xt;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Ae&&s.reason===J.NotAllowed?new ye("could not reconnect, token might be expired"):new Xt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ne.CONNECTED)throw new Xt("Signal connection got severed during reconnect");(A=this.regionUrlProvider)===null||A===void 0||A.resetAttempts(),this.emit(_.Restarted)}catch(r){const s=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return C(this,void 0,void 0,function*(){var A;if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");if(!this.pcManager)throw new ye("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Ae&&i.reason===J.NotAllowed?new ye("could not reconnect, token might be expired"):i instanceof Ae&&i.reason===J.LeaveRequest?i:new Xt(r)}if(this.emit(_.SignalResumed),n){const i=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(i)}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!==ne.CONNECTED)throw new Xt("Signal connection got severed during reconnect");this.client.setReconnected(),((A=this.reliableDC)===null||A===void 0?void 0:A.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(_.Resumed)})}waitForPCInitialConnection(e,A){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(A,e)})}waitForPCReconnected(){return C(this,void 0,void 0,function*(){this.pcState=hA.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ke(Hb),!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=hA.Connected}catch(e){throw this.pcState=hA.Disconnected,new Ae("could not establish PC connection, ".concat(e.message),J.InternalError)}})}publishRpcResponse(e,A,n,i){return C(this,void 0,void 0,function*(){const r=new Ne({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcResponse",value:new au({requestId:A,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,X.RELIABLE)})}publishRpcAck(e,A){return C(this,void 0,void 0,function*(){const n=new Ne({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcAck",value:new su({requestId:A})}});yield this.sendDataPacket(n,X.RELIABLE)})}sendDataPacket(e,A){return C(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(A);const i=this.dataChannelForKind(A);i&&i.send(n),this.updateAndEmitDCBufferStatus(A)})}waitForBufferStatusLow(e){return new Promise((A,n)=>C(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))A();else{const i=()=>n("Engine closed");for(this.once(_.Closing,i);!this.dcBufferStatus.get(e);)yield Ke(10);this.off(_.Closing,i),A()}}))}ensureDataTransportConnected(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new ye("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,a=i?"Subscriber":"Publisher";if(!s)throw new Ae("".concat(a," connection not set"),J.InternalError);let o=!1;!i&&!n.dataChannelForKind(A,i)&&(n.createDataChannels(),o=!0),!o&&!i&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(o=!0),o&&n.negotiate();const c=n.dataChannelForKind(A,i);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(s.isICEConnected&&((r=n.dataChannelForKind(A,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield Ke(50)}throw new Ae("could not establish ".concat(a," connection, state: ").concat(s.getICEConnectionState()),J.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!==ue.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return C(this,void 0,void 0,function*(){return new Promise((e,A)=>C(this,void 0,void 0,function*(){if(!this.pcManager){A(new aa("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&A("cannot negotiate on closed engine"),this.on(_.Closing,i),this.pcManager.publisher.once(Jt.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(a=>{const o=a.codec.toLowerCase();qw(o)&&s.set(a.payload,o)}),this.emit(_.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof aa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Dt.RR_UNKNOWN),A(r)}finally{this.off(_.Closing,i)}}))})}dataChannelForKind(e,A){if(A){if(e===X.LOSSY)return this.lossyDCSub;if(e===X.RELIABLE)return this.reliableDCSub}else{if(e===X.LOSSY)return this.lossyDC;if(e===X.RELIABLE)return this.reliableDC}}sendSyncState(e,A){var n,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),a=(i=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&i!==void 0?i:!0,o=new Array,c=new Array;e.forEach(l=>{l.isDesired!==a&&o.push(l.trackSid),l.isEnabled||c.push(l.trackSid)}),this.client.sendSyncState(new Qu({answer:r?lr({sdp:r.sdp,type:r.type}):void 0,offer:s?lr({sdp:s.sdp,type:s.type}):void 0,subscription:new Xi({trackSids:o,subscribe:!a,participantTracks:[]}),publishTracks:ib(A),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],A=(n,i)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Eu({label:n.label,id:n.id,target:i}))};return A(this.dataChannelForKind(X.LOSSY),cA.PUBLISHER),A(this.dataChannelForKind(X.RELIABLE),cA.PUBLISHER),A(this.dataChannelForKind(X.LOSSY,!0),cA.SUBSCRIBER),A(this.dataChannelForKind(X.RELIABLE,!0),cA.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Te.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ve()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ve()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Xt extends Error{}function Mb(t){return t!==void 0&&t>13}function Nb(t,e){const A=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=A,e.participantIdentity=A;const n=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=n,e.destinationIdentities=n}class Ka{constructor(e,A){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=A}updateToken(e){this.token=e}isCloud(){return ma(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 A=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(i=>i.url===n.url));if(A.length>0){const n=A[0];return this.attemptedRegions.push(n),W.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return C(this,void 0,void 0,function*(){const A=yield fetch("".concat(Kb(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(A.ok){const n=yield A.json();return this.lastUpdateAt=Date.now(),n}else throw new Ae("Could not fetch region settings: ".concat(A.statusText),A.status===401?J.NotAllowed:J.InternalError,A.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Kb(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class th{get info(){return this._info}constructor(e,A,n){this.reader=A,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class Vb extends th{handleChunkReceived(e){var A;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(A=this.onProgress)===null||A===void 0||A.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>C(this,void 0,void 0,function*(){try{const{done:A,value:n}=yield e.read();return A?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return C(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return C(this,void 0,void 0,function*(){var e,A,n,i;let r=new Set;try{for(var s=!0,a=XA(this),o;o=yield a.next(),e=o.done,!e;s=!0){i=o.value,s=!1;const c=i;r.add(c)}}catch(c){A={error:c}}finally{try{!s&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(A)throw A.error}}return Array.from(r)})}}class Gb extends th{constructor(e,A,n){super(e,A,n),this.receivedChunks=new Map}handleChunkReceived(e){var A;const n=or(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(A=this.onProgress)===null||A===void 0||A.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),A=new TextDecoder;return{next:()=>C(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:A.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return C(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return C(this,void 0,void 0,function*(){var e,A,n,i;let r="";try{for(var s=!0,a=XA(this),o;o=yield a.next(),e=o.done,!e;s=!0)i=o.value,s=!1,r+=i}catch(c){A={error:c}}finally{try{!s&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(A)throw A.error}}return r})}}class nh{constructor(e,A,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=A}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 jb extends nh{}class Wb extends nh{}class ih extends k{constructor(e,A,n,i,r){super(e,n,r),this.sid=A,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?x.Muted:x.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const A=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",A),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(x.Ended,this))};e.addEventListener("removetrack",A)}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(),Da)),rb()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var A;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(A=this.receiver)===null||A===void 0?void 0:A.getSynchronizationSources()[0];if(n){const{timestamp:i,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(x.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Jb extends ih{constructor(e,A,n,i,r,s){super(e,A,k.Kind.Audio,n,s),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=ur(a,this.prevStats)),this.prevStats=a}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var A;for(const n of this.attachedElements)this.audioContext?(A=this.gainNode)===null||A===void 0||A.gain.setTargetAtTime(e,0,.1):n.volume=e;UA()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(UA())return 1;let e=0;return this.attachedElements.forEach(A=>{A.volume>e&&(e=A.volume)}),e}setSinkId(e){return C(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(A=>{if(pa(A))return A.setSinkId(e)}))})}attach(e){const A=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&pa(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&A&&(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 A;return e?(A=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(A=super.detach(),this.disconnectWebAudio()),A}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,A){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(A.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{n.connect(i),n=i}),this.gainNode=e.createGain(),n.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(x.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(x.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,A;(e=this.gainNode)===null||e===void 0||e.disconnect(),(A=this.sourceNode)===null||A===void 0||A.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 A;return e.forEach(n=>{n.type==="inbound-rtp"&&(A={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),A})}}const Va=100;class Xb extends ih{constructor(e,A,n,i,r){super(e,A,k.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=ur(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=_a(()=>{this.updateDimensions()},Va),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(A=>{e?Vt(this._mediaStreamTrack,A):Kt(this._mediaStreamTrack,A)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(A=>A.element===e)===void 0){const A=new qb(e);this.observeElementInfo(A)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(A=>A===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 A=this.elementInfos.filter(n=>n===e);for(const n of A)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let A=[];if(e)return this.stopObservingElement(e),super.detach(e);A=super.detach();for(const n of A)this.stopObservingElement(n);return A}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 A,n="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,A={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&i.set(r.id,r)}),A&&n!==""&&i.get(n)&&(A.mimeType=i.get(n).mimeType),A})}stopObservingElement(e){const A=this.elementInfos.filter(n=>n.element===e);for(const n of A)this.stopObservingElementInfo(n)}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,A;const n=this.elementInfos.reduce((a,o)=>Math.max(a,o.visibilityChangedAt||0),0),i=!((A=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&A!==void 0)||A?this.isInBackground:!1,r=this.elementInfos.some(a=>a.pictureInPicture),s=this.elementInfos.some(a=>a.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-n<Va){Te.setTimeout(()=>{this.updateVisibility()},Va);return}this.lastVisible=s,this.emit(x.VisibilityChanged,s,this)}}updateDimensions(){var e,A;let n=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const a=s.width()*r,o=s.height()*r;a+o>n+i&&(n=a,i=o)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((A=this.lastDimensions)===null||A===void 0?void 0:A.height)===i||(this.lastDimensions={width:n,height:i},this.emit(x.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const A=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return A==="screen"?Qd():A||(Qd()>2?2:1)}}class qb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,A){this.onVisibilityChanged=n=>{var i;const{target:r,isIntersecting:s}=n;r===this.element&&(this.isIntersecting=s,this.isPiP=In(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var n,i,r;(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=In(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=In(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=A??Ga(e),this.isPiP=Ve()&&In(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,A,n;this.isIntersecting=Ga(this.element),this.isPiP=In(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Sd().observe(this.element),Ed().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),(n=(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,A,n,i,r;(e=Sd())===null||e===void 0||e.unobserve(this.element),(A=Ed())===null||A===void 0||A.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function In(t){var e,A;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ga(t,(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window):!1}function Ga(t,e){const A=e||window;let n=t.offsetTop,i=t.offsetLeft;const r=t.offsetWidth,s=t.offsetHeight,{hidden:a}=t,{display:o}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,n+=t.offsetTop,i+=t.offsetLeft;return n<A.pageYOffset+A.innerHeight&&i<A.pageXOffset+A.innerWidth&&n+s>A.pageYOffset&&i+r>A.pageXOffset&&!a&&o!=="none"}class _A extends yA.EventEmitter{constructor(e,A,n,i){var r;super(),this.metadataMuted=!1,this.encryption=qe.NONE,this.log=W,this.handleMuted=()=>{this.emit(x.Muted)},this.handleUnmuted=()=>{this.emit(x.Unmuted)},this.log=FA((r=i==null?void 0:i.loggerName)!==null&&r!==void 0?r:lA.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=A,this.trackName=n,this.source=k.Source.Unknown}setTrack(e){this.track&&(this.track.off(x.Muted,this.handleMuted),this.track.off(x.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(x.Muted,this.handleMuted),e.on(x.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),z(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==qe.NONE}get audioTrack(){if(xA(this.track))return this.track}get videoTrack(){if(Wt(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=k.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===k.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={}))})(_A||(_A={}));class ja extends _A{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,A,n,i){super(e,A.sid,A.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(x.Ended)},this.updateInfo(A),this.setTrack(n)}setTrack(e){this.track&&this.track.off(x.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(x.Ended,this.handleTrackEnded)}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(xA(this.track)){const A=this.track.getSourceTrackSettings(),n=new Set;return A.autoGainControl&&n.add(oA.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&n.add(oA.TF_ECHO_CANCELLATION),A.noiseSuppression&&n.add(oA.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&n.add(oA.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(oA.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(oA.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function gr(t,e){return C(this,void 0,void 0,function*(){t??(t={});let A=!1;const{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:r}=Pd(t);let s=r.audio,a=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),i&&typeof r.video=="object"&&(r.video.processor=i),t.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},A=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},A=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const o=Fd(r,Gd,jd),c=Ea(o),l=navigator.mediaDevices.getUserMedia(c);r.audio&&(Qe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>Qe.userMediaPromiseMap.delete("audioinput"))),r.video&&(Qe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>Qe.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(d=>C(this,void 0,void 0,function*(){const h=d.kind==="audio";let p=h?o.audio:o.video;(typeof p=="boolean"||!p)&&(p={});let f;const m=h?c.audio:c.video;typeof m!="boolean"&&(f=m);const B=d.getSettings().deviceId;f!=null&&f.deviceId&&$A(f.deviceId)!==B?f.deviceId=B:f||(f={deviceId:B});const b=Eb(d,f,e);return b.kind===k.Kind.Video?b.source=k.Source.Camera:b.kind===k.Kind.Audio&&(b.source=k.Source.Microphone),b.mediaStream=u,xA(b)&&n?yield b.setProcessor(n):Wt(b)&&i&&(yield b.setProcessor(i)),b})))}catch(u){if(!A)throw u;return gr(Object.assign(Object.assign({},t),{audio:s,video:a}),e)}})}function Yb(t){return C(this,void 0,void 0,function*(){return(yield gr({audio:!1,video:t??!0}))[0]})}function zb(t){return C(this,void 0,void 0,function*(){return(yield gr({audio:t??!0,video:!1}))[0]})}var tt;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(tt||(tt={}));function Zb(t){switch(t){case yn.EXCELLENT:return tt.Excellent;case yn.GOOD:return tt.Good;case yn.POOR:return tt.Poor;case yn.LOST:return tt.Lost;default:return tt.Unknown}}class rh extends yA.EventEmitter{get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||A===void 0?void 0:A.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===Ji.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ht.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,A,n,i,r,s){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ji.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=tt.Unknown,this.log=W,this.log=FA((o=s==null?void 0:s.loggerName)!==null&&o!==void 0?o:lA.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=A,this.name=n,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,A]of this.trackPublications)if(A.source===e)return A}getTrackPublicationByName(e){for(const[,A]of this.trackPublications)if(A.trackName===e)return A}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new wa,this.once(P.Active,()=>{var e,A;(A=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||A===void 0||A.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const A=this.getTrackPublication(k.Source.Camera);return!(!((e=A==null?void 0:A.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const A=this.getTrackPublication(k.Source.Microphone);return!(!((e=A==null?void 0:A.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(k.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 A;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===Ht.ACTIVE&&((A=this.participantInfo)===null||A===void 0?void 0:A.state)!==Ht.ACTIVE&&this.emit(P.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const A=this.metadata!==e,n=this.metadata;this.metadata=e,A&&this.emit(P.ParticipantMetadataChanged,n)}_setName(e){const A=this.name!==e;this.name=e,A&&this.emit(P.ParticipantNameChanged,e)}_setAttributes(e){const A=sb(this.attributes,e);this._attributes=e,Object.keys(A).length>0&&this.emit(P.AttributesChanged,A)}setPermissions(e){var A,n,i,r,s,a;const o=this.permissions,c=e.canPublish!==((A=this.permissions)===null||A===void 0?void 0:A.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var d;return l!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(P.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(P.IsSpeakingChanged,e))}setConnectionQuality(e){const A=this._connectionQuality;this._connectionQuality=Zb(e),A!==this._connectionQuality&&this.emit(P.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,A;this.activeFuture&&((A=(e=this.activeFuture).reject)===null||A===void 0||A.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(A=>xA(A.track)&&A.track.setAudioContext(e))}addTrackPublication(e){e.on(x.Muted,()=>{this.emit(P.TrackMuted,e)}),e.on(x.Unmuted,()=>{this.emit(P.TrackUnmuted,e)});const A=e;switch(A.track&&(A.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case k.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case k.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function $b(t){var e,A,n;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new yu({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(A=t.participantSid)!==null&&A!==void 0?A:"",allTracks:(n=t.allowAll)!==null&&n!==void 0?n:!1,trackSids:t.allowedTrackSids||[]})}const sh=15e3;class ey extends rh{constructor(e,A,n,i,r){super(e,A,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=qe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new wa)},this.handleReconnected=()=>{var s,a;(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||a===void 0||a.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(o=>this.log.warn(o.message,this.logContext)),(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||a===void 0||a.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:a,reason:o,message:c}=s,l=this.pendingSignalRequests.get(a);l&&(o!==qs.OK&&l.reject(new Bd(c,o)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let a=s.value.value,o=null,c=null;a.value.case==="payload"?o=a.value.value:a.value.case==="error"&&(c=de.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,o,c);break;case"rpcAck":let l=s.value.value;this.handleIncomingRpcAck(l.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(s=>$b(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,a)=>{if(a===void 0&&(a=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),z(s)));return}this.engine.updateMuteStatus(s.sid,a)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),z(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),z(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const a=this.audioTrackPublications.get(s.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>C(this,void 0,void 0,function*(){var a,o,c,l,u,d;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const B=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var p=!0,f=XA(B),m;m=yield f.next(),a=m.done,!a;p=!0){l=m.value,p=!1;const b=l;Hw(b)&&(this.log.debug("publish ".concat(b," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),z(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,b,h.options))}}catch(b){o={error:b}}finally{try{!p&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const a=this.trackPublications.get(s.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=s=>C(this,void 0,void 0,function*(){if(s.source===k.Source.ScreenShare||s.source===k.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),z(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(vt(s)||et(s))try{if(Ve())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:s.source===k.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),z(s))),a.onchange=()=>{a.state!=="denied"&&(s.isMuted||s.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),z(s))),vt(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),z(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==qe.NONE}getTrackPublication(e){const A=super.getTrackPublication(e);if(A)return A}getTrackPublicationByName(e){const A=super.getTrackPublicationByName(e);if(A)return A}setupEngine(e){this.engine=e,this.engine.on(_.RemoteMute,(A,n)=>{const i=this.trackPublications.get(A);!i||!i.track||(n?i.mute():i.unmute())}),this.engine.on(_.Connected,this.handleReconnected).on(_.SignalRestarted,this.handleReconnected).on(_.SignalResumed,this.handleReconnected).on(_.Restarting,this.handleReconnecting).on(_.Resuming,this.handleReconnecting).on(_.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_.Disconnected,this.handleDisconnected).on(_.SignalRequestResponse,this.handleSignalRequestResponse).on(_.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(A){var n=this;let{metadata:i,name:r,attributes:s}=A;return function*(){return new Promise((a,o)=>C(n,void 0,void 0,function*(){var c,l;try{let u=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(l=r??this.name)!==null&&l!==void 0?l:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:a,reject:p=>{o(p),u=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!u;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(p=>{let[f,m]=p;return this.attributes[f]===m||m===""&&!this.attributes[f]}))){this.pendingSignalRequests.delete(d),a();return}yield Ke(50)}o(new Bd("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&o(u)}}))}()})}setCameraEnabled(e,A,n){return this.setTrackEnabled(k.Source.Camera,e,A,n)}setMicrophoneEnabled(e,A,n){return this.setTrackEnabled(k.Source.Microphone,e,A,n)}setScreenShareEnabled(e,A,n){return this.setTrackEnabled(k.Source.ScreenShare,e,A,n)}setPermissions(e){const A=this.permissions,n=super.setPermissions(e);return n&&A&&this.emit(P.ParticipantPermissionsChanged,A),n}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){this.encryptionType=e?qe.GCM:qe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,A,n,i){return C(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:A})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(A)if(a)yield a.unmute();else{let o;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case k.Source.Camera:o=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case k.Source.Microphone:o=yield this.createTracks({audio:(s=n)!==null&&s!==void 0?s:!0});break;case k.Source.ScreenShare:o=yield this.createScreenTracks(Object.assign({},n));break;default:throw new IA(e)}}catch(c){throw o==null||o.forEach(l=>{l.stop()}),c instanceof Error&&this.emit(P.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const u of o)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),z(u))),c.push(this.publishTrack(u,i));[a]=yield Promise.all(c)}catch(c){throw o==null||o.forEach(l=>{l.stop()}),c}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===k.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const o=this.getTrackPublication(k.Source.ScreenShareAudio);o&&o.track&&this.unpublishTrack(o.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return C(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(k.Source.Camera)||this.pendingPublishing.has(k.Source.Microphone))){this.pendingPublishing.add(k.Source.Camera),this.pendingPublishing.add(k.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(A=>this.publishTrack(A)))}finally{this.pendingPublishing.delete(k.Source.Camera),this.pendingPublishing.delete(k.Source.Microphone)}}})}createTracks(e){return C(this,void 0,void 0,function*(){var A,n;e??(e={});const i=Fd(e,(A=this.roomOptions)===null||A===void 0?void 0:A.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield gr(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(xA(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=k.Source.Microphone,this.emit(P.AudioStreamAcquired)),Wt(a)&&(this.cameraError=void 0,a.source=k.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return C(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new sa("getDisplayMedia not supported");e.resolution===void 0&&!Gw()&&(e.resolution=ha.h1080fps30.resolution);const A=nb(e),n=yield navigator.mediaDevices.getDisplayMedia(A),i=n.getVideoTracks();if(i.length===0)throw new IA("no video track found");const r=new fr(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=k.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(P.AudioStreamAcquired);const a=new dr(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=k.Source.ScreenShareAudio,s.push(a)}return s})}publishTrack(e,A){return C(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,A)})}publishOrRepublishTrack(e,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,o,c,l;vt(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!s&&(yield r.republishPromise),jt(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let B;switch(n.source){case k.Source.Microphone:B="audioinput";break;case k.Source.Camera:B="videoinput"}B&&r.activeDeviceMap.has(B)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(B)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new dr(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new fr(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new IA("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let d;if(r.trackPublications.forEach(B=>{B.track&&B.track===n&&(d=B)}),d)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),z(d))),d;const h="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,p=(o=i==null?void 0:i.forceStereo)!==null&&o!==void 0?o:h;p&&(i||(i={}),i.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),z(n))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(l=i.red)!==null&&l!==void 0||(i.red=!1));const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!jw()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(n.source=f.source);const m=new Promise((B,b)=>C(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ne.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:z(n)}));const U=()=>C(this,void 0,void 0,function*(){try{const w=yield this.publish(n,f,p);B(w)}catch(w){b(w)}});setTimeout(()=>{this.engine.off(_.SignalConnected,U),b(new oa("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(_.SignalConnected,U),this.engine.on(_.Closing,()=>{this.engine.off(_.SignalConnected,U),b(new oa("publishing rejected as engine closed",499))})}else try{const U=yield this.publish(n,f,p);B(U)}catch(U){b(U)}}catch(U){b(U)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(B){throw B}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),z(e))),!1;const{canPublish:A,canPublishSources:n}=this.permissions;return A&&(n.length===0||n.map(i=>ab(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),z(e))),!1)}publish(e,A,n){return C(this,void 0,void 0,function*(){var i,r,s,a,o,c,l,u,d,h;if(!this.hasPermissionsToPublish(e))throw new oa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(v=>jt(e)&&v.source===e.source)&&e.source!==k.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),z(e))),A.stopMicTrackOnMute&&xA(e)&&(e.stopOnMute=!0),e.source===k.Source.ScreenShare&&Gt()&&(A.simulcast=!1),A.videoCodec==="av1"&&!Nw()&&(A.videoCodec=void 0),A.videoCodec==="vp9"&&!Kw()&&(A.videoCodec=void 0),A.videoCodec===void 0&&(A.videoCodec=Pa),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(v=>A.videoCodec===cr(v.mime))||(A.videoCodec=cr(this.enabledPublishVideoCodecs[0].mime)));const f=A.videoCodec;e.on(x.Muted,this.onTrackMuted),e.on(x.Unmuted,this.onTrackUnmuted),e.on(x.Ended,this.handleTrackEnded),e.on(x.UpstreamPaused,this.onTrackUpstreamPaused),e.on(x.UpstreamResumed,this.onTrackUpstreamResumed),e.on(x.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new Gs({cid:e.mediaStreamTrack.id,name:A.name,type:k.kindToProto(e.kind),muted:e.isMuted,source:k.sourceToProto(e.source),disableDtx:!(!((i=A.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=A.red)!==null&&r!==void 0)||r),stream:A==null?void 0:A.stream,backupCodecPolicy:A==null?void 0:A.backupCodecPolicy});let B;if(e.kind===k.Kind.Video){let v={width:0,height:0};try{v=yield e.waitForDimensions()}catch{const E=(a=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&a!==void 0?a:Sn.h720.resolution;v={width:E.width,height:E.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),z(e)),{dims:v}))}m.width=v.width,m.height=v.height,et(e)&&(kn(f)&&(e.source===k.Source.ScreenShare&&(A.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),z(e))))),A.scalabilityMode=(o=A.scalabilityMode)!==null&&o!==void 0?o:"L3T3_KEY"),m.simulcastCodecs=[new Vs({codec:f,cid:e.mediaStreamTrack.id})],A.backupCodec===!0&&(A.backupCodec={codec:Pa}),A.backupCodec&&f!==A.backupCodec.codec&&m.encryption===qe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new Vs({codec:A.backupCodec.codec,cid:""})))),B=Oa(e.source===k.Source.ScreenShare,m.width,m.height,A),m.layers=$d(m.width,m.height,B,kn(A.videoCodec))}else e.kind===k.Kind.Audio&&(B=[{maxBitrate:(c=A.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(u=(l=A.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(h=(d=A.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const b=()=>C(this,void 0,void 0,function*(){var v,y,E;if(!this.engine.pcManager)throw new ye("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,A,B),et(e)&&((v=A.degradationPreference)!==null&&v!==void 0||(A.degradationPreference=Lb(e)),e.setDegradationPreference(A.degradationPreference)),B)if(Gt()&&e.kind===k.Kind.Audio){let T;for(const F of this.engine.pcManager.publisher.getTransceivers())if(F.sender===e.sender){T=F;break}T&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:T,codec:"opus",maxbr:!((y=B[0])===null||y===void 0)&&y.maxBitrate?B[0].maxBitrate/1e3:0})}else e.codec&&kn(e.codec)&&(!((E=B[0])===null||E===void 0)&&E.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:B[0].maxBitrate/1e3});yield this.engine.negotiate()});let U;if(this.enabledPublishVideoCodecs.length>0)U=(yield Promise.all([this.engine.addTrack(m),b()]))[0];else{U=yield this.engine.addTrack(m);let v;if(U.codecs.forEach(y=>{v===void 0&&(v=y.mimeType)}),v&&e.kind===k.Kind.Video){const y=cr(v);y!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),z(e)),{codec:y})),A.videoCodec=y,B=Oa(e.source===k.Source.ScreenShare,m.width,m.height,A))}yield b()}const w=new ja(e.kind,U,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return w.options=A,e.sid=U.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:B,trackInfo:U})),et(e)?e.startMonitor(this.engine.client):vt(e)&&e.startMonitor(),this.addTrackPublication(w),this.emit(P.LocalTrackPublished,w),w})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,A,n){return C(this,void 0,void 0,function*(){var i;if(this.encryptionType!==qe.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new IA("track is not published");if(!et(e))throw new IA("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),n),a=_b(e,A,s);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),z(e)));return}const o=e.addSimulcastTrack(A,a);if(!o)return;const c=new Gs({cid:o.mediaStreamTrack.id,type:k.kindToProto(e.kind),muted:e.isMuted,source:k.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=$d(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const l=()=>C(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,s,a),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(A," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))})}unpublishTrack(e,A){return C(this,void 0,void 0,function*(){var n,i;if(jt(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),z(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?z(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(x.Muted,this.onTrackMuted),e.off(x.Unmuted,this.onTrackUnmuted),e.off(x.Ended,this.handleTrackEnded),e.off(x.UpstreamPaused,this.onTrackUpstreamPaused),e.off(x.UpstreamResumed,this.onTrackUpstreamResumed),e.off(x.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),A===void 0&&(A=(i=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),A?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ue.FAILED&&o)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===o&&(c.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),et(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(a=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case k.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case k.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(P.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return C(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,s)=>C(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(o=>{o.track&&(A&&(o.options=Object.assign(Object.assign({},o.options),A)),a.push(o))}),yield Promise.all(a.map(o=>C(this,void 0,void 0,function*(){const c=o.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==k.Source.ScreenShare&&c.source!==k.Source.ScreenShareAudio&&(vt(c)||et(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:o.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,o.options,!0)}))),r()}catch(a){s(a)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?X.RELIABLE:X.LOSSY,s=i.destinationIdentities,a=i.topic,o=new Ne({kind:r,value:{case:"user",value:new nu({participantIdentity:n.identity,payload:A,destinationIdentities:s,topic:a})}});yield n.engine.sendDataPacket(o,r)}()})}publishDtmf(e,A){return C(this,void 0,void 0,function*(){const n=new Ne({kind:X.RELIABLE,value:{case:"sipDtmf",value:new iu({code:e,digit:A})}});yield this.engine.sendDataPacket(n,X.RELIABLE)})}sendChatMessage(e,A){return C(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:A==null?void 0:A.attachments},i=new Ne({value:{case:"chatMessage",value:new Ds(Object.assign(Object.assign({},n),{timestamp:re.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,X.RELIABLE),this.emit(P.ChatMessage,n),n})}editChatMessage(e,A){return C(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},A),{message:e,editTimestamp:Date.now()}),i=new Ne({value:{case:"chatMessage",value:new Ds(Object.assign(Object.assign({},n),{timestamp:re.parse(n.timestamp),editTimestamp:re.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,X.RELIABLE),this.emit(P.ChatMessage,n),n})}sendText(e,A){return C(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,a=(n=A==null?void 0:A.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),o=new Array(a?a.length+1:1).fill(0),c=(u,d)=>{var h;o[d]=u;const p=o.reduce((f,m)=>f+m,0);(h=A==null?void 0:A.onProgress)===null||h===void 0||h.call(A,p)},l=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:A==null?void 0:A.destinationIdentities,topic:A==null?void 0:A.topic,attachedStreamIds:a,attributes:A==null?void 0:A.attributes});return yield l.write(e),c(1,0),yield l.close(),A!=null&&A.attachments&&a&&(yield Promise.all(A.attachments.map((u,d)=>C(this,void 0,void 0,function*(){return this._sendFile(a[d],u,{topic:A.topic,mimeType:u.type,onProgress:h=>{c(h,d+1)}})})))),l.info})}streamText(e){return C(this,void 0,void 0,function*(){var A,n;const i=(A=e==null?void 0:e.streamId)!==null&&A!==void 0?A:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new Os({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:Bt(r.timestamp),totalLength:Bt(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new gu({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"?Hs.UPDATE:Hs.CREATE})}}),a=e==null?void 0:e.destinationIdentities,o=new Ne({destinationIdentities:a,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(o,X.RELIABLE);let c=0;const l=this,u=new WritableStream({write(p){return C(this,void 0,void 0,function*(){for(const f of Ab(p,sh)){yield l.engine.waitForBufferStatusLow(X.RELIABLE);const m=new Ms({content:f,streamId:i,chunkIndex:Bt(c)}),B=new Ne({destinationIdentities:a,value:{case:"streamChunk",value:m}});yield l.engine.sendDataPacket(B,X.RELIABLE),c+=1}})},close(){return C(this,void 0,void 0,function*(){const p=new Ns({streamId:i}),f=new Ne({destinationIdentities:a,value:{case:"streamTrailer",value:p}});yield l.engine.sendDataPacket(f,X.RELIABLE)})},abort(p){console.log("Sink error:",p)}});let d=()=>C(this,void 0,void 0,function*(){yield h.close()});l.engine.once(_.Closing,d);const h=new jb(u,r,()=>this.engine.off(_.Closing,d));return h})}sendFile(e,A){return C(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,A),{id:n}})}_sendFile(e,A,n){return C(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:A.size,name:A.name,mimeType:(i=n==null?void 0:n.mimeType)!==null&&i!==void 0?i:A.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),s=A.stream().getReader();for(;;){const{done:a,value:o}=yield s.read();if(a)break;yield r.write(o)}return yield r.close(),r.info})}streamBytes(e){return C(this,void 0,void 0,function*(){var A,n,i,r,s;const a=(A=e==null?void 0:e.streamId)!==null&&A!==void 0?A:crypto.randomUUID(),o=e==null?void 0:e.destinationIdentities,c={id:a,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown"},l=new Os({totalLength:Bt((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:Bt(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new pu({name:c.name})}}),u=new Ne({destinationIdentities:o,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,X.RELIABLE);let d=0;const h=new Oe,p=this.engine,f=this.log,m=new WritableStream({write(b){return C(this,void 0,void 0,function*(){const U=yield h.lock();let w=0;try{for(;w<b.byteLength;){const v=b.slice(w,w+sh);yield p.waitForBufferStatusLow(X.RELIABLE);const y=new Ne({destinationIdentities:o,value:{case:"streamChunk",value:new Ms({content:v,streamId:a,chunkIndex:Bt(d)})}});yield p.sendDataPacket(y,X.RELIABLE),d+=1,w+=v.byteLength}}finally{U()}})},close(){return C(this,void 0,void 0,function*(){const b=new Ns({streamId:a}),U=new Ne({destinationIdentities:o,value:{case:"streamTrailer",value:b}});yield p.sendDataPacket(U,X.RELIABLE)})},abort(b){f.error("Sink error:",b)}});return new Wb(m,c)})}performRpc(e){return C(this,arguments,void 0,function(A){var n=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:a=1e4}=A;return function*(){return new Promise((c,l)=>C(n,void 0,void 0,function*(){var u,d,h,p;if(La(s)>Wd){l(de.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||d===void 0)&&d.version&&mt((p=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||p===void 0?void 0:p.version,"1.8.0")<0){l(de.builtIn("UNSUPPORTED_SERVER"));return}const f=crypto.randomUUID();yield this.publishRpcRequest(i,f,r,s,a-2e3);const m=setTimeout(()=>{this.pendingAcks.delete(f),l(de.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(f),clearTimeout(B)},2e3);this.pendingAcks.set(f,{resolve:()=>{clearTimeout(m)},participantIdentity:i});const B=setTimeout(()=>{this.pendingResponses.delete(f),l(de.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(f,{resolve:(b,U)=>{clearTimeout(B),this.pendingAcks.has(f)&&(console.warn("RPC response received before ack",f),this.pendingAcks.delete(f),clearTimeout(m)),U?l(U):c(b??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,A){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,A)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=A,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const A=this.pendingAcks.get(e);A?(A.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,A,n){const i=this.pendingResponses.get(e);i?(i.resolve(A,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,A,n,i,r){return C(this,void 0,void 0,function*(){const s=new Ne({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcRequest",value:new ru({id:A,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,X.RELIABLE)})}handleParticipantDisconnected(e){for(const[A,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(A);for(const[A,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,de.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(A))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(A=>A.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(A=>{var n,i;const r=this.trackPublications.get(A.sid);if(r){const s=r.isMuted||((i=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==A.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),z(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(A.sid,s))}}),!0):!1}getPublicationForTrack(e){let A;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(vt(i)||et(i))&&i.mediaStreamTrack===e&&(A=n):e===i&&(A=n))}),A}waitForPendingPublicationOfSource(e){return C(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield Ke(20)}})}}class Ay extends _A{constructor(e,A,n,i){super(e,A.sid,A.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=AA.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(x.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(A)}setSubscribed(e){const A=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Xi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new cu({participantSid:"",trackSids:[this.trackSid]})]});this.emit(x.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(A),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?_A.SubscriptionStatus.Unsubscribed:super.isSubscribed?_A.SubscriptionStatus.Subscribed:_A.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?_A.PermissionStatus.Allowed:_A.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var A,n;this.isManualOperationAllowed()&&(((A=this.videoDimensions)===null||A===void 0?void 0:A.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Ua(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Ua(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const A=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(x.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(x.VisibilityChanged,this.handleVisibilityChange),i.off(x.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(x.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(x.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(x.VisibilityChanged,this.handleVisibilityChange),e.on(x.Ended,this.handleEnded),this.emit(x.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(A))}setAllowed(e){const A=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(A)}setSubscriptionError(e){this.emit(x.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const A=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):A!==e.muted&&this.emit(e.muted?x.Muted:x.Unmuted)}emitSubscriptionUpdateIfChanged(e){const A=this.subscriptionStatus;e!==A&&this.emit(x.SubscriptionStatusChanged,A,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(x.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===k.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Ua(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Bu({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=AA.HIGH,this.emit(x.UpdateSettings,e)}}class pr extends rh{static fromParticipantInfo(e,A,n){return new pr(e,A.sid,A.identity,A.name,A.metadata,A.attributes,n,A.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,A,n,i,r,s,a){let o=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ji.STANDARD;super(A,n||"",i,r,s,a,o),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(x.UpdateSettings,A=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),z(e))),this.signalClient.sendUpdateTrackSettings(A)}),e.on(x.UpdateSubscription,A=>{A.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(A)}),e.on(x.SubscriptionPermissionChanged,A=>{this.emit(P.TrackSubscriptionPermissionChanged,e,A)}),e.on(x.SubscriptionStatusChanged,A=>{this.emit(P.TrackSubscriptionStatusChanged,e,A)}),e.on(x.Subscribed,A=>{this.emit(P.TrackSubscribed,A,e)}),e.on(x.Unsubscribed,A=>{this.emit(P.TrackUnsubscribed,A,e)}),e.on(x.SubscriptionFailed,A=>{this.emit(P.TrackSubscriptionFailed,e.trackSid,A)})}getTrackPublication(e){const A=super.getTrackPublication(e);if(A)return A}getTrackPublicationByName(e){const A=super.getTrackPublicationByName(e);if(A)return A}setVolume(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:k.Source.Microphone;this.volumeMap.set(A,e);const n=this.getTrackPublication(A);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:k.Source.Microphone;const A=this.getTrackPublication(e);return A&&A.track?A.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,A,n,i,r,s){let a=this.getTrackPublicationBySid(A);if(a||A.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:A})),this.emit(P.TrackSubscriptionFailed,A);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,A,n,i,r,s-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),z(a))),this.emit(P.TrackSubscriptionFailed,A);return}const o=e.kind==="video";let c;return o?c=new Xb(e,A,i,r):c=new Jb(e,A,i,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(n),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&ya(c)&&xA(c)&&c.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 A=new Map,n=new Map;return e.tracks.forEach(i=>{var r,s;let a=this.getTrackPublicationBySid(i.sid);if(a)a.updateInfo(i);else{const o=k.kindFromProto(i.type);if(!o)return;a=new Ay(o,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),a.updateInfo(i),n.set(i.sid,a);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));c&&a.source!==k.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:z(c),newTrack:z(a)})),this.addTrackPublication(a)}A.set(i.sid,a)}),this.trackPublications.forEach(i=>{A.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),z(i))),this.unpublishTrack(i.trackSid,!0))}),n.forEach(i=>{this.emit(P.TrackPublished,i)}),!0}unpublishTrack(e,A){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case k.Kind.Audio:this.audioTrackPublications.delete(e);break;case k.Kind.Video:this.videoTrackPublications.delete(e);break}A&&this.emit(P.TrackUnpublished,n)}setAudioOutput(e){return C(this,void 0,void 0,function*(){this.audioOutput=e;const A=[];this.audioTrackPublications.forEach(n=>{var i;xA(n.track)&&ya(n.track)&&A.push(n.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(A)})}emit(e){for(var A=arguments.length,n=new Array(A>1?A-1:0),i=1;i<A;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var q;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(q||(q={}));const ty=4*1e3;class qt extends yA.EventEmitter{constructor(e){var A,n,i,r;if(super(),A=this,this.state=q.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=W,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,a,o)=>C(this,void 0,void 0,function*(){var c;if(!Vw())throw UA()?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 l=yield this.disconnectLock.lock();if(this.state===q.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(q.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ma(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ka(s,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(h=>{var p;(p=this.regionUrlProvider)===null||p===void 0||p.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const u=(h,p,f)=>C(this,void 0,void 0,function*(){var m,B;this.abortController&&this.abortController.abort();const b=new AbortController;this.abortController=b,l==null||l();try{yield this.attemptConnection(f??s,a,o,b),this.abortController=void 0,h()}catch(U){if(this.regionUrlProvider&&U instanceof Ae&&U.reason!==J.Cancelled&&U.reason!==J.NotAllowed){let w=null;try{w=yield this.regionUrlProvider.getNextBestRegionUrl((m=this.abortController)===null||m===void 0?void 0:m.signal)}catch(v){if(v instanceof Ae&&(v.status===401||v.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(v);return}}w&&!(!((B=this.abortController)===null||B===void 0)&&B.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(U.message,". Retrying with another region: ").concat(w),this.logContext),this.recreateEngine(),yield u(h,p,w)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Td(U)),p(U))}else{let w=aA.UNKNOWN_REASON;U instanceof Ae&&(w=Td(U)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,w),p(U)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new wa((h,p)=>{u(h,p,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,a,o,c,l,u)=>C(this,void 0,void 0,function*(){var d,h,p;const f=yield o.join(s,a,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},u.signal);let m=f.serverInfo;if(m||(m={version:f.serverVersion,region:f.serverRegion}),this.serverInfo=m,this.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(B=>{let[b,U]=B;return"".concat(b,": ").concat(U)}).join(", ")),{room:(d=f.room)===null||d===void 0?void 0:d.name,roomSid:(h=f.room)===null||h===void 0?void 0:h.sid,identity:(p=f.participant)===null||p===void 0?void 0:p.identity}),!m.version)throw new kw("unknown server version");return m.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),f}),this.applyJoinResponse=s=>{const a=s.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(o){this.log.error(o instanceof Error?o.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:o}))}this.handleParticipantUpdates([a,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,a,o,c)=>C(this,void 0,void 0,function*(){var l,u;this.state===q.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.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({},Ra),o),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,a,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(I.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Ae("could not establish signal connection",J.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Ae&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ae("Connection attempt aborted",J.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Ve()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ve()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(q.Connected),this.emit(I.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];return C(A,[...a],void 0,function(){var c=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,d,h,p;const f=yield c.disconnectLock.lock();try{if(c.state===q.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===q.Connecting||c.state===q.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(u=c.abortController)===null||u===void 0||u.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Ae("Client initiated disconnect",J.Cancelled)),c.connectFuture=void 0),!((p=c.engine)===null||p===void 0)&&p.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(l,aA.CLIENT_INITIATED),c.engine=void 0}finally{f()}}()})},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 s=[],a=uA();if(a&&a.os==="iOS"){const o="livekit-dummy-audio-el";let c=document.getElementById(o);if(!c){c=document.createElement("audio"),c.id=o,c.autoplay=!0,c.hidden=!0;const l=Ca();l.enabled=!0;const u=new MediaStream([l]);c.srcObject=u,document.addEventListener("visibilitychange",()=>{c&&(c.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(c),this.once(I.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(o=>{o.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(l=>{s.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(o=>(o.muted=!1,o.play()))]),this.handleAudioPlaybackStarted()}catch(o){throw this.handleAudioPlaybackFailed(o),o}}),this.startVideo=()=>C(this,void 0,void 0,function*(){const s=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(o=>{var c;(c=o.track)===null||c===void 0||c.attachedElements.forEach(l=>{s.includes(l)||s.push(l)})});yield Promise.all(s.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 s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(q.Reconnecting)&&this.emit(I.Reconnecting)},this.handleSignalRestarted=s=>C(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);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:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(q.Connected),this.emit(I.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(a=>{var o;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(o=this.sidToIdentity.get(a.sid))!==null&&o!==void 0?o:"");let c=this.remoteParticipants.get(a.identity);a.state===Ht.DISCONNECTED?this.handleParticipantDisconnected(a.identity,c):c=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=s=>{const a=[],o={};s.forEach(c=>{if(o[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(c.sid);l&&(l.audioLevel=c.level,l.setIsSpeaking(!0),a.push(l))}}),o[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{o[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(I.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=s=>{const a=new Map;this.activeSpeakers.forEach(c=>{const l=this.remoteParticipants.get(c.identity);l&&l.sid!==c.sid||a.set(c.sid,c)}),s.forEach(c=>{let l=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=c.level,l.setIsSpeaking(c.active),c.active?a.set(c.sid,l):a.delete(c.sid))});const o=Array.from(a.values());o.sort((c,l)=>l.audioLevel-c.audioLevel),this.activeSpeakers=o,this.emitWhenConnected(I.ActiveSpeakersChanged,o)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);if(!c||!c.track)return;const l=k.streamStateFromProto(a.state);l!==c.track.streamState&&(c.track.streamState=l,o.emit(P.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(I.TrackStreamStateChanged,c,c.track.streamState,o))})},this.handleSubscriptionPermissionUpdate=s=>{const a=this.getRemoteParticipantBySid(s.participantSid);if(!a)return;const o=a.getTrackPublicationBySid(s.trackSid);o&&o.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const a=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!a)return;const o=a.getTrackPublicationBySid(s.trackSid);o&&o.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const a=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(a,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(a,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(a,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(a,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,a);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const o=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,o.id,o.method,o.payload,o.responseTimeoutMs,o.version)}},this.handleUserPacket=(s,a,o)=>{this.emit(I.DataReceived,a.payload,s,o,a.topic),s==null||s.emit(P.DataReceived,a.payload,o)},this.handleSipDtmf=(s,a)=>{this.emit(I.SipDTMFReceived,a,s),s==null||s.emit(P.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(s,a)=>{const o=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),c=o==null?void 0:o.trackPublications.get(a.trackId),l=zw(a,this.transcriptionReceivedTimes);c==null||c.emit(x.TranscriptionReceived,l),o==null||o.emit(P.TranscriptionReceived,l,c),this.emit(I.TranscriptionReceived,l,o,c)},this.handleChatMessage=(s,a)=>{const o=Zw(a);this.emit(I.ChatMessage,o,s)},this.handleMetrics=(s,a)=>{this.emit(I.MetricsReceived,s,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(I.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(I.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(I.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(I.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>C(this,void 0,void 0,function*(){var s,a,o;const c=Qe.getInstance().previousDevices,l=yield Qe.getInstance().getDevices(void 0,!1),u=uA();if((u==null?void 0:u.name)==="Chrome"&&u.os!=="iOS")for(let h of l){const p=c.find(f=>f.deviceId===h.deviceId);p&&p.label!==""&&p.kind===h.kind&&p.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(I.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const p=tb(h),f=this.localParticipant.getTrackPublication(p);if(f&&(!((s=f.track)===null||s===void 0)&&s.isUserProvided))continue;const m=l.filter(b=>b.kind===h),B=this.getActiveDevice(h);if(B===((a=c.filter(b=>b.kind===h)[0])===null||a===void 0?void 0:a.deviceId)&&m.length>0&&((o=m[0])===null||o===void 0?void 0:o.deviceId)!==B){yield this.switchActiveDevice(h,m[0].deviceId);continue}h==="audioinput"&&!ZA()||h==="videoinput"||m.length>0&&!m.find(b=>b.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,m[0].deviceId))}this.emit(I.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const a=this.roomInfo;this.roomInfo=s,a&&a.metadata!==s.metadata&&this.emitWhenConnected(I.RoomMetadataChanged,s.metadata),(a==null?void 0:a.activeRecording)!==s.activeRecording&&this.emitWhenConnected(I.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const o=this.getRemoteParticipantBySid(a.participantSid);o&&o.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(I.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(I.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(I.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(I.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(I.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var a;(a=s==null?void 0:s.onPublish)===null||a===void 0||a.call(s,this)},this.onLocalTrackPublished=s=>C(this,void 0,void 0,function*(){var a,o,c,l,u,d;(a=s.track)===null||a===void 0||a.on(x.TrackProcessorUpdate,this.onTrackProcessorUpdate),(o=s.track)===null||o===void 0||o.on(x.Restarted,this.onLocalTrackRestarted),(u=(l=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(I.LocalTrackPublished,s,this.localParticipant),vt(s.track)&&(yield s.track.checkForSilence())&&this.emit(I.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),p=_d(s.source);p&&h&&h!==this.localParticipant.activeDeviceMap.get(p)&&(this.localParticipant.activeDeviceMap.set(p,h),this.emit(I.ActiveDeviceChanged,p,h))}),this.onLocalTrackUnpublished=s=>{var a,o;(a=s.track)===null||a===void 0||a.off(x.TrackProcessorUpdate,this.onTrackProcessorUpdate),(o=s.track)===null||o===void 0||o.off(x.Restarted,this.onLocalTrackRestarted),this.emit(I.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>C(this,void 0,void 0,function*(){const a=yield s.getDeviceId(!1),o=_d(s.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.log.debug("local track restarted, setting ".concat(o," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(o,a),this.emit(I.ActiveDeviceChanged,o,a))}),this.onLocalConnectionQualityChanged=s=>{this.emit(I.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(I.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(I.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(I.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},yb),e),this.log=FA((n=this.options.loggerName)!==null&&n!==void 0?n:lA.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Gd),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},jd),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},bb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Oe,this.localParticipant=new ey("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",$A(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",$A(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",$A(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ve()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),qt.cleanupRegistry&&qt.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,A){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,A)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,A){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,A)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,A){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,A)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,A,n,i,r,s){return C(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,A),s!==1){yield this.engine.publishRpcResponse(e,A,null,de.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,A,null,de.builtIn("UNSUPPORTED_METHOD"));return}let o=null,c=null;try{const l=yield a({requestId:A,callerIdentity:e,payload:i,responseTimeout:r});La(l)>Wd?(o=de.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=l}catch(l){l instanceof de?o=l:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),l),o=de.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,A,c,o)})}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 ob(this.options.e2ee),this.e2eeManager.on(YA.ParticipantEncryptionStatusChanged,(A,n)=>{eb(n)&&(this.isE2EEEnabled=A),this.emit(I.ParticipantEncryptionStatusChanged,A,n)}),this.e2eeManager.on(YA.EncryptionError,A=>this.emit(I.EncryptionError,A)),(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,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&A!==void 0?A:!1}getSid(){return C(this,void 0,void 0,function*(){return this.state===q.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,A)=>{const n=i=>{i.sid!==""&&(this.engine.off(_.RoomUpdate,n),e(i.sid))};this.engine.on(_.RoomUpdate,n),this.once(I.Disconnected,()=>{this.engine.off(_.RoomUpdate,n),A("Room disconnected before room server id was available")})})})}get name(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&A!==void 0?A:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&A!==void 0?A:0}get numPublishers(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&A!==void 0?A:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ob(this.options),this.engine.on(_.ParticipantUpdate,this.handleParticipantUpdates).on(_.RoomUpdate,this.handleRoomUpdate).on(_.SpeakersChanged,this.handleSpeakersChanged).on(_.StreamStateChanged,this.handleStreamStateUpdate).on(_.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_.SubscriptionError,this.handleSubscriptionError).on(_.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_.MediaTrackAdded,(e,A,n)=>{this.onTrackAdded(e,A,n)}).on(_.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(_.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_.DataPacketReceived,this.handleDataPacket).on(_.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(q.SignalReconnecting)&&this.emit(I.SignalReconnecting)}).on(_.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(q.Connected)&&this.emit(I.Reconnected)}).on(_.SignalResumed,()=>{this.bufferedEvents=[],(this.state===q.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_.Restarting,this.handleRestarting).on(_.SignalRestarted,this.handleSignalRestarted).on(_.Offline,()=>{this.setAndEmitConnectionState(q.Reconnecting)&&this.emit(I.Reconnecting)}).on(_.DCBufferStatusChanged,(e,A)=>{this.emit(I.DCBufferStatusChanged,e,A)}).on(_.LocalTrackSubscribed,e=>{const A=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:i}=n;return i===e});if(!A){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(P.LocalTrackSubscribed,A),this.emitWhenConnected(I.LocalTrackSubscribed,A,this.localParticipant)}).on(_.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((A,n)=>{this.handleParticipantDisconnected(n,A)}),this.emit(I.Moved,e.room.name,e.token),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))}static getLocalDevices(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Qe.getInstance().getDevices(e,A)}prepareConnection(e,A){return C(this,void 0,void 0,function*(){if(this.state===q.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ma(new URL(e))&&A){this.regionUrlProvider=new Ka(e,A);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===q.Disconnected&&(this.regionUrl=n,yield fetch(ba(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(ba(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,A){return C(this,void 0,void 0,function*(){let n=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new bA({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new bA({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new bA({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new bA({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":n=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new bA({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new bA({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":i=new bA({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>C(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new qi({reason:aA.CLIENT_INITIATED,action:Mt.RECONNECT}))});break;case"subscriber-bandwidth":if(A===void 0||typeof A!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new bA({scenario:{case:"subscriberBandwidth",value:Bt(A)}});break;case"leave-full-reconnect":i=new bA({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var a,o,c,l,u,d,h,p;let f=!0,m=!1;const B=s?{exact:i}:i;if(n==="audioinput"){m=r.localParticipant.audioTrackPublications.size===0;const b=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=B;const U=Array.from(r.localParticipant.audioTrackPublications.values()).filter(w=>w.source===k.Source.Microphone);try{f=(yield Promise.all(U.map(w=>{var v;return(v=w.audioTrack)===null||v===void 0?void 0:v.setDeviceId(B)}))).every(w=>w===!0)}catch(w){throw r.options.audioCaptureDefaults.deviceId=b,w}}else if(n==="videoinput"){m=r.localParticipant.videoTrackPublications.size===0;const b=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=B;const U=Array.from(r.localParticipant.videoTrackPublications.values()).filter(w=>w.source===k.Source.Camera);try{f=(yield Promise.all(U.map(w=>{var v;return(v=w.videoTrack)===null||v===void 0?void 0:v.setDeviceId(B)}))).every(w=>w===!0)}catch(w){throw r.options.videoCaptureDefaults.deviceId=b,w}}else if(n==="audiooutput"){if(!pa()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield Qe.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(l=(p=r.options).audioOutput)!==null&&l!==void 0||(p.audioOutput={});const b=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((d=r.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(U=>U.setAudioOutput({deviceId:i})))}catch(U){throw r.options.audioOutput.deviceId=b,U}}return(m||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(I.ActiveDeviceChanged,n,i)),f}()})}setupLocalParticipantEvents(){this.localParticipant.on(P.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(P.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(P.AttributesChanged,this.onLocalAttributesChanged).on(P.TrackMuted,this.onLocalTrackMuted).on(P.TrackUnmuted,this.onLocalTrackUnmuted).on(P.LocalTrackPublished,this.onLocalTrackPublished).on(P.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(P.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(P.MediaDevicesError,this.onMediaDevicesError).on(P.AudioStreamAcquired,this.startAudio).on(P.ChatMessage,this.onLocalChatMessageSent).on(P.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,A,n){if(this.state===q.Connecting||this.state===q.Reconnecting){const l=()=>{this.onTrackAdded(e,A,n),u()},u=()=>{this.off(I.Reconnected,l),this.off(I.Connected,l),this.off(I.Disconnected,u)};this.once(I.Reconnected,l),this.once(I.Connected,l),this.once(I.Disconnected,u);return}if(this.state===q.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 i=Mw(A.id),r=i[0];let s=i[1],a=e.id;if(s&&s.startsWith("TR")&&(a=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const o=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!o){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),o.addSubscribedMediaTrack(e,a,A,n,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,A=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==q.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,a;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(a=i.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(P.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(P.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(P.AttributesChanged,this.onLocalAttributesChanged).off(P.TrackMuted,this.onLocalTrackMuted).off(P.TrackUnmuted,this.onLocalTrackUnmuted).off(P.LocalTrackPublished,this.onLocalTrackPublished).off(P.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(P.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(P.MediaDevicesError,this.onMediaDevicesError).off(P.AudioStreamAcquired,this.startAudio).off(P.ChatMessage,this.onLocalChatMessageSent).off(P.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),Ve()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(q.Disconnected),this.emit(I.Disconnected,A)}}}handleParticipantDisconnected(e,A){var n;this.remoteParticipants.delete(e),A&&(A.trackPublications.forEach(i=>{A.unpublishTrack(i.trackSid,!0)}),this.emit(I.ParticipantDisconnected,A),A.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(A.identity))}handleStreamHeader(e,A){return C(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:or(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:o=>{r=o,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Vb(s,a,or(e.totalLength)),{identity:A})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:o=>{r=o,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Gb(s,a,or(e.totalLength)),{identity:A})}})}handleStreamChunk(e){const A=this.byteStreamControllers.get(e.streamId);A&&e.content.length>0&&A.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const A=this.textStreamControllers.get(e.streamId);A&&(A.info.attributes=Object.assign(Object.assign({},A.info.attributes),e.attributes),A.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return C(this,void 0,void 0,function*(){var e,A;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=xd())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ke(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const n=((A=this.audioContext)===null||A===void 0?void 0:A.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(I.AudioPlaybackStatusChanged,n))})}createParticipant(e,A){var n;let i;return A?i=pr.fromParticipantInfo(this.engine.client,A,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new pr(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,A){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return A&&i.updateInfo(A)&&this.sidToIdentity.set(A.sid,A.identity),i}const n=this.createParticipant(e,A);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(A.sid,A.identity),this.emitWhenConnected(I.ParticipantConnected,n),n.on(P.TrackPublished,i=>{this.emitWhenConnected(I.TrackPublished,i,n)}).on(P.TrackSubscribed,(i,r)=>{i.kind===k.Kind.Audio?(i.on(x.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(x.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===k.Kind.Video&&(i.on(x.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(x.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(I.TrackSubscribed,i,r,n)}).on(P.TrackUnpublished,i=>{this.emit(I.TrackUnpublished,i,n)}).on(P.TrackUnsubscribed,(i,r)=>{this.emit(I.TrackUnsubscribed,i,r,n)}).on(P.TrackMuted,i=>{this.emitWhenConnected(I.TrackMuted,i,n)}).on(P.TrackUnmuted,i=>{this.emitWhenConnected(I.TrackUnmuted,i,n)}).on(P.ParticipantMetadataChanged,i=>{this.emitWhenConnected(I.ParticipantMetadataChanged,i,n)}).on(P.ParticipantNameChanged,i=>{this.emitWhenConnected(I.ParticipantNameChanged,i,n)}).on(P.AttributesChanged,i=>{this.emitWhenConnected(I.ParticipantAttributesChanged,i,n)}).on(P.ConnectionQualityChanged,i=>{this.emitWhenConnected(I.ConnectionQualityChanged,i,n)}).on(P.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(I.ParticipantPermissionsChanged,i,n)}).on(P.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(I.TrackSubscriptionStatusChanged,i,r,n)}).on(P.TrackSubscriptionFailed,(i,r)=>{this.emit(I.TrackSubscriptionFailed,i,n,r)}).on(P.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(I.TrackSubscriptionPermissionChanged,i,r,n)}).on(P.Active,()=>{this.emitWhenConnected(I.ParticipantActive,n)}),A&&n.updateInfo(A),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,i)=>(n.push(...i.getTrackPublications()),n),[]),A=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,A)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const A of e.videoTrackPublications.values())A.isSubscribed&&$w(A)&&A.emitTrackUpdate()}getRemoteParticipantBySid(e){const A=this.sidToIdentity.get(e);if(A)return this.remoteParticipants.get(A)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Te.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,aA.STATE_MISMATCH))):e=0},ty)}clearConnectionReconcile(){this.connectionReconcileInterval&&Te.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(I.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[A,n]=e;this.emit(A,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var A=arguments.length,n=new Array(A>1?A-1:0),i=1;i<A;i++)n[i-1]=arguments[i];if(this.state===q.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===q.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return C(this,void 0,void 0,function*(){var A,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ji({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:re.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ht({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(I.SignalConnected),this.emit(I.Connected),this.setAndEmitConnectionState(q.Connected),i.video){const s=new ja(k.Kind.Video,new Ot({source:Be.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO,name:"video-dummy"}),new fr(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:kd(160*((A=r.aspectRatios[0])!==null&&A!==void 0?A:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(P.LocalTrackPublished,s)}if(i.audio){const s=new ja(k.Kind.Audio,new Ot({source:Be.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO}),new dr(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ca(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(P.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let a=new ht({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ht.ACTIVE,tracks:[],joinedAt:re.parse(Date.now())});const o=this.getOrCreateParticipant(a.identity,a);if(r.video){const c=kd(160*((n=r.aspectRatios[s%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new Ot({source:Be.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO});o.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}if(r.audio){const c=Ca(),l=new Ot({source:Be.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO});o.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}o.updateInfo(a)}})}emit(e){for(var A=arguments.length,n=new Array(A>1?A-1:0),i=1;i<A;i++)n[i-1]=arguments[i];if(e!==I.ActiveSpeakersChanged&&e!==I.TranscriptionReceived){const r=ah(n).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}qt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ah(t){return t.map(e=>{if(e)return Array.isArray(e)?ah(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var fA;(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"})(fA||(fA={}));class nt extends yA.EventEmitter{constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=fA.IDLE,this.logs=[],this.options={},this.url=e,this.token=A,this.name=this.constructor.name,this.room=new qt(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return C(this,void 0,void 0,function*(){if(this.status!==fA.IDLE)throw Error("check is running already");this.setStatus(fA.RUNNING);try{yield this.perform()}catch(A){A instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(A.message):this.appendError(A.message))}return yield this.disconnect(),yield new Promise(A=>setTimeout(A,500)),this.status!==fA.SKIPPED&&this.setStatus(this.isSuccess()?fA.SUCCESS:fA.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===q.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!==q.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(fA.SKIPPED)}switchProtocol(e){return C(this,void 0,void 0,function*(){let A=!1,n=!1;if(this.room.on(I.Reconnecting,()=>{A=!0}),this.room.once(I.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!A)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(n)return;yield Ke(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 ny extends nt{get description(){return"Cloud regions"}perform(){return C(this,void 0,void 0,function*(){const e=new Ka(this.url,this.token);if(!e.isCloud()){this.skip();return}const A=[],n=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(n.has(s))continue;n.add(s);const a=yield this.checkCloudRegion(s);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),A.push(a)}A.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=A[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return C(this,void 0,void 0,function*(){var A,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(A=this.room.serverInfo)===null||A===void 0?void 0:A.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,o=1e6/s,c="A".repeat(s),l=Date.now();for(let p=0;p<o;p++)yield r.write(c);yield r.close();const u=Date.now(),d=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:i,rtt:1e4,duration:u-l};return d==null||d.forEach(p=>{p.type==="candidate-pair"&&p.nominated&&(h.rtt=p.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const Wa=1e4;class iy extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return C(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),A=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-A.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-A.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=A):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Wa/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Wa/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 A=document.createElement("canvas");A.width=1280,A.height=720;const n=A.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,A.width,A.height),requestAnimationFrame(r)};r();const a=A.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={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 d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,Wa)),clearInterval(u),a.stop(),A.remove(),yield this.disconnect(),l})}}class ry extends nt{get description(){return"Can publish audio"}perform(){return C(this,void 0,void 0,function*(){var e;const A=yield this.connect(),n=yield zb();if(yield Id(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),A.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(s=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class sy extends nt{get description(){return"Can publish video"}perform(){return C(this,void 0,void 0,function*(){var e;const A=yield this.connect(),n=yield Yb();yield this.checkForVideo(n.mediaStreamTrack),A.localParticipant.publishTrack(n),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return C(this,void 0,void 0,function*(){const A=new MediaStream;A.addTrack(e.clone());const n=document.createElement("video");n.srcObject=A,n.muted=!0,yield new Promise(i=>{n.onplay=()=>{setTimeout(()=>{var r,s,a,o;const c=document.createElement("canvas"),l=e.getSettings(),u=(s=(r=l.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&s!==void 0?s:1280,d=(o=(a=l.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&o!==void 0?o:720;c.width=u,c.height=d;const h=c.getContext("2d");h.drawImage(n,0,0);const f=h.getImageData(0,0,c.width,c.height).data;let m=!0;for(let B=0;B<f.length;B+=4)if(f[B]!==0||f[B+1]!==0||f[B+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},n.play()}),n.remove()})}}class ay extends nt{get description(){return"Resuming connection after interruption"}perform(){return C(this,void 0,void 0,function*(){var e;const A=yield this.connect();let n=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),a=()=>{n=!0};A.on(I.SignalReconnecting,a).on(I.Reconnecting,a).on(I.Reconnected,()=>{i=!0,r(!0)}),(e=A.engine.client.ws)===null||e===void 0||e.close();const o=A.engine.client.onClose;if(o&&o(""),yield s,n){if(!i||A.state!==q.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 oy extends nt{get description(){return"Can connect via TURN"}perform(){return C(this,void 0,void 0,function*(){var e,A;const n=new ka,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,a=!1;for(let o of i.iceServers)for(let c of o.urls)c.startsWith("turn:")?(s=!0,a=!0):c.startsWith("turns:")&&(s=!0,a=!0,r=!0),c.startsWith("stun:")&&(a=!0);a?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((A=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||A===void 0)&&A.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(o=>setTimeout(o,0)))})}}class cy extends nt{get description(){return"Establishing WebRTC connection"}perform(){return C(this,void 0,void 0,function*(){let e=!1,A=!1;this.room.on(I.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let a="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(ly(s.address)?a+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,a+=" (passive)"):s.protocol==="udp"&&(A=!0)),this.appendMessage(a)}n&&n(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),W.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),A||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function ly(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 A=parseInt(e[1],10);if(A>=16&&A<=31)return!0}}return!1}class uy extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return C(this,void 0,void 0,function*(){var e,A,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new ka;const r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===lu.Cloud&&(!((A=r.serverInfo)===null||A===void 0)&&A.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield i.close()})}}class HU extends yA.EventEmitter{constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=A,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:fA.IDLE,name:"",description:""}),e}updateCheck(e,A){this.checkResults.set(e,A),this.emit("checkUpdate",e,A)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==fA.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return C(this,void 0,void 0,function*(){const A=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(A,s)};n.on("update",i);const r=yield n.run();return n.off("update",i),r})}checkWebsocket(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(uy)})}checkWebRTC(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(cy)})}checkTURN(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(oy)})}checkReconnect(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ay)})}checkPublishAudio(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ry)})}checkPublishVideo(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(sy)})}checkConnectionProtocol(){return C(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(iy);if(e.data&&"protocol"in e.data){const A=e.data;this.options.protocol=A.protocol}return e})}checkCloudRegion(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ny)})}}const dy=/\{[^{}]+\}/g;function hy(){return Math.random().toString(36).slice(2,11)}function fy(t){let{baseUrl:e="",Request:A=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:r,headers:s,...a}={...t};e=uh(e);const o=[];async function c(l,u){const{baseUrl:d,fetch:h=n,Request:p=A,headers:f,params:m={},parseAs:B="json",querySerializer:b,bodySerializer:U=r??py,body:w,...v}=u||{};d&&(e=uh(d));let y=typeof i=="function"?i:lh(i);b&&(y=typeof b=="function"?b:lh({...typeof i=="object"?i:{},...b}));const E=w===void 0?void 0:U(w),T=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},F={redirect:"follow",...a,...v,body:E,headers:By(T,s,f,m.header)};let R,D,O=new A(my(l,{baseUrl:e,params:m,querySerializer:y}),F);for(const N in v)N in O||(O[N]=v[N]);if(o.length){R=hy(),D=Object.freeze({baseUrl:e,fetch:h,parseAs:B,querySerializer:y,bodySerializer:U});for(const N of o)if(N&&typeof N=="object"&&typeof N.onRequest=="function"){const V=await N.onRequest({request:O,schemaPath:l,params:m,options:D,id:R});if(V){if(!(V instanceof A))throw new Error("onRequest: must return new Request() when modifying the request");O=V}}}let M=await h(O);if(o.length)for(let N=o.length-1;N>=0;N--){const V=o[N];if(V&&typeof V=="object"&&typeof V.onResponse=="function"){const Fe=await V.onResponse({request:O,response:M,schemaPath:l,params:m,options:D,id:R});if(Fe){if(!(Fe instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");M=Fe}}}if(M.status===204||M.headers.get("Content-Length")==="0")return M.ok?{data:{},response:M}:{error:{},response:M};if(M.ok)return B==="stream"?{data:M.body,response:M}:{data:await M[B](),response:M};let ae=await M.text();try{ae=JSON.parse(ae)}catch{}return{error:ae,response:M}}return{GET(l,u){return c(l,{...u,method:"GET"})},PUT(l,u){return c(l,{...u,method:"PUT"})},POST(l,u){return c(l,{...u,method:"POST"})},DELETE(l,u){return c(l,{...u,method:"DELETE"})},OPTIONS(l,u){return c(l,{...u,method:"OPTIONS"})},HEAD(l,u){return c(l,{...u,method:"HEAD"})},PATCH(l,u){return c(l,{...u,method:"PATCH"})},TRACE(l,u){return c(l,{...u,method:"TRACE"})},use(...l){for(const u of l)if(u){if(typeof u!="object"||!("onRequest"in u||"onResponse"in u))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");o.push(u)}},eject(...l){for(const u of l){const d=o.indexOf(u);d!==-1&&o.splice(d,1)}}}}function mr(t,e,A){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${(A==null?void 0:A.allowReserved)===!0?e:encodeURIComponent(e)}`}function oh(t,e,A){if(!e||typeof e!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[A.style]||"&";if(A.style!=="deepObject"&&A.explode===!1){for(const a in e)n.push(a,A.allowReserved===!0?e[a]:encodeURIComponent(e[a]));const s=n.join(",");switch(A.style){case"form":return`${t}=${s}`;case"label":return`.${s}`;case"matrix":return`;${t}=${s}`;default:return s}}for(const s in e){const a=A.style==="deepObject"?`${t}[${s}]`:s;n.push(mr(a,e[s],A))}const r=n.join(i);return A.style==="label"||A.style==="matrix"?`${i}${r}`:r}function ch(t,e,A){if(!Array.isArray(e))return"";if(A.explode===!1){const r={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[A.style]||",",s=(A.allowReserved===!0?e:e.map(a=>encodeURIComponent(a))).join(r);switch(A.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${t}=${s}`;default:return`${t}=${s}`}}const n={simple:",",label:".",matrix:";"}[A.style]||"&",i=[];for(const r of e)A.style==="simple"||A.style==="label"?i.push(A.allowReserved===!0?r:encodeURIComponent(r)):i.push(mr(t,r,A));return A.style==="label"||A.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function lh(t){return function(A){const n=[];if(A&&typeof A=="object")for(const i in A){const r=A[i];if(r!=null){if(Array.isArray(r)){if(r.length===0)continue;n.push(ch(i,r,{style:"form",explode:!0,...t==null?void 0:t.array,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}if(typeof r=="object"){n.push(oh(i,r,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}n.push(mr(i,r,t))}}return n.join("&")}}function gy(t,e){let A=t;for(const n of t.match(dy)??[]){let i=n.substring(1,n.length-1),r=!1,s="simple";if(i.endsWith("*")&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const a=e[i];if(Array.isArray(a)){A=A.replace(n,ch(i,a,{style:s,explode:r}));continue}if(typeof a=="object"){A=A.replace(n,oh(i,a,{style:s,explode:r}));continue}if(s==="matrix"){A=A.replace(n,`;${mr(i,a)}`);continue}A=A.replace(n,s==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return A}function py(t){return t instanceof FormData?t:JSON.stringify(t)}function my(t,e){var i;let A=`${e.baseUrl}${t}`;(i=e.params)!=null&&i.path&&(A=gy(A,e.params.path));let n=e.querySerializer(e.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(A+=`?${n}`),A}function By(...t){const e=new Headers;for(const A of t){if(!A||typeof A!="object")continue;const n=A instanceof Headers?A.entries():Object.entries(A);for(const[i,r]of n)if(r===null)e.delete(i);else if(Array.isArray(r))for(const s of r)e.append(i,s);else r!==void 0&&e.set(i,r)}return e}function uh(t){return t.endsWith("/")?t.substring(0,t.length-1):t}class dh{constructor(e){this.client=fy({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}setAuthToken(e){this.client.use({onRequest({request:A}){return A.headers.set("Authorization",`Bearer ${e}`),A}})}setApiToken(e){this.client.use({onRequest({request:A}){return A.headers.set("Authorization",`Token ${e}`),A}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async clientInitialise(e,A={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:A})}async clientStartSession(e,A){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:A})}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,A){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:A})}async listPlans(){return await this.client.GET("/api/plans")}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async getProductAnalytics(e,A,n){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...A&&{start_date:A},...n&&{end_date:n}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,A){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:A})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,A){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:A})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,A){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async searchProductKnowledgeBlocks(e,A,n){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:A,...n&&{limit:n.toString()}}}})}async updateProductKnowledgeBlock(e,A,n){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}},body:n})}async deleteProductKnowledgeBlock(e,A){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}}})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async replacePlan(e,A){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:A})}async updatePlan(e,A){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:A})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,A){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:A})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,A){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async updatePlanKnowledgeBlock(e,A,n){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}},body:n})}async deletePlanKnowledgeBlock(e,A){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,A){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:A})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,A){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:A})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,A){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:A})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,A){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async createRevisionKnowledgeBlock(e,A){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async updateRevisionKnowledgeBlock(e,A,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}},body:n})}async deleteRevisionKnowledgeBlock(e,A){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}}})}async listSessions(e,A){const n={token:e};return A!=null&&A.productId&&(n.product_id=A.productId),A!=null&&A.startDate&&(n.start_date=A.startDate),A!=null&&A.endDate&&(n.end_date=A.endDate),await this.client.GET("/api/sessions",{params:{query:n}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,A){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:A}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async updateSession(e,A){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:A})}async listUserSessions(e){const A={};return e!=null&&e.productId&&(A.product_id=e.productId),e!=null&&e.startDate&&(A.start_date=e.startDate),e!=null&&e.endDate&&(A.end_date=e.endDate),e!=null&&e.page&&(A.page=e.page),e!=null&&e.limit&&(A.limit=e.limit),e!=null&&e.courseName&&(A.course_name=e.courseName),e!=null&&e.userName&&(A.user_name=e.userName),e!=null&&e.company&&(A.company=e.company),e!=null&&e.email&&(A.email=e.email),e!=null&&e.sortBy&&(A.sort_by=e.sortBy),e!=null&&e.sortOrder&&(A.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(A).length>0?{query:A}:void 0})}async listUserSessionsAggregate(e){const A={};return e!=null&&e.productId&&(A.product_id=e.productId),e!=null&&e.startDate&&(A.start_date=e.startDate),e!=null&&e.endDate&&(A.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(A).length>0?{query:A}:void 0})}async getJoinToken(e,{clientType:A,user:n}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...A&&{client_type:A},...n&&{user:encodeURIComponent(n)}}}})}async trackEvent(e){try{return await this.client.POST("/api/track",{body:{sent_at:new Date().toISOString(),...e}})}catch(A){console.error("[obi] error tracking event:",A)}return{}}getClient(){return this.client}}const hh="https://app.coragents.ai";class Br extends kr{constructor(e,A,n,i){super(),this.state=null,this.isPaused=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=A,this.clientType=n,this.api=i.api||new dh({baseUrl:hh}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(r=>new qt(r)),this.captureScreen=i.captureScreen||null}async start(){console.debug("[obi] starting session",{planId:this.planId}),this.setState("connecting"),this.speakingStateChanged("thinking");try{const A=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(A!=null&&A.url)||!(A!=null&&A.token)||!(A!=null&&A.room)||!(A!=null&&A.session_uuid))throw new Error("Invalid room info");this.sessionUuid=A==null?void 0:A.session_uuid,this.roomId=A==null?void 0:A.room,this.joinToken=A==null?void 0:A.token,this.roomUrl=A==null?void 0:A.url,await this.joinRoom(),this.setState("connected"),console.debug("[obi] started session",{planId:this.planId,sessionUuid:this.sessionUuid})}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:A=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(I.Disconnected,n=>{if(console.debug("[obi] room disconnected",{reason:n}),!this.room)return;let i=null;switch(n){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(I.TrackSubscribed,n=>{n.kind==="audio"&&(n.attach(),n.source===k.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(n.mediaStream)))}),this.room.on(I.LocalTrackPublished,n=>{n.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(n.audioTrack.mediaStream))}),this.room.on(I.ParticipantAttributesChanged,n=>{if(!n["lk.agent.state"])return;const i=n["lk.agent.state"];switch(i){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.state!=="connected"&&this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",i)}}),this.room.on(I.DataReceived,async n=>{try{const i=new TextDecoder().decode(n);console.debug("[obi] data received",i);const r=JSON.parse(i);switch(r.status||r.request||r.type){case"course_progress":typeof r.current_step=="number"&&typeof r.total_steps=="number"&&Array.isArray(r.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,r.current_step),totalSteps:Math.max(1,r.total_steps),stepNames:r.step_names});break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;default:console.warn("[obi] unknown data received",r)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async n=>(console.debug("[obi] checking microphone",{sessionUuid:this.sessionUuid}),await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async n=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,r=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||r)return console.error("[obi] error capturing screen",{error:r}),"error";try{return await this.room.localParticipant.sendFile(new File([i],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(s){return console.error("[obi] error sending screen capture",{error:s}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let n=0;n<9&&!(this.room.state===q.Connected&&this.room.remoteParticipants.size>=1);n++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===q.Connected&&this.room.remoteParticipants.size>=1)){console.error("[obi] room not connected",{state:this.room.state,numParticipants:this.room.remoteParticipants.size}),this.shutdown("invalid-room");return}if(e&&await this.room.localParticipant.setMicrophoneEnabled(!0),A){let n=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(n=!0);n?this.speakingState="speaking":this.speakingState="listening"}}async continue(){console.debug("[obi] continuing session",{sessionUuid:this.sessionUuid}),this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(A){console.error("[obi] error checking microphone permission:",A)}return e?(console.debug("[obi] microphone permission granted",{sessionUuid:this.sessionUuid}),await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):console.debug("[obi] microphone permission denied",{sessionUuid:this.sessionUuid}),e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){console.debug("[obi] sharing microphone",{sessionUuid:this.sessionUuid}),this.speakingStateChanged("thinking");let e=null,A=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(n){n=n,this.isMicShared=!1}e?console.debug("[obi] shared microphone",{sessionUuid:this.sessionUuid}):console.error("[obi] failed to share microphone",{error:A}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){console.debug("[obi] sharing screen",{sessionUuid:this.sessionUuid}),this.speakingStateChanged("thinking"),await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),await this.sendData({request:"share_screen",success:!0}),this.setState("navigate")}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}muteMicrophone(){console.debug("[obi] muting microphone",{sessionUuid:this.sessionUuid}),this.room.localParticipant.getTrackPublications().forEach(e=>{var A,n;e.handleMuted(),(n=(A=e.track)==null?void 0:A.mediaStream)==null||n.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){console.debug("[obi] unmuting microphone",{sessionUuid:this.sessionUuid}),this.room.localParticipant.getTrackPublications().forEach(e=>{var A,n;e.handleUnmuted(),(n=(A=e.track)==null?void 0:A.mediaStream)==null||n.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){console.debug("[obi] stopping session",{sessionUuid:this.sessionUuid});const A=this.room;this.room=null,await A.disconnect(),console.debug("[obi] stopped session",{sessionUuid:this.sessionUuid})}this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const n=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const r=[],s=50,a=5e3,o=8,c=Math.pow(a/s,1/o);for(let l=0;l<o;l++){const u=s*Math.pow(c,l),d=s*Math.pow(c,l+1),h=Math.floor(u/n),p=Math.floor(d/n),f=Math.min(p,i.length),m=Math.min(h,f);if(m<f){const B=i.slice(m,f).reduce((b,U)=>b+U,0)/(f-m)/255;r.push(B)}else r.push(0)}return r}setState(e){console.debug("[obi] state changed",{state:e,oldState:this.state});const A=this.state;this.state=e,this.emit("stateChanged",e,A)}static deserialise(e,A,n,i={}){const r=JSON.parse(e),s=new Br(A,r.planId,n,i);return s.state=r.state,s.speakingState=r.speakingState,s.identity=r.identity||null,s.isPaused=r.isPaused||!1,s.sessionUuid=r.sessionUuid||null,s.roomId=r.roomId||null,s.joinToken=r.joinToken||null,s.roomUrl=r.roomUrl||null,s}speakingStateChanged(e){console.debug("[obi] speaking state changed",{state:e,oldState:this.speakingState});const A=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,A)}async sendData(e){console.debug("[obi] sending data",{data:e}),await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const A=new AudioContext,n=A.createAnalyser();return A.createMediaStreamSource(e).connect(n),n.fftSize=2048,n.smoothingTimeConstant=.6,n}}class vr extends kr{constructor(e,A,n={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=A,this.api=n.api||new dh({baseUrl:n.apiBaseUrl||hh}),this.sessionFactory=n.sessionFactory||((i,r,s,a)=>new Br(i,r,s,a)),this.captureScreen=n.captureScreen||null}async initialise(e={}){var A,n,i,r;if(console.debug("[obi] initialising client"),!this.appToken)throw new Error("App token is required");this.setState("loading");try{const s=await this.api.clientInitialise(this.appToken,{identity:e.identity});this.identity=e.identity||null,this.product=((A=s.data)==null?void 0:A.product)||null,this.plans=((n=s.data)==null?void 0:n.onboarding_plans)||[],this.selectedPlan=((i=s.data)==null?void 0:i.selected_plan)||null,this.showWidget=((r=s.data)==null?void 0:r.show_widget)||!1,e.planUuid&&this.plans.find(a=>a.uuid===e.planUuid)&&(this.selectedPlan=this.plans.find(a=>a.uuid===e.planUuid)||null,this.selectedPlanUuid=e.planUuid),console.debug("[obi] initialised client",{identity:this.identity,product:this.product,plans:this.plans,selectedPlan:this.selectedPlan,showWidget:this.showWidget})}catch(s){throw this.error=s instanceof Error?s:new Error(String(s)),this.setState("error"),s}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e),this.trackEvent(e?"plan_selected":"plan_cancelled")}async startSession(e,A){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(A),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(n=>{this.session=null,console.error("[obi] error starting session",n)}),this.trackEvent("session_started"),this.session}async resumeSession(e){var A,n;return console.debug("[obi] resuming session",{clientState:this.state,sessionState:(A=this.session)==null?void 0:A.state,speakingState:(n=this.session)==null?void 0:n.speakingState}),this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(i=>{console.error("[obi] error joining room",{error:i}),i instanceof Error&&i.message==="Room is not connected"&&this.session.stop()}),this.trackEvent("session_resumed"),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",A=>{var n,i;(i=(n=this.session)==null?void 0:n.removeAllListeners)==null||i.call(n),this.session=null,this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",A)}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session_stopped"),await this.session.stop(),this.session=null)}isLoading(){return this.state==="loading"}isReady(){return this.state==="ready"}serialise(){var e;return JSON.stringify({state:this.state,appToken:this.appToken,clientType:this.clientType,identity:this.identity,product:this.product,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise()})}static deserialise(e,A,n,i={}){const r=JSON.parse(e),s=new vr(A,n,i);return s.state=r.state,s.identity=r.identity||null,s.product=r.product||null,s.plans=r.plans||[],s.selectedPlan=r.selectedPlan||null,s.selectedPlanUuid=r.selectedPlanUuid||null,s.showWidget=r.showWidget||!1,r.session&&(s.session=Br.deserialise(r.session,A,n,{api:s.api})),s}setState(e){const A=this.state;this.state=e,this.emit("stateChanged",e,A)}trackEvent(e,A={}){var n,i,r;this.api.trackEvent({event:e,client_type:this.clientType,plan_id:(n=this.selectedPlan)==null?void 0:n.uuid,product_id:(i=this.product)==null?void 0:i.uuid,session_id:(r=this.session)==null?void 0:r.sessionUuid,...A}).then(()=>{console.debug("[obi] tracked event",{event:e,data:A})}).catch(s=>{console.error("[obi] error tracking event",{event:e,data:A,error:s})})}}var Cr,K,fh,Ct,gh,ph,mh,Bh,Ja,Xa,qa,vh,xn={},Ch=[],vy=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_n=Array.isArray;function PA(t,e){for(var A in e)t[A]=e[A];return t}function Ya(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function za(t,e,A){var n,i,r,s={};for(r in e)r=="key"?n=e[r]:r=="ref"?i=e[r]:s[r]=e[r];if(arguments.length>2&&(s.children=arguments.length>3?Cr.call(arguments,2):A),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)s[r]==null&&(s[r]=t.defaultProps[r]);return wr(t,s,n,i,null)}function wr(t,e,A,n,i){var r={type:t,props:e,key:A,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++fh,__i:-1,__u:0};return i==null&&K.vnode!=null&&K.vnode(r),r}function Pe(t){return t.children}function RA(t,e){this.props=t,this.context=e}function Yt(t,e){if(e==null)return t.__?Yt(t.__,t.__i+1):null;for(var A;e<t.__k.length;e++)if((A=t.__k[e])!=null&&A.__e!=null)return A.__e;return typeof t.type=="function"?Yt(t):null}function wh(t){var e,A;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((A=t.__k[e])!=null&&A.__e!=null){t.__e=t.__c.base=A.__e;break}return wh(t)}}function Za(t){(!t.__d&&(t.__d=!0)&&Ct.push(t)&&!br.__r++||gh!=K.debounceRendering)&&((gh=K.debounceRendering)||ph)(br)}function br(){for(var t,e,A,n,i,r,s,a=1;Ct.length;)Ct.length>a&&Ct.sort(mh),t=Ct.shift(),a=Ct.length,t.__d&&(A=void 0,i=(n=(e=t).__v).__e,r=[],s=[],e.__P&&((A=PA({},n)).__v=n.__v+1,K.vnode&&K.vnode(A),$a(e.__P,A,n,e.__n,e.__P.namespaceURI,32&n.__u?[i]:null,r,i??Yt(n),!!(32&n.__u),s),A.__v=n.__v,A.__.__k[A.__i]=A,Eh(r,A,s),A.__e!=i&&wh(A)));br.__r=0}function bh(t,e,A,n,i,r,s,a,o,c,l){var u,d,h,p,f,m,B=n&&n.__k||Ch,b=e.length;for(o=Cy(A,e,B,o,b),u=0;u<b;u++)(h=A.__k[u])!=null&&(d=h.__i==-1?xn:B[h.__i]||xn,h.__i=u,m=$a(t,h,d,i,r,s,a,o,c,l),p=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&eo(d.ref,null,h),l.push(h.ref,h.__c||p,h)),f==null&&p!=null&&(f=p),4&h.__u||d.__k===h.__k?o=yh(h,o,t):typeof h.type=="function"&&m!==void 0?o=m:p&&(o=p.nextSibling),h.__u&=-7);return A.__e=f,o}function Cy(t,e,A,n,i){var r,s,a,o,c,l=A.length,u=l,d=0;for(t.__k=new Array(i),r=0;r<i;r++)(s=e[r])!=null&&typeof s!="boolean"&&typeof s!="function"?(o=r+d,(s=t.__k[r]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?wr(null,s,null,null,null):_n(s)?wr(Pe,{children:s},null,null,null):s.constructor==null&&s.__b>0?wr(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,a=null,(c=s.__i=wy(s,A,o,u))!=-1&&(u--,(a=A[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(i>l?d--:i<l&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=o&&(c==o-1?d--:c==o+1?d++:(c>o?d--:d++,s.__u|=4))):t.__k[r]=null;if(u)for(r=0;r<l;r++)(a=A[r])!=null&&!(2&a.__u)&&(a.__e==n&&(n=Yt(a)),kh(a,a));return n}function yh(t,e,A){var n,i;if(typeof t.type=="function"){for(n=t.__k,i=0;n&&i<n.length;i++)n[i]&&(n[i].__=t,e=yh(n[i],e,A));return e}t.__e!=e&&(e&&t.type&&!A.contains(e)&&(e=Yt(t)),A.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function yr(t,e){return e=e||[],t==null||typeof t=="boolean"||(_n(t)?t.some(function(A){yr(A,e)}):e.push(t)),e}function wy(t,e,A,n){var i,r,s=t.key,a=t.type,o=e[A];if(o===null&&t.key==null||o&&s==o.key&&a==o.type&&!(2&o.__u))return A;if(n>(o!=null&&!(2&o.__u)?1:0))for(i=A-1,r=A+1;i>=0||r<e.length;){if(i>=0){if((o=e[i])&&!(2&o.__u)&&s==o.key&&a==o.type)return i;i--}if(r<e.length){if((o=e[r])&&!(2&o.__u)&&s==o.key&&a==o.type)return r;r++}}return-1}function Uh(t,e,A){e[0]=="-"?t.setProperty(e,A??""):t[e]=A==null?"":typeof A!="number"||vy.test(e)?A:A+"px"}function Ur(t,e,A,n,i){var r;e:if(e=="style")if(typeof A=="string")t.style.cssText=A;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)A&&e in A||Uh(t.style,e,"");if(A)for(e in A)n&&A[e]==n[e]||Uh(t.style,e,A[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(Bh,"$1")),e=e.toLowerCase()in t||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=A,A?n?A.u=n.u:(A.u=Ja,t.addEventListener(e,r?qa:Xa,r)):t.removeEventListener(e,r?qa:Xa,r);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=A??"";break e}catch{}typeof A=="function"||(A==null||A===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&A==1?"":A))}}function Qh(t){return function(e){if(this.l){var A=this.l[e.type+t];if(e.t==null)e.t=Ja++;else if(e.t<A.u)return;return A(K.event?K.event(e):e)}}}function $a(t,e,A,n,i,r,s,a,o,c){var l,u,d,h,p,f,m,B,b,U,w,v,y,E,T,F,R,D=e.type;if(e.constructor!=null)return null;128&A.__u&&(o=!!(32&A.__u),r=[a=e.__e=A.__e]),(l=K.__b)&&l(e);e:if(typeof D=="function")try{if(B=e.props,b="prototype"in D&&D.prototype.render,U=(l=D.contextType)&&n[l.__c],w=l?U?U.props.value:l.__:n,A.__c?m=(u=e.__c=A.__c).__=u.__E:(b?e.__c=u=new D(B,w):(e.__c=u=new RA(B,w),u.constructor=D,u.render=yy),U&&U.sub(u),u.props=B,u.state||(u.state={}),u.context=w,u.__n=n,d=u.__d=!0,u.__h=[],u._sb=[]),b&&u.__s==null&&(u.__s=u.state),b&&D.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=PA({},u.__s)),PA(u.__s,D.getDerivedStateFromProps(B,u.__s))),h=u.props,p=u.state,u.__v=e,d)b&&D.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),b&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(b&&D.getDerivedStateFromProps==null&&B!==h&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(B,w),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(B,u.__s,w)===!1||e.__v==A.__v){for(e.__v!=A.__v&&(u.props=B,u.state=u.__s,u.__d=!1),e.__e=A.__e,e.__k=A.__k,e.__k.some(function(O){O&&(O.__=e)}),v=0;v<u._sb.length;v++)u.__h.push(u._sb[v]);u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(B,u.__s,w),b&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(h,p,f)})}if(u.context=w,u.props=B,u.__P=t,u.__e=!1,y=K.__r,E=0,b){for(u.state=u.__s,u.__d=!1,y&&y(e),l=u.render(u.props,u.state,u.context),T=0;T<u._sb.length;T++)u.__h.push(u._sb[T]);u._sb=[]}else do u.__d=!1,y&&y(e),l=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++E<25);u.state=u.__s,u.getChildContext!=null&&(n=PA(PA({},n),u.getChildContext())),b&&!d&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(h,p)),F=l,l!=null&&l.type===Pe&&l.key==null&&(F=Sh(l.props.children)),a=bh(t,_n(F)?F:[F],e,A,n,i,r,s,a,o,c),u.base=e.__e,e.__u&=-161,u.__h.length&&s.push(u),m&&(u.__E=u.__=null)}catch(O){if(e.__v=null,o||r!=null)if(O.then){for(e.__u|=o?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;r[r.indexOf(a)]=null,e.__e=a}else for(R=r.length;R--;)Ya(r[R]);else e.__e=A.__e,e.__k=A.__k;K.__e(O,e,A)}else r==null&&e.__v==A.__v?(e.__k=A.__k,e.__e=A.__e):a=e.__e=by(A.__e,e,A,n,i,r,s,o,c);return(l=K.diffed)&&l(e),128&e.__u?void 0:a}function Eh(t,e,A){for(var n=0;n<A.length;n++)eo(A[n],A[++n],A[++n]);K.__c&&K.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(r){r.call(i)})}catch(r){K.__e(r,i.__v)}})}function Sh(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:_n(t)?t.map(Sh):PA({},t)}function by(t,e,A,n,i,r,s,a,o){var c,l,u,d,h,p,f,m=A.props,B=e.props,b=e.type;if(b=="svg"?i="http://www.w3.org/2000/svg":b=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),r!=null){for(c=0;c<r.length;c++)if((h=r[c])&&"setAttribute"in h==!!b&&(b?h.localName==b:h.nodeType==3)){t=h,r[c]=null;break}}if(t==null){if(b==null)return document.createTextNode(B);t=document.createElementNS(i,b,B.is&&B),a&&(K.__m&&K.__m(e,r),a=!1),r=null}if(b==null)m===B||a&&t.data==B||(t.data=B);else{if(r=r&&Cr.call(t.childNodes),m=A.props||xn,!a&&r!=null)for(m={},c=0;c<t.attributes.length;c++)m[(h=t.attributes[c]).name]=h.value;for(c in m)if(h=m[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=h;else if(!(c in B)){if(c=="value"&&"defaultValue"in B||c=="checked"&&"defaultChecked"in B)continue;Ur(t,c,null,h,i)}}for(c in B)h=B[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?l=h:c=="value"?p=h:c=="checked"?f=h:a&&typeof h!="function"||m[c]===h||Ur(t,c,h,m[c],i);if(l)a||u&&(l.__html==u.__html||l.__html==t.innerHTML)||(t.innerHTML=l.__html),e.__k=[];else if(u&&(t.innerHTML=""),bh(e.type=="template"?t.content:t,_n(d)?d:[d],e,A,n,b=="foreignObject"?"http://www.w3.org/1999/xhtml":i,r,s,r?r[0]:A.__k&&Yt(A,0),a,o),r!=null)for(c=r.length;c--;)Ya(r[c]);a||(c="value",b=="progress"&&p==null?t.removeAttribute("value"):p!=null&&(p!==t[c]||b=="progress"&&!p||b=="option"&&p!=m[c])&&Ur(t,c,p,m[c],i),c="checked",f!=null&&f!=t[c]&&Ur(t,c,f,m[c],i))}return t}function eo(t,e,A){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(i){K.__e(i,A)}}function kh(t,e,A){var n,i;if(K.unmount&&K.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||eo(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(r){K.__e(r,e)}n.base=n.__P=null}if(n=t.__k)for(i=0;i<n.length;i++)n[i]&&kh(n[i],e,A||typeof t.type!="function");A||Ya(t.__e),t.__c=t.__=t.__e=void 0}function yy(t,e,A){return this.constructor(t,A)}function Uy(t,e,A){var n,i,r,s;e==document&&(e=document.documentElement),K.__&&K.__(t,e),i=(n=typeof A=="function")?null:A&&A.__k||e.__k,r=[],s=[],$a(e,t=(!n&&A||e).__k=za(Pe,null,[t]),i||xn,xn,e.namespaceURI,!n&&A?[A]:i?null:e.firstChild?Cr.call(e.childNodes):null,r,!n&&A?A:i?i.__e:e.firstChild,n,s),Eh(r,t,s)}function Qy(t){function e(A){var n,i;return this.getChildContext||(n=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(r){this.props.value!=r.value&&n.forEach(function(s){s.__e=!0,Za(s)})},this.sub=function(r){n.add(r);var s=r.componentWillUnmount;r.componentWillUnmount=function(){n&&n.delete(r),s&&s.call(r)}}),A.children}return e.__c="__cC"+vh++,e.__=t,e.Provider=e.__l=(e.Consumer=function(A,n){return A.children(n)}).contextType=e,e}Cr=Ch.slice,K={__e:function(t,e,A,n){for(var i,r,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((r=i.constructor)&&r.getDerivedStateFromError!=null&&(i.setState(r.getDerivedStateFromError(t)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,n||{}),s=i.__d),s)return i.__E=i}catch(a){t=a}throw t}},fh=0,RA.prototype.setState=function(t,e){var A;A=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=PA({},this.state),typeof t=="function"&&(t=t(PA({},A),this.props)),t&&PA(A,t),t!=null&&this.__v&&(e&&this._sb.push(e),Za(this))},RA.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Za(this))},RA.prototype.render=Pe,Ct=[],ph=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,mh=function(t,e){return t.__v.__b-e.__v.__b},br.__r=0,Bh=/(PointerCapture)$|Capture$/i,Ja=0,Xa=Qh(!1),qa=Qh(!0),vh=0;var Ey=0;function g(t,e,A,n,i,r){e||(e={});var s,a,o=e;if("ref"in o)for(a in o={},e)a=="ref"?s=e[a]:o[a]=e[a];var c={type:t,props:o,key:A,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ey,__i:-1,__u:0,__source:i,__self:r};if(typeof t=="function"&&(s=t.defaultProps))for(a in s)o[a]===void 0&&(o[a]=s[a]);return K.vnode&&K.vnode(c),c}const Sy=`:root,:host{--obi-modal-padding: 48px 48px 32px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 12px;--obi-modal-shadow: 0px 1px 2px rgba(0, 0, 0, .05);--obi-modal-xsmall-width: 320px;--obi-modal-xsmall-height: 240px;--obi-modal-small-width: 480px;--obi-modal-small-height: 400px;--obi-modal-medium-width: 640px;--obi-modal-medium-height: 545px;--obi-modal-large-width: 1200px;--obi-modal-large-height: 700px;--obi-font-family: "Satoshi", sans-serif;--obi-color-primary: #9500FF;--obi-color-primary-50: color-mix(in srgb, var(--obi-color-primary) 50%, white 50%);--obi-color-primary-30: color-mix(in srgb, var(--obi-color-primary) 30%, white 70%);--obi-color-tint: color-mix(in srgb, var(--obi-color-primary) 5%, white 95%);--obi-color-text: #18181B;--obi-course-color-selected: var(--obi-color-primary-50);--obi-course-color-tint: var(--obi-color-tint);--obi-course-progress-step-completed: #B3B3B3;--obi-course-progress-step-incomplete: #D9D9D9;--obi-course-progress-text-color: #757575;font-family:var(--obi-font-family);color:var(--obi-color-text)}.obi-button{font-family:var(--obi-font-family);color:var(--obi-color-text)}dialog{margin:auto;padding:0;border:none;border-radius:var(--obi-modal-border-radius);box-shadow:var(--obi-modal-shadow);background:var(--obi-modal-background-color);box-sizing:border-box}dialog>.modal-content{padding:var(--obi-modal-padding);box-sizing:border-box}dialog,dialog.modal-medium,dialog>.modal-content,dialog.modal-medium>.modal-content{width:var(--obi-modal-medium-width);min-height:var(--obi-modal-medium-height)}dialog.modal-xsmall,dialog.modal-xsmall>.modal-content{width:var(--obi-modal-xsmall-width);min-height:var(--obi-modal-xsmall-height)}dialog.modal-small,dialog.modal-small>.modal-content{width:var(--obi-modal-small-width);min-height:var(--obi-modal-small-height)}dialog.modal-large,dialog.modal-large>.modal-content{width:var(--obi-modal-large-width);min-height:var(--obi-modal-large-height)}dialog::backdrop{background:rgba(0,0,0,.5)}.tour-content{display:block;width:100%;height:100%}.tour-content .container{box-sizing:border-box;display:flex;flex-direction:column;align-items:center;padding:0;width:100%;height:100%}.tour-content .header{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:100%}.tour-content .title{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:700;font-size:32px;line-height:90%;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0}.tour-content .subtitle{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b;margin:0}.tour-content .visual{width:480px;height:240px;margin-top:24px;border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative}.tour-content .description{width:100%;min-height:48px;margin:24px 0 0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b}.tour-content .button-container{display:flex;margin-top:24px;flex-direction:column;align-items:center;gap:16px;width:100%}.tour-content .action-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;min-width:200px;height:40px;background:#303030;border:1px solid #303030;border-radius:4px;cursor:pointer;text-decoration:none}.tour-content .action-button.disabled{opacity:.6;cursor:not-allowed}.tour-content .button-text{height:16px;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{flex:1;display:flex;flex-direction:column}.obi-close-button{position:absolute;top:24px;right:24px;width:24px;height:24px;cursor:pointer;border:none;background:none;padding:0;display:flex;align-items:center;justify-content:center;z-index:1}.obi-panel{box-sizing:border-box;padding:24px;background-color:#fff;box-shadow:0 16px 32px -4px #0000001f,0 4px 8px -2px #00000014,inset 0 1px #fff9;border-radius:12px}.obi-pill.container{width:96px;height:30px;display:flex;align-items:center;justify-content:center}.obi-pill.container .pill{display:flex;align-items:center;justify-content:center;width:48px;height:6px;opacity:.7;border-radius:3px;background-color:var(--obi-color-primary);transition:width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill.container .pill.button{cursor:pointer}.obi-pill.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill.container.active .pill{width:96px;height:30px;border-radius:15px;opacity:1}.obi-pill.container.busy,.obi-pill.container.busy .pill{width:220px}.obi-pill2.container{display:flex;align-items:center;justify-content:center}.obi-pill2.container .pill{display:flex;align-items:center;justify-content:center;width:48px;height:6px;opacity:.7;border-radius:3px;background-color:var(--obi-color-primary);transform:translateY(0);transition:width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill2.container .pill.button{cursor:pointer}.obi-pill2.container:not(.active){transition:height 0s linear .15s;height:6px}.obi-pill2.container:not(.active) .pill{transform:translateY(12px);transition:transform 0s linear .15s,width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill2.container.active{transition:none;height:30px}.obi-pill2.container.active .pill{transition:transform 0s,width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out;width:96px;height:30px;border-radius:15px;opacity:1}.obi-pill2.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-popout{position:relative;display:inline-block}.obi-popout .obi-popout-target{cursor:pointer;display:inline-block}.obi-popout .content{position:absolute;background-color:#fff0;z-index:100;animation:popout-appear .15s ease-out}@keyframes popout-appear{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.obi-round-button-popout{z-index:600}.obi-round-button{flex:0 0 auto;display:flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:50%;padding:0;box-sizing:border-box;background-color:#fff;border:1px solid #D9D9D9;box-shadow:none}.obi-round-button:hover{cursor:pointer}.obi-round-button:disabled{box-shadow:none;background-color:#f0f0f0;color:#999;cursor:not-allowed!important;pointer-events:none}.obi-round-button-title{padding:8px 16px;border-radius:12px;background-color:#fff;color:#000;font-size:14px;font-weight:400;white-space:nowrap;box-shadow:0 4px 12px #00000026,0 2px 4px #0000001a;border:1px solid rgba(0,0,0,.08);z-index:5000;pointer-events:none;-webkit-user-select:none;user-select:none;position:relative}.obi-round-button-title:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-top:6px solid white;filter:drop-shadow(0 2px 2px rgba(0,0,0,.1))}.obi-equaliser{display:flex;align-items:center;gap:2px;height:32px}.obi-equaliser .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-equaliser .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1}.obi-message{display:inline-flex;align-items:center;justify-content:center;min-width:140px;padding:0 15px;text-wrap:nowrap;font-size:16px;font-weight:400;height:30px;box-sizing:border-box;background-color:#fff;border-radius:15px;border:1px solid #D9D9D9}.obi-message.clickable{box-shadow:0 4px 6px #0000001a;cursor:pointer}.obi-loading-dots{display:flex;align-items:center;gap:2px;height:32px}.obi-loading-dots .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-loading-dots .dot{width:3px;height:3px;border-radius:2px;position:relative;z-index:2}.obi-loading-dots .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1;height:0px;animation:bounce .9s ease-in-out infinite}@keyframes bounce{0%,60%,to{height:0px}30%{height:16px}}.obi-exit-survey{position:relative;width:320px;margin:0 auto;-webkit-backdrop-filter:none;backdrop-filter:none;background:white;z-index:9999}.obi-exit-survey-container{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-header{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-title{width:272px;height:22px;margin:0;font-family:Satoshi,sans-serif;font-size:16px;font-weight:600;line-height:140%;text-align:center;color:#1e1e1e;flex:none;align-self:stretch}.obi-exit-survey-subtitle{width:272px;height:20px;margin:0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;text-align:center;color:#757575;flex:none;align-self:stretch}.obi-exit-survey-options{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-options textarea{height:80px;resize:none;outline:none}.obi-exit-survey-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;width:272px;height:44px;border-radius:12px;cursor:pointer;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-button:hover{transform:translateY(-1px);box-shadow:0 4px 8px #0000001a}.obi-exit-survey-button:active{transform:translateY(0)}.obi-exit-survey-button-continue{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-button-continue:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-button-wrap-up{background:#303030;border:1px solid rgba(217,217,217);color:#fff;font-weight:500}.obi-exit-survey-button-wrap-up:hover{background:#404040;border-color:#d9d9d9}.obi-exit-survey-reason-button{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-reason-button:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-reason-button-secondary{display:flex;flex-direction:row;justify-content:center;align-items:center;padding:4px 6px;gap:8px;width:272px;height:28px;border-radius:4px;cursor:pointer;border:none;background:transparent;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;color:#5a5a5a;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-reason-button-secondary:hover{background:rgba(0,0,0,.05);color:#3a3a3a}.obi-message-input{display:inline-block;position:relative}.obi-message-input .container{width:212px;height:30px;box-sizing:border-box;background:#FFFFFF;border:1px solid var(--obi-color-primary-30);border-radius:15px;display:flex;align-items:center;flex:none;order:2;flex-grow:0;transition:height .3s ease,border-radius .3s ease;animation:expandMessageInput .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .container{height:auto;min-height:140px;border-radius:15px;align-items:flex-start;padding:8px 0;animation:expandMessageInputWide .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input .field{flex:1 1 0;border:none;background:transparent;outline:none;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:18px;color:#000;padding:4px 3px 0 16px;height:100%;box-sizing:border-box;min-width:0;resize:none;overflow:hidden;scrollbar-width:none;transition:padding .3s ease;animation:fadeInInputField .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .field{height:auto;min-height:120px;padding:4px 16px;overflow-y:auto;line-height:18px}.obi-message-input .field::placeholder{color:#999}.obi-message-input .field:disabled{cursor:not-allowed;opacity:.6}.obi-message-input .send{position:absolute;bottom:3px;right:4px;flex-shrink:0;width:24px;height:24px;background:var(--obi-color-primary);border:none;border-radius:9999px;display:flex;justify-content:center;align-items:center;cursor:pointer;transition:all .3s ease;color:#fff}.obi-message-input.expanded .send{width:28px;height:28px;position:relative;top:0;bottom:0;margin-right:0}.obi-message-input.expanded .button-container{display:flex;justify-content:space-between;align-items:center;width:100%;margin-top:8px}.obi-message-input .send:disabled{background:#CCCCCC;cursor:not-allowed;transform:none}.obi-message-input .container:focus-within{border-color:var(--obi-color-primary);box-shadow:0 0 0 2px #9008ff1a}@keyframes expandMessageInput{0%{width:32px}to{width:212px}}@keyframes expandMessageInputWide{0%{width:212px}to{width:340px}}@keyframes fadeInInputField{0%{opacity:0}60%{opacity:0}to{opacity:1}}.obi-course-progress{display:flex;flex-direction:column;justify-content:center;align-items:flex-start;gap:6px;width:100%;min-width:0;height:24px;flex:none;order:1;align-self:stretch;flex-grow:0}.obi-course-progress-steps{display:flex;flex-direction:row;align-items:center;justify-content:space-between;padding:0;gap:2px;width:100%;height:6px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-container{display:flex;flex-direction:column;justify-content:center;align-items:stretch;padding:2px 0;height:6px;flex:1;min-width:0}.obi-course-progress-step{width:100%;height:2px;background:var(--obi-course-progress-step-incomplete);border-radius:24px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-step.completed{background:var(--obi-course-progress-step-completed)}.obi-course-progress-description{width:100%;height:14px;font-family:var(--obi-font-family);font-style:normal;font-weight:500;font-size:14px;line-height:100%;color:var(--obi-course-progress-text-color);flex:none;order:1;flex-grow:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.obi-widget-popout{z-index:400}.obi-widget-panel{display:flex;flex-direction:column;gap:8px;align-items:center;justify-content:center;min-width:222px;width:min-content;padding:12px;box-sizing:border-box;border-radius:27px;background:white;transition:background .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel:not(.messaging){width:256px}.obi-widget-panel.tool-usage{width:384px}.obi-widget-panel:not(.expanded){background:transparent;border:none;box-shadow:none;transition:background .1s ease-out .1s,border .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel.maximized{transform:translateY(-110px)}.obi-widget-panel .obi-widget{display:flex;align-items:center;min-width:192px;padding-left:58px;box-sizing:border-box;gap:4px}.obi-widget-panel .obi-widget.active.in-plan{padding-left:0}.obi-widget-panel .obi-widget.active.in-plan .obi-round-button{animation:fade-in-button .2s ease-out .15s both}.obi-widget-panel .obi-widget.active .obi-equaliser{animation:fade-in-equaliser .2s ease-out .15s both}@keyframes fade-in-button{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes fade-in-equaliser{0%{opacity:0}to{opacity:1}}.obi-widget-panel .obi-course-progress-container{display:none;width:100%;max-height:0;opacity:0;transform:translateY(-10px);overflow:hidden;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel:hover .obi-course-progress-container{display:block;max-width:22 0px;animation:expand-course-progress .3s ease-in-out forwards}.obi-widget-panel:hover .obi-course-progress-container.expanded{max-width:330px}@keyframes expand-course-progress{0%{max-height:0;opacity:0;transform:translateY(-10px)}to{max-height:40px;opacity:1;transform:translateY(0)}}.obi-widget-pill-text{font-size:16px;font-weight:400;color:#fff;opacity:0;animation:fade-in-pill-text .3s ease-in-out forwards}@keyframes fade-in-pill-text{0%{opacity:0}40%{opacity:0}to{opacity:1}}.obi-widget-buttons{display:flex;flex-direction:row;gap:4px}.obi-widget-out-of-plan{display:flex;align-items:center;gap:4px}.obi-widget-out-of-plan .text{color:#fff;animation:fade-in-pill-text .3s ease-in-out forwards}.obi-widget-out-of-plan .round-button{display:none;animation:fade-in-button .2s ease-out .15s both}.obi-widget-out-of-plan .message{display:none}.obi-widget-out-of-plan.active:hover .round-button,.obi-widget-out-of-plan.active:hover .message,.obi-widget-out-of-plan.active.hover .round-button,.obi-widget-out-of-plan.active.hover .message{display:flex}.tour-select{display:block;font-family:Inter,sans-serif}.course-container{display:flex;padding:20px;align-items:flex-start;gap:8px;height:180px;border-radius:6px;border:1px solid rgba(0,0,0,.6);background:#fff;cursor:pointer;transition:all .2s;flex-direction:column;box-sizing:border-box;overflow:hidden}.course-container:hover{background-color:#f9fafb;border-color:#d1d5db;box-shadow:0 1px 2px #0000000d}.course-container:active{transform:scale(.98)}.course-container.selected{border-radius:6px;border:1px solid var(--obi-course-color-selected);background:var(--obi-course-color-tint)}.course-container.selected:hover{background:var(--obi-course-color-tint)}.header-row{display:flex;justify-content:space-between;align-items:flex-start;align-self:stretch;flex-shrink:0;text-align:left}.course-title{color:#000;font-family:Inter,sans-serif;font-size:20px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.2px;margin:0}.duration{display:flex;padding:4px 12px;justify-content:center;align-items:center;gap:8px;border-radius:9999px;background:var(--obi-course-color-tint);color:#000;font-family:Inter,sans-serif;font-size:14px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.14px;flex-shrink:0}.course-container.selected .duration{background:#fff}.course-description{flex:1 0 0;color:#0009;font-family:Inter,sans-serif;font-size:16px;font-style:normal;font-weight:400;line-height:140%;letter-spacing:-.16px;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;text-align:left}.course-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;padding:0;flex:1 0 0;align-self:stretch;min-height:364px}.controls{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.tabs{display:flex;gap:10px}.tab{display:flex;padding:6px 12px;justify-content:center;align-items:center;align-self:stretch;border:none;background:none;cursor:pointer;font-family:Inter,sans-serif;font-size:16px;font-weight:500;color:#0006;border-bottom:2px solid transparent;transition:all .2s}.tab.active{color:#000;border-bottom:2px solid var(--obi-color-primary)}.tab:hover{color:#000}.filter{position:relative;display:flex;align-items:center;width:336px;height:40px}.filter input{color:var(--obi-color-text);caret-color:var(--obi-color-text);padding:8px 12px 8px 36px;border-radius:6px;border:1px solid rgba(0,0,0,.1);background:#fff;font-family:Inter,sans-serif;font-size:14px;line-height:20px;width:100%;height:100%;box-sizing:border-box;outline:none}.filter input:focus{outline:1px solid var(--obi-color-primary);outline-offset:-1px}.filter input::placeholder{color:#0006}.filter svg{position:absolute;left:12px;pointer-events:none}@media (max-width: 767px){.course-grid{grid-template-columns:1fr}}.loading,.error,.empty{display:flex;justify-content:center;align-items:center;margin-top:16px}.error{color:#ef4444}.tour-select-modal-container{display:flex;flex-direction:column;align-items:center;gap:24px;flex:1 0 0;align-self:stretch;font-family:Satoshi,sans-serif;color:#000;text-align:center;max-width:1200px;width:100%;min-height:600px;box-sizing:border-box}.course-list-wrapper{flex:1;overflow-y:auto;width:100%;min-height:0;max-height:424px;padding-right:3px;box-sizing:border-box}.course-list-wrapper::-webkit-scrollbar{width:3px}.course-list-wrapper::-webkit-scrollbar-track{background:transparent}.course-list-wrapper::-webkit-scrollbar-thumb{background-color:#000;border-radius:2px;min-height:20px}.course-list-wrapper::-webkit-scrollbar-thumb:hover{background-color:#333}.header{display:flex;align-items:flex-start;gap:16px;width:100%;text-align:left}.icon{display:flex;width:56px;height:56px;padding:12px;justify-content:center;align-items:center;border-radius:12px;border:1px solid var(--obi-color-primary);background:var(--obi-color-primary);box-sizing:border-box}.icon img{width:32px;height:32px;color:#fff;fill:#fff}.title-section{align-self:stretch;flex:1}.tour-select-modal-container h1{color:#18181b;font-family:Satoshi;font-size:32px;font-style:normal;font-weight:700;line-height:90%;letter-spacing:-.96px;margin:0 0 8px}.subtitle{color:#18181b;font-family:Satoshi;font-size:20px;font-style:normal;font-weight:500;line-height:90%;letter-spacing:-.6px;margin:0}.footer{display:flex;width:360px;flex-direction:column;align-items:center;gap:12px}.footer-button{display:flex;height:48px;padding:16px;justify-content:center;align-items:center;gap:8px;align-self:stretch;border-radius:6px;background:#18181b;border:none;cursor:pointer;color:#fafafa;font-family:Satoshi;font-weight:500;transition:opacity .2s ease}.footer-button:disabled{opacity:.5;cursor:not-allowed}.footer-button:not(:disabled){opacity:1}.footer-button:not(:disabled):hover{background:#27272a}.footer-text{color:#18181b;font-family:Satoshi;font-size:12px;font-style:normal;font-weight:400;line-height:100%;letter-spacing:-.12px;margin:0;text-align:center}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%);background-size:200% 100%;animation:loading 1.5s infinite;border-radius:4px}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.skeleton-title{height:32px;width:60%;margin-bottom:12px}.skeleton-subtitle{height:20px;width:80%}
|
|
46
|
+
`},xa}var Md;function Bb(){if(Md)return dA;Md=1;var t=pb(),e=mb(),A=Ia();return dA.grammar=A,dA.write=e,dA.parse=t.parse,dA.parseParams=t.parseParams,dA.parseFmtpConfig=t.parseFmtpConfig,dA.parsePayloads=t.parsePayloads,dA.parseRemoteCandidates=t.parseRemoteCandidates,dA.parseImageAttributes=t.parseImageAttributes,dA.parseSimulcastStreamList=t.parseSimulcastStreamList,dA}var At=Bb();function _a(t,e,A){var n,i,r;e===void 0&&(e=50),A===void 0&&(A={});var s=(n=A.isImmediate)!=null&&n,a=(i=A.callback)!=null&&i,o=A.maxWait,c=Date.now(),l=[];function u(){if(o!==void 0){var h=Date.now()-c;if(h+e>=o)return o-h}return e}var d=function(){var h=[].slice.call(arguments),p=this;return new Promise(function(f,m){var B=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var U=t.apply(p,h);a&&a(U),l.forEach(function(w){return(0,w.resolve)(U)}),l=[]}},u()),B){var b=t.apply(p,h);return a&&a(b),f(b)}l.push({resolve:f,reject:m})})};return d.cancel=function(h){r!==void 0&&clearTimeout(r),l.forEach(function(p){return(0,p.reject)(h)}),l=[]},d}const vb=.7,Cb=20,Jt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Nd extends yA.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=W,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=_a(i=>C(this,void 0,void 0,function*(){this.emit(Jt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),Cb),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=FA((n=A.loggerName)!==null&&n!==void 0?n:lA.PCTransport),this.loggerOptions=A,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=A=>{var n;A.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,A.candidate))},e.onicecandidateerror=A=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,A)},e.oniceconnectionstatechange=()=>{var A;(A=this.onIceConnectionStateChange)===null||A===void 0||A.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var A;(A=this.onSignalingStatechange)===null||A===void 0||A.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var A;(A=this.onConnectionStateChange)===null||A===void 0||A.call(this,e.connectionState)},e.ondatachannel=A=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,A)},e.ontrack=A=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,A)},e}get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions).loggerContextCb)===null||A===void 0?void 0:A.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){return C(this,void 0,void 0,function*(){var A;let n;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=wb(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=At.parse((A=e.sdp)!==null&&A!==void 0?A:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let a=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(a=c.payload,!0):!1),a===0)return!0;let o=!1;for(const c of r.fmtp)if(c.payload===a){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),o=!0;break}return o||s.maxbr>0&&r.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),n=At.write(i)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Jt.NegotiationComplete),e.sdp&&At.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Jt.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return C(this,void 0,void 0,function*(){var A;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 r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const i=At.parse((A=n.sdp)!==null&&A!==void 0?A:"");i.media.forEach(r=>{Vd(r),r.type==="audio"?Kd(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let a=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(a=c.payload,!0):!1),a===0||(kn(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const o=Math.round(s.maxbr*vb);for(const c of r.fmtp)if(c.payload===a){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(o));break}return!0})}),yield this.setMungedSDP(n,At.write(i)),this.onOffer(n)})}createAndSetAnswer(){return C(this,void 0,void 0,function*(){var e;const A=yield this.pc.createAnswer(),n=At.parse((e=A.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(i=>{Vd(i),i.type==="audio"&&Kd(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(A,At.write(n)),A})}createDataChannel(e,A){return this.pc.createDataChannel(e,A)}addTransceiver(e,A){return this.pc.addTransceiver(e,A)}addTrack(e){if(!this._pc)throw new ye("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var A;if(!this._pc)throw new ye("PC closed, cannot configure");return(A=this._pc)===null||A===void 0?void 0:A.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var A;return(A=this._pc)===null||A===void 0?void 0:A.removeTrack(e)}getConnectionState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&A!==void 0?A:"closed"}getICEConnectionState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&A!==void 0?A:"closed"}getSignallingState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&A!==void 0?A:"closed"}getTransceivers(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&A!==void 0?A:[]}getSenders(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&A!==void 0?A:[]}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 A="";const n=new Map,i=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":A=a.selectedCandidatePairId;break;case"candidate-pair":A===""&&a.selected&&(A=a.id),n.set(a.id,a);break;case"remote-candidate":i.set(a.id,"".concat(a.address,":").concat(a.port));break}}),A==="")return;const s=(e=n.get(A))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,A,n){return C(this,void 0,void 0,function*(){if(A){const i=e.sdp;e.sdp=A;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:A})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new aa(r)}})}ensureVideoDDExtensionForSVC(e,A){var n,i;if(!((n=e.ext)===null||n===void 0?void 0:n.some(s=>s.uri===wd))){if(this.ddExtID===0){let s=0;A.media.forEach(a=>{var o;a.type==="video"&&((o=a.ext)===null||o===void 0||o.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:wd})}}}function Kd(t,e,A){let n=0;t.rtp.some(i=>i.codec==="opus"?(n=i.payload,!0):!1),n>0&&(t.rtcpFb||(t.rtcpFb=[]),A.includes(t.mid)&&!t.rtcpFb.some(i=>i.payload===n&&i.type==="nack")&&t.rtcpFb.push({payload:n,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(i=>i.payload===n?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function wb(t){var e;const A=[],n=[],i=At.parse((e=t.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var a;s.type==="audio"&&(s.rtp.some(o=>o.codec==="opus"?(r=o.payload,!0):!1),!((a=s.rtcpFb)===null||a===void 0)&&a.some(o=>o.payload===r&&o.type==="nack")&&n.push(s.mid),s.fmtp.some(o=>o.payload===r?(o.config.includes("sprop-stereo=1")&&A.push(s.mid),!0):!1))}),{stereoMids:A,nackMids:n}}function Vd(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 Pa="vp8",bb={audioPreset:ua.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ha.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Pa,backupCodec:!0},Gd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},jd={deviceId:{ideal:"default"},resolution:Sn.h720.resolution},yb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new hw,disconnectOnPageLeave:!0,webAudioMix:!1},Ra={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ue;(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"})(ue||(ue={}));class Ub{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,A,n){var i;this.peerConnectionTimeout=Ra.peerConnectionTimeout,this.log=W,this.updateState=()=>{var r;const s=this.state,a=this.requiredTransports.map(o=>o.getConnectionState());a.every(o=>o==="connected")?this.state=ue.CONNECTED:a.some(o=>o==="failed")?this.state=ue.FAILED:a.some(o=>o==="connecting")?this.state=ue.CONNECTING:a.every(o=>o==="closed")?this.state=ue.CLOSED:a.some(o=>o==="closed")?this.state=ue.CLOSING:a.every(o=>o==="new")&&(this.state=ue.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(ue[s]," to ").concat(ue[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=FA((i=n.loggerName)!==null&&i!==void 0?i:lA.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!A,this.isSubscriberConnectionRequired=A,this.publisher=new Nd(e,n),this.subscriber=new Nd(e,n),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=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,cA.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,cA.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=ue.NEW,this.connectionLock=new Oe,this.remoteOfferLock=new Oe}get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions).loggerContextCb)===null||A===void 0?void 0:A.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){return this.publisher.setRemoteDescription(e)}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 A of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(A)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}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,A){return C(this,void 0,void 0,function*(){A===cA.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){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 A=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{A()}})}updateConfiguration(e,A){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),A&&this.triggerIceRestart()}ensurePCTransportConnection(e,A){return C(this,void 0,void 0,function*(){var n;const i=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,A)))}finally{i()}})}negotiate(e){return C(this,void 0,void 0,function*(){return new Promise((A,n)=>C(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Jt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Jt.NegotiationComplete,()=>{clearTimeout(i),A()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),n(s)})}))})}addPublisherTransceiver(e,A){return this.publisher.addTransceiver(e,A)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,A){return this.publisher.createDataChannel(e,A)}getConnectedAddress(e){return e===cA.PUBLISHER?this.publisher.getConnectedAddress():e===cA.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,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((o,c)=>C(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),Te.clearTimeout(u),c(new Ae("room connection has been cancelled",J.Cancelled))};i!=null&&i.signal.aborted&&l(),i==null||i.signal.addEventListener("abort",l);const u=Te.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",l),c(new Ae("could not establish pc connection",J.InternalError))},s);for(;this.state!==ue.CONNECTED;)if(yield Ke(50),i!=null&&i.signal.aborted){c(new Ae("room connection has been cancelled",J.Cancelled));return}Te.clearTimeout(u),i==null||i.signal.removeEventListener("abort",l),o()}))}()})}}class de extends Error{constructor(e,A,n){super(A),this.code=e,this.message=Jd(A,de.MAX_MESSAGE_BYTES),this.data=n?Jd(n,de.MAX_DATA_BYTES):void 0}static fromProto(e){return new de(e.code,e.message,e.data)}toProto(){return new ou({code:this.code,message:this.message,data:this.data})}static builtIn(e,A){return new de(de.ErrorCode[e],de.ErrorMessage[e],A)}}de.MAX_MESSAGE_BYTES=256,de.MAX_DATA_BYTES=15360,de.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},de.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 Wd=15360;function La(t){return new TextEncoder().encode(t).length}function Jd(t,e){if(La(t)<=e)return t;let A=0,n=t.length;const i=new TextEncoder;for(;A<n;){const r=Math.floor((A+n+1)/2);i.encode(t.slice(0,r)).length<=e?A=r:n=r-1}return t.slice(0,A)}const Da=2e3;function ur(t,e){if(!e)return 0;let A,n;return"bytesReceived"in t?(A=t.bytesReceived,n=e.bytesReceived):"bytesSent"in t&&(A=t.bytesSent,n=e.bytesSent),A===void 0||n===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(A-n)*8*1e3/(t.timestamp-e.timestamp)}const Qb=1e3;class Xd extends k{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,A,n){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,A,r),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=_a(()=>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(x.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Oe,this.pauseUpstreamLock=new Oe,this.processorLock=new Oe,this.restartLock=new Oe,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==k.Kind.Video)return;const{width:e,height:A}=this._mediaStreamTrack.getSettings();if(e&&A)return{width:e,height:A}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,A;return(A=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&A!==void 0?A:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,A){return C(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!A)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Vt(this._mediaStreamTrack,r)}),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 i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Kt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Kt(i??e,r)}))})}waitForDimensions(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Qb;return function*(){var n;if(e.kind===k.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=uA())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Ke(10));const i=Date.now();for(;Date.now()-i<A;){const r=e.dimensions;if(r)return r;yield Ke(50)}throw new IA("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===$A(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),$A(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===k.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===k.Kind.Audio?"audioinput":"videoinput";return A?Qe.getInstance().normalizeDeviceId(r,n,i):n}()})}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,A){return C(this,void 0,void 0,function*(){if(!this.sender)throw new IA("unable to replace an unpublished track");let n,i;return typeof A=="boolean"?n=A:A!==void 0&&(n=A.userProvidedTrack,i=A.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return C(this,void 0,void 0,function*(){this.manuallyStopped=!1;const A=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:i}=e,r=fw(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===k.Kind.Video?s.video=n||i?{deviceId:n,facingMode:i}:!0:s.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{Vt(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield o.applyConstraints(r),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=e,this.emit(x.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{A()}})}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?x.Muted:x.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),bd()&&(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 A=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(x.UpstreamPaused,this);const n=uA();if((n==null?void 0:n.name)==="Safari"&&mt(n.version,"12.0")<0)throw new sa("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{A()}})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;const A=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(x.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{A()}})}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(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),o={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield A.init(o),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Kt(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(c=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))),n.processor=A,n.processorElement=a,n.processor.processedTrack){for(const c of n.attachedElements)c!==n.processorElement&&i&&(Vt(n._mediaStreamTrack,c),Kt(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(x.TrackProcessorUpdate,n.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return C(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,A||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(x.TrackProcessorUpdate))}()})}}class dr extends Xd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,k.Kind.Audio,A,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!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(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}s&&this.prevStats&&(this._currentBitrate=ur(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(x.AudioTrackFeatureUpdate,this,oA.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(x.AudioTrackFeatureUpdate,this,oA.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===k.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{A()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==$A(this._constraints.deviceId);return this.source===k.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{A()}})}restartTrack(e){return C(this,void 0,void 0,function*(){let A;if(e){const n=Ea({audio:e});typeof n.audio!="boolean"&&(A=n.audio)}yield this.restart(A)})}restart(e){const A=Object.create(null,{restart:{get:()=>super.restart}});return C(this,void 0,void 0,function*(){const n=yield A.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Ve()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Da)))}setProcessor(e){return C(this,void 0,void 0,function*(){var A;const n=yield this.processorLock.lock();try{if(!UA()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield(A=this.sender)===null||A===void 0?void 0:A.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(x.TrackProcessorUpdate,this.processor)}finally{n()}})}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 A=yield this.sender.getStats();let n;return A.forEach(i=>{i.type==="outbound-rtp"&&(n={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),n})}checkForSilence(){return C(this,void 0,void 0,function*(){const e=yield Id(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(x.AudioSilenceDetected)),e})}}function Eb(t,e,A){switch(t.kind){case"audio":return new dr(t,e,!1,void 0,A);case"video":return new fr(t,e,!1,A);default:throw new IA("unsupported track type: ".concat(t.kind))}}const Sb=Object.values(Sn),kb=Object.values(da),Tb=Object.values(ha),Fb=[Sn.h180,Sn.h360],Ib=[da.h180,da.h360],xb=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(A=>{var n,i;return new ee(Math.floor(t.width/A.scaleResolutionDownBy),Math.floor(t.height/A.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(A.scaleResolutionDownBy,2)*(((n=t.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((i=A.fps)!==null&&i!==void 0?i:30))))),A.fps,t.encoding.priority)}),Ha=["q","h","f"];function Oa(t,e,A,n){var i,r;let s=n==null?void 0:n.videoEncoding;t&&(s=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,o=n==null?void 0:n.scalabilityMode,c=n==null?void 0:n.videoCodec;if(!s&&!a&&!o||!e||!A)return[{}];s||(s=Pb(t,e,A,c),W.debug("using video encoding",s));const l=s.maxFramerate,u=new ee(e,A,s.maxBitrate,s.maxFramerate,s.priority);if(o&&kn(c)){const p=new hr(o),f=[];if(p.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(o));const m=uA();if(ZA()||UA()||(m==null?void 0:m.name)==="Chrome"&&mt(m==null?void 0:m.version,"113")<0){const B=p.suffix=="h"?2:3;for(let b=0;b<p.spatial;b+=1)f.push({rid:Ha[2-b],maxBitrate:s.maxBitrate/Math.pow(B,b),maxFramerate:u.encoding.maxFramerate});f[0].scalabilityMode=o}else f.push({maxBitrate:s.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:o});return u.encoding.priority&&(f[0].priority=u.encoding.priority,f[0].networkPriority=u.encoding.priority),W.debug("using svc encoding",{encodings:f}),f}if(!a)return[s];let d=[];t?d=(i=Yd(n==null?void 0:n.screenShareSimulcastLayers))!==null&&i!==void 0?i:qd(t,u):d=(r=Yd(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:qd(t,u);let h;if(d.length>0){const p=d[0];d.length>1&&([,h]=d);const f=Math.max(e,A);if(f>=960&&h)return Ma(e,A,[p,h,u],l);if(f>=480)return Ma(e,A,[p,u],l)}return Ma(e,A,[u])}function _b(t,e,A){var n,i,r,s;if(!A.backupCodec||A.backupCodec===!0||A.backupCodec.codec===A.videoCodec)return;e!==A.backupCodec.codec&&W.warn("requested a different codec than specified as backup",{serverRequested:e,backup:A.backupCodec.codec}),A.videoCodec=e,A.videoEncoding=A.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),o=(n=a.width)!==null&&n!==void 0?n:(i=t.dimensions)===null||i===void 0?void 0:i.width,c=(r=a.height)!==null&&r!==void 0?r:(s=t.dimensions)===null||s===void 0?void 0:s.height;return t.source===k.Source.ScreenShare&&A.simulcast&&(A.simulcast=!1),Oa(t.source===k.Source.ScreenShare,o,c,A)}function Pb(t,e,A,n){const i=Rb(t,e,A);let{encoding:r}=i[0];const s=Math.max(e,A);for(let a=0;a<i.length;a+=1){const o=i[a];if(r=o.encoding,o.width>=s)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Rb(t,e,A){if(t)return Tb;const n=e>A?e/A:A/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Sb:kb}function qd(t,e){if(t)return xb(e);const{width:A,height:n}=e,i=A>n?A/n:n/A;return Math.abs(i-16/9)<Math.abs(i-4/3)?Fb:Ib}function Ma(t,e,A,n){const i=[];if(A.forEach((r,s)=>{if(s>=Ha.length)return;const a=Math.min(t,e),c={rid:Ha[s],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(c.maxFramerate=l);const u=Gt()||s===0;r.encoding.priority&&u&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),UA()&&Ud()==="ios"){let r;i.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let s=!0;i.forEach(a=>{var o;a.maxFramerate!=r&&(s&&(s=!1,W.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),W.info('Setting framerate of encoding "'.concat((o=a.rid)!==null&&o!==void 0?o:"",'" to ').concat(r)),a.maxFramerate=r)})}return i}function Yd(t){if(t)return t.sort((e,A)=>{const{encoding:n}=e,{encoding:i}=A;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class hr{constructor(e){const A=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!A)throw new Error("invalid scalability mode");if(this.spatial=parseInt(A[1]),this.temporal=parseInt(A[2]),A.length>3)switch(A[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=A[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Lb(t){return t.source===k.Source.ScreenShare||t.constraints.height&&$A(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const Db=5e3;class fr extends Xd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,k.Kind.Video,A,n,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const s=new Map(r.map(a=>[a.rid,a]));if(this.prevStats){let a=0;s.forEach((o,c)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(c);a+=ur(o,u)}),this._currentBitrate=a}this.prevStats=s}),this.senderLock=new Oe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var A;if(this.signalClient=e,!Ve())return;const n=(A=this.sender)===null||A===void 0?void 0:A.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Da))}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 A,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var a=!0,o=XA(this.simulcastCodecs.values()),c;c=yield o.next(),A=c.done,!A;a=!0)r=c.value,a=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(l){n={error:l}}finally{try{!a&&!A&&(i=o.return)&&(yield i.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return C(this,void 0,void 0,function*(){var A,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var a=!0,o=XA(this.simulcastCodecs.values()),c;c=yield o.next(),A=c.done,!A;a=!0){r=c.value,a=!1;const l=r;yield(s=l.sender)===null||s===void 0?void 0:s.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!a&&!A&&(i=o.return)&&(yield i.call(o))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===k.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{A()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.source===k.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{A()}})}setTrackMuted(e){super.setTrackMuted(e);for(const A of this.simulcastCodecs.values())A.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 A=[],n=yield this.sender.getStats();return n.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},a=n.get(i.remoteId);a&&(s.jitter=a.jitter,s.packetsLost=a.packetsLost,s.roundTripTime=a.roundTripTime),A.push(s)}}),A.sort((i,r)=>{var s,a;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((a=i.frameWidth)!==null&&a!==void 0?a:0)}),A})}setPublishingQuality(e){const A=[];for(let n=AA.LOW;n<=AA.HIGH;n+=1)A.push(new Xs({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(A)}restartTrack(e){return C(this,void 0,void 0,function*(){var A,n,i,r,s;let a;if(e){const u=Ea({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a);try{for(var o=!0,c=XA(this.simulcastCodecs.values()),l;l=yield c.next(),A=l.done,!A;o=!0){r=l.value,o=!1;const u=r;u.sender&&((s=u.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!o&&!A&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const A=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});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,a,o,c,l,u;if(yield A.setProcessor.call(i,n,r),!((l=i.processor)===null||l===void 0)&&l.processedTrack)try{for(var d=!0,h=XA(i.simulcastCodecs.values()),p;p=yield h.next(),s=p.done,!s;d=!0)c=p.value,d=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(i.processor.processedTrack)}catch(f){a={error:f}}finally{try{!d&&!s&&(o=h.return)&&(yield o.call(h))}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 A=this.sender.getParameters();A.degradationPreference=e,this.sender.setParameters(A)}catch(A){this.log.warn("failed to set degradationPreference",Object.assign({error:A},this.logContext))}})}addSimulcastTrack(e,A){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:A};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,A){const n=this.simulcastCodecs.get(e);n&&(n.sender=A,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Db))}setPublishingCodecs(e){return C(this,void 0,void 0,function*(){var A,n,i,r,s,a,o;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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(A=!0,n=XA(e);i=yield n.next(),r=i.done,!r;A=!0){o=i.value,A=!1;const l=o;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const d of l.qualities)if(d.enabled){c.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield zd(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){s={error:l}}finally{try{!A&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return C(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield zd(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),bd()&&this.isInBackground&&this.source===k.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function zd(t,e,A,n,i,r){return C(this,void 0,void 0,function*(){const s=yield n.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:t,qualities:A,senderEncodings:e}));try{const a=t.getParameters(),{encodings:o}=a;if(!o)return;if(o.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:e}));return}let c=!1;const l=uA();if((l==null?void 0:l.name)==="Chrome"&&mt(l==null?void 0:l.version,"133")>0&&o[0].scalabilityMode){const d=o[0],h=new hr(d.scalabilityMode);let p=Lt.OFF;if(A.forEach(f=>{f.enabled&&(p===Lt.OFF||f.quality>p)&&(p=f.quality)}),p===Lt.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==p+1){c=!0,d.active=!0;const f=new hr(e[0].scalabilityMode);h.spatial=p+1,h.suffix=f.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-p),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else o.forEach((d,h)=>{var p;let f=(p=d.rid)!==null&&p!==void 0?p:"";f===""&&(f="q");const m=Zd(f),B=A.find(b=>b.quality===m);B&&d.active!==B.enabled&&(c=!0,d.active=B.enabled,i.debug("setting layer ".concat(B.quality," to ").concat(d.active?"enabled":"disabled"),r),Gt()&&(B.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(a.encodings=o,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:a.encodings})),yield t.setParameters(a))}finally{s()}})}function Zd(t){switch(t){case"f":return AA.HIGH;case"h":return AA.MEDIUM;case"q":return AA.LOW;default:return AA.HIGH}}function $d(t,e,A,n){if(!A)return[new ft({quality:AA.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(n){const i=A[0].scalabilityMode,r=new hr(i),s=[],a=r.suffix=="h"?1.5:2,o=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new ft({quality:Math.min(AA.HIGH,r.spatial-1)-c,width:Math.ceil(t/Math.pow(a,c)),height:Math.ceil(e/Math.pow(a,c)),bitrate:A[0].maxBitrate?Math.ceil(A[0].maxBitrate/Math.pow(o,c)):0,ssrc:0}));return s}return A.map(i=>{var r,s,a;const o=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=Zd((s=i.rid)!==null&&s!==void 0?s:"");return new ft({quality:c,width:Math.ceil(t/o),height:Math.ceil(e/o),bitrate:(a=i.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const eh="_lossy",Ah="_reliable",Hb=2*1e3,Na="leave-reconnect";var hA;(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"})(hA||(hA={}));class Ob extends yA.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var A;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ra.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=hA.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=W,this.handleDataChannel=n=>C(this,[n],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===Ah)r.reliableDCSub=s;else if(s.label===eh)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>C(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let a;if(n.data instanceof ArrayBuffer)a=n.data;else if(n.data instanceof Blob)a=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const o=Ne.fromBinary(new Uint8Array(a));((i=o.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(_.ActiveSpeakersUpdate,o.value.value.speakers):(((r=o.value)===null||r===void 0?void 0:r.case)==="user"&&Nb(o,o.value.value),this.emit(_.DataPacketReceived,o))}finally{s()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:s}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?X.LOSSY:X.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,i)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=o=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(o,"ms. giving up"),this.logContext),this.emit(_.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(a===null){r(s);return}n===Na&&(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=Te.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,i)=>{this.pcState===hA.Connected&&n();const r=()=>{this.off(_.Disconnected,s),n()},s=()=>{this.off(_.Restarted,r),i()};this.once(_.Restarted,r),this.once(_.Disconnected,s)}),this.updateAndEmitDCBufferStatus=n=>{const i=this.isBufferStatusLow(n);typeof i<"u"&&i!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,i),this.emit(_.DCBufferStatusChanged,i,n))},this.isBufferStatusLow=n=>{const i=this.dataChannelForKind(n);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ne.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Dt.RR_SIGNAL_DISCONNECTED))},this.log=FA((A=e.loggerName)!==null&&A!==void 0?A:lA.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ka(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Oe,this.dataProcessLock=new Oe,this.dcBufferStatus=new Map([[X.LOSSY,!0],[X.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(_.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(_.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(_.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(_.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(_.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(_.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(_.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(_.SignalRequestResponse,n)}get logContext(){var e,A,n,i,r,s,a,o;return{room:(A=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||A===void 0?void 0:A.name,roomID:(i=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(o=(a=this.latestJoinResponse)===null||a===void 0?void 0:a.participant)===null||o===void 0?void 0:o.sid}}join(e,A,n,i){return C(this,void 0,void 0,function*(){this.url=e,this.token=A,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,A,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(_.SignalConnected)},10),r}catch(r){if(r instanceof Ae&&r.reason===J.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,A,n,i);throw r}})}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(_.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 A=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};A(this.lossyDC),A(this.lossyDCSub),A(this.reliableDC),A(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}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 IA("a track with the same ID has already been published");return new Promise((A,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new Ae("publication of local track timed out, no response from server",J.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),A(r)},reject:()=>{clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:A}=this.pendingTrackResolvers[e.track.id];A&&A(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(A){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:A}))}return!1}updateMuteStatus(e,A){this.client.sendMuteTrack(e,A)}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 A,n;if(this.pcManager&&this.pcManager.currentState!==ue.NEW)return;this.participantSid=(A=e.participant)===null||A===void 0?void 0:A.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new Ub(i,e.subscriberPrimary,this.loggerOptions),this.emit(_.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>C(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===ue.CONNECTED){const l=this.pcState===hA.New;this.pcState=hA.Connected,l&&this.emit(_.Connected,e)}else r===ue.FAILED&&this.pcState===hA.Connected&&(this.pcState=hA.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Dt.RR_SUBSCRIBER_FAILED:Dt.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===ne.RECONNECTING,c=[ue.FAILED,ue.CLOSING,ue.CLOSED].includes(r);o&&c&&!this._isClosed&&this.emit(_.Offline)}),this.pcManager.onTrack=r=>{this.emit(_.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Mb((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>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))}),this.client.onTrickle=(e,A)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:A})),this.pcManager.addIceCandidate(e,A))},this.client.onOffer=e=>C(this,void 0,void 0,function*(){if(!this.pcManager)return;const A=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(A)}),this.client.onLocalTrackPublished=e=>{var A;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(A=e.track)===null||A===void 0?void 0:A.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:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(_.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(_.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,A)=>{this.emit(_.RemoteMute,e,A)},this.client.onSubscribedQualityUpdate=e=>{this.emit(_.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var A;this.participantSid=(A=e.participant)===null||A===void 0?void 0:A.sid,this.emit(_.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Dt.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 Mt.DISCONNECT:this.emit(_.Disconnected,e==null?void 0:e.reason),this.close();break;case Mt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Na);break;case Mt.RESUME:this.handleDisconnect(Na)}}}makeRTCConfiguration(e){var A;const n=Object.assign({},this.rtcConfig);if(!((A=this.signalOpts)===null||A===void 0)&&A.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),n.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Un.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}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(eh,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ah,{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,A,n){return C(this,void 0,void 0,function*(){if(fa())return yield this.createTransceiverRTCRtpSender(e,A,n);if(ga())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,A,n,i){return C(this,void 0,void 0,function*(){if(fa())return this.createSimulcastTransceiverSender(e,A,n,i);if(ga())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,A,n){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Wt(e)&&(e.codec=A.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,A,n,i){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(A.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return C(this,void 0,void 0,function*(){var A,n,i;if(!this._isClosed){if(this.attemptingReconnect){W.warn("already attempting reconnect, returning early",this.logContext);return}(((A=this.clientConfiguration)===null||A===void 0?void 0:A.resumeConnection)===Un.DISABLED||((i=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&i!==void 0?i:ue.NEW)===ue.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let s=!0;r instanceof ye?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Xt||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",Dt.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(_.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(A){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:A}))}return null}restartConnection(e){return C(this,void 0,void 0,function*(){var A,n,i;try{if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Xt;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Ae&&s.reason===J.NotAllowed?new ye("could not reconnect, token might be expired"):new Xt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ne.CONNECTED)throw new Xt("Signal connection got severed during reconnect");(A=this.regionUrlProvider)===null||A===void 0||A.resetAttempts(),this.emit(_.Restarted)}catch(r){const s=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return C(this,void 0,void 0,function*(){var A;if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");if(!this.pcManager)throw new ye("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Ae&&i.reason===J.NotAllowed?new ye("could not reconnect, token might be expired"):i instanceof Ae&&i.reason===J.LeaveRequest?i:new Xt(r)}if(this.emit(_.SignalResumed),n){const i=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(i)}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!==ne.CONNECTED)throw new Xt("Signal connection got severed during reconnect");this.client.setReconnected(),((A=this.reliableDC)===null||A===void 0?void 0:A.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(_.Resumed)})}waitForPCInitialConnection(e,A){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(A,e)})}waitForPCReconnected(){return C(this,void 0,void 0,function*(){this.pcState=hA.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ke(Hb),!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=hA.Connected}catch(e){throw this.pcState=hA.Disconnected,new Ae("could not establish PC connection, ".concat(e.message),J.InternalError)}})}publishRpcResponse(e,A,n,i){return C(this,void 0,void 0,function*(){const r=new Ne({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcResponse",value:new au({requestId:A,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,X.RELIABLE)})}publishRpcAck(e,A){return C(this,void 0,void 0,function*(){const n=new Ne({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcAck",value:new su({requestId:A})}});yield this.sendDataPacket(n,X.RELIABLE)})}sendDataPacket(e,A){return C(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(A);const i=this.dataChannelForKind(A);i&&i.send(n),this.updateAndEmitDCBufferStatus(A)})}waitForBufferStatusLow(e){return new Promise((A,n)=>C(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))A();else{const i=()=>n("Engine closed");for(this.once(_.Closing,i);!this.dcBufferStatus.get(e);)yield Ke(10);this.off(_.Closing,i),A()}}))}ensureDataTransportConnected(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new ye("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,a=i?"Subscriber":"Publisher";if(!s)throw new Ae("".concat(a," connection not set"),J.InternalError);let o=!1;!i&&!n.dataChannelForKind(A,i)&&(n.createDataChannels(),o=!0),!o&&!i&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(o=!0),o&&n.negotiate();const c=n.dataChannelForKind(A,i);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(s.isICEConnected&&((r=n.dataChannelForKind(A,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield Ke(50)}throw new Ae("could not establish ".concat(a," connection, state: ").concat(s.getICEConnectionState()),J.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!==ue.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return C(this,void 0,void 0,function*(){return new Promise((e,A)=>C(this,void 0,void 0,function*(){if(!this.pcManager){A(new aa("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&A("cannot negotiate on closed engine"),this.on(_.Closing,i),this.pcManager.publisher.once(Jt.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(a=>{const o=a.codec.toLowerCase();qw(o)&&s.set(a.payload,o)}),this.emit(_.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof aa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Dt.RR_UNKNOWN),A(r)}finally{this.off(_.Closing,i)}}))})}dataChannelForKind(e,A){if(A){if(e===X.LOSSY)return this.lossyDCSub;if(e===X.RELIABLE)return this.reliableDCSub}else{if(e===X.LOSSY)return this.lossyDC;if(e===X.RELIABLE)return this.reliableDC}}sendSyncState(e,A){var n,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),a=(i=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&i!==void 0?i:!0,o=new Array,c=new Array;e.forEach(l=>{l.isDesired!==a&&o.push(l.trackSid),l.isEnabled||c.push(l.trackSid)}),this.client.sendSyncState(new Qu({answer:r?lr({sdp:r.sdp,type:r.type}):void 0,offer:s?lr({sdp:s.sdp,type:s.type}):void 0,subscription:new Xi({trackSids:o,subscribe:!a,participantTracks:[]}),publishTracks:ib(A),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],A=(n,i)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Eu({label:n.label,id:n.id,target:i}))};return A(this.dataChannelForKind(X.LOSSY),cA.PUBLISHER),A(this.dataChannelForKind(X.RELIABLE),cA.PUBLISHER),A(this.dataChannelForKind(X.LOSSY,!0),cA.SUBSCRIBER),A(this.dataChannelForKind(X.RELIABLE,!0),cA.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Te.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ve()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ve()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Xt extends Error{}function Mb(t){return t!==void 0&&t>13}function Nb(t,e){const A=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=A,e.participantIdentity=A;const n=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=n,e.destinationIdentities=n}class Ka{constructor(e,A){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=A}updateToken(e){this.token=e}isCloud(){return ma(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 A=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(i=>i.url===n.url));if(A.length>0){const n=A[0];return this.attemptedRegions.push(n),W.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return C(this,void 0,void 0,function*(){const A=yield fetch("".concat(Kb(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(A.ok){const n=yield A.json();return this.lastUpdateAt=Date.now(),n}else throw new Ae("Could not fetch region settings: ".concat(A.statusText),A.status===401?J.NotAllowed:J.InternalError,A.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Kb(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class th{get info(){return this._info}constructor(e,A,n){this.reader=A,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class Vb extends th{handleChunkReceived(e){var A;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(A=this.onProgress)===null||A===void 0||A.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>C(this,void 0,void 0,function*(){try{const{done:A,value:n}=yield e.read();return A?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return C(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return C(this,void 0,void 0,function*(){var e,A,n,i;let r=new Set;try{for(var s=!0,a=XA(this),o;o=yield a.next(),e=o.done,!e;s=!0){i=o.value,s=!1;const c=i;r.add(c)}}catch(c){A={error:c}}finally{try{!s&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(A)throw A.error}}return Array.from(r)})}}class Gb extends th{constructor(e,A,n){super(e,A,n),this.receivedChunks=new Map}handleChunkReceived(e){var A;const n=or(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(A=this.onProgress)===null||A===void 0||A.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),A=new TextDecoder;return{next:()=>C(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:A.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return C(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return C(this,void 0,void 0,function*(){var e,A,n,i;let r="";try{for(var s=!0,a=XA(this),o;o=yield a.next(),e=o.done,!e;s=!0)i=o.value,s=!1,r+=i}catch(c){A={error:c}}finally{try{!s&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(A)throw A.error}}return r})}}class nh{constructor(e,A,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=A}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 jb extends nh{}class Wb extends nh{}class ih extends k{constructor(e,A,n,i,r){super(e,n,r),this.sid=A,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?x.Muted:x.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const A=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",A),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(x.Ended,this))};e.addEventListener("removetrack",A)}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(),Da)),rb()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var A;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(A=this.receiver)===null||A===void 0?void 0:A.getSynchronizationSources()[0];if(n){const{timestamp:i,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(x.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Jb extends ih{constructor(e,A,n,i,r,s){super(e,A,k.Kind.Audio,n,s),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=ur(a,this.prevStats)),this.prevStats=a}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var A;for(const n of this.attachedElements)this.audioContext?(A=this.gainNode)===null||A===void 0||A.gain.setTargetAtTime(e,0,.1):n.volume=e;UA()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(UA())return 1;let e=0;return this.attachedElements.forEach(A=>{A.volume>e&&(e=A.volume)}),e}setSinkId(e){return C(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(A=>{if(pa(A))return A.setSinkId(e)}))})}attach(e){const A=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&pa(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&A&&(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 A;return e?(A=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(A=super.detach(),this.disconnectWebAudio()),A}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,A){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(A.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{n.connect(i),n=i}),this.gainNode=e.createGain(),n.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(x.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(x.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,A;(e=this.gainNode)===null||e===void 0||e.disconnect(),(A=this.sourceNode)===null||A===void 0||A.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 A;return e.forEach(n=>{n.type==="inbound-rtp"&&(A={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),A})}}const Va=100;class Xb extends ih{constructor(e,A,n,i,r){super(e,A,k.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=ur(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=_a(()=>{this.updateDimensions()},Va),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(A=>{e?Vt(this._mediaStreamTrack,A):Kt(this._mediaStreamTrack,A)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(A=>A.element===e)===void 0){const A=new qb(e);this.observeElementInfo(A)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(A=>A===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 A=this.elementInfos.filter(n=>n===e);for(const n of A)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let A=[];if(e)return this.stopObservingElement(e),super.detach(e);A=super.detach();for(const n of A)this.stopObservingElement(n);return A}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 A,n="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,A={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&i.set(r.id,r)}),A&&n!==""&&i.get(n)&&(A.mimeType=i.get(n).mimeType),A})}stopObservingElement(e){const A=this.elementInfos.filter(n=>n.element===e);for(const n of A)this.stopObservingElementInfo(n)}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,A;const n=this.elementInfos.reduce((a,o)=>Math.max(a,o.visibilityChangedAt||0),0),i=!((A=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&A!==void 0)||A?this.isInBackground:!1,r=this.elementInfos.some(a=>a.pictureInPicture),s=this.elementInfos.some(a=>a.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-n<Va){Te.setTimeout(()=>{this.updateVisibility()},Va);return}this.lastVisible=s,this.emit(x.VisibilityChanged,s,this)}}updateDimensions(){var e,A;let n=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const a=s.width()*r,o=s.height()*r;a+o>n+i&&(n=a,i=o)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((A=this.lastDimensions)===null||A===void 0?void 0:A.height)===i||(this.lastDimensions={width:n,height:i},this.emit(x.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const A=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return A==="screen"?Qd():A||(Qd()>2?2:1)}}class qb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,A){this.onVisibilityChanged=n=>{var i;const{target:r,isIntersecting:s}=n;r===this.element&&(this.isIntersecting=s,this.isPiP=In(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var n,i,r;(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=In(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=In(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=A??Ga(e),this.isPiP=Ve()&&In(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,A,n;this.isIntersecting=Ga(this.element),this.isPiP=In(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Sd().observe(this.element),Ed().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),(n=(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,A,n,i,r;(e=Sd())===null||e===void 0||e.unobserve(this.element),(A=Ed())===null||A===void 0||A.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function In(t){var e,A;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ga(t,(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window):!1}function Ga(t,e){const A=e||window;let n=t.offsetTop,i=t.offsetLeft;const r=t.offsetWidth,s=t.offsetHeight,{hidden:a}=t,{display:o}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,n+=t.offsetTop,i+=t.offsetLeft;return n<A.pageYOffset+A.innerHeight&&i<A.pageXOffset+A.innerWidth&&n+s>A.pageYOffset&&i+r>A.pageXOffset&&!a&&o!=="none"}class _A extends yA.EventEmitter{constructor(e,A,n,i){var r;super(),this.metadataMuted=!1,this.encryption=qe.NONE,this.log=W,this.handleMuted=()=>{this.emit(x.Muted)},this.handleUnmuted=()=>{this.emit(x.Unmuted)},this.log=FA((r=i==null?void 0:i.loggerName)!==null&&r!==void 0?r:lA.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=A,this.trackName=n,this.source=k.Source.Unknown}setTrack(e){this.track&&(this.track.off(x.Muted,this.handleMuted),this.track.off(x.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(x.Muted,this.handleMuted),e.on(x.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),z(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==qe.NONE}get audioTrack(){if(xA(this.track))return this.track}get videoTrack(){if(Wt(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=k.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===k.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={}))})(_A||(_A={}));class ja extends _A{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,A,n,i){super(e,A.sid,A.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(x.Ended)},this.updateInfo(A),this.setTrack(n)}setTrack(e){this.track&&this.track.off(x.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(x.Ended,this.handleTrackEnded)}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(xA(this.track)){const A=this.track.getSourceTrackSettings(),n=new Set;return A.autoGainControl&&n.add(oA.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&n.add(oA.TF_ECHO_CANCELLATION),A.noiseSuppression&&n.add(oA.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&n.add(oA.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(oA.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(oA.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function gr(t,e){return C(this,void 0,void 0,function*(){t??(t={});let A=!1;const{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:r}=Pd(t);let s=r.audio,a=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),i&&typeof r.video=="object"&&(r.video.processor=i),t.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},A=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},A=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const o=Fd(r,Gd,jd),c=Ea(o),l=navigator.mediaDevices.getUserMedia(c);r.audio&&(Qe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>Qe.userMediaPromiseMap.delete("audioinput"))),r.video&&(Qe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>Qe.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(d=>C(this,void 0,void 0,function*(){const h=d.kind==="audio";let p=h?o.audio:o.video;(typeof p=="boolean"||!p)&&(p={});let f;const m=h?c.audio:c.video;typeof m!="boolean"&&(f=m);const B=d.getSettings().deviceId;f!=null&&f.deviceId&&$A(f.deviceId)!==B?f.deviceId=B:f||(f={deviceId:B});const b=Eb(d,f,e);return b.kind===k.Kind.Video?b.source=k.Source.Camera:b.kind===k.Kind.Audio&&(b.source=k.Source.Microphone),b.mediaStream=u,xA(b)&&n?yield b.setProcessor(n):Wt(b)&&i&&(yield b.setProcessor(i)),b})))}catch(u){if(!A)throw u;return gr(Object.assign(Object.assign({},t),{audio:s,video:a}),e)}})}function Yb(t){return C(this,void 0,void 0,function*(){return(yield gr({audio:!1,video:t??!0}))[0]})}function zb(t){return C(this,void 0,void 0,function*(){return(yield gr({audio:t??!0,video:!1}))[0]})}var tt;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(tt||(tt={}));function Zb(t){switch(t){case yn.EXCELLENT:return tt.Excellent;case yn.GOOD:return tt.Good;case yn.POOR:return tt.Poor;case yn.LOST:return tt.Lost;default:return tt.Unknown}}class rh extends yA.EventEmitter{get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||A===void 0?void 0:A.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===Ji.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ht.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,A,n,i,r,s){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ji.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=tt.Unknown,this.log=W,this.log=FA((o=s==null?void 0:s.loggerName)!==null&&o!==void 0?o:lA.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=A,this.name=n,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,A]of this.trackPublications)if(A.source===e)return A}getTrackPublicationByName(e){for(const[,A]of this.trackPublications)if(A.trackName===e)return A}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new wa,this.once(P.Active,()=>{var e,A;(A=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||A===void 0||A.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const A=this.getTrackPublication(k.Source.Camera);return!(!((e=A==null?void 0:A.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const A=this.getTrackPublication(k.Source.Microphone);return!(!((e=A==null?void 0:A.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(k.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 A;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===Ht.ACTIVE&&((A=this.participantInfo)===null||A===void 0?void 0:A.state)!==Ht.ACTIVE&&this.emit(P.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const A=this.metadata!==e,n=this.metadata;this.metadata=e,A&&this.emit(P.ParticipantMetadataChanged,n)}_setName(e){const A=this.name!==e;this.name=e,A&&this.emit(P.ParticipantNameChanged,e)}_setAttributes(e){const A=sb(this.attributes,e);this._attributes=e,Object.keys(A).length>0&&this.emit(P.AttributesChanged,A)}setPermissions(e){var A,n,i,r,s,a;const o=this.permissions,c=e.canPublish!==((A=this.permissions)===null||A===void 0?void 0:A.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var d;return l!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(P.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(P.IsSpeakingChanged,e))}setConnectionQuality(e){const A=this._connectionQuality;this._connectionQuality=Zb(e),A!==this._connectionQuality&&this.emit(P.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,A;this.activeFuture&&((A=(e=this.activeFuture).reject)===null||A===void 0||A.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(A=>xA(A.track)&&A.track.setAudioContext(e))}addTrackPublication(e){e.on(x.Muted,()=>{this.emit(P.TrackMuted,e)}),e.on(x.Unmuted,()=>{this.emit(P.TrackUnmuted,e)});const A=e;switch(A.track&&(A.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case k.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case k.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function $b(t){var e,A,n;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new yu({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(A=t.participantSid)!==null&&A!==void 0?A:"",allTracks:(n=t.allowAll)!==null&&n!==void 0?n:!1,trackSids:t.allowedTrackSids||[]})}const sh=15e3;class ey extends rh{constructor(e,A,n,i,r){super(e,A,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=qe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new wa)},this.handleReconnected=()=>{var s,a;(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||a===void 0||a.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(o=>this.log.warn(o.message,this.logContext)),(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||a===void 0||a.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:a,reason:o,message:c}=s,l=this.pendingSignalRequests.get(a);l&&(o!==qs.OK&&l.reject(new Bd(c,o)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let a=s.value.value,o=null,c=null;a.value.case==="payload"?o=a.value.value:a.value.case==="error"&&(c=de.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,o,c);break;case"rpcAck":let l=s.value.value;this.handleIncomingRpcAck(l.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(s=>$b(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,a)=>{if(a===void 0&&(a=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),z(s)));return}this.engine.updateMuteStatus(s.sid,a)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),z(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),z(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const a=this.audioTrackPublications.get(s.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>C(this,void 0,void 0,function*(){var a,o,c,l,u,d;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const B=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var p=!0,f=XA(B),m;m=yield f.next(),a=m.done,!a;p=!0){l=m.value,p=!1;const b=l;Hw(b)&&(this.log.debug("publish ".concat(b," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),z(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,b,h.options))}}catch(b){o={error:b}}finally{try{!p&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const a=this.trackPublications.get(s.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=s=>C(this,void 0,void 0,function*(){if(s.source===k.Source.ScreenShare||s.source===k.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),z(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(vt(s)||et(s))try{if(Ve())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:s.source===k.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),z(s))),a.onchange=()=>{a.state!=="denied"&&(s.isMuted||s.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),z(s))),vt(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),z(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==qe.NONE}getTrackPublication(e){const A=super.getTrackPublication(e);if(A)return A}getTrackPublicationByName(e){const A=super.getTrackPublicationByName(e);if(A)return A}setupEngine(e){this.engine=e,this.engine.on(_.RemoteMute,(A,n)=>{const i=this.trackPublications.get(A);!i||!i.track||(n?i.mute():i.unmute())}),this.engine.on(_.Connected,this.handleReconnected).on(_.SignalRestarted,this.handleReconnected).on(_.SignalResumed,this.handleReconnected).on(_.Restarting,this.handleReconnecting).on(_.Resuming,this.handleReconnecting).on(_.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_.Disconnected,this.handleDisconnected).on(_.SignalRequestResponse,this.handleSignalRequestResponse).on(_.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(A){var n=this;let{metadata:i,name:r,attributes:s}=A;return function*(){return new Promise((a,o)=>C(n,void 0,void 0,function*(){var c,l;try{let u=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(l=r??this.name)!==null&&l!==void 0?l:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:a,reject:p=>{o(p),u=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!u;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(p=>{let[f,m]=p;return this.attributes[f]===m||m===""&&!this.attributes[f]}))){this.pendingSignalRequests.delete(d),a();return}yield Ke(50)}o(new Bd("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&o(u)}}))}()})}setCameraEnabled(e,A,n){return this.setTrackEnabled(k.Source.Camera,e,A,n)}setMicrophoneEnabled(e,A,n){return this.setTrackEnabled(k.Source.Microphone,e,A,n)}setScreenShareEnabled(e,A,n){return this.setTrackEnabled(k.Source.ScreenShare,e,A,n)}setPermissions(e){const A=this.permissions,n=super.setPermissions(e);return n&&A&&this.emit(P.ParticipantPermissionsChanged,A),n}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){this.encryptionType=e?qe.GCM:qe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,A,n,i){return C(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:A})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(A)if(a)yield a.unmute();else{let o;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case k.Source.Camera:o=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case k.Source.Microphone:o=yield this.createTracks({audio:(s=n)!==null&&s!==void 0?s:!0});break;case k.Source.ScreenShare:o=yield this.createScreenTracks(Object.assign({},n));break;default:throw new IA(e)}}catch(c){throw o==null||o.forEach(l=>{l.stop()}),c instanceof Error&&this.emit(P.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const u of o)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),z(u))),c.push(this.publishTrack(u,i));[a]=yield Promise.all(c)}catch(c){throw o==null||o.forEach(l=>{l.stop()}),c}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===k.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const o=this.getTrackPublication(k.Source.ScreenShareAudio);o&&o.track&&this.unpublishTrack(o.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return C(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(k.Source.Camera)||this.pendingPublishing.has(k.Source.Microphone))){this.pendingPublishing.add(k.Source.Camera),this.pendingPublishing.add(k.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(A=>this.publishTrack(A)))}finally{this.pendingPublishing.delete(k.Source.Camera),this.pendingPublishing.delete(k.Source.Microphone)}}})}createTracks(e){return C(this,void 0,void 0,function*(){var A,n;e??(e={});const i=Fd(e,(A=this.roomOptions)===null||A===void 0?void 0:A.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield gr(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(xA(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=k.Source.Microphone,this.emit(P.AudioStreamAcquired)),Wt(a)&&(this.cameraError=void 0,a.source=k.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return C(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new sa("getDisplayMedia not supported");e.resolution===void 0&&!Gw()&&(e.resolution=ha.h1080fps30.resolution);const A=nb(e),n=yield navigator.mediaDevices.getDisplayMedia(A),i=n.getVideoTracks();if(i.length===0)throw new IA("no video track found");const r=new fr(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=k.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(P.AudioStreamAcquired);const a=new dr(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=k.Source.ScreenShareAudio,s.push(a)}return s})}publishTrack(e,A){return C(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,A)})}publishOrRepublishTrack(e,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,o,c,l;vt(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!s&&(yield r.republishPromise),jt(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let B;switch(n.source){case k.Source.Microphone:B="audioinput";break;case k.Source.Camera:B="videoinput"}B&&r.activeDeviceMap.has(B)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(B)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new dr(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new fr(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new IA("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let d;if(r.trackPublications.forEach(B=>{B.track&&B.track===n&&(d=B)}),d)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),z(d))),d;const h="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,p=(o=i==null?void 0:i.forceStereo)!==null&&o!==void 0?o:h;p&&(i||(i={}),i.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),z(n))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(l=i.red)!==null&&l!==void 0||(i.red=!1));const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!jw()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(n.source=f.source);const m=new Promise((B,b)=>C(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ne.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:z(n)}));const U=()=>C(this,void 0,void 0,function*(){try{const w=yield this.publish(n,f,p);B(w)}catch(w){b(w)}});setTimeout(()=>{this.engine.off(_.SignalConnected,U),b(new oa("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(_.SignalConnected,U),this.engine.on(_.Closing,()=>{this.engine.off(_.SignalConnected,U),b(new oa("publishing rejected as engine closed",499))})}else try{const U=yield this.publish(n,f,p);B(U)}catch(U){b(U)}}catch(U){b(U)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(B){throw B}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),z(e))),!1;const{canPublish:A,canPublishSources:n}=this.permissions;return A&&(n.length===0||n.map(i=>ab(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),z(e))),!1)}publish(e,A,n){return C(this,void 0,void 0,function*(){var i,r,s,a,o,c,l,u,d,h;if(!this.hasPermissionsToPublish(e))throw new oa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(v=>jt(e)&&v.source===e.source)&&e.source!==k.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),z(e))),A.stopMicTrackOnMute&&xA(e)&&(e.stopOnMute=!0),e.source===k.Source.ScreenShare&&Gt()&&(A.simulcast=!1),A.videoCodec==="av1"&&!Nw()&&(A.videoCodec=void 0),A.videoCodec==="vp9"&&!Kw()&&(A.videoCodec=void 0),A.videoCodec===void 0&&(A.videoCodec=Pa),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(v=>A.videoCodec===cr(v.mime))||(A.videoCodec=cr(this.enabledPublishVideoCodecs[0].mime)));const f=A.videoCodec;e.on(x.Muted,this.onTrackMuted),e.on(x.Unmuted,this.onTrackUnmuted),e.on(x.Ended,this.handleTrackEnded),e.on(x.UpstreamPaused,this.onTrackUpstreamPaused),e.on(x.UpstreamResumed,this.onTrackUpstreamResumed),e.on(x.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new Gs({cid:e.mediaStreamTrack.id,name:A.name,type:k.kindToProto(e.kind),muted:e.isMuted,source:k.sourceToProto(e.source),disableDtx:!(!((i=A.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=A.red)!==null&&r!==void 0)||r),stream:A==null?void 0:A.stream,backupCodecPolicy:A==null?void 0:A.backupCodecPolicy});let B;if(e.kind===k.Kind.Video){let v={width:0,height:0};try{v=yield e.waitForDimensions()}catch{const E=(a=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&a!==void 0?a:Sn.h720.resolution;v={width:E.width,height:E.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),z(e)),{dims:v}))}m.width=v.width,m.height=v.height,et(e)&&(kn(f)&&(e.source===k.Source.ScreenShare&&(A.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),z(e))))),A.scalabilityMode=(o=A.scalabilityMode)!==null&&o!==void 0?o:"L3T3_KEY"),m.simulcastCodecs=[new Vs({codec:f,cid:e.mediaStreamTrack.id})],A.backupCodec===!0&&(A.backupCodec={codec:Pa}),A.backupCodec&&f!==A.backupCodec.codec&&m.encryption===qe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new Vs({codec:A.backupCodec.codec,cid:""})))),B=Oa(e.source===k.Source.ScreenShare,m.width,m.height,A),m.layers=$d(m.width,m.height,B,kn(A.videoCodec))}else e.kind===k.Kind.Audio&&(B=[{maxBitrate:(c=A.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(u=(l=A.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(h=(d=A.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const b=()=>C(this,void 0,void 0,function*(){var v,y,E;if(!this.engine.pcManager)throw new ye("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,A,B),et(e)&&((v=A.degradationPreference)!==null&&v!==void 0||(A.degradationPreference=Lb(e)),e.setDegradationPreference(A.degradationPreference)),B)if(Gt()&&e.kind===k.Kind.Audio){let T;for(const F of this.engine.pcManager.publisher.getTransceivers())if(F.sender===e.sender){T=F;break}T&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:T,codec:"opus",maxbr:!((y=B[0])===null||y===void 0)&&y.maxBitrate?B[0].maxBitrate/1e3:0})}else e.codec&&kn(e.codec)&&(!((E=B[0])===null||E===void 0)&&E.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:B[0].maxBitrate/1e3});yield this.engine.negotiate()});let U;if(this.enabledPublishVideoCodecs.length>0)U=(yield Promise.all([this.engine.addTrack(m),b()]))[0];else{U=yield this.engine.addTrack(m);let v;if(U.codecs.forEach(y=>{v===void 0&&(v=y.mimeType)}),v&&e.kind===k.Kind.Video){const y=cr(v);y!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),z(e)),{codec:y})),A.videoCodec=y,B=Oa(e.source===k.Source.ScreenShare,m.width,m.height,A))}yield b()}const w=new ja(e.kind,U,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return w.options=A,e.sid=U.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:B,trackInfo:U})),et(e)?e.startMonitor(this.engine.client):vt(e)&&e.startMonitor(),this.addTrackPublication(w),this.emit(P.LocalTrackPublished,w),w})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,A,n){return C(this,void 0,void 0,function*(){var i;if(this.encryptionType!==qe.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new IA("track is not published");if(!et(e))throw new IA("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),n),a=_b(e,A,s);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),z(e)));return}const o=e.addSimulcastTrack(A,a);if(!o)return;const c=new Gs({cid:o.mediaStreamTrack.id,type:k.kindToProto(e.kind),muted:e.isMuted,source:k.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=$d(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const l=()=>C(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,s,a),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(A," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))})}unpublishTrack(e,A){return C(this,void 0,void 0,function*(){var n,i;if(jt(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),z(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?z(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(x.Muted,this.onTrackMuted),e.off(x.Unmuted,this.onTrackUnmuted),e.off(x.Ended,this.handleTrackEnded),e.off(x.UpstreamPaused,this.onTrackUpstreamPaused),e.off(x.UpstreamResumed,this.onTrackUpstreamResumed),e.off(x.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),A===void 0&&(A=(i=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),A?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ue.FAILED&&o)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===o&&(c.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),et(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(a=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case k.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case k.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(P.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return C(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,s)=>C(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(o=>{o.track&&(A&&(o.options=Object.assign(Object.assign({},o.options),A)),a.push(o))}),yield Promise.all(a.map(o=>C(this,void 0,void 0,function*(){const c=o.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==k.Source.ScreenShare&&c.source!==k.Source.ScreenShareAudio&&(vt(c)||et(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:o.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,o.options,!0)}))),r()}catch(a){s(a)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return C(this,arguments,void 0,function(A){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?X.RELIABLE:X.LOSSY,s=i.destinationIdentities,a=i.topic,o=new Ne({kind:r,value:{case:"user",value:new nu({participantIdentity:n.identity,payload:A,destinationIdentities:s,topic:a})}});yield n.engine.sendDataPacket(o,r)}()})}publishDtmf(e,A){return C(this,void 0,void 0,function*(){const n=new Ne({kind:X.RELIABLE,value:{case:"sipDtmf",value:new iu({code:e,digit:A})}});yield this.engine.sendDataPacket(n,X.RELIABLE)})}sendChatMessage(e,A){return C(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:A==null?void 0:A.attachments},i=new Ne({value:{case:"chatMessage",value:new Ds(Object.assign(Object.assign({},n),{timestamp:re.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,X.RELIABLE),this.emit(P.ChatMessage,n),n})}editChatMessage(e,A){return C(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},A),{message:e,editTimestamp:Date.now()}),i=new Ne({value:{case:"chatMessage",value:new Ds(Object.assign(Object.assign({},n),{timestamp:re.parse(n.timestamp),editTimestamp:re.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,X.RELIABLE),this.emit(P.ChatMessage,n),n})}sendText(e,A){return C(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,a=(n=A==null?void 0:A.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),o=new Array(a?a.length+1:1).fill(0),c=(u,d)=>{var h;o[d]=u;const p=o.reduce((f,m)=>f+m,0);(h=A==null?void 0:A.onProgress)===null||h===void 0||h.call(A,p)},l=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:A==null?void 0:A.destinationIdentities,topic:A==null?void 0:A.topic,attachedStreamIds:a,attributes:A==null?void 0:A.attributes});return yield l.write(e),c(1,0),yield l.close(),A!=null&&A.attachments&&a&&(yield Promise.all(A.attachments.map((u,d)=>C(this,void 0,void 0,function*(){return this._sendFile(a[d],u,{topic:A.topic,mimeType:u.type,onProgress:h=>{c(h,d+1)}})})))),l.info})}streamText(e){return C(this,void 0,void 0,function*(){var A,n;const i=(A=e==null?void 0:e.streamId)!==null&&A!==void 0?A:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new Os({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:Bt(r.timestamp),totalLength:Bt(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new gu({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"?Hs.UPDATE:Hs.CREATE})}}),a=e==null?void 0:e.destinationIdentities,o=new Ne({destinationIdentities:a,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(o,X.RELIABLE);let c=0;const l=this,u=new WritableStream({write(p){return C(this,void 0,void 0,function*(){for(const f of Ab(p,sh)){yield l.engine.waitForBufferStatusLow(X.RELIABLE);const m=new Ms({content:f,streamId:i,chunkIndex:Bt(c)}),B=new Ne({destinationIdentities:a,value:{case:"streamChunk",value:m}});yield l.engine.sendDataPacket(B,X.RELIABLE),c+=1}})},close(){return C(this,void 0,void 0,function*(){const p=new Ns({streamId:i}),f=new Ne({destinationIdentities:a,value:{case:"streamTrailer",value:p}});yield l.engine.sendDataPacket(f,X.RELIABLE)})},abort(p){console.log("Sink error:",p)}});let d=()=>C(this,void 0,void 0,function*(){yield h.close()});l.engine.once(_.Closing,d);const h=new jb(u,r,()=>this.engine.off(_.Closing,d));return h})}sendFile(e,A){return C(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,A),{id:n}})}_sendFile(e,A,n){return C(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:A.size,name:A.name,mimeType:(i=n==null?void 0:n.mimeType)!==null&&i!==void 0?i:A.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),s=A.stream().getReader();for(;;){const{done:a,value:o}=yield s.read();if(a)break;yield r.write(o)}return yield r.close(),r.info})}streamBytes(e){return C(this,void 0,void 0,function*(){var A,n,i,r,s;const a=(A=e==null?void 0:e.streamId)!==null&&A!==void 0?A:crypto.randomUUID(),o=e==null?void 0:e.destinationIdentities,c={id:a,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown"},l=new Os({totalLength:Bt((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:Bt(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new pu({name:c.name})}}),u=new Ne({destinationIdentities:o,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,X.RELIABLE);let d=0;const h=new Oe,p=this.engine,f=this.log,m=new WritableStream({write(b){return C(this,void 0,void 0,function*(){const U=yield h.lock();let w=0;try{for(;w<b.byteLength;){const v=b.slice(w,w+sh);yield p.waitForBufferStatusLow(X.RELIABLE);const y=new Ne({destinationIdentities:o,value:{case:"streamChunk",value:new Ms({content:v,streamId:a,chunkIndex:Bt(d)})}});yield p.sendDataPacket(y,X.RELIABLE),d+=1,w+=v.byteLength}}finally{U()}})},close(){return C(this,void 0,void 0,function*(){const b=new Ns({streamId:a}),U=new Ne({destinationIdentities:o,value:{case:"streamTrailer",value:b}});yield p.sendDataPacket(U,X.RELIABLE)})},abort(b){f.error("Sink error:",b)}});return new Wb(m,c)})}performRpc(e){return C(this,arguments,void 0,function(A){var n=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:a=1e4}=A;return function*(){return new Promise((c,l)=>C(n,void 0,void 0,function*(){var u,d,h,p;if(La(s)>Wd){l(de.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||d===void 0)&&d.version&&mt((p=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||p===void 0?void 0:p.version,"1.8.0")<0){l(de.builtIn("UNSUPPORTED_SERVER"));return}const f=crypto.randomUUID();yield this.publishRpcRequest(i,f,r,s,a-2e3);const m=setTimeout(()=>{this.pendingAcks.delete(f),l(de.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(f),clearTimeout(B)},2e3);this.pendingAcks.set(f,{resolve:()=>{clearTimeout(m)},participantIdentity:i});const B=setTimeout(()=>{this.pendingResponses.delete(f),l(de.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(f,{resolve:(b,U)=>{clearTimeout(B),this.pendingAcks.has(f)&&(console.warn("RPC response received before ack",f),this.pendingAcks.delete(f),clearTimeout(m)),U?l(U):c(b??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,A){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,A)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=A,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const A=this.pendingAcks.get(e);A?(A.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,A,n){const i=this.pendingResponses.get(e);i?(i.resolve(A,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,A,n,i,r){return C(this,void 0,void 0,function*(){const s=new Ne({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcRequest",value:new ru({id:A,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,X.RELIABLE)})}handleParticipantDisconnected(e){for(const[A,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(A);for(const[A,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,de.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(A))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(A=>A.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(A=>{var n,i;const r=this.trackPublications.get(A.sid);if(r){const s=r.isMuted||((i=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==A.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),z(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(A.sid,s))}}),!0):!1}getPublicationForTrack(e){let A;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(vt(i)||et(i))&&i.mediaStreamTrack===e&&(A=n):e===i&&(A=n))}),A}waitForPendingPublicationOfSource(e){return C(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield Ke(20)}})}}class Ay extends _A{constructor(e,A,n,i){super(e,A.sid,A.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=AA.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(x.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(A)}setSubscribed(e){const A=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Xi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new cu({participantSid:"",trackSids:[this.trackSid]})]});this.emit(x.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(A),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?_A.SubscriptionStatus.Unsubscribed:super.isSubscribed?_A.SubscriptionStatus.Subscribed:_A.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?_A.PermissionStatus.Allowed:_A.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var A,n;this.isManualOperationAllowed()&&(((A=this.videoDimensions)===null||A===void 0?void 0:A.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Ua(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Ua(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const A=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(x.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(x.VisibilityChanged,this.handleVisibilityChange),i.off(x.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(x.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(x.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(x.VisibilityChanged,this.handleVisibilityChange),e.on(x.Ended,this.handleEnded),this.emit(x.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(A))}setAllowed(e){const A=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(A)}setSubscriptionError(e){this.emit(x.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const A=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):A!==e.muted&&this.emit(e.muted?x.Muted:x.Unmuted)}emitSubscriptionUpdateIfChanged(e){const A=this.subscriptionStatus;e!==A&&this.emit(x.SubscriptionStatusChanged,A,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(x.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===k.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Ua(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Bu({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=AA.HIGH,this.emit(x.UpdateSettings,e)}}class pr extends rh{static fromParticipantInfo(e,A,n){return new pr(e,A.sid,A.identity,A.name,A.metadata,A.attributes,n,A.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,A,n,i,r,s,a){let o=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ji.STANDARD;super(A,n||"",i,r,s,a,o),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(x.UpdateSettings,A=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),z(e))),this.signalClient.sendUpdateTrackSettings(A)}),e.on(x.UpdateSubscription,A=>{A.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(A)}),e.on(x.SubscriptionPermissionChanged,A=>{this.emit(P.TrackSubscriptionPermissionChanged,e,A)}),e.on(x.SubscriptionStatusChanged,A=>{this.emit(P.TrackSubscriptionStatusChanged,e,A)}),e.on(x.Subscribed,A=>{this.emit(P.TrackSubscribed,A,e)}),e.on(x.Unsubscribed,A=>{this.emit(P.TrackUnsubscribed,A,e)}),e.on(x.SubscriptionFailed,A=>{this.emit(P.TrackSubscriptionFailed,e.trackSid,A)})}getTrackPublication(e){const A=super.getTrackPublication(e);if(A)return A}getTrackPublicationByName(e){const A=super.getTrackPublicationByName(e);if(A)return A}setVolume(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:k.Source.Microphone;this.volumeMap.set(A,e);const n=this.getTrackPublication(A);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:k.Source.Microphone;const A=this.getTrackPublication(e);return A&&A.track?A.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,A,n,i,r,s){let a=this.getTrackPublicationBySid(A);if(a||A.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:A})),this.emit(P.TrackSubscriptionFailed,A);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,A,n,i,r,s-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),z(a))),this.emit(P.TrackSubscriptionFailed,A);return}const o=e.kind==="video";let c;return o?c=new Xb(e,A,i,r):c=new Jb(e,A,i,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(n),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&ya(c)&&xA(c)&&c.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 A=new Map,n=new Map;return e.tracks.forEach(i=>{var r,s;let a=this.getTrackPublicationBySid(i.sid);if(a)a.updateInfo(i);else{const o=k.kindFromProto(i.type);if(!o)return;a=new Ay(o,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),a.updateInfo(i),n.set(i.sid,a);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));c&&a.source!==k.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:z(c),newTrack:z(a)})),this.addTrackPublication(a)}A.set(i.sid,a)}),this.trackPublications.forEach(i=>{A.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),z(i))),this.unpublishTrack(i.trackSid,!0))}),n.forEach(i=>{this.emit(P.TrackPublished,i)}),!0}unpublishTrack(e,A){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case k.Kind.Audio:this.audioTrackPublications.delete(e);break;case k.Kind.Video:this.videoTrackPublications.delete(e);break}A&&this.emit(P.TrackUnpublished,n)}setAudioOutput(e){return C(this,void 0,void 0,function*(){this.audioOutput=e;const A=[];this.audioTrackPublications.forEach(n=>{var i;xA(n.track)&&ya(n.track)&&A.push(n.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(A)})}emit(e){for(var A=arguments.length,n=new Array(A>1?A-1:0),i=1;i<A;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var q;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(q||(q={}));const ty=4*1e3;class qt extends yA.EventEmitter{constructor(e){var A,n,i,r;if(super(),A=this,this.state=q.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=W,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,a,o)=>C(this,void 0,void 0,function*(){var c;if(!Vw())throw UA()?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 l=yield this.disconnectLock.lock();if(this.state===q.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(q.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ma(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ka(s,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(h=>{var p;(p=this.regionUrlProvider)===null||p===void 0||p.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const u=(h,p,f)=>C(this,void 0,void 0,function*(){var m,B;this.abortController&&this.abortController.abort();const b=new AbortController;this.abortController=b,l==null||l();try{yield this.attemptConnection(f??s,a,o,b),this.abortController=void 0,h()}catch(U){if(this.regionUrlProvider&&U instanceof Ae&&U.reason!==J.Cancelled&&U.reason!==J.NotAllowed){let w=null;try{w=yield this.regionUrlProvider.getNextBestRegionUrl((m=this.abortController)===null||m===void 0?void 0:m.signal)}catch(v){if(v instanceof Ae&&(v.status===401||v.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(v);return}}w&&!(!((B=this.abortController)===null||B===void 0)&&B.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(U.message,". Retrying with another region: ").concat(w),this.logContext),this.recreateEngine(),yield u(h,p,w)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Td(U)),p(U))}else{let w=aA.UNKNOWN_REASON;U instanceof Ae&&(w=Td(U)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,w),p(U)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new wa((h,p)=>{u(h,p,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,a,o,c,l,u)=>C(this,void 0,void 0,function*(){var d,h,p;const f=yield o.join(s,a,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},u.signal);let m=f.serverInfo;if(m||(m={version:f.serverVersion,region:f.serverRegion}),this.serverInfo=m,this.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(B=>{let[b,U]=B;return"".concat(b,": ").concat(U)}).join(", ")),{room:(d=f.room)===null||d===void 0?void 0:d.name,roomSid:(h=f.room)===null||h===void 0?void 0:h.sid,identity:(p=f.participant)===null||p===void 0?void 0:p.identity}),!m.version)throw new kw("unknown server version");return m.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),f}),this.applyJoinResponse=s=>{const a=s.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(o){this.log.error(o instanceof Error?o.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:o}))}this.handleParticipantUpdates([a,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,a,o,c)=>C(this,void 0,void 0,function*(){var l,u;this.state===q.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.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({},Ra),o),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,a,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(I.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Ae("could not establish signal connection",J.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Ae&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ae("Connection attempt aborted",J.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Ve()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ve()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(q.Connected),this.emit(I.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];return C(A,[...a],void 0,function(){var c=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,d,h,p;const f=yield c.disconnectLock.lock();try{if(c.state===q.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===q.Connecting||c.state===q.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(u=c.abortController)===null||u===void 0||u.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Ae("Client initiated disconnect",J.Cancelled)),c.connectFuture=void 0),!((p=c.engine)===null||p===void 0)&&p.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(l,aA.CLIENT_INITIATED),c.engine=void 0}finally{f()}}()})},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 s=[],a=uA();if(a&&a.os==="iOS"){const o="livekit-dummy-audio-el";let c=document.getElementById(o);if(!c){c=document.createElement("audio"),c.id=o,c.autoplay=!0,c.hidden=!0;const l=Ca();l.enabled=!0;const u=new MediaStream([l]);c.srcObject=u,document.addEventListener("visibilitychange",()=>{c&&(c.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(c),this.once(I.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(o=>{o.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(l=>{s.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(o=>(o.muted=!1,o.play()))]),this.handleAudioPlaybackStarted()}catch(o){throw this.handleAudioPlaybackFailed(o),o}}),this.startVideo=()=>C(this,void 0,void 0,function*(){const s=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(o=>{var c;(c=o.track)===null||c===void 0||c.attachedElements.forEach(l=>{s.includes(l)||s.push(l)})});yield Promise.all(s.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 s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(q.Reconnecting)&&this.emit(I.Reconnecting)},this.handleSignalRestarted=s=>C(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);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:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(q.Connected),this.emit(I.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(a=>{var o;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(o=this.sidToIdentity.get(a.sid))!==null&&o!==void 0?o:"");let c=this.remoteParticipants.get(a.identity);a.state===Ht.DISCONNECTED?this.handleParticipantDisconnected(a.identity,c):c=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=s=>{const a=[],o={};s.forEach(c=>{if(o[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(c.sid);l&&(l.audioLevel=c.level,l.setIsSpeaking(!0),a.push(l))}}),o[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{o[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(I.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=s=>{const a=new Map;this.activeSpeakers.forEach(c=>{const l=this.remoteParticipants.get(c.identity);l&&l.sid!==c.sid||a.set(c.sid,c)}),s.forEach(c=>{let l=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=c.level,l.setIsSpeaking(c.active),c.active?a.set(c.sid,l):a.delete(c.sid))});const o=Array.from(a.values());o.sort((c,l)=>l.audioLevel-c.audioLevel),this.activeSpeakers=o,this.emitWhenConnected(I.ActiveSpeakersChanged,o)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);if(!c||!c.track)return;const l=k.streamStateFromProto(a.state);l!==c.track.streamState&&(c.track.streamState=l,o.emit(P.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(I.TrackStreamStateChanged,c,c.track.streamState,o))})},this.handleSubscriptionPermissionUpdate=s=>{const a=this.getRemoteParticipantBySid(s.participantSid);if(!a)return;const o=a.getTrackPublicationBySid(s.trackSid);o&&o.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const a=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!a)return;const o=a.getTrackPublicationBySid(s.trackSid);o&&o.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const a=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(a,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(a,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(a,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(a,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,a);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const o=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,o.id,o.method,o.payload,o.responseTimeoutMs,o.version)}},this.handleUserPacket=(s,a,o)=>{this.emit(I.DataReceived,a.payload,s,o,a.topic),s==null||s.emit(P.DataReceived,a.payload,o)},this.handleSipDtmf=(s,a)=>{this.emit(I.SipDTMFReceived,a,s),s==null||s.emit(P.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(s,a)=>{const o=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),c=o==null?void 0:o.trackPublications.get(a.trackId),l=zw(a,this.transcriptionReceivedTimes);c==null||c.emit(x.TranscriptionReceived,l),o==null||o.emit(P.TranscriptionReceived,l,c),this.emit(I.TranscriptionReceived,l,o,c)},this.handleChatMessage=(s,a)=>{const o=Zw(a);this.emit(I.ChatMessage,o,s)},this.handleMetrics=(s,a)=>{this.emit(I.MetricsReceived,s,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(I.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(I.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(I.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(I.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>C(this,void 0,void 0,function*(){var s,a,o;const c=Qe.getInstance().previousDevices,l=yield Qe.getInstance().getDevices(void 0,!1),u=uA();if((u==null?void 0:u.name)==="Chrome"&&u.os!=="iOS")for(let h of l){const p=c.find(f=>f.deviceId===h.deviceId);p&&p.label!==""&&p.kind===h.kind&&p.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(I.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const p=tb(h),f=this.localParticipant.getTrackPublication(p);if(f&&(!((s=f.track)===null||s===void 0)&&s.isUserProvided))continue;const m=l.filter(b=>b.kind===h),B=this.getActiveDevice(h);if(B===((a=c.filter(b=>b.kind===h)[0])===null||a===void 0?void 0:a.deviceId)&&m.length>0&&((o=m[0])===null||o===void 0?void 0:o.deviceId)!==B){yield this.switchActiveDevice(h,m[0].deviceId);continue}h==="audioinput"&&!ZA()||h==="videoinput"||m.length>0&&!m.find(b=>b.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,m[0].deviceId))}this.emit(I.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const a=this.roomInfo;this.roomInfo=s,a&&a.metadata!==s.metadata&&this.emitWhenConnected(I.RoomMetadataChanged,s.metadata),(a==null?void 0:a.activeRecording)!==s.activeRecording&&this.emitWhenConnected(I.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const o=this.getRemoteParticipantBySid(a.participantSid);o&&o.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(I.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(I.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(I.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(I.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(I.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var a;(a=s==null?void 0:s.onPublish)===null||a===void 0||a.call(s,this)},this.onLocalTrackPublished=s=>C(this,void 0,void 0,function*(){var a,o,c,l,u,d;(a=s.track)===null||a===void 0||a.on(x.TrackProcessorUpdate,this.onTrackProcessorUpdate),(o=s.track)===null||o===void 0||o.on(x.Restarted,this.onLocalTrackRestarted),(u=(l=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(I.LocalTrackPublished,s,this.localParticipant),vt(s.track)&&(yield s.track.checkForSilence())&&this.emit(I.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),p=_d(s.source);p&&h&&h!==this.localParticipant.activeDeviceMap.get(p)&&(this.localParticipant.activeDeviceMap.set(p,h),this.emit(I.ActiveDeviceChanged,p,h))}),this.onLocalTrackUnpublished=s=>{var a,o;(a=s.track)===null||a===void 0||a.off(x.TrackProcessorUpdate,this.onTrackProcessorUpdate),(o=s.track)===null||o===void 0||o.off(x.Restarted,this.onLocalTrackRestarted),this.emit(I.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>C(this,void 0,void 0,function*(){const a=yield s.getDeviceId(!1),o=_d(s.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.log.debug("local track restarted, setting ".concat(o," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(o,a),this.emit(I.ActiveDeviceChanged,o,a))}),this.onLocalConnectionQualityChanged=s=>{this.emit(I.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(I.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(I.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(I.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},yb),e),this.log=FA((n=this.options.loggerName)!==null&&n!==void 0?n:lA.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Gd),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},jd),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},bb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Oe,this.localParticipant=new ey("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",$A(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",$A(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",$A(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ve()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),qt.cleanupRegistry&&qt.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,A){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,A)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,A){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,A)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,A){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,A)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,A,n,i,r,s){return C(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,A),s!==1){yield this.engine.publishRpcResponse(e,A,null,de.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,A,null,de.builtIn("UNSUPPORTED_METHOD"));return}let o=null,c=null;try{const l=yield a({requestId:A,callerIdentity:e,payload:i,responseTimeout:r});La(l)>Wd?(o=de.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=l}catch(l){l instanceof de?o=l:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),l),o=de.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,A,c,o)})}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 ob(this.options.e2ee),this.e2eeManager.on(YA.ParticipantEncryptionStatusChanged,(A,n)=>{eb(n)&&(this.isE2EEEnabled=A),this.emit(I.ParticipantEncryptionStatusChanged,A,n)}),this.e2eeManager.on(YA.EncryptionError,A=>this.emit(I.EncryptionError,A)),(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,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&A!==void 0?A:!1}getSid(){return C(this,void 0,void 0,function*(){return this.state===q.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,A)=>{const n=i=>{i.sid!==""&&(this.engine.off(_.RoomUpdate,n),e(i.sid))};this.engine.on(_.RoomUpdate,n),this.once(I.Disconnected,()=>{this.engine.off(_.RoomUpdate,n),A("Room disconnected before room server id was available")})})})}get name(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&A!==void 0?A:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&A!==void 0?A:0}get numPublishers(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&A!==void 0?A:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ob(this.options),this.engine.on(_.ParticipantUpdate,this.handleParticipantUpdates).on(_.RoomUpdate,this.handleRoomUpdate).on(_.SpeakersChanged,this.handleSpeakersChanged).on(_.StreamStateChanged,this.handleStreamStateUpdate).on(_.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_.SubscriptionError,this.handleSubscriptionError).on(_.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_.MediaTrackAdded,(e,A,n)=>{this.onTrackAdded(e,A,n)}).on(_.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(_.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_.DataPacketReceived,this.handleDataPacket).on(_.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(q.SignalReconnecting)&&this.emit(I.SignalReconnecting)}).on(_.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(q.Connected)&&this.emit(I.Reconnected)}).on(_.SignalResumed,()=>{this.bufferedEvents=[],(this.state===q.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_.Restarting,this.handleRestarting).on(_.SignalRestarted,this.handleSignalRestarted).on(_.Offline,()=>{this.setAndEmitConnectionState(q.Reconnecting)&&this.emit(I.Reconnecting)}).on(_.DCBufferStatusChanged,(e,A)=>{this.emit(I.DCBufferStatusChanged,e,A)}).on(_.LocalTrackSubscribed,e=>{const A=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:i}=n;return i===e});if(!A){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(P.LocalTrackSubscribed,A),this.emitWhenConnected(I.LocalTrackSubscribed,A,this.localParticipant)}).on(_.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((A,n)=>{this.handleParticipantDisconnected(n,A)}),this.emit(I.Moved,e.room.name,e.token),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))}static getLocalDevices(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Qe.getInstance().getDevices(e,A)}prepareConnection(e,A){return C(this,void 0,void 0,function*(){if(this.state===q.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ma(new URL(e))&&A){this.regionUrlProvider=new Ka(e,A);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===q.Disconnected&&(this.regionUrl=n,yield fetch(ba(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(ba(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,A){return C(this,void 0,void 0,function*(){let n=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new bA({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new bA({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new bA({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new bA({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":n=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new bA({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new bA({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":i=new bA({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>C(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new qi({reason:aA.CLIENT_INITIATED,action:Mt.RECONNECT}))});break;case"subscriber-bandwidth":if(A===void 0||typeof A!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new bA({scenario:{case:"subscriberBandwidth",value:Bt(A)}});break;case"leave-full-reconnect":i=new bA({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,A){return C(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var a,o,c,l,u,d,h,p;let f=!0,m=!1;const B=s?{exact:i}:i;if(n==="audioinput"){m=r.localParticipant.audioTrackPublications.size===0;const b=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=B;const U=Array.from(r.localParticipant.audioTrackPublications.values()).filter(w=>w.source===k.Source.Microphone);try{f=(yield Promise.all(U.map(w=>{var v;return(v=w.audioTrack)===null||v===void 0?void 0:v.setDeviceId(B)}))).every(w=>w===!0)}catch(w){throw r.options.audioCaptureDefaults.deviceId=b,w}}else if(n==="videoinput"){m=r.localParticipant.videoTrackPublications.size===0;const b=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=B;const U=Array.from(r.localParticipant.videoTrackPublications.values()).filter(w=>w.source===k.Source.Camera);try{f=(yield Promise.all(U.map(w=>{var v;return(v=w.videoTrack)===null||v===void 0?void 0:v.setDeviceId(B)}))).every(w=>w===!0)}catch(w){throw r.options.videoCaptureDefaults.deviceId=b,w}}else if(n==="audiooutput"){if(!pa()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield Qe.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(l=(p=r.options).audioOutput)!==null&&l!==void 0||(p.audioOutput={});const b=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((d=r.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(U=>U.setAudioOutput({deviceId:i})))}catch(U){throw r.options.audioOutput.deviceId=b,U}}return(m||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(I.ActiveDeviceChanged,n,i)),f}()})}setupLocalParticipantEvents(){this.localParticipant.on(P.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(P.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(P.AttributesChanged,this.onLocalAttributesChanged).on(P.TrackMuted,this.onLocalTrackMuted).on(P.TrackUnmuted,this.onLocalTrackUnmuted).on(P.LocalTrackPublished,this.onLocalTrackPublished).on(P.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(P.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(P.MediaDevicesError,this.onMediaDevicesError).on(P.AudioStreamAcquired,this.startAudio).on(P.ChatMessage,this.onLocalChatMessageSent).on(P.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,A,n){if(this.state===q.Connecting||this.state===q.Reconnecting){const l=()=>{this.onTrackAdded(e,A,n),u()},u=()=>{this.off(I.Reconnected,l),this.off(I.Connected,l),this.off(I.Disconnected,u)};this.once(I.Reconnected,l),this.once(I.Connected,l),this.once(I.Disconnected,u);return}if(this.state===q.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 i=Mw(A.id),r=i[0];let s=i[1],a=e.id;if(s&&s.startsWith("TR")&&(a=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const o=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!o){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),o.addSubscribedMediaTrack(e,a,A,n,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,A=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==q.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,a;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(a=i.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(P.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(P.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(P.AttributesChanged,this.onLocalAttributesChanged).off(P.TrackMuted,this.onLocalTrackMuted).off(P.TrackUnmuted,this.onLocalTrackUnmuted).off(P.LocalTrackPublished,this.onLocalTrackPublished).off(P.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(P.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(P.MediaDevicesError,this.onMediaDevicesError).off(P.AudioStreamAcquired,this.startAudio).off(P.ChatMessage,this.onLocalChatMessageSent).off(P.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),Ve()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(q.Disconnected),this.emit(I.Disconnected,A)}}}handleParticipantDisconnected(e,A){var n;this.remoteParticipants.delete(e),A&&(A.trackPublications.forEach(i=>{A.unpublishTrack(i.trackSid,!0)}),this.emit(I.ParticipantDisconnected,A),A.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(A.identity))}handleStreamHeader(e,A){return C(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:or(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:o=>{r=o,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Vb(s,a,or(e.totalLength)),{identity:A})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:o=>{r=o,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Gb(s,a,or(e.totalLength)),{identity:A})}})}handleStreamChunk(e){const A=this.byteStreamControllers.get(e.streamId);A&&e.content.length>0&&A.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const A=this.textStreamControllers.get(e.streamId);A&&(A.info.attributes=Object.assign(Object.assign({},A.info.attributes),e.attributes),A.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return C(this,void 0,void 0,function*(){var e,A;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=xd())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ke(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const n=((A=this.audioContext)===null||A===void 0?void 0:A.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(I.AudioPlaybackStatusChanged,n))})}createParticipant(e,A){var n;let i;return A?i=pr.fromParticipantInfo(this.engine.client,A,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new pr(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,A){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return A&&i.updateInfo(A)&&this.sidToIdentity.set(A.sid,A.identity),i}const n=this.createParticipant(e,A);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(A.sid,A.identity),this.emitWhenConnected(I.ParticipantConnected,n),n.on(P.TrackPublished,i=>{this.emitWhenConnected(I.TrackPublished,i,n)}).on(P.TrackSubscribed,(i,r)=>{i.kind===k.Kind.Audio?(i.on(x.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(x.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===k.Kind.Video&&(i.on(x.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(x.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(I.TrackSubscribed,i,r,n)}).on(P.TrackUnpublished,i=>{this.emit(I.TrackUnpublished,i,n)}).on(P.TrackUnsubscribed,(i,r)=>{this.emit(I.TrackUnsubscribed,i,r,n)}).on(P.TrackMuted,i=>{this.emitWhenConnected(I.TrackMuted,i,n)}).on(P.TrackUnmuted,i=>{this.emitWhenConnected(I.TrackUnmuted,i,n)}).on(P.ParticipantMetadataChanged,i=>{this.emitWhenConnected(I.ParticipantMetadataChanged,i,n)}).on(P.ParticipantNameChanged,i=>{this.emitWhenConnected(I.ParticipantNameChanged,i,n)}).on(P.AttributesChanged,i=>{this.emitWhenConnected(I.ParticipantAttributesChanged,i,n)}).on(P.ConnectionQualityChanged,i=>{this.emitWhenConnected(I.ConnectionQualityChanged,i,n)}).on(P.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(I.ParticipantPermissionsChanged,i,n)}).on(P.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(I.TrackSubscriptionStatusChanged,i,r,n)}).on(P.TrackSubscriptionFailed,(i,r)=>{this.emit(I.TrackSubscriptionFailed,i,n,r)}).on(P.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(I.TrackSubscriptionPermissionChanged,i,r,n)}).on(P.Active,()=>{this.emitWhenConnected(I.ParticipantActive,n)}),A&&n.updateInfo(A),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,i)=>(n.push(...i.getTrackPublications()),n),[]),A=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,A)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const A of e.videoTrackPublications.values())A.isSubscribed&&$w(A)&&A.emitTrackUpdate()}getRemoteParticipantBySid(e){const A=this.sidToIdentity.get(e);if(A)return this.remoteParticipants.get(A)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Te.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,aA.STATE_MISMATCH))):e=0},ty)}clearConnectionReconcile(){this.connectionReconcileInterval&&Te.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(I.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[A,n]=e;this.emit(A,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var A=arguments.length,n=new Array(A>1?A-1:0),i=1;i<A;i++)n[i-1]=arguments[i];if(this.state===q.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===q.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return C(this,void 0,void 0,function*(){var A,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ji({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:re.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ht({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(I.SignalConnected),this.emit(I.Connected),this.setAndEmitConnectionState(q.Connected),i.video){const s=new ja(k.Kind.Video,new Ot({source:Be.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO,name:"video-dummy"}),new fr(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:kd(160*((A=r.aspectRatios[0])!==null&&A!==void 0?A:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(P.LocalTrackPublished,s)}if(i.audio){const s=new ja(k.Kind.Audio,new Ot({source:Be.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO}),new dr(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ca(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(P.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let a=new ht({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ht.ACTIVE,tracks:[],joinedAt:re.parse(Date.now())});const o=this.getOrCreateParticipant(a.identity,a);if(r.video){const c=kd(160*((n=r.aspectRatios[s%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new Ot({source:Be.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO});o.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}if(r.audio){const c=Ca(),l=new Ot({source:Be.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sA.AUDIO});o.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}o.updateInfo(a)}})}emit(e){for(var A=arguments.length,n=new Array(A>1?A-1:0),i=1;i<A;i++)n[i-1]=arguments[i];if(e!==I.ActiveSpeakersChanged&&e!==I.TranscriptionReceived){const r=ah(n).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}qt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ah(t){return t.map(e=>{if(e)return Array.isArray(e)?ah(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var fA;(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"})(fA||(fA={}));class nt extends yA.EventEmitter{constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=fA.IDLE,this.logs=[],this.options={},this.url=e,this.token=A,this.name=this.constructor.name,this.room=new qt(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return C(this,void 0,void 0,function*(){if(this.status!==fA.IDLE)throw Error("check is running already");this.setStatus(fA.RUNNING);try{yield this.perform()}catch(A){A instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(A.message):this.appendError(A.message))}return yield this.disconnect(),yield new Promise(A=>setTimeout(A,500)),this.status!==fA.SKIPPED&&this.setStatus(this.isSuccess()?fA.SUCCESS:fA.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===q.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!==q.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(fA.SKIPPED)}switchProtocol(e){return C(this,void 0,void 0,function*(){let A=!1,n=!1;if(this.room.on(I.Reconnecting,()=>{A=!0}),this.room.once(I.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!A)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(n)return;yield Ke(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 ny extends nt{get description(){return"Cloud regions"}perform(){return C(this,void 0,void 0,function*(){const e=new Ka(this.url,this.token);if(!e.isCloud()){this.skip();return}const A=[],n=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(n.has(s))continue;n.add(s);const a=yield this.checkCloudRegion(s);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),A.push(a)}A.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=A[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return C(this,void 0,void 0,function*(){var A,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(A=this.room.serverInfo)===null||A===void 0?void 0:A.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,o=1e6/s,c="A".repeat(s),l=Date.now();for(let p=0;p<o;p++)yield r.write(c);yield r.close();const u=Date.now(),d=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:i,rtt:1e4,duration:u-l};return d==null||d.forEach(p=>{p.type==="candidate-pair"&&p.nominated&&(h.rtt=p.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const Wa=1e4;class iy extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return C(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),A=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-A.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-A.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=A):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Wa/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Wa/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 A=document.createElement("canvas");A.width=1280,A.height=720;const n=A.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,A.width,A.height),requestAnimationFrame(r)};r();const a=A.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={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 d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,Wa)),clearInterval(u),a.stop(),A.remove(),yield this.disconnect(),l})}}class ry extends nt{get description(){return"Can publish audio"}perform(){return C(this,void 0,void 0,function*(){var e;const A=yield this.connect(),n=yield zb();if(yield Id(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),A.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(s=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class sy extends nt{get description(){return"Can publish video"}perform(){return C(this,void 0,void 0,function*(){var e;const A=yield this.connect(),n=yield Yb();yield this.checkForVideo(n.mediaStreamTrack),A.localParticipant.publishTrack(n),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return C(this,void 0,void 0,function*(){const A=new MediaStream;A.addTrack(e.clone());const n=document.createElement("video");n.srcObject=A,n.muted=!0,yield new Promise(i=>{n.onplay=()=>{setTimeout(()=>{var r,s,a,o;const c=document.createElement("canvas"),l=e.getSettings(),u=(s=(r=l.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&s!==void 0?s:1280,d=(o=(a=l.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&o!==void 0?o:720;c.width=u,c.height=d;const h=c.getContext("2d");h.drawImage(n,0,0);const f=h.getImageData(0,0,c.width,c.height).data;let m=!0;for(let B=0;B<f.length;B+=4)if(f[B]!==0||f[B+1]!==0||f[B+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},n.play()}),n.remove()})}}class ay extends nt{get description(){return"Resuming connection after interruption"}perform(){return C(this,void 0,void 0,function*(){var e;const A=yield this.connect();let n=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),a=()=>{n=!0};A.on(I.SignalReconnecting,a).on(I.Reconnecting,a).on(I.Reconnected,()=>{i=!0,r(!0)}),(e=A.engine.client.ws)===null||e===void 0||e.close();const o=A.engine.client.onClose;if(o&&o(""),yield s,n){if(!i||A.state!==q.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 oy extends nt{get description(){return"Can connect via TURN"}perform(){return C(this,void 0,void 0,function*(){var e,A;const n=new ka,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,a=!1;for(let o of i.iceServers)for(let c of o.urls)c.startsWith("turn:")?(s=!0,a=!0):c.startsWith("turns:")&&(s=!0,a=!0,r=!0),c.startsWith("stun:")&&(a=!0);a?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((A=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||A===void 0)&&A.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(o=>setTimeout(o,0)))})}}class cy extends nt{get description(){return"Establishing WebRTC connection"}perform(){return C(this,void 0,void 0,function*(){let e=!1,A=!1;this.room.on(I.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let a="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(ly(s.address)?a+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,a+=" (passive)"):s.protocol==="udp"&&(A=!0)),this.appendMessage(a)}n&&n(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),W.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),A||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function ly(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 A=parseInt(e[1],10);if(A>=16&&A<=31)return!0}}return!1}class uy extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return C(this,void 0,void 0,function*(){var e,A,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new ka;const r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===lu.Cloud&&(!((A=r.serverInfo)===null||A===void 0)&&A.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield i.close()})}}class HU extends yA.EventEmitter{constructor(e,A){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=A,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:fA.IDLE,name:"",description:""}),e}updateCheck(e,A){this.checkResults.set(e,A),this.emit("checkUpdate",e,A)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==fA.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return C(this,void 0,void 0,function*(){const A=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(A,s)};n.on("update",i);const r=yield n.run();return n.off("update",i),r})}checkWebsocket(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(uy)})}checkWebRTC(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(cy)})}checkTURN(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(oy)})}checkReconnect(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ay)})}checkPublishAudio(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ry)})}checkPublishVideo(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(sy)})}checkConnectionProtocol(){return C(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(iy);if(e.data&&"protocol"in e.data){const A=e.data;this.options.protocol=A.protocol}return e})}checkCloudRegion(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ny)})}}const dy=/\{[^{}]+\}/g;function hy(){return Math.random().toString(36).slice(2,11)}function fy(t){let{baseUrl:e="",Request:A=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:r,headers:s,...a}={...t};e=uh(e);const o=[];async function c(l,u){const{baseUrl:d,fetch:h=n,Request:p=A,headers:f,params:m={},parseAs:B="json",querySerializer:b,bodySerializer:U=r??py,body:w,...v}=u||{};d&&(e=uh(d));let y=typeof i=="function"?i:lh(i);b&&(y=typeof b=="function"?b:lh({...typeof i=="object"?i:{},...b}));const E=w===void 0?void 0:U(w),T=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},F={redirect:"follow",...a,...v,body:E,headers:By(T,s,f,m.header)};let R,D,O=new A(my(l,{baseUrl:e,params:m,querySerializer:y}),F);for(const N in v)N in O||(O[N]=v[N]);if(o.length){R=hy(),D=Object.freeze({baseUrl:e,fetch:h,parseAs:B,querySerializer:y,bodySerializer:U});for(const N of o)if(N&&typeof N=="object"&&typeof N.onRequest=="function"){const V=await N.onRequest({request:O,schemaPath:l,params:m,options:D,id:R});if(V){if(!(V instanceof A))throw new Error("onRequest: must return new Request() when modifying the request");O=V}}}let M=await h(O);if(o.length)for(let N=o.length-1;N>=0;N--){const V=o[N];if(V&&typeof V=="object"&&typeof V.onResponse=="function"){const Fe=await V.onResponse({request:O,response:M,schemaPath:l,params:m,options:D,id:R});if(Fe){if(!(Fe instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");M=Fe}}}if(M.status===204||M.headers.get("Content-Length")==="0")return M.ok?{data:{},response:M}:{error:{},response:M};if(M.ok)return B==="stream"?{data:M.body,response:M}:{data:await M[B](),response:M};let ae=await M.text();try{ae=JSON.parse(ae)}catch{}return{error:ae,response:M}}return{GET(l,u){return c(l,{...u,method:"GET"})},PUT(l,u){return c(l,{...u,method:"PUT"})},POST(l,u){return c(l,{...u,method:"POST"})},DELETE(l,u){return c(l,{...u,method:"DELETE"})},OPTIONS(l,u){return c(l,{...u,method:"OPTIONS"})},HEAD(l,u){return c(l,{...u,method:"HEAD"})},PATCH(l,u){return c(l,{...u,method:"PATCH"})},TRACE(l,u){return c(l,{...u,method:"TRACE"})},use(...l){for(const u of l)if(u){if(typeof u!="object"||!("onRequest"in u||"onResponse"in u))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");o.push(u)}},eject(...l){for(const u of l){const d=o.indexOf(u);d!==-1&&o.splice(d,1)}}}}function mr(t,e,A){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${(A==null?void 0:A.allowReserved)===!0?e:encodeURIComponent(e)}`}function oh(t,e,A){if(!e||typeof e!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[A.style]||"&";if(A.style!=="deepObject"&&A.explode===!1){for(const a in e)n.push(a,A.allowReserved===!0?e[a]:encodeURIComponent(e[a]));const s=n.join(",");switch(A.style){case"form":return`${t}=${s}`;case"label":return`.${s}`;case"matrix":return`;${t}=${s}`;default:return s}}for(const s in e){const a=A.style==="deepObject"?`${t}[${s}]`:s;n.push(mr(a,e[s],A))}const r=n.join(i);return A.style==="label"||A.style==="matrix"?`${i}${r}`:r}function ch(t,e,A){if(!Array.isArray(e))return"";if(A.explode===!1){const r={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[A.style]||",",s=(A.allowReserved===!0?e:e.map(a=>encodeURIComponent(a))).join(r);switch(A.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${t}=${s}`;default:return`${t}=${s}`}}const n={simple:",",label:".",matrix:";"}[A.style]||"&",i=[];for(const r of e)A.style==="simple"||A.style==="label"?i.push(A.allowReserved===!0?r:encodeURIComponent(r)):i.push(mr(t,r,A));return A.style==="label"||A.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function lh(t){return function(A){const n=[];if(A&&typeof A=="object")for(const i in A){const r=A[i];if(r!=null){if(Array.isArray(r)){if(r.length===0)continue;n.push(ch(i,r,{style:"form",explode:!0,...t==null?void 0:t.array,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}if(typeof r=="object"){n.push(oh(i,r,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}n.push(mr(i,r,t))}}return n.join("&")}}function gy(t,e){let A=t;for(const n of t.match(dy)??[]){let i=n.substring(1,n.length-1),r=!1,s="simple";if(i.endsWith("*")&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const a=e[i];if(Array.isArray(a)){A=A.replace(n,ch(i,a,{style:s,explode:r}));continue}if(typeof a=="object"){A=A.replace(n,oh(i,a,{style:s,explode:r}));continue}if(s==="matrix"){A=A.replace(n,`;${mr(i,a)}`);continue}A=A.replace(n,s==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return A}function py(t){return t instanceof FormData?t:JSON.stringify(t)}function my(t,e){var i;let A=`${e.baseUrl}${t}`;(i=e.params)!=null&&i.path&&(A=gy(A,e.params.path));let n=e.querySerializer(e.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(A+=`?${n}`),A}function By(...t){const e=new Headers;for(const A of t){if(!A||typeof A!="object")continue;const n=A instanceof Headers?A.entries():Object.entries(A);for(const[i,r]of n)if(r===null)e.delete(i);else if(Array.isArray(r))for(const s of r)e.append(i,s);else r!==void 0&&e.set(i,r)}return e}function uh(t){return t.endsWith("/")?t.substring(0,t.length-1):t}class dh{constructor(e){this.client=fy({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}setAuthToken(e){this.client.use({onRequest({request:A}){return A.headers.set("Authorization",`Bearer ${e}`),A}})}setApiToken(e){this.client.use({onRequest({request:A}){return A.headers.set("Authorization",`Token ${e}`),A}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async clientInitialise(e,A={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:A})}async clientStartSession(e,A){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:A})}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,A){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:A})}async listPlans(){return await this.client.GET("/api/plans")}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async getProductAnalytics(e,A,n){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...A&&{start_date:A},...n&&{end_date:n}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,A){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:A})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,A){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:A})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,A){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async searchProductKnowledgeBlocks(e,A,n){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:A,...n&&{limit:n.toString()}}}})}async updateProductKnowledgeBlock(e,A,n){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}},body:n})}async deleteProductKnowledgeBlock(e,A){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}}})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async replacePlan(e,A){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:A})}async updatePlan(e,A){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:A})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,A){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:A})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,A){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async updatePlanKnowledgeBlock(e,A,n){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}},body:n})}async deletePlanKnowledgeBlock(e,A){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,A){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:A})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,A){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:A})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,A){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:A})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,A){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async createRevisionKnowledgeBlock(e,A){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:A})}async updateRevisionKnowledgeBlock(e,A,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}},body:n})}async deleteRevisionKnowledgeBlock(e,A){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:A}}})}async listSessions(e,A){const n={token:e};return A!=null&&A.productId&&(n.product_id=A.productId),A!=null&&A.startDate&&(n.start_date=A.startDate),A!=null&&A.endDate&&(n.end_date=A.endDate),await this.client.GET("/api/sessions",{params:{query:n}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,A){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:A}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async updateSession(e,A){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:A})}async listUserSessions(e){const A={};return e!=null&&e.productId&&(A.product_id=e.productId),e!=null&&e.startDate&&(A.start_date=e.startDate),e!=null&&e.endDate&&(A.end_date=e.endDate),e!=null&&e.page&&(A.page=e.page),e!=null&&e.limit&&(A.limit=e.limit),e!=null&&e.courseName&&(A.course_name=e.courseName),e!=null&&e.userName&&(A.user_name=e.userName),e!=null&&e.company&&(A.company=e.company),e!=null&&e.email&&(A.email=e.email),e!=null&&e.sortBy&&(A.sort_by=e.sortBy),e!=null&&e.sortOrder&&(A.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(A).length>0?{query:A}:void 0})}async listUserSessionsAggregate(e){const A={};return e!=null&&e.productId&&(A.product_id=e.productId),e!=null&&e.startDate&&(A.start_date=e.startDate),e!=null&&e.endDate&&(A.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(A).length>0?{query:A}:void 0})}async getJoinToken(e,{clientType:A,user:n}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...A&&{client_type:A},...n&&{user:encodeURIComponent(n)}}}})}async trackEvent(e){try{return await this.client.POST("/api/track",{body:{sent_at:new Date().toISOString(),...e}})}catch(A){console.error("[obi] error tracking event:",A)}return{}}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}getClient(){return this.client}}const hh="https://app.coragents.ai";class Br extends kr{constructor(e,A,n,i){super(),this.state=null,this.isPaused=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=A,this.clientType=n,this.api=i.api||new dh({baseUrl:hh}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(r=>new qt(r)),this.captureScreen=i.captureScreen||null}async start(){console.debug("[obi] starting session",{planId:this.planId}),this.setState("connecting"),this.speakingStateChanged("thinking");try{const A=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(A!=null&&A.url)||!(A!=null&&A.token)||!(A!=null&&A.room)||!(A!=null&&A.session_uuid))throw new Error("Invalid room info");this.sessionUuid=A==null?void 0:A.session_uuid,this.roomId=A==null?void 0:A.room,this.joinToken=A==null?void 0:A.token,this.roomUrl=A==null?void 0:A.url,await this.joinRoom(),this.setState("connected"),console.debug("[obi] started session",{planId:this.planId,sessionUuid:this.sessionUuid})}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:A=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(I.Disconnected,n=>{if(console.debug("[obi] room disconnected",{reason:n}),!this.room)return;let i=null;switch(n){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(I.TrackSubscribed,n=>{n.kind==="audio"&&(n.attach(),n.source===k.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(n.mediaStream)))}),this.room.on(I.LocalTrackPublished,n=>{n.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(n.audioTrack.mediaStream))}),this.room.on(I.ParticipantAttributesChanged,n=>{if(!n["lk.agent.state"])return;const i=n["lk.agent.state"];switch(i){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.state!=="connected"&&this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",i)}}),this.room.on(I.DataReceived,async n=>{try{const i=new TextDecoder().decode(n);console.debug("[obi] data received",i);const r=JSON.parse(i);switch(r.status||r.request||r.type){case"course_progress":typeof r.current_step=="number"&&typeof r.total_steps=="number"&&Array.isArray(r.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,r.current_step),totalSteps:Math.max(1,r.total_steps),stepNames:r.step_names});break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;default:console.warn("[obi] unknown data received",r)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async n=>(console.debug("[obi] checking microphone",{sessionUuid:this.sessionUuid}),await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async n=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,r=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||r)return console.error("[obi] error capturing screen",{error:r}),"error";try{return await this.room.localParticipant.sendFile(new File([i],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(s){return console.error("[obi] error sending screen capture",{error:s}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let n=0;n<9&&!(this.room.state===q.Connected&&this.room.remoteParticipants.size>=1);n++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===q.Connected&&this.room.remoteParticipants.size>=1)){console.error("[obi] room not connected",{state:this.room.state,numParticipants:this.room.remoteParticipants.size}),this.shutdown("invalid-room");return}if(e&&await this.room.localParticipant.setMicrophoneEnabled(!0),A){let n=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(n=!0);n?this.speakingState="speaking":this.speakingState="listening"}}async continue(){console.debug("[obi] continuing session",{sessionUuid:this.sessionUuid}),this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(A){console.error("[obi] error checking microphone permission:",A)}return e?(console.debug("[obi] microphone permission granted",{sessionUuid:this.sessionUuid}),await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):console.debug("[obi] microphone permission denied",{sessionUuid:this.sessionUuid}),e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){console.debug("[obi] sharing microphone",{sessionUuid:this.sessionUuid}),this.speakingStateChanged("thinking");let e=null,A=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(n){n=n,this.isMicShared=!1}e?console.debug("[obi] shared microphone",{sessionUuid:this.sessionUuid}):console.error("[obi] failed to share microphone",{error:A}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){console.debug("[obi] sharing screen",{sessionUuid:this.sessionUuid}),this.speakingStateChanged("thinking"),await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),await this.sendData({request:"share_screen",success:!0}),this.setState("navigate")}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}muteMicrophone(){console.debug("[obi] muting microphone",{sessionUuid:this.sessionUuid}),this.room.localParticipant.getTrackPublications().forEach(e=>{var A,n;e.handleMuted(),(n=(A=e.track)==null?void 0:A.mediaStream)==null||n.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){console.debug("[obi] unmuting microphone",{sessionUuid:this.sessionUuid}),this.room.localParticipant.getTrackPublications().forEach(e=>{var A,n;e.handleUnmuted(),(n=(A=e.track)==null?void 0:A.mediaStream)==null||n.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){console.debug("[obi] stopping session",{sessionUuid:this.sessionUuid});const A=this.room;this.room=null,await A.disconnect(),console.debug("[obi] stopped session",{sessionUuid:this.sessionUuid})}this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const n=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const r=[],s=50,a=5e3,o=8,c=Math.pow(a/s,1/o);for(let l=0;l<o;l++){const u=s*Math.pow(c,l),d=s*Math.pow(c,l+1),h=Math.floor(u/n),p=Math.floor(d/n),f=Math.min(p,i.length),m=Math.min(h,f);if(m<f){const B=i.slice(m,f).reduce((b,U)=>b+U,0)/(f-m)/255;r.push(B)}else r.push(0)}return r}setState(e){console.debug("[obi] state changed",{state:e,oldState:this.state});const A=this.state;this.state=e,this.emit("stateChanged",e,A)}static deserialise(e,A,n,i={}){const r=JSON.parse(e),s=new Br(A,r.planId,n,i);return s.state=r.state,s.speakingState=r.speakingState,s.identity=r.identity||null,s.isPaused=r.isPaused||!1,s.sessionUuid=r.sessionUuid||null,s.roomId=r.roomId||null,s.joinToken=r.joinToken||null,s.roomUrl=r.roomUrl||null,s}speakingStateChanged(e){console.debug("[obi] speaking state changed",{state:e,oldState:this.speakingState});const A=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,A)}async sendData(e){console.debug("[obi] sending data",{data:e}),await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const A=new AudioContext,n=A.createAnalyser();return A.createMediaStreamSource(e).connect(n),n.fftSize=2048,n.smoothingTimeConstant=.6,n}}class vr extends kr{constructor(e,A,n={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=A,this.api=n.api||new dh({baseUrl:n.apiBaseUrl||hh}),this.sessionFactory=n.sessionFactory||((i,r,s,a)=>new Br(i,r,s,a)),this.captureScreen=n.captureScreen||null}async initialise(e={}){var A,n,i,r;if(console.debug("[obi] initialising client"),!this.appToken)throw new Error("App token is required");this.setState("loading");try{const s=await this.api.clientInitialise(this.appToken,{identity:e.identity});if(this.identity=e.identity||null,this.product=((A=s.data)==null?void 0:A.product)||null,this.plans=((n=s.data)==null?void 0:n.onboarding_plans)||[],this.selectedPlan=((i=s.data)==null?void 0:i.selected_plan)||null,this.showWidget=((r=s.data)==null?void 0:r.show_widget)||!1,e.planUuid){let a=this.plans.find(o=>o.uuid===e.planUuid)||null;if(!a)try{const o=await this.api.getSessionPlan(e.planUuid);a=this.plans.find(c=>{var l;return c.uuid===((l=o.data)==null?void 0:l.plan_uuid)})||null}catch(o){console.error("[obi] error getting session plan",o)}a?(this.selectedPlan=a,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}console.debug("[obi] initialised client",{identity:this.identity,product:this.product,plans:this.plans,selectedPlan:this.selectedPlan,showWidget:this.showWidget})}catch(s){throw this.error=s instanceof Error?s:new Error(String(s)),this.setState("error"),s}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e),this.trackEvent(e?"plan_selected":"plan_cancelled")}async startSession(e,A){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(A),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(n=>{this.session=null,console.error("[obi] error starting session",n)}),this.trackEvent("session_started"),this.session}async resumeSession(e){var A,n;return console.debug("[obi] resuming session",{clientState:this.state,sessionState:(A=this.session)==null?void 0:A.state,speakingState:(n=this.session)==null?void 0:n.speakingState}),this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(i=>{console.error("[obi] error joining room",{error:i}),i instanceof Error&&i.message==="Room is not connected"&&this.session.stop()}),this.trackEvent("session_resumed"),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",A=>{var n,i;(i=(n=this.session)==null?void 0:n.removeAllListeners)==null||i.call(n),this.session=null,this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",A)}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session_stopped"),await this.session.stop(),this.session=null)}isLoading(){return this.state==="loading"}isReady(){return this.state==="ready"}serialise(){var e;return JSON.stringify({state:this.state,appToken:this.appToken,clientType:this.clientType,identity:this.identity,product:this.product,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise()})}static deserialise(e,A,n,i={}){const r=JSON.parse(e),s=new vr(A,n,i);return s.state=r.state,s.identity=r.identity||null,s.product=r.product||null,s.plans=r.plans||[],s.selectedPlan=r.selectedPlan||null,s.selectedPlanUuid=r.selectedPlanUuid||null,s.showWidget=r.showWidget||!1,r.session&&(s.session=Br.deserialise(r.session,A,n,{api:s.api})),s}setState(e){const A=this.state;this.state=e,this.emit("stateChanged",e,A)}trackEvent(e,A={}){var n,i,r;this.api.trackEvent({event:e,client_type:this.clientType,plan_id:(n=this.selectedPlan)==null?void 0:n.uuid,product_id:(i=this.product)==null?void 0:i.uuid,session_id:(r=this.session)==null?void 0:r.sessionUuid,...A}).then(()=>{console.debug("[obi] tracked event",{event:e,data:A})}).catch(s=>{console.error("[obi] error tracking event",{event:e,data:A,error:s})})}}var Cr,K,fh,Ct,gh,ph,mh,Bh,Ja,Xa,qa,vh,xn={},Ch=[],vy=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_n=Array.isArray;function PA(t,e){for(var A in e)t[A]=e[A];return t}function Ya(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function za(t,e,A){var n,i,r,s={};for(r in e)r=="key"?n=e[r]:r=="ref"?i=e[r]:s[r]=e[r];if(arguments.length>2&&(s.children=arguments.length>3?Cr.call(arguments,2):A),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)s[r]==null&&(s[r]=t.defaultProps[r]);return wr(t,s,n,i,null)}function wr(t,e,A,n,i){var r={type:t,props:e,key:A,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++fh,__i:-1,__u:0};return i==null&&K.vnode!=null&&K.vnode(r),r}function Pe(t){return t.children}function RA(t,e){this.props=t,this.context=e}function Yt(t,e){if(e==null)return t.__?Yt(t.__,t.__i+1):null;for(var A;e<t.__k.length;e++)if((A=t.__k[e])!=null&&A.__e!=null)return A.__e;return typeof t.type=="function"?Yt(t):null}function wh(t){var e,A;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((A=t.__k[e])!=null&&A.__e!=null){t.__e=t.__c.base=A.__e;break}return wh(t)}}function Za(t){(!t.__d&&(t.__d=!0)&&Ct.push(t)&&!br.__r++||gh!=K.debounceRendering)&&((gh=K.debounceRendering)||ph)(br)}function br(){for(var t,e,A,n,i,r,s,a=1;Ct.length;)Ct.length>a&&Ct.sort(mh),t=Ct.shift(),a=Ct.length,t.__d&&(A=void 0,i=(n=(e=t).__v).__e,r=[],s=[],e.__P&&((A=PA({},n)).__v=n.__v+1,K.vnode&&K.vnode(A),$a(e.__P,A,n,e.__n,e.__P.namespaceURI,32&n.__u?[i]:null,r,i??Yt(n),!!(32&n.__u),s),A.__v=n.__v,A.__.__k[A.__i]=A,Eh(r,A,s),A.__e!=i&&wh(A)));br.__r=0}function bh(t,e,A,n,i,r,s,a,o,c,l){var u,d,h,p,f,m,B=n&&n.__k||Ch,b=e.length;for(o=Cy(A,e,B,o,b),u=0;u<b;u++)(h=A.__k[u])!=null&&(d=h.__i==-1?xn:B[h.__i]||xn,h.__i=u,m=$a(t,h,d,i,r,s,a,o,c,l),p=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&eo(d.ref,null,h),l.push(h.ref,h.__c||p,h)),f==null&&p!=null&&(f=p),4&h.__u||d.__k===h.__k?o=yh(h,o,t):typeof h.type=="function"&&m!==void 0?o=m:p&&(o=p.nextSibling),h.__u&=-7);return A.__e=f,o}function Cy(t,e,A,n,i){var r,s,a,o,c,l=A.length,u=l,d=0;for(t.__k=new Array(i),r=0;r<i;r++)(s=e[r])!=null&&typeof s!="boolean"&&typeof s!="function"?(o=r+d,(s=t.__k[r]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?wr(null,s,null,null,null):_n(s)?wr(Pe,{children:s},null,null,null):s.constructor==null&&s.__b>0?wr(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,a=null,(c=s.__i=wy(s,A,o,u))!=-1&&(u--,(a=A[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(i>l?d--:i<l&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=o&&(c==o-1?d--:c==o+1?d++:(c>o?d--:d++,s.__u|=4))):t.__k[r]=null;if(u)for(r=0;r<l;r++)(a=A[r])!=null&&!(2&a.__u)&&(a.__e==n&&(n=Yt(a)),kh(a,a));return n}function yh(t,e,A){var n,i;if(typeof t.type=="function"){for(n=t.__k,i=0;n&&i<n.length;i++)n[i]&&(n[i].__=t,e=yh(n[i],e,A));return e}t.__e!=e&&(e&&t.type&&!A.contains(e)&&(e=Yt(t)),A.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function yr(t,e){return e=e||[],t==null||typeof t=="boolean"||(_n(t)?t.some(function(A){yr(A,e)}):e.push(t)),e}function wy(t,e,A,n){var i,r,s=t.key,a=t.type,o=e[A];if(o===null&&t.key==null||o&&s==o.key&&a==o.type&&!(2&o.__u))return A;if(n>(o!=null&&!(2&o.__u)?1:0))for(i=A-1,r=A+1;i>=0||r<e.length;){if(i>=0){if((o=e[i])&&!(2&o.__u)&&s==o.key&&a==o.type)return i;i--}if(r<e.length){if((o=e[r])&&!(2&o.__u)&&s==o.key&&a==o.type)return r;r++}}return-1}function Uh(t,e,A){e[0]=="-"?t.setProperty(e,A??""):t[e]=A==null?"":typeof A!="number"||vy.test(e)?A:A+"px"}function Ur(t,e,A,n,i){var r;e:if(e=="style")if(typeof A=="string")t.style.cssText=A;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)A&&e in A||Uh(t.style,e,"");if(A)for(e in A)n&&A[e]==n[e]||Uh(t.style,e,A[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(Bh,"$1")),e=e.toLowerCase()in t||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=A,A?n?A.u=n.u:(A.u=Ja,t.addEventListener(e,r?qa:Xa,r)):t.removeEventListener(e,r?qa:Xa,r);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=A??"";break e}catch{}typeof A=="function"||(A==null||A===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&A==1?"":A))}}function Qh(t){return function(e){if(this.l){var A=this.l[e.type+t];if(e.t==null)e.t=Ja++;else if(e.t<A.u)return;return A(K.event?K.event(e):e)}}}function $a(t,e,A,n,i,r,s,a,o,c){var l,u,d,h,p,f,m,B,b,U,w,v,y,E,T,F,R,D=e.type;if(e.constructor!=null)return null;128&A.__u&&(o=!!(32&A.__u),r=[a=e.__e=A.__e]),(l=K.__b)&&l(e);e:if(typeof D=="function")try{if(B=e.props,b="prototype"in D&&D.prototype.render,U=(l=D.contextType)&&n[l.__c],w=l?U?U.props.value:l.__:n,A.__c?m=(u=e.__c=A.__c).__=u.__E:(b?e.__c=u=new D(B,w):(e.__c=u=new RA(B,w),u.constructor=D,u.render=yy),U&&U.sub(u),u.props=B,u.state||(u.state={}),u.context=w,u.__n=n,d=u.__d=!0,u.__h=[],u._sb=[]),b&&u.__s==null&&(u.__s=u.state),b&&D.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=PA({},u.__s)),PA(u.__s,D.getDerivedStateFromProps(B,u.__s))),h=u.props,p=u.state,u.__v=e,d)b&&D.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),b&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(b&&D.getDerivedStateFromProps==null&&B!==h&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(B,w),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(B,u.__s,w)===!1||e.__v==A.__v){for(e.__v!=A.__v&&(u.props=B,u.state=u.__s,u.__d=!1),e.__e=A.__e,e.__k=A.__k,e.__k.some(function(O){O&&(O.__=e)}),v=0;v<u._sb.length;v++)u.__h.push(u._sb[v]);u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(B,u.__s,w),b&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(h,p,f)})}if(u.context=w,u.props=B,u.__P=t,u.__e=!1,y=K.__r,E=0,b){for(u.state=u.__s,u.__d=!1,y&&y(e),l=u.render(u.props,u.state,u.context),T=0;T<u._sb.length;T++)u.__h.push(u._sb[T]);u._sb=[]}else do u.__d=!1,y&&y(e),l=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++E<25);u.state=u.__s,u.getChildContext!=null&&(n=PA(PA({},n),u.getChildContext())),b&&!d&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(h,p)),F=l,l!=null&&l.type===Pe&&l.key==null&&(F=Sh(l.props.children)),a=bh(t,_n(F)?F:[F],e,A,n,i,r,s,a,o,c),u.base=e.__e,e.__u&=-161,u.__h.length&&s.push(u),m&&(u.__E=u.__=null)}catch(O){if(e.__v=null,o||r!=null)if(O.then){for(e.__u|=o?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;r[r.indexOf(a)]=null,e.__e=a}else for(R=r.length;R--;)Ya(r[R]);else e.__e=A.__e,e.__k=A.__k;K.__e(O,e,A)}else r==null&&e.__v==A.__v?(e.__k=A.__k,e.__e=A.__e):a=e.__e=by(A.__e,e,A,n,i,r,s,o,c);return(l=K.diffed)&&l(e),128&e.__u?void 0:a}function Eh(t,e,A){for(var n=0;n<A.length;n++)eo(A[n],A[++n],A[++n]);K.__c&&K.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(r){r.call(i)})}catch(r){K.__e(r,i.__v)}})}function Sh(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:_n(t)?t.map(Sh):PA({},t)}function by(t,e,A,n,i,r,s,a,o){var c,l,u,d,h,p,f,m=A.props,B=e.props,b=e.type;if(b=="svg"?i="http://www.w3.org/2000/svg":b=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),r!=null){for(c=0;c<r.length;c++)if((h=r[c])&&"setAttribute"in h==!!b&&(b?h.localName==b:h.nodeType==3)){t=h,r[c]=null;break}}if(t==null){if(b==null)return document.createTextNode(B);t=document.createElementNS(i,b,B.is&&B),a&&(K.__m&&K.__m(e,r),a=!1),r=null}if(b==null)m===B||a&&t.data==B||(t.data=B);else{if(r=r&&Cr.call(t.childNodes),m=A.props||xn,!a&&r!=null)for(m={},c=0;c<t.attributes.length;c++)m[(h=t.attributes[c]).name]=h.value;for(c in m)if(h=m[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=h;else if(!(c in B)){if(c=="value"&&"defaultValue"in B||c=="checked"&&"defaultChecked"in B)continue;Ur(t,c,null,h,i)}}for(c in B)h=B[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?l=h:c=="value"?p=h:c=="checked"?f=h:a&&typeof h!="function"||m[c]===h||Ur(t,c,h,m[c],i);if(l)a||u&&(l.__html==u.__html||l.__html==t.innerHTML)||(t.innerHTML=l.__html),e.__k=[];else if(u&&(t.innerHTML=""),bh(e.type=="template"?t.content:t,_n(d)?d:[d],e,A,n,b=="foreignObject"?"http://www.w3.org/1999/xhtml":i,r,s,r?r[0]:A.__k&&Yt(A,0),a,o),r!=null)for(c=r.length;c--;)Ya(r[c]);a||(c="value",b=="progress"&&p==null?t.removeAttribute("value"):p!=null&&(p!==t[c]||b=="progress"&&!p||b=="option"&&p!=m[c])&&Ur(t,c,p,m[c],i),c="checked",f!=null&&f!=t[c]&&Ur(t,c,f,m[c],i))}return t}function eo(t,e,A){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(i){K.__e(i,A)}}function kh(t,e,A){var n,i;if(K.unmount&&K.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||eo(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(r){K.__e(r,e)}n.base=n.__P=null}if(n=t.__k)for(i=0;i<n.length;i++)n[i]&&kh(n[i],e,A||typeof t.type!="function");A||Ya(t.__e),t.__c=t.__=t.__e=void 0}function yy(t,e,A){return this.constructor(t,A)}function Uy(t,e,A){var n,i,r,s;e==document&&(e=document.documentElement),K.__&&K.__(t,e),i=(n=typeof A=="function")?null:A&&A.__k||e.__k,r=[],s=[],$a(e,t=(!n&&A||e).__k=za(Pe,null,[t]),i||xn,xn,e.namespaceURI,!n&&A?[A]:i?null:e.firstChild?Cr.call(e.childNodes):null,r,!n&&A?A:i?i.__e:e.firstChild,n,s),Eh(r,t,s)}function Qy(t){function e(A){var n,i;return this.getChildContext||(n=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(r){this.props.value!=r.value&&n.forEach(function(s){s.__e=!0,Za(s)})},this.sub=function(r){n.add(r);var s=r.componentWillUnmount;r.componentWillUnmount=function(){n&&n.delete(r),s&&s.call(r)}}),A.children}return e.__c="__cC"+vh++,e.__=t,e.Provider=e.__l=(e.Consumer=function(A,n){return A.children(n)}).contextType=e,e}Cr=Ch.slice,K={__e:function(t,e,A,n){for(var i,r,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((r=i.constructor)&&r.getDerivedStateFromError!=null&&(i.setState(r.getDerivedStateFromError(t)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,n||{}),s=i.__d),s)return i.__E=i}catch(a){t=a}throw t}},fh=0,RA.prototype.setState=function(t,e){var A;A=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=PA({},this.state),typeof t=="function"&&(t=t(PA({},A),this.props)),t&&PA(A,t),t!=null&&this.__v&&(e&&this._sb.push(e),Za(this))},RA.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Za(this))},RA.prototype.render=Pe,Ct=[],ph=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,mh=function(t,e){return t.__v.__b-e.__v.__b},br.__r=0,Bh=/(PointerCapture)$|Capture$/i,Ja=0,Xa=Qh(!1),qa=Qh(!0),vh=0;var Ey=0;function g(t,e,A,n,i,r){e||(e={});var s,a,o=e;if("ref"in o)for(a in o={},e)a=="ref"?s=e[a]:o[a]=e[a];var c={type:t,props:o,key:A,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ey,__i:-1,__u:0,__source:i,__self:r};if(typeof t=="function"&&(s=t.defaultProps))for(a in s)o[a]===void 0&&(o[a]=s[a]);return K.vnode&&K.vnode(c),c}const Sy=`:root,:host{--obi-modal-padding: 48px 48px 32px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 12px;--obi-modal-shadow: 0px 1px 2px rgba(0, 0, 0, .05);--obi-modal-xsmall-width: 320px;--obi-modal-xsmall-height: 240px;--obi-modal-small-width: 480px;--obi-modal-small-height: 400px;--obi-modal-medium-width: 640px;--obi-modal-medium-height: 545px;--obi-modal-large-width: 1200px;--obi-modal-large-height: 700px;--obi-font-family: "Satoshi", sans-serif;--obi-color-primary: #9500FF;--obi-color-primary-50: color-mix(in srgb, var(--obi-color-primary) 50%, white 50%);--obi-color-primary-30: color-mix(in srgb, var(--obi-color-primary) 30%, white 70%);--obi-color-tint: color-mix(in srgb, var(--obi-color-primary) 5%, white 95%);--obi-color-text: #18181B;--obi-course-color-selected: var(--obi-color-primary-50);--obi-course-color-tint: var(--obi-color-tint);--obi-course-progress-step-completed: #B3B3B3;--obi-course-progress-step-incomplete: #D9D9D9;--obi-course-progress-text-color: #757575;font-family:var(--obi-font-family);color:var(--obi-color-text)}.obi-button{font-family:var(--obi-font-family);color:var(--obi-color-text)}dialog{margin:auto;padding:0;border:none;border-radius:var(--obi-modal-border-radius);box-shadow:var(--obi-modal-shadow);background:var(--obi-modal-background-color);box-sizing:border-box}dialog>.modal-content{padding:var(--obi-modal-padding);box-sizing:border-box}dialog,dialog.modal-medium,dialog>.modal-content,dialog.modal-medium>.modal-content{width:var(--obi-modal-medium-width);min-height:var(--obi-modal-medium-height)}dialog.modal-xsmall,dialog.modal-xsmall>.modal-content{width:var(--obi-modal-xsmall-width);min-height:var(--obi-modal-xsmall-height)}dialog.modal-small,dialog.modal-small>.modal-content{width:var(--obi-modal-small-width);min-height:var(--obi-modal-small-height)}dialog.modal-large,dialog.modal-large>.modal-content{width:var(--obi-modal-large-width);min-height:var(--obi-modal-large-height)}dialog::backdrop{background:rgba(0,0,0,.5)}.tour-content{display:block;width:100%;height:100%}.tour-content .container{box-sizing:border-box;display:flex;flex-direction:column;align-items:center;padding:0;width:100%;height:100%}.tour-content .header{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:100%}.tour-content .title{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:700;font-size:32px;line-height:90%;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0}.tour-content .subtitle{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b;margin:0}.tour-content .visual{width:480px;height:240px;margin-top:24px;border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative}.tour-content .description{width:100%;min-height:48px;margin:24px 0 0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b}.tour-content .button-container{display:flex;margin-top:24px;flex-direction:column;align-items:center;gap:16px;width:100%}.tour-content .action-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;min-width:200px;height:40px;background:#303030;border:1px solid #303030;border-radius:4px;cursor:pointer;text-decoration:none}.tour-content .action-button.disabled{opacity:.6;cursor:not-allowed}.tour-content .button-text{height:16px;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{flex:1;display:flex;flex-direction:column}.obi-close-button{position:absolute;top:24px;right:24px;width:24px;height:24px;cursor:pointer;border:none;background:none;padding:0;display:flex;align-items:center;justify-content:center;z-index:1}.obi-panel{box-sizing:border-box;padding:24px;background-color:#fff;box-shadow:0 16px 32px -4px #0000001f,0 4px 8px -2px #00000014,inset 0 1px #fff9;border-radius:12px}.obi-pill.container{width:96px;height:30px;display:flex;align-items:center;justify-content:center}.obi-pill.container .pill{display:flex;align-items:center;justify-content:center;width:48px;height:6px;opacity:.7;border-radius:3px;background-color:var(--obi-color-primary);transition:width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill.container .pill.button{cursor:pointer}.obi-pill.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill.container.active .pill{width:96px;height:30px;border-radius:15px;opacity:1}.obi-pill.container.busy,.obi-pill.container.busy .pill{width:220px}.obi-pill2.container{display:flex;align-items:center;justify-content:center}.obi-pill2.container .pill{display:flex;align-items:center;justify-content:center;width:48px;height:6px;opacity:.7;border-radius:3px;background-color:var(--obi-color-primary);transform:translateY(0);transition:width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill2.container .pill.button{cursor:pointer}.obi-pill2.container:not(.active){transition:height 0s linear .15s;height:6px}.obi-pill2.container:not(.active) .pill{transform:translateY(12px);transition:transform 0s linear .15s,width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill2.container.active{transition:none;height:30px}.obi-pill2.container.active .pill{transition:transform 0s,width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out;width:96px;height:30px;border-radius:15px;opacity:1}.obi-pill2.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-popout{position:relative;display:inline-block}.obi-popout .obi-popout-target{cursor:pointer;display:inline-block}.obi-popout .content{position:absolute;background-color:#fff0;z-index:100;animation:popout-appear .15s ease-out}@keyframes popout-appear{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.obi-round-button-popout{z-index:600}.obi-round-button{flex:0 0 auto;display:flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:50%;padding:0;box-sizing:border-box;background-color:#fff;border:1px solid #D9D9D9;box-shadow:none}.obi-round-button:hover{cursor:pointer}.obi-round-button:disabled{box-shadow:none;background-color:#f0f0f0;color:#999;cursor:not-allowed!important;pointer-events:none}.obi-round-button-title{padding:8px 16px;border-radius:12px;background-color:#fff;color:#000;font-size:14px;font-weight:400;white-space:nowrap;box-shadow:0 4px 12px #00000026,0 2px 4px #0000001a;border:1px solid rgba(0,0,0,.08);z-index:5000;pointer-events:none;-webkit-user-select:none;user-select:none;position:relative}.obi-round-button-title:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-top:6px solid white;filter:drop-shadow(0 2px 2px rgba(0,0,0,.1))}.obi-equaliser{display:flex;align-items:center;gap:2px;height:32px}.obi-equaliser .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-equaliser .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1}.obi-message{display:inline-flex;align-items:center;justify-content:center;min-width:140px;padding:0 15px;text-wrap:nowrap;font-size:16px;font-weight:400;height:30px;box-sizing:border-box;background-color:#fff;border-radius:15px;border:1px solid #D9D9D9}.obi-message.clickable{box-shadow:0 4px 6px #0000001a;cursor:pointer}.obi-loading-dots{display:flex;align-items:center;gap:2px;height:32px}.obi-loading-dots .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-loading-dots .dot{width:3px;height:3px;border-radius:2px;position:relative;z-index:2}.obi-loading-dots .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1;height:0px;animation:bounce .9s ease-in-out infinite}@keyframes bounce{0%,60%,to{height:0px}30%{height:16px}}.obi-exit-survey{position:relative;width:320px;margin:0 auto;-webkit-backdrop-filter:none;backdrop-filter:none;background:white;z-index:9999}.obi-exit-survey-container{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-header{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-title{width:272px;height:22px;margin:0;font-family:Satoshi,sans-serif;font-size:16px;font-weight:600;line-height:140%;text-align:center;color:#1e1e1e;flex:none;align-self:stretch}.obi-exit-survey-subtitle{width:272px;height:20px;margin:0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;text-align:center;color:#757575;flex:none;align-self:stretch}.obi-exit-survey-options{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-options textarea{height:80px;resize:none;outline:none}.obi-exit-survey-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;width:272px;height:44px;border-radius:12px;cursor:pointer;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-button:hover{transform:translateY(-1px);box-shadow:0 4px 8px #0000001a}.obi-exit-survey-button:active{transform:translateY(0)}.obi-exit-survey-button-continue{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-button-continue:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-button-wrap-up{background:#303030;border:1px solid rgba(217,217,217);color:#fff;font-weight:500}.obi-exit-survey-button-wrap-up:hover{background:#404040;border-color:#d9d9d9}.obi-exit-survey-reason-button{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-reason-button:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-reason-button-secondary{display:flex;flex-direction:row;justify-content:center;align-items:center;padding:4px 6px;gap:8px;width:272px;height:28px;border-radius:4px;cursor:pointer;border:none;background:transparent;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;color:#5a5a5a;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-reason-button-secondary:hover{background:rgba(0,0,0,.05);color:#3a3a3a}.obi-message-input{display:inline-block;position:relative}.obi-message-input .container{width:212px;height:30px;box-sizing:border-box;background:#FFFFFF;border:1px solid var(--obi-color-primary-30);border-radius:15px;display:flex;align-items:center;flex:none;order:2;flex-grow:0;transition:height .3s ease,border-radius .3s ease;animation:expandMessageInput .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .container{height:auto;min-height:140px;border-radius:15px;align-items:flex-start;padding:8px 0;animation:expandMessageInputWide .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input .field{flex:1 1 0;border:none;background:transparent;outline:none;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:18px;color:#000;padding:4px 3px 0 16px;height:100%;box-sizing:border-box;min-width:0;resize:none;overflow:hidden;scrollbar-width:none;transition:padding .3s ease;animation:fadeInInputField .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .field{height:auto;min-height:120px;padding:4px 16px;overflow-y:auto;line-height:18px}.obi-message-input .field::placeholder{color:#999}.obi-message-input .field:disabled{cursor:not-allowed;opacity:.6}.obi-message-input .send{position:absolute;bottom:3px;right:4px;flex-shrink:0;width:24px;height:24px;background:var(--obi-color-primary);border:none;border-radius:9999px;display:flex;justify-content:center;align-items:center;cursor:pointer;transition:all .3s ease;color:#fff}.obi-message-input.expanded .send{width:28px;height:28px;position:relative;top:0;bottom:0;margin-right:0}.obi-message-input.expanded .button-container{display:flex;justify-content:space-between;align-items:center;width:100%;margin-top:8px}.obi-message-input .send:disabled{background:#CCCCCC;cursor:not-allowed;transform:none}.obi-message-input .container:focus-within{border-color:var(--obi-color-primary);box-shadow:0 0 0 2px #9008ff1a}@keyframes expandMessageInput{0%{width:32px}to{width:212px}}@keyframes expandMessageInputWide{0%{width:212px}to{width:340px}}@keyframes fadeInInputField{0%{opacity:0}60%{opacity:0}to{opacity:1}}.obi-course-progress{display:flex;flex-direction:column;justify-content:center;align-items:flex-start;gap:6px;width:100%;min-width:0;height:24px;flex:none;order:1;align-self:stretch;flex-grow:0}.obi-course-progress-steps{display:flex;flex-direction:row;align-items:center;justify-content:space-between;padding:0;gap:2px;width:100%;height:6px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-container{display:flex;flex-direction:column;justify-content:center;align-items:stretch;padding:2px 0;height:6px;flex:1;min-width:0}.obi-course-progress-step{width:100%;height:2px;background:var(--obi-course-progress-step-incomplete);border-radius:24px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-step.completed{background:var(--obi-course-progress-step-completed)}.obi-course-progress-description{width:100%;height:14px;font-family:var(--obi-font-family);font-style:normal;font-weight:500;font-size:14px;line-height:100%;color:var(--obi-course-progress-text-color);flex:none;order:1;flex-grow:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.obi-widget-popout{z-index:400}.obi-widget-panel{display:flex;flex-direction:column;gap:8px;align-items:center;justify-content:center;min-width:222px;width:min-content;padding:12px;box-sizing:border-box;border-radius:27px;background:white;transition:background .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel:not(.messaging){width:256px}.obi-widget-panel.tool-usage{width:384px}.obi-widget-panel:not(.expanded){background:transparent;border:none;box-shadow:none;transition:background .1s ease-out .1s,border .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel.maximized{transform:translateY(-110px)}.obi-widget-panel .obi-widget{display:flex;align-items:center;min-width:192px;padding-left:58px;box-sizing:border-box;gap:4px}.obi-widget-panel .obi-widget.active.in-plan{padding-left:0}.obi-widget-panel .obi-widget.active.in-plan .obi-round-button{animation:fade-in-button .2s ease-out .15s both}.obi-widget-panel .obi-widget.active .obi-equaliser{animation:fade-in-equaliser .2s ease-out .15s both}@keyframes fade-in-button{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes fade-in-equaliser{0%{opacity:0}to{opacity:1}}.obi-widget-panel .obi-course-progress-container{display:none;width:100%;max-height:0;opacity:0;transform:translateY(-10px);overflow:hidden;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel:hover .obi-course-progress-container{display:block;max-width:22 0px;animation:expand-course-progress .3s ease-in-out forwards}.obi-widget-panel:hover .obi-course-progress-container.expanded{max-width:330px}@keyframes expand-course-progress{0%{max-height:0;opacity:0;transform:translateY(-10px)}to{max-height:40px;opacity:1;transform:translateY(0)}}.obi-widget-pill-text{font-size:16px;font-weight:400;color:#fff;opacity:0;animation:fade-in-pill-text .3s ease-in-out forwards}@keyframes fade-in-pill-text{0%{opacity:0}40%{opacity:0}to{opacity:1}}.obi-widget-buttons{display:flex;flex-direction:row;gap:4px}.obi-widget-out-of-plan{display:flex;align-items:center;gap:4px}.obi-widget-out-of-plan .text{color:#fff;animation:fade-in-pill-text .3s ease-in-out forwards}.obi-widget-out-of-plan .round-button{display:none;animation:fade-in-button .2s ease-out .15s both}.obi-widget-out-of-plan .message{display:none}.obi-widget-out-of-plan.active:hover .round-button,.obi-widget-out-of-plan.active:hover .message,.obi-widget-out-of-plan.active.hover .round-button,.obi-widget-out-of-plan.active.hover .message{display:flex}.tour-select{display:block;font-family:Inter,sans-serif}.course-container{display:flex;padding:20px;align-items:flex-start;gap:8px;height:180px;border-radius:6px;border:1px solid rgba(0,0,0,.6);background:#fff;cursor:pointer;transition:all .2s;flex-direction:column;box-sizing:border-box;overflow:hidden}.course-container:hover{background-color:#f9fafb;border-color:#d1d5db;box-shadow:0 1px 2px #0000000d}.course-container:active{transform:scale(.98)}.course-container.selected{border-radius:6px;border:1px solid var(--obi-course-color-selected);background:var(--obi-course-color-tint)}.course-container.selected:hover{background:var(--obi-course-color-tint)}.header-row{display:flex;justify-content:space-between;align-items:flex-start;align-self:stretch;flex-shrink:0;text-align:left}.course-title{color:#000;font-family:Inter,sans-serif;font-size:20px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.2px;margin:0}.duration{display:flex;padding:4px 12px;justify-content:center;align-items:center;gap:8px;border-radius:9999px;background:var(--obi-course-color-tint);color:#000;font-family:Inter,sans-serif;font-size:14px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.14px;flex-shrink:0}.course-container.selected .duration{background:#fff}.course-description{flex:1 0 0;color:#0009;font-family:Inter,sans-serif;font-size:16px;font-style:normal;font-weight:400;line-height:140%;letter-spacing:-.16px;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;text-align:left}.course-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;padding:0;flex:1 0 0;align-self:stretch;min-height:364px}.controls{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.tabs{display:flex;gap:10px}.tab{display:flex;padding:6px 12px;justify-content:center;align-items:center;align-self:stretch;border:none;background:none;cursor:pointer;font-family:Inter,sans-serif;font-size:16px;font-weight:500;color:#0006;border-bottom:2px solid transparent;transition:all .2s}.tab.active{color:#000;border-bottom:2px solid var(--obi-color-primary)}.tab:hover{color:#000}.filter{position:relative;display:flex;align-items:center;width:336px;height:40px}.filter input{color:var(--obi-color-text);caret-color:var(--obi-color-text);padding:8px 12px 8px 36px;border-radius:6px;border:1px solid rgba(0,0,0,.1);background:#fff;font-family:Inter,sans-serif;font-size:14px;line-height:20px;width:100%;height:100%;box-sizing:border-box;outline:none}.filter input:focus{outline:1px solid var(--obi-color-primary);outline-offset:-1px}.filter input::placeholder{color:#0006}.filter svg{position:absolute;left:12px;pointer-events:none}@media (max-width: 767px){.course-grid{grid-template-columns:1fr}}.loading,.error,.empty{display:flex;justify-content:center;align-items:center;margin-top:16px}.error{color:#ef4444}.tour-select-modal-container{display:flex;flex-direction:column;align-items:center;gap:24px;flex:1 0 0;align-self:stretch;font-family:Satoshi,sans-serif;color:#000;text-align:center;max-width:1200px;width:100%;min-height:600px;box-sizing:border-box}.course-list-wrapper{flex:1;overflow-y:auto;width:100%;min-height:0;max-height:424px;padding-right:3px;box-sizing:border-box}.course-list-wrapper::-webkit-scrollbar{width:3px}.course-list-wrapper::-webkit-scrollbar-track{background:transparent}.course-list-wrapper::-webkit-scrollbar-thumb{background-color:#000;border-radius:2px;min-height:20px}.course-list-wrapper::-webkit-scrollbar-thumb:hover{background-color:#333}.header{display:flex;align-items:flex-start;gap:16px;width:100%;text-align:left}.icon{display:flex;width:56px;height:56px;padding:12px;justify-content:center;align-items:center;border-radius:12px;border:1px solid var(--obi-color-primary);background:var(--obi-color-primary);box-sizing:border-box}.icon img{width:32px;height:32px;color:#fff;fill:#fff}.title-section{align-self:stretch;flex:1}.tour-select-modal-container h1{color:#18181b;font-family:Satoshi;font-size:32px;font-style:normal;font-weight:700;line-height:90%;letter-spacing:-.96px;margin:0 0 8px}.subtitle{color:#18181b;font-family:Satoshi;font-size:20px;font-style:normal;font-weight:500;line-height:90%;letter-spacing:-.6px;margin:0}.footer{display:flex;width:360px;flex-direction:column;align-items:center;gap:12px}.footer-button{display:flex;height:48px;padding:16px;justify-content:center;align-items:center;gap:8px;align-self:stretch;border-radius:6px;background:#18181b;border:none;cursor:pointer;color:#fafafa;font-family:Satoshi;font-weight:500;transition:opacity .2s ease}.footer-button:disabled{opacity:.5;cursor:not-allowed}.footer-button:not(:disabled){opacity:1}.footer-button:not(:disabled):hover{background:#27272a}.footer-text{color:#18181b;font-family:Satoshi;font-size:12px;font-style:normal;font-weight:400;line-height:100%;letter-spacing:-.12px;margin:0;text-align:center}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%);background-size:200% 100%;animation:loading 1.5s infinite;border-radius:4px}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.skeleton-title{height:32px;width:60%;margin-bottom:12px}.skeleton-subtitle{height:20px;width:80%}
|
|
47
47
|
`;var wt,se,Ao,Th,Pn=0,Fh=[],pe=K,Ih=pe.__b,xh=pe.__r,_h=pe.diffed,Ph=pe.__c,Rh=pe.unmount,Lh=pe.__;function Rn(t,e){pe.__h&&pe.__h(se,t,Pn||e),Pn=0;var A=se.__H||(se.__H={__:[],__h:[]});return t>=A.__.length&&A.__.push({}),A.__[t]}function Z(t){return Pn=1,ky(Oh,t)}function ky(t,e,A){var n=Rn(wt++,2);if(n.t=t,!n.__c&&(n.__=[A?A(e):Oh(void 0,e),function(a){var o=n.__N?n.__N[0]:n.__[0],c=n.t(o,a);o!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=se,!se.__f)){var i=function(a,o,c){if(!n.__c.__H)return!0;var l=n.__c.__H.__.filter(function(d){return!!d.__c});if(l.every(function(d){return!d.__N}))return!r||r.call(this,a,o,c);var u=n.__c.props!==a;return l.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(u=!0)}}),r&&r.call(this,a,o,c)||u};se.__f=!0;var r=se.shouldComponentUpdate,s=se.componentWillUpdate;se.componentWillUpdate=function(a,o,c){if(this.__e){var l=r;r=void 0,i(a,o,c),r=l}s&&s.call(this,a,o,c)},se.shouldComponentUpdate=i}return n.__N||n.__}function Ge(t,e){var A=Rn(wt++,3);!pe.__s&&ro(A.__H,e)&&(A.__=t,A.u=e,se.__H.__h.push(A))}function to(t,e){var A=Rn(wt++,4);!pe.__s&&ro(A.__H,e)&&(A.__=t,A.u=e,se.__h.push(A))}function QA(t){return Pn=5,no(function(){return{current:t}},[])}function no(t,e){var A=Rn(wt++,7);return ro(A.__H,e)&&(A.__=t(),A.__H=e,A.__h=t),A.__}function Ty(t,e){return Pn=8,no(function(){return t},e)}function Dh(t){var e=se.context[t.__c],A=Rn(wt++,9);return A.c=t,e?(A.__==null&&(A.__=!0,e.sub(se)),e.props.value):t.__}function Fy(){for(var t;t=Fh.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Qr),t.__H.__h.forEach(io),t.__H.__h=[]}catch(e){t.__H.__h=[],pe.__e(e,t.__v)}}pe.__b=function(t){se=null,Ih&&Ih(t)},pe.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Lh&&Lh(t,e)},pe.__r=function(t){xh&&xh(t),wt=0;var e=(se=t.__c).__H;e&&(Ao===se?(e.__h=[],se.__h=[],e.__.forEach(function(A){A.__N&&(A.__=A.__N),A.u=A.__N=void 0})):(e.__h.forEach(Qr),e.__h.forEach(io),e.__h=[],wt=0)),Ao=se},pe.diffed=function(t){_h&&_h(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Fh.push(e)!==1&&Th===pe.requestAnimationFrame||((Th=pe.requestAnimationFrame)||Iy)(Fy)),e.__H.__.forEach(function(A){A.u&&(A.__H=A.u),A.u=void 0})),Ao=se=null},pe.__c=function(t,e){e.some(function(A){try{A.__h.forEach(Qr),A.__h=A.__h.filter(function(n){return!n.__||io(n)})}catch(n){e.some(function(i){i.__h&&(i.__h=[])}),e=[],pe.__e(n,A.__v)}}),Ph&&Ph(t,e)},pe.unmount=function(t){Rh&&Rh(t);var e,A=t.__c;A&&A.__H&&(A.__H.__.forEach(function(n){try{Qr(n)}catch(i){e=i}}),A.__H=void 0,e&&pe.__e(e,A.__v))};var Hh=typeof requestAnimationFrame=="function";function Iy(t){var e,A=function(){clearTimeout(n),Hh&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(A,100);Hh&&(e=requestAnimationFrame(A))}function Qr(t){var e=se,A=t.__c;typeof A=="function"&&(t.__c=void 0,A()),se=e}function io(t){var e=se;t.__c=t.__(),se=e}function ro(t,e){return!t||t.length!==e.length||e.some(function(A,n){return A!==t[n]})}function Oh(t,e){return typeof e=="function"?e(t):e}function xy({size:t=24,color:e="#000"}){return g("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:e,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-x-icon lucide-x",children:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]})}function Mh({onClose:t}){return g("button",{class:"obi-button obi-close-button",onClick:t,"aria-label":"Close",type:"button",children:g(xy,{})})}function Nh({open:t=!1,children:e,onClose:A,size:n="medium"}){const i=QA(null),r=QA(null);Ge(()=>{const c=i.current;c&&(t&&!c.open?c.showModal():!t&&c.open&&(r.current="programmatic",c.close()))},[t]);const s=c=>{const l=i.current;c.target===l&&(r.current="user-initiated",l==null||l.close())},a=c=>{c.preventDefault(),r.current||(r.current="user-initiated");const l=r.current;r.current=null,A==null||A(l)},o=()=>{var c;r.current="user-initiated",(c=i.current)==null||c.close()};return Ge(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",a),()=>{c.removeEventListener("click",s),c.removeEventListener("close",a)}},[A]),g("dialog",{ref:i,className:`modal-${n}`,children:[g(Mh,{onClose:o}),g("div",{class:"modal-content",children:t?typeof e=="function"?e():e:null})]})}function so(t){const{children:e,className:A="",...n}=t;return g("div",{className:`${A} obi-panel`,...n,children:e})}function ao({className:t="",isActive:e=!1,speakingStatus:A,onClick:n,onMouseEnter:i,onMouseLeave:r,children:s}){let a=`obi-pill container ${e&&"active"}`;return A==="user-speaking"&&(a+=" user-speaking"),A==="busy"&&(a+=" busy"),g("div",{className:a,onMouseEnter:i,onMouseLeave:r,children:g("div",{className:`obi-pill pill ${t}`,onClick:n,children:s})})}function Kh({className:t="",active:e,speakingStatus:A,onClick:n,onMouseEnter:i,onMouseLeave:r,children:s,...a}){const o=`obi-pill2 container ${e?"active":""} ${A==="user-speaking"?"user-speaking":""} ${t}`;return g("div",{className:o,...a,children:g("div",{className:"pill",onClick:n,onMouseEnter:i,onMouseLeave:r,children:s})})}function bt({type:t,size:e=24}){return g("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:_y(t)})}function _y(t){switch(t){case"pause":return g(Pe,{children:[g("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),g("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return g(Pe,{children:g("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return g(Pe,{children:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]});case"message":return g(Pe,{children:g("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return g(Pe,{children:[g("path",{d:"m14 10 7-7"}),g("path",{d:"M20 10h-6V4"}),g("path",{d:"m3 21 7-7"}),g("path",{d:"M4 14h6v6"})]});case"voice":return g(Pe,{children:[g("path",{d:"M2 10v3"}),g("path",{d:"M6 6v11"}),g("path",{d:"M10 3v18"}),g("path",{d:"M14 8v7"}),g("path",{d:"M18 5v13"}),g("path",{d:"M22 10v3"})]});case"open":return g(Pe,{children:[g("path",{d:"M12 7v14"}),g("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const oo=Qy(null);function Py({children:t}){const e=Dh(oo);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:A,isOpen:n,setIsOpen:i,setAnimating:r,targetRef:s,trigger:a,onChange:o,delayMs:c}=e,l=QA(null),u=Vh(s,r),[d,h]=Z(!1);Ge(()=>{A!==void 0&&A!==d&&(A?f():m()),h(A)},[A]),Ge(()=>()=>{l.current&&clearTimeout(l.current)},[]);function p(){l.current&&(clearTimeout(l.current),l.current=null)}function f(){p(),c>0?l.current=setTimeout(()=>{o==null||o(!0),i(!0),l.current=null},c):(o==null||o(!0),i(!0))}function m(){p(),o==null||o(!1),i(!1)}const B=()=>{a==="click"&&(n?m():f())};function b(){a==="hover"&&f()}function U(){a==="hover"&&m()}return g("div",{ref:u,class:"target",onClick:B,onMouseEnter:b,onMouseLeave:U,children:t})}function Ry({children:t}){const e=Dh(oo);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:A,animating:n,setAnimating:i,targetRef:r,contentRef:s}=e,a=Vh(s,i);return to(()=>{if(A&&!n&&r.current&&s.current){const o=s.current;if(!o)return;const c=r.current;if(!c)return;const l=o.getBoundingClientRect(),u=c.getBoundingClientRect(),d=u.right-u.left;o.style.top=`${l.top-l.bottom-(8+e.offset)}px`,o.style.left=`${-(l.right-l.left-d)/2}px`}},[A,n]),A?g("div",{ref:a,class:"content",style:{opacity:n?0:1},children:t}):null}function je({trigger:t="click",open:e,onChange:A,children:n,delayMs:i=0,offset:r=0,className:s=""}){const[a,o]=Z(!1),[c,l]=Z(!1),u=QA(null),d=QA(null),h={controlledOpen:e,isOpen:a,setIsOpen:o,animating:c,setAnimating:l,targetRef:u,contentRef:d,trigger:t,onChange:A,delayMs:i,offset:r};return g(oo.Provider,{value:h,children:g("div",{class:`obi-popout ${s}`,children:n})})}je.Target=Py,je.Content=Ry;function Vh(t,e){const A=QA(null),n=QA(null),i=QA(!0),r=Ty(s=>{if(t.current=s,!s){n.current&&(n.current.disconnect(),n.current=null),i.current=!0;return}function a(){if(i.current){i.current=!1;return}A.current?clearTimeout(A.current):e(!0),A.current=setTimeout(()=>{e(!1),A.current=null},200)}n.current=new ResizeObserver(a),n.current.observe(s,{box:"border-box"})},[]);return Ge(()=>()=>{n.current&&(n.current.disconnect(),n.current=null)},[]),r}function gA({className:t,onClick:e,type:A,disabled:n,title:i}){const r={cancel:g(bt,{type:"close",size:16}),pause:g(bt,{type:"pause",size:16}),play:g(bt,{type:"play",size:16}),message:g(bt,{type:"message",size:16}),minimize:g(bt,{type:"minimize",size:16}),voice:g(bt,{type:"voice",size:16}),open:g(bt,{type:"open",size:16})}[A],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[A],a=g("button",{class:`obi-button obi-round-button ${s} ${t}`,onClick:n?void 0:e,disabled:n,children:r});return i?g(je,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[g(je.Target,{children:a}),g(je.Content,{children:g("div",{className:"obi-round-button-title",children:i})})]}):a}const Gh=8,Er=8,Ly=50,Dy=.7,zt=3;function jh({getBands:t,color:e="white"}){const A=QA(null);return Ge(()=>{if(!t)return;const n=setInterval(()=>{try{const i=t();if(!A.current)return;const r=A.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,Er).map(a=>{const o=Math.abs(a);return Math.min(o/Dy*Gh,Gh)||zt}):Array(Er).fill(zt);for(;s.length<Er;)s.push(zt);s.forEach((a,o)=>{if(a<zt&&(a=zt),r[o]){const c=a*2;r[o].style.height=`${c}px`,r[o].style.display=a>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},Ly);return()=>{clearInterval(n)}},[t]),g("div",{className:"obi-equaliser",ref:A,children:Array.from({length:Er},(n,i)=>g("div",{className:"column",children:g("div",{className:"bar",style:{height:`${zt}px`,backgroundColor:e,display:"block"}})},i))})}function Ln({className:t,children:e,onClick:A}){return A?g("button",{class:`obi-button obi-message ${t} clickable`,onClick:A,children:e}):g("div",{class:`obi-message ${t}`,children:e})}const Hy=8;function Wh({color:t="white"}){return g("div",{className:"obi-loading-dots",children:Array.from({length:Hy},(e,A)=>g("div",{className:"column",children:[g("div",{className:"bar",style:{backgroundColor:t,animationDelay:`${A*.15}s`}}),g("div",{className:"dot",style:{backgroundColor:t}})]},A))})}function Oy({onContinue:t,onWrapUp:e}){return g(so,{className:"obi-exit-survey",children:g(Ny,{onContinue:t,onWrapUp:()=>{e()}})})}function My({onReasonSelect:t,onClose:e}){const[A,n]=Z("reason"),i=r=>{r==="other"?n("other-reason"):t(r)};return g(so,{className:`obi-exit-survey ${A==="reason"?"obi-exit-survey-reason":""}`,children:A==="reason"?g(Ky,{onReasonSelect:i}):g(Vy,{onReasonSelect:i,onClose:e})})}function Ny({onContinue:t,onWrapUp:e}){return g("div",{className:"obi-exit-survey-container",children:[g("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),g("div",{className:"obi-exit-survey-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:t,type:"button",children:"No, let's continue"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function Ky({onReasonSelect:t}){return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("testing"),type:"button",children:"Will do later"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("no-time"),type:"button",children:"Can't talk right now"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("format-mismatch"),type:"button",children:"Prefer written instructions"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("technical-issue"),type:"button",children:"Experienced technical issues"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("other"),type:"button",children:"Other"})]})]})}function Vy({onReasonSelect:t,onClose:e}){return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:[g(Mh,{onClose:e}),g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>t("other-feedback"),type:"button",children:"Send feedback"})]})]})}function Gy(t,e){for(var A in e)t[A]=e[A];return t}function Jh(t,e){for(var A in t)if(A!=="__source"&&!(A in e))return!0;for(var n in e)if(n!=="__source"&&t[n]!==e[n])return!0;return!1}function Xh(t,e){this.props=t,this.context=e}(Xh.prototype=new RA).isPureReactComponent=!0,Xh.prototype.shouldComponentUpdate=function(t,e){return Jh(this.props,t)||Jh(this.state,e)};var qh=K.__b;K.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),qh&&qh(t)};var jy=K.__e;K.__e=function(t,e,A,n){if(t.then){for(var i,r=e;r=r.__;)if((i=r.__c)&&i.__c)return e.__e==null&&(e.__e=A.__e,e.__k=A.__k),i.__c(t,e)}jy(t,e,A,n)};var Yh=K.unmount;function zh(t,e,A){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),t.__c.__H=null),(t=Gy({},t)).__c!=null&&(t.__c.__P===A&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(n){return zh(n,e,A)})),t}function Zh(t,e,A){return t&&A&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return Zh(n,e,A)}),t.__c&&t.__c.__P===e&&(t.__e&&A.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=A)),t}function co(){this.__u=0,this.o=null,this.__b=null}function $h(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Sr(){this.i=null,this.l=null}K.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Yh&&Yh(t)},(co.prototype=new RA).__c=function(t,e){var A=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(A);var i=$h(n.__v),r=!1,s=function(){r||(r=!0,A.__R=null,i?i(a):a())};A.__R=s;var a=function(){if(!--n.__u){if(n.state.__a){var o=n.state.__a;n.__v.__k[0]=Zh(o,o.__c.__P,o.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),t.then(s,s)},co.prototype.componentWillUnmount=function(){this.o=[]},co.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var A=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=zh(this.__b,A,n.__O=n.__P)}this.__b=null}var i=e.__a&&za(Pe,null,t.fallback);return i&&(i.__u&=-33),[za(Pe,null,e.__a?null:t.children),i]};var ef=function(t,e,A){if(++A[1]===A[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(A=t.i;A;){for(;A.length>3;)A.pop()();if(A[1]<A[0])break;t.i=A=A[2]}};(Sr.prototype=new RA).__a=function(t){var e=this,A=$h(e.__v),n=e.l.get(t);return n[0]++,function(i){var r=function(){e.props.revealOrder?(n.push(i),ef(e,t,n)):i()};A?A(r):r()}},Sr.prototype.render=function(t){this.i=null,this.l=new Map;var e=yr(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var A=e.length;A--;)this.l.set(e[A],this.i=[1,0,this.i]);return t.children},Sr.prototype.componentDidUpdate=Sr.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,A){ef(t,A,e)})};var Wy=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Jy=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Xy=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,qy=/[A-Z0-9]/g,Yy=typeof document<"u",zy=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};RA.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(RA.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Af=K.event;function Zy(){}function $y(){return this.cancelBubble}function eU(){return this.defaultPrevented}K.event=function(t){return Af&&(t=Af(t)),t.persist=Zy,t.isPropagationStopped=$y,t.isDefaultPrevented=eU,t.nativeEvent=t};var AU={enumerable:!1,configurable:!0,get:function(){return this.class}},tf=K.vnode;K.vnode=function(t){typeof t.type=="string"&&function(e){var A=e.props,n=e.type,i={},r=n.indexOf("-")===-1;for(var s in A){var a=A[s];if(!(s==="value"&&"defaultValue"in A&&a==null||Yy&&s==="children"&&n==="noscript"||s==="class"||s==="className")){var o=s.toLowerCase();s==="defaultValue"&&"value"in A&&A.value==null?s="value":s==="download"&&a===!0?a="":o==="translate"&&a==="no"?a=!1:o[0]==="o"&&o[1]==="n"?o==="ondoubleclick"?s="ondblclick":o!=="onchange"||n!=="input"&&n!=="textarea"||zy(A.type)?o==="onfocus"?s="onfocusin":o==="onblur"?s="onfocusout":Xy.test(s)&&(s=o):o=s="oninput":r&&Jy.test(s)?s=s.replace(qy,"-$&").toLowerCase():a===null&&(a=void 0),o==="oninput"&&i[s=o]&&(s="oninputCapture"),i[s]=a}}n=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=yr(A.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),n=="select"&&i.defaultValue!=null&&(i.value=yr(A.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),A.class&&!A.className?(i.class=A.class,Object.defineProperty(i,"className",AU)):(A.className&&!A.class||A.class&&A.className)&&(i.class=i.className=A.className),e.props=i}(t),t.$$typeof=Wy,tf&&tf(t)};var nf=K.__r;K.__r=function(t){nf&&nf(t),t.__c};var rf=K.diffed;K.diffed=function(t){rf&&rf(t);var e=t.props,A=t.__e;A!=null&&t.type==="textarea"&&"value"in e&&e.value!==A.value&&(A.value=e.value==null?"":e.value)};function tU(t){const{placeholder:e="Type your message...",value:A,defaultValue:n,onChange:i,onSend:r,onCancel:s,onExpand:a,isLoading:o=!1,disabled:c=!1,maxLength:l=500,children:u}=t,[d,h]=Z(A||n||""),[p,f]=Z((A||n||"").length>24),m=QA(null);to(()=>{p&&(a==null||a(!0))},[]);const B=A!==void 0?A:d,b=v=>{const y=v.currentTarget.value;A===void 0&&h(y),i==null||i(y)},U=v=>{v.key==="Escape"&&(h(A||n||""),f(!1),s==null||s()),v.key==="Enter"&&!v.shiftKey&&B.trim()&&(v.preventDefault(),h(A||n||""),f(!1),w()),(B||"").length>=24&&!p&&(f(!0),a==null||a(!0))};Ge(()=>{m.current&&m.current.focus()},[m.current]);const w=()=>{!B.trim()||o||c||(r==null||r(B.trim()),A===void 0&&h(""))};return g("div",{className:`obi-message-input ${p?"expanded":""}`,children:[g("div",{className:"container",children:g("textarea",{ref:m,className:"field",placeholder:e,value:B,onInput:b,onKeyDown:U,disabled:c||o,maxLength:l,rows:1})}),g("div",{className:"button-container",children:[p&&g("div",{children:u}),g("button",{className:"obi-button send",onClick:w,disabled:!B.trim()||o||c,type:"button",children:g("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function nU(t){const{currentStep:e,totalSteps:A,stepNames:n,className:i}=t,r=Array.from({length:A},(o,c)=>({isCompleted:c<e,stepNumber:c+1})),s=n[e-1]||`Step ${e}`,a=`${e}/${A} • ${s}`;return g("div",{class:`obi-course-progress ${i||""}`,children:[g("div",{class:"obi-course-progress-steps",children:r.map((o,c)=>g("div",{class:"obi-course-progress-container",children:g("div",{class:`obi-course-progress-step ${o.isCompleted?"completed":""}`})},c))}),g("div",{class:"obi-course-progress-description",children:a})]})}function iU(t){const{disabled:e,inPlan:A,isPaused:n}=t,[i,r]=Z(null),[s,a]=Z(t.isActive??t.defaultIsActive??!1),[o,c]=Z(!1),[l,u]=Z(t.cancelling??!1),[d,h]=Z(t.messaging??!1),[p,f]=Z(!1),[m,B]=Z(!1);to(()=>{t.messaging!==void 0&&h(t.messaging)},[t.messaging]);function b(){a(!0),c(!1),B(!0),t.messaging!==void 0&&h(t.messaging)}function U(){}function w(){i&&(clearTimeout(i),r(null))}function v(){r(setTimeout(()=>{a(t.defaultIsActive??!1),B(!1)},400))}function y(oe){var Je;f(!1),(Je=t.onMessage)==null||Je.call(t,oe)}function E(){h(!1),f(!1),a(!1),c(!0)}function T(){h(!1),u(!0),f(!1)}function F(){var oe;A||((oe=t.onOpen)==null||oe.call(t))}function R(){var oe;(oe=t.onMessage)==null||oe.call(t,"Okay, let's continue.")}function D(oe){var Je;t.messaging===void 0&&((Je=t.onMessagingChange)==null||Je.call(t,oe),h(oe)),oe||f(!1)}const O=t.isActive??((s||A)&&!o&&!e),M=O&&A,ae=O&&A&&!p,N=t.speakingStatus==="user-speaking",V=t.speakingStatus==="thinking",Fe=t.speakingStatus==="busy",ve=O&&!A&&!l&&m,Ce=O&&A&&n&&!N&&!l,tA=O&&A&&n&&N&&!l,Le=O&&A&&!n&&N&&!l,we=O&&A&&!n&&Fe&&!l,nA=d&&N,Ye=ve||Ce||tA||Le||l,Ie=400,it=O&&A&&!p,We=ve?5:10;return!A&&!l?g(rU,{...t}):!A&&l?g(sU,{onCancelReason:oe=>{var Je;a(t.defaultIsActive??!1),u(!1),(Je=t.onCancelReason)==null||Je.call(t,oe)},onClose:()=>{a(t.defaultIsActive??!1),u(!1)}}):g(so,{className:`obi-widget-panel ${M?"expanded":""} ${p?"maximized":""} ${d?"messaging":""} ${Fe?"tool-usage":""}`,children:[g("div",{className:`obi-widget ${O?"active":""} ${A?"in-plan":""}`,onMouseEnter:w,onMouseLeave:v,children:[ae&&g(gA,{type:"cancel",onClick:T,disabled:l,title:"Cancel session"}),ae&&!n&&g(gA,{type:"pause",onClick:t.onPause,title:"Pause session"}),ae&&n&&g(gA,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),g(je,{className:"obi-widget-popout",open:Ye,trigger:null,delayMs:Ie,offset:We,children:[g(je.Target,{children:[nA&&g(tU,{value:t.message,defaultValue:"Okay, let's continue.",onCancel:()=>D(!1),onSend:y,onExpand:f,children:g("div",{className:"obi-widget-buttons",children:[g(gA,{type:"cancel",onClick:T,disabled:l,title:"Cancel session"}),!n&&g(gA,{type:"pause",onClick:t.onPause,title:"Pause session"}),n&&g(gA,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),g(gA,{type:d?"voice":"message",disabled:!N||t.messaging!==void 0,onClick:()=>D(!d),title:d?"Voice input":"Text input"}),g(gA,{type:"minimize",onClick:E,title:"Minimize widget"})]})}),!nA&&g(ao,{className:O&&!A?"button":"",isActive:O,speakingStatus:t.speakingStatus,onClick:F,onMouseEnter:b,onMouseLeave:U,children:[O&&!A&&!we&&g("span",{className:"obi-widget-pill-text",children:"Tutorials"}),O&&A&&we&&g("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),O&&A&&!V&&!we&&g(jh,{getBands:t.spectrum}),O&&V&&!we&&g(Wh,{})]})]}),g(je.Content,{children:g("div",{onMouseLeave:v,children:[ve&&g(Ln,{onClick:F,children:"Click to see all"}),Ce&&g(Ln,{children:"Session will pause shortly"}),tA&&g(Ln,{children:"Paused"}),Le&&g(Ln,{onClick:R,children:"Ready to continue?"}),l&&g(Oy,{onContinue:()=>{u(!1),t.messaging!==void 0&&h(t.messaging)},onWrapUp:()=>{var oe;(oe=t.onCancel)==null||oe.call(t)}})]})})]}),ae&&g(gA,{type:d?"voice":"message",disabled:!N||t.messaging!==void 0,onClick:()=>D(!d),title:d?"Voice input":"Text input"}),ae&&g(gA,{type:"minimize",onClick:E,title:"Minimize widget"})]}),it&&t.courseProgress&&g("div",{className:`obi-course-progress-container ${d?"expanded":""}`,children:g(nU,{currentStep:t.courseProgress.currentStep,totalSteps:t.courseProgress.totalSteps,stepNames:t.courseProgress.stepNames})})]})}function rU(t){const{disabled:e}=t,[A,n]=Z(null),[i,r]=Z(t.isActive??t.defaultIsActive??!1),[s,a]=Z(!1),[o,c]=Z(t.hovered??!1);function l(){r(!0),a(!1),c(!0)}function u(){}function d(){A&&(clearTimeout(A),n(null))}function h(){i&&n(setTimeout(()=>{r(t.defaultIsActive??!1),c(!1)},400))}function p(){r(!1),a(!0)}function f(){var w;(w=t.onOpen)==null||w.call(t)}const m=t.hovered??(o&&!s),B=t.isActive??(i&&!e&&!s),b=B&&m,U=`round-button ${B?"active":""}`;return g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:`obi-widget-out-of-plan ${m?"hover":""} ${B?"active":""}`,onMouseEnter:d,onMouseLeave:h,children:[g("div",{className:U,style:{width:"27px",height:"30px"}}),g(je,{className:"obi-widget-popout",open:b,trigger:null,delayMs:400,offset:5,children:[g(je.Target,{children:g(Kh,{className:B?"button":"",active:B,onClick:f,onMouseEnter:l,onMouseLeave:u,children:B&&g("span",{className:"text",children:"Tutorials"})})}),g(je.Content,{children:g("div",{onMouseLeave:h,children:g(Ln,{className:"message",onClick:f,children:"Click to see all"})})})]}),g(gA,{className:U,type:"minimize",onClick:p,title:"Minimize widget"})]})})}function sU(t){return g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:"obi-widget-out-of-plan",children:g(je,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[g(je.Target,{children:g(Kh,{active:!1})}),g(je.Content,{children:g(My,{onReasonSelect:e=>{var A;(A=t.onCancelReason)==null||A.call(t,e)},onClose:()=>{var e;(e=t.onClose)==null||e.call(t)}})})]})})})}function aU({open:t=!1,children:e,onClose:A}){return g(Nh,{open:t,onClose:A,children:g("div",{className:"tour content-area",children:t?typeof e=="function"?e():e:null})})}function Zt({title:t="",subtitle:e="",agentName:A="Obi",buttonText:n="Continue",speakingState:i=null,actionDisabled:r=!1,href:s=null,centerVisual:a,description:o,button:c,onAction:l}){const[u,d]=Z(r),[h,p]=Z(!1),[f,m]=Z(i);return Ge(()=>{h||(i==="listening"&&f!=="listening"&&u&&d(!1),i!=="listening"&&!u&&d(!0)),m(i)},[i,u]),Ge(()=>{d(r)},[r]),g("div",{className:"tour-content",children:g("div",{className:"container",children:[g("div",{className:"header",children:[g("h1",{className:"title",children:t}),g("p",{className:"subtitle",children:e})]}),g("div",{className:"visual",style:{background:"var(--obi-color-tint)"},children:a}),g("div",{className:"description",children:o}),g("div",{className:"button-container",children:c||g(s?"a":"button",{className:`action-button ${u?"disabled":""}`,onClick:()=>{u||(d(!0),p(!0),l==null||l())},disabled:u,...s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:g("span",{className:"button-text",children:(()=>{switch(i){case"thinking":return"Loading...";case"speaking":return`${A} is speaking`;default:return n}})()})})})]})})}function oU({logoUrl:t="",appName:e="App"}){const[A,n]=Z(!1),[i,r]=Z(!1),s=()=>{n(!0)},a=()=>{r(!0),n(!1)},o={container:{display:"block"},logoContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden"},backgroundPattern:{position:"absolute",inset:0,zIndex:0,background:"#F5F5F5",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='277' height='195' viewBox='0 0 277 195' fill='none'%3E%3Cpath opacity='0.4' d='M341.308 0.75C380.279 0.750001 411.872 24.3772 411.872 53.5229C411.872 82.6685 380.279 106.296 341.308 106.296H215.792C176.964 108.335 145.691 130.837 141.128 159.475V256.616C145.912 286.659 180.089 309.954 221.548 309.954H330.872C375.607 309.954 411.872 282.833 411.872 249.377V159.069C411.872 129.923 443.465 106.296 482.436 106.296C521.407 106.296 553 129.923 553 159.069V257.181C553 285.058 524.099 307.88 487.483 309.815C489.264 309.902 491.061 309.954 492.871 309.954C448.137 309.954 411.872 337.076 411.872 370.532C411.872 369.177 411.803 367.834 411.686 366.502C409.098 393.885 378.582 415.5 341.308 415.5H210.118C171.147 415.5 139.554 391.873 139.554 362.727C139.554 362.204 139.565 361.683 139.585 361.163C133.564 332.156 100.023 309.954 59.5488 309.954C61.4544 309.954 63.3441 309.9 65.2169 309.803C28.7434 307.76 -8.57239e-07 284.982 0 257.181V159.069C1.64632e-06 130.901 29.5078 107.89 66.6662 106.377C64.3207 106.224 61.9472 106.141 59.5488 106.141C100.012 106.141 133.54 83.951 139.575 54.9552C139.558 54.4793 139.554 54.0018 139.554 53.5229C139.554 24.3772 171.147 0.75 210.118 0.75H341.308Z' fill='white'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"190px 60px",backgroundSize:"300px 225px"},logoWrapper:{background:"#888888",width:"120px",height:"120px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",zIndex:10,overflow:"hidden"},appLogo:{width:"120px",height:"120px",objectFit:"cover",display:t&&!A&&i?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!t||A||!i?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return g("div",{style:o.container,children:g("div",{style:o.logoContainer,children:[g("div",{style:o.backgroundPattern}),g("div",{style:o.logoWrapper,children:[t&&g("img",{style:o.appLogo,src:t,alt:`${e} logo`,onError:s,onLoad:a}),g("div",{style:o.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function cU({session:t,speakingState:e,onAction:A}){const n=t.appName?`Navigate to ${t.appName}`:"Navigate to app",i=t.appName?`Open ${t.appName}`:"Open app",r=t.appName?`Enjoy the tutorial in ${t.appName}`:"Enjoy the tutorial";return g(Zt,{title:n,subtitle:"Click the button below to open the app",agentName:t.agentName||"Obi",buttonText:i,speakingState:e,actionDisabled:!0,href:t.url,description:r,centerVisual:g(oU,{logoUrl:t.appLogoUrl,appName:t.appName}),onAction:A})}function sf({className:t=""}){return g("svg",{width:"64",height:"64",viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,children:g("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function lU({children:t}){const e={container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"flex",width:"120px",height:"120px",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",borderRadius:"8px",color:"#FFFFFF",position:"relative",overflow:"hidden",background:"var(--obi-color-primary)",boxShadow:`
|
|
48
48
|
0 0 20px color-mix(in srgb, var(--obi-color-primary) 20%, transparent),
|
|
49
49
|
0 0 40px color-mix(in srgb, var(--obi-color-primary) 15%, transparent),
|