obi-sdk 0.19.8 → 0.19.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/obi-sdk.standalone.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const A=i.sdp.split(`
|
|
|
39
39
|
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
|
40
40
|
`);n.RTCSessionDescription&&i instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:i.type,sdp:A}):i.sdp=A}return t.apply(this,arguments)}}function ta(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.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():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function na(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.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"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>t.apply(this,[s]))})}var hF=Object.freeze({__proto__:null,removeExtmapAllowMixed:Bl,shimAddIceCandidateNullOrEmpty:ta,shimConnectionState:Cl,shimMaxMessageSize:$o,shimParameterlessSetLocalDescription:na,shimRTCIceCandidate:Zo,shimRTCIceCandidateRelayProtocol:bl,shimSendThrowTypeError:ea});function pF(){let{window:n}=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 t=sv,r=cF(n),i={browserDetails:r,commonShim:hF,extractVersion:Yo,disableLog:oF,disableWarnings:aF,sdp:dF};switch(r.browser){case"chrome":if(!yv||!vl||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(r.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=yv,ta(n,r),na(n),lv(n,r),dv(n),vl(n,r),hv(n),mv(n,r),pv(n),fv(n),vv(n,r),Zo(n),bl(n),Cl(n),$o(n,r),ea(n),Bl(n,r);break;case"firefox":if(!Iv||!yl||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=Iv,ta(n,r),na(n),wv(n,r),yl(n,r),bv(n),_v(n),Cv(n),Bv(n),Sv(n),kv(n),Ev(n),Uv(n),Tv(n),Zo(n),Cl(n),$o(n,r),ea(n);break;case"safari":if(!Nv||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Nv,ta(n,r),na(n),Ov(n),Dv(n),Qv(n),Fv(n),xv(n),Lv(n),Rv(n),Mv(n),Zo(n),bl(n),$o(n,r),ea(n),Bl(n,r);break;default:t("Unsupported browser!");break}return i}pF({window:typeof window>"u"?void 0:window});const fF=10,ra="lk_e2ee",gF={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:fF,keyringSize:16};var gr;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(gr||(gr={}));var Vv;(function(n){n.KeyRatcheted="keyRatcheted"})(Vv||(Vv={}));var mr;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(mr||(mr={}));var Gv;(function(n){n.Error="cryptorError"})(Gv||(Gv={}));function mF(){return vF()||_l()}function _l(){return typeof window.RTCRtpScriptTransform<"u"}function vF(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class x4 extends Un.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,r,i)=>{ue.debug("key ratcheted event received",{ratchetResult:t,participantId:r,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},gF),e),this.on(gr.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,r){const i={key:e,participantIdentity:t,keyIndex:r};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(r??0),i),this.emit(gr.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(gr.RatchetRequest,e,t)}}class vr extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var de;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest"})(de||(de={}));class Qe extends vr{constructor(e,t,r,i){super(1,e),this.name="ConnectionError",this.status=r,this.reason=t,this.context=i,this.reasonName=de[t]}}class Sl extends vr{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Vn extends vr{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class yF extends vr{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ut extends vr{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class kl extends vr{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class El extends vr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class jv extends vr{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:pl[t]}}var ia;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(ia||(ia={})),function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e}(ia||(ia={}));var Wv;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Wv||(Wv={}));var L;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(L||(L={}));var V;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(V||(V={}));var N;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(N||(N={}));var M;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate"})(M||(M={}));function wF(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const bF=/version\/(\d+(\.?_?\d+)+)/i;let Ul;function dn(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(Ul===void 0||e){const r=CF.find(i=>{let{test:A}=i;return A.test(t)});Ul=r==null?void 0:r.describe(t)}return Ul}const CF=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Aa(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Tl(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Aa(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Tl(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Aa(bF,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Tl(n)}}}];function Aa(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const r=e.match(n);return r&&r.length>=t&&r[t]||""}function Tl(n){return n.includes("mac os")?Aa(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var BF="2.13.0";const _F=BF,SF=16;class yt{}yt.setTimeout=function(){return setTimeout(...arguments)},yt.setInterval=function(){return setInterval(...arguments)},yt.clearTimeout=function(){return clearTimeout(...arguments)},yt.clearInterval=function(){return clearInterval(...arguments)};const kF=5e3,WA=[];var $t;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})($t||($t={}));class R extends Un.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=R.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ue,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),kF):this.handleAppVisibilityChanged()},this.log=Kn((i=r.loggerName)!==null&&i!==void 0?i:ln.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=R.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Be(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===R.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===R.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(WA.forEach(A=>{A.parentElement===null&&!e&&(e=A)}),e&&WA.splice(WA.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Di(this.mediaStreamTrack,e);const r=e.srcObject.getTracks(),i=r.some(A=>A.kind==="audio");return e.play().then(()=>{this.emit(i?M.AudioPlaybackStarted:M.VideoPlaybackStarted)}).catch(A=>{A.name==="NotAllowedError"?this.emit(i?M.AudioPlaybackFailed:M.VideoPlaybackFailed,A):A.name==="AbortError"?ue.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):ue.warn("could not playback ".concat(i?"audio":"video"),A),i&&e&&r.some(s=>s.kind==="video")&&A.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(M.ElementAttached,e),e}detach(e){try{if(e){Mi(this.mediaStreamTrack,e);const r=this.attachedElements.indexOf(e);return r>=0&&(this.attachedElements.splice(r,1),this.recycleElement(e),this.emit(M.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(r=>{Mi(this.mediaStreamTrack,r),t.push(r),this.recycleElement(r),this.emit(M.ElementDetached,r)}),this.attachedElements=[],t}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=Kn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),WA.forEach(r=>{r.parentElement||(t=!1)}),t&&WA.push(e)}}handleAppVisibilityChanged(){return S(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===R.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Kt()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Kt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Di(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let r;n.kind==="audio"?r=t.getAudioTracks():r=t.getVideoTracks(),r.includes(n)||(r.forEach(i=>{t.removeTrack(i)}),t.addTrack(n)),(!yr()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(yr()||Ni())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Mi(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=n.Source||(n.Source={}));let r;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(r=n.StreamState||(n.StreamState={}));function i(c){switch(c){case e.Audio:return on.AUDIO;case e.Video:return on.VIDEO;default:return on.DATA}}n.kindToProto=i;function A(c){switch(c){case on.AUDIO:return e.Audio;case on.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=A;function s(c){switch(c){case t.Camera:return ot.CAMERA;case t.Microphone:return ot.MICROPHONE;case t.ScreenShare:return ot.SCREEN_SHARE;case t.ScreenShareAudio:return ot.SCREEN_SHARE_AUDIO;default:return ot.UNKNOWN}}n.sourceToProto=s;function o(c){switch(c){case ot.CAMERA:return t.Camera;case ot.MICROPHONE:return t.Microphone;case ot.SCREEN_SHARE:return t.ScreenShare;case ot.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function a(c){switch(c){case ol.ACTIVE:return r.Active;case ol.PAUSED:return r.Paused;default:return r.Unknown}}n.streamStateFromProto=a})(R||(R={}));class Ie{constructor(e,t,r,i,A){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(t!==void 0&&r!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:r,maxFramerate:i,priority:A};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 EF=["vp8","h264"],UF=["vp8","h264","vp9","av1"];function TF(n){return!!EF.find(e=>e===n)}var qv;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(qv||(qv={}));var Il;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Il||(Il={}));const qA={h90:new Ie(160,90,9e4,20),h180:new Ie(320,180,16e4,20),h216:new Ie(384,216,18e4,20),h360:new Ie(640,360,45e4,20),h540:new Ie(960,540,8e5,25),h720:new Ie(1280,720,17e5,30),h1080:new Ie(1920,1080,3e6,30),h1440:new Ie(2560,1440,5e6,30),h2160:new Ie(3840,2160,8e6,30)},Fl={h120:new Ie(160,120,7e4,20),h180:new Ie(240,180,125e3,20),h240:new Ie(320,240,14e4,20),h360:new Ie(480,360,33e4,20),h480:new Ie(640,480,5e5,20),h540:new Ie(720,540,6e5,25),h720:new Ie(960,720,13e5,30),h1080:new Ie(1440,1080,23e5,30),h1440:new Ie(1920,1440,38e5,30)},xl={h360fps3:new Ie(640,360,2e5,3,"medium"),h360fps15:new Ie(640,360,4e5,15,"medium"),h720fps5:new Ie(1280,720,8e5,5,"medium"),h720fps15:new Ie(1280,720,15e5,15,"medium"),h720fps30:new Ie(1280,720,2e6,30,"medium"),h1080fps15:new Ie(1920,1080,25e5,15,"medium"),h1080fps30:new Ie(1920,1080,5e6,30,"medium"),original:new Ie(0,0,7e6,30,"medium")},IF="|",Jv="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function FF(n){const e=n.split(IF);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Ht(n){return S(this,void 0,void 0,function*(){return new Promise(e=>yt.setTimeout(e,n))})}function Ql(){return"addTransceiver"in RTCPeerConnection.prototype}function Rl(){return"addTrack"in RTCPeerConnection.prototype}function xF(){if(!("getCapabilities"in RTCRtpSender)||yr())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function QF(){if(!("getCapabilities"in RTCRtpSender)||Ni())return!1;if(yr()){const t=dn();if(t!=null&&t.version&&Zr(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function JA(n){return n==="av1"||n==="vp9"}function Pl(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function RF(){return typeof RTCPeerConnection>"u"?!1:Ql()||Rl()}function Ni(){var n;return((n=dn())===null||n===void 0?void 0:n.name)==="Firefox"}function yr(){var n;return((n=dn())===null||n===void 0?void 0:n.name)==="Safari"}function PF(){const n=dn();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function zv(){var n,e;return Kt()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function OF(){const n=dn(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Zr(e,n.osVersion)>=0?!0:n.name==="Safari"&&Zr(e,n.version)>=0}function Kt(){return typeof document<"u"}function Tn(){return navigator.product=="ReactNative"}function Ol(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Xv(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Yv(){if(!Tn())return;let n=Xv();if(n)return n.platform}function Zv(){if(Kt())return window.devicePixelRatio;if(Tn()){let n=Xv();if(n)return n.devicePixelRatio}return 1}function Zr(n,e){const t=n.split("."),r=e.split("."),i=Math.min(t.length,r.length);for(let A=0;A<i;++A){const s=parseInt(t[A],10),o=parseInt(r[A],10);if(s>o)return 1;if(s<o)return-1;if(A===i-1&&s===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==r.length?0:t.length<r.length?-1:1}function LF(n){for(const e of n)e.target.handleResize(e)}function DF(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Ll=null;const $v=()=>(Ll||(Ll=new ResizeObserver(LF)),Ll);let Dl=null;const e0=()=>(Dl||(Dl=new IntersectionObserver(DF,{root:null,rootMargin:"0px"})),Dl);function MF(){var n;const e=new UI({sdk:Dm.JS,protocol:SF,version:_F});return Tn()&&(e.os=(n=Yv())!==null&&n!==void 0?n:""),e}function t0(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=n,i.height=e;const A=i.getContext("2d");A==null||A.fillRect(0,0,i.width,i.height),r&&A&&(A.beginPath(),A.arc(n/2,e/2,50,0,Math.PI*2,!0),A.closePath(),A.fillStyle="grey",A.fill());const s=i.captureStream(),[o]=s.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let zA;function Ml(){if(!zA){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const r=n.createMediaStreamDestination();if(e.connect(t),t.connect(r),e.start(),[zA]=r.stream.getAudioTracks(),!zA)throw Error("Could not get empty media stream audio track");zA.enabled=!1}return zA.clone()}class Nl{constructor(e,t){this.onFinally=t,this.promise=new Promise((r,i)=>S(this,void 0,void 0,function*(){this.resolve=r,this.reject=i,e&&(yield e(r,i))})).finally(()=>{var r;return(r=this.onFinally)===null||r===void 0?void 0:r.call(this)})}}function NF(n){return UF.includes(n)}function wr(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function HF(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Hl(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function KF(n,e){return n.segments.map(t=>{let{id:r,text:i,language:A,startTime:s,endTime:o,final:a}=t;var c;const u=(c=e.get(r))!==null&&c!==void 0?c:Date.now(),l=Date.now();return a?e.delete(r):e.set(r,u),{id:r,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:A,firstReceivedTime:u,lastReceivedTime:l}})}function VF(n){const{id:e,timestamp:t,message:r,editTimestamp:i}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function n0(n){switch(n.reason){case de.LeaveRequest:return n.context;case de.Cancelled:return an.CLIENT_INITIATED;case de.NotAllowed:return an.USER_REJECTED;case de.ServerUnreachable:return an.JOIN_FAILURE;default:return an.UNKNOWN_REASON}}function sa(n){return n!==void 0?Number(n):void 0}function $r(n){return n!==void 0?BigInt(n):void 0}function Hi(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Gn(n){return!!n&&n.kind==R.Kind.Audio}function Ki(n){return!!n&&n.kind==R.Kind.Video}function br(n){return Hi(n)&&Ki(n)}function ei(n){return Hi(n)&&Gn(n)}function Kl(n){return!!n&&!n.isLocal}function GF(n){return!!n&&!n.isLocal}function Vl(n){return Kl(n)&&Ki(n)}function jF(n){return n.isLocal}function WF(n,e){const t=[];let r=new TextEncoder().encode(n);for(;r.length>e;){let i=e;for(;i>0;){const A=r[i];if(A!==void 0&&(A&192)!==128)break;i--}t.push(r.slice(0,i)),r=r.slice(i)}return r.length>0&&t.push(r),t}function r0(n,e,t){var r,i,A,s;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:c}=o0(n??{}),u=e==null?void 0:e.processor,l=t==null?void 0:t.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(Gl(d.audio,e),(r=(A=d.audio).deviceId)!==null&&r!==void 0||(A.deviceId={ideal:"default"}),(a||u)&&(d.audio.processor=a??u)),d.video&&(Gl(d.video,t),(i=(s=d.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||l)&&(d.video.processor=c??l)),d}function Gl(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function jl(n){var e,t,r,i;const A={};if(n.video)if(typeof n.video=="object"){const s={},o=s,a=n.video;Object.keys(a).forEach(c=>{switch(c){case"resolution":Gl(o,a.resolution);break;default:o[c]=a[c]}}),A.video=s,(e=(r=A.video).deviceId)!==null&&e!==void 0||(r.deviceId={ideal:"default"})}else A.video=n.video?{deviceId:{ideal:"default"}}:!1;else A.video=!1;return n.audio?typeof n.audio=="object"?(A.audio=n.audio,(t=(i=A.audio).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})):A.audio={deviceId:{ideal:"default"}}:A.audio=!1,A}function i0(n){return S(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const r=A0();if(r){const i=r.createAnalyser();i.fftSize=2048;const A=i.frequencyBinCount,s=new Uint8Array(A);r.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Ht(t),i.getByteTimeDomainData(s);const a=s.some(c=>c!==128&&c!==0);return r.close(),!a}return!1}()})}function A0(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const r=()=>S(this,void 0,void 0,function*(){var i;try{t.state==="suspended"&&(yield t.resume())}catch(A){console.warn("Error trying to auto-resume audio context",A)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",r)});window.document.body.addEventListener("click",r)}return t}}function qF(n){return n==="audioinput"?R.Source.Microphone:n==="videoinput"?R.Source.Camera:R.Source.Unknown}function s0(n){return n===R.Source.Microphone?"audioinput":n===R.Source.Camera?"videoinput":void 0}function JF(n){var e,t;let r=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(r=typeof r=="boolean"?{}:r,yr()?r=Object.assign(Object.assign({},r),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):r=Object.assign(Object.assign({},r),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:r,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function oa(n){return n.split("/")[1].toLowerCase()}function zF(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new dl({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Be(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?Be(n.track):{})}}function XF(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function YF(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const r=[...Object.keys(e),...Object.keys(n)],i={};for(const A of r)n[A]!==e[A]&&(i[A]=(t=e[A])!==null&&t!==void 0?t:"");return i}function o0(n){const e=Object.assign({},n);let t,r;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(r=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:r,optionsWithoutProcessor:wF(e)}}function ZF(n){switch(n){case ot.CAMERA:return R.Source.Camera;case ot.MICROPHONE:return R.Source.Microphone;case ot.SCREEN_SHARE:return R.Source.ScreenShare;case ot.SCREEN_SHARE_AUDIO:return R.Source.ScreenShareAudio;default:return R.Source.Unknown}}class $F extends Un.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var r,i;const{kind:A,data:s}=t.data;switch(A){case"error":ue.error(s.error.message),this.emit(mr.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(mr.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(mr.ParticipantEncryptionStatusChanged,s.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(gr.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=t=>{ue.error("e2ee worker encountered an error:",{error:t.error}),this.emit(mr.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!mF())throw new Sl("tried to setup end-to-end encryption on an unsupported browser");if(ue.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:nF.getLevel()}};this.worker&&(ue.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ue.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ue.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(N.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(L.TrackPublished,(r,i)=>this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Jt.NONE,i.identity)),e.on(L.ConnectionStateChanged,r=>{r===ge.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{this.setParticipantCryptorEnabled(A.trackInfo.encryption!==Jt.NONE,i.identity)})})}).on(L.TrackUnsubscribed,(r,i,A)=>{var s;const o={kind:"removeTransform",data:{participantIdentity:A.identity,trackId:r.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(o)}).on(L.TrackSubscribed,(r,i,A)=>{this.setupE2EEReceiver(r,A.identity,i.trackInfo)}).on(L.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(r=>{this.postKey(r)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(V.LocalTrackPublished,r=>S(this,void 0,void 0,function*(){this.setupE2EESender(r.track,r.track.sender)})),t.on(gr.SetKey,r=>this.postKey(r)).on(gr.RatchetRequest,(r,i)=>this.postRatchetRequest(r,i))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const r={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(r)}postKey(e){let{key:t,participantIdentity:r,keyIndex:i}=e;var A;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((A=this.room)===null||A===void 0?void 0:A.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker){const r={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(r)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const r={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,r){if(e.receiver){if(!(r!=null&&r.mimeType)||r.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?oa(r.mimeType):void 0)}}setupE2EESender(e,t){if(!Hi(e)||!t){t||ue.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,r,i){return S(this,void 0,void 0,function*(){if(this.worker){if(_l()){const A={kind:"decode",participantIdentity:r,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,A)}else{if(ra in e&&i){const a={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:r}};this.worker.postMessage(a);return}let A=e.writableStream,s=e.readableStream;if(!A||!s){const a=e.createEncodedStreams();e.writableStream=a.writable,A=a.writable,e.readableStream=a.readable,s=a.readable}const o={kind:"decode",data:{readableStream:s,writableStream:A,trackId:t,codec:i,participantIdentity:r}};this.worker.postMessage(o,[s,A])}e[ra]=!0}})}handleSender(e,t,r){var i;if(!(ra 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(_l()){ue.info("initialize script transform");const A={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,A)}else{ue.info("initialize encoded streams");const A=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:A.readable,writableStream:A.writable,codec:r,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[A.readable,A.writable])}e[ra]=!0}}}const Wl="default";class pt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new pt),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;if(((A=pt.userMediaPromiseMap)===null||A===void 0?void 0:A.size)>0){ue.debug("awaiting getUserMedia promise");try{t?yield pt.userMediaPromiseMap.get(t):yield Promise.all(pt.userMediaPromiseMap.values())}catch{ue.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(yr()&&r.hasDeviceInUse(t))&&(s.filter(a=>a.kind===t).length===0||s.some(a=>{const c=a.label==="",u=t?a.kind===t:!0;return c&&u}))){const a={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(u=>{u.stop()})}return r._previousDevices=s,t&&(s=s.filter(o=>o.kind===t)),s}()})}normalizeDeviceId(e,t,r){return S(this,void 0,void 0,function*(){if(t!==Wl)return t;const i=yield this.getDevices(e),A=i.find(o=>o.deviceId===Wl);if(!A){ue.warn("could not reliably determine default device");return}const s=i.find(o=>o.deviceId!==Wl&&o.groupId===(r??A.groupId));if(!s){ue.warn("could not reliably determine default device");return}return s==null?void 0:s.deviceId})}hasDeviceInUse(e){return e?pt.userMediaPromiseMap.has(e):pt.userMediaPromiseMap.size>0}}pt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],pt.userMediaPromiseMap=new Map;var XA;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(XA||(XA={}));class ex{constructor(){this.pendingTasks=new Map,this.taskMutex=new Dt,this.nextTaskIndex=0}run(e){return S(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:XA.WAITING};this.pendingTasks.set(t.id,t);const r=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=XA.RUNNING,yield e()}finally{t.status=XA.COMPLETED,this.pendingTasks.delete(t.id),r()}})}flush(){return S(this,void 0,void 0,function*(){return this.run(()=>S(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function tx(n,e){const t=new URL(HF(n));return e.forEach((r,i)=>{t.searchParams.set(i,r)}),a0(t,"rtc")}function nx(n){const e=new URL(Hl(n));return a0(e,"validate")}function rx(n){return n.endsWith("/")?n:"".concat(n,"/")}function a0(n,e){return n.pathname="".concat(rx(n.pathname)).concat(e),n.toString()}const ix=["syncState","trickle","offer","answer","simulate","leave"];function Ax(n){const e=ix.indexOf(n.case)>=0;return ue.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Le;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Le||(Le={}));class ql{get currentState(){return this.state}get isDisconnected(){return this.state===Le.DISCONNECTING||this.state===Le.DISCONNECTED}get isEstablishingConnection(){return this.state===Le.CONNECTING||this.state===Le.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var r;this.rtt=0,this.state=Le.DISCONNECTED,this.log=ue,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=Kn((r=t.loggerName)!==null&&r!==void 0?r:ln.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new ex,this.queuedRequests=[],this.closingLock=new Dt,this.connectionLock=new Dt,this.state=Le.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,r,i){return S(this,void 0,void 0,function*(){return this.state=Le.CONNECTING,this.options=r,yield this.connect(e,t,r,i)})}reconnect(e,t,r,i){return S(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=Le.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:r,reconnectReason:i}))})}connect(e,t,r,i){this.connectOptions=r;const A=MF(),s=sx(t,A,r),o=tx(e,s),a=nx(o);return new Promise((c,u)=>S(this,void 0,void 0,function*(){const l=yield this.connectionLock.lock();try{const d=()=>S(this,void 0,void 0,function*(){this.close(),clearTimeout(h),u(new Qe("room connection has been cancelled (signal)",de.Cancelled))}),h=setTimeout(()=>{this.close(),u(new Qe("room connection has timed out (signal)",de.ServerUnreachable))},r.websocketTimeout);i!=null&&i.aborted&&d(),i==null||i.addEventListener("abort",d);const f=new URL(o);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:r.reconnect,reconnectReason:r.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=p=>S(this,void 0,void 0,function*(){if(this.state!==Le.CONNECTED){this.state=Le.DISCONNECTED,clearTimeout(h);try{const g=yield fetch(a);if(g.status.toFixed(0).startsWith("4")){const v=yield g.text();u(new Qe(v,de.NotAllowed,g.status))}else u(new Qe("Encountered unknown websocket error during connection: ".concat(p.toString()),de.InternalError,g.status))}catch(g){u(new Qe(g instanceof Error?g.message:"server was not reachable",de.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>S(this,void 0,void 0,function*(){var g,v,y;let C;if(typeof p.data=="string"){const B=JSON.parse(p.data);C=Gm.fromJson(B,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)C=Gm.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==Le.CONNECTED){let B=!1;if(((g=C.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=Le.CONNECTED,i==null||i.removeEventListener("abort",d),this.pingTimeoutDuration=C.message.value.pingTimeout,this.pingIntervalDuration=C.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(C.message.value)):this.state===Le.RECONNECTING&&C.message.case!=="leave"?(this.state=Le.CONNECTED,i==null||i.removeEventListener("abort",d),this.startPingInterval(),((v=C.message)===null||v===void 0?void 0:v.case)==="reconnect"?c(C.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),B=!0)):this.isEstablishingConnection&&C.message.case==="leave"?u(new Qe("Received leave request while trying to (re)connect",de.LeaveRequest,void 0,C.message.value.reason)):r.reconnect||u(new Qe("did not receive join response, got ".concat((y=C.message)===null||y===void 0?void 0:y.case," instead"),de.InternalError)),!B)return}this.signalLatency&&(yield Ht(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new Qe("Websocket got closed during a (re)connection attempt",de.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{l()}}))}close(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Le.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(A=>{e.ws?e.ws.onclose=()=>{A()}:A()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,Ht(250)])),e.ws=void 0}}finally{t&&(e.state=Le.DISCONNECTED),r()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:aa(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:aa(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ul({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new ll({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=A.getNextRequestId();return yield A.sendRequest({case:"updateMetadata",value:new Jm({requestId:o,metadata:r,name:i,attributes:s})}),o}()})}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,t){return this.sendRequest({case:"updateLayers",value:new qm({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ym({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ke.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new ev({timestamp:Ke.parse(Date.now()),rtt:Ke.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Wm({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new qo({reason:an.CLIENT_INITIATED,action:Oi.DISCONNECT})})}sendRequest(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!Ax(t)&&r.state===Le.RECONNECTING){r.queuedRequests.push(()=>S(r,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(i||(yield r.requestQueue.flush()),r.signalLatency&&(yield Ht(r.signalLatency)),!r.ws||r.ws.readyState!==r.ws.OPEN){r.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),r.logContext);return}const s=new FI({message:t});try{r.useJSON?r.ws.send(s.toJsonString()):r.ws.send(s.toBinary())}catch(o){r.log.error("error sending signal message",Object.assign(Object.assign({},r.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,r;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let A=!1;if(i.case==="answer"){const s=c0(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=c0(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((t=i.value.participants)!==null&&t!==void 0?t:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((r=i.value.speakers)!==null&&r!==void 0?r:[]):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(),A=!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})));A||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return S(this,void 0,void 0,function*(){if(this.state===Le.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(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=yt.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&&yt.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=yt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&yt.clearInterval(this.pingInterval)}}function c0(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function aa(n){return new Xr({sdp:n.sdp,type:n.type})}function sx(n,e,t){var r;const i=new URLSearchParams;return i.set("access_token",n),t.reconnect&&(i.set("reconnect","1"),t.sid&&i.set("sid",t.sid)),i.set("auto_subscribe",t.autoSubscribe?"1":"0"),i.set("sdk",Tn()?"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),t.adaptiveStream&&i.set("adaptive_stream","1"),t.reconnectReason&&i.set("reconnect_reason",t.reconnectReason.toString()),!((r=navigator.connection)===null||r===void 0)&&r.type&&i.set("network",navigator.connection.type),i}var hn={},Jl={},zl={exports:{}},u0;function Xl(){if(u0)return zl.exports;u0=1;var n=zl.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 t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{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 t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{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 t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{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(n).forEach(function(e){var t=n[e];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),zl.exports}var l0;function ox(){return l0||(l0=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,a,c,u){if(u&&!c)a[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(a[c[l]]=e(o[l+1]))},r=function(o,a,c){var u=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:u&&!a[o.name]&&(a[o.name]={});var l=o.push?{}:u?a[o.name]:a;t(c.match(o.reg),l,o.names,o.name),o.push&&a[o.push].push(l)},i=Xl(),A=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var a={},c=[],u=a;return o.split(/(\r\n|\r|\n)/).filter(A).forEach(function(l){var d=l[0],h=l.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(i[d]||[]).length;f+=1){var p=i[d][f];if(p.reg.test(h))return r(p,u,h)}}),a.media=c,a};var s=function(o,a){var c=a.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&a.length>1&&(o[c[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var a=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)a.push({component:c[u],ip:c[u+1],port:c[u+2]});return a},n.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(s,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(c){var u,l=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),l=!0),{scid:u,paused:l}})})}}(Jl)),Jl}var Yl,d0;function ax(){if(d0)return Yl;d0=1;var n=Xl(),e=/%[sdv%]/g,t=function(s){var o=1,a=arguments,c=a.length;return s.replace(e,function(u){if(o>=c)return u;var l=a[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},r=function(s,o,a){var c=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,u=[s+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var d=o.names[l];o.name?u.push(a[o.name][d]):u.push(a[o.names[l]])}else u.push(a[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],A=["i","c","b","a"];return Yl=function(s,o){o=o||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(l){l.payloads==null&&(l.payloads="")});var a=o.outerOrder||i,c=o.innerOrder||A,u=[];return a.forEach(function(l){n[l].forEach(function(d){d.name in s&&s[d.name]!=null?u.push(r(l,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){u.push(r(l,d,h))})})}),s.media.forEach(function(l){u.push(r("m",n.m[0],l)),c.forEach(function(d){n[d].forEach(function(h){h.name in l&&l[h.name]!=null?u.push(r(d,h,l)):h.push in l&&l[h.push]!=null&&l[h.push].forEach(function(f){u.push(r(d,h,f))})})})}),u.join(`\r
|
|
41
41
|
`)+`\r
|
|
42
|
-
`},Yl}var h0;function cx(){if(h0)return hn;h0=1;var n=ox(),e=ax(),t=Xl();return hn.grammar=t,hn.write=e,hn.parse=n.parse,hn.parseParams=n.parseParams,hn.parseFmtpConfig=n.parseFmtpConfig,hn.parsePayloads=n.parsePayloads,hn.parseRemoteCandidates=n.parseRemoteCandidates,hn.parseImageAttributes=n.parseImageAttributes,hn.parseSimulcastStreamList=n.parseSimulcastStreamList,hn}var Cr=cx();function Zl(n,e,t){var r,i,A;e===void 0&&(e=50),t===void 0&&(t={});var s=(r=t.isImmediate)!=null&&r,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&A===void 0;if(A!==void 0&&clearTimeout(A),A=setTimeout(function(){if(A=void 0,c=Date.now(),!s){var C=n.apply(f,h);o&&o(C),u.forEach(function(B){return(0,B.resolve)(C)}),u=[]}},l()),v){var y=n.apply(f,h);return o&&o(y),p(y)}u.push({resolve:p,reject:g})})};return d.cancel=function(h){A!==void 0&&clearTimeout(A),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const ux=.7,lx=20,Vi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class p0 extends Un.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var r;super(),this.log=ue,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Zl(i=>S(this,void 0,void 0,function*(){this.emit(Vi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(A){if(i)i(A);else throw A}}),lx),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=Kn((r=t.loggerName)!==null&&r!==void 0?r:ln.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var r;t.candidate&&((r=this.onIceCandidate)===null||r===void 0||r.call(this,t.candidate))},e.onicecandidateerror=t=>{var r;(r=this.onIceCandidateError)===null||r===void 0||r.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var r;(r=this.onDataChannel)===null||r===void 0||r.call(this,t)},e.ontrack=t=>{var r;(r=this.onTrack)===null||r===void 0||r.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return S(this,void 0,void 0,function*(){var t;let r;if(e.type==="offer"){let{stereoMids:i,nackMids:A}=dx(e);this.remoteStereoMids=i,this.remoteNackMids=A}else if(e.type==="answer"){const i=Cr.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{A.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||A.mid!=s.transceiver.mid)return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of A.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&A.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),r=Cr.write(i)}yield this.setMungedSDP(e,r,!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(Vi.NegotiationComplete),e.sdp&&Cr.parse(e.sdp).media.forEach(A=>{A.type==="video"&&this.emit(Vi.RTPVideoPayloadTypes,A.rtp)}))})}createAndSendOffer(e){return S(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const A=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&A)yield this._pc.setRemoteDescription(A);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const i=Cr.parse((t=r.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{g0(A),A.type==="audio"?f0(A,[],[]):A.type==="video"&&this.trackBitrates.some(s=>{if(!A.msid||!s.cid||!A.msid.includes(s.cid))return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(JA(s.codec)&&this.ensureVideoDDExtensionForSVC(A,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*ux);for(const c of A.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(r,Cr.write(i)),this.onOffer(r)})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),r=Cr.parse((e=t.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(i=>{g0(i),i.type==="audio"&&f0(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Cr.write(r)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ut("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ut("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}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 S(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const r=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),r.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=r.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,r){return S(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(r?"remote":"local"," description"),this.logContext),r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(A){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:A,sdp:t})),e.sdp=i}}try{r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let A="unknown error";i instanceof Error?A=i.message:typeof i=="string"&&(A=i);const s={error:A,sdp:e.sdp};throw!r&&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 kl(A)}})}ensureVideoDDExtensionForSVC(e,t){var r,i;if(!((r=e.ext)===null||r===void 0?void 0:r.some(s=>s.uri===Jv))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.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:Jv})}}}function f0(n,e,t){let r=0;n.rtp.some(i=>i.codec==="opus"?(r=i.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===r&&i.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===r?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function dx(n){var e;const t=[],r=[],i=Cr.parse((e=n.sdp)!==null&&e!==void 0?e:"");let A=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(A=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===A&&a.type==="nack")&&r.push(s.mid),s.fmtp.some(a=>a.payload===A?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:r}}function g0(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const $l="vp8",hx={audioPreset:Il.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:xl.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:$l,backupCodec:!0},m0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},v0={deviceId:{ideal:"default"},resolution:qA.h720.resolution},px={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new iF,disconnectOnPageLeave:!0,webAudioMix:!1},ed={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Xe;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Xe||(Xe={}));class fx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,r){var i;this.peerConnectionTimeout=ed.peerConnectionTimeout,this.log=ue,this.updateState=()=>{var A;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Xe.CONNECTED:o.some(a=>a==="failed")?this.state=Xe.FAILED:o.some(a=>a==="connecting")?this.state=Xe.CONNECTING:o.every(a=>a==="closed")?this.state=Xe.CLOSED:o.some(a=>a==="closed")?this.state=Xe.CLOSING:o.every(a=>a==="new")&&(this.state=Xe.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Xe[s]," to ").concat(Xe[this.state]),this.logContext),(A=this.onStateChange)===null||A===void 0||A.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Kn((i=r.loggerName)!==null&&i!==void 0?i:ln.PCManager),this.loggerOptions=r,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new p0(e,r),this.subscriber=new p0(e,r),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=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,un.PUBLISHER)},this.subscriber.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,un.SUBSCRIBER)},this.subscriber.onDataChannel=A=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,A)},this.subscriber.onTrack=A=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,A)},this.publisher.onOffer=A=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,A)},this.state=Xe.NEW,this.connectionLock=new Dt,this.remoteOfferLock=new Dt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.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 S(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return S(this,void 0,void 0,function*(){t===un.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return S(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 t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return S(this,void 0,void 0,function*(){var r;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((r=this.requiredTransports)===null||r===void 0?void 0:r.map(A=>this.ensureTransportConnected(A,e,t)))}finally{i()}})}negotiate(e){return S(this,void 0,void 0,function*(){return new Promise((t,r)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{r("negotiation timed out")},this.peerConnectionTimeout),A=()=>{clearTimeout(i),r("negotiation aborted")};e.signal.addEventListener("abort",A),this.publisher.once(Vi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Vi.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),r(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===un.PUBLISHER?this.publisher.getConnectedAddress():e===un.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,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(r.getConnectionState()!=="connected")return new Promise((a,c)=>S(A,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),yt.clearTimeout(l),c(new Qe("room connection has been cancelled",de.Cancelled))};i!=null&&i.signal.aborted&&u(),i==null||i.signal.addEventListener("abort",u);const l=yt.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",u),c(new Qe("could not establish pc connection",de.InternalError))},s);for(;this.state!==Xe.CONNECTED;)if(yield Ht(50),i!=null&&i.signal.aborted){c(new Qe("room connection has been cancelled",de.Cancelled));return}yt.clearTimeout(l),i==null||i.signal.removeEventListener("abort",u),a()}))}()})}}class Ye extends Error{constructor(e,t,r){super(t),this.code=e,this.message=w0(t,Ye.MAX_MESSAGE_BYTES),this.data=r?w0(r,Ye.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ye(e.code,e.message,e.data)}toProto(){return new Pm({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ye(Ye.ErrorCode[e],Ye.ErrorMessage[e],t)}}Ye.MAX_MESSAGE_BYTES=256,Ye.MAX_DATA_BYTES=15360,Ye.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},Ye.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 y0=15360;function td(n){return new TextEncoder().encode(n).length}function w0(n,e){if(td(n)<=e)return n;let t=0,r=n.length;const i=new TextEncoder;for(;t<r;){const A=Math.floor((t+r+1)/2);i.encode(n.slice(0,A)).length<=e?t=A:r=A-1}return n.slice(0,t)}const nd=2e3;function ca(n,e){if(!e)return 0;let t,r;return"bytesReceived"in n?(t=n.bytesReceived,r=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,r=e.bytesSent),t===void 0||r===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-r)*8*1e3/(n.timestamp-e.timestamp)}const gx=1e3;class b0 extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,A=arguments.length>4?arguments[4]:void 0;super(e,t,A),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=Zl(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(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(M.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Dt,this.pauseUpstreamLock=new Dt,this.processorLock=new Dt,this.restartLock=new Dt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),r&&(this._constraints=r)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return S(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(A=>{Mi(this._mediaStreamTrack,A)}),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 A=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&&(Di(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{A()}}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.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(A=>{Di(i??e,A)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:gx;return function*(){var r;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((r=dn())===null||r===void 0?void 0:r.os)==="iOS"&&(yield Ht(10));const i=Date.now();for(;Date.now()-i<t;){const A=e.dimensions;if(A)return A;yield Ht(50)}throw new Vn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===wr(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),wr(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===R.Source.ScreenShare)return;const{deviceId:r,groupId:i}=e._mediaStreamTrack.getSettings(),A=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?pt.getInstance().normalizeDeviceId(A,r,i):r}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Vn("unable to replace an unpublished track");let r,i;return typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:r,facingMode:i}=e,A=AF(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===R.Kind.Video?s.video=r||i?{deviceId:r,facingMode:i}:!0:s.audio=r?{deviceId:r}:!0,this.attachedElements.forEach(c=>{Mi(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(A),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(M.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?M.Muted:M.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 S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zv()&&(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 S(this,void 0,void 0,function*(){var e;const t=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(M.UpstreamPaused,this);const r=dn();if((r==null?void 0:r.name)==="Safari"&&Zr(r.version,"12.0")<0)throw new Sl("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{t()}})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;const t=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(M.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return S(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 S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;const s=yield r.processorLock.lock();try{r.log.debug("setting up processor",r.logContext);const o=document.createElement(r.kind),a={kind:r.kind,track:r._mediaStreamTrack,element:o,audioContext:r.audioContext};if(yield t.init(a),r.log.debug("processor initialized",r.logContext),r.processor&&(yield r.stopProcessor()),r.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Di(r._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>r.log.error("failed to play processor element",Object.assign(Object.assign({},r.logContext),{error:c}))),r.processor=t,r.processorElement=o,r.processor.processedTrack){for(const c of r.attachedElements)c!==r.processorElement&&i&&(Mi(r._mediaStreamTrack,c),Di(r.processor.processedTrack,c));yield(A=r.sender)===null||A===void 0?void 0:A.replaceTrack(r.processor.processedTrack)}r.emit(M.TrackProcessorUpdate,r.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var r,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(r=e.processor.processedTrack)===null||r===void 0||r.stop(),yield e.processor.destroy(),e.processor=void 0,t||((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(M.TrackProcessorUpdate))}()})}}class ua extends b0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,A=arguments.length>4?arguments[4]:void 0;super(e,R.Kind.Audio,t,r,A),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=ca(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,cn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,cn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const r=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==wr(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||r)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return S(this,void 0,void 0,function*(){let t;if(e){const r=jl({audio:e});typeof r.audio!="boolean"&&(t=r.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const r=yield t.restart.call(this,e);return this.checkForSilence(),r})}startMonitor(){Kt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},nd)))}setProcessor(e){return S(this,void 0,void 0,function*(){var t;const r=yield this.processorLock.lock();try{if(!Tn()&&!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(t=this.sender)===null||t===void 0?void 0:t.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(M.TrackProcessorUpdate,this.processor)}finally{r()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let r;return t.forEach(i=>{i.type==="outbound-rtp"&&(r={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),r})}checkForSilence(){return S(this,void 0,void 0,function*(){const e=yield i0(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(M.AudioSilenceDetected)),e})}}function mx(n,e,t){switch(n.kind){case"audio":return new ua(n,e,!1,void 0,t);case"video":return new da(n,e,!1,t);default:throw new Vn("unsupported track type: ".concat(n.kind))}}const vx=Object.values(qA),yx=Object.values(Fl),wx=Object.values(xl),bx=[qA.h180,qA.h360],Cx=[Fl.h180,Fl.h360],Bx=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var r,i;return new Ie(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((r=n.encoding.maxFramerate)!==null&&r!==void 0?r:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,n.encoding.priority)}),rd=["q","h","f"];function id(n,e,t,r){var i,A;let s=r==null?void 0:r.videoEncoding;n&&(s=r==null?void 0:r.screenShareEncoding);const o=r==null?void 0:r.simulcast,a=r==null?void 0:r.scalabilityMode,c=r==null?void 0:r.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Sx(n,e,t,c),ue.debug("using video encoding",s));const u=s.maxFramerate,l=new Ie(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&JA(c)){const f=new la(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=dn();if(yr()||Tn()||(g==null?void 0:g.name)==="Chrome"&&Zr(g==null?void 0:g.version,"113")<0){const v=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)p.push({rid:rd[2-y],maxBitrate:s.maxBitrate/Math.pow(v,y),maxFramerate:l.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(p[0].priority=l.encoding.priority,p[0].networkPriority=l.encoding.priority),ue.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let d=[];n?d=(i=B0(r==null?void 0:r.screenShareSimulcastLayers))!==null&&i!==void 0?i:C0(n,l):d=(A=B0(r==null?void 0:r.videoSimulcastLayers))!==null&&A!==void 0?A:C0(n,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const p=Math.max(e,t);if(p>=960&&h)return Ad(e,t,[f,h,l],u);if(p>=480)return Ad(e,t,[f,l],u)}return Ad(e,t,[l])}function _x(n,e,t){var r,i,A,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ue.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(r=o.width)!==null&&r!==void 0?r:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(A=o.height)!==null&&A!==void 0?A:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),id(n.source===R.Source.ScreenShare,a,c,t)}function Sx(n,e,t,r){const i=kx(n,e,t);let{encoding:A}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(A=a.encoding,a.width>=s)break}if(r)switch(r){case"av1":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.7;break;case"vp9":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.85;break}return A}function kx(n,e,t){if(n)return wx;const r=e>t?e/t:t/e;return Math.abs(r-16/9)<Math.abs(r-4/3)?vx:yx}function C0(n,e){if(n)return Bx(e);const{width:t,height:r}=e,i=t>r?t/r:r/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?bx:Cx}function Ad(n,e,t,r){const i=[];if(t.forEach((A,s)=>{if(s>=rd.length)return;const o=Math.min(n,e),c={rid:rd[s],scaleResolutionDownBy:Math.max(1,o/Math.min(A.width,A.height)),maxBitrate:A.encoding.maxBitrate},u=r&&A.encoding.maxFramerate?Math.min(r,A.encoding.maxFramerate):A.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=Ni()||s===0;A.encoding.priority&&l&&(c.priority=A.encoding.priority,c.networkPriority=A.encoding.priority),i.push(c)}),Tn()&&Yv()==="ios"){let A;i.forEach(o=>{A?o.maxFramerate&&o.maxFramerate>A&&(A=o.maxFramerate):A=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=A&&(s&&(s=!1,ue.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ue.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(A)),o.maxFramerate=A)})}return i}function B0(n){if(n)return n.sort((e,t)=>{const{encoding:r}=e,{encoding:i}=t;return r.maxBitrate>i.maxBitrate?1:r.maxBitrate<i.maxBitrate?-1:r.maxBitrate===i.maxBitrate&&r.maxFramerate&&i.maxFramerate?r.maxFramerate>i.maxFramerate?1:-1:0})}class la{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Ex(n){return n.source===R.Source.ScreenShare||n.constraints.height&&wr(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ux=5e3;class da extends b0{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,r,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let A;try{A=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(A.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=ca(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Dt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Kt())return;const r=(t=this.sender)===null||t===void 0?void 0:t.getParameters();r&&(this.encodings=r.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},nd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=fr(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)A=c.value,o=!1,yield(s=A.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=fr(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){A=c.value,o=!1;const u=A;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.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{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],r=yield this.sender.getStats();return r.forEach(i=>{var A;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:(A=i.rid)!==null&&A!==void 0?A:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=r.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,A)=>{var s,o;return((s=A.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let r=$t.LOW;r<=$t.HIGH;r+=1)t.push(new hl({quality:r,enabled:r<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;let o;if(e){const l=jl({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=fr(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){A=u.value,a=!1;const l=A;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){r={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(r){var i=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,r,A),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=fr(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return S(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const r={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,r),r}setSimulcastTrackSender(e,t){const r=this.simulcastCodecs.get(e);r&&(r.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ux))}setPublishingCodecs(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s,o,a;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(t=!0,r=fr(e);i=yield r.next(),A=i.done,!A;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield _0(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!A&&(o=r.return)&&(yield o.call(r))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return S(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 _0(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zv()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function _0(n,e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=yield r.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},A),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},A),{encodings:a,senderEncodings:e}));return}let c=!1;const u=dn();if((u==null?void 0:u.name)==="Chrome"&&Zr(u==null?void 0:u.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new la(d.scalabilityMode);let f=xi.OFF;if(t.forEach(p=>{p.enabled&&(f===xi.OFF||p.quality>f)&&(f=p.quality)}),f===xi.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const p=new la(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let p=(f=d.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=S0(p),v=t.find(y=>y.quality===g);v&&d.active!==v.enabled&&(c=!0,d.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(d.active?"enabled":"disabled"),A),Ni()&&(v.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&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},A),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function S0(n){switch(n){case"f":return $t.HIGH;case"h":return $t.MEDIUM;case"q":return $t.LOW;default:return $t.HIGH}}function k0(n,e,t,r){if(!t)return[new zr({quality:$t.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(r){const i=t[0].scalabilityMode,A=new la(i),s=[],o=A.suffix=="h"?1.5:2,a=A.suffix=="h"?2:3;for(let c=0;c<A.spatial;c+=1)s.push(new zr({quality:Math.min($t.HIGH,A.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return t.map(i=>{var A,s,o;const a=(A=i.scaleResolutionDownBy)!==null&&A!==void 0?A:1;let c=S0((s=i.rid)!==null&&s!==void 0?s:"");return new zr({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const E0="_lossy",U0="_reliable",Tx=2*1e3,sd="leave-reconnect";var pn;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(pn||(pn={}));class Ix extends Un.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ed.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=pn.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=ue,this.handleDataChannel=r=>S(this,[r],void 0,function(i){var A=this;let{channel:s}=i;return function*(){if(s){if(s.label===U0)A.reliableDCSub=s;else if(s.label===E0)A.lossyDCSub=s;else return;A.log.debug("on data channel ".concat(s.id,", ").concat(s.label),A.logContext),s.onmessage=A.handleDataMessage}}()}),this.handleDataMessage=r=>S(this,void 0,void 0,function*(){var i,A;const s=yield this.dataProcessLock.lock();try{let o;if(r.data instanceof ArrayBuffer)o=r.data;else if(r.data instanceof Blob)o=yield r.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:r.data}));return}const a=Nt.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,a.value.value.speakers):(((A=a.value)===null||A===void 0?void 0:A.case)==="user"&&xx(a,a.value.value),this.emit(N.DataPacketReceived,a))}finally{s()}}),this.handleDataError=r=>{const A=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(r instanceof ErrorEvent&&r.error){const{error:s}=r.error;this.log.error("DataChannel error on ".concat(A,": ").concat(r.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(A),Object.assign(Object.assign({},this.logContext),{event:r}))},this.handleBufferedAmountLow=r=>{const A=r.currentTarget.maxRetransmits===0?fe.LOSSY:fe.RELIABLE;this.updateAndEmitDCBufferStatus(A)},this.handleDisconnect=(r,i)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const A=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(N.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){A(s);return}r===sd&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=yt.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((r,i)=>{this.pcState===pn.Connected&&r();const A=()=>{this.off(N.Disconnected,s),r()},s=()=>{this.off(N.Restarted,A),i()};this.once(N.Restarted,A),this.once(N.Disconnected,s)}),this.updateAndEmitDCBufferStatus=r=>{const i=this.isBufferStatusLow(r);typeof i<"u"&&i!==this.dcBufferStatus.get(r)&&(this.dcBufferStatus.set(r,i),this.emit(N.DCBufferStatusChanged,i,r))},this.isBufferStatusLow=r=>{const i=this.dataChannelForKind(r);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Le.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Qi.RR_SIGNAL_DISCONNECTED))},this.log=Kn((t=e.loggerName)!==null&&t!==void 0?t:ln.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ql(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Dt,this.dataProcessLock=new Dt,this.dcBufferStatus=new Map([[fe.LOSSY,!0],[fe.RELIABLE,!0]]),this.client.onParticipantUpdate=r=>this.emit(N.ParticipantUpdate,r),this.client.onConnectionQuality=r=>this.emit(N.ConnectionQualityUpdate,r),this.client.onRoomUpdate=r=>this.emit(N.RoomUpdate,r),this.client.onSubscriptionError=r=>this.emit(N.SubscriptionError,r),this.client.onSubscriptionPermissionUpdate=r=>this.emit(N.SubscriptionPermissionUpdate,r),this.client.onSpeakersChanged=r=>this.emit(N.SpeakersChanged,r),this.client.onStreamStateUpdate=r=>this.emit(N.StreamStateChanged,r),this.client.onRequestResponse=r=>this.emit(N.SignalRequestResponse,r)}get logContext(){var e,t,r,i,A,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.room)===null||i===void 0?void 0:i.sid,participant:(s=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,r,i){return S(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=r,this.maxJoinAttempts=r.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const A=yield this.client.join(e,t,r,i);return this._isClosed=!1,this.latestJoinResponse=A,this.subscriberPrimary=A.subscriberPrimary,this.pcManager||(yield this.configure(A)),(!this.subscriberPrimary||A.fastPublish)&&this.negotiate(),this.clientConfiguration=A.clientConfiguration,setTimeout(()=>{this.emit(N.SignalConnected)},10),A}catch(A){if(A instanceof Qe&&A.reason===de.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,t,r,i);throw A}})}close(){return S(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(N.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return S(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 t=r=>{r&&(r.close(),r.onbufferedamountlow=null,r.onclose=null,r.onclosing=null,r.onerror=null,r.onmessage=null,r.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Vn("a track with the same ID has already been published");return new Promise((t,r)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],r(new Qe("publication of local track timed out, no response from server",de.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:A=>{clearTimeout(i),t(A)},reject:()=>{clearTimeout(i),r(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return S(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 S(this,void 0,void 0,function*(){var t,r;if(this.pcManager&&this.pcManager.currentState!==Xe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new fx(i,e.subscriberPrimary,this.loggerOptions),this.emit(N.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(A,s)=>{this.client.sendIceCandidate(A,s)},this.pcManager.onPublisherOffer=A=>{this.client.sendOffer(A)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(A,s,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(A),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),A===Xe.CONNECTED){const u=this.pcState===pn.New;this.pcState=pn.Connected,u&&this.emit(N.Connected,e)}else A===Xe.FAILED&&this.pcState===pn.Connected&&(this.pcState=pn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Qi.RR_SUBSCRIBER_FAILED:Qi.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Le.RECONNECTING,c=[Xe.FAILED,Xe.CLOSING,Xe.CLOSED].includes(A);a&&c&&!this._isClosed&&this.emit(N.Offline)}),this.pcManager.onTrack=A=>{this.emit(N.MediaTrackAdded,A.track,A.streams[0],A.receiver)},Fx((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>S(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,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>S(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.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:r}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],r(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(N.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(N.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(N.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(N.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(N.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Qi.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 Oi.DISCONNECT:this.emit(N.Disconnected,e==null?void 0:e.reason),this.close();break;case Oi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(sd);break;case Oi.RESUME:this.handleDisconnect(sd)}}}makeRTCConfiguration(e){var t;const r=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),r.encodedInsertableStreams=!0),e.iceServers&&!r.iceServers){const i=[];e.iceServers.forEach(A=>{const s={urls:A.urls};A.username&&(s.username=A.username),A.credential&&(s.credential=A.credential),i.push(s)}),r.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===GA.ENABLED&&(r.iceTransportPolicy="relay"),r.sdpSemantics="unified-plan",r.continualGatheringPolicy="gather_continually",r}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(E0,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(U0,{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,t,r){return S(this,void 0,void 0,function*(){if(Ql())return yield this.createTransceiverRTCRtpSender(e,t,r);if(Rl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ut("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(Ql())return this.createSimulcastTransceiverSender(e,t,r,i);if(Rl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ut("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,r){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Ki(e)&&(e.codec=t.videoCodec);const A={direction:"sendonly",streams:i};return r&&(A.sendEncodings=r),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,A)).sender})}createSimulcastTransceiverSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("publisher is closed");const A={direction:"sendonly"};i&&(A.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,A);if(r.videoCodec)return e.setSimulcastTrackSender(r.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return S(this,void 0,void 0,function*(){var t,r,i;if(!this._isClosed){if(this.attemptingReconnect){ue.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===GA.DISABLED||((i=(r=this.pcManager)===null||r===void 0?void 0:r.currentState)!==null&&i!==void 0?i:Xe.NEW)===Xe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(A){this.reconnectAttempts+=1;let s=!0;A instanceof ut?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:A})),s=!1):A instanceof Gi||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",Qi.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(N.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return S(this,void 0,void 0,function*(){var t,r,i;try{if(!this.url||!this.token)throw new ut("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let A;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Gi;A=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Qe&&s.reason===de.NotAllowed?new ut("could not reconnect, token might be expired"):new Gi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(N.SignalRestarted,A),yield this.waitForPCReconnected(),this.client.currentState!==Le.CONNECTED)throw new Gi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(N.Restarted)}catch(A){const s=yield(r=this.regionUrlProvider)===null||r===void 0?void 0:r.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),A}})}resumeConnection(e){return S(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ut("could not reconnect, url or token not saved");if(!this.pcManager)throw new ut("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Resuming);let r;try{this.setupSignalClientCallbacks(),r=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let A="";throw i instanceof Error&&(A=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Qe&&i.reason===de.NotAllowed?new ut("could not reconnect, token might be expired"):i instanceof Qe&&i.reason===de.LeaveRequest?i:new Gi(A)}if(this.emit(N.SignalResumed),r){const i=this.makeRTCConfiguration(r);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!==Le.CONNECTED)throw new Gi("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(N.Resumed)})}waitForPCInitialConnection(e,t){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=pn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ht(Tx),!this.pcManager)throw new ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=pn.Connected}catch(e){throw this.pcState=pn.Disconnected,new Qe("could not establish PC connection, ".concat(e.message),de.InternalError)}})}publishRpcResponse(e,t,r,i){return S(this,void 0,void 0,function*(){const A=new Nt({destinationIdentities:[e],kind:fe.RELIABLE,value:{case:"rpcResponse",value:new Rm({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:r??""}})}});yield this.sendDataPacket(A,fe.RELIABLE)})}publishRpcAck(e,t){return S(this,void 0,void 0,function*(){const r=new Nt({destinationIdentities:[e],kind:fe.RELIABLE,value:{case:"rpcAck",value:new Qm({requestId:t})}});yield this.sendDataPacket(r,fe.RELIABLE)})}sendDataPacket(e,t){return S(this,void 0,void 0,function*(){const r=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(r),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,r)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>r("Engine closed");for(this.once(N.Closing,i);!this.dcBufferStatus.get(e);)yield Ht(10);this.off(N.Closing,i),t()}}))}ensureDataTransportConnected(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var A;if(!r.pcManager)throw new ut("PC manager is closed");const s=i?r.pcManager.subscriber:r.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Qe("".concat(o," connection not set"),de.InternalError);let a=!1;!i&&!r.dataChannelForKind(t,i)&&(r.createDataChannels(),a=!0),!a&&!i&&!r.pcManager.publisher.isICEConnected&&r.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&r.negotiate();const c=r.dataChannelForKind(t,i);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+r.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((A=r.dataChannelForKind(t,i))===null||A===void 0?void 0:A.readyState)==="open")return;yield Ht(50)}throw new Qe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),de.InternalError)}()})}ensurePublisherConnected(e){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Xe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((e,t)=>S(this,void 0,void 0,function*(){if(!this.pcManager){t(new kl("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const r=new AbortController,i=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(N.Closing,i),this.pcManager.publisher.once(Vi.RTPVideoPayloadTypes,A=>{const s=new Map;A.forEach(o=>{const a=o.codec.toLowerCase();NF(a)&&s.set(o.payload,a)}),this.emit(N.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(r),e()}catch(A){A instanceof kl&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Qi.RR_UNKNOWN),t(A)}finally{this.off(N.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===fe.LOSSY)return this.lossyDCSub;if(e===fe.RELIABLE)return this.reliableDCSub}else{if(e===fe.LOSSY)return this.lossyDC;if(e===fe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var r,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const A=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new Zm({answer:A?aa({sdp:A.sdp,type:A.type}):void 0,offer:s?aa({sdp:s.sdp,type:s.type}):void 0,subscription:new Wo({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:zF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(r,i)=>{(r==null?void 0:r.id)!==void 0&&r.id!==null&&e.push(new $m({label:r.label,id:r.id,target:i}))};return t(this.dataChannelForKind(fe.LOSSY),un.PUBLISHER),t(this.dataChannelForKind(fe.RELIABLE),un.PUBLISHER),t(this.dataChannelForKind(fe.LOSSY,!0),un.SUBSCRIBER),t(this.dataChannelForKind(fe.RELIABLE,!0),un.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&yt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Kt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Kt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Gi extends Error{}function Fx(n){return n!==void 0&&n>13}function xx(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const r=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=r,e.destinationIdentities=r}class od{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ol(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return S(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 t=this.regionSettings.regions.filter(r=>!this.attemptedRegions.find(i=>i.url===r.url));if(t.length>0){const r=t[0];return this.attemptedRegions.push(r),ue.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return S(this,void 0,void 0,function*(){const t=yield fetch("".concat(Qx(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const r=yield t.json();return this.lastUpdateAt=Date.now(),r}else throw new Qe("Could not fetch region settings: ".concat(t.statusText),t.status===401?de.NotAllowed:de.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Qx(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class T0{get info(){return this._info}constructor(e,t,r){this.reader=t,this.totalByteSize=r,this._info=e,this.bytesReceived=0}}class Rx extends T0{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>S(this,void 0,void 0,function*(){try{const{done:t,value:r}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:r.content})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A=new Set;try{for(var s=!0,o=fr(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;A.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return Array.from(A)})}}class Px extends T0{constructor(e,t,r){super(e,t,r),this.receivedChunks=new Map}handleChunkReceived(e){var t;const r=sa(e.chunkIndex),i=this.receivedChunks.get(r);if(i&&i.version>e.version)return;this.receivedChunks.set(r,e),this.bytesReceived+=e.content.byteLength;const A=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,A)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>S(this,void 0,void 0,function*(){try{const{done:r,value:i}=yield e.read();return r?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A="";try{for(var s=!0,o=fr(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,A+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return A})}}class I0{constructor(e,t,r){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=r,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return S(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 Ox extends I0{}class Lx extends I0{}class F0 extends R{constructor(e,t,r,i,A){super(e,r,A),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?M.Muted:M.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=r=>{r.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(M.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(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(),nd)),XF()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const r=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(r){const{timestamp:i,rtpTimestamp:A}=r;A&&this.rtpTimestamp!==A&&(this.emit(M.TimeSyncUpdate,{timestamp:i,rtpTimestamp:A}),this.rtpTimestamp=A)}};e()}}class Dx extends F0{constructor(e,t,r,i,A,s){super(e,t,R.Kind.Audio,r,s),this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ca(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],A&&(this.sinkId=A.deviceId)}setVolume(e){var t;for(const r of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):r.volume=e;Tn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Tn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return S(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Pl(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Pl(e)&&e.setSinkId(this.sinkId).catch(r=>{this.log.error("Failed to set sink id on remote audio track",r,this.logContext)}),this.audioContext&&t&&(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 t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}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,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let r=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{r.connect(i),r=i}),this.gainNode=e.createGain(),r.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(M.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(M.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(r=>{r.type==="inbound-rtp"&&(t={type:"audio",streamId:r.id,timestamp:r.timestamp,jitter:r.jitter,bytesReceived:r.bytesReceived,concealedSamples:r.concealedSamples,concealmentEvents:r.concealmentEvents,silentConcealedSamples:r.silentConcealedSamples,silentConcealmentEvents:r.silentConcealmentEvents,totalAudioEnergy:r.totalAudioEnergy,totalSamplesDuration:r.totalSamplesDuration})}),t})}}const ad=100;class Mx extends F0{constructor(e,t,r,i,A){super(e,t,R.Kind.Video,r,A),this.elementInfos=[],this.monitorReceiver=()=>S(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=ca(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Zl(()=>{this.updateDimensions()},ad),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Mi(this._mediaStreamTrack,t):Di(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Nx(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===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 t=this.elementInfos.filter(r=>r===e);for(const r of t)r.stopObserving();this.elementInfos=this.elementInfos.filter(r=>r!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const r of t)this.stopObservingElement(r);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,r="",i=new Map;return e.forEach(A=>{A.type==="inbound-rtp"?(r=A.codecId,t={type:"video",streamId:A.id,framesDecoded:A.framesDecoded,framesDropped:A.framesDropped,framesReceived:A.framesReceived,packetsReceived:A.packetsReceived,packetsLost:A.packetsLost,frameWidth:A.frameWidth,frameHeight:A.frameHeight,pliCount:A.pliCount,firCount:A.firCount,nackCount:A.nackCount,jitter:A.jitter,timestamp:A.timestamp,bytesReceived:A.bytesReceived,decoderImplementation:A.decoderImplementation}):A.type==="codec"&&i.set(A.id,A)}),t&&r!==""&&i.get(r)&&(t.mimeType=i.get(r).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(r=>r.element===e);for(const r of t)this.stopObservingElementInfo(r)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const r=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,A=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||A;if(this.lastVisible!==s){if(!s&&Date.now()-r<ad){yt.setTimeout(()=>{this.updateVisibility()},ad);return}this.lastVisible=s,this.emit(M.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let r=0,i=0;const A=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*A,a=s.height()*A;o+a>r+i&&(r=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===r&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:r,height:i},this.emit(M.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Zv():t||(Zv()>2?2:1)}}class Nx{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=r=>{var i;const{target:A,isIntersecting:s}=r;A===this.element&&(this.isIntersecting=s,this.isPiP=YA(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var r,i,A;(i=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=YA(this.element),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this)},this.onLeavePiP=()=>{var r;this.isPiP=YA(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.element=e,this.isIntersecting=t??cd(e),this.isPiP=Kt()&&YA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,r;this.isIntersecting=cd(this.element),this.isPiP=YA(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,e0().observe(this.element),$v().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),(r=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,r,i,A;(e=e0())===null||e===void 0||e.unobserve(this.element),(t=$v())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(r=window.documentPictureInPicture)===null||r===void 0||r.removeEventListener("enter",this.onEnterPiP),(A=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||A===void 0||A.removeEventListener("pagehide",this.onLeavePiP)}}function YA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?cd(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function cd(n,e){const t=e||window;let r=n.offsetTop,i=n.offsetLeft;const A=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,r+=n.offsetTop,i+=n.offsetLeft;return r<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&r+s>t.pageYOffset&&i+A>t.pageXOffset&&!o&&a!=="none"}class jn extends Un.EventEmitter{constructor(e,t,r,i){var A;super(),this.metadataMuted=!1,this.encryption=Jt.NONE,this.log=ue,this.handleMuted=()=>{this.emit(M.Muted)},this.handleUnmuted=()=>{this.emit(M.Unmuted)},this.log=Kn((A=i==null?void 0:i.loggerName)!==null&&A!==void 0?A:ln.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=r,this.source=R.Source.Unknown}setTrack(e){this.track&&(this.track.off(M.Muted,this.handleMuted),this.track.off(M.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(M.Muted,this.handleMuted),e.on(M.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Be(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Jt.NONE}get audioTrack(){if(Gn(this.track))return this.track}get videoTrack(){if(Ki(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.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(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(jn||(jn={}));class ud extends jn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(M.Ended)},this.updateInfo(t),this.setTrack(r)}setTrack(e){this.track&&this.track.off(M.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(M.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 S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Gn(this.track)){const t=this.track.getSourceTrackSettings(),r=new Set;return t.autoGainControl&&r.add(cn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&r.add(cn.TF_ECHO_CANCELLATION),t.noiseSuppression&&r.add(cn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&r.add(cn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||r.add(cn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&r.add(cn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(r.values())}else return[]}}function ha(n,e){return S(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:A}=o0(n);let s=A.audio,o=A.video;if(r&&typeof A.audio=="object"&&(A.audio.processor=r),i&&typeof A.video=="object"&&(A.video.processor=i),n.audio&&typeof A.audio=="object"&&typeof A.audio.deviceId=="string"){const l=A.audio.deviceId;A.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},A.audio),{deviceId:{ideal:l}})}if(A.video&&typeof A.video=="object"&&typeof A.video.deviceId=="string"){const l=A.video.deviceId;A.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},A.video),{deviceId:{ideal:l}})}(A.audio===!0||typeof A.audio=="object"&&!A.audio.deviceId)&&(A.audio={deviceId:"default"}),A.video===!0?A.video={deviceId:"default"}:typeof A.video=="object"&&!A.video.deviceId&&(A.video.deviceId="default");const a=r0(A,m0,v0),c=jl(a),u=navigator.mediaDevices.getUserMedia(c);A.audio&&(pt.userMediaPromiseMap.set("audioinput",u),u.catch(()=>pt.userMediaPromiseMap.delete("audioinput"))),A.video&&(pt.userMediaPromiseMap.set("videoinput",u),u.catch(()=>pt.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>S(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let p;const g=h?c.audio:c.video;typeof g!="boolean"&&(p=g);const v=d.getSettings().deviceId;p!=null&&p.deviceId&&wr(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const y=mx(d,p,e);return y.kind===R.Kind.Video?y.source=R.Source.Camera:y.kind===R.Kind.Audio&&(y.source=R.Source.Microphone),y.mediaStream=l,Gn(y)&&r?yield y.setProcessor(r):Ki(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return ha(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function Hx(n){return S(this,void 0,void 0,function*(){return(yield ha({audio:!1,video:n??!0}))[0]})}function Kx(n){return S(this,void 0,void 0,function*(){return(yield ha({audio:n??!0,video:!1}))[0]})}var Br;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Br||(Br={}));function Vx(n){switch(n){case VA.EXCELLENT:return Br.Excellent;case VA.GOOD:return Br.Good;case VA.POOR:return Br.Poor;case VA.LOST:return Br.Lost;default:return Br.Unknown}}class x0 extends Un.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.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===jo.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ri.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,r,i,A,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:jo.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Br.Unknown,this.log=ue,this.log=Kn((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:ln.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=r,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=A??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Nl,this.once(V.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.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 t;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===Ri.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ri.ACTIVE&&this.emit(V.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,r=this.metadata;this.metadata=e,t&&this.emit(V.ParticipantMetadataChanged,r)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(V.ParticipantNameChanged,e)}_setAttributes(e){const t=YF(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(V.AttributesChanged,t)}setPermissions(e){var t,r,i,A,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((r=this.permissions)===null||r===void 0?void 0:r.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((A=this.permissions)===null||A===void 0?void 0:A.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(V.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(V.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Vx(e),t!==this._connectionQuality&&this.emit(V.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Gn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(M.Muted,()=>{this.emit(V.TrackMuted,e)}),e.on(M.Unmuted,()=>{this.emit(V.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Gx(n){var e,t,r;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Xm({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(r=n.allowAll)!==null&&r!==void 0?r:!1,trackSids:n.allowedTrackSids||[]})}const Q0=15e3;class jx extends x0{constructor(e,t,r,i,A){super(e,t,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=Jt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Nl)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,u=this.pendingSignalRequests.get(o);u&&(a!==pl.OK&&u.reject(new jv(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=Ye.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Gx(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Be(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Be(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Be(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.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 v=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,p=fr(v),g;g=yield p.next(),o=g.done,!o;f=!0){u=g.value,f=!1;const y=u;TF(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Be(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>S(this,void 0,void 0,function*(){if(s.source===R.Source.ScreenShare||s.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Be(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(ei(s)||br(s))try{if(Kt())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===R.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Be(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.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),Be(s))),ei(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),Be(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=r,this.roomOptions=i,this.setupEngine(r),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Jt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(N.RemoteMute,(t,r)=>{const i=this.trackPublications.get(t);!i||!i.track||(r?i.mute():i.unmute())}),this.engine.on(N.Connected,this.handleReconnected).on(N.SignalRestarted,this.handleReconnected).on(N.SignalResumed,this.handleReconnected).on(N.Restarting,this.handleReconnecting).on(N.Resuming,this.handleReconnecting).on(N.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(N.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(N.Disconnected,this.handleDisconnected).on(N.SignalRequestResponse,this.handleSignalRequestResponse).on(N.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return S(this,arguments,void 0,function(t){var r=this;let{metadata:i,name:A,attributes:s}=t;return function*(){return new Promise((o,a)=>S(r,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=A??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:A,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!A||this.name===A)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[p,g]=f;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(d),o();return}yield Ht(50)}a(new jv("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,r){return this.setTrackEnabled(R.Source.Camera,e,t,r)}setMicrophoneEnabled(e,t,r){return this.setTrackEnabled(R.Source.Microphone,e,t,r)}setScreenShareEnabled(e,t,r){return this.setTrackEnabled(R.Source.ScreenShare,e,t,r)}setPermissions(e){const t=this.permissions,r=super.setPermissions(e);return r&&t&&this.emit(V.ParticipantPermissionsChanged,t),r}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){this.encryptionType=e?Jt.GCM:Jt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,r,i){return S(this,void 0,void 0,function*(){var A,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let a;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 R.Source.Camera:a=yield this.createTracks({video:(A=r)!==null&&A!==void 0?A:!0});break;case R.Source.Microphone:a=yield this.createTracks({audio:(s=r)!==null&&s!==void 0?s:!0});break;case R.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Vn(e)}}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(V.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Be(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(R.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return S(this,void 0,void 0,function*(){var t,r;e??(e={});const i=r0(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(r=this.roomOptions)===null||r===void 0?void 0:r.videoCaptureDefaults);try{return(yield ha(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Gn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit(V.AudioStreamAcquired)),Ki(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(A){throw A instanceof Error&&(e.audio&&(this.microphoneError=A),e.video&&(this.cameraError=A)),A}})}createScreenTracks(e){return S(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Sl("getDisplayMedia not supported");e.resolution===void 0&&!PF()&&(e.resolution=xl.h1080fps30.resolution);const t=JF(e),r=yield navigator.mediaDevices.getDisplayMedia(t),i=r.getVideoTracks();if(i.length===0)throw new Vn("no video track found");const A=new da(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});A.source=R.Source.ScreenShare,e.contentHint&&(A.mediaStreamTrack.contentHint=e.contentHint);const s=[A];if(r.getAudioTracks().length>0){this.emit(V.AudioStreamAcquired);const o=new ua(r.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;ei(r)&&r.setAudioContext(A.audioContext),yield(o=A.reconnectFuture)===null||o===void 0?void 0:o.promise,A.republishPromise&&!s&&(yield A.republishPromise),Hi(r)&&A.pendingPublishPromises.has(r)&&(yield A.pendingPublishPromises.get(r));let l;if(r instanceof MediaStreamTrack)l=r.getConstraints();else{l=r.constraints;let v;switch(r.source){case R.Source.Microphone:v="audioinput";break;case R.Source.Camera:v="videoinput"}v&&A.activeDeviceMap.has(v)&&(l=Object.assign(Object.assign({},l),{deviceId:A.activeDeviceMap.get(v)}))}if(r instanceof MediaStreamTrack)switch(r.kind){case"audio":r=new ua(r,l,!0,A.audioContext,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;case"video":r=new da(r,l,!0,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;default:throw new Vn("unsupported MediaStreamTrack kind ".concat(r.kind))}else r.updateLoggerOptions({loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});let d;if(A.trackPublications.forEach(v=>{v.track&&v.track===r&&(d=v)}),d)return A.log.warn("track has already been published, skipping",Object.assign(Object.assign({},A.logContext),Be(d))),d;const h="channelCount"in r.mediaStreamTrack.getSettings()&&r.mediaStreamTrack.getSettings().channelCount===2||r.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&A.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},A.logContext),Be(r))),i.red===void 0&&A.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),(u=i.red)!==null&&u!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},A.roomOptions.publishDefaults),i);!OF()&&A.roomOptions.e2ee&&(A.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({},A.logContext)),p.simulcast=!1),p.source&&(r.source=p.source);const g=new Promise((v,y)=>S(A,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Le.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Be(r)}));const C=()=>S(this,void 0,void 0,function*(){try{const B=yield this.publish(r,p,f);v(B)}catch(B){y(B)}});setTimeout(()=>{this.engine.off(N.SignalConnected,C),y(new El("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(N.SignalConnected,C),this.engine.on(N.Closing,()=>{this.engine.off(N.SignalConnected,C),y(new El("publishing rejected as engine closed",499))})}else try{const C=yield this.publish(r,p,f);v(C)}catch(C){y(C)}}catch(C){y(C)}}));A.pendingPublishPromises.set(r,g);try{return yield g}catch(v){throw v}finally{A.pendingPublishPromises.delete(r)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Be(e))),!1;const{canPublish:t,canPublishSources:r}=this.permissions;return t&&(r.length===0||r.map(i=>ZF(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Be(e))),!1)}publish(e,t,r){return S(this,void 0,void 0,function*(){var i,A,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new El("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(b=>Hi(e)&&b.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Be(e))),t.stopMicTrackOnMute&&Gn(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Ni()&&(t.simulcast=!1),t.videoCodec==="av1"&&!xF()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!QF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=$l),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(b=>t.videoCodec===oa(b.mime))||(t.videoCodec=oa(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(M.Muted,this.onTrackMuted),e.on(M.Unmuted,this.onTrackUnmuted),e.on(M.Ended,this.handleTrackEnded),e.on(M.UpstreamPaused,this.onTrackUpstreamPaused),e.on(M.UpstreamResumed,this.onTrackUpstreamResumed),e.on(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new cl({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(!((A=t.red)!==null&&A!==void 0)||A),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let v;if(e.kind===R.Kind.Video){let b={width:0,height:0};try{b=yield e.waitForDimensions()}catch{const k=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:qA.h720.resolution;b={width:k.width,height:k.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{dims:b}))}g.width=b.width,g.height=b.height,br(e)&&(JA(p)&&(e.source===R.Source.ScreenShare&&(t.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),Be(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new al({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:$l}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===Jt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new al({codec:t.backupCodec.codec,cid:""})))),v=id(e.source===R.Source.ScreenShare,g.width,g.height,t),g.layers=k0(g.width,g.height,v,JA(t.videoCodec))}else e.kind===R.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ut("cannot publish track when not connected");const y=()=>S(this,void 0,void 0,function*(){var b,_,k;if(!this.engine.pcManager)throw new ut("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),br(e)&&((b=t.degradationPreference)!==null&&b!==void 0||(t.degradationPreference=Ex(e)),e.setDegradationPreference(t.degradationPreference)),v)if(Ni()&&e.kind===R.Kind.Audio){let U;for(const I of this.engine.pcManager.publisher.getTransceivers())if(I.sender===e.sender){U=I;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((_=v[0])===null||_===void 0)&&_.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&JA(e.codec)&&(!((k=v[0])===null||k===void 0)&&k.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([this.engine.addTrack(g),y()]))[0];else{C=yield this.engine.addTrack(g);let b;if(C.codecs.forEach(_=>{b===void 0&&(b=_.mimeType)}),b&&e.kind===R.Kind.Video){const _=oa(b);_!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{codec:_})),t.videoCodec=_,v=id(e.source===R.Source.ScreenShare,g.width,g.height,t))}yield y()}const B=new ud(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return B.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:C})),br(e)?e.startMonitor(this.engine.client):ei(e)&&e.startMonitor(),this.addTrackPublication(B),this.emit(V.LocalTrackPublished,B),B})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,r){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==Jt.NONE)return;let A;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(A=h)}),!A)throw new Vn("track is not published");if(!br(e))throw new Vn("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),r),o=_x(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Be(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new cl({cid:a.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=k0(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new ut("cannot publish track when not connected");const u=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return S(this,void 0,void 0,function*(){var r,i;if(Hi(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Be(e))),yield c)}const A=this.getPublicationForTrack(e),s=A?Be(A):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!A||!A.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=A.track,e.off(M.Muted,this.onTrackMuted),e.off(M.Unmuted,this.onTrackUnmuted),e.off(M.Ended,this.handleTrackEnded),e.off(M.UpstreamPaused,this.onTrackUpstreamPaused),e.off(M.UpstreamResumed,this.onTrackUpstreamResumed),e.off(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(r=this.roomOptions)===null||r===void 0?void 0:r.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Xe.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),br(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!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(A.trackSid),A.kind){case R.Kind.Audio:this.audioTrackPublications.delete(A.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(A.trackSid);break}return this.emit(V.LocalTrackUnpublished,A),A.setTrack(void 0),o&&(yield this.engine.negotiate()),A})}unpublishTracks(e){return S(this,void 0,void 0,function*(){return(yield Promise.all(e.map(r=>this.unpublishTrack(r)))).filter(r=>!!r)})}republishAllTracks(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){r.republishPromise&&(yield r.republishPromise),r.republishPromise=new Promise((A,s)=>S(r,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),o.push(a))}),yield Promise.all(o.map(a=>S(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==R.Source.ScreenShare&&c.source!==R.Source.ScreenShareAudio&&(ei(c)||br(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),A()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield r.republishPromise}()})}publishData(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const A=i.reliable?fe.RELIABLE:fe.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Nt({kind:A,value:{case:"user",value:new Im({participantIdentity:r.identity,payload:t,destinationIdentities:s,topic:o})}});yield r.engine.sendDataPacket(a,A)}()})}publishDtmf(e,t){return S(this,void 0,void 0,function*(){const r=new Nt({kind:fe.RELIABLE,value:{case:"sipDtmf",value:new Fm({code:e,digit:t})}});yield this.engine.sendDataPacket(r,fe.RELIABLE)})}sendChatMessage(e,t){return S(this,void 0,void 0,function*(){const r={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},i=new Nt({value:{case:"chatMessage",value:new nl(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp)}))}});return yield this.engine.sendDataPacket(i,fe.RELIABLE),this.emit(V.ChatMessage,r),r})}editChatMessage(e,t){return S(this,void 0,void 0,function*(){const r=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Nt({value:{case:"chatMessage",value:new nl(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp),editTimestamp:Ke.parse(r.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,fe.RELIABLE),this.emit(V.ChatMessage,r),r})}sendText(e,t){return S(this,void 0,void 0,function*(){var r;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(r=t==null?void 0:t.attachments)===null||r===void 0?void 0:r.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((p,g)=>p+g,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),c(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>S(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return S(this,void 0,void 0,function*(){var t,r;const i=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new il({streamId:i,mimeType:A.mimeType,topic:A.topic,timestamp:$r(A.timestamp),totalLength:$r(e==null?void 0:e.totalSize),attributes:A.attributes,contentHeader:{case:"textHeader",value:new Km({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"?rl.UPDATE:rl.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new Nt({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,fe.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return S(this,void 0,void 0,function*(){for(const p of WF(f,Q0)){yield u.engine.waitForBufferStatusLow(fe.RELIABLE);const g=new Al({content:p,streamId:i,chunkIndex:$r(c)}),v=new Nt({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield u.engine.sendDataPacket(v,fe.RELIABLE),c+=1}})},close(){return S(this,void 0,void 0,function*(){const f=new sl({streamId:i}),p=new Nt({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(p,fe.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>S(this,void 0,void 0,function*(){yield h.close()});u.engine.once(N.Closing,d);const h=new Ox(l,A,()=>this.engine.off(N.Closing,d));return h})}sendFile(e,t){return S(this,void 0,void 0,function*(){const r=crypto.randomUUID();return yield this._sendFile(r,e,t),{id:r}})}_sendFile(e,t,r){return S(this,void 0,void 0,function*(){var i;const A=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=r==null?void 0:r.mimeType)!==null&&i!==void 0?i:t.type,topic:r==null?void 0:r.topic,destinationIdentities:r==null?void 0:r.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield A.write(a)}return yield A.close(),A.info})}streamBytes(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(r=e==null?void 0:e.mimeType)!==null&&r!==void 0?r:"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:(A=e==null?void 0:e.name)!==null&&A!==void 0?A:"unknown"},u=new il({totalLength:$r((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:$r(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Vm({name:c.name})}}),l=new Nt({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,fe.RELIABLE);let d=0;const h=new Dt,f=this.engine,p=this.log,g=new WritableStream({write(y){return S(this,void 0,void 0,function*(){const C=yield h.lock();let B=0;try{for(;B<y.byteLength;){const b=y.slice(B,B+Q0);yield f.waitForBufferStatusLow(fe.RELIABLE);const _=new Nt({destinationIdentities:a,value:{case:"streamChunk",value:new Al({content:b,streamId:o,chunkIndex:$r(d)})}});yield f.sendDataPacket(_,fe.RELIABLE),d+=1,B+=b.byteLength}}finally{C()}})},close(){return S(this,void 0,void 0,function*(){const y=new sl({streamId:o}),C=new Nt({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(C,fe.RELIABLE)})},abort(y){p.error("Sink error:",y)}});return new Lx(g,c)})}performRpc(e){return S(this,arguments,void 0,function(t){var r=this;let{destinationIdentity:i,method:A,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>S(r,void 0,void 0,function*(){var l,d,h,f;if(td(s)>y0){u(Ye.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&Zr((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){u(Ye.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,A,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),u(Ye.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(v)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:i});const v=setTimeout(()=>{this.pendingResponses.delete(p),u(Ye.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(y,C)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),C?u(C):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,r){const i=this.pendingResponses.get(e);i?(i.resolve(t,r),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=new Nt({destinationIdentities:[e],kind:fe.RELIABLE,value:{case:"rpcRequest",value:new xm({id:t,method:r,payload:i,responseTimeoutMs:A,version:1})}});yield this.engine.sendDataPacket(s,fe.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:r}]of this.pendingAcks)r===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:r,resolve:i}]of this.pendingResponses)r===e&&(i(null,Ye.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var r,i;const A=this.trackPublications.get(t.sid);if(A){const s=A.isMuted||((i=(r=A.track)===null||r===void 0?void 0:r.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Be(A)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(r=>{const i=r.track;i&&(e instanceof MediaStreamTrack?(ei(i)||br(i))&&i.mediaStreamTrack===e&&(t=r):e===i&&(t=r))}),t}waitForPendingPublicationOfSource(e){return S(this,void 0,void 0,function*(){const r=Date.now();for(;Date.now()<r+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(A=>{let[s]=A;return s.source===e});if(i)return i[1];yield Ht(20)}})}}class Wx extends jn{constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=$t.HIGH,this.handleEnded=A=>{this.setTrack(void 0),this.emit(M.Ended,A)},this.handleVisibilityChange=A=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(A),this.logContext),this.disabled=!A,this.emitTrackUpdate()},this.handleVideoDimensionsChange=A=>{this.log.debug("adaptivestream video dimensions ".concat(A.width,"x").concat(A.height),this.logContext),this.videoDimensions=A,this.emitTrackUpdate()},this.subscribed=r,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Wo({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Om({participantSid:"",trackSids:[this.trackSid]})]});this.emit(M.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(r)}get subscriptionStatus(){return this.subscribed===!1?jn.SubscriptionStatus.Unsubscribed:super.isSubscribed?jn.SubscriptionStatus.Subscribed:jn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?jn.PermissionStatus.Allowed:jn.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 t,r;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((r=this.videoDimensions)===null||r===void 0?void 0:r.height)===e.height||(Vl(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Vl(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,r=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(M.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(M.VisibilityChanged,this.handleVisibilityChange),i.off(M.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(M.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(M.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(M.VisibilityChanged,this.handleVisibilityChange),e.on(M.Ended,this.handleEnded),this.emit(M.Subscribed,e)),this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(M.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?M.Muted:M.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(M.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(M.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===R.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 Vl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new jm({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=$t.HIGH,this.emit(M.UpdateSettings,e)}}class pa extends x0{static fromParticipantInfo(e,t,r){return new pa(e,t.sid,t.identity,t.name,t.metadata,t.attributes,r,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,r,i,A,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:jo.STANDARD;super(t,r||"",i,A,s,o,a),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(M.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Be(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(M.UpdateSubscription,t=>{t.participantTracks.forEach(r=>{r.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(M.SubscriptionPermissionChanged,t=>{this.emit(V.TrackSubscriptionPermissionChanged,e,t)}),e.on(M.SubscriptionStatusChanged,t=>{this.emit(V.TrackSubscriptionStatusChanged,e,t)}),e.on(M.Subscribed,t=>{this.emit(V.TrackSubscribed,t,e)}),e.on(M.Unsubscribed,t=>{this.emit(V.TrackUnsubscribed,t,e)}),e.on(M.SubscriptionFailed,t=>{this.emit(V.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:R.Source.Microphone;this.volumeMap.set(t,e);const r=this.getTrackPublication(t);r&&r.track&&r.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,r,i,A,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(V.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,r,i,A,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),Be(o))),this.emit(V.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new Mx(e,t,i,A):c=new Dx(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(r),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Kl(c)&&Gn(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,r=new Map;return e.tracks.forEach(i=>{var A,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=R.kindFromProto(i.type);if(!a)return;o=new Wx(a,i,(A=this.signalClient.connectOptions)===null||A===void 0?void 0:A.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),r.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==R.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Be(c),newTrack:Be(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Be(i))),this.unpublishTrack(i.trackSid,!0))}),r.forEach(i=>{this.emit(V.TrackPublished,i)}),!0}unpublishTrack(e,t){const r=this.trackPublications.get(e);if(!r)return;const{track:i}=r;switch(i&&(i.stop(),r.setTrack(void 0)),this.trackPublications.delete(e),r.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(V.TrackUnpublished,r)}setAudioOutput(e){return S(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(r=>{var i;Gn(r.track)&&Kl(r.track)&&t.push(r.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:r})),super.emit(e,...r)}}var ge;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ge||(ge={}));const qx=4*1e3;class ji extends Un.EventEmitter{constructor(e){var t,r,i,A;if(super(),t=this,this.state=ge.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ue,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,o,a)=>S(this,void 0,void 0,function*(){var c;if(!RF())throw Tn()?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 u=yield this.disconnectLock.lock();if(this.state===ge.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(ge.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ol(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new od(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const l=(h,f,p)=>S(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{yield this.attemptConnection(p??s,o,a,y),this.abortController=void 0,h()}catch(C){if(this.regionUrlProvider&&C instanceof Qe&&C.reason!==de.Cancelled&&C.reason!==de.NotAllowed){let B=null;try{B=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(b){if(b instanceof Qe&&(b.status===401||b.reason===de.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(b);return}}B&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(B),this.logContext),this.recreateEngine(),yield l(h,f,B)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,n0(C)),f(C))}else{let B=an.UNKNOWN_REASON;C instanceof Qe&&(B=n0(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,B),f(C)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Nl((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>S(this,void 0,void 0,function*(){var d,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(v=>{let[y,C]=v;return"".concat(y,": ").concat(C)}).join(", ")),{room:(d=p.room)===null||d===void 0?void 0:d.name,roomSid:(h=p.room)===null||h===void 0?void 0:h.sid,identity:(f=p.participant)===null||f===void 0?void 0:f.identity}),!g.version)throw new yF("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>S(this,void 0,void 0,function*(){var u,l;this.state===ge.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ed),a),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,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Qe("could not establish signal connection",de.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Qe&&(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 Qe("Connection attempt aborted",de.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Kt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Kt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ge.Connected),this.emit(L.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return S(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===ge.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===ge.Connecting||c.state===ge.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Qe("Client initiated disconnect",de.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,an.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const s=[],o=dn();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=Ml();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,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(L.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>S(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{s.includes(u)||s.push(u)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.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(ge.Reconnecting)&&this.emit(L.Reconnecting)},this.handleSignalRestarted=s=>S(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(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}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(ge.Connected),this.emit(L.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Ri.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(L.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(L.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=R.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(V.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(L.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);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 a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(L.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(V.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(L.SipDTMFReceived,o,s),s==null||s.emit(V.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a==null?void 0:a.trackPublications.get(o.trackId),u=KF(o,this.transcriptionReceivedTimes);c==null||c.emit(M.TranscriptionReceived,u),a==null||a.emit(V.TranscriptionReceived,u,c),this.emit(L.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=VF(o);this.emit(L.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(L.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(L.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(L.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(L.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(L.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var s,o,a;const c=pt.getInstance().previousDevices,u=yield pt.getInstance().getDevices(void 0,!1),l=dn();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of u){const f=c.find(p=>p.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(L.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=qF(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=u.filter(y=>y.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&g.length>0&&((a=g[0])===null||a===void 0?void 0:a.deviceId)!==v){yield this.switchActiveDevice(h,g[0].deviceId);continue}h==="audioinput"&&!yr()||h==="videoinput"||g.length>0&&!g.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(L.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(L.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(L.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(L.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(L.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(L.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(L.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(L.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(M.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(L.LocalTrackPublished,s,this.localParticipant),ei(s.track)&&(yield s.track.checkForSilence())&&this.emit(L.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=s0(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(L.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(M.Restarted,this.onLocalTrackRestarted),this.emit(L.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>S(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=s0(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(L.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(L.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(L.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(L.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(L.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},px),e),this.log=Kn((r=this.options.loggerName)!==null&&r!==void 0?r:ln.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},m0),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},v0),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},hx),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Dt,this.localParticipant=new jx("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",wr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",wr(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",wr(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Kt()){const s=new AbortController;(A=navigator.mediaDevices)===null||A===void 0||A.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),ji.cleanupRegistry&&ji.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,r,i,A,s){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,Ye.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(r);if(!o){yield this.engine.publishRpcResponse(e,t,null,Ye.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:A});td(u)>y0?(a=Ye.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(r))):c=u}catch(u){u instanceof Ye?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),a=Ye.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return S(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 $F(this.options.e2ee),this.e2eeManager.on(mr.ParticipantEncryptionStatusChanged,(t,r)=>{jF(r)&&(this.isE2EEEnabled=t),this.emit(L.ParticipantEncryptionStatusChanged,t,r)}),this.e2eeManager.on(mr.EncryptionError,t=>this.emit(L.EncryptionError,t)),(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,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return S(this,void 0,void 0,function*(){return this.state===ge.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const r=i=>{i.sid!==""&&(this.engine.off(N.RoomUpdate,r),e(i.sid))};this.engine.on(N.RoomUpdate,r),this.once(L.Disconnected,()=>{this.engine.off(N.RoomUpdate,r),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ix(this.options),this.engine.on(N.ParticipantUpdate,this.handleParticipantUpdates).on(N.RoomUpdate,this.handleRoomUpdate).on(N.SpeakersChanged,this.handleSpeakersChanged).on(N.StreamStateChanged,this.handleStreamStateUpdate).on(N.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(N.SubscriptionError,this.handleSubscriptionError).on(N.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(N.MediaTrackAdded,(e,t,r)=>{this.onTrackAdded(e,t,r)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ge.SignalReconnecting)&&this.emit(L.SignalReconnecting)}).on(N.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ge.Connected)&&this.emit(L.Reconnected)}).on(N.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ge.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.Offline,()=>{this.setAndEmitConnectionState(ge.Reconnecting)&&this.emit(L.Reconnecting)}).on(N.DCBufferStatusChanged,(e,t)=>{this.emit(L.DCBufferStatusChanged,e,t)}).on(N.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(r=>{let{trackSid:i}=r;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(V.LocalTrackSubscribed,t),this.emitWhenConnected(L.LocalTrackSubscribed,t,this.localParticipant)}).on(N.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,r)=>{this.handleParticipantDisconnected(r,t)}),this.emit(L.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 t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pt.getInstance().getDevices(e,t)}prepareConnection(e,t){return S(this,void 0,void 0,function*(){if(this.state===ge.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ol(new URL(e))&&t){this.regionUrlProvider=new od(e,t);const r=yield this.regionUrlProvider.getNextBestRegionUrl();r&&this.state===ge.Disconnected&&(this.regionUrl=r,yield fetch(Hl(r),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(r),this.logContext))}else yield fetch(Hl(e),{method:"HEAD"})}catch(r){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:r}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return S(this,void 0,void 0,function*(){let r=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new En({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new En({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new En({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new En({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":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new En({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new En({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 En({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),r=()=>S(this,void 0,void 0,function*(){const A=this.engine.client.onLeave;A&&A(new qo({reason:an.CLIENT_INITIATED,action:Oi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new En({scenario:{case:"subscriberBandwidth",value:$r(t)}});break;case"leave-full-reconnect":i=new En({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield r())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(r==="audioinput"){g=A.localParticipant.audioTrackPublications.size===0;const y=(o=A.getActiveDevice(r))!==null&&o!==void 0?o:A.options.audioCaptureDefaults.deviceId;A.options.audioCaptureDefaults.deviceId=v;const C=Array.from(A.localParticipant.audioTrackPublications.values()).filter(B=>B.source===R.Source.Microphone);try{p=(yield Promise.all(C.map(B=>{var b;return(b=B.audioTrack)===null||b===void 0?void 0:b.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw A.options.audioCaptureDefaults.deviceId=y,B}}else if(r==="videoinput"){g=A.localParticipant.videoTrackPublications.size===0;const y=(a=A.getActiveDevice(r))!==null&&a!==void 0?a:A.options.videoCaptureDefaults.deviceId;A.options.videoCaptureDefaults.deviceId=v;const C=Array.from(A.localParticipant.videoTrackPublications.values()).filter(B=>B.source===R.Source.Camera);try{p=(yield Promise.all(C.map(B=>{var b;return(b=B.videoTrack)===null||b===void 0?void 0:b.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw A.options.videoCaptureDefaults.deviceId=y,B}}else if(r==="audiooutput"){if(!Pl()&&!A.options.webAudioMix||A.options.webAudioMix&&A.audioContext&&!("setSinkId"in A.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");A.options.webAudioMix&&(i=(c=yield pt.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=A.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=A.getActiveDevice(r))!==null&&l!==void 0?l:A.options.audioOutput.deviceId;A.options.audioOutput.deviceId=i;try{A.options.webAudioMix&&((d=A.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(A.remoteParticipants.values()).map(C=>C.setAudioOutput({deviceId:i})))}catch(C){throw A.options.audioOutput.deviceId=y,C}}return(g||r==="audiooutput")&&(A.localParticipant.activeDeviceMap.set(r,r==="audiooutput"&&((h=A.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),A.emit(L.ActiveDeviceChanged,r,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(V.AttributesChanged,this.onLocalAttributesChanged).on(V.TrackMuted,this.onLocalTrackMuted).on(V.TrackUnmuted,this.onLocalTrackUnmuted).on(V.LocalTrackPublished,this.onLocalTrackPublished).on(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(V.MediaDevicesError,this.onMediaDevicesError).on(V.AudioStreamAcquired,this.startAudio).on(V.ChatMessage,this.onLocalChatMessageSent).on(V.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,t,r){if(this.state===ge.Connecting||this.state===ge.Reconnecting){const u=()=>{this.onTrackAdded(e,t,r),l()},l=()=>{this.off(L.Reconnected,u),this.off(L.Connected,u),this.off(L.Disconnected,l)};this.once(L.Reconnected,u),this.once(L.Connected,u),this.once(L.Disconnected,l);return}if(this.state===ge.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=FF(t.id),A=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),A===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===A);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(A),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,r,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ge.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{i.unpublishTrack(A.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var A,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((A=i.track)===null||A===void 0||A.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(V.AttributesChanged,this.onLocalAttributesChanged).off(V.TrackMuted,this.onLocalTrackMuted).off(V.TrackUnmuted,this.onLocalTrackUnmuted).off(V.LocalTrackPublished,this.onLocalTrackPublished).off(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(V.MediaDevicesError,this.onMediaDevicesError).off(V.AudioStreamAcquired,this.startAudio).off(V.ChatMessage,this.onLocalChatMessageSent).off(V.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),Kt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=navigator.mediaDevices)===null||r===void 0||r.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ge.Disconnected),this.emit(L.Disconnected,t)}}}handleParticipantDisconnected(e,t){var r;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(L.ParticipantDisconnected,t),t.setDisconnected(),(r=this.localParticipant)===null||r===void 0||r.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return S(this,void 0,void 0,function*(){var r;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 A;const s={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sa(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Rx(s,o,sa(e.totalLength)),{identity:t})}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 A;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},o=new ReadableStream({start:a=>{A=a,this.textStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Px(s,o,sa(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const r=this.textStreamControllers.get(e.streamId);r&&e.content.length>0&&r.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return S(this,void 0,void 0,function*(){var e,t;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=A0())!==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(),Ht(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const r=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(L.AudioPlaybackStatusChanged,r))})}createParticipant(e,t){var r;let i;return t?i=pa.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new pa(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(A=>this.log.warn("Could not set audio output: ".concat(A.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const r=this.createParticipant(e,t);return this.remoteParticipants.set(e,r),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(L.ParticipantConnected,r),r.on(V.TrackPublished,i=>{this.emitWhenConnected(L.TrackPublished,i,r)}).on(V.TrackSubscribed,(i,A)=>{i.kind===R.Kind.Audio?(i.on(M.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(M.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===R.Kind.Video&&(i.on(M.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(M.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(L.TrackSubscribed,i,A,r)}).on(V.TrackUnpublished,i=>{this.emit(L.TrackUnpublished,i,r)}).on(V.TrackUnsubscribed,(i,A)=>{this.emit(L.TrackUnsubscribed,i,A,r)}).on(V.TrackMuted,i=>{this.emitWhenConnected(L.TrackMuted,i,r)}).on(V.TrackUnmuted,i=>{this.emitWhenConnected(L.TrackUnmuted,i,r)}).on(V.ParticipantMetadataChanged,i=>{this.emitWhenConnected(L.ParticipantMetadataChanged,i,r)}).on(V.ParticipantNameChanged,i=>{this.emitWhenConnected(L.ParticipantNameChanged,i,r)}).on(V.AttributesChanged,i=>{this.emitWhenConnected(L.ParticipantAttributesChanged,i,r)}).on(V.ConnectionQualityChanged,i=>{this.emitWhenConnected(L.ConnectionQualityChanged,i,r)}).on(V.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(L.ParticipantPermissionsChanged,i,r)}).on(V.TrackSubscriptionStatusChanged,(i,A)=>{this.emitWhenConnected(L.TrackSubscriptionStatusChanged,i,A,r)}).on(V.TrackSubscriptionFailed,(i,A)=>{this.emit(L.TrackSubscriptionFailed,i,r,A)}).on(V.TrackSubscriptionPermissionChanged,(i,A)=>{this.emitWhenConnected(L.TrackSubscriptionPermissionChanged,i,A,r)}).on(V.Active,()=>{this.emitWhenConnected(L.ParticipantActive,r)}),t&&r.updateInfo(t),r}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,i)=>(r.push(...i.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&GF(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=yt.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,an.STATE_MISMATCH))):e=0},qx)}clearConnectionReconcile(){this.connectionReconcileInterval&&yt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(L.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,r]=e;this.emit(t,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(this.state===ge.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,r]);else if(this.state===ge.Connected)return this.emit(e,...r);return!1}simulateParticipants(e){return S(this,void 0,void 0,function*(){var t,r;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),A=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Vo({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ke.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Jr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected),this.emit(L.Connected),this.setAndEmitConnectionState(ge.Connected),i.video){const s=new ud(R.Kind.Video,new Pi({source:ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO,name:"video-dummy"}),new da(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:t0(160*((t=A.aspectRatios[0])!==null&&t!==void 0?t: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(V.LocalTrackPublished,s)}if(i.audio){const s=new ud(R.Kind.Audio,new Pi({source:ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO}),new ua(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ml(),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(V.LocalTrackPublished,s)}for(let s=0;s<A.count-1;s+=1){let o=new Jr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ri.ACTIVE,tracks:[],joinedAt:Ke.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(A.video){const c=t0(160*((r=A.aspectRatios[s%A.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),u=new Pi({source:ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(A.audio){const c=Ml(),u=new Pi({source:ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(e!==L.ActiveSpeakersChanged&&e!==L.TranscriptionReceived){const A=R0(r).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:A}))}return super.emit(e,...r)}}ji.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function R0(n){return n.map(e=>{if(e)return Array.isArray(e)?R0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var fn;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(fn||(fn={}));class _r extends Un.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=fn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ji(r.roomOptions),this.connectOptions=r.connectOptions,this.options=r}run(e){return S(this,void 0,void 0,function*(){if(this.status!==fn.IDLE)throw Error("check is running already");this.setStatus(fn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==fn.SKIPPED&&this.setStatus(this.isSuccess()?fn.SUCCESS:fn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return S(this,void 0,void 0,function*(){return this.room.state===ge.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==ge.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(fn.SKIPPED)}switchProtocol(e){return S(this,void 0,void 0,function*(){let t=!1,r=!1;if(this.room.on(L.Reconnecting,()=>{t=!0}),this.room.once(L.Reconnected,()=>{r=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(A=>setTimeout(A,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(r)return;yield Ht(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 Jx extends _r{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const e=new od(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],r=new Set;for(let A=0;A<3;A++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(r.has(s))continue;r.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((A,s)=>(A.duration-s.duration)*.5+(A.rtt-s.rtt)*.5);const i=t[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 S(this,void 0,void 0,function*(){var t,r;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const A=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield A.write(c);yield A.close();const l=Date.now(),d=yield(r=this.room.engine.pcManager)===null||r===void 0?void 0:r.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const ld=1e4;class zx extends _r{get description(){return"Connection via UDP vs TCP"}perform(){return S(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const r=this.bestStats;this.appendMessage("upstream bitrate: ".concat((r.bitrateTotal/r.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((r.rttTotal/r.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((r.jitterTotal/r.count*1e3).toFixed(2)," ms")),r.packetsLost>0&&this.appendWarning("packets lost: ".concat((r.packetsLost/r.packetsSent*100).toFixed(2),"%")),r.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((r.qualityLimitationDurations.bandwidth/(ld/1e3)*100).toFixed(2),"%")),r.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((r.qualityLimitationDurations.cpu/(ld/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return S(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const r=t.getContext("2d");if(!r)throw new Error("Could not get canvas context");let i=0;const A=()=>{i=(i+1)%360,r.fillStyle="hsl(".concat(i,", 100%, 50%)"),r.fillRect(0,0,t.width,t.height),requestAnimationFrame(A)};A();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>S(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,ld)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class Xx extends _r{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Kx();if(yield i0(r,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(r),yield new Promise(o=>setTimeout(o,3e3));const A=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!A)throw new Error("Could not get RTCStats");let s=0;if(A.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class Yx extends _r{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Hx();yield this.checkForVideo(r.mediaStreamTrack),t.localParticipant.publishTrack(r),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let A=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(A+=s.packetsSent)}),A===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(A," video packets"))})}checkForVideo(e){return S(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const r=document.createElement("video");r.srcObject=t,r.muted=!0,yield new Promise(i=>{r.onplay=()=>{setTimeout(()=>{var A,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(A=u.width)!==null&&A!==void 0?A:r.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:r.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(r,0,0);const p=h.getImageData(0,0,c.width,c.height).data;let g=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},r.play()}),r.remove()})}}class Zx extends _r{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect();let r=!1,i=!1,A;const s=new Promise(c=>{setTimeout(c,5e3),A=c}),o=()=>{r=!0};t.on(L.SignalReconnecting,o).on(L.Reconnecting,o).on(L.Reconnected,()=>{i=!0,A(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,r){if(!i||t.state!==ge.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 $x extends _r{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var e,t;const r=new ql,i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let A=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,A=!0),c.startsWith("stun:")&&(o=!0);o?s&&!A&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class eQ extends _r{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(L.SignalConnected,()=>{const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,A)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(tQ(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}r&&r(i,A)},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(),ue.info("now the room is connected")}catch(r){throw this.appendWarning("ports need to be open on firewall in order to connect."),r}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function tQ(n){const e=n.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 t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class nQ extends _r{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var e,t,r;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new ql;const A=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(A.serverVersion,".")),((e=A.serverInfo)===null||e===void 0?void 0:e.edition)===Lm.Cloud&&(!((t=A.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((r=A.serverInfo)===null||r===void 0?void 0:r.region)),yield i.close()})}}class Q4 extends Un.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=r}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:fn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==fn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return S(this,void 0,void 0,function*(){const t=this.getNextCheckId(),r=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};r.on("update",i);const A=yield r.run();return r.off("update",i),A})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(nQ)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(eQ)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck($x)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Zx)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Xx)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Yx)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(zx);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Jx)})}}const rQ=/\{[^{}]+\}/g;function iQ(){return Math.random().toString(36).slice(2,11)}function AQ(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:A,headers:s,...o}={...n};e=D0(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=r,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:y,bodySerializer:C=A??oQ,body:B,...b}=l||{};d&&(e=D0(d));let _=typeof i=="function"?i:L0(i);y&&(_=typeof y=="function"?y:L0({...typeof i=="object"?i:{},...y}));const k=B===void 0?void 0:C(B),U=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},I={redirect:"follow",...o,...b,body:k,headers:cQ(U,s,p,g.header)};let P,x,O=new t(aQ(u,{baseUrl:e,params:g,querySerializer:_}),I);for(const F in b)F in O||(O[F]=b[F]);if(a.length){P=iQ(),x=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:_,bodySerializer:C});for(const F of a)if(F&&typeof F=="object"&&typeof F.onRequest=="function"){const D=await F.onRequest({request:O,schemaPath:u,params:g,options:x,id:P});if(D){if(!(D instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");O=D}}}let H=await h(O);if(a.length)for(let F=a.length-1;F>=0;F--){const D=a[F];if(D&&typeof D=="object"&&typeof D.onResponse=="function"){const X=await D.onResponse({request:O,response:H,schemaPath:u,params:g,options:x,id:P});if(X){if(!(X instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");H=X}}}if(H.status===204||H.headers.get("Content-Length")==="0")return H.ok?{data:{},response:H}:{error:{},response:H};if(H.ok)return v==="stream"?{data:H.body,response:H}:{data:await H[v](),response:H};let z=await H.text();try{z=JSON.parse(z)}catch{}return{error:z,response:H}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function fa(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${(t==null?void 0:t.allowReserved)===!0?e:encodeURIComponent(e)}`}function P0(n,e,t){if(!e||typeof e!="object")return"";const r=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)r.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=r.join(",");switch(t.style){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${n}[${s}]`:s;r.push(fa(o,e[s],t))}const A=r.join(i);return t.style==="label"||t.style==="matrix"?`${i}${A}`:A}function O0(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const A={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(A);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return`${n}=${s}`}}const r={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const A of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?A:encodeURIComponent(A)):i.push(fa(n,A,t));return t.style==="label"||t.style==="matrix"?`${r}${i.join(r)}`:i.join(r)}function L0(n){return function(t){const r=[];if(t&&typeof t=="object")for(const i in t){const A=t[i];if(A!=null){if(Array.isArray(A)){if(A.length===0)continue;r.push(O0(i,A,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof A=="object"){r.push(P0(i,A,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}r.push(fa(i,A,n))}}return r.join("&")}}function sQ(n,e){let t=n;for(const r of n.match(rQ)??[]){let i=r.substring(1,r.length-1),A=!1,s="simple";if(i.endsWith("*")&&(A=!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 o=e[i];if(Array.isArray(o)){t=t.replace(r,O0(i,o,{style:s,explode:A}));continue}if(typeof o=="object"){t=t.replace(r,P0(i,o,{style:s,explode:A}));continue}if(s==="matrix"){t=t.replace(r,`;${fa(i,o)}`);continue}t=t.replace(r,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function oQ(n){return n instanceof FormData?n:JSON.stringify(n)}function aQ(n,e){var i;let t=`${e.baseUrl}${n}`;(i=e.params)!=null&&i.path&&(t=sQ(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function cQ(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const r=t instanceof Headers?t.entries():Object.entries(t);for(const[i,A]of r)if(A===null)e.delete(i);else if(Array.isArray(A))for(const s of A)e.append(i,s);else A!==void 0&&e.set(i,A)}return e}function D0(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const M0="Onboardee-Session-Token",N0="OnboardeeSessionToken";class H0{constructor(e){this.client=AQ({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const r=window.localStorage.getItem(N0);r&&t.headers.set(M0,r)}return t},onResponse({response:t}){const r=t.headers.get(M0);return r&&window.localStorage&&window.localStorage.setItem(N0,r),t}})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}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,t={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:t})}async clientStartSession(e,t){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:t})}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,t){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:t})}async listPlans(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}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,t,r,i){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r},...i&&{course_id:i}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,t){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:t})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,t){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:t})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,t){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async searchProductKnowledgeBlocks(e,t,r){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...r&&{limit:r.toString()}}}})}async updateProductKnowledgeBlock(e,t,r){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}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 getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getPlanAnalytics(e,t,r){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r}}}})}async replacePlan(e,t){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:t})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}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,t){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updatePlanKnowledgeBlock(e,t,r){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deletePlanKnowledgeBlock(e,t){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,t){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,t){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,t){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:t})}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,t){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async createRevisionKnowledgeBlock(e,t){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updateRevisionKnowledgeBlock(e,t,r){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e,t){const r={token:e};return t!=null&&t.productId&&(r.product_id=t.productId),t!=null&&t.startDate&&(r.start_date=t.startDate),t!=null&&t.endDate&&(r.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:r}})}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,t){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:t}}})}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,t){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:t})}async listUserSessions(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),e!=null&&e.courseName&&(t.course_name=e.courseName),e!=null&&e.userName&&(t.user_name=e.userName),e!=null&&e.company&&(t.company=e.company),e!=null&&e.email&&(t.email=e.email),e!=null&&e.sortBy&&(t.sort_by=e.sortBy),e!=null&&e.sortOrder&&(t.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(t).length>0?{query:t}:void 0})}async listUserSessionsAggregate(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(t).length>0?{query:t}:void 0})}async getJoinToken(e,{clientType:t,user:r}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...r&&{user:encodeURIComponent(r)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}async getPlanSDK(e){return await this.client.GET("/api/plans/{uuid}/sdk",{params:{path:{uuid:e}}})}getClient(){return this.client}}const K0="https://app.coragents.ai";class ga extends qc{constructor(e,t,r,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.startedAt=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=t,this.clientType=r,this.api=i.api||new H0({baseUrl:K0}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(A=>new ji(A)),this.captureScreen=i.captureScreen||null}async start(){this.planId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const t=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(t!=null&&t.url)||!(t!=null&&t.token)||!(t!=null&&t.room)||!(t!=null&&t.session_uuid))throw new Error("Invalid room info");this.sessionUuid=t==null?void 0:t.session_uuid,this.roomId=t==null?void 0:t.room,this.joinToken=t==null?void 0:t.token,this.roomUrl=t==null?void 0:t.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("connected"),this.planId,this.sessionUuid}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(L.Disconnected,r=>{if(!this.room)return;let i=null;switch(r){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(L.TrackSubscribed,r=>{r.kind==="audio"&&(r.attach(),r.source===R.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(r.mediaStream)))}),this.room.on(L.LocalTrackPublished,r=>{r.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(r.audioTrack.mediaStream))}),this.room.on(L.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"])return;const i=r["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(L.DataReceived,async r=>{try{const i=new TextDecoder().decode(r),A=JSON.parse(i);switch(A.status||A.request||A.type){case"course_progress":typeof A.current_step=="number"&&typeof A.total_steps=="number"&&Array.isArray(A.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,A.current_step),totalSteps:Math.max(1,A.total_steps),stepNames:A.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;case"shutdown":this.shutdown("server-sent");break;default:console.warn("[obi] unknown data received",A)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async r=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async r=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,A=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||A)return console.error("[obi] error capturing screen",{error:A}),"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 r=0;r<9&&!(this.room.state===ge.Connected&&this.room.remoteParticipants.size>=1);r++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===ge.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),t){let r=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(r=!0);r?this.speakingState="speaking":this.speakingState="listening"}}async continue(){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(t){console.error("[obi] error checking microphone permission:",t)}return e?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid,this.speakingStateChanged("thinking");let e=null,t=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){r=r,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){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(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleMuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleUnmuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){this.sessionUuid,e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),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,startedAt:this.startedAt})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const r=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const A=[],s=50,o=5e3,a=8,c=Math.pow(o/s,1/a);for(let u=0;u<a;u++){const l=s*Math.pow(c,u),d=s*Math.pow(c,u+1),h=Math.floor(l/r),f=Math.floor(d/r),p=Math.min(f,i.length),g=Math.min(h,p);if(g<p){const v=i.slice(g,p).reduce((y,C)=>y+C,0)/(p-g)/255;A.push(v)}else A.push(0)}return A}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,r,i={}){const A=JSON.parse(e),s=new ga(t,A.planId,r,i);return s.state=A.state,s.speakingState=A.speakingState,s.identity=A.identity||null,s.isPaused=A.isPaused||!1,s.sessionUuid=A.sessionUuid||null,s.roomId=A.roomId||null,s.joinToken=A.joinToken||null,s.roomUrl=A.roomUrl||null,s.startedAt=A.startedAt||null,s}speakingStateChanged(e){this.speakingState;const t=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,t)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const t=new AudioContext,r=t.createAnalyser();return t.createMediaStreamSource(e).connect(r),r.fftSize=2048,r.smoothingTimeConstant=.6,r}}class ma extends qc{constructor(e,t,r={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=t,this.api=r.api||new H0({baseUrl:r.apiBaseUrl||K0}),this.sessionFactory=r.sessionFactory||((i,A,s,o)=>new ga(i,A,s,o)),this.captureScreen=r.captureScreen||null}async initialise(e={}){var t,r,i,A,s;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const o=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=o.data)==null?void 0:t.product)||null,this.plans=((r=o.data)==null?void 0:r.onboarding_plans)||[],this.selectedPlan=((i=o.data)==null?void 0:i.selected_plan)||null,this.planIsCompleted=((A=o.data)==null?void 0:A.plan_is_completed)||[],this.showWidget=((s=o.data)==null?void 0:s.show_widget)||!1,e.planUuid){let a=null;try{const c=await this.api.getPlanSDK(e.planUuid);if(c.error)throw new Error(`Plan not found: ${c.error}`);c.data&&(a=c.data)}catch(c){try{const u=await this.api.getSessionPlan(e.planUuid);if(u.error)throw new Error(`Session plan not found: ${u.error}`);u.data&&(a=u.data)}catch(u){console.error("[obi] error getting plan via both endpoints",{planErr:c,sessionErr:u})}}a?(this.selectedPlan=a,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(o){throw this.error=o instanceof Error?o:new Error(String(o)),this.setState("error"),o}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}async startSession(e,t){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(t),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,r;return this.state,(t=this.session)==null||t.state,(r=this.session)==null||r.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.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",t=>{var r,i,A;if((r=this.session)!=null&&r.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const s=this.plans.findIndex(o=>{var a;return o.uuid===((a=this.selectedPlan)==null?void 0:a.uuid)});s!==-1&&(this.planIsCompleted[s]=!0)}(A=(i=this.session)==null?void 0:i.removeAllListeners)==null||A.call(i),this.session=null,this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",t)}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session-stopped",{sessionUuid:this.session.sessionUuid}),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(),serialisedAt:new Date().toISOString()})}static deserialise(e,t,r,i={}){const A=JSON.parse(e);if(A.serialisedAt){const o=new Date(A.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)throw new Error("Client was serialised more than 20 seconds ago, assuming it's dead.")}else throw new Error("Client was not serialised, assuming it's dead.");const s=new ma(t,r,i);return s.state=A.state,s.identity=A.identity||null,s.product=A.product||null,s.plans=A.plans||[],s.selectedPlan=A.selectedPlan||null,s.selectedPlanUuid=A.selectedPlanUuid||null,s.showWidget=A.showWidget||!1,A.session&&(s.session=ga.deserialise(A.session,t,r,{api:s.api})),s}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var r,i,A;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(r=this.selectedPlan)==null?void 0:r.uuid,productId:(i=this.product)==null?void 0:i.uuid,sessionId:(A=this.session)==null?void 0:A.sessionUuid})}}var va,te,V0,ti,G0,j0,W0,q0,dd,hd,pd,J0,ZA={},z0=[],uQ=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,$A=Array.isArray;function Wn(n,e){for(var t in e)n[t]=e[t];return n}function fd(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function gd(n,e,t){var r,i,A,s={};for(A in e)A=="key"?r=e[A]:A=="ref"?i=e[A]:s[A]=e[A];if(arguments.length>2&&(s.children=arguments.length>3?va.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(A in n.defaultProps)s[A]==null&&(s[A]=n.defaultProps[A]);return ya(n,s,r,i,null)}function ya(n,e,t,r,i){var A={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++V0,__i:-1,__u:0};return i==null&&te.vnode!=null&&te.vnode(A),A}function St(n){return n.children}function qn(n,e){this.props=n,this.context=e}function Wi(n,e){if(e==null)return n.__?Wi(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?Wi(n):null}function X0(n){var e,t;if((n=n.__)!=null&&n.__c!=null){for(n.__e=n.__c.base=null,e=0;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null){n.__e=n.__c.base=t.__e;break}return X0(n)}}function md(n){(!n.__d&&(n.__d=!0)&&ti.push(n)&&!wa.__r++||G0!=te.debounceRendering)&&((G0=te.debounceRendering)||j0)(wa)}function wa(){for(var n,e,t,r,i,A,s,o=1;ti.length;)ti.length>o&&ti.sort(W0),n=ti.shift(),o=ti.length,n.__d&&(t=void 0,i=(r=(e=n).__v).__e,A=[],s=[],e.__P&&((t=Wn({},r)).__v=r.__v+1,te.vnode&&te.vnode(t),vd(e.__P,t,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,A,i??Wi(r),!!(32&r.__u),s),t.__v=r.__v,t.__.__k[t.__i]=t,ty(A,t,s),t.__e!=i&&X0(t)));wa.__r=0}function Y0(n,e,t,r,i,A,s,o,a,c,u){var l,d,h,f,p,g,v=r&&r.__k||z0,y=e.length;for(a=lQ(t,e,v,a,y),l=0;l<y;l++)(h=t.__k[l])!=null&&(d=h.__i==-1?ZA:v[h.__i]||ZA,h.__i=l,g=vd(n,h,d,i,A,s,o,a,c,u),f=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&yd(d.ref,null,h),u.push(h.ref,h.__c||f,h)),p==null&&f!=null&&(p=f),4&h.__u||d.__k===h.__k?a=Z0(h,a,n):typeof h.type=="function"&&g!==void 0?a=g:f&&(a=f.nextSibling),h.__u&=-7);return t.__e=p,a}function lQ(n,e,t,r,i){var A,s,o,a,c,u=t.length,l=u,d=0;for(n.__k=new Array(i),A=0;A<i;A++)(s=e[A])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=A+d,(s=n.__k[A]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?ya(null,s,null,null,null):$A(s)?ya(St,{children:s},null,null,null):s.constructor==null&&s.__b>0?ya(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=n,s.__b=n.__b+1,o=null,(c=s.__i=dQ(s,t,a,l))!=-1&&(l--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(i>u?d--:i<u&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=a&&(c==a-1?d--:c==a+1?d++:(c>a?d--:d++,s.__u|=4))):n.__k[A]=null;if(l)for(A=0;A<u;A++)(o=t[A])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Wi(o)),ry(o,o));return r}function Z0(n,e,t){var r,i;if(typeof n.type=="function"){for(r=n.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=n,e=Z0(r[i],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Wi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ba(n,e){return e=e||[],n==null||typeof n=="boolean"||($A(n)?n.some(function(t){ba(t,e)}):e.push(n)),e}function dQ(n,e,t,r){var i,A,s=n.key,o=n.type,a=e[t];if(a===null&&n.key==null||a&&s==a.key&&o==a.type&&!(2&a.__u))return t;if(r>(a!=null&&!(2&a.__u)?1:0))for(i=t-1,A=t+1;i>=0||A<e.length;){if(i>=0){if((a=e[i])&&!(2&a.__u)&&s==a.key&&o==a.type)return i;i--}if(A<e.length){if((a=e[A])&&!(2&a.__u)&&s==a.key&&o==a.type)return A;A++}}return-1}function $0(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||uQ.test(e)?t:t+"px"}function Ca(n,e,t,r,i){var A;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||$0(n.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||$0(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")A=e!=(e=e.replace(q0,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+A]=t,t?r?t.u=r.u:(t.u=dd,n.addEventListener(e,A?pd:hd,A)):n.removeEventListener(e,A?pd:hd,A);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 n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function ey(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=dd++;else if(e.t<t.u)return;return t(te.event?te.event(e):e)}}}function vd(n,e,t,r,i,A,s,o,a,c){var u,l,d,h,f,p,g,v,y,C,B,b,_,k,U,I,P,x=e.type;if(e.constructor!=null)return null;128&t.__u&&(a=!!(32&t.__u),A=[o=e.__e=t.__e]),(u=te.__b)&&u(e);e:if(typeof x=="function")try{if(v=e.props,y="prototype"in x&&x.prototype.render,C=(u=x.contextType)&&r[u.__c],B=u?C?C.props.value:u.__:r,t.__c?g=(l=e.__c=t.__c).__=l.__E:(y?e.__c=l=new x(v,B):(e.__c=l=new qn(v,B),l.constructor=x,l.render=pQ),C&&C.sub(l),l.props=v,l.state||(l.state={}),l.context=B,l.__n=r,d=l.__d=!0,l.__h=[],l._sb=[]),y&&l.__s==null&&(l.__s=l.state),y&&x.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=Wn({},l.__s)),Wn(l.__s,x.getDerivedStateFromProps(v,l.__s))),h=l.props,f=l.state,l.__v=e,d)y&&x.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),y&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(y&&x.getDerivedStateFromProps==null&&v!==h&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(v,B),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(v,l.__s,B)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(l.props=v,l.state=l.__s,l.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(O){O&&(O.__=e)}),b=0;b<l._sb.length;b++)l.__h.push(l._sb[b]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(v,l.__s,B),y&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(h,f,p)})}if(l.context=B,l.props=v,l.__P=n,l.__e=!1,_=te.__r,k=0,y){for(l.state=l.__s,l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),U=0;U<l._sb.length;U++)l.__h.push(l._sb[U]);l._sb=[]}else do l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++k<25);l.state=l.__s,l.getChildContext!=null&&(r=Wn(Wn({},r),l.getChildContext())),y&&!d&&l.getSnapshotBeforeUpdate!=null&&(p=l.getSnapshotBeforeUpdate(h,f)),I=u,u!=null&&u.type===St&&u.key==null&&(I=ny(u.props.children)),o=Y0(n,$A(I)?I:[I],e,t,r,i,A,s,o,a,c),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),g&&(l.__E=l.__=null)}catch(O){if(e.__v=null,a||A!=null)if(O.then){for(e.__u|=a?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;A[A.indexOf(o)]=null,e.__e=o}else for(P=A.length;P--;)fd(A[P]);else e.__e=t.__e,e.__k=t.__k;te.__e(O,e,t)}else A==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=hQ(t.__e,e,t,r,i,A,s,a,c);return(u=te.diffed)&&u(e),128&e.__u?void 0:o}function ty(n,e,t){for(var r=0;r<t.length;r++)yd(t[r],t[++r],t[++r]);te.__c&&te.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(A){A.call(i)})}catch(A){te.__e(A,i.__v)}})}function ny(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:$A(n)?n.map(ny):Wn({},n)}function hQ(n,e,t,r,i,A,s,o,a){var c,u,l,d,h,f,p,g=t.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),A!=null){for(c=0;c<A.length;c++)if((h=A[c])&&"setAttribute"in h==!!y&&(y?h.localName==y:h.nodeType==3)){n=h,A[c]=null;break}}if(n==null){if(y==null)return document.createTextNode(v);n=document.createElementNS(i,y,v.is&&v),o&&(te.__m&&te.__m(e,A),o=!1),A=null}if(y==null)g===v||o&&n.data==v||(n.data=v);else{if(A=A&&va.call(n.childNodes),g=t.props||ZA,!o&&A!=null)for(g={},c=0;c<n.attributes.length;c++)g[(h=n.attributes[c]).name]=h.value;for(c in g)if(h=g[c],c!="children"){if(c=="dangerouslySetInnerHTML")l=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;Ca(n,c,null,h,i)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?u=h:c=="value"?f=h:c=="checked"?p=h:o&&typeof h!="function"||g[c]===h||Ca(n,c,h,g[c],i);if(u)o||l&&(u.__html==l.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(l&&(n.innerHTML=""),Y0(e.type=="template"?n.content:n,$A(d)?d:[d],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,A,s,A?A[0]:t.__k&&Wi(t,0),o,a),A!=null)for(c=A.length;c--;)fd(A[c]);o||(c="value",y=="progress"&&f==null?n.removeAttribute("value"):f!=null&&(f!==n[c]||y=="progress"&&!f||y=="option"&&f!=g[c])&&Ca(n,c,f,g[c],i),c="checked",p!=null&&p!=n[c]&&Ca(n,c,p,g[c],i))}return n}function yd(n,e,t){try{if(typeof n=="function"){var r=typeof n.__u=="function";r&&n.__u(),r&&e==null||(n.__u=n(e))}else n.current=e}catch(i){te.__e(i,t)}}function ry(n,e,t){var r,i;if(te.unmount&&te.unmount(n),(r=n.ref)&&(r.current&&r.current!=n.__e||yd(r,null,e)),(r=n.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(A){te.__e(A,e)}r.base=r.__P=null}if(r=n.__k)for(i=0;i<r.length;i++)r[i]&&ry(r[i],e,t||typeof n.type!="function");t||fd(n.__e),n.__c=n.__=n.__e=void 0}function pQ(n,e,t){return this.constructor(n,t)}function fQ(n,e,t){var r,i,A,s;e==document&&(e=document.documentElement),te.__&&te.__(n,e),i=(r=typeof t=="function")?null:t&&t.__k||e.__k,A=[],s=[],vd(e,n=(!r&&t||e).__k=gd(St,null,[n]),i||ZA,ZA,e.namespaceURI,!r&&t?[t]:i?null:e.firstChild?va.call(e.childNodes):null,A,!r&&t?t:i?i.__e:e.firstChild,r,s),ty(A,n,s)}function iy(n){function e(t){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(A){this.props.value!=A.value&&r.forEach(function(s){s.__e=!0,md(s)})},this.sub=function(A){r.add(A);var s=A.componentWillUnmount;A.componentWillUnmount=function(){r&&r.delete(A),s&&s.call(A)}}),t.children}return e.__c="__cC"+J0++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}va=z0.slice,te={__e:function(n,e,t,r){for(var i,A,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((A=i.constructor)&&A.getDerivedStateFromError!=null&&(i.setState(A.getDerivedStateFromError(n)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,r||{}),s=i.__d),s)return i.__E=i}catch(o){n=o}throw n}},V0=0,qn.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Wn({},this.state),typeof n=="function"&&(n=n(Wn({},t),this.props)),n&&Wn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),md(this))},qn.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),md(this))},qn.prototype.render=St,ti=[],j0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,W0=function(n,e){return n.__v.__b-e.__v.__b},wa.__r=0,q0=/(PointerCapture)$|Capture$/i,dd=0,hd=ey(!1),pd=ey(!0),J0=0;var gQ=0;function w(n,e,t,r,i,A){e||(e={});var s,o,a=e;if("ref"in a)for(o in a={},e)o=="ref"?s=e[o]:a[o]=e[o];var c={type:n,props:a,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--gQ,__i:-1,__u:0,__source:i,__self:A};if(typeof n=="function"&&(s=n.defaultProps))for(o in s)a[o]===void 0&&(a[o]=s[o]);return te.vnode&&te.vnode(c),c}var ni,Ve,wd,Ay,es=0,sy=[],rt=te,oy=rt.__b,ay=rt.__r,cy=rt.diffed,uy=rt.__c,ly=rt.unmount,dy=rt.__;function ts(n,e){rt.__h&&rt.__h(Ve,n,es||e),es=0;var t=Ve.__H||(Ve.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function he(n){return es=1,mQ(fy,n)}function mQ(n,e,t){var r=ts(ni++,2);if(r.t=n,!r.__c&&(r.__=[t?t(e):fy(void 0,e),function(o){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,o);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var i=function(o,a,c){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(d){return!!d.__c});if(u.every(function(d){return!d.__N}))return!A||A.call(this,o,a,c);var l=r.__c.props!==o;return u.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(l=!0)}}),A&&A.call(this,o,a,c)||l};Ve.__f=!0;var A=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(o,a,c){if(this.__e){var u=A;A=void 0,i(o,a,c),A=u}s&&s.call(this,o,a,c)},Ve.shouldComponentUpdate=i}return r.__N||r.__}function Vt(n,e){var t=ts(ni++,3);!rt.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__H.__h.push(t))}function Ba(n,e){var t=ts(ni++,4);!rt.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__h.push(t))}function In(n){return es=5,bd(function(){return{current:n}},[])}function bd(n,e){var t=ts(ni++,7);return Bd(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function vQ(n,e){return es=8,bd(function(){return n},e)}function hy(n){var e=Ve.context[n.__c],t=ts(ni++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ve)),e.props.value):n.__}function yQ(){for(var n;n=sy.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(_a),n.__H.__h.forEach(Cd),n.__H.__h=[]}catch(e){n.__H.__h=[],rt.__e(e,n.__v)}}rt.__b=function(n){Ve=null,oy&&oy(n)},rt.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),dy&&dy(n,e)},rt.__r=function(n){ay&&ay(n),ni=0;var e=(Ve=n.__c).__H;e&&(wd===Ve?(e.__h=[],Ve.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(_a),e.__h.forEach(Cd),e.__h=[],ni=0)),wd=Ve},rt.diffed=function(n){cy&&cy(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(sy.push(e)!==1&&Ay===rt.requestAnimationFrame||((Ay=rt.requestAnimationFrame)||wQ)(yQ)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),wd=Ve=null},rt.__c=function(n,e){e.some(function(t){try{t.__h.forEach(_a),t.__h=t.__h.filter(function(r){return!r.__||Cd(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],rt.__e(r,t.__v)}}),uy&&uy(n,e)},rt.unmount=function(n){ly&&ly(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{_a(r)}catch(i){e=i}}),t.__H=void 0,e&&rt.__e(e,t.__v))};var py=typeof requestAnimationFrame=="function";function wQ(n){var e,t=function(){clearTimeout(r),py&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);py&&(e=requestAnimationFrame(t))}function _a(n){var e=Ve,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ve=e}function Cd(n){var e=Ve;n.__c=n.__(),Ve=e}function Bd(n,e){return!n||n.length!==e.length||e.some(function(t,r){return t!==n[r]})}function fy(n,e){return typeof e=="function"?e(n):e}function bQ({size:n=24,color:e="#000"}){return w("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,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:[w("path",{d:"M18 6 6 18"}),w("path",{d:"m6 6 12 12"})]})}function gy({onClose:n}){return w("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:w(bQ,{})})}function my({open:n=!1,children:e,onClose:t,size:r="medium"}){const i=In(null),A=In(null);Vt(()=>{const c=i.current;c&&(n&&!c.open?c.showModal():!n&&c.open&&(A.current="programmatic",c.close()))},[n]);const s=c=>{const u=i.current;c.target===u&&(A.current="user-initiated",u==null||u.close())},o=c=>{c.preventDefault(),A.current||(A.current="user-initiated");const u=A.current;A.current=null,t==null||t(u)},a=()=>{var c;A.current="user-initiated",(c=i.current)==null||c.close()};return Vt(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",o),()=>{c.removeEventListener("click",s),c.removeEventListener("close",o)}},[t]),w("dialog",{ref:i,className:`modal-${r}`,children:[w(gy,{onClose:a}),w("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function _d(n){const{children:e,className:t="",...r}=n;return w("div",{className:`${t} obi-panel`,...r,children:e})}function Sa({className:n="",isActive:e=!1,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),w("div",{className:o,onMouseEnter:i,onMouseLeave:A,children:w("div",{className:`obi-pill pill ${n}`,onClick:r,children:s})})}function CQ({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return w("div",{className:a,...o,children:w("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function BQ({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return w("div",{className:a,...o,children:w("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function ri({type:n,size:e=24}){return w("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:_Q(n)})}function _Q(n){switch(n){case"pause":return w(St,{children:[w("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),w("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return w(St,{children:w("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 w(St,{children:[w("path",{d:"M18 6 6 18"}),w("path",{d:"m6 6 12 12"})]});case"message":return w(St,{children:w("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 w(St,{children:[w("path",{d:"m14 10 7-7"}),w("path",{d:"M20 10h-6V4"}),w("path",{d:"m3 21 7-7"}),w("path",{d:"M4 14h6v6"})]});case"voice":return w(St,{children:[w("path",{d:"M2 10v3"}),w("path",{d:"M6 6v11"}),w("path",{d:"M10 3v18"}),w("path",{d:"M14 8v7"}),w("path",{d:"M18 5v13"}),w("path",{d:"M22 10v3"})]});case"open":return w(St,{children:[w("path",{d:"M12 7v14"}),w("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 Sd=iy(null);function SQ({children:n}){const e=hy(Sd);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:r,setIsOpen:i,setAnimating:A,targetRef:s,trigger:o,onChange:a,delayMs:c}=e,u=In(null),l=vy(s,A),[d,h]=he(!1);Vt(()=>{t!==void 0&&t!==d&&(t?p():g()),h(t)},[t]),Vt(()=>()=>{u.current&&clearTimeout(u.current)},[]);function f(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){f(),c>0?u.current=setTimeout(()=>{a==null||a(!0),i(!0),u.current=null},c):(a==null||a(!0),i(!0))}function g(){f(),a==null||a(!1),i(!1)}const v=()=>{o==="click"&&(r?g():p())};function y(){o==="hover"&&p()}function C(){o==="hover"&&g()}return w("div",{ref:l,class:"target",onClick:v,onMouseEnter:y,onMouseLeave:C,children:n})}function kQ({children:n}){const e=hy(Sd);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:r,setAnimating:i,targetRef:A,contentRef:s}=e,o=vy(s,i);return Ba(()=>{if(t&&!r&&A.current&&s.current){const a=s.current;if(!a)return;const c=A.current;if(!c)return;const u=a.getBoundingClientRect(),l=c.getBoundingClientRect(),d=l.right-l.left;a.style.top=`${u.top-u.bottom-(8+e.offset)}px`,a.style.left=`${-(u.right-u.left-d)/2}px`}},[t,r]),t?w("div",{ref:o,class:"content",style:{opacity:r?0:1},children:n}):null}function Gt({trigger:n="click",open:e,onChange:t,children:r,delayMs:i=0,offset:A=0,className:s=""}){const[o,a]=he(!1),[c,u]=he(!1),l=In(null),d=In(null),h={controlledOpen:e,isOpen:o,setIsOpen:a,animating:c,setAnimating:u,targetRef:l,contentRef:d,trigger:n,onChange:t,delayMs:i,offset:A};return w(Sd.Provider,{value:h,children:w("div",{class:`obi-popout ${s}`,children:r})})}Gt.Target=SQ,Gt.Content=kQ;function vy(n,e){const t=In(null),r=In(null),i=In(!0),A=vQ(s=>{if(n.current=s,!s){r.current&&(r.current.disconnect(),r.current=null),i.current=!0;return}function o(){if(i.current){i.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}r.current=new ResizeObserver(o),r.current.observe(s,{box:"border-box"})},[]);return Vt(()=>()=>{r.current&&(r.current.disconnect(),r.current=null)},[]),A}function gn({className:n,onClick:e,type:t,disabled:r,title:i}){const A={cancel:w(ri,{type:"close",size:16}),pause:w(ri,{type:"pause",size:16}),play:w(ri,{type:"play",size:16}),message:w(ri,{type:"message",size:16}),minimize:w(ri,{type:"minimize",size:16}),voice:w(ri,{type:"voice",size:16}),open:w(ri,{type:"open",size:16})}[t],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=w("button",{class:`obi-button obi-round-button ${s} ${n}`,onClick:r?void 0:e,disabled:r,children:A});return i?w(Gt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[w(Gt.Target,{children:o}),w(Gt.Content,{children:w("div",{className:"obi-round-button-title",children:i})})]}):o}const yy=8,ka=8,EQ=50,UQ=.7,qi=3;function wy({getBands:n,color:e="white"}){const t=In(null);return Vt(()=>{if(!n)return;const r=setInterval(()=>{try{const i=n();if(!t.current)return;const A=t.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,ka).map(o=>{const a=Math.abs(o);return Math.min(a/UQ*yy,yy)||qi}):Array(ka).fill(qi);for(;s.length<ka;)s.push(qi);s.forEach((o,a)=>{if(o<qi&&(o=qi),A[a]){const c=o*2;A[a].style.height=`${c}px`,A[a].style.display=o>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},EQ);return()=>{clearInterval(r)}},[n]),w("div",{className:"obi-equaliser",ref:t,children:Array.from({length:ka},(r,i)=>w("div",{className:"column",children:w("div",{className:"bar",style:{height:`${qi}px`,backgroundColor:e,display:"block"}})},i))})}function Sr({className:n,children:e,onClick:t}){return t?w("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):w("div",{class:`obi-message ${n}`,children:e})}const TQ=8;function by({color:n="white"}){return w("div",{className:"obi-loading-dots",children:Array.from({length:TQ},(e,t)=>w("div",{className:"column",children:[w("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),w("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function IQ({onContinue:n,onWrapUp:e}){return w(_d,{className:"obi-exit-survey",children:w(xQ,{onContinue:n,onWrapUp:()=>{e()}})})}function FQ({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[r,i]=he("reason"),A=s=>{s==="other"?(n(),i("other-reason")):e(s)};return w(_d,{className:`obi-exit-survey ${r==="reason"?"obi-exit-survey-reason":""}`,children:r==="reason"?w(QQ,{onReasonSelect:A}):w(RQ,{onReasonSelect:A,onClose:t})})}function xQ({onContinue:n,onWrapUp:e}){return w("div",{className:"obi-exit-survey-container",children:[w("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),w("div",{className:"obi-exit-survey-options",children:[w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),w("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 QQ({onReasonSelect:n}){return w("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[w("div",{className:"obi-exit-survey-header",children:w("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),w("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("cant-talk"),type:"button",children:"Can't talk right now"}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function RQ({onReasonSelect:n,onClose:e}){const[t,r]=he("");return w("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[w("div",{className:"obi-exit-survey-header",children:[w(gy,{onClose:e}),w("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),w("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[w("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:i=>r(i.target.value)}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>n("other-feedback",t),type:"button",children:"Send feedback"})]})]})}function PQ(n,e){for(var t in e)n[t]=e[t];return n}function Cy(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function By(n,e){this.props=n,this.context=e}(By.prototype=new qn).isPureReactComponent=!0,By.prototype.shouldComponentUpdate=function(n,e){return Cy(this.props,n)||Cy(this.state,e)};var _y=te.__b;te.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),_y&&_y(n)};var OQ=te.__e;te.__e=function(n,e,t,r){if(n.then){for(var i,A=e;A=A.__;)if((i=A.__c)&&i.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),i.__c(n,e)}OQ(n,e,t,r)};var Sy=te.unmount;function ky(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=PQ({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return ky(r,e,t)})),n}function Ey(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Ey(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function kd(){this.__u=0,this.o=null,this.__b=null}function Uy(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Ea(){this.i=null,this.l=null}te.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Sy&&Sy(n)},(kd.prototype=new qn).__c=function(n,e){var t=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(t);var i=Uy(r.__v),A=!1,s=function(){A||(A=!0,t.__R=null,i?i(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Ey(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},kd.prototype.componentWillUnmount=function(){this.o=[]},kd.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=ky(this.__b,t,r.__O=r.__P)}this.__b=null}var i=e.__a&&gd(St,null,n.fallback);return i&&(i.__u&=-33),[gd(St,null,e.__a?null:n.children),i]};var Ty=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;n.i=t=t[2]}};(Ea.prototype=new qn).__a=function(n){var e=this,t=Uy(e.__v),r=e.l.get(n);return r[0]++,function(i){var A=function(){e.props.revealOrder?(r.push(i),Ty(e,n,r)):i()};t?t(A):A()}},Ea.prototype.render=function(n){this.i=null,this.l=new Map;var e=ba(n.children);n.revealOrder&&n.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return n.children},Ea.prototype.componentDidUpdate=Ea.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Ty(n,t,e)})};var LQ=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,DQ=/^(?: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]/,MQ=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NQ=/[A-Z0-9]/g,HQ=typeof document<"u",KQ=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};qn.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(qn.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var Iy=te.event;function VQ(){}function GQ(){return this.cancelBubble}function jQ(){return this.defaultPrevented}te.event=function(n){return Iy&&(n=Iy(n)),n.persist=VQ,n.isPropagationStopped=GQ,n.isDefaultPrevented=jQ,n.nativeEvent=n};var WQ={enumerable:!1,configurable:!0,get:function(){return this.class}},Fy=te.vnode;te.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,r=e.type,i={},A=r.indexOf("-")===-1;for(var s in t){var o=t[s];if(!(s==="value"&&"defaultValue"in t&&o==null||HQ&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in t&&t.value==null?s="value":s==="download"&&o===!0?o="":a==="translate"&&o==="no"?o=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||KQ(t.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":MQ.test(s)&&(s=a):a=s="oninput":A&&DQ.test(s)?s=s.replace(NQ,"-$&").toLowerCase():o===null&&(o=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=o}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=ba(t.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ba(t.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",WQ)):(t.className&&!t.class||t.class&&t.className)&&(i.class=i.className=t.className),e.props=i}(n),n.$$typeof=LQ,Fy&&Fy(n)};var xy=te.__r;te.__r=function(n){xy&&xy(n),n.__c};var Qy=te.diffed;te.diffed=function(n){Qy&&Qy(n);var e=n.props,t=n.__e;t!=null&&n.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value)};function qQ(n){const{placeholder:e="Type your message...",value:t,defaultValue:r,onChange:i,onSend:A,onCancel:s,onExpand:o,isLoading:a=!1,disabled:c=!1,maxLength:u=500,children:l}=n,[d,h]=he(t||r||""),[f,p]=he((t||r||"").length>24),g=In(null);Ba(()=>{f&&(o==null||o(!0))},[]);const v=t!==void 0?t:d,y=b=>{const _=b.currentTarget.value;t===void 0&&h(_),i==null||i(_)},C=b=>{b.key==="Escape"&&(h(t||r||""),p(!1),s==null||s()),b.key==="Enter"&&!b.shiftKey&&v.trim()&&(b.preventDefault(),h(t||r||""),p(!1),B()),(v||"").length>=24&&!f&&(p(!0),o==null||o(!0))};Vt(()=>{g.current&&g.current.focus()},[g.current]);const B=()=>{!v.trim()||a||c||(A==null||A(v.trim()),t===void 0&&h(""))};return w("div",{className:`obi-message-input ${f?"expanded":""}`,children:[w("div",{className:"container",children:w("textarea",{ref:g,className:"field",placeholder:e,value:v,onInput:y,onKeyDown:C,disabled:c||a,maxLength:u,rows:1})}),w("div",{className:"button-container",children:[f&&w("div",{children:l}),w("button",{className:"obi-button send",onClick:B,disabled:!v.trim()||a||c,type:"button",children:w("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:w("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 JQ(n){const{currentStep:e,totalSteps:t,stepNames:r,className:i}=n,A=Array.from({length:t},(a,c)=>({isCompleted:c<e,stepNumber:c+1})),s=r[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${s}`;return w("div",{class:`obi-course-progress ${i||""}`,children:[w("div",{class:"obi-course-progress-steps",children:A.map((a,c)=>w("div",{class:"obi-course-progress-container",children:w("div",{class:`obi-course-progress-step ${a.isCompleted?"completed":""}`})},c))}),w("div",{class:"obi-course-progress-description",children:o})]})}function Ry({className:n="",size:e=64}){return w("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:w("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 zQ(n){const{disabled:e,inPlan:t,isPaused:r}=n,[i,A]=he(null),[s,o]=he(n.isActive??n.defaultIsActive??!1),[a,c]=he(!1),[u,l]=he(n.cancelling??!1),[d,h]=he(n.messaging??!1),[f,p]=he(!1),[g,v]=he(d),[y,C]=he(!1);Ba(()=>{n.messaging!==void 0&&h(n.messaging)},[n.messaging]);function B(){o(!0),c(!1),C(!0),n.messaging!==void 0&&h(n.messaging)}function b(){}function _(){i&&(clearTimeout(i),A(null))}function k(){A(setTimeout(()=>{o(n.defaultIsActive??!1),C(!1)},400))}function U(ve){var Pt;p(!1),(Pt=n.onMessage)==null||Pt.call(n,ve)}function I(){var ve;h(!1),p(!1),o(!1),c(!0),(ve=n.onMinimize)==null||ve.call(n)}function P(){var ve;h(!1),l(!0),p(!1),(ve=n.onCancelClick)==null||ve.call(n)}function x(){var ve;t||((ve=n.onOpen)==null||ve.call(n))}function O(ve){var Pt,pi,wn,Ln,tr,Mr;switch(ve){case"need-help":(Pt=n.onMessage)==null||Pt.call(n,"I'm struggling."),(pi=n.onOneClickAction)==null||pi.call(n,"need-help");break;case"continue":(wn=n.onMessage)==null||wn.call(n,"Okay, let's continue."),(Ln=n.onOneClickAction)==null||Ln.call(n,"continue");break;case"say-again":(tr=n.onMessage)==null||tr.call(n,"Please say that again."),(Mr=n.onOneClickAction)==null||Mr.call(n,"say-again");break}}function H(ve){var Pt;n.messaging===void 0&&((Pt=n.onMessagingChange)==null||Pt.call(n,ve),h(ve)),ve||p(!1)}const z=n.isActive??((s||t)&&!a&&!e),F=z&&t,D=z&&t&&!f,X=n.speakingStatus==="user-speaking",J=n.speakingStatus==="thinking",$=n.speakingStatus==="busy",Se=z&&!t&&!u&&y,We=z&&t&&r&&!X&&!u,Te=z&&t&&!We&&!X&&d!==g&&!u,dt=z&&t&&r&&X&&!u,Re=z&&t&&!r&&X&&!u,Fe=z&&t&&!r&&$&&!u,re=d&&X,$e=Se||We||dt||Re||Te||u,Ct=400,Wt=z&&t&&!f,hi=Se?5:10;return Ba(()=>{X&&v(d)},[X]),!t&&!u?w(XQ,{...n}):!t&&u?w(YQ,{onOtherSelect:()=>{var ve;(ve=n.onCancelReasonOther)==null||ve.call(n)},onCancelReason:ve=>{var Pt;o(n.defaultIsActive??!1),l(!1),(Pt=n.onCancelReason)==null||Pt.call(n,ve)},onClose:()=>{o(n.defaultIsActive??!1),l(!1)}}):w(_d,{className:`obi-widget-panel ${F?"expanded":""} ${f?"maximized":""} ${d?"messaging":""} ${$?"tool-usage":""}`,children:[w("div",{className:`obi-widget ${z?"active":""} ${t?"in-plan":""}`,onMouseEnter:_,onMouseLeave:k,children:[D&&w(gn,{type:"cancel",onClick:P,disabled:u,title:"Cancel session"}),D&&!r&&w(gn,{type:"pause",onClick:n.onPause,title:"Pause session"}),D&&r&&w(gn,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),w(Gt,{className:"obi-widget-popout",open:$e,trigger:null,delayMs:Ct,offset:hi,children:[w(Gt.Target,{children:[re&&w(qQ,{value:n.message,defaultValue:"Okay, let's continue.",onCancel:()=>H(!1),onSend:U,onExpand:p,onChange:n.onMessageChange,children:w("div",{className:"obi-widget-buttons",children:[w(gn,{type:"cancel",onClick:P,disabled:u,title:"Cancel session"}),!r&&w(gn,{type:"pause",onClick:n.onPause,title:"Pause session"}),r&&w(gn,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),w(gn,{type:d?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>H(!d),title:d?"Voice input":"Text input"}),w(gn,{type:"minimize",onClick:I,title:"Minimize widget"})]})}),!re&&w(Sa,{className:z&&!t?"button":"",isActive:z,speakingStatus:n.speakingStatus,onClick:x,onMouseEnter:B,onMouseLeave:b,children:[z&&!t&&!Fe&&w("span",{className:"obi-widget-pill-text",children:"Tutorials"}),z&&t&&Fe&&w("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),z&&t&&!J&&!Fe&&w(wy,{getBands:n.spectrum}),z&&J&&!Fe&&w(by,{})]})]}),w(Gt.Content,{children:w("div",{onMouseLeave:k,children:[Se&&w(Sr,{onClick:x,children:"Click to see all"}),We&&w(Sr,{children:"Session will pause shortly"}),Te&&w(Sr,{children:["Switching to ",d?"chat":"voice"]}),dt&&w(Sr,{children:"Paused"}),Re&&w("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[w(Sr,{onClick:()=>O("need-help"),children:"Need help"}),w(Sr,{onClick:()=>O("continue"),children:"Continue"}),w(Sr,{onClick:()=>O("say-again"),children:"Say again"})]}),u&&w(IQ,{onContinue:()=>{var ve;(ve=n.onCancelAbort)==null||ve.call(n),l(!1),n.messaging!==void 0&&h(n.messaging)},onWrapUp:()=>{var ve;(ve=n.onCancel)==null||ve.call(n)}})]})})]}),D&&w(gn,{type:d?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>H(!d),title:d?"Voice input":"Text input"}),D&&w(gn,{type:"minimize",onClick:I,title:"Minimize widget"})]}),Wt&&n.courseProgress&&w("div",{className:`obi-course-progress-container ${d?"expanded":""}`,children:w(JQ,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames})})]})}function XQ(n){const{disabled:e,completedTutorials:t,totalTutorials:r,agentName:i}=n,[A,s]=he(null),[o,a]=he(n.isActive??n.defaultIsActive??!1),[c,u]=he(!1),[l,d]=he(n.hovered??!1);function h(){var U;a(!0),u(!1),d(!0),(U=n.onHover)==null||U.call(n,!0)}function f(){}function p(){A&&(clearTimeout(A),s(null))}function g(){o&&s(setTimeout(()=>{var U;a(n.defaultIsActive??!1),d(!1),(U=n.onHover)==null||U.call(n,!1)},400))}function v(){a(!1),u(!0)}function y(){var U;(U=n.onOpen)==null||U.call(n)}const C=n.hovered??(l&&!c),B=n.isActive??(o&&!e&&!c),b=B&&C,_=`round-button ${B?"active":""}`;let k=`${i||"Obi"}`;return t!==void 0&&r!==void 0&&t>=0&&r>0&&(k=`${t}/${r} completed`),w("div",{className:"obi-widget-out-of-plan-container",children:w("div",{className:`obi-widget-out-of-plan ${C?"hover":""} ${B?"active":""}`,onMouseEnter:p,onMouseLeave:g,children:[w("div",{className:_,style:{width:"30px",height:"30px"}}),w(Gt,{className:"obi-widget-popout",open:b,trigger:null,delayMs:400,offset:5,children:[w(Gt.Target,{children:w(BQ,{className:B?"button":"",active:B,onClick:y,onMouseEnter:h,onMouseLeave:f,children:w("span",{className:"text",children:[w(Ry,{size:16}),k]})})}),w(Gt.Content,{children:w("div",{onMouseLeave:g,children:w(Sr,{className:"message",onClick:y,children:"Click to see all"})})})]}),w(gn,{className:_,type:"minimize",onClick:v,title:"Minimize widget"})]})})}function YQ(n){return w("div",{className:"obi-widget-out-of-plan-container",children:w("div",{className:"obi-widget-out-of-plan",children:w(Gt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[w(Gt.Target,{children:w(CQ,{active:!1})}),w(Gt.Content,{children:w(FQ,{onOtherSelect:()=>{var e;(e=n.onOtherSelect)==null||e.call(n)},onReasonSelect:(e,t)=>{var r;(r=n.onCancelReason)==null||r.call(n,e,t)},onClose:()=>{var e;(e=n.onClose)==null||e.call(n)}})})]})})})}function ZQ({open:n=!1,children:e,onClose:t}){return w(my,{open:n,onClose:t,children:w("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function Ji({title:n="",subtitle:e="",agentName:t="Obi",buttonText:r="Continue",speakingState:i=null,actionDisabled:A=!1,href:s=null,centerVisual:o,description:a,button:c,onAction:u}){const[l,d]=he(A),[h,f]=he(!1),[p,g]=he(i);return Vt(()=>{h||(i==="listening"&&p!=="listening"&&l&&d(!1),i!=="listening"&&!l&&d(!0)),g(i)},[i,l]),Vt(()=>{d(A)},[A]),w("div",{className:"tour-content",children:w("div",{className:"container",children:[w("div",{className:"header",children:[w("h1",{className:"title",children:n}),w("p",{className:"subtitle",children:e})]}),w("div",{className:"visual",style:{background:"var(--obi-color-tint)"},children:o}),w("div",{className:"description",children:a}),w("div",{className:"button-container",children:c||w(s?"a":"button",{className:`action-button ${l?"disabled":""}`,onClick:()=>{l||(d(!0),f(!0),u==null||u())},disabled:l,...s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:w("span",{className:"button-text",children:(()=>{switch(i){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return r}})()})})})]})})}function $Q({logoUrl:n="",appName:e="App"}){const[t,r]=he(!1),[i,A]=he(!1),s=()=>{r(!0)},o=()=>{A(!0),r(!1)},a={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:n&&!t&&i?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!n||t||!i?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return w("div",{style:a.container,children:w("div",{style:a.logoContainer,children:[w("div",{style:a.backgroundPattern}),w("div",{style:a.logoWrapper,children:[n&&w("img",{style:a.appLogo,src:n,alt:`${e} logo`,onError:s,onLoad:o}),w("div",{style:a.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function eR({session:n,speakingState:e,onAction:t}){const r=n.appName?`Navigate to ${n.appName}`:"Navigate to app",i=n.appName?`Open ${n.appName}`:"Open app",A=n.appName?`Enjoy the tutorial in ${n.appName}`:"Enjoy the tutorial";return w(Ji,{title:r,subtitle:"Click the button below to open the app",agentName:n.agentName||"Obi",buttonText:i,speakingState:e,actionDisabled:!0,href:n.url,description:A,centerVisual:w($Q,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}function tR({}){return w("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:w(Sa,{isActive:!0,children:w("div",{className:"obi-static-voice-visual",children:[w("div",{className:"column",children:w("div",{className:"bar bar-1"})}),w("div",{className:"column",children:w("div",{className:"bar bar-2"})}),w("div",{className:"column",children:w("div",{className:"bar bar-3"})}),w("div",{className:"column",children:w("div",{className:"bar bar-4"})}),w("div",{className:"column",children:w("div",{className:"bar bar-5"})}),w("div",{className:"column",children:w("div",{className:"bar bar-6"})}),w("div",{className:"column",children:w("div",{className:"bar bar-7"})}),w("div",{className:"column",children:w("div",{className:"bar bar-8"})})]})})})}function nR({session:n,speakingState:e,onAction:t}){return w(Ji,{title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,buttonText:"Start now",agentName:n.agentName||"Obi",speakingState:e,centerVisual:w(tR,{}),onAction:t})}function rR(){const n={host:{display:"block",position:"relative",width:"100%",height:"100%"},container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},permissionDialog:{boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"flex-start",alignItems:"center",padding:"16px 20px",gap:"16px",position:"absolute",width:"344px",height:"125px",left:"calc(50% - 344px/2)",top:"calc(50% - 125px/2)",background:"#FFFFFF",border:"1px solid #E5E7EB",boxShadow:"0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px -2px rgba(0, 0, 0, 0.05)",borderRadius:"8px"},permissionContent:{width:"100%",display:"flex",flexDirection:"column",gap:"16px"},permissionContentTop:{display:"flex",flexDirection:"row",alignItems:"center",padding:"0px",gap:"16px"},micIconContainer:{color:"var(--obi-color-text)",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"12px",gap:"8px",width:"48px",height:"48px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:0,flexGrow:0},micIcon:{width:"24px",height:"24px",flex:"none",order:0,flexGrow:0},permissionText:{flex:1,height:"24px",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"16px",lineHeight:"24px",display:"flex",alignItems:"center",color:"#111827",flexGrow:1,order:1},allowButton:{alignSelf:"flex-end",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"10px 20px",gap:"8px",minWidth:"80px",height:"40px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:2,flexGrow:0,cursor:"pointer",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"14px",lineHeight:"20px",color:"#374151"},cursorPointer:{position:"absolute",width:"24px",height:"24px",right:"80px",bottom:"60px",zIndex:3,animation:"pointToAllow 2s ease-in-out infinite"},cursorSvg:{width:"100%",height:"100%",filter:"drop-shadow(0px 1px 1.8px rgba(0, 0, 0, 0.65))"}};return w("div",{style:n.host,children:[w("style",{children:`
|
|
42
|
+
`},Yl}var h0;function cx(){if(h0)return hn;h0=1;var n=ox(),e=ax(),t=Xl();return hn.grammar=t,hn.write=e,hn.parse=n.parse,hn.parseParams=n.parseParams,hn.parseFmtpConfig=n.parseFmtpConfig,hn.parsePayloads=n.parsePayloads,hn.parseRemoteCandidates=n.parseRemoteCandidates,hn.parseImageAttributes=n.parseImageAttributes,hn.parseSimulcastStreamList=n.parseSimulcastStreamList,hn}var Cr=cx();function Zl(n,e,t){var r,i,A;e===void 0&&(e=50),t===void 0&&(t={});var s=(r=t.isImmediate)!=null&&r,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&A===void 0;if(A!==void 0&&clearTimeout(A),A=setTimeout(function(){if(A=void 0,c=Date.now(),!s){var C=n.apply(f,h);o&&o(C),u.forEach(function(B){return(0,B.resolve)(C)}),u=[]}},l()),v){var y=n.apply(f,h);return o&&o(y),p(y)}u.push({resolve:p,reject:g})})};return d.cancel=function(h){A!==void 0&&clearTimeout(A),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const ux=.7,lx=20,Vi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class p0 extends Un.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var r;super(),this.log=ue,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Zl(i=>S(this,void 0,void 0,function*(){this.emit(Vi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(A){if(i)i(A);else throw A}}),lx),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=Kn((r=t.loggerName)!==null&&r!==void 0?r:ln.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var r;t.candidate&&((r=this.onIceCandidate)===null||r===void 0||r.call(this,t.candidate))},e.onicecandidateerror=t=>{var r;(r=this.onIceCandidateError)===null||r===void 0||r.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var r;(r=this.onDataChannel)===null||r===void 0||r.call(this,t)},e.ontrack=t=>{var r;(r=this.onTrack)===null||r===void 0||r.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return S(this,void 0,void 0,function*(){var t;let r;if(e.type==="offer"){let{stereoMids:i,nackMids:A}=dx(e);this.remoteStereoMids=i,this.remoteNackMids=A}else if(e.type==="answer"){const i=Cr.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{A.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||A.mid!=s.transceiver.mid)return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of A.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&A.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),r=Cr.write(i)}yield this.setMungedSDP(e,r,!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(Vi.NegotiationComplete),e.sdp&&Cr.parse(e.sdp).media.forEach(A=>{A.type==="video"&&this.emit(Vi.RTPVideoPayloadTypes,A.rtp)}))})}createAndSendOffer(e){return S(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const A=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&A)yield this._pc.setRemoteDescription(A);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const i=Cr.parse((t=r.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{g0(A),A.type==="audio"?f0(A,[],[]):A.type==="video"&&this.trackBitrates.some(s=>{if(!A.msid||!s.cid||!A.msid.includes(s.cid))return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(JA(s.codec)&&this.ensureVideoDDExtensionForSVC(A,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*ux);for(const c of A.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(r,Cr.write(i)),this.onOffer(r)})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),r=Cr.parse((e=t.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(i=>{g0(i),i.type==="audio"&&f0(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Cr.write(r)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ut("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ut("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}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 S(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const r=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),r.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=r.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,r){return S(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(r?"remote":"local"," description"),this.logContext),r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(A){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:A,sdp:t})),e.sdp=i}}try{r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let A="unknown error";i instanceof Error?A=i.message:typeof i=="string"&&(A=i);const s={error:A,sdp:e.sdp};throw!r&&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 kl(A)}})}ensureVideoDDExtensionForSVC(e,t){var r,i;if(!((r=e.ext)===null||r===void 0?void 0:r.some(s=>s.uri===Jv))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.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:Jv})}}}function f0(n,e,t){let r=0;n.rtp.some(i=>i.codec==="opus"?(r=i.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===r&&i.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===r?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function dx(n){var e;const t=[],r=[],i=Cr.parse((e=n.sdp)!==null&&e!==void 0?e:"");let A=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(A=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===A&&a.type==="nack")&&r.push(s.mid),s.fmtp.some(a=>a.payload===A?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:r}}function g0(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const $l="vp8",hx={audioPreset:Il.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:xl.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:$l,backupCodec:!0},m0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},v0={deviceId:{ideal:"default"},resolution:qA.h720.resolution},px={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new iF,disconnectOnPageLeave:!0,webAudioMix:!1},ed={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Xe;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Xe||(Xe={}));class fx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,r){var i;this.peerConnectionTimeout=ed.peerConnectionTimeout,this.log=ue,this.updateState=()=>{var A;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Xe.CONNECTED:o.some(a=>a==="failed")?this.state=Xe.FAILED:o.some(a=>a==="connecting")?this.state=Xe.CONNECTING:o.every(a=>a==="closed")?this.state=Xe.CLOSED:o.some(a=>a==="closed")?this.state=Xe.CLOSING:o.every(a=>a==="new")&&(this.state=Xe.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Xe[s]," to ").concat(Xe[this.state]),this.logContext),(A=this.onStateChange)===null||A===void 0||A.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Kn((i=r.loggerName)!==null&&i!==void 0?i:ln.PCManager),this.loggerOptions=r,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new p0(e,r),this.subscriber=new p0(e,r),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=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,un.PUBLISHER)},this.subscriber.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,un.SUBSCRIBER)},this.subscriber.onDataChannel=A=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,A)},this.subscriber.onTrack=A=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,A)},this.publisher.onOffer=A=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,A)},this.state=Xe.NEW,this.connectionLock=new Dt,this.remoteOfferLock=new Dt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.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 S(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return S(this,void 0,void 0,function*(){t===un.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return S(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 t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return S(this,void 0,void 0,function*(){var r;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((r=this.requiredTransports)===null||r===void 0?void 0:r.map(A=>this.ensureTransportConnected(A,e,t)))}finally{i()}})}negotiate(e){return S(this,void 0,void 0,function*(){return new Promise((t,r)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{r("negotiation timed out")},this.peerConnectionTimeout),A=()=>{clearTimeout(i),r("negotiation aborted")};e.signal.addEventListener("abort",A),this.publisher.once(Vi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Vi.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),r(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===un.PUBLISHER?this.publisher.getConnectedAddress():e===un.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,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(r.getConnectionState()!=="connected")return new Promise((a,c)=>S(A,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),yt.clearTimeout(l),c(new Qe("room connection has been cancelled",de.Cancelled))};i!=null&&i.signal.aborted&&u(),i==null||i.signal.addEventListener("abort",u);const l=yt.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",u),c(new Qe("could not establish pc connection",de.InternalError))},s);for(;this.state!==Xe.CONNECTED;)if(yield Ht(50),i!=null&&i.signal.aborted){c(new Qe("room connection has been cancelled",de.Cancelled));return}yt.clearTimeout(l),i==null||i.signal.removeEventListener("abort",u),a()}))}()})}}class Ye extends Error{constructor(e,t,r){super(t),this.code=e,this.message=w0(t,Ye.MAX_MESSAGE_BYTES),this.data=r?w0(r,Ye.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ye(e.code,e.message,e.data)}toProto(){return new Pm({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ye(Ye.ErrorCode[e],Ye.ErrorMessage[e],t)}}Ye.MAX_MESSAGE_BYTES=256,Ye.MAX_DATA_BYTES=15360,Ye.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},Ye.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 y0=15360;function td(n){return new TextEncoder().encode(n).length}function w0(n,e){if(td(n)<=e)return n;let t=0,r=n.length;const i=new TextEncoder;for(;t<r;){const A=Math.floor((t+r+1)/2);i.encode(n.slice(0,A)).length<=e?t=A:r=A-1}return n.slice(0,t)}const nd=2e3;function ca(n,e){if(!e)return 0;let t,r;return"bytesReceived"in n?(t=n.bytesReceived,r=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,r=e.bytesSent),t===void 0||r===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-r)*8*1e3/(n.timestamp-e.timestamp)}const gx=1e3;class b0 extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,A=arguments.length>4?arguments[4]:void 0;super(e,t,A),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=Zl(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(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(M.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Dt,this.pauseUpstreamLock=new Dt,this.processorLock=new Dt,this.restartLock=new Dt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),r&&(this._constraints=r)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return S(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(A=>{Mi(this._mediaStreamTrack,A)}),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 A=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&&(Di(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{A()}}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.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(A=>{Di(i??e,A)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:gx;return function*(){var r;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((r=dn())===null||r===void 0?void 0:r.os)==="iOS"&&(yield Ht(10));const i=Date.now();for(;Date.now()-i<t;){const A=e.dimensions;if(A)return A;yield Ht(50)}throw new Vn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===wr(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),wr(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===R.Source.ScreenShare)return;const{deviceId:r,groupId:i}=e._mediaStreamTrack.getSettings(),A=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?pt.getInstance().normalizeDeviceId(A,r,i):r}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Vn("unable to replace an unpublished track");let r,i;return typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:r,facingMode:i}=e,A=AF(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===R.Kind.Video?s.video=r||i?{deviceId:r,facingMode:i}:!0:s.audio=r?{deviceId:r}:!0,this.attachedElements.forEach(c=>{Mi(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(A),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(M.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?M.Muted:M.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 S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zv()&&(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 S(this,void 0,void 0,function*(){var e;const t=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(M.UpstreamPaused,this);const r=dn();if((r==null?void 0:r.name)==="Safari"&&Zr(r.version,"12.0")<0)throw new Sl("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{t()}})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;const t=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(M.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return S(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 S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;const s=yield r.processorLock.lock();try{r.log.debug("setting up processor",r.logContext);const o=document.createElement(r.kind),a={kind:r.kind,track:r._mediaStreamTrack,element:o,audioContext:r.audioContext};if(yield t.init(a),r.log.debug("processor initialized",r.logContext),r.processor&&(yield r.stopProcessor()),r.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Di(r._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>r.log.error("failed to play processor element",Object.assign(Object.assign({},r.logContext),{error:c}))),r.processor=t,r.processorElement=o,r.processor.processedTrack){for(const c of r.attachedElements)c!==r.processorElement&&i&&(Mi(r._mediaStreamTrack,c),Di(r.processor.processedTrack,c));yield(A=r.sender)===null||A===void 0?void 0:A.replaceTrack(r.processor.processedTrack)}r.emit(M.TrackProcessorUpdate,r.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var r,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(r=e.processor.processedTrack)===null||r===void 0||r.stop(),yield e.processor.destroy(),e.processor=void 0,t||((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(M.TrackProcessorUpdate))}()})}}class ua extends b0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,A=arguments.length>4?arguments[4]:void 0;super(e,R.Kind.Audio,t,r,A),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=ca(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,cn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,cn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const r=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==wr(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||r)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return S(this,void 0,void 0,function*(){let t;if(e){const r=jl({audio:e});typeof r.audio!="boolean"&&(t=r.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const r=yield t.restart.call(this,e);return this.checkForSilence(),r})}startMonitor(){Kt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},nd)))}setProcessor(e){return S(this,void 0,void 0,function*(){var t;const r=yield this.processorLock.lock();try{if(!Tn()&&!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(t=this.sender)===null||t===void 0?void 0:t.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(M.TrackProcessorUpdate,this.processor)}finally{r()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let r;return t.forEach(i=>{i.type==="outbound-rtp"&&(r={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),r})}checkForSilence(){return S(this,void 0,void 0,function*(){const e=yield i0(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(M.AudioSilenceDetected)),e})}}function mx(n,e,t){switch(n.kind){case"audio":return new ua(n,e,!1,void 0,t);case"video":return new da(n,e,!1,t);default:throw new Vn("unsupported track type: ".concat(n.kind))}}const vx=Object.values(qA),yx=Object.values(Fl),wx=Object.values(xl),bx=[qA.h180,qA.h360],Cx=[Fl.h180,Fl.h360],Bx=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var r,i;return new Ie(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((r=n.encoding.maxFramerate)!==null&&r!==void 0?r:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,n.encoding.priority)}),rd=["q","h","f"];function id(n,e,t,r){var i,A;let s=r==null?void 0:r.videoEncoding;n&&(s=r==null?void 0:r.screenShareEncoding);const o=r==null?void 0:r.simulcast,a=r==null?void 0:r.scalabilityMode,c=r==null?void 0:r.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Sx(n,e,t,c),ue.debug("using video encoding",s));const u=s.maxFramerate,l=new Ie(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&JA(c)){const f=new la(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=dn();if(yr()||Tn()||(g==null?void 0:g.name)==="Chrome"&&Zr(g==null?void 0:g.version,"113")<0){const v=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)p.push({rid:rd[2-y],maxBitrate:s.maxBitrate/Math.pow(v,y),maxFramerate:l.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(p[0].priority=l.encoding.priority,p[0].networkPriority=l.encoding.priority),ue.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let d=[];n?d=(i=B0(r==null?void 0:r.screenShareSimulcastLayers))!==null&&i!==void 0?i:C0(n,l):d=(A=B0(r==null?void 0:r.videoSimulcastLayers))!==null&&A!==void 0?A:C0(n,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const p=Math.max(e,t);if(p>=960&&h)return Ad(e,t,[f,h,l],u);if(p>=480)return Ad(e,t,[f,l],u)}return Ad(e,t,[l])}function _x(n,e,t){var r,i,A,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ue.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(r=o.width)!==null&&r!==void 0?r:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(A=o.height)!==null&&A!==void 0?A:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),id(n.source===R.Source.ScreenShare,a,c,t)}function Sx(n,e,t,r){const i=kx(n,e,t);let{encoding:A}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(A=a.encoding,a.width>=s)break}if(r)switch(r){case"av1":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.7;break;case"vp9":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.85;break}return A}function kx(n,e,t){if(n)return wx;const r=e>t?e/t:t/e;return Math.abs(r-16/9)<Math.abs(r-4/3)?vx:yx}function C0(n,e){if(n)return Bx(e);const{width:t,height:r}=e,i=t>r?t/r:r/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?bx:Cx}function Ad(n,e,t,r){const i=[];if(t.forEach((A,s)=>{if(s>=rd.length)return;const o=Math.min(n,e),c={rid:rd[s],scaleResolutionDownBy:Math.max(1,o/Math.min(A.width,A.height)),maxBitrate:A.encoding.maxBitrate},u=r&&A.encoding.maxFramerate?Math.min(r,A.encoding.maxFramerate):A.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=Ni()||s===0;A.encoding.priority&&l&&(c.priority=A.encoding.priority,c.networkPriority=A.encoding.priority),i.push(c)}),Tn()&&Yv()==="ios"){let A;i.forEach(o=>{A?o.maxFramerate&&o.maxFramerate>A&&(A=o.maxFramerate):A=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=A&&(s&&(s=!1,ue.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ue.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(A)),o.maxFramerate=A)})}return i}function B0(n){if(n)return n.sort((e,t)=>{const{encoding:r}=e,{encoding:i}=t;return r.maxBitrate>i.maxBitrate?1:r.maxBitrate<i.maxBitrate?-1:r.maxBitrate===i.maxBitrate&&r.maxFramerate&&i.maxFramerate?r.maxFramerate>i.maxFramerate?1:-1:0})}class la{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Ex(n){return n.source===R.Source.ScreenShare||n.constraints.height&&wr(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ux=5e3;class da extends b0{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,r,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let A;try{A=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(A.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=ca(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Dt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Kt())return;const r=(t=this.sender)===null||t===void 0?void 0:t.getParameters();r&&(this.encodings=r.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},nd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=fr(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)A=c.value,o=!1,yield(s=A.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=fr(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){A=c.value,o=!1;const u=A;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.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{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],r=yield this.sender.getStats();return r.forEach(i=>{var A;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:(A=i.rid)!==null&&A!==void 0?A:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=r.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,A)=>{var s,o;return((s=A.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let r=$t.LOW;r<=$t.HIGH;r+=1)t.push(new hl({quality:r,enabled:r<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;let o;if(e){const l=jl({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=fr(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){A=u.value,a=!1;const l=A;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){r={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(r){var i=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,r,A),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=fr(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return S(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const r={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,r),r}setSimulcastTrackSender(e,t){const r=this.simulcastCodecs.get(e);r&&(r.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ux))}setPublishingCodecs(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s,o,a;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(t=!0,r=fr(e);i=yield r.next(),A=i.done,!A;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield _0(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!A&&(o=r.return)&&(yield o.call(r))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return S(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 _0(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zv()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function _0(n,e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=yield r.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},A),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},A),{encodings:a,senderEncodings:e}));return}let c=!1;const u=dn();if((u==null?void 0:u.name)==="Chrome"&&Zr(u==null?void 0:u.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new la(d.scalabilityMode);let f=xi.OFF;if(t.forEach(p=>{p.enabled&&(f===xi.OFF||p.quality>f)&&(f=p.quality)}),f===xi.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const p=new la(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let p=(f=d.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=S0(p),v=t.find(y=>y.quality===g);v&&d.active!==v.enabled&&(c=!0,d.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(d.active?"enabled":"disabled"),A),Ni()&&(v.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&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},A),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function S0(n){switch(n){case"f":return $t.HIGH;case"h":return $t.MEDIUM;case"q":return $t.LOW;default:return $t.HIGH}}function k0(n,e,t,r){if(!t)return[new zr({quality:$t.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(r){const i=t[0].scalabilityMode,A=new la(i),s=[],o=A.suffix=="h"?1.5:2,a=A.suffix=="h"?2:3;for(let c=0;c<A.spatial;c+=1)s.push(new zr({quality:Math.min($t.HIGH,A.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return t.map(i=>{var A,s,o;const a=(A=i.scaleResolutionDownBy)!==null&&A!==void 0?A:1;let c=S0((s=i.rid)!==null&&s!==void 0?s:"");return new zr({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const E0="_lossy",U0="_reliable",Tx=2*1e3,sd="leave-reconnect";var pn;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(pn||(pn={}));class Ix extends Un.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ed.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=pn.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=ue,this.handleDataChannel=r=>S(this,[r],void 0,function(i){var A=this;let{channel:s}=i;return function*(){if(s){if(s.label===U0)A.reliableDCSub=s;else if(s.label===E0)A.lossyDCSub=s;else return;A.log.debug("on data channel ".concat(s.id,", ").concat(s.label),A.logContext),s.onmessage=A.handleDataMessage}}()}),this.handleDataMessage=r=>S(this,void 0,void 0,function*(){var i,A;const s=yield this.dataProcessLock.lock();try{let o;if(r.data instanceof ArrayBuffer)o=r.data;else if(r.data instanceof Blob)o=yield r.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:r.data}));return}const a=Nt.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,a.value.value.speakers):(((A=a.value)===null||A===void 0?void 0:A.case)==="user"&&xx(a,a.value.value),this.emit(N.DataPacketReceived,a))}finally{s()}}),this.handleDataError=r=>{const A=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(r instanceof ErrorEvent&&r.error){const{error:s}=r.error;this.log.error("DataChannel error on ".concat(A,": ").concat(r.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(A),Object.assign(Object.assign({},this.logContext),{event:r}))},this.handleBufferedAmountLow=r=>{const A=r.currentTarget.maxRetransmits===0?fe.LOSSY:fe.RELIABLE;this.updateAndEmitDCBufferStatus(A)},this.handleDisconnect=(r,i)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const A=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(N.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){A(s);return}r===sd&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=yt.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((r,i)=>{this.pcState===pn.Connected&&r();const A=()=>{this.off(N.Disconnected,s),r()},s=()=>{this.off(N.Restarted,A),i()};this.once(N.Restarted,A),this.once(N.Disconnected,s)}),this.updateAndEmitDCBufferStatus=r=>{const i=this.isBufferStatusLow(r);typeof i<"u"&&i!==this.dcBufferStatus.get(r)&&(this.dcBufferStatus.set(r,i),this.emit(N.DCBufferStatusChanged,i,r))},this.isBufferStatusLow=r=>{const i=this.dataChannelForKind(r);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Le.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Qi.RR_SIGNAL_DISCONNECTED))},this.log=Kn((t=e.loggerName)!==null&&t!==void 0?t:ln.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ql(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Dt,this.dataProcessLock=new Dt,this.dcBufferStatus=new Map([[fe.LOSSY,!0],[fe.RELIABLE,!0]]),this.client.onParticipantUpdate=r=>this.emit(N.ParticipantUpdate,r),this.client.onConnectionQuality=r=>this.emit(N.ConnectionQualityUpdate,r),this.client.onRoomUpdate=r=>this.emit(N.RoomUpdate,r),this.client.onSubscriptionError=r=>this.emit(N.SubscriptionError,r),this.client.onSubscriptionPermissionUpdate=r=>this.emit(N.SubscriptionPermissionUpdate,r),this.client.onSpeakersChanged=r=>this.emit(N.SpeakersChanged,r),this.client.onStreamStateUpdate=r=>this.emit(N.StreamStateChanged,r),this.client.onRequestResponse=r=>this.emit(N.SignalRequestResponse,r)}get logContext(){var e,t,r,i,A,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.room)===null||i===void 0?void 0:i.sid,participant:(s=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,r,i){return S(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=r,this.maxJoinAttempts=r.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const A=yield this.client.join(e,t,r,i);return this._isClosed=!1,this.latestJoinResponse=A,this.subscriberPrimary=A.subscriberPrimary,this.pcManager||(yield this.configure(A)),(!this.subscriberPrimary||A.fastPublish)&&this.negotiate(),this.clientConfiguration=A.clientConfiguration,setTimeout(()=>{this.emit(N.SignalConnected)},10),A}catch(A){if(A instanceof Qe&&A.reason===de.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,t,r,i);throw A}})}close(){return S(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(N.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return S(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 t=r=>{r&&(r.close(),r.onbufferedamountlow=null,r.onclose=null,r.onclosing=null,r.onerror=null,r.onmessage=null,r.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Vn("a track with the same ID has already been published");return new Promise((t,r)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],r(new Qe("publication of local track timed out, no response from server",de.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:A=>{clearTimeout(i),t(A)},reject:()=>{clearTimeout(i),r(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return S(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 S(this,void 0,void 0,function*(){var t,r;if(this.pcManager&&this.pcManager.currentState!==Xe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new fx(i,e.subscriberPrimary,this.loggerOptions),this.emit(N.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(A,s)=>{this.client.sendIceCandidate(A,s)},this.pcManager.onPublisherOffer=A=>{this.client.sendOffer(A)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(A,s,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(A),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),A===Xe.CONNECTED){const u=this.pcState===pn.New;this.pcState=pn.Connected,u&&this.emit(N.Connected,e)}else A===Xe.FAILED&&this.pcState===pn.Connected&&(this.pcState=pn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Qi.RR_SUBSCRIBER_FAILED:Qi.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Le.RECONNECTING,c=[Xe.FAILED,Xe.CLOSING,Xe.CLOSED].includes(A);a&&c&&!this._isClosed&&this.emit(N.Offline)}),this.pcManager.onTrack=A=>{this.emit(N.MediaTrackAdded,A.track,A.streams[0],A.receiver)},Fx((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>S(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,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>S(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.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:r}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],r(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(N.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(N.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(N.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(N.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(N.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Qi.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 Oi.DISCONNECT:this.emit(N.Disconnected,e==null?void 0:e.reason),this.close();break;case Oi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(sd);break;case Oi.RESUME:this.handleDisconnect(sd)}}}makeRTCConfiguration(e){var t;const r=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),r.encodedInsertableStreams=!0),e.iceServers&&!r.iceServers){const i=[];e.iceServers.forEach(A=>{const s={urls:A.urls};A.username&&(s.username=A.username),A.credential&&(s.credential=A.credential),i.push(s)}),r.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===GA.ENABLED&&(r.iceTransportPolicy="relay"),r.sdpSemantics="unified-plan",r.continualGatheringPolicy="gather_continually",r}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(E0,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(U0,{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,t,r){return S(this,void 0,void 0,function*(){if(Ql())return yield this.createTransceiverRTCRtpSender(e,t,r);if(Rl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ut("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(Ql())return this.createSimulcastTransceiverSender(e,t,r,i);if(Rl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ut("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,r){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Ki(e)&&(e.codec=t.videoCodec);const A={direction:"sendonly",streams:i};return r&&(A.sendEncodings=r),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,A)).sender})}createSimulcastTransceiverSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("publisher is closed");const A={direction:"sendonly"};i&&(A.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,A);if(r.videoCodec)return e.setSimulcastTrackSender(r.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return S(this,void 0,void 0,function*(){var t,r,i;if(!this._isClosed){if(this.attemptingReconnect){ue.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===GA.DISABLED||((i=(r=this.pcManager)===null||r===void 0?void 0:r.currentState)!==null&&i!==void 0?i:Xe.NEW)===Xe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(A){this.reconnectAttempts+=1;let s=!0;A instanceof ut?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:A})),s=!1):A instanceof Gi||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",Qi.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(N.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return S(this,void 0,void 0,function*(){var t,r,i;try{if(!this.url||!this.token)throw new ut("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let A;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Gi;A=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Qe&&s.reason===de.NotAllowed?new ut("could not reconnect, token might be expired"):new Gi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(N.SignalRestarted,A),yield this.waitForPCReconnected(),this.client.currentState!==Le.CONNECTED)throw new Gi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(N.Restarted)}catch(A){const s=yield(r=this.regionUrlProvider)===null||r===void 0?void 0:r.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),A}})}resumeConnection(e){return S(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ut("could not reconnect, url or token not saved");if(!this.pcManager)throw new ut("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Resuming);let r;try{this.setupSignalClientCallbacks(),r=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let A="";throw i instanceof Error&&(A=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Qe&&i.reason===de.NotAllowed?new ut("could not reconnect, token might be expired"):i instanceof Qe&&i.reason===de.LeaveRequest?i:new Gi(A)}if(this.emit(N.SignalResumed),r){const i=this.makeRTCConfiguration(r);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!==Le.CONNECTED)throw new Gi("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(N.Resumed)})}waitForPCInitialConnection(e,t){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=pn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ht(Tx),!this.pcManager)throw new ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=pn.Connected}catch(e){throw this.pcState=pn.Disconnected,new Qe("could not establish PC connection, ".concat(e.message),de.InternalError)}})}publishRpcResponse(e,t,r,i){return S(this,void 0,void 0,function*(){const A=new Nt({destinationIdentities:[e],kind:fe.RELIABLE,value:{case:"rpcResponse",value:new Rm({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:r??""}})}});yield this.sendDataPacket(A,fe.RELIABLE)})}publishRpcAck(e,t){return S(this,void 0,void 0,function*(){const r=new Nt({destinationIdentities:[e],kind:fe.RELIABLE,value:{case:"rpcAck",value:new Qm({requestId:t})}});yield this.sendDataPacket(r,fe.RELIABLE)})}sendDataPacket(e,t){return S(this,void 0,void 0,function*(){const r=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(r),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,r)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>r("Engine closed");for(this.once(N.Closing,i);!this.dcBufferStatus.get(e);)yield Ht(10);this.off(N.Closing,i),t()}}))}ensureDataTransportConnected(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var A;if(!r.pcManager)throw new ut("PC manager is closed");const s=i?r.pcManager.subscriber:r.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Qe("".concat(o," connection not set"),de.InternalError);let a=!1;!i&&!r.dataChannelForKind(t,i)&&(r.createDataChannels(),a=!0),!a&&!i&&!r.pcManager.publisher.isICEConnected&&r.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&r.negotiate();const c=r.dataChannelForKind(t,i);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+r.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((A=r.dataChannelForKind(t,i))===null||A===void 0?void 0:A.readyState)==="open")return;yield Ht(50)}throw new Qe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),de.InternalError)}()})}ensurePublisherConnected(e){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Xe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((e,t)=>S(this,void 0,void 0,function*(){if(!this.pcManager){t(new kl("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const r=new AbortController,i=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(N.Closing,i),this.pcManager.publisher.once(Vi.RTPVideoPayloadTypes,A=>{const s=new Map;A.forEach(o=>{const a=o.codec.toLowerCase();NF(a)&&s.set(o.payload,a)}),this.emit(N.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(r),e()}catch(A){A instanceof kl&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Qi.RR_UNKNOWN),t(A)}finally{this.off(N.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===fe.LOSSY)return this.lossyDCSub;if(e===fe.RELIABLE)return this.reliableDCSub}else{if(e===fe.LOSSY)return this.lossyDC;if(e===fe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var r,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const A=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new Zm({answer:A?aa({sdp:A.sdp,type:A.type}):void 0,offer:s?aa({sdp:s.sdp,type:s.type}):void 0,subscription:new Wo({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:zF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(r,i)=>{(r==null?void 0:r.id)!==void 0&&r.id!==null&&e.push(new $m({label:r.label,id:r.id,target:i}))};return t(this.dataChannelForKind(fe.LOSSY),un.PUBLISHER),t(this.dataChannelForKind(fe.RELIABLE),un.PUBLISHER),t(this.dataChannelForKind(fe.LOSSY,!0),un.SUBSCRIBER),t(this.dataChannelForKind(fe.RELIABLE,!0),un.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&yt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Kt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Kt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Gi extends Error{}function Fx(n){return n!==void 0&&n>13}function xx(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const r=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=r,e.destinationIdentities=r}class od{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ol(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return S(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 t=this.regionSettings.regions.filter(r=>!this.attemptedRegions.find(i=>i.url===r.url));if(t.length>0){const r=t[0];return this.attemptedRegions.push(r),ue.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return S(this,void 0,void 0,function*(){const t=yield fetch("".concat(Qx(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const r=yield t.json();return this.lastUpdateAt=Date.now(),r}else throw new Qe("Could not fetch region settings: ".concat(t.statusText),t.status===401?de.NotAllowed:de.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Qx(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class T0{get info(){return this._info}constructor(e,t,r){this.reader=t,this.totalByteSize=r,this._info=e,this.bytesReceived=0}}class Rx extends T0{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>S(this,void 0,void 0,function*(){try{const{done:t,value:r}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:r.content})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A=new Set;try{for(var s=!0,o=fr(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;A.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return Array.from(A)})}}class Px extends T0{constructor(e,t,r){super(e,t,r),this.receivedChunks=new Map}handleChunkReceived(e){var t;const r=sa(e.chunkIndex),i=this.receivedChunks.get(r);if(i&&i.version>e.version)return;this.receivedChunks.set(r,e),this.bytesReceived+=e.content.byteLength;const A=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,A)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>S(this,void 0,void 0,function*(){try{const{done:r,value:i}=yield e.read();return r?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A="";try{for(var s=!0,o=fr(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,A+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return A})}}class I0{constructor(e,t,r){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=r,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return S(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 Ox extends I0{}class Lx extends I0{}class F0 extends R{constructor(e,t,r,i,A){super(e,r,A),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?M.Muted:M.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=r=>{r.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(M.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(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(),nd)),XF()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const r=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(r){const{timestamp:i,rtpTimestamp:A}=r;A&&this.rtpTimestamp!==A&&(this.emit(M.TimeSyncUpdate,{timestamp:i,rtpTimestamp:A}),this.rtpTimestamp=A)}};e()}}class Dx extends F0{constructor(e,t,r,i,A,s){super(e,t,R.Kind.Audio,r,s),this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ca(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],A&&(this.sinkId=A.deviceId)}setVolume(e){var t;for(const r of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):r.volume=e;Tn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Tn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return S(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Pl(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Pl(e)&&e.setSinkId(this.sinkId).catch(r=>{this.log.error("Failed to set sink id on remote audio track",r,this.logContext)}),this.audioContext&&t&&(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 t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}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,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let r=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{r.connect(i),r=i}),this.gainNode=e.createGain(),r.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(M.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(M.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(r=>{r.type==="inbound-rtp"&&(t={type:"audio",streamId:r.id,timestamp:r.timestamp,jitter:r.jitter,bytesReceived:r.bytesReceived,concealedSamples:r.concealedSamples,concealmentEvents:r.concealmentEvents,silentConcealedSamples:r.silentConcealedSamples,silentConcealmentEvents:r.silentConcealmentEvents,totalAudioEnergy:r.totalAudioEnergy,totalSamplesDuration:r.totalSamplesDuration})}),t})}}const ad=100;class Mx extends F0{constructor(e,t,r,i,A){super(e,t,R.Kind.Video,r,A),this.elementInfos=[],this.monitorReceiver=()=>S(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=ca(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Zl(()=>{this.updateDimensions()},ad),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Mi(this._mediaStreamTrack,t):Di(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Nx(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===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 t=this.elementInfos.filter(r=>r===e);for(const r of t)r.stopObserving();this.elementInfos=this.elementInfos.filter(r=>r!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const r of t)this.stopObservingElement(r);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,r="",i=new Map;return e.forEach(A=>{A.type==="inbound-rtp"?(r=A.codecId,t={type:"video",streamId:A.id,framesDecoded:A.framesDecoded,framesDropped:A.framesDropped,framesReceived:A.framesReceived,packetsReceived:A.packetsReceived,packetsLost:A.packetsLost,frameWidth:A.frameWidth,frameHeight:A.frameHeight,pliCount:A.pliCount,firCount:A.firCount,nackCount:A.nackCount,jitter:A.jitter,timestamp:A.timestamp,bytesReceived:A.bytesReceived,decoderImplementation:A.decoderImplementation}):A.type==="codec"&&i.set(A.id,A)}),t&&r!==""&&i.get(r)&&(t.mimeType=i.get(r).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(r=>r.element===e);for(const r of t)this.stopObservingElementInfo(r)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const r=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,A=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||A;if(this.lastVisible!==s){if(!s&&Date.now()-r<ad){yt.setTimeout(()=>{this.updateVisibility()},ad);return}this.lastVisible=s,this.emit(M.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let r=0,i=0;const A=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*A,a=s.height()*A;o+a>r+i&&(r=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===r&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:r,height:i},this.emit(M.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Zv():t||(Zv()>2?2:1)}}class Nx{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=r=>{var i;const{target:A,isIntersecting:s}=r;A===this.element&&(this.isIntersecting=s,this.isPiP=YA(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var r,i,A;(i=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=YA(this.element),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this)},this.onLeavePiP=()=>{var r;this.isPiP=YA(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.element=e,this.isIntersecting=t??cd(e),this.isPiP=Kt()&&YA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,r;this.isIntersecting=cd(this.element),this.isPiP=YA(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,e0().observe(this.element),$v().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),(r=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,r,i,A;(e=e0())===null||e===void 0||e.unobserve(this.element),(t=$v())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(r=window.documentPictureInPicture)===null||r===void 0||r.removeEventListener("enter",this.onEnterPiP),(A=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||A===void 0||A.removeEventListener("pagehide",this.onLeavePiP)}}function YA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?cd(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function cd(n,e){const t=e||window;let r=n.offsetTop,i=n.offsetLeft;const A=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,r+=n.offsetTop,i+=n.offsetLeft;return r<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&r+s>t.pageYOffset&&i+A>t.pageXOffset&&!o&&a!=="none"}class jn extends Un.EventEmitter{constructor(e,t,r,i){var A;super(),this.metadataMuted=!1,this.encryption=Jt.NONE,this.log=ue,this.handleMuted=()=>{this.emit(M.Muted)},this.handleUnmuted=()=>{this.emit(M.Unmuted)},this.log=Kn((A=i==null?void 0:i.loggerName)!==null&&A!==void 0?A:ln.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=r,this.source=R.Source.Unknown}setTrack(e){this.track&&(this.track.off(M.Muted,this.handleMuted),this.track.off(M.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(M.Muted,this.handleMuted),e.on(M.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Be(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Jt.NONE}get audioTrack(){if(Gn(this.track))return this.track}get videoTrack(){if(Ki(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.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(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(jn||(jn={}));class ud extends jn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(M.Ended)},this.updateInfo(t),this.setTrack(r)}setTrack(e){this.track&&this.track.off(M.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(M.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 S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Gn(this.track)){const t=this.track.getSourceTrackSettings(),r=new Set;return t.autoGainControl&&r.add(cn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&r.add(cn.TF_ECHO_CANCELLATION),t.noiseSuppression&&r.add(cn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&r.add(cn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||r.add(cn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&r.add(cn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(r.values())}else return[]}}function ha(n,e){return S(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:A}=o0(n);let s=A.audio,o=A.video;if(r&&typeof A.audio=="object"&&(A.audio.processor=r),i&&typeof A.video=="object"&&(A.video.processor=i),n.audio&&typeof A.audio=="object"&&typeof A.audio.deviceId=="string"){const l=A.audio.deviceId;A.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},A.audio),{deviceId:{ideal:l}})}if(A.video&&typeof A.video=="object"&&typeof A.video.deviceId=="string"){const l=A.video.deviceId;A.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},A.video),{deviceId:{ideal:l}})}(A.audio===!0||typeof A.audio=="object"&&!A.audio.deviceId)&&(A.audio={deviceId:"default"}),A.video===!0?A.video={deviceId:"default"}:typeof A.video=="object"&&!A.video.deviceId&&(A.video.deviceId="default");const a=r0(A,m0,v0),c=jl(a),u=navigator.mediaDevices.getUserMedia(c);A.audio&&(pt.userMediaPromiseMap.set("audioinput",u),u.catch(()=>pt.userMediaPromiseMap.delete("audioinput"))),A.video&&(pt.userMediaPromiseMap.set("videoinput",u),u.catch(()=>pt.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>S(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let p;const g=h?c.audio:c.video;typeof g!="boolean"&&(p=g);const v=d.getSettings().deviceId;p!=null&&p.deviceId&&wr(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const y=mx(d,p,e);return y.kind===R.Kind.Video?y.source=R.Source.Camera:y.kind===R.Kind.Audio&&(y.source=R.Source.Microphone),y.mediaStream=l,Gn(y)&&r?yield y.setProcessor(r):Ki(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return ha(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function Hx(n){return S(this,void 0,void 0,function*(){return(yield ha({audio:!1,video:n??!0}))[0]})}function Kx(n){return S(this,void 0,void 0,function*(){return(yield ha({audio:n??!0,video:!1}))[0]})}var Br;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Br||(Br={}));function Vx(n){switch(n){case VA.EXCELLENT:return Br.Excellent;case VA.GOOD:return Br.Good;case VA.POOR:return Br.Poor;case VA.LOST:return Br.Lost;default:return Br.Unknown}}class x0 extends Un.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.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===jo.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ri.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,r,i,A,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:jo.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Br.Unknown,this.log=ue,this.log=Kn((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:ln.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=r,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=A??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Nl,this.once(V.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.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 t;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===Ri.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ri.ACTIVE&&this.emit(V.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,r=this.metadata;this.metadata=e,t&&this.emit(V.ParticipantMetadataChanged,r)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(V.ParticipantNameChanged,e)}_setAttributes(e){const t=YF(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(V.AttributesChanged,t)}setPermissions(e){var t,r,i,A,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((r=this.permissions)===null||r===void 0?void 0:r.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((A=this.permissions)===null||A===void 0?void 0:A.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(V.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(V.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Vx(e),t!==this._connectionQuality&&this.emit(V.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Gn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(M.Muted,()=>{this.emit(V.TrackMuted,e)}),e.on(M.Unmuted,()=>{this.emit(V.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Gx(n){var e,t,r;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Xm({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(r=n.allowAll)!==null&&r!==void 0?r:!1,trackSids:n.allowedTrackSids||[]})}const Q0=15e3;class jx extends x0{constructor(e,t,r,i,A){super(e,t,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=Jt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Nl)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,u=this.pendingSignalRequests.get(o);u&&(a!==pl.OK&&u.reject(new jv(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=Ye.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Gx(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Be(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Be(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Be(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.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 v=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,p=fr(v),g;g=yield p.next(),o=g.done,!o;f=!0){u=g.value,f=!1;const y=u;TF(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Be(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>S(this,void 0,void 0,function*(){if(s.source===R.Source.ScreenShare||s.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Be(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(ei(s)||br(s))try{if(Kt())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===R.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Be(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.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),Be(s))),ei(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),Be(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=r,this.roomOptions=i,this.setupEngine(r),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Jt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(N.RemoteMute,(t,r)=>{const i=this.trackPublications.get(t);!i||!i.track||(r?i.mute():i.unmute())}),this.engine.on(N.Connected,this.handleReconnected).on(N.SignalRestarted,this.handleReconnected).on(N.SignalResumed,this.handleReconnected).on(N.Restarting,this.handleReconnecting).on(N.Resuming,this.handleReconnecting).on(N.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(N.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(N.Disconnected,this.handleDisconnected).on(N.SignalRequestResponse,this.handleSignalRequestResponse).on(N.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return S(this,arguments,void 0,function(t){var r=this;let{metadata:i,name:A,attributes:s}=t;return function*(){return new Promise((o,a)=>S(r,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=A??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:A,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!A||this.name===A)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[p,g]=f;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(d),o();return}yield Ht(50)}a(new jv("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,r){return this.setTrackEnabled(R.Source.Camera,e,t,r)}setMicrophoneEnabled(e,t,r){return this.setTrackEnabled(R.Source.Microphone,e,t,r)}setScreenShareEnabled(e,t,r){return this.setTrackEnabled(R.Source.ScreenShare,e,t,r)}setPermissions(e){const t=this.permissions,r=super.setPermissions(e);return r&&t&&this.emit(V.ParticipantPermissionsChanged,t),r}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){this.encryptionType=e?Jt.GCM:Jt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,r,i){return S(this,void 0,void 0,function*(){var A,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let a;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 R.Source.Camera:a=yield this.createTracks({video:(A=r)!==null&&A!==void 0?A:!0});break;case R.Source.Microphone:a=yield this.createTracks({audio:(s=r)!==null&&s!==void 0?s:!0});break;case R.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Vn(e)}}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(V.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Be(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(R.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return S(this,void 0,void 0,function*(){var t,r;e??(e={});const i=r0(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(r=this.roomOptions)===null||r===void 0?void 0:r.videoCaptureDefaults);try{return(yield ha(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Gn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit(V.AudioStreamAcquired)),Ki(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(A){throw A instanceof Error&&(e.audio&&(this.microphoneError=A),e.video&&(this.cameraError=A)),A}})}createScreenTracks(e){return S(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Sl("getDisplayMedia not supported");e.resolution===void 0&&!PF()&&(e.resolution=xl.h1080fps30.resolution);const t=JF(e),r=yield navigator.mediaDevices.getDisplayMedia(t),i=r.getVideoTracks();if(i.length===0)throw new Vn("no video track found");const A=new da(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});A.source=R.Source.ScreenShare,e.contentHint&&(A.mediaStreamTrack.contentHint=e.contentHint);const s=[A];if(r.getAudioTracks().length>0){this.emit(V.AudioStreamAcquired);const o=new ua(r.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;ei(r)&&r.setAudioContext(A.audioContext),yield(o=A.reconnectFuture)===null||o===void 0?void 0:o.promise,A.republishPromise&&!s&&(yield A.republishPromise),Hi(r)&&A.pendingPublishPromises.has(r)&&(yield A.pendingPublishPromises.get(r));let l;if(r instanceof MediaStreamTrack)l=r.getConstraints();else{l=r.constraints;let v;switch(r.source){case R.Source.Microphone:v="audioinput";break;case R.Source.Camera:v="videoinput"}v&&A.activeDeviceMap.has(v)&&(l=Object.assign(Object.assign({},l),{deviceId:A.activeDeviceMap.get(v)}))}if(r instanceof MediaStreamTrack)switch(r.kind){case"audio":r=new ua(r,l,!0,A.audioContext,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;case"video":r=new da(r,l,!0,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;default:throw new Vn("unsupported MediaStreamTrack kind ".concat(r.kind))}else r.updateLoggerOptions({loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});let d;if(A.trackPublications.forEach(v=>{v.track&&v.track===r&&(d=v)}),d)return A.log.warn("track has already been published, skipping",Object.assign(Object.assign({},A.logContext),Be(d))),d;const h="channelCount"in r.mediaStreamTrack.getSettings()&&r.mediaStreamTrack.getSettings().channelCount===2||r.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&A.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},A.logContext),Be(r))),i.red===void 0&&A.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),(u=i.red)!==null&&u!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},A.roomOptions.publishDefaults),i);!OF()&&A.roomOptions.e2ee&&(A.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({},A.logContext)),p.simulcast=!1),p.source&&(r.source=p.source);const g=new Promise((v,y)=>S(A,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Le.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Be(r)}));const C=()=>S(this,void 0,void 0,function*(){try{const B=yield this.publish(r,p,f);v(B)}catch(B){y(B)}});setTimeout(()=>{this.engine.off(N.SignalConnected,C),y(new El("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(N.SignalConnected,C),this.engine.on(N.Closing,()=>{this.engine.off(N.SignalConnected,C),y(new El("publishing rejected as engine closed",499))})}else try{const C=yield this.publish(r,p,f);v(C)}catch(C){y(C)}}catch(C){y(C)}}));A.pendingPublishPromises.set(r,g);try{return yield g}catch(v){throw v}finally{A.pendingPublishPromises.delete(r)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Be(e))),!1;const{canPublish:t,canPublishSources:r}=this.permissions;return t&&(r.length===0||r.map(i=>ZF(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Be(e))),!1)}publish(e,t,r){return S(this,void 0,void 0,function*(){var i,A,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new El("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(b=>Hi(e)&&b.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Be(e))),t.stopMicTrackOnMute&&Gn(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Ni()&&(t.simulcast=!1),t.videoCodec==="av1"&&!xF()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!QF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=$l),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(b=>t.videoCodec===oa(b.mime))||(t.videoCodec=oa(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(M.Muted,this.onTrackMuted),e.on(M.Unmuted,this.onTrackUnmuted),e.on(M.Ended,this.handleTrackEnded),e.on(M.UpstreamPaused,this.onTrackUpstreamPaused),e.on(M.UpstreamResumed,this.onTrackUpstreamResumed),e.on(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new cl({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(!((A=t.red)!==null&&A!==void 0)||A),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let v;if(e.kind===R.Kind.Video){let b={width:0,height:0};try{b=yield e.waitForDimensions()}catch{const k=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:qA.h720.resolution;b={width:k.width,height:k.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{dims:b}))}g.width=b.width,g.height=b.height,br(e)&&(JA(p)&&(e.source===R.Source.ScreenShare&&(t.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),Be(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new al({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:$l}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===Jt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new al({codec:t.backupCodec.codec,cid:""})))),v=id(e.source===R.Source.ScreenShare,g.width,g.height,t),g.layers=k0(g.width,g.height,v,JA(t.videoCodec))}else e.kind===R.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ut("cannot publish track when not connected");const y=()=>S(this,void 0,void 0,function*(){var b,_,k;if(!this.engine.pcManager)throw new ut("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),br(e)&&((b=t.degradationPreference)!==null&&b!==void 0||(t.degradationPreference=Ex(e)),e.setDegradationPreference(t.degradationPreference)),v)if(Ni()&&e.kind===R.Kind.Audio){let U;for(const I of this.engine.pcManager.publisher.getTransceivers())if(I.sender===e.sender){U=I;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((_=v[0])===null||_===void 0)&&_.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&JA(e.codec)&&(!((k=v[0])===null||k===void 0)&&k.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([this.engine.addTrack(g),y()]))[0];else{C=yield this.engine.addTrack(g);let b;if(C.codecs.forEach(_=>{b===void 0&&(b=_.mimeType)}),b&&e.kind===R.Kind.Video){const _=oa(b);_!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{codec:_})),t.videoCodec=_,v=id(e.source===R.Source.ScreenShare,g.width,g.height,t))}yield y()}const B=new ud(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return B.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:C})),br(e)?e.startMonitor(this.engine.client):ei(e)&&e.startMonitor(),this.addTrackPublication(B),this.emit(V.LocalTrackPublished,B),B})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,r){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==Jt.NONE)return;let A;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(A=h)}),!A)throw new Vn("track is not published");if(!br(e))throw new Vn("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),r),o=_x(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Be(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new cl({cid:a.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=k0(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new ut("cannot publish track when not connected");const u=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return S(this,void 0,void 0,function*(){var r,i;if(Hi(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Be(e))),yield c)}const A=this.getPublicationForTrack(e),s=A?Be(A):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!A||!A.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=A.track,e.off(M.Muted,this.onTrackMuted),e.off(M.Unmuted,this.onTrackUnmuted),e.off(M.Ended,this.handleTrackEnded),e.off(M.UpstreamPaused,this.onTrackUpstreamPaused),e.off(M.UpstreamResumed,this.onTrackUpstreamResumed),e.off(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(r=this.roomOptions)===null||r===void 0?void 0:r.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Xe.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),br(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!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(A.trackSid),A.kind){case R.Kind.Audio:this.audioTrackPublications.delete(A.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(A.trackSid);break}return this.emit(V.LocalTrackUnpublished,A),A.setTrack(void 0),o&&(yield this.engine.negotiate()),A})}unpublishTracks(e){return S(this,void 0,void 0,function*(){return(yield Promise.all(e.map(r=>this.unpublishTrack(r)))).filter(r=>!!r)})}republishAllTracks(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){r.republishPromise&&(yield r.republishPromise),r.republishPromise=new Promise((A,s)=>S(r,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),o.push(a))}),yield Promise.all(o.map(a=>S(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==R.Source.ScreenShare&&c.source!==R.Source.ScreenShareAudio&&(ei(c)||br(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),A()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield r.republishPromise}()})}publishData(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const A=i.reliable?fe.RELIABLE:fe.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Nt({kind:A,value:{case:"user",value:new Im({participantIdentity:r.identity,payload:t,destinationIdentities:s,topic:o})}});yield r.engine.sendDataPacket(a,A)}()})}publishDtmf(e,t){return S(this,void 0,void 0,function*(){const r=new Nt({kind:fe.RELIABLE,value:{case:"sipDtmf",value:new Fm({code:e,digit:t})}});yield this.engine.sendDataPacket(r,fe.RELIABLE)})}sendChatMessage(e,t){return S(this,void 0,void 0,function*(){const r={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},i=new Nt({value:{case:"chatMessage",value:new nl(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp)}))}});return yield this.engine.sendDataPacket(i,fe.RELIABLE),this.emit(V.ChatMessage,r),r})}editChatMessage(e,t){return S(this,void 0,void 0,function*(){const r=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Nt({value:{case:"chatMessage",value:new nl(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp),editTimestamp:Ke.parse(r.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,fe.RELIABLE),this.emit(V.ChatMessage,r),r})}sendText(e,t){return S(this,void 0,void 0,function*(){var r;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(r=t==null?void 0:t.attachments)===null||r===void 0?void 0:r.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((p,g)=>p+g,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),c(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>S(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return S(this,void 0,void 0,function*(){var t,r;const i=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new il({streamId:i,mimeType:A.mimeType,topic:A.topic,timestamp:$r(A.timestamp),totalLength:$r(e==null?void 0:e.totalSize),attributes:A.attributes,contentHeader:{case:"textHeader",value:new Km({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"?rl.UPDATE:rl.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new Nt({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,fe.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return S(this,void 0,void 0,function*(){for(const p of WF(f,Q0)){yield u.engine.waitForBufferStatusLow(fe.RELIABLE);const g=new Al({content:p,streamId:i,chunkIndex:$r(c)}),v=new Nt({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield u.engine.sendDataPacket(v,fe.RELIABLE),c+=1}})},close(){return S(this,void 0,void 0,function*(){const f=new sl({streamId:i}),p=new Nt({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(p,fe.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>S(this,void 0,void 0,function*(){yield h.close()});u.engine.once(N.Closing,d);const h=new Ox(l,A,()=>this.engine.off(N.Closing,d));return h})}sendFile(e,t){return S(this,void 0,void 0,function*(){const r=crypto.randomUUID();return yield this._sendFile(r,e,t),{id:r}})}_sendFile(e,t,r){return S(this,void 0,void 0,function*(){var i;const A=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=r==null?void 0:r.mimeType)!==null&&i!==void 0?i:t.type,topic:r==null?void 0:r.topic,destinationIdentities:r==null?void 0:r.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield A.write(a)}return yield A.close(),A.info})}streamBytes(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(r=e==null?void 0:e.mimeType)!==null&&r!==void 0?r:"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:(A=e==null?void 0:e.name)!==null&&A!==void 0?A:"unknown"},u=new il({totalLength:$r((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:$r(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Vm({name:c.name})}}),l=new Nt({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,fe.RELIABLE);let d=0;const h=new Dt,f=this.engine,p=this.log,g=new WritableStream({write(y){return S(this,void 0,void 0,function*(){const C=yield h.lock();let B=0;try{for(;B<y.byteLength;){const b=y.slice(B,B+Q0);yield f.waitForBufferStatusLow(fe.RELIABLE);const _=new Nt({destinationIdentities:a,value:{case:"streamChunk",value:new Al({content:b,streamId:o,chunkIndex:$r(d)})}});yield f.sendDataPacket(_,fe.RELIABLE),d+=1,B+=b.byteLength}}finally{C()}})},close(){return S(this,void 0,void 0,function*(){const y=new sl({streamId:o}),C=new Nt({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(C,fe.RELIABLE)})},abort(y){p.error("Sink error:",y)}});return new Lx(g,c)})}performRpc(e){return S(this,arguments,void 0,function(t){var r=this;let{destinationIdentity:i,method:A,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>S(r,void 0,void 0,function*(){var l,d,h,f;if(td(s)>y0){u(Ye.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&Zr((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){u(Ye.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,A,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),u(Ye.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(v)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:i});const v=setTimeout(()=>{this.pendingResponses.delete(p),u(Ye.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(y,C)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),C?u(C):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,r){const i=this.pendingResponses.get(e);i?(i.resolve(t,r),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=new Nt({destinationIdentities:[e],kind:fe.RELIABLE,value:{case:"rpcRequest",value:new xm({id:t,method:r,payload:i,responseTimeoutMs:A,version:1})}});yield this.engine.sendDataPacket(s,fe.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:r}]of this.pendingAcks)r===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:r,resolve:i}]of this.pendingResponses)r===e&&(i(null,Ye.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var r,i;const A=this.trackPublications.get(t.sid);if(A){const s=A.isMuted||((i=(r=A.track)===null||r===void 0?void 0:r.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Be(A)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(r=>{const i=r.track;i&&(e instanceof MediaStreamTrack?(ei(i)||br(i))&&i.mediaStreamTrack===e&&(t=r):e===i&&(t=r))}),t}waitForPendingPublicationOfSource(e){return S(this,void 0,void 0,function*(){const r=Date.now();for(;Date.now()<r+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(A=>{let[s]=A;return s.source===e});if(i)return i[1];yield Ht(20)}})}}class Wx extends jn{constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=$t.HIGH,this.handleEnded=A=>{this.setTrack(void 0),this.emit(M.Ended,A)},this.handleVisibilityChange=A=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(A),this.logContext),this.disabled=!A,this.emitTrackUpdate()},this.handleVideoDimensionsChange=A=>{this.log.debug("adaptivestream video dimensions ".concat(A.width,"x").concat(A.height),this.logContext),this.videoDimensions=A,this.emitTrackUpdate()},this.subscribed=r,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Wo({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Om({participantSid:"",trackSids:[this.trackSid]})]});this.emit(M.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(r)}get subscriptionStatus(){return this.subscribed===!1?jn.SubscriptionStatus.Unsubscribed:super.isSubscribed?jn.SubscriptionStatus.Subscribed:jn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?jn.PermissionStatus.Allowed:jn.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 t,r;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((r=this.videoDimensions)===null||r===void 0?void 0:r.height)===e.height||(Vl(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Vl(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,r=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(M.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(M.VisibilityChanged,this.handleVisibilityChange),i.off(M.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(M.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(M.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(M.VisibilityChanged,this.handleVisibilityChange),e.on(M.Ended,this.handleEnded),this.emit(M.Subscribed,e)),this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(M.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?M.Muted:M.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(M.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(M.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===R.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 Vl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new jm({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=$t.HIGH,this.emit(M.UpdateSettings,e)}}class pa extends x0{static fromParticipantInfo(e,t,r){return new pa(e,t.sid,t.identity,t.name,t.metadata,t.attributes,r,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,r,i,A,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:jo.STANDARD;super(t,r||"",i,A,s,o,a),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(M.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Be(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(M.UpdateSubscription,t=>{t.participantTracks.forEach(r=>{r.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(M.SubscriptionPermissionChanged,t=>{this.emit(V.TrackSubscriptionPermissionChanged,e,t)}),e.on(M.SubscriptionStatusChanged,t=>{this.emit(V.TrackSubscriptionStatusChanged,e,t)}),e.on(M.Subscribed,t=>{this.emit(V.TrackSubscribed,t,e)}),e.on(M.Unsubscribed,t=>{this.emit(V.TrackUnsubscribed,t,e)}),e.on(M.SubscriptionFailed,t=>{this.emit(V.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:R.Source.Microphone;this.volumeMap.set(t,e);const r=this.getTrackPublication(t);r&&r.track&&r.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,r,i,A,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(V.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,r,i,A,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),Be(o))),this.emit(V.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new Mx(e,t,i,A):c=new Dx(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(r),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Kl(c)&&Gn(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,r=new Map;return e.tracks.forEach(i=>{var A,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=R.kindFromProto(i.type);if(!a)return;o=new Wx(a,i,(A=this.signalClient.connectOptions)===null||A===void 0?void 0:A.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),r.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==R.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Be(c),newTrack:Be(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Be(i))),this.unpublishTrack(i.trackSid,!0))}),r.forEach(i=>{this.emit(V.TrackPublished,i)}),!0}unpublishTrack(e,t){const r=this.trackPublications.get(e);if(!r)return;const{track:i}=r;switch(i&&(i.stop(),r.setTrack(void 0)),this.trackPublications.delete(e),r.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(V.TrackUnpublished,r)}setAudioOutput(e){return S(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(r=>{var i;Gn(r.track)&&Kl(r.track)&&t.push(r.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:r})),super.emit(e,...r)}}var ge;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ge||(ge={}));const qx=4*1e3;class ji extends Un.EventEmitter{constructor(e){var t,r,i,A;if(super(),t=this,this.state=ge.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ue,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,o,a)=>S(this,void 0,void 0,function*(){var c;if(!RF())throw Tn()?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 u=yield this.disconnectLock.lock();if(this.state===ge.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(ge.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ol(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new od(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const l=(h,f,p)=>S(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{yield this.attemptConnection(p??s,o,a,y),this.abortController=void 0,h()}catch(C){if(this.regionUrlProvider&&C instanceof Qe&&C.reason!==de.Cancelled&&C.reason!==de.NotAllowed){let B=null;try{B=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(b){if(b instanceof Qe&&(b.status===401||b.reason===de.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(b);return}}B&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(B),this.logContext),this.recreateEngine(),yield l(h,f,B)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,n0(C)),f(C))}else{let B=an.UNKNOWN_REASON;C instanceof Qe&&(B=n0(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,B),f(C)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Nl((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>S(this,void 0,void 0,function*(){var d,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(v=>{let[y,C]=v;return"".concat(y,": ").concat(C)}).join(", ")),{room:(d=p.room)===null||d===void 0?void 0:d.name,roomSid:(h=p.room)===null||h===void 0?void 0:h.sid,identity:(f=p.participant)===null||f===void 0?void 0:f.identity}),!g.version)throw new yF("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>S(this,void 0,void 0,function*(){var u,l;this.state===ge.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ed),a),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,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Qe("could not establish signal connection",de.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Qe&&(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 Qe("Connection attempt aborted",de.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Kt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Kt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ge.Connected),this.emit(L.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return S(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===ge.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===ge.Connecting||c.state===ge.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Qe("Client initiated disconnect",de.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,an.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const s=[],o=dn();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=Ml();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,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(L.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>S(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{s.includes(u)||s.push(u)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.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(ge.Reconnecting)&&this.emit(L.Reconnecting)},this.handleSignalRestarted=s=>S(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(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}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(ge.Connected),this.emit(L.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Ri.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(L.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(L.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=R.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(V.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(L.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);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 a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(L.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(V.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(L.SipDTMFReceived,o,s),s==null||s.emit(V.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a==null?void 0:a.trackPublications.get(o.trackId),u=KF(o,this.transcriptionReceivedTimes);c==null||c.emit(M.TranscriptionReceived,u),a==null||a.emit(V.TranscriptionReceived,u,c),this.emit(L.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=VF(o);this.emit(L.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(L.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(L.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(L.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(L.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(L.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var s,o,a;const c=pt.getInstance().previousDevices,u=yield pt.getInstance().getDevices(void 0,!1),l=dn();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of u){const f=c.find(p=>p.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(L.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=qF(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=u.filter(y=>y.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&g.length>0&&((a=g[0])===null||a===void 0?void 0:a.deviceId)!==v){yield this.switchActiveDevice(h,g[0].deviceId);continue}h==="audioinput"&&!yr()||h==="videoinput"||g.length>0&&!g.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(L.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(L.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(L.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(L.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(L.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(L.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(L.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(L.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(M.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(L.LocalTrackPublished,s,this.localParticipant),ei(s.track)&&(yield s.track.checkForSilence())&&this.emit(L.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=s0(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(L.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(M.Restarted,this.onLocalTrackRestarted),this.emit(L.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>S(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=s0(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(L.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(L.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(L.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(L.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(L.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},px),e),this.log=Kn((r=this.options.loggerName)!==null&&r!==void 0?r:ln.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},m0),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},v0),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},hx),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Dt,this.localParticipant=new jx("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",wr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",wr(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",wr(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Kt()){const s=new AbortController;(A=navigator.mediaDevices)===null||A===void 0||A.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),ji.cleanupRegistry&&ji.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,r,i,A,s){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,Ye.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(r);if(!o){yield this.engine.publishRpcResponse(e,t,null,Ye.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:A});td(u)>y0?(a=Ye.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(r))):c=u}catch(u){u instanceof Ye?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),a=Ye.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return S(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 $F(this.options.e2ee),this.e2eeManager.on(mr.ParticipantEncryptionStatusChanged,(t,r)=>{jF(r)&&(this.isE2EEEnabled=t),this.emit(L.ParticipantEncryptionStatusChanged,t,r)}),this.e2eeManager.on(mr.EncryptionError,t=>this.emit(L.EncryptionError,t)),(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,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return S(this,void 0,void 0,function*(){return this.state===ge.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const r=i=>{i.sid!==""&&(this.engine.off(N.RoomUpdate,r),e(i.sid))};this.engine.on(N.RoomUpdate,r),this.once(L.Disconnected,()=>{this.engine.off(N.RoomUpdate,r),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ix(this.options),this.engine.on(N.ParticipantUpdate,this.handleParticipantUpdates).on(N.RoomUpdate,this.handleRoomUpdate).on(N.SpeakersChanged,this.handleSpeakersChanged).on(N.StreamStateChanged,this.handleStreamStateUpdate).on(N.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(N.SubscriptionError,this.handleSubscriptionError).on(N.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(N.MediaTrackAdded,(e,t,r)=>{this.onTrackAdded(e,t,r)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ge.SignalReconnecting)&&this.emit(L.SignalReconnecting)}).on(N.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ge.Connected)&&this.emit(L.Reconnected)}).on(N.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ge.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.Offline,()=>{this.setAndEmitConnectionState(ge.Reconnecting)&&this.emit(L.Reconnecting)}).on(N.DCBufferStatusChanged,(e,t)=>{this.emit(L.DCBufferStatusChanged,e,t)}).on(N.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(r=>{let{trackSid:i}=r;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(V.LocalTrackSubscribed,t),this.emitWhenConnected(L.LocalTrackSubscribed,t,this.localParticipant)}).on(N.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,r)=>{this.handleParticipantDisconnected(r,t)}),this.emit(L.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 t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pt.getInstance().getDevices(e,t)}prepareConnection(e,t){return S(this,void 0,void 0,function*(){if(this.state===ge.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ol(new URL(e))&&t){this.regionUrlProvider=new od(e,t);const r=yield this.regionUrlProvider.getNextBestRegionUrl();r&&this.state===ge.Disconnected&&(this.regionUrl=r,yield fetch(Hl(r),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(r),this.logContext))}else yield fetch(Hl(e),{method:"HEAD"})}catch(r){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:r}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return S(this,void 0,void 0,function*(){let r=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new En({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new En({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new En({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new En({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":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new En({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new En({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 En({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),r=()=>S(this,void 0,void 0,function*(){const A=this.engine.client.onLeave;A&&A(new qo({reason:an.CLIENT_INITIATED,action:Oi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new En({scenario:{case:"subscriberBandwidth",value:$r(t)}});break;case"leave-full-reconnect":i=new En({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield r())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(r==="audioinput"){g=A.localParticipant.audioTrackPublications.size===0;const y=(o=A.getActiveDevice(r))!==null&&o!==void 0?o:A.options.audioCaptureDefaults.deviceId;A.options.audioCaptureDefaults.deviceId=v;const C=Array.from(A.localParticipant.audioTrackPublications.values()).filter(B=>B.source===R.Source.Microphone);try{p=(yield Promise.all(C.map(B=>{var b;return(b=B.audioTrack)===null||b===void 0?void 0:b.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw A.options.audioCaptureDefaults.deviceId=y,B}}else if(r==="videoinput"){g=A.localParticipant.videoTrackPublications.size===0;const y=(a=A.getActiveDevice(r))!==null&&a!==void 0?a:A.options.videoCaptureDefaults.deviceId;A.options.videoCaptureDefaults.deviceId=v;const C=Array.from(A.localParticipant.videoTrackPublications.values()).filter(B=>B.source===R.Source.Camera);try{p=(yield Promise.all(C.map(B=>{var b;return(b=B.videoTrack)===null||b===void 0?void 0:b.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw A.options.videoCaptureDefaults.deviceId=y,B}}else if(r==="audiooutput"){if(!Pl()&&!A.options.webAudioMix||A.options.webAudioMix&&A.audioContext&&!("setSinkId"in A.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");A.options.webAudioMix&&(i=(c=yield pt.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=A.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=A.getActiveDevice(r))!==null&&l!==void 0?l:A.options.audioOutput.deviceId;A.options.audioOutput.deviceId=i;try{A.options.webAudioMix&&((d=A.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(A.remoteParticipants.values()).map(C=>C.setAudioOutput({deviceId:i})))}catch(C){throw A.options.audioOutput.deviceId=y,C}}return(g||r==="audiooutput")&&(A.localParticipant.activeDeviceMap.set(r,r==="audiooutput"&&((h=A.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),A.emit(L.ActiveDeviceChanged,r,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(V.AttributesChanged,this.onLocalAttributesChanged).on(V.TrackMuted,this.onLocalTrackMuted).on(V.TrackUnmuted,this.onLocalTrackUnmuted).on(V.LocalTrackPublished,this.onLocalTrackPublished).on(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(V.MediaDevicesError,this.onMediaDevicesError).on(V.AudioStreamAcquired,this.startAudio).on(V.ChatMessage,this.onLocalChatMessageSent).on(V.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,t,r){if(this.state===ge.Connecting||this.state===ge.Reconnecting){const u=()=>{this.onTrackAdded(e,t,r),l()},l=()=>{this.off(L.Reconnected,u),this.off(L.Connected,u),this.off(L.Disconnected,l)};this.once(L.Reconnected,u),this.once(L.Connected,u),this.once(L.Disconnected,l);return}if(this.state===ge.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=FF(t.id),A=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),A===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===A);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(A),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,r,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ge.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{i.unpublishTrack(A.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var A,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((A=i.track)===null||A===void 0||A.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(V.AttributesChanged,this.onLocalAttributesChanged).off(V.TrackMuted,this.onLocalTrackMuted).off(V.TrackUnmuted,this.onLocalTrackUnmuted).off(V.LocalTrackPublished,this.onLocalTrackPublished).off(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(V.MediaDevicesError,this.onMediaDevicesError).off(V.AudioStreamAcquired,this.startAudio).off(V.ChatMessage,this.onLocalChatMessageSent).off(V.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),Kt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=navigator.mediaDevices)===null||r===void 0||r.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ge.Disconnected),this.emit(L.Disconnected,t)}}}handleParticipantDisconnected(e,t){var r;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(L.ParticipantDisconnected,t),t.setDisconnected(),(r=this.localParticipant)===null||r===void 0||r.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return S(this,void 0,void 0,function*(){var r;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 A;const s={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sa(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Rx(s,o,sa(e.totalLength)),{identity:t})}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 A;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},o=new ReadableStream({start:a=>{A=a,this.textStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Px(s,o,sa(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const r=this.textStreamControllers.get(e.streamId);r&&e.content.length>0&&r.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return S(this,void 0,void 0,function*(){var e,t;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=A0())!==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(),Ht(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const r=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(L.AudioPlaybackStatusChanged,r))})}createParticipant(e,t){var r;let i;return t?i=pa.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new pa(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(A=>this.log.warn("Could not set audio output: ".concat(A.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const r=this.createParticipant(e,t);return this.remoteParticipants.set(e,r),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(L.ParticipantConnected,r),r.on(V.TrackPublished,i=>{this.emitWhenConnected(L.TrackPublished,i,r)}).on(V.TrackSubscribed,(i,A)=>{i.kind===R.Kind.Audio?(i.on(M.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(M.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===R.Kind.Video&&(i.on(M.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(M.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(L.TrackSubscribed,i,A,r)}).on(V.TrackUnpublished,i=>{this.emit(L.TrackUnpublished,i,r)}).on(V.TrackUnsubscribed,(i,A)=>{this.emit(L.TrackUnsubscribed,i,A,r)}).on(V.TrackMuted,i=>{this.emitWhenConnected(L.TrackMuted,i,r)}).on(V.TrackUnmuted,i=>{this.emitWhenConnected(L.TrackUnmuted,i,r)}).on(V.ParticipantMetadataChanged,i=>{this.emitWhenConnected(L.ParticipantMetadataChanged,i,r)}).on(V.ParticipantNameChanged,i=>{this.emitWhenConnected(L.ParticipantNameChanged,i,r)}).on(V.AttributesChanged,i=>{this.emitWhenConnected(L.ParticipantAttributesChanged,i,r)}).on(V.ConnectionQualityChanged,i=>{this.emitWhenConnected(L.ConnectionQualityChanged,i,r)}).on(V.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(L.ParticipantPermissionsChanged,i,r)}).on(V.TrackSubscriptionStatusChanged,(i,A)=>{this.emitWhenConnected(L.TrackSubscriptionStatusChanged,i,A,r)}).on(V.TrackSubscriptionFailed,(i,A)=>{this.emit(L.TrackSubscriptionFailed,i,r,A)}).on(V.TrackSubscriptionPermissionChanged,(i,A)=>{this.emitWhenConnected(L.TrackSubscriptionPermissionChanged,i,A,r)}).on(V.Active,()=>{this.emitWhenConnected(L.ParticipantActive,r)}),t&&r.updateInfo(t),r}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,i)=>(r.push(...i.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&GF(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=yt.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,an.STATE_MISMATCH))):e=0},qx)}clearConnectionReconcile(){this.connectionReconcileInterval&&yt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(L.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,r]=e;this.emit(t,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(this.state===ge.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,r]);else if(this.state===ge.Connected)return this.emit(e,...r);return!1}simulateParticipants(e){return S(this,void 0,void 0,function*(){var t,r;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),A=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Vo({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ke.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Jr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected),this.emit(L.Connected),this.setAndEmitConnectionState(ge.Connected),i.video){const s=new ud(R.Kind.Video,new Pi({source:ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO,name:"video-dummy"}),new da(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:t0(160*((t=A.aspectRatios[0])!==null&&t!==void 0?t: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(V.LocalTrackPublished,s)}if(i.audio){const s=new ud(R.Kind.Audio,new Pi({source:ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO}),new ua(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ml(),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(V.LocalTrackPublished,s)}for(let s=0;s<A.count-1;s+=1){let o=new Jr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ri.ACTIVE,tracks:[],joinedAt:Ke.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(A.video){const c=t0(160*((r=A.aspectRatios[s%A.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),u=new Pi({source:ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(A.audio){const c=Ml(),u=new Pi({source:ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:on.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(e!==L.ActiveSpeakersChanged&&e!==L.TranscriptionReceived){const A=R0(r).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:A}))}return super.emit(e,...r)}}ji.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function R0(n){return n.map(e=>{if(e)return Array.isArray(e)?R0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var fn;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(fn||(fn={}));class _r extends Un.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=fn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ji(r.roomOptions),this.connectOptions=r.connectOptions,this.options=r}run(e){return S(this,void 0,void 0,function*(){if(this.status!==fn.IDLE)throw Error("check is running already");this.setStatus(fn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==fn.SKIPPED&&this.setStatus(this.isSuccess()?fn.SUCCESS:fn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return S(this,void 0,void 0,function*(){return this.room.state===ge.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==ge.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(fn.SKIPPED)}switchProtocol(e){return S(this,void 0,void 0,function*(){let t=!1,r=!1;if(this.room.on(L.Reconnecting,()=>{t=!0}),this.room.once(L.Reconnected,()=>{r=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(A=>setTimeout(A,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(r)return;yield Ht(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 Jx extends _r{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const e=new od(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],r=new Set;for(let A=0;A<3;A++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(r.has(s))continue;r.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((A,s)=>(A.duration-s.duration)*.5+(A.rtt-s.rtt)*.5);const i=t[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 S(this,void 0,void 0,function*(){var t,r;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const A=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield A.write(c);yield A.close();const l=Date.now(),d=yield(r=this.room.engine.pcManager)===null||r===void 0?void 0:r.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const ld=1e4;class zx extends _r{get description(){return"Connection via UDP vs TCP"}perform(){return S(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const r=this.bestStats;this.appendMessage("upstream bitrate: ".concat((r.bitrateTotal/r.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((r.rttTotal/r.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((r.jitterTotal/r.count*1e3).toFixed(2)," ms")),r.packetsLost>0&&this.appendWarning("packets lost: ".concat((r.packetsLost/r.packetsSent*100).toFixed(2),"%")),r.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((r.qualityLimitationDurations.bandwidth/(ld/1e3)*100).toFixed(2),"%")),r.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((r.qualityLimitationDurations.cpu/(ld/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return S(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const r=t.getContext("2d");if(!r)throw new Error("Could not get canvas context");let i=0;const A=()=>{i=(i+1)%360,r.fillStyle="hsl(".concat(i,", 100%, 50%)"),r.fillRect(0,0,t.width,t.height),requestAnimationFrame(A)};A();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>S(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,ld)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class Xx extends _r{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Kx();if(yield i0(r,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(r),yield new Promise(o=>setTimeout(o,3e3));const A=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!A)throw new Error("Could not get RTCStats");let s=0;if(A.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class Yx extends _r{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Hx();yield this.checkForVideo(r.mediaStreamTrack),t.localParticipant.publishTrack(r),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let A=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(A+=s.packetsSent)}),A===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(A," video packets"))})}checkForVideo(e){return S(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const r=document.createElement("video");r.srcObject=t,r.muted=!0,yield new Promise(i=>{r.onplay=()=>{setTimeout(()=>{var A,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(A=u.width)!==null&&A!==void 0?A:r.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:r.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(r,0,0);const p=h.getImageData(0,0,c.width,c.height).data;let g=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},r.play()}),r.remove()})}}class Zx extends _r{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect();let r=!1,i=!1,A;const s=new Promise(c=>{setTimeout(c,5e3),A=c}),o=()=>{r=!0};t.on(L.SignalReconnecting,o).on(L.Reconnecting,o).on(L.Reconnected,()=>{i=!0,A(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,r){if(!i||t.state!==ge.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 $x extends _r{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var e,t;const r=new ql,i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let A=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,A=!0),c.startsWith("stun:")&&(o=!0);o?s&&!A&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class eQ extends _r{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(L.SignalConnected,()=>{const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,A)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(tQ(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}r&&r(i,A)},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(),ue.info("now the room is connected")}catch(r){throw this.appendWarning("ports need to be open on firewall in order to connect."),r}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function tQ(n){const e=n.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 t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class nQ extends _r{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var e,t,r;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new ql;const A=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(A.serverVersion,".")),((e=A.serverInfo)===null||e===void 0?void 0:e.edition)===Lm.Cloud&&(!((t=A.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((r=A.serverInfo)===null||r===void 0?void 0:r.region)),yield i.close()})}}class Q4 extends Un.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=r}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:fn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==fn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return S(this,void 0,void 0,function*(){const t=this.getNextCheckId(),r=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};r.on("update",i);const A=yield r.run();return r.off("update",i),A})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(nQ)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(eQ)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck($x)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Zx)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Xx)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Yx)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(zx);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Jx)})}}const rQ=/\{[^{}]+\}/g;function iQ(){return Math.random().toString(36).slice(2,11)}function AQ(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:A,headers:s,...o}={...n};e=D0(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=r,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:y,bodySerializer:C=A??oQ,body:B,...b}=l||{};d&&(e=D0(d));let _=typeof i=="function"?i:L0(i);y&&(_=typeof y=="function"?y:L0({...typeof i=="object"?i:{},...y}));const k=B===void 0?void 0:C(B),U=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},I={redirect:"follow",...o,...b,body:k,headers:cQ(U,s,p,g.header)};let P,x,O=new t(aQ(u,{baseUrl:e,params:g,querySerializer:_}),I);for(const F in b)F in O||(O[F]=b[F]);if(a.length){P=iQ(),x=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:_,bodySerializer:C});for(const F of a)if(F&&typeof F=="object"&&typeof F.onRequest=="function"){const D=await F.onRequest({request:O,schemaPath:u,params:g,options:x,id:P});if(D){if(!(D instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");O=D}}}let H=await h(O);if(a.length)for(let F=a.length-1;F>=0;F--){const D=a[F];if(D&&typeof D=="object"&&typeof D.onResponse=="function"){const X=await D.onResponse({request:O,response:H,schemaPath:u,params:g,options:x,id:P});if(X){if(!(X instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");H=X}}}if(H.status===204||H.headers.get("Content-Length")==="0")return H.ok?{data:{},response:H}:{error:{},response:H};if(H.ok)return v==="stream"?{data:H.body,response:H}:{data:await H[v](),response:H};let z=await H.text();try{z=JSON.parse(z)}catch{}return{error:z,response:H}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function fa(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${(t==null?void 0:t.allowReserved)===!0?e:encodeURIComponent(e)}`}function P0(n,e,t){if(!e||typeof e!="object")return"";const r=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)r.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=r.join(",");switch(t.style){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${n}[${s}]`:s;r.push(fa(o,e[s],t))}const A=r.join(i);return t.style==="label"||t.style==="matrix"?`${i}${A}`:A}function O0(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const A={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(A);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return`${n}=${s}`}}const r={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const A of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?A:encodeURIComponent(A)):i.push(fa(n,A,t));return t.style==="label"||t.style==="matrix"?`${r}${i.join(r)}`:i.join(r)}function L0(n){return function(t){const r=[];if(t&&typeof t=="object")for(const i in t){const A=t[i];if(A!=null){if(Array.isArray(A)){if(A.length===0)continue;r.push(O0(i,A,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof A=="object"){r.push(P0(i,A,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}r.push(fa(i,A,n))}}return r.join("&")}}function sQ(n,e){let t=n;for(const r of n.match(rQ)??[]){let i=r.substring(1,r.length-1),A=!1,s="simple";if(i.endsWith("*")&&(A=!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 o=e[i];if(Array.isArray(o)){t=t.replace(r,O0(i,o,{style:s,explode:A}));continue}if(typeof o=="object"){t=t.replace(r,P0(i,o,{style:s,explode:A}));continue}if(s==="matrix"){t=t.replace(r,`;${fa(i,o)}`);continue}t=t.replace(r,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function oQ(n){return n instanceof FormData?n:JSON.stringify(n)}function aQ(n,e){var i;let t=`${e.baseUrl}${n}`;(i=e.params)!=null&&i.path&&(t=sQ(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function cQ(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const r=t instanceof Headers?t.entries():Object.entries(t);for(const[i,A]of r)if(A===null)e.delete(i);else if(Array.isArray(A))for(const s of A)e.append(i,s);else A!==void 0&&e.set(i,A)}return e}function D0(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const M0="Onboardee-Session-Token",N0="OnboardeeSessionToken";class H0{constructor(e){this.client=AQ({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const r=window.localStorage.getItem(N0);r&&t.headers.set(M0,r)}return t},onResponse({response:t}){const r=t.headers.get(M0);return r&&window.localStorage&&window.localStorage.setItem(N0,r),t}})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}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,t={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:t})}async clientStartSession(e,t){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:t})}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,t){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:t})}async listPlans(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}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,t,r,i){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r},...i&&{course_id:i}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,t){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:t})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,t){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:t})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,t){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async searchProductKnowledgeBlocks(e,t,r){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...r&&{limit:r.toString()}}}})}async updateProductKnowledgeBlock(e,t,r){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}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 getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getPlanAnalytics(e,t,r){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r}}}})}async replacePlan(e,t){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:t})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}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,t){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updatePlanKnowledgeBlock(e,t,r){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deletePlanKnowledgeBlock(e,t){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,t){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,t){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,t){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:t})}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,t){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async createRevisionKnowledgeBlock(e,t){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updateRevisionKnowledgeBlock(e,t,r){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e,t){const r={token:e};return t!=null&&t.productId&&(r.product_id=t.productId),t!=null&&t.startDate&&(r.start_date=t.startDate),t!=null&&t.endDate&&(r.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:r}})}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,t){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:t}}})}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,t){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:t})}async listUserSessions(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),e!=null&&e.courseName&&(t.course_name=e.courseName),e!=null&&e.userName&&(t.user_name=e.userName),e!=null&&e.company&&(t.company=e.company),e!=null&&e.email&&(t.email=e.email),e!=null&&e.sortBy&&(t.sort_by=e.sortBy),e!=null&&e.sortOrder&&(t.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(t).length>0?{query:t}:void 0})}async listUserSessionsAggregate(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(t).length>0?{query:t}:void 0})}async getJoinToken(e,{clientType:t,user:r}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...r&&{user:encodeURIComponent(r)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}async getPlanSDK(e){return await this.client.GET("/api/plans/{uuid}/sdk",{params:{path:{uuid:e}}})}getClient(){return this.client}}const K0="https://app.coragents.ai";class ga extends qc{constructor(e,t,r,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.startedAt=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=t,this.clientType=r,this.api=i.api||new H0({baseUrl:K0}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(A=>new ji(A)),this.captureScreen=i.captureScreen||null}async start(){this.planId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const t=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(t!=null&&t.url)||!(t!=null&&t.token)||!(t!=null&&t.room)||!(t!=null&&t.session_uuid))throw new Error("Invalid room info");this.sessionUuid=t==null?void 0:t.session_uuid,this.roomId=t==null?void 0:t.room,this.joinToken=t==null?void 0:t.token,this.roomUrl=t==null?void 0:t.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("connected"),this.planId,this.sessionUuid}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(L.Disconnected,r=>{if(!this.room)return;let i=null;switch(r){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(L.TrackSubscribed,r=>{r.kind==="audio"&&(r.attach(),r.source===R.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(r.mediaStream)))}),this.room.on(L.LocalTrackPublished,r=>{r.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(r.audioTrack.mediaStream))}),this.room.on(L.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"])return;const i=r["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(L.DataReceived,async r=>{try{const i=new TextDecoder().decode(r),A=JSON.parse(i);switch(A.status||A.request||A.type){case"course_progress":typeof A.current_step=="number"&&typeof A.total_steps=="number"&&Array.isArray(A.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,A.current_step),totalSteps:Math.max(1,A.total_steps),stepNames:A.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;case"shutdown":this.shutdown("server-sent");break;default:console.warn("[obi] unknown data received",A)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async r=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async r=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,A=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||A)return console.error("[obi] error capturing screen",{error:A}),"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 r=0;r<9&&!(this.room.state===ge.Connected&&this.room.remoteParticipants.size>=1);r++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===ge.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),t){let r=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(r=!0);r?this.speakingState="speaking":this.speakingState="listening"}}async continue(){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(t){console.error("[obi] error checking microphone permission:",t)}return e?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid,this.speakingStateChanged("thinking");let e=null,t=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){r=r,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){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(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleMuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleUnmuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){this.sessionUuid,e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),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,startedAt:this.startedAt})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const r=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const A=[],s=50,o=5e3,a=8,c=Math.pow(o/s,1/a);for(let u=0;u<a;u++){const l=s*Math.pow(c,u),d=s*Math.pow(c,u+1),h=Math.floor(l/r),f=Math.floor(d/r),p=Math.min(f,i.length),g=Math.min(h,p);if(g<p){const v=i.slice(g,p).reduce((y,C)=>y+C,0)/(p-g)/255;A.push(v)}else A.push(0)}return A}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,r,i={}){const A=JSON.parse(e),s=new ga(t,A.planId,r,i);return s.state=A.state,s.speakingState=A.speakingState,s.identity=A.identity||null,s.isPaused=A.isPaused||!1,s.sessionUuid=A.sessionUuid||null,s.roomId=A.roomId||null,s.joinToken=A.joinToken||null,s.roomUrl=A.roomUrl||null,s.startedAt=A.startedAt||null,s}speakingStateChanged(e){this.speakingState;const t=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,t)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const t=new AudioContext,r=t.createAnalyser();return t.createMediaStreamSource(e).connect(r),r.fftSize=2048,r.smoothingTimeConstant=.6,r}}class ma extends qc{constructor(e,t,r={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=t,this.api=r.api||new H0({baseUrl:r.apiBaseUrl||K0}),this.sessionFactory=r.sessionFactory||((i,A,s,o)=>new ga(i,A,s,o)),this.captureScreen=r.captureScreen||null}async initialise(e={}){var t,r,i,A,s;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const o=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=o.data)==null?void 0:t.product)||null,this.plans=((r=o.data)==null?void 0:r.onboarding_plans)||[],this.selectedPlan=((i=o.data)==null?void 0:i.selected_plan)||null,this.planIsCompleted=((A=o.data)==null?void 0:A.plan_is_completed)||[],this.showWidget=((s=o.data)==null?void 0:s.show_widget)||!1,e.planUuid){let a=null;try{const c=await this.api.getPlanSDK(e.planUuid);if(c.error)throw new Error(`Plan not found: ${c.error}`);c.data&&(a=c.data)}catch(c){try{const u=await this.api.getSessionPlan(e.planUuid);if(u.error)throw new Error(`Session plan not found: ${u.error}`);u.data&&(a=u.data)}catch(u){console.error("[obi] error getting plan via both endpoints",{planErr:c,sessionErr:u})}}a?(this.selectedPlan=a,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(o){throw this.error=o instanceof Error?o:new Error(String(o)),this.setState("error"),o}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}async startSession(e,t){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(t),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,r;return this.state,(t=this.session)==null||t.state,(r=this.session)==null||r.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.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",t=>{var r,i,A;if((r=this.session)!=null&&r.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const s=this.plans.findIndex(o=>{var a;return o.uuid===((a=this.selectedPlan)==null?void 0:a.uuid)});s!==-1&&(this.planIsCompleted[s]=!0)}(A=(i=this.session)==null?void 0:i.removeAllListeners)==null||A.call(i),this.session=null,this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",t)}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session-stopped",{sessionUuid:this.session.sessionUuid}),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(),serialisedAt:new Date().toISOString()})}static deserialise(e,t,r,i={}){const A=JSON.parse(e);if(A.serialisedAt){const o=new Date(A.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)throw new Error("Client was serialised more than 20 seconds ago, assuming it's dead.")}else throw new Error("Client was not serialised, assuming it's dead.");const s=new ma(t,r,i);return s.state=A.state,s.identity=A.identity||null,s.product=A.product||null,s.plans=A.plans||[],s.selectedPlan=A.selectedPlan||null,s.selectedPlanUuid=A.selectedPlanUuid||null,s.showWidget=A.showWidget||!1,A.session&&(s.session=ga.deserialise(A.session,t,r,{api:s.api})),s}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var r,i,A;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(r=this.selectedPlan)==null?void 0:r.uuid,productId:(i=this.product)==null?void 0:i.uuid,sessionId:(A=this.session)==null?void 0:A.sessionUuid})}}var va,te,V0,ti,G0,j0,W0,q0,dd,hd,pd,J0,ZA={},z0=[],uQ=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,$A=Array.isArray;function Wn(n,e){for(var t in e)n[t]=e[t];return n}function fd(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function gd(n,e,t){var r,i,A,s={};for(A in e)A=="key"?r=e[A]:A=="ref"?i=e[A]:s[A]=e[A];if(arguments.length>2&&(s.children=arguments.length>3?va.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(A in n.defaultProps)s[A]==null&&(s[A]=n.defaultProps[A]);return ya(n,s,r,i,null)}function ya(n,e,t,r,i){var A={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++V0,__i:-1,__u:0};return i==null&&te.vnode!=null&&te.vnode(A),A}function St(n){return n.children}function qn(n,e){this.props=n,this.context=e}function Wi(n,e){if(e==null)return n.__?Wi(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?Wi(n):null}function X0(n){var e,t;if((n=n.__)!=null&&n.__c!=null){for(n.__e=n.__c.base=null,e=0;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null){n.__e=n.__c.base=t.__e;break}return X0(n)}}function md(n){(!n.__d&&(n.__d=!0)&&ti.push(n)&&!wa.__r++||G0!=te.debounceRendering)&&((G0=te.debounceRendering)||j0)(wa)}function wa(){for(var n,e,t,r,i,A,s,o=1;ti.length;)ti.length>o&&ti.sort(W0),n=ti.shift(),o=ti.length,n.__d&&(t=void 0,i=(r=(e=n).__v).__e,A=[],s=[],e.__P&&((t=Wn({},r)).__v=r.__v+1,te.vnode&&te.vnode(t),vd(e.__P,t,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,A,i??Wi(r),!!(32&r.__u),s),t.__v=r.__v,t.__.__k[t.__i]=t,ty(A,t,s),t.__e!=i&&X0(t)));wa.__r=0}function Y0(n,e,t,r,i,A,s,o,a,c,u){var l,d,h,f,p,g,v=r&&r.__k||z0,y=e.length;for(a=lQ(t,e,v,a,y),l=0;l<y;l++)(h=t.__k[l])!=null&&(d=h.__i==-1?ZA:v[h.__i]||ZA,h.__i=l,g=vd(n,h,d,i,A,s,o,a,c,u),f=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&yd(d.ref,null,h),u.push(h.ref,h.__c||f,h)),p==null&&f!=null&&(p=f),4&h.__u||d.__k===h.__k?a=Z0(h,a,n):typeof h.type=="function"&&g!==void 0?a=g:f&&(a=f.nextSibling),h.__u&=-7);return t.__e=p,a}function lQ(n,e,t,r,i){var A,s,o,a,c,u=t.length,l=u,d=0;for(n.__k=new Array(i),A=0;A<i;A++)(s=e[A])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=A+d,(s=n.__k[A]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?ya(null,s,null,null,null):$A(s)?ya(St,{children:s},null,null,null):s.constructor==null&&s.__b>0?ya(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=n,s.__b=n.__b+1,o=null,(c=s.__i=dQ(s,t,a,l))!=-1&&(l--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(i>u?d--:i<u&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=a&&(c==a-1?d--:c==a+1?d++:(c>a?d--:d++,s.__u|=4))):n.__k[A]=null;if(l)for(A=0;A<u;A++)(o=t[A])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Wi(o)),ry(o,o));return r}function Z0(n,e,t){var r,i;if(typeof n.type=="function"){for(r=n.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=n,e=Z0(r[i],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Wi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ba(n,e){return e=e||[],n==null||typeof n=="boolean"||($A(n)?n.some(function(t){ba(t,e)}):e.push(n)),e}function dQ(n,e,t,r){var i,A,s=n.key,o=n.type,a=e[t];if(a===null&&n.key==null||a&&s==a.key&&o==a.type&&!(2&a.__u))return t;if(r>(a!=null&&!(2&a.__u)?1:0))for(i=t-1,A=t+1;i>=0||A<e.length;){if(i>=0){if((a=e[i])&&!(2&a.__u)&&s==a.key&&o==a.type)return i;i--}if(A<e.length){if((a=e[A])&&!(2&a.__u)&&s==a.key&&o==a.type)return A;A++}}return-1}function $0(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||uQ.test(e)?t:t+"px"}function Ca(n,e,t,r,i){var A;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||$0(n.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||$0(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")A=e!=(e=e.replace(q0,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+A]=t,t?r?t.u=r.u:(t.u=dd,n.addEventListener(e,A?pd:hd,A)):n.removeEventListener(e,A?pd:hd,A);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 n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function ey(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=dd++;else if(e.t<t.u)return;return t(te.event?te.event(e):e)}}}function vd(n,e,t,r,i,A,s,o,a,c){var u,l,d,h,f,p,g,v,y,C,B,b,_,k,U,I,P,x=e.type;if(e.constructor!=null)return null;128&t.__u&&(a=!!(32&t.__u),A=[o=e.__e=t.__e]),(u=te.__b)&&u(e);e:if(typeof x=="function")try{if(v=e.props,y="prototype"in x&&x.prototype.render,C=(u=x.contextType)&&r[u.__c],B=u?C?C.props.value:u.__:r,t.__c?g=(l=e.__c=t.__c).__=l.__E:(y?e.__c=l=new x(v,B):(e.__c=l=new qn(v,B),l.constructor=x,l.render=pQ),C&&C.sub(l),l.props=v,l.state||(l.state={}),l.context=B,l.__n=r,d=l.__d=!0,l.__h=[],l._sb=[]),y&&l.__s==null&&(l.__s=l.state),y&&x.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=Wn({},l.__s)),Wn(l.__s,x.getDerivedStateFromProps(v,l.__s))),h=l.props,f=l.state,l.__v=e,d)y&&x.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),y&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(y&&x.getDerivedStateFromProps==null&&v!==h&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(v,B),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(v,l.__s,B)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(l.props=v,l.state=l.__s,l.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(O){O&&(O.__=e)}),b=0;b<l._sb.length;b++)l.__h.push(l._sb[b]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(v,l.__s,B),y&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(h,f,p)})}if(l.context=B,l.props=v,l.__P=n,l.__e=!1,_=te.__r,k=0,y){for(l.state=l.__s,l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),U=0;U<l._sb.length;U++)l.__h.push(l._sb[U]);l._sb=[]}else do l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++k<25);l.state=l.__s,l.getChildContext!=null&&(r=Wn(Wn({},r),l.getChildContext())),y&&!d&&l.getSnapshotBeforeUpdate!=null&&(p=l.getSnapshotBeforeUpdate(h,f)),I=u,u!=null&&u.type===St&&u.key==null&&(I=ny(u.props.children)),o=Y0(n,$A(I)?I:[I],e,t,r,i,A,s,o,a,c),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),g&&(l.__E=l.__=null)}catch(O){if(e.__v=null,a||A!=null)if(O.then){for(e.__u|=a?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;A[A.indexOf(o)]=null,e.__e=o}else for(P=A.length;P--;)fd(A[P]);else e.__e=t.__e,e.__k=t.__k;te.__e(O,e,t)}else A==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=hQ(t.__e,e,t,r,i,A,s,a,c);return(u=te.diffed)&&u(e),128&e.__u?void 0:o}function ty(n,e,t){for(var r=0;r<t.length;r++)yd(t[r],t[++r],t[++r]);te.__c&&te.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(A){A.call(i)})}catch(A){te.__e(A,i.__v)}})}function ny(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:$A(n)?n.map(ny):Wn({},n)}function hQ(n,e,t,r,i,A,s,o,a){var c,u,l,d,h,f,p,g=t.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),A!=null){for(c=0;c<A.length;c++)if((h=A[c])&&"setAttribute"in h==!!y&&(y?h.localName==y:h.nodeType==3)){n=h,A[c]=null;break}}if(n==null){if(y==null)return document.createTextNode(v);n=document.createElementNS(i,y,v.is&&v),o&&(te.__m&&te.__m(e,A),o=!1),A=null}if(y==null)g===v||o&&n.data==v||(n.data=v);else{if(A=A&&va.call(n.childNodes),g=t.props||ZA,!o&&A!=null)for(g={},c=0;c<n.attributes.length;c++)g[(h=n.attributes[c]).name]=h.value;for(c in g)if(h=g[c],c!="children"){if(c=="dangerouslySetInnerHTML")l=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;Ca(n,c,null,h,i)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?u=h:c=="value"?f=h:c=="checked"?p=h:o&&typeof h!="function"||g[c]===h||Ca(n,c,h,g[c],i);if(u)o||l&&(u.__html==l.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(l&&(n.innerHTML=""),Y0(e.type=="template"?n.content:n,$A(d)?d:[d],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,A,s,A?A[0]:t.__k&&Wi(t,0),o,a),A!=null)for(c=A.length;c--;)fd(A[c]);o||(c="value",y=="progress"&&f==null?n.removeAttribute("value"):f!=null&&(f!==n[c]||y=="progress"&&!f||y=="option"&&f!=g[c])&&Ca(n,c,f,g[c],i),c="checked",p!=null&&p!=n[c]&&Ca(n,c,p,g[c],i))}return n}function yd(n,e,t){try{if(typeof n=="function"){var r=typeof n.__u=="function";r&&n.__u(),r&&e==null||(n.__u=n(e))}else n.current=e}catch(i){te.__e(i,t)}}function ry(n,e,t){var r,i;if(te.unmount&&te.unmount(n),(r=n.ref)&&(r.current&&r.current!=n.__e||yd(r,null,e)),(r=n.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(A){te.__e(A,e)}r.base=r.__P=null}if(r=n.__k)for(i=0;i<r.length;i++)r[i]&&ry(r[i],e,t||typeof n.type!="function");t||fd(n.__e),n.__c=n.__=n.__e=void 0}function pQ(n,e,t){return this.constructor(n,t)}function fQ(n,e,t){var r,i,A,s;e==document&&(e=document.documentElement),te.__&&te.__(n,e),i=(r=typeof t=="function")?null:t&&t.__k||e.__k,A=[],s=[],vd(e,n=(!r&&t||e).__k=gd(St,null,[n]),i||ZA,ZA,e.namespaceURI,!r&&t?[t]:i?null:e.firstChild?va.call(e.childNodes):null,A,!r&&t?t:i?i.__e:e.firstChild,r,s),ty(A,n,s)}function iy(n){function e(t){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(A){this.props.value!=A.value&&r.forEach(function(s){s.__e=!0,md(s)})},this.sub=function(A){r.add(A);var s=A.componentWillUnmount;A.componentWillUnmount=function(){r&&r.delete(A),s&&s.call(A)}}),t.children}return e.__c="__cC"+J0++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}va=z0.slice,te={__e:function(n,e,t,r){for(var i,A,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((A=i.constructor)&&A.getDerivedStateFromError!=null&&(i.setState(A.getDerivedStateFromError(n)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,r||{}),s=i.__d),s)return i.__E=i}catch(o){n=o}throw n}},V0=0,qn.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Wn({},this.state),typeof n=="function"&&(n=n(Wn({},t),this.props)),n&&Wn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),md(this))},qn.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),md(this))},qn.prototype.render=St,ti=[],j0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,W0=function(n,e){return n.__v.__b-e.__v.__b},wa.__r=0,q0=/(PointerCapture)$|Capture$/i,dd=0,hd=ey(!1),pd=ey(!0),J0=0;var gQ=0;function w(n,e,t,r,i,A){e||(e={});var s,o,a=e;if("ref"in a)for(o in a={},e)o=="ref"?s=e[o]:a[o]=e[o];var c={type:n,props:a,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--gQ,__i:-1,__u:0,__source:i,__self:A};if(typeof n=="function"&&(s=n.defaultProps))for(o in s)a[o]===void 0&&(a[o]=s[o]);return te.vnode&&te.vnode(c),c}var ni,Ve,wd,Ay,es=0,sy=[],rt=te,oy=rt.__b,ay=rt.__r,cy=rt.diffed,uy=rt.__c,ly=rt.unmount,dy=rt.__;function ts(n,e){rt.__h&&rt.__h(Ve,n,es||e),es=0;var t=Ve.__H||(Ve.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function he(n){return es=1,mQ(fy,n)}function mQ(n,e,t){var r=ts(ni++,2);if(r.t=n,!r.__c&&(r.__=[t?t(e):fy(void 0,e),function(o){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,o);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var i=function(o,a,c){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(d){return!!d.__c});if(u.every(function(d){return!d.__N}))return!A||A.call(this,o,a,c);var l=r.__c.props!==o;return u.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(l=!0)}}),A&&A.call(this,o,a,c)||l};Ve.__f=!0;var A=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(o,a,c){if(this.__e){var u=A;A=void 0,i(o,a,c),A=u}s&&s.call(this,o,a,c)},Ve.shouldComponentUpdate=i}return r.__N||r.__}function Vt(n,e){var t=ts(ni++,3);!rt.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__H.__h.push(t))}function Ba(n,e){var t=ts(ni++,4);!rt.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__h.push(t))}function In(n){return es=5,bd(function(){return{current:n}},[])}function bd(n,e){var t=ts(ni++,7);return Bd(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function vQ(n,e){return es=8,bd(function(){return n},e)}function hy(n){var e=Ve.context[n.__c],t=ts(ni++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ve)),e.props.value):n.__}function yQ(){for(var n;n=sy.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(_a),n.__H.__h.forEach(Cd),n.__H.__h=[]}catch(e){n.__H.__h=[],rt.__e(e,n.__v)}}rt.__b=function(n){Ve=null,oy&&oy(n)},rt.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),dy&&dy(n,e)},rt.__r=function(n){ay&&ay(n),ni=0;var e=(Ve=n.__c).__H;e&&(wd===Ve?(e.__h=[],Ve.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(_a),e.__h.forEach(Cd),e.__h=[],ni=0)),wd=Ve},rt.diffed=function(n){cy&&cy(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(sy.push(e)!==1&&Ay===rt.requestAnimationFrame||((Ay=rt.requestAnimationFrame)||wQ)(yQ)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),wd=Ve=null},rt.__c=function(n,e){e.some(function(t){try{t.__h.forEach(_a),t.__h=t.__h.filter(function(r){return!r.__||Cd(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],rt.__e(r,t.__v)}}),uy&&uy(n,e)},rt.unmount=function(n){ly&&ly(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{_a(r)}catch(i){e=i}}),t.__H=void 0,e&&rt.__e(e,t.__v))};var py=typeof requestAnimationFrame=="function";function wQ(n){var e,t=function(){clearTimeout(r),py&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);py&&(e=requestAnimationFrame(t))}function _a(n){var e=Ve,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ve=e}function Cd(n){var e=Ve;n.__c=n.__(),Ve=e}function Bd(n,e){return!n||n.length!==e.length||e.some(function(t,r){return t!==n[r]})}function fy(n,e){return typeof e=="function"?e(n):e}function bQ({size:n=24,color:e="#000"}){return w("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,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:[w("path",{d:"M18 6 6 18"}),w("path",{d:"m6 6 12 12"})]})}function gy({onClose:n}){return w("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:w(bQ,{})})}function my({open:n=!1,children:e,onClose:t,size:r="medium"}){const i=In(null),A=In(null);Vt(()=>{const c=i.current;c&&(n&&!c.open?c.showModal():!n&&c.open&&(A.current="programmatic",c.close()))},[n]);const s=c=>{const u=i.current;c.target===u&&(A.current="user-initiated",u==null||u.close())},o=c=>{c.preventDefault(),A.current||(A.current="user-initiated");const u=A.current;A.current=null,t==null||t(u)},a=()=>{var c;A.current="user-initiated",(c=i.current)==null||c.close()};return Vt(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",o),()=>{c.removeEventListener("click",s),c.removeEventListener("close",o)}},[t]),w("dialog",{ref:i,className:`modal-${r}`,children:[w(gy,{onClose:a}),w("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function _d(n){const{children:e,className:t="",...r}=n;return w("div",{className:`${t} obi-panel`,...r,children:e})}function Sa({className:n="",isActive:e=!1,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),w("div",{className:o,onMouseEnter:i,onMouseLeave:A,children:w("div",{className:`obi-pill pill ${n}`,onClick:r,children:s})})}function CQ({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return w("div",{className:a,...o,children:w("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function BQ({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return w("div",{className:a,...o,children:w("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function ri({type:n,size:e=24}){return w("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:_Q(n)})}function _Q(n){switch(n){case"pause":return w(St,{children:[w("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),w("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return w(St,{children:w("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 w(St,{children:[w("path",{d:"M18 6 6 18"}),w("path",{d:"m6 6 12 12"})]});case"message":return w(St,{children:w("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 w(St,{children:[w("path",{d:"m14 10 7-7"}),w("path",{d:"M20 10h-6V4"}),w("path",{d:"m3 21 7-7"}),w("path",{d:"M4 14h6v6"})]});case"voice":return w(St,{children:[w("path",{d:"M2 10v3"}),w("path",{d:"M6 6v11"}),w("path",{d:"M10 3v18"}),w("path",{d:"M14 8v7"}),w("path",{d:"M18 5v13"}),w("path",{d:"M22 10v3"})]});case"open":return w(St,{children:[w("path",{d:"M12 7v14"}),w("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 Sd=iy(null);function SQ({children:n}){const e=hy(Sd);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:r,setIsOpen:i,setAnimating:A,targetRef:s,trigger:o,onChange:a,delayMs:c}=e,u=In(null),l=vy(s,A),[d,h]=he(!1);Vt(()=>{t!==void 0&&t!==d&&(t?p():g()),h(t)},[t]),Vt(()=>()=>{u.current&&clearTimeout(u.current)},[]);function f(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){f(),c>0?u.current=setTimeout(()=>{a==null||a(!0),i(!0),u.current=null},c):(a==null||a(!0),i(!0))}function g(){f(),a==null||a(!1),i(!1)}const v=()=>{o==="click"&&(r?g():p())};function y(){o==="hover"&&p()}function C(){o==="hover"&&g()}return w("div",{ref:l,class:"target",onClick:v,onMouseEnter:y,onMouseLeave:C,children:n})}function kQ({children:n}){const e=hy(Sd);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:r,setAnimating:i,targetRef:A,contentRef:s}=e,o=vy(s,i);return Ba(()=>{if(t&&!r&&A.current&&s.current){const a=s.current;if(!a)return;const c=A.current;if(!c)return;const u=a.getBoundingClientRect(),l=c.getBoundingClientRect(),d=l.right-l.left;a.style.top=`${u.top-u.bottom-(8+e.offset)}px`,a.style.left=`${-(u.right-u.left-d)/2}px`}},[t,r]),t?w("div",{ref:o,class:"content",style:{opacity:r?0:1},children:n}):null}function Gt({trigger:n="click",open:e,onChange:t,children:r,delayMs:i=0,offset:A=0,className:s=""}){const[o,a]=he(!1),[c,u]=he(!1),l=In(null),d=In(null),h={controlledOpen:e,isOpen:o,setIsOpen:a,animating:c,setAnimating:u,targetRef:l,contentRef:d,trigger:n,onChange:t,delayMs:i,offset:A};return w(Sd.Provider,{value:h,children:w("div",{class:`obi-popout ${s}`,children:r})})}Gt.Target=SQ,Gt.Content=kQ;function vy(n,e){const t=In(null),r=In(null),i=In(!0),A=vQ(s=>{if(n.current=s,!s){r.current&&(r.current.disconnect(),r.current=null),i.current=!0;return}function o(){if(i.current){i.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}r.current=new ResizeObserver(o),r.current.observe(s,{box:"border-box"})},[]);return Vt(()=>()=>{r.current&&(r.current.disconnect(),r.current=null)},[]),A}function gn({className:n,onClick:e,type:t,disabled:r,title:i}){const A={cancel:w(ri,{type:"close",size:16}),pause:w(ri,{type:"pause",size:16}),play:w(ri,{type:"play",size:16}),message:w(ri,{type:"message",size:16}),minimize:w(ri,{type:"minimize",size:16}),voice:w(ri,{type:"voice",size:16}),open:w(ri,{type:"open",size:16})}[t],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=w("button",{class:`obi-button obi-round-button ${s} ${n}`,onClick:r?void 0:e,disabled:r,children:A});return i?w(Gt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[w(Gt.Target,{children:o}),w(Gt.Content,{children:w("div",{className:"obi-round-button-title",children:i})})]}):o}const yy=8,ka=8,EQ=50,UQ=.7,qi=3;function wy({getBands:n,color:e="white"}){const t=In(null);return Vt(()=>{if(!n)return;const r=setInterval(()=>{try{const i=n();if(!t.current)return;const A=t.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,ka).map(o=>{const a=Math.abs(o);return Math.min(a/UQ*yy,yy)||qi}):Array(ka).fill(qi);for(;s.length<ka;)s.push(qi);s.forEach((o,a)=>{if(o<qi&&(o=qi),A[a]){const c=o*2;A[a].style.height=`${c}px`,A[a].style.display=o>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},EQ);return()=>{clearInterval(r)}},[n]),w("div",{className:"obi-equaliser",ref:t,children:Array.from({length:ka},(r,i)=>w("div",{className:"column",children:w("div",{className:"bar",style:{height:`${qi}px`,backgroundColor:e,display:"block"}})},i))})}function Sr({className:n,children:e,onClick:t}){return t?w("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):w("div",{class:`obi-message ${n}`,children:e})}const TQ=8;function by({color:n="white"}){return w("div",{className:"obi-loading-dots",children:Array.from({length:TQ},(e,t)=>w("div",{className:"column",children:[w("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),w("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function IQ({onContinue:n,onWrapUp:e}){return w(_d,{className:"obi-exit-survey",children:w(xQ,{onContinue:n,onWrapUp:()=>{e()}})})}function FQ({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[r,i]=he("reason"),A=s=>{s==="other"?(n(),i("other-reason")):e(s)};return w(_d,{className:`obi-exit-survey ${r==="reason"?"obi-exit-survey-reason":""}`,children:r==="reason"?w(QQ,{onReasonSelect:A}):w(RQ,{onReasonSelect:A,onClose:t})})}function xQ({onContinue:n,onWrapUp:e}){return w("div",{className:"obi-exit-survey-container",children:[w("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),w("div",{className:"obi-exit-survey-options",children:[w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),w("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 QQ({onReasonSelect:n}){return w("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[w("div",{className:"obi-exit-survey-header",children:w("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),w("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("cant-talk"),type:"button",children:"Can't talk right now"}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function RQ({onReasonSelect:n,onClose:e}){const[t,r]=he("");return w("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[w("div",{className:"obi-exit-survey-header",children:[w(gy,{onClose:e}),w("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),w("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[w("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:i=>r(i.target.value)}),w("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>n("other-feedback",t),type:"button",children:"Send feedback"})]})]})}function PQ(n,e){for(var t in e)n[t]=e[t];return n}function Cy(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function By(n,e){this.props=n,this.context=e}(By.prototype=new qn).isPureReactComponent=!0,By.prototype.shouldComponentUpdate=function(n,e){return Cy(this.props,n)||Cy(this.state,e)};var _y=te.__b;te.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),_y&&_y(n)};var OQ=te.__e;te.__e=function(n,e,t,r){if(n.then){for(var i,A=e;A=A.__;)if((i=A.__c)&&i.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),i.__c(n,e)}OQ(n,e,t,r)};var Sy=te.unmount;function ky(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=PQ({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return ky(r,e,t)})),n}function Ey(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Ey(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function kd(){this.__u=0,this.o=null,this.__b=null}function Uy(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Ea(){this.i=null,this.l=null}te.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Sy&&Sy(n)},(kd.prototype=new qn).__c=function(n,e){var t=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(t);var i=Uy(r.__v),A=!1,s=function(){A||(A=!0,t.__R=null,i?i(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Ey(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},kd.prototype.componentWillUnmount=function(){this.o=[]},kd.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=ky(this.__b,t,r.__O=r.__P)}this.__b=null}var i=e.__a&&gd(St,null,n.fallback);return i&&(i.__u&=-33),[gd(St,null,e.__a?null:n.children),i]};var Ty=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;n.i=t=t[2]}};(Ea.prototype=new qn).__a=function(n){var e=this,t=Uy(e.__v),r=e.l.get(n);return r[0]++,function(i){var A=function(){e.props.revealOrder?(r.push(i),Ty(e,n,r)):i()};t?t(A):A()}},Ea.prototype.render=function(n){this.i=null,this.l=new Map;var e=ba(n.children);n.revealOrder&&n.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return n.children},Ea.prototype.componentDidUpdate=Ea.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Ty(n,t,e)})};var LQ=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,DQ=/^(?: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]/,MQ=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NQ=/[A-Z0-9]/g,HQ=typeof document<"u",KQ=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};qn.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(qn.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var Iy=te.event;function VQ(){}function GQ(){return this.cancelBubble}function jQ(){return this.defaultPrevented}te.event=function(n){return Iy&&(n=Iy(n)),n.persist=VQ,n.isPropagationStopped=GQ,n.isDefaultPrevented=jQ,n.nativeEvent=n};var WQ={enumerable:!1,configurable:!0,get:function(){return this.class}},Fy=te.vnode;te.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,r=e.type,i={},A=r.indexOf("-")===-1;for(var s in t){var o=t[s];if(!(s==="value"&&"defaultValue"in t&&o==null||HQ&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in t&&t.value==null?s="value":s==="download"&&o===!0?o="":a==="translate"&&o==="no"?o=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||KQ(t.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":MQ.test(s)&&(s=a):a=s="oninput":A&&DQ.test(s)?s=s.replace(NQ,"-$&").toLowerCase():o===null&&(o=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=o}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=ba(t.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ba(t.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",WQ)):(t.className&&!t.class||t.class&&t.className)&&(i.class=i.className=t.className),e.props=i}(n),n.$$typeof=LQ,Fy&&Fy(n)};var xy=te.__r;te.__r=function(n){xy&&xy(n),n.__c};var Qy=te.diffed;te.diffed=function(n){Qy&&Qy(n);var e=n.props,t=n.__e;t!=null&&n.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value)};function qQ(n){const{placeholder:e="Type your message...",value:t,defaultValue:r,onChange:i,onSend:A,onCancel:s,onExpand:o,isLoading:a=!1,disabled:c=!1,maxLength:u=500,children:l}=n,[d,h]=he(t||r||""),[f,p]=he((t||r||"").length>24),g=In(null);Ba(()=>{f&&(o==null||o(!0))},[]);const v=t!==void 0?t:d,y=b=>{const _=b.currentTarget.value;t===void 0&&h(_),i==null||i(_)},C=b=>{b.key==="Escape"&&(h(t||r||""),p(!1),s==null||s()),b.key==="Enter"&&!b.shiftKey&&v.trim()&&(b.preventDefault(),h(t||r||""),p(!1),B()),(v||"").length>=24&&!f&&(p(!0),o==null||o(!0))};Vt(()=>{g.current&&g.current.focus()},[g.current]);const B=()=>{!v.trim()||a||c||(A==null||A(v.trim()),t===void 0&&h(""))};return w("div",{className:`obi-message-input ${f?"expanded":""}`,children:[w("div",{className:"container",children:w("textarea",{ref:g,className:"field",placeholder:e,value:v,onInput:y,onKeyDown:C,disabled:c||a,maxLength:u,rows:1})}),w("div",{className:"button-container",children:[f&&w("div",{children:l}),w("button",{className:"obi-button send",onClick:B,disabled:!v.trim()||a||c,type:"button",children:w("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:w("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 JQ(n){const{currentStep:e,totalSteps:t,stepNames:r,className:i}=n,A=Array.from({length:t},(a,c)=>({isCompleted:c<e,stepNumber:c+1})),s=r[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${s}`;return w("div",{class:`obi-course-progress ${i||""}`,children:[w("div",{class:"obi-course-progress-steps",children:A.map((a,c)=>w("div",{class:"obi-course-progress-container",children:w("div",{class:`obi-course-progress-step ${a.isCompleted?"completed":""}`})},c))}),w("div",{class:"obi-course-progress-description",children:o})]})}function Ry({className:n="",size:e=64}){return w("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:w("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 zQ(n){const{disabled:e,inPlan:t,isPaused:r}=n,[i,A]=he(null),[s,o]=he(n.isActive??n.defaultIsActive??!1),[a,c]=he(!1),[u,l]=he(n.cancelling??!1),[d,h]=he(n.messaging??!1),[f,p]=he(!1),[g,v]=he(d),[y,C]=he(!1);Ba(()=>{n.messaging!==void 0&&h(n.messaging)},[n.messaging]);function B(){o(!0),c(!1),C(!0),n.messaging!==void 0&&h(n.messaging)}function b(){}function _(){i&&(clearTimeout(i),A(null))}function k(){A(setTimeout(()=>{o(n.defaultIsActive??!1),C(!1)},400))}function U(ve){var Pt;p(!1),(Pt=n.onMessage)==null||Pt.call(n,ve)}function I(){var ve;h(!1),p(!1),o(!1),c(!0),(ve=n.onMinimize)==null||ve.call(n)}function P(){var ve;h(!1),l(!0),p(!1),(ve=n.onCancelClick)==null||ve.call(n)}function x(){var ve;t||((ve=n.onOpen)==null||ve.call(n))}function O(ve){var Pt,pi,wn,Ln,tr,Mr;switch(ve){case"need-help":(Pt=n.onMessage)==null||Pt.call(n,"I'm struggling, can you look at my screen and help me out."),(pi=n.onOneClickAction)==null||pi.call(n,"need-help");break;case"continue":(wn=n.onMessage)==null||wn.call(n,"Okay, let's continue."),(Ln=n.onOneClickAction)==null||Ln.call(n,"continue");break;case"say-again":(tr=n.onMessage)==null||tr.call(n,"Please say that again."),(Mr=n.onOneClickAction)==null||Mr.call(n,"say-again");break}}function H(ve){var Pt;n.messaging===void 0&&((Pt=n.onMessagingChange)==null||Pt.call(n,ve),h(ve)),ve||p(!1)}const z=n.isActive??((s||t)&&!a&&!e),F=z&&t,D=z&&t&&!f,X=n.speakingStatus==="user-speaking",J=n.speakingStatus==="thinking",$=n.speakingStatus==="busy",Se=z&&!t&&!u&&y,We=z&&t&&r&&!X&&!u,Te=z&&t&&!We&&!X&&d!==g&&!u,dt=z&&t&&r&&X&&!u,Re=z&&t&&!r&&X&&!u,Fe=z&&t&&!r&&$&&!u,re=d&&X,$e=Se||We||dt||Re||Te||u,Ct=400,Wt=z&&t&&!f,hi=Se?5:10;return Ba(()=>{X&&v(d)},[X]),!t&&!u?w(XQ,{...n}):!t&&u?w(YQ,{onOtherSelect:()=>{var ve;(ve=n.onCancelReasonOther)==null||ve.call(n)},onCancelReason:ve=>{var Pt;o(n.defaultIsActive??!1),l(!1),(Pt=n.onCancelReason)==null||Pt.call(n,ve)},onClose:()=>{o(n.defaultIsActive??!1),l(!1)}}):w(_d,{className:`obi-widget-panel ${F?"expanded":""} ${f?"maximized":""} ${d?"messaging":""} ${$?"tool-usage":""}`,children:[w("div",{className:`obi-widget ${z?"active":""} ${t?"in-plan":""}`,onMouseEnter:_,onMouseLeave:k,children:[D&&w(gn,{type:"cancel",onClick:P,disabled:u,title:"Cancel session"}),D&&!r&&w(gn,{type:"pause",onClick:n.onPause,title:"Pause session"}),D&&r&&w(gn,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),w(Gt,{className:"obi-widget-popout",open:$e,trigger:null,delayMs:Ct,offset:hi,children:[w(Gt.Target,{children:[re&&w(qQ,{value:n.message,defaultValue:"Okay, let's continue.",onCancel:()=>H(!1),onSend:U,onExpand:p,onChange:n.onMessageChange,children:w("div",{className:"obi-widget-buttons",children:[w(gn,{type:"cancel",onClick:P,disabled:u,title:"Cancel session"}),!r&&w(gn,{type:"pause",onClick:n.onPause,title:"Pause session"}),r&&w(gn,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),w(gn,{type:d?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>H(!d),title:d?"Voice input":"Text input"}),w(gn,{type:"minimize",onClick:I,title:"Minimize widget"})]})}),!re&&w(Sa,{className:z&&!t?"button":"",isActive:z,speakingStatus:n.speakingStatus,onClick:x,onMouseEnter:B,onMouseLeave:b,children:[z&&!t&&!Fe&&w("span",{className:"obi-widget-pill-text",children:"Tutorials"}),z&&t&&Fe&&w("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),z&&t&&!J&&!Fe&&w(wy,{getBands:n.spectrum}),z&&J&&!Fe&&w(by,{})]})]}),w(Gt.Content,{children:w("div",{onMouseLeave:k,children:[Se&&w(Sr,{onClick:x,children:"Click to see all"}),We&&w(Sr,{children:"Session will pause shortly"}),Te&&w(Sr,{children:["Switched to ",d?"chat":"voice"]}),dt&&w(Sr,{children:"Paused"}),Re&&w("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[w(Sr,{onClick:()=>O("need-help"),children:"Need help"}),w(Sr,{onClick:()=>O("continue"),children:"Continue"}),w(Sr,{onClick:()=>O("say-again"),children:"Say again"})]}),u&&w(IQ,{onContinue:()=>{var ve;(ve=n.onCancelAbort)==null||ve.call(n),l(!1),n.messaging!==void 0&&h(n.messaging)},onWrapUp:()=>{var ve;(ve=n.onCancel)==null||ve.call(n)}})]})})]}),D&&w(gn,{type:d?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>H(!d),title:d?"Voice input":"Text input"}),D&&w(gn,{type:"minimize",onClick:I,title:"Minimize widget"})]}),Wt&&n.courseProgress&&w("div",{className:`obi-course-progress-container ${d?"expanded":""}`,children:w(JQ,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames})})]})}function XQ(n){const{disabled:e,completedTutorials:t,totalTutorials:r,agentName:i}=n,[A,s]=he(null),[o,a]=he(n.isActive??n.defaultIsActive??!1),[c,u]=he(!1),[l,d]=he(n.hovered??!1);function h(){var U;a(!0),u(!1),d(!0),(U=n.onHover)==null||U.call(n,!0)}function f(){}function p(){A&&(clearTimeout(A),s(null))}function g(){o&&s(setTimeout(()=>{var U;a(n.defaultIsActive??!1),d(!1),(U=n.onHover)==null||U.call(n,!1)},400))}function v(){a(!1),u(!0)}function y(){var U;(U=n.onOpen)==null||U.call(n)}const C=n.hovered??(l&&!c),B=n.isActive??(o&&!e&&!c),b=B&&C,_=`round-button ${B?"active":""}`;let k=`${i||"Obi"}`;return t!==void 0&&r!==void 0&&t>=0&&r>0&&(k=`${t}/${r} completed`),w("div",{className:"obi-widget-out-of-plan-container",children:w("div",{className:`obi-widget-out-of-plan ${C?"hover":""} ${B?"active":""}`,onMouseEnter:p,onMouseLeave:g,children:[w("div",{className:_,style:{width:"30px",height:"30px"}}),w(Gt,{className:"obi-widget-popout",open:b,trigger:null,delayMs:400,offset:5,children:[w(Gt.Target,{children:w(BQ,{className:B?"button":"",active:B,onClick:y,onMouseEnter:h,onMouseLeave:f,children:w("span",{className:"text",children:[w(Ry,{size:16}),k]})})}),w(Gt.Content,{children:w("div",{onMouseLeave:g,children:w(Sr,{className:"message",onClick:y,children:"Click to see all"})})})]}),w(gn,{className:_,type:"minimize",onClick:v,title:"Minimize widget"})]})})}function YQ(n){return w("div",{className:"obi-widget-out-of-plan-container",children:w("div",{className:"obi-widget-out-of-plan",children:w(Gt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[w(Gt.Target,{children:w(CQ,{active:!1})}),w(Gt.Content,{children:w(FQ,{onOtherSelect:()=>{var e;(e=n.onOtherSelect)==null||e.call(n)},onReasonSelect:(e,t)=>{var r;(r=n.onCancelReason)==null||r.call(n,e,t)},onClose:()=>{var e;(e=n.onClose)==null||e.call(n)}})})]})})})}function ZQ({open:n=!1,children:e,onClose:t}){return w(my,{open:n,onClose:t,children:w("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function Ji({title:n="",subtitle:e="",agentName:t="Obi",buttonText:r="Continue",speakingState:i=null,actionDisabled:A=!1,href:s=null,centerVisual:o,description:a,button:c,onAction:u}){const[l,d]=he(A),[h,f]=he(!1),[p,g]=he(i);return Vt(()=>{h||(i==="listening"&&p!=="listening"&&l&&d(!1),i!=="listening"&&!l&&d(!0)),g(i)},[i,l]),Vt(()=>{d(A)},[A]),w("div",{className:"tour-content",children:w("div",{className:"container",children:[w("div",{className:"header",children:[w("h1",{className:"title",children:n}),w("p",{className:"subtitle",children:e})]}),w("div",{className:"visual",style:{background:"var(--obi-color-tint)"},children:o}),w("div",{className:"description",children:a}),w("div",{className:"button-container",children:c||w(s?"a":"button",{className:`action-button ${l?"disabled":""}`,onClick:()=>{l||(d(!0),f(!0),u==null||u())},disabled:l,...s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:w("span",{className:"button-text",children:(()=>{switch(i){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return r}})()})})})]})})}function $Q({logoUrl:n="",appName:e="App"}){const[t,r]=he(!1),[i,A]=he(!1),s=()=>{r(!0)},o=()=>{A(!0),r(!1)},a={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:n&&!t&&i?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!n||t||!i?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return w("div",{style:a.container,children:w("div",{style:a.logoContainer,children:[w("div",{style:a.backgroundPattern}),w("div",{style:a.logoWrapper,children:[n&&w("img",{style:a.appLogo,src:n,alt:`${e} logo`,onError:s,onLoad:o}),w("div",{style:a.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function eR({session:n,speakingState:e,onAction:t}){const r=n.appName?`Navigate to ${n.appName}`:"Navigate to app",i=n.appName?`Open ${n.appName}`:"Open app",A=n.appName?`Enjoy the tutorial in ${n.appName}`:"Enjoy the tutorial";return w(Ji,{title:r,subtitle:"Click the button below to open the app",agentName:n.agentName||"Obi",buttonText:i,speakingState:e,actionDisabled:!0,href:n.url,description:A,centerVisual:w($Q,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}function tR({}){return w("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:w(Sa,{isActive:!0,children:w("div",{className:"obi-static-voice-visual",children:[w("div",{className:"column",children:w("div",{className:"bar bar-1"})}),w("div",{className:"column",children:w("div",{className:"bar bar-2"})}),w("div",{className:"column",children:w("div",{className:"bar bar-3"})}),w("div",{className:"column",children:w("div",{className:"bar bar-4"})}),w("div",{className:"column",children:w("div",{className:"bar bar-5"})}),w("div",{className:"column",children:w("div",{className:"bar bar-6"})}),w("div",{className:"column",children:w("div",{className:"bar bar-7"})}),w("div",{className:"column",children:w("div",{className:"bar bar-8"})})]})})})}function nR({session:n,speakingState:e,onAction:t}){return w(Ji,{title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,buttonText:"Start now",agentName:n.agentName||"Obi",speakingState:e,centerVisual:w(tR,{}),onAction:t})}function rR(){const n={host:{display:"block",position:"relative",width:"100%",height:"100%"},container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},permissionDialog:{boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"flex-start",alignItems:"center",padding:"16px 20px",gap:"16px",position:"absolute",width:"344px",height:"125px",left:"calc(50% - 344px/2)",top:"calc(50% - 125px/2)",background:"#FFFFFF",border:"1px solid #E5E7EB",boxShadow:"0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px -2px rgba(0, 0, 0, 0.05)",borderRadius:"8px"},permissionContent:{width:"100%",display:"flex",flexDirection:"column",gap:"16px"},permissionContentTop:{display:"flex",flexDirection:"row",alignItems:"center",padding:"0px",gap:"16px"},micIconContainer:{color:"var(--obi-color-text)",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"12px",gap:"8px",width:"48px",height:"48px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:0,flexGrow:0},micIcon:{width:"24px",height:"24px",flex:"none",order:0,flexGrow:0},permissionText:{flex:1,height:"24px",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"16px",lineHeight:"24px",display:"flex",alignItems:"center",color:"#111827",flexGrow:1,order:1},allowButton:{alignSelf:"flex-end",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"10px 20px",gap:"8px",minWidth:"80px",height:"40px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:2,flexGrow:0,cursor:"pointer",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"14px",lineHeight:"20px",color:"#374151"},cursorPointer:{position:"absolute",width:"24px",height:"24px",right:"80px",bottom:"60px",zIndex:3,animation:"pointToAllow 2s ease-in-out infinite"},cursorSvg:{width:"100%",height:"100%",filter:"drop-shadow(0px 1px 1.8px rgba(0, 0, 0, 0.65))"}};return w("div",{style:n.host,children:[w("style",{children:`
|
|
43
43
|
@keyframes pointToAllow {
|
|
44
44
|
0%, 100% { transform: translate(0, 0); }
|
|
45
45
|
50% { transform: translate(2px, -1px); }
|