obi-sdk 0.19.23 → 0.19.25-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -39,12 +39,12 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
39
39
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
40
40
  `);n.RTCSessionDescription&&r instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function zr(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 Hr(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 r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Uk=Object.freeze({__proto__:null,removeExtmapAllowMixed:La,shimAddIceCandidateNullOrEmpty:zr,shimConnectionState:Na,shimMaxMessageSize:Gr,shimParameterlessSetLocalDescription:Hr,shimRTCIceCandidate:Vr,shimRTCIceCandidateRelayProtocol:Aa,shimSendThrowTypeError:Wr});function Bk(){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=nd,i=Nk(n),r={browserDetails:i,commonShim:Uk,extractVersion:jr,disableLog:Ok,disableWarnings:Ak,sdp:Dk};switch(i.browser){case"chrome":if(!md||!Ra||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),r;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),r;t("adapter.js shimming chrome."),r.browserShim=md,zr(n,i),Hr(n),od(n,i),cd(n),Ra(n,i),ld(n),fd(n,i),ud(n),dd(n),pd(n,i),Vr(n),Aa(n),Na(n),Gr(n,i),Wr(n),La(n,i);break;case"firefox":if(!_d||!Ia||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=_d,zr(n,i),Hr(n),gd(n,i),Ia(n,i),vd(n),kd(n),bd(n),yd(n),Td(n),Sd(n),Cd(n),xd(n),wd(n),Vr(n),Na(n),Gr(n,i),Wr(n);break;case"safari":if(!Dd||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=Dd,zr(n,i),Hr(n),Ad(n),Ld(n),Rd(n),Ed(n),Pd(n),Nd(n),Id(n),Md(n),Vr(n),Aa(n),Gr(n,i),Wr(n),La(n,i);break;default:t("Unsupported browser!");break}return r}Bk({window:typeof window>"u"?void 0:window});const Fk=10,qr="lk_e2ee",jk={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Fk,keyringSize:16};var Kt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Kt||(Kt={}));var Fd;(function(n){n.KeyRatcheted="keyRatcheted"})(Fd||(Fd={}));var $t;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})($t||($t={}));var jd;(function(n){n.Error="cryptorError"})(jd||(jd={}));function Vk(){return Gk()||Ma()}function Ma(){return typeof window.RTCRtpScriptTransform<"u"}function Gk(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class ox extends Tt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,r)=>{$.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},jk),e),this.on(Kt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const r={key:e,participantIdentity:t,keyIndex:i};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(i??0),r),this.emit(Kt.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Kt.RatchetRequest,e,t)}}class Yt extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var X;(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"})(X||(X={}));class re extends Yt{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=X[t]}}class Da extends Yt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Pt extends Yt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Wk extends Yt{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class _e extends Yt{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ua extends Yt{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Ba extends Yt{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Vd extends Yt{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:wa[t]}}var Kr;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Kr||(Kr={})),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}(Kr||(Kr={}));var Gd;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Gd||(Gd={}));var O;(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"})(O||(O={}));var L;(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"})(L||(L={}));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 A;(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"})(A||(A={}));function zk(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const Hk=/version\/(\d+(\.?_?\d+)+)/i;let Fa;function ct(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(Fa===void 0||e){const i=qk.find(r=>{let{test:s}=r;return s.test(t)});Fa=i==null?void 0:i.describe(t)}return Fa}const qk=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:$r(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ja(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:$r(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ja(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:$r(Hk,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:ja(n)}}}];function $r(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function ja(n){return n.includes("mac os")?$r(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Kk="2.13.0";const $k=Kk,Yk=16;class Ae{}Ae.setTimeout=function(){return setTimeout(...arguments)},Ae.setInterval=function(){return setInterval(...arguments)},Ae.clearTimeout=function(){return clearTimeout(...arguments)},Ae.clearInterval=function(){return clearInterval(...arguments)};const Xk=5e3,vi=[];var Ze;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ze||(Ze={}));class P extends Tt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=P.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=$,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Xk):this.handleAppVisibilityChanged()},this.log=Et((r=i.loggerName)!==null&&r!==void 0?r:ot.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=P.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),te(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===P.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===P.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(vi.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&vi.splice(vi.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),jn(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?A.AudioPlaybackStarted:A.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?A.AudioPlaybackFailed:A.VideoPlaybackFailed,s):s.name==="AbortError"?$.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):$.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(A.ElementAttached,e),e}detach(e){try{if(e){Vn(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(A.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Vn(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(A.ElementDetached,i)}),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=Et(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),vi.forEach(i=>{i.parentElement||(t=!1)}),t&&vi.push(e)}}handleAppVisibilityChanged(){return y(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===P.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){We()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){We()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function jn(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(r=>{t.removeTrack(r)}),t.addTrack(n)),(!Xt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Xt()||Gn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Vn(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 i;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function r(c){switch(c){case e.Audio:return it.AUDIO;case e.Video:return it.VIDEO;default:return it.DATA}}n.kindToProto=r;function s(c){switch(c){case it.AUDIO:return e.Audio;case it.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(c){switch(c){case t.Camera:return Ce.CAMERA;case t.Microphone:return Ce.MICROPHONE;case t.ScreenShare:return Ce.SCREEN_SHARE;case t.ScreenShareAudio:return Ce.SCREEN_SHARE_AUDIO;default:return Ce.UNKNOWN}}n.sourceToProto=a;function o(c){switch(c){case Ce.CAMERA:return t.Camera;case Ce.MICROPHONE:return t.Microphone;case Ce.SCREEN_SHARE:return t.ScreenShare;case Ce.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function l(c){switch(c){case ba.ACTIVE:return i.Active;case ba.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=l})(P||(P={}));class ie{constructor(e,t,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Jk=["vp8","h264"],Qk=["vp8","h264","vp9","av1"];function Zk(n){return!!Jk.find(e=>e===n)}var Wd;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Wd||(Wd={}));var Va;(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}})(Va||(Va={}));const bi={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)},Ga={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)},Wa={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")},eT="|",zd="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function tT(n){const e=n.split(eT);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Ge(n){return y(this,void 0,void 0,function*(){return new Promise(e=>Ae.setTimeout(e,n))})}function za(){return"addTransceiver"in RTCPeerConnection.prototype}function Ha(){return"addTrack"in RTCPeerConnection.prototype}function nT(){if(!("getCapabilities"in RTCRtpSender)||Xt())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 iT(){if(!("getCapabilities"in RTCRtpSender)||Gn())return!1;if(Xt()){const t=ct();if(t!=null&&t.version&&pn(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 yi(n){return n==="av1"||n==="vp9"}function qa(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function rT(){return typeof RTCPeerConnection>"u"?!1:za()||Ha()}function Gn(){var n;return((n=ct())===null||n===void 0?void 0:n.name)==="Firefox"}function Xt(){var n;return((n=ct())===null||n===void 0?void 0:n.name)==="Safari"}function sT(){const n=ct();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Hd(){var n,e;return We()?(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 aT(){const n=ct(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&pn(e,n.osVersion)>=0?!0:n.name==="Safari"&&pn(e,n.version)>=0}function We(){return typeof document<"u"}function St(){return navigator.product=="ReactNative"}function Ka(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function qd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Kd(){if(!St())return;let n=qd();if(n)return n.platform}function $d(){if(We())return window.devicePixelRatio;if(St()){let n=qd();if(n)return n.devicePixelRatio}return 1}function pn(n,e){const t=n.split("."),i=e.split("."),r=Math.min(t.length,i.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(i[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function oT(n){for(const e of n)e.target.handleResize(e)}function cT(n){for(const e of n)e.target.handleVisibilityChanged(e)}let $a=null;const Yd=()=>($a||($a=new ResizeObserver(oT)),$a);let Ya=null;const Xd=()=>(Ya||(Ya=new IntersectionObserver(cT,{root:null,rootMargin:"0px"})),Ya);function lT(){var n;const e=new Qy({sdk:Lu.JS,protocol:Yk,version:$k});return St()&&(e.os=(n=Kd())!==null&&n!==void 0?n:""),e}function Jd(){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,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=n,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(n/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=r.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let ki;function Xa(){if(!ki){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[ki]=i.stream.getAudioTracks(),!ki)throw Error("Could not get empty media stream audio track");ki.enabled=!1}return ki.clone()}class Ja{constructor(e,t){this.onFinally=t,this.promise=new Promise((i,r)=>y(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function uT(n){return Qk.includes(n)}function Jt(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 dT(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Qa(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function hT(n,e){return n.segments.map(t=>{let{id:i,text:r,language:s,startTime:a,endTime:o,final:l}=t;var c;const u=(c=e.get(i))!==null&&c!==void 0?c:Date.now(),d=Date.now();return l?e.delete(i):e.set(i,u),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:l,language:s,firstReceivedTime:u,lastReceivedTime:d}})}function fT(n){const{id:e,timestamp:t,message:i,editTimestamp:r}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function Qd(n){switch(n.reason){case X.LeaveRequest:return n.context;case X.Cancelled:return rt.CLIENT_INITIATED;case X.NotAllowed:return rt.USER_REJECTED;case X.ServerUnreachable:return rt.JOIN_FAILURE;default:return rt.UNKNOWN_REASON}}function Yr(n){return n!==void 0?Number(n):void 0}function mn(n){return n!==void 0?BigInt(n):void 0}function Wn(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Rt(n){return!!n&&n.kind==P.Kind.Audio}function zn(n){return!!n&&n.kind==P.Kind.Video}function Qt(n){return Wn(n)&&zn(n)}function gn(n){return Wn(n)&&Rt(n)}function Za(n){return!!n&&!n.isLocal}function pT(n){return!!n&&!n.isLocal}function eo(n){return Za(n)&&zn(n)}function mT(n){return n.isLocal}function gT(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&t.push(i),t}function Zd(n,e,t){var i,r,s,a;const{optionsWithoutProcessor:o,audioProcessor:l,videoProcessor:c}=ih(n??{}),u=e==null?void 0:e.processor,d=t==null?void 0:t.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(to(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(l||u)&&(h.audio.processor=l??u)),h.video&&(to(h.video,t),(r=(a=h.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(c||d)&&(h.video.processor=c??d)),h}function to(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function no(n){var e,t,i,r;const s={};if(n.video)if(typeof n.video=="object"){const a={},o=a,l=n.video;Object.keys(l).forEach(c=>{switch(c){case"resolution":to(o,l.resolution);break;default:o[c]=l[c]}}),s.video=a,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=n.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return n.audio?typeof n.audio=="object"?(s.audio=n.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function eh(n){return y(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=th();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Ge(t),r.getByteTimeDomainData(a);const l=a.some(c=>c!==128&&c!==0);return i.close(),!l}return!1}()})}function th(){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 i=()=>y(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return t}}function vT(n){return n==="audioinput"?P.Source.Microphone:n==="videoinput"?P.Source.Camera:P.Source.Unknown}function nh(n){return n===P.Source.Microphone?"audioinput":n===P.Source.Camera?"videoinput":void 0}function bT(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Xt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{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:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Xr(n){return n.split("/")[1].toLowerCase()}function yT(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Ca({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function te(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?te(n.track):{})}}function kT(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function TT(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],r={};for(const s of i)n[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function ih(n){const e=Object.assign({},n);let t,i;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&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:zk(e)}}function ST(n){switch(n){case Ce.CAMERA:return P.Source.Camera;case Ce.MICROPHONE:return P.Source.Microphone;case Ce.SCREEN_SHARE:return P.Source.ScreenShare;case Ce.SCREEN_SHARE_AUDIO:return P.Source.ScreenShareAudio;default:return P.Source.Unknown}}class CT extends Tt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,r;const{kind:s,data:a}=t.data;switch(s){case"error":$.error(a.error.message),this.emit($t.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit($t.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit($t.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Kt.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{$.error("e2ee worker encountered an error:",{error:t.error}),this.emit($t.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Vk())throw new Da("tried to setup end-to-end encryption on an unsupported browser");if($.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:_k.getLevel()}};this.worker&&($.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){$.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?$.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(O.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==$e.NONE,r.identity)),e.on(O.ConnectionStateChanged,i=>{i===Z.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==$e.NONE,r.identity)})})}).on(O.TrackUnsubscribed,(i,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(O.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(O.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(L.LocalTrackPublished,i=>y(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(Kt.SetKey,i=>this.postKey(i)).on(Kt.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:t,keyIndex:r}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}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 i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Xr(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Wn(e)||!t){t||$.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,r){return y(this,void 0,void 0,function*(){if(this.worker){if(Ma()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(qr in e&&r){const l={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:i}};this.worker.postMessage(l);return}let s=e.writableStream,a=e.readableStream;if(!s||!a){const l=e.createEncodedStreams();e.writableStream=l.writable,s=l.writable,e.readableStream=l.readable,a=l.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:r,participantIdentity:i}};this.worker.postMessage(o,[a,s])}e[qr]=!0}})}handleSender(e,t,i){var r;if(!(qr in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ma()){$.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{$.info("initialize encoded streams");const s=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[s.readable,s.writable])}e[qr]=!0}}}const io="default";class Pe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Pe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=Pe.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){$.debug("awaiting getUserMedia promise");try{t?yield Pe.userMediaPromiseMap.get(t):yield Promise.all(Pe.userMediaPromiseMap.values())}catch{$.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Xt()&&i.hasDeviceInUse(t))&&(a.filter(l=>l.kind===t).length===0||a.some(l=>{const c=l.label==="",u=t?l.kind===t:!0;return c&&u}))){const l={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(l);a=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,i){return y(this,void 0,void 0,function*(){if(t!==io)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===io);if(!s){$.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==io&&o.groupId===(i??s.groupId));if(!a){$.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?Pe.userMediaPromiseMap.has(e):Pe.userMediaPromiseMap.size>0}}Pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Pe.userMediaPromiseMap=new Map;var Ti;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Ti||(Ti={}));class xT{constructor(){this.pendingTasks=new Map,this.taskMutex=new Fe,this.nextTaskIndex=0}run(e){return y(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ti.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ti.RUNNING,yield e()}finally{t.status=Ti.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return y(this,void 0,void 0,function*(){return this.run(()=>y(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function wT(n,e){const t=new URL(dT(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),rh(t,"rtc")}function _T(n){const e=new URL(Qa(n));return rh(e,"validate")}function ET(n){return n.endsWith("/")?n:"".concat(n,"/")}function rh(n,e){return n.pathname="".concat(ET(n.pathname)).concat(e),n.toString()}const PT=["syncState","trickle","offer","answer","simulate","leave"];function RT(n){const e=PT.indexOf(n.case)>=0;return $.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ce;(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"})(ce||(ce={}));class ro{get currentState(){return this.state}get isDisconnected(){return this.state===ce.DISCONNECTING||this.state===ce.DISCONNECTED}get isEstablishingConnection(){return this.state===ce.CONNECTING||this.state===ce.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 i;this.rtt=0,this.state=ce.DISCONNECTED,this.log=$,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=Et((i=t.loggerName)!==null&&i!==void 0?i:ot.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new xT,this.queuedRequests=[],this.closingLock=new Fe,this.connectionLock=new Fe,this.state=ce.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,i,r){return y(this,void 0,void 0,function*(){return this.state=ce.CONNECTING,this.options=i,yield this.connect(e,t,i,r)})}reconnect(e,t,i,r){return y(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=ce.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,t,i,r){this.connectOptions=i;const s=lT(),a=IT(t,s,i),o=wT(e,a),l=_T(o);return new Promise((c,u)=>y(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const h=()=>y(this,void 0,void 0,function*(){this.close(),clearTimeout(f),u(new re("room connection has been cancelled (signal)",X.Cancelled))}),f=setTimeout(()=>{this.close(),u(new re("room connection has timed out (signal)",X.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const g=new URL(o);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=m=>y(this,void 0,void 0,function*(){if(this.state!==ce.CONNECTED){this.state=ce.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(l);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();u(new re(b,X.NotAllowed,v.status))}else u(new re("Encountered unknown websocket error during connection: ".concat(m.toString()),X.InternalError,v.status))}catch(v){u(new re(v instanceof Error?v.message:"server was not reachable",X.ServerUnreachable))}return}this.handleWSError(m)}),this.ws.onmessage=m=>y(this,void 0,void 0,function*(){var v,b,S;let x;if(typeof m.data=="string"){const k=JSON.parse(m.data);x=ju.fromJson(k,{ignoreUnknownFields:!0})}else if(m.data instanceof ArrayBuffer)x=ju.fromBinary(new Uint8Array(m.data));else{this.log.error("could not decode websocket message: ".concat(typeof m.data),this.logContext);return}if(this.state!==ce.CONNECTED){let k=!1;if(((v=x.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=ce.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=x.message.value.pingTimeout,this.pingIntervalDuration=x.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(x.message.value)):this.state===ce.RECONNECTING&&x.message.case!=="leave"?(this.state=ce.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=x.message)===null||b===void 0?void 0:b.case)==="reconnect"?c(x.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),k=!0)):this.isEstablishingConnection&&x.message.case==="leave"?u(new re("Received leave request while trying to (re)connect",X.LeaveRequest,void 0,x.message.value.reason)):i.reconnect||u(new re("did not receive join response, got ".concat((S=x.message)===null||S===void 0?void 0:S.case," instead"),X.InternalError)),!k)return}this.signalLatency&&(yield Ge(this.signalLatency)),this.handleSignalResponse(x)}),this.ws.onclose=m=>{this.isEstablishingConnection&&u(new re("Websocket got closed during a (re)connection attempt",X.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:m.reason,code:m.code,wasClean:m.wasClean,state:this.state})),this.handleOnClose(m.reason)}}finally{d()}}))}close(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ce.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,Ge(250)])),e.ws=void 0}}finally{t&&(e.state=ce.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Jr(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Jr(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 Ta({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Sa({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new zu({requestId:o,metadata:i,name:r,attributes:a})}),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 Wu({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ku({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ue.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Xu({timestamp:ue.parse(Date.now()),rtt:ue.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Gu({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Dr({reason:rt.CLIENT_INITIATED,action:Bn.DISCONNECT})})}sendRequest(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!RT(t)&&i.state===ce.RECONNECTING){i.queuedRequests.push(()=>y(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield Ge(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const a=new tk({message:t});try{i.useJSON?i.ws.send(a.toJsonString()):i.ws.send(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const a=sh(r.value);this.onAnswer&&this.onAnswer(a)}else if(r.case==="offer"){const a=sh(r.value);this.onOffer&&this.onOffer(a)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return y(this,void 0,void 0,function*(){if(this.state===ce.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=Ae.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&&Ae.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=Ae.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ae.clearInterval(this.pingInterval)}}function sh(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 Jr(n){return new hn({sdp:n.sdp,type:n.type})}function IT(n,e,t){var i;const r=new URLSearchParams;return r.set("access_token",n),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",St()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}var lt={},so={},ao={exports:{}},ah;function oo(){if(ah)return ao.exports;ah=1;var n=ao.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(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),ao.exports}var oh;function OT(){return oh||(oh=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,l,c,u){if(u&&!c)l[u]=e(o[1]);else for(var d=0;d<c.length;d+=1)o[d+1]!=null&&(l[c[d]]=e(o[d+1]))},i=function(o,l,c){var u=o.name&&o.names;o.push&&!l[o.push]?l[o.push]=[]:u&&!l[o.name]&&(l[o.name]={});var d=o.push?{}:u?l[o.name]:l;t(c.match(o.reg),d,o.names,o.name),o.push&&l[o.push].push(d)},r=oo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var l={},c=[],u=l;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var g=0;g<(r[h]||[]).length;g+=1){var m=r[h][g];if(m.reg.test(f))return i(m,u,f)}}),l.media=c,l};var a=function(o,l){var c=l.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&l.length>1&&(o[c[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var l=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)l.push({component:c[u],ip:c[u+1],port:c[u+2]});return l},n.parseImageAttributes=function(o){return o.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(l){return l.split(",").map(function(c){var u,d=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),d=!0),{scid:u,paused:d}})})}}(so)),so}var co,ch;function AT(){if(ch)return co;ch=1;var n=oo(),e=/%[sdv%]/g,t=function(a){var o=1,l=arguments,c=l.length;return a.replace(e,function(u){if(o>=c)return u;var d=l[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(a,o,l){var c=o.format instanceof Function?o.format(o.push?l:l[o.name]):o.format,u=[a+"="+c];if(o.names)for(var d=0;d<o.names.length;d+=1){var h=o.names[d];o.name?u.push(l[o.name][h]):u.push(l[o.names[d]])}else u.push(l[o.name]);return t.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return co=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var l=o.outerOrder||r,c=o.innerOrder||s,u=[];return l.forEach(function(d){n[d].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(i(d,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){u.push(i(d,h,f))})})}),a.media.forEach(function(d){u.push(i("m",n.m[0],d)),c.forEach(function(h){n[h].forEach(function(f){f.name in d&&d[f.name]!=null?u.push(i(h,f,d)):f.push in d&&d[f.push]!=null&&d[f.push].forEach(function(g){u.push(i(h,f,g))})})})}),u.join(`\r
41
41
  `)+`\r
42
- `},co}var lh;function NT(){if(lh)return lt;lh=1;var n=OT(),e=AT(),t=oo();return lt.grammar=t,lt.write=e,lt.parse=n.parse,lt.parseParams=n.parseParams,lt.parseFmtpConfig=n.parseFmtpConfig,lt.parsePayloads=n.parsePayloads,lt.parseRemoteCandidates=n.parseRemoteCandidates,lt.parseImageAttributes=n.parseImageAttributes,lt.parseSimulcastStreamList=n.parseSimulcastStreamList,lt}var Zt=NT();function lo(n,e,t){var i,r,s;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(r=t.callback)!=null&&r,l=t.maxWait,c=Date.now(),u=[];function d(){if(l!==void 0){var f=Date.now()-c;if(f+e>=l)return l-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(m,v){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,c=Date.now(),!a){var x=n.apply(g,f);o&&o(x),u.forEach(function(k){return(0,k.resolve)(x)}),u=[]}},d()),b){var S=n.apply(g,f);return o&&o(S),m(S)}u.push({resolve:m,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(g){return(0,g.reject)(f)}),u=[]},h}const LT=.7,MT=20,Hn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class uh extends Tt.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 i;super(),this.log=$,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=lo(r=>y(this,void 0,void 0,function*(){this.emit(Hn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),MT),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=Et((i=t.loggerName)!==null&&i!==void 0?i:ot.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.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 i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.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 y(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return y(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:r,nackMids:s}=DT(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=Zt.parse((t=e.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s.mid!=a.transceiver.mid)return!1;let o=0;if(s.rtp.some(c=>c.codec.toUpperCase()===a.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let l=!1;for(const c of s.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Zt.write(r)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Hn.NegotiationComplete),e.sdp&&Zt.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Hn.RTPVideoPayloadTypes,s.rtp)}))})}createAndSendOffer(e){return y(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 s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Zt.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{hh(s),s.type==="audio"?dh(s,[],[]):s.type==="video"&&this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let o=0;if(s.rtp.some(c=>c.codec.toUpperCase()===a.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(yi(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*LT);for(const c of s.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),yield this.setMungedSDP(i,Zt.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Zt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{hh(r),r.type==="audio"&&dh(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Zt.write(i)),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 _e("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 _e("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 y(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=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),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return y(this,void 0,void 0,function*(){if(t){const r=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:t})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Ua(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===zd))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var l;o.type==="video"&&((l=o.ext)===null||l===void 0||l.forEach(c=>{c.value>a&&(a=c.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:zd})}}}function dh(n,e,t){let i=0;n.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function DT(n){var e;const t=[],i=[],r=Zt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(l=>l.codec==="opus"?(s=l.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(l=>l.payload===s&&l.type==="nack")&&i.push(a.mid),a.fmtp.some(l=>l.payload===s?(l.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function hh(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 uo="vp8",UT={audioPreset:Va.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Wa.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:uo,backupCodec:!0},fh={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ph={deviceId:{ideal:"default"},resolution:bi.h720.resolution},BT={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Pk,disconnectOnPageLeave:!0,webAudioMix:!1},ho={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var pe;(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"})(pe||(pe={}));class FT{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=ho.peerConnectionTimeout,this.log=$,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(l=>l.getConnectionState());o.every(l=>l==="connected")?this.state=pe.CONNECTED:o.some(l=>l==="failed")?this.state=pe.FAILED:o.some(l=>l==="connecting")?this.state=pe.CONNECTING:o.every(l=>l==="closed")?this.state=pe.CLOSED:o.some(l=>l==="closed")?this.state=pe.CLOSING:o.every(l=>l==="new")&&(this.state=pe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(pe[a]," to ").concat(pe[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Et((r=i.loggerName)!==null&&r!==void 0?r:ot.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new uh(e,i),this.subscriber=new uh(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,at.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,at.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=s=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s)},this.state=pe.NEW,this.connectionLock=new Fe,this.remoteOfferLock=new Fe}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 y(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(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return y(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return y(this,void 0,void 0,function*(){t===at.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return y(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 y(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return y(this,void 0,void 0,function*(){return new Promise((t,i)=>y(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Hn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Hn.NegotiationComplete,()=>{clearTimeout(r),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),i(a)})}))})}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===at.PUBLISHER?this.publisher.getConnectedAddress():e===at.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 y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((l,c)=>y(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Ae.clearTimeout(d),c(new re("room connection has been cancelled",X.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Ae.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(new re("could not establish pc connection",X.InternalError))},a);for(;this.state!==pe.CONNECTED;)if(yield Ge(50),r!=null&&r.signal.aborted){c(new re("room connection has been cancelled",X.Cancelled));return}Ae.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}class me extends Error{constructor(e,t,i){super(t),this.code=e,this.message=gh(t,me.MAX_MESSAGE_BYTES),this.data=i?gh(i,me.MAX_DATA_BYTES):void 0}static fromProto(e){return new me(e.code,e.message,e.data)}toProto(){return new Ou({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new me(me.ErrorCode[e],me.ErrorMessage[e],t)}}me.MAX_MESSAGE_BYTES=256,me.MAX_DATA_BYTES=15360,me.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},me.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 mh=15360;function fo(n){return new TextEncoder().encode(n).length}function gh(n,e){if(fo(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}const po=2e3;function Qr(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const jT=1e3;class vh extends P{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=lo(()=>y(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>y(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(A.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Fe,this.pauseUpstreamLock=new Fe,this.processorLock=new Fe,this.restartLock=new Fe,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==P.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 y(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Vn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){const s=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&&(jn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{jn(r??e,s)}))})}waitForDimensions(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jT;return function*(){var i;if(e.kind===P.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ct())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ge(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield Ge(50)}throw new Pt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return y(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Jt(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Jt(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return y(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===P.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===P.Kind.Audio?"audioinput":"videoinput";return t?Pe.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return y(this,void 0,void 0,function*(){if(!this.sender)throw new Pt("unable to replace an unpublished track");let i,r;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return y(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Rk(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===P.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(c=>{Vn(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield l.applyConstraints(s),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l),this._constraints=e,this.emit(A.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{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?A.Muted:A.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hd()&&(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 y(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(A.UpstreamPaused,this);const i=ct();if((i==null?void 0:i.name)==="Safari"&&pn(i.version,"12.0")<0)throw new Da("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 y(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(A.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 y(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 y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),l={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(l),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(jn(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Vn(i._mediaStreamTrack,c),jn(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(A.TrackProcessorUpdate,i.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(A.TrackProcessorUpdate))}()})}}class Zr extends vh{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,P.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>y(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}a&&this.prevStats&&(this._currentBitrate=Qr(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===P.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 y(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 i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Jt(this._constraints.deviceId);return this.source===P.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return y(this,void 0,void 0,function*(){let t;if(e){const i=no({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return y(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){We()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},po)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!St()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(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(A.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return y(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 i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return y(this,void 0,void 0,function*(){const e=yield eh(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(A.AudioSilenceDetected)),e})}}function VT(n,e,t){switch(n.kind){case"audio":return new Zr(n,e,!1,void 0,t);case"video":return new ts(n,e,!1,t);default:throw new Pt("unsupported track type: ".concat(n.kind))}}const GT=Object.values(bi),WT=Object.values(Ga),zT=Object.values(Wa),HT=[bi.h180,bi.h360],qT=[Ga.h180,Ga.h360],KT=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;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)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),mo=["q","h","f"];function go(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,l=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!a&&!o&&!l||!e||!t)return[{}];a||(a=YT(n,e,t,c),$.debug("using video encoding",a));const u=a.maxFramerate,d=new ie(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(l&&yi(c)){const g=new es(l),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const v=ct();if(Xt()||St()||(v==null?void 0:v.name)==="Chrome"&&pn(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3;for(let S=0;S<g.spatial;S+=1)m.push({rid:mo[2-S],maxBitrate:a.maxBitrate/Math.pow(b,S),maxFramerate:d.encoding.maxFramerate});m[0].scalabilityMode=l}else m.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:l});return d.encoding.priority&&(m[0].priority=d.encoding.priority,m[0].networkPriority=d.encoding.priority),$.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(r=yh(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:bh(n,d):h=(s=yh(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:bh(n,d);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const m=Math.max(e,t);if(m>=960&&f)return vo(e,t,[g,f,d],u);if(m>=480)return vo(e,t,[g,d],u)}return vo(e,t,[d])}function $T(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&$.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(),l=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===P.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),go(n.source===P.Source.ScreenShare,l,c,t)}function YT(n,e,t,i){const r=XT(n,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const l=r[o];if(s=l.encoding,l.width>=a)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function XT(n,e,t){if(n)return zT;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?GT:WT}function bh(n,e){if(n)return KT(e);const{width:t,height:i}=e,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?HT:qT}function vo(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=mo.length)return;const o=Math.min(n,e),c={rid:mo[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(c.maxFramerate=u);const d=Gn()||a===0;s.encoding.priority&&d&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),St()&&Kd()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var l;o.maxFramerate!=s&&(a&&(a=!1,$.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),$.info('Setting framerate of encoding "'.concat((l=o.rid)!==null&&l!==void 0?l:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function yh(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:r}=t;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class es{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 JT(n){return n.source===P.Source.ScreenShare||n.constraints.height&&Jt(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const QT=5e3;class ts extends vh{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,P.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>y(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}const a=new Map(s.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((l,c)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=Qr(l,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new Fe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!We())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},po))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,l=qt(this.simulcastCodecs.values()),c;c=yield l.next(),t=c.done,!t;o=!0)s=c.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){i={error:u}}finally{try{!o&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,l=qt(this.simulcastCodecs.values()),c;c=yield l.next(),t=c.done,!t;o=!0){s=c.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!o&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===P.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 y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===P.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 y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ze.LOW;i<=Ze.HIGH;i+=1)t.push(new xa({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const d=no({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var l=!0,c=qt(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;l=!0){s=u.value,l=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!l&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return y(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,l,c,u,d;if(yield t.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=qt(r.simulcastCodecs.values()),g;g=yield f.next(),a=g.done,!a;h=!0)c=g.value,h=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){o={error:m}}finally{try{!h&&!a&&(l=f.return)&&(yield l.call(f))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return y(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 i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},QT))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a,o,l;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,i=qt(e);r=yield i.next(),s=r.done,!s;t=!0){l=r.value,t=!1;const u=l;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){c.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield kh(d.sender,d.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e){return y(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 kh(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hd()&&this.isInBackground&&this.source===P.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function kh(n,e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:l}=o;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:l,senderEncodings:e}));return}let c=!1;const u=ct();if((u==null?void 0:u.name)==="Chrome"&&pn(u==null?void 0:u.version,"133")>0&&l[0].scalabilityMode){const h=l[0],f=new es(h.scalabilityMode);let g=Ln.OFF;if(t.forEach(m=>{m.enabled&&(g===Ln.OFF||m.quality>g)&&(g=m.quality)}),g===Ln.OFF)h.active&&(h.active=!1,c=!0);else if(!h.active||f.spatial!==g+1){c=!0,h.active=!0;const m=new es(e[0].scalabilityMode);f.spatial=g+1,f.suffix=m.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-g),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else l.forEach((h,f)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const v=Th(m),b=t.find(S=>S.quality===v);b&&h.active!==b.enabled&&(c=!0,h.active=b.enabled,r.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),s),Gn()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))});c&&(o.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Th(n){switch(n){case"f":return Ze.HIGH;case"h":return Ze.MEDIUM;case"q":return Ze.LOW;default:return Ze.HIGH}}function Sh(n,e,t,i){if(!t)return[new dn({quality:Ze.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new es(r),a=[],o=s.suffix=="h"?1.5:2,l=s.suffix=="h"?2:3;for(let c=0;c<s.spatial;c+=1)a.push(new dn({quality:Math.min(Ze.HIGH,s.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(l,c)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const l=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let c=Th((a=r.rid)!==null&&a!==void 0?a:"");return new dn({quality:c,width:Math.ceil(n/l),height:Math.ceil(e/l),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ch="_lossy",xh="_reliable",ZT=2*1e3,bo="leave-reconnect";var ut;(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"})(ut||(ut={}));class eS extends Tt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ho.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=ut.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=$,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===xh)s.reliableDCSub=a;else if(a.label===Ch)s.lossyDCSub=a;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label),s.logContext),a.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>y(this,void 0,void 0,function*(){var r,s;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const l=Ve.fromBinary(new Uint8Array(o));((r=l.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,l.value.value.speakers):(((s=l.value)===null||s===void 0?void 0:s.case)==="user"&&nS(l,l.value.value),this.emit(N.DataPacketReceived,l))}finally{a()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?Q.LOSSY:Q.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=l=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(l,"ms. giving up"),this.logContext),this.emit(N.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===bo&&(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=Ae.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ut.Connected&&i();const s=()=>{this.off(N.Disconnected,a),i()},a=()=>{this.off(N.Restarted,s),r()};this.once(N.Restarted,s),this.once(N.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(N.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ce.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Mn.RR_SIGNAL_DISCONNECTED))},this.log=Et((t=e.loggerName)!==null&&t!==void 0?t:ot.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ro(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Fe,this.dataProcessLock=new Fe,this.dcBufferStatus=new Map([[Q.LOSSY,!0],[Q.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(N.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(N.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(N.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(N.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(N.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(N.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(N.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(N.SignalRequestResponse,i)}get logContext(){var e,t,i,r,s,a,o,l;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,pID:(l=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||l===void 0?void 0:l.sid}}join(e,t,i,r){return y(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout(()=>{this.emit(N.SignalConnected)},10),s}catch(s){if(s instanceof re&&s.reason===X.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,i,r);throw s}})}close(){return y(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 y(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=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.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 y(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Pt("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new re("publication of local track timed out, no response from server",X.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject: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 y(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 y(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==pe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new FT(r,e.subscriberPrimary,this.loggerOptions),this.emit(N.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,a)=>{this.client.sendIceCandidate(s,a)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,a,o)=>y(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),s===pe.CONNECTED){const u=this.pcState===ut.New;this.pcState=ut.Connected,u&&this.emit(N.Connected,e)}else s===pe.FAILED&&this.pcState===ut.Connected&&(this.pcState=ut.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Mn.RR_SUBSCRIBER_FAILED:Mn.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===ce.RECONNECTING,c=[pe.FAILED,pe.CLOSING,pe.CLOSED].includes(s);l&&c&&!this._isClosed&&this.emit(N.Offline)}),this.pcManager.onTrack=s=>{this.emit(N.MediaTrackAdded,s.track,s.streams[0],s.receiver)},tS((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>y(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=>y(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(N.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(N.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,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",Mn.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 Bn.DISCONNECT:this.emit(N.Disconnected,e==null?void 0:e.reason),this.close();break;case Bn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(bo);break;case Bn.RESUME:this.handleDisconnect(bo)}}}makeRTCConfiguration(e){var t;const i=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),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===mi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ch,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(xh,{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,i){return y(this,void 0,void 0,function*(){if(za())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Ha())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new _e("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(za())return this.createSimulcastTransceiverSender(e,t,i,r);if(Ha())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new _e("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),zn(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return y(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){$.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===mi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:pe.NEW)===pe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof _e?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof qn||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Mn.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 y(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new _e("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new qn;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof re&&a.reason===X.NotAllowed?new _e("could not reconnect, token might be expired"):new qn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(N.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ce.CONNECTED)throw new qn("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(N.Restarted)}catch(s){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return y(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new _e("could not reconnect, url or token not saved");if(!this.pcManager)throw new _e("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof re&&r.reason===X.NotAllowed?new _e("could not reconnect, token might be expired"):r instanceof re&&r.reason===X.LeaveRequest?r:new qn(s)}if(this.emit(N.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r)}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!==ce.CONNECTED)throw new qn("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 y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ge(ZT),!this.pcManager)throw new _e("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ut.Connected}catch(e){throw this.pcState=ut.Disconnected,new re("could not establish PC connection, ".concat(e.message),X.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new Ve({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcResponse",value:new Iu({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,Q.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new Ve({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcAck",value:new Ru({requestId:t})}});yield this.sendDataPacket(i,Q.RELIABLE)})}sendDataPacket(e,t){return y(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const r=this.dataChannelForKind(t);r&&r.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>y(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const r=()=>i("Engine closed");for(this.once(N.Closing,r);!this.dcBufferStatus.get(e);)yield Ge(10);this.off(N.Closing,r),t()}}))}ensureDataTransportConnected(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new _e("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new re("".concat(o," connection not set"),X.InternalError);let l=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),l=!0),!l&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(l=!0),l&&i.negotiate();const c=i.dataChannelForKind(t,r);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Ge(50)}throw new re("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),X.InternalError)}()})}ensurePublisherConnected(e){return y(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==pe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return y(this,void 0,void 0,function*(){return new Promise((e,t)=>y(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ua("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(N.Closing,r),this.pcManager.publisher.once(Hn.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const l=o.codec.toLowerCase();uT(l)&&a.set(o.payload,l)}),this.emit(N.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Ua&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Mn.RR_UNKNOWN),t(s)}finally{this.off(N.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===Q.LOSSY)return this.lossyDCSub;if(e===Q.RELIABLE)return this.reliableDCSub}else{if(e===Q.LOSSY)return this.lossyDC;if(e===Q.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,l=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&l.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new $u({answer:s?Jr({sdp:s.sdp,type:s.type}):void 0,offer:a?Jr({sdp:a.sdp,type:a.type}):void 0,subscription:new Mr({trackSids:l,subscribe:!o,participantTracks:[]}),publishTracks:yT(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Yu({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(Q.LOSSY),at.PUBLISHER),t(this.dataChannelForKind(Q.RELIABLE),at.PUBLISHER),t(this.dataChannelForKind(Q.LOSSY,!0),at.SUBSCRIBER),t(this.dataChannelForKind(Q.RELIABLE,!0),at.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ae.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){We()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){We()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class qn extends Error{}function tS(n){return n!==void 0&&n>13}function nS(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class yo{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 Ka(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return y(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(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),$.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return y(this,void 0,void 0,function*(){const t=yield fetch("".concat(iS(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new re("Could not fetch region settings: ".concat(t.statusText),t.status===401?X.NotAllowed:X.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function iS(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class wh{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class rS extends wh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>y(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s=new Set;try{for(var a=!0,o=qt(this),l;l=yield o.next(),e=l.done,!e;a=!0){r=l.value,a=!1;const c=r;s.add(c)}}catch(c){t={error:c}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class sS extends wh{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Yr(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>y(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:t.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s="";try{for(var a=!0,o=qt(this),l;l=yield o.next(),e=l.done,!e;a=!0)r=l.value,a=!1,s+=r}catch(c){t={error:c}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return s})}}class _h{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return y(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 aS extends _h{}class oS extends _h{}class Eh extends P{constructor(e,t,i,r,s){super(e,i,s),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.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(A.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return y(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(),po)),kT()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(A.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class cS extends Eh{constructor(e,t,i,r,s,a){super(e,t,P.Kind.Audio,i,a),this.monitorReceiver=()=>y(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=Qr(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;St()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(St())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return y(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(qa(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&qa(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,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 i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(A.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(A.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,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 y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const ko=100;class lS extends Eh{constructor(e,t,i,r,s){super(e,t,P.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>y(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Qr(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=lo(()=>{this.updateDimensions()},ko),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Vn(this._mediaStreamTrack,t):jn(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 uS(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(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,l)=>Math.max(o,l.visibilityChangedAt||0),0),r=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,s=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!r||s;if(this.lastVisible!==a){if(!a&&Date.now()-i<ko){Ae.setTimeout(()=>{this.updateVisibility()},ko);return}this.lastVisible=a,this.emit(A.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,l=a.height()*s;o+l>i+r&&(i=o,r=l)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(A.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?$d():t||($d()>2?2:1)}}class uS{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:a}=i;s===this.element&&(this.isIntersecting=a,this.isPiP=Si(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Si(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Si(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??To(e),this.isPiP=We()&&Si(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=To(this.element),this.isPiP=Si(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Xd().observe(this.element),Yd().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=Xd())===null||e===void 0||e.unobserve(this.element),(t=Yd())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Si(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?To(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function To(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:l}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!o&&l!=="none"}class It extends Tt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=$e.NONE,this.log=$,this.handleMuted=()=>{this.emit(A.Muted)},this.handleUnmuted=()=>{this.emit(A.Unmuted)},this.log=Et((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:ot.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=P.Source.Unknown}setTrack(e){this.track&&(this.track.off(A.Muted,this.handleMuted),this.track.off(A.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(A.Muted,this.handleMuted),e.on(A.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),te(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==$e.NONE}get audioTrack(){if(Rt(this.track))return this.track}get videoTrack(){if(zn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=P.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===P.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={}))})(It||(It={}));class So extends It{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(A.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(A.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(A.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 y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Rt(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(st.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(st.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(st.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(st.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(st.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(st.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ns(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=ih(n);let a=s.audio,o=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),n.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},t=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},t=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const l=Zd(s,fh,ph),c=no(l),u=navigator.mediaDevices.getUserMedia(c);s.audio&&(Pe.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("audioinput"))),s.video&&(Pe.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>y(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?l.audio:l.video;(typeof g=="boolean"||!g)&&(g={});let m;const v=f?c.audio:c.video;typeof v!="boolean"&&(m=v);const b=h.getSettings().deviceId;m!=null&&m.deviceId&&Jt(m.deviceId)!==b?m.deviceId=b:m||(m={deviceId:b});const S=VT(h,m,e);return S.kind===P.Kind.Video?S.source=P.Source.Camera:S.kind===P.Kind.Audio&&(S.source=P.Source.Microphone),S.mediaStream=d,Rt(S)&&i?yield S.setProcessor(i):zn(S)&&r&&(yield S.setProcessor(r)),S})))}catch(d){if(!t)throw d;return ns(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function dS(n){return y(this,void 0,void 0,function*(){return(yield ns({audio:!1,video:n??!0}))[0]})}function hS(n){return y(this,void 0,void 0,function*(){return(yield ns({audio:n??!0,video:!1}))[0]})}var en;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(en||(en={}));function fS(n){switch(n){case pi.EXCELLENT:return en.Excellent;case pi.GOOD:return en.Good;case pi.POOR:return en.Poor;case pi.LOST:return en.Lost;default:return en.Unknown}}class Ph extends Tt.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===Lr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Dn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Lr.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=en.Unknown,this.log=$,this.log=Et((l=a==null?void 0:a.loggerName)!==null&&l!==void 0?l:ot.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}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 Ja,this.once(L.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(P.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(P.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(P.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===Dn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Dn.ACTIVE&&this.emit(L.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(L.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(L.ParticipantNameChanged,e)}_setAttributes(e){const t=TT(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(L.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const l=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(L.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(L.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=fS(e),t!==this._connectionQuality&&this.emit(L.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=>Rt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(A.Muted,()=>{this.emit(L.TrackMuted,e)}),e.on(A.Unmuted,()=>{this.emit(L.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case P.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case P.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function pS(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new qu({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}const Rh=15e3;class mS extends Ph{constructor(e,t,i,r,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=$e.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ja)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(l=>this.log.warn(l.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:l,message:c}=a,u=this.pendingSignalRequests.get(o);u&&(l!==wa.OK&&u.reject(new Vd(c,l)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,l=null,c=null;o.value.case==="payload"?l=o.value.value:o.value.case==="error"&&(c=me.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,l,c);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>pS(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),te(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),te(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),te(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>y(this,void 0,void 0,function*(){var o,l,c,u,d,h;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var g=!0,m=qt(b),v;v=yield m.next(),o=v.done,!o;g=!0){u=v.value,g=!1;const S=u;Zk(S)&&(this.log.debug("publish ".concat(S," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),te(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,S,f.options))}}catch(S){l={error:S}}finally{try{!g&&!o&&(c=m.return)&&(yield c.call(m))}finally{if(l)throw l.error}}}else a.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>y(this,void 0,void 0,function*(){if(a.source===P.Source.ScreenShare||a.source===P.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),te(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(gn(a)||Qt(a))try{if(We())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===P.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),te(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),te(a))),gn(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),te(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==$e.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,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.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 y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return y(this,arguments,void 0,function(t){var i=this;let{metadata:r,name:s,attributes:a}=t;return function*(){return new Promise((o,l)=>y(i,void 0,void 0,function*(){var c,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{l(g),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(g=>{let[m,v]=g;return this.attributes[m]===v||v===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),o();return}yield Ge(50)}l(new Vd("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(P.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(P.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(P.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(L.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?$e.GCM:$e.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,r){return y(this,void 0,void 0,function*(){var s,a;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 l;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 P.Source.Camera:l=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case P.Source.Microphone:l=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case P.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Pt(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(L.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const d of l)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),te(d))),c.push(this.publishTrack(d,r));[o]=yield Promise.all(c)}catch(c){throw l==null||l.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===P.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const l=this.getTrackPublication(P.Source.ScreenShareAudio);l&&l.track&&this.unpublishTrack(l.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return y(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(P.Source.Camera)||this.pendingPublishing.has(P.Source.Microphone))){this.pendingPublishing.add(P.Source.Camera),this.pendingPublishing.add(P.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(P.Source.Camera),this.pendingPublishing.delete(P.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const r=Zd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield ns(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Rt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=P.Source.Microphone,this.emit(L.AudioStreamAcquired)),zn(o)&&(this.cameraError=void 0,o.source=P.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return y(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Da("getDisplayMedia not supported");e.resolution===void 0&&!sT()&&(e.resolution=Wa.h1080fps30.resolution);const t=bT(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new Pt("no video track found");const s=new ts(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=P.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(L.AudioStreamAcquired);const o=new Zr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=P.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return y(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,l,c,u;gn(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),Wn(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case P.Source.Microphone:b="audioinput";break;case P.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Zr(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new ts(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Pt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),te(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(l=r==null?void 0:r.forceStereo)!==null&&l!==void 0?l:f;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),te(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=r.dtx)!==null&&c!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const m=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!aT()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),m.simulcast=!1),m.source&&(i.source=m.source);const v=new Promise((b,S)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ce.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:te(i)}));const x=()=>y(this,void 0,void 0,function*(){try{const k=yield this.publish(i,m,g);b(k)}catch(k){S(k)}});setTimeout(()=>{this.engine.off(N.SignalConnected,x),S(new Ba("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(N.SignalConnected,x),this.engine.on(N.Closing,()=>{this.engine.off(N.SignalConnected,x),S(new Ba("publishing rejected as engine closed",499))})}else try{const x=yield this.publish(i,m,g);b(x)}catch(x){S(x)}}catch(x){S(x)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),te(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>ST(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),te(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var r,s,a,o,l,c,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new Ba("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(T=>Wn(e)&&T.source===e.source)&&e.source!==P.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),te(e))),t.stopMicTrackOnMute&&Rt(e)&&(e.stopOnMute=!0),e.source===P.Source.ScreenShare&&Gn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!nT()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!iT()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=uo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(T=>t.videoCodec===Xr(T.mime))||(t.videoCodec=Xr(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(A.Muted,this.onTrackMuted),e.on(A.Unmuted,this.onTrackUnmuted),e.on(A.Ended,this.handleTrackEnded),e.on(A.UpstreamPaused,this.onTrackUpstreamPaused),e.on(A.UpstreamResumed,this.onTrackUpstreamResumed),e.on(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new ka({cid:e.mediaStreamTrack.id,name:t.name,type:P.kindToProto(e.kind),muted:e.isMuted,source:P.sourceToProto(e.source),disableDtx:!(!((r=t.dtx)!==null&&r!==void 0)||r),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let b;if(e.kind===P.Kind.Video){let T={width:0,height:0};try{T=yield e.waitForDimensions()}catch{const _=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:bi.h720.resolution;T={width:_.width,height:_.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{dims:T}))}v.width=T.width,v.height=T.height,Qt(e)&&(yi(m)&&(e.source===P.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),te(e))))),t.scalabilityMode=(l=t.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),v.simulcastCodecs=[new ya({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:uo}),t.backupCodec&&m!==t.backupCodec.codec&&v.encryption===$e.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new ya({codec:t.backupCodec.codec,cid:""})))),b=go(e.source===P.Source.ScreenShare,v.width,v.height,t),v.layers=Sh(v.width,v.height,b,yi(t.videoCodec))}else e.kind===P.Kind.Audio&&(b=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new _e("cannot publish track when not connected");const S=()=>y(this,void 0,void 0,function*(){var T,C,_;if(!this.engine.pcManager)throw new _e("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Qt(e)&&((T=t.degradationPreference)!==null&&T!==void 0||(t.degradationPreference=JT(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Gn()&&e.kind===P.Kind.Audio){let R;for(const I of this.engine.pcManager.publisher.getTransceivers())if(I.sender===e.sender){R=I;break}R&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:R,codec:"opus",maxbr:!((C=b[0])===null||C===void 0)&&C.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&yi(e.codec)&&(!((_=b[0])===null||_===void 0)&&_.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let x;if(this.enabledPublishVideoCodecs.length>0)x=(yield Promise.all([this.engine.addTrack(v),S()]))[0];else{x=yield this.engine.addTrack(v);let T;if(x.codecs.forEach(C=>{T===void 0&&(T=C.mimeType)}),T&&e.kind===P.Kind.Video){const C=Xr(T);C!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{codec:C})),t.videoCodec=C,b=go(e.source===P.Source.ScreenShare,v.width,v.height,t))}yield S()}const k=new So(e.kind,x,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return k.options=t,e.sid=x.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:x})),Qt(e)?e.startMonitor(this.engine.client):gn(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(L.LocalTrackPublished,k),k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==$e.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new Pt("track is not published");if(!Qt(e))throw new Pt("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=$T(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),te(e)));return}const l=e.addSimulcastTrack(t,o);if(!l)return;const c=new ka({cid:l.mediaStreamTrack.id,type:P.kindToProto(e.kind),muted:e.isMuted,source:P.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=Sh(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new _e("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,l,a,o),yield this.engine.negotiate()}),h=(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:h}))})}unpublishTrack(e,t){return y(this,void 0,void 0,function*(){var i,r;if(Wn(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),te(e))),yield c)}const s=this.getPublicationForTrack(e),a=s?te(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=s.track,e.off(A.Muted,this.onTrackMuted),e.off(A.Unmuted,this.onTrackUnmuted),e.off(A.Ended,this.handleTrackEnded),e.off(A.UpstreamPaused,this.onTrackUpstreamPaused),e.off(A.UpstreamResumed,this.onTrackUpstreamResumed),e.off(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const l=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<pe.FAILED&&l)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===l&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(l)&&(o=!0),Qt(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),a),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case P.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case P.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(L.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return y(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,a)=>y(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(l=>{l.track&&(t&&(l.options=Object.assign(Object.assign({},l.options),t)),o.push(l))}),yield Promise.all(o.map(l=>y(this,void 0,void 0,function*(){const c=l.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==P.Source.ScreenShare&&c.source!==P.Source.ScreenShareAudio&&(gn(c)||Qt(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:l.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,l.options,!0)}))),s()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?Q.RELIABLE:Q.LOSSY,a=r.destinationIdentities,o=r.topic,l=new Ve({kind:s,value:{case:"user",value:new _u({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(l,s)}()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new Ve({kind:Q.RELIABLE,value:{case:"sipDtmf",value:new Eu({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Q.RELIABLE)})}sendChatMessage(e,t){return y(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new Ve({value:{case:"chatMessage",value:new fa(Object.assign(Object.assign({},i),{timestamp:ue.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Q.RELIABLE),this.emit(L.ChatMessage,i),i})}editChatMessage(e,t){return y(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Ve({value:{case:"chatMessage",value:new fa(Object.assign(Object.assign({},i),{timestamp:ue.parse(i.timestamp),editTimestamp:ue.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Q.RELIABLE),this.emit(L.ChatMessage,i),i})}sendText(e,t){return y(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),l=new Array(o?o.length+1:1).fill(0),c=(d,h)=>{var f;l[h]=d;const g=l.reduce((m,v)=>m+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},u=yield this.streamText({streamId:r,totalSize:a,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((d,h)=>y(this,void 0,void 0,function*(){return this._sendFile(o[h],d,{topic:t.topic,mimeType:d.type,onProgress:f=>{c(f,h+1)}})})))),u.info})}streamText(e){return y(this,void 0,void 0,function*(){var t,i;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new ma({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:mn(s.timestamp),totalLength:mn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Bu({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"?pa.UPDATE:pa.CREATE})}}),o=e==null?void 0:e.destinationIdentities,l=new Ve({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,Q.RELIABLE);let c=0;const u=this,d=new WritableStream({write(g){return y(this,void 0,void 0,function*(){for(const m of gT(g,Rh)){yield u.engine.waitForBufferStatusLow(Q.RELIABLE);const v=new ga({content:m,streamId:r,chunkIndex:mn(c)}),b=new Ve({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,Q.RELIABLE),c+=1}})},close(){return y(this,void 0,void 0,function*(){const g=new va({streamId:r}),m=new Ve({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield u.engine.sendDataPacket(m,Q.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(N.Closing,h);const f=new aS(d,s,()=>this.engine.off(N.Closing,h));return f})}sendFile(e,t){return y(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return y(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:l}=yield a.read();if(o)break;yield s.write(l)}return yield s.close(),s.info})}streamBytes(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},u=new ma({totalLength:mn((a=c.size)!==null&&a!==void 0?a:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:mn(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Fu({name:c.name})}}),d=new Ve({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,Q.RELIABLE);let h=0;const f=new Fe,g=this.engine,m=this.log,v=new WritableStream({write(S){return y(this,void 0,void 0,function*(){const x=yield f.lock();let k=0;try{for(;k<S.byteLength;){const T=S.slice(k,k+Rh);yield g.waitForBufferStatusLow(Q.RELIABLE);const C=new Ve({destinationIdentities:l,value:{case:"streamChunk",value:new ga({content:T,streamId:o,chunkIndex:mn(h)})}});yield g.sendDataPacket(C,Q.RELIABLE),h+=1,k+=T.byteLength}}finally{x()}})},close(){return y(this,void 0,void 0,function*(){const S=new va({streamId:o}),x=new Ve({destinationIdentities:l,value:{case:"streamTrailer",value:S}});yield g.sendDataPacket(x,Q.RELIABLE)})},abort(S){m.error("Sink error:",S)}});return new oS(v,c)})}performRpc(e){return y(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:r,method:s,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>y(i,void 0,void 0,function*(){var d,h,f,g;if(fo(a)>mh){u(me.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||h===void 0)&&h.version&&pn((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){u(me.builtIn("UNSUPPORTED_SERVER"));return}const m=crypto.randomUUID();yield this.publishRpcRequest(r,m,s,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(m),u(me.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(b)},2e3);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(m),u(me.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(S,x)=>{clearTimeout(b),this.pendingAcks.has(m)&&(console.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(v)),x?u(x):c(S??"")},participantIdentity:r})}))}()})}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,i){const r=this.pendingResponses.get(e);r?(r.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=new Ve({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcRequest",value:new Pu({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,Q.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,me.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 i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),te(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(gn(r)||Qt(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return y(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[a]=s;return a.source===e});if(r)return r[1];yield Ge(20)}})}}class gS extends It{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ze.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(A.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Mr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Au({participantSid:"",trackSids:[this.trackSid]})]});this.emit(A.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?It.SubscriptionStatus.Unsubscribed:super.isSubscribed?It.SubscriptionStatus.Subscribed:It.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?It.PermissionStatus.Allowed:It.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,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(eo(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&eo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(A.VisibilityChanged,this.handleVisibilityChange),r.off(A.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(A.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(A.VisibilityChanged,this.handleVisibilityChange),e.on(A.Ended,this.handleEnded),this.emit(A.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(A.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?A.Muted:A.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(A.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(A.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===P.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 eo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Vu({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=Ze.HIGH,this.emit(A.UpdateSettings,e)}}class is extends Ph{static fromParticipantInfo(e,t,i){return new is(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Lr.STANDARD;super(t,i||"",r,s,a,o,l),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(A.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),te(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(A.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(A.SubscriptionPermissionChanged,t=>{this.emit(L.TrackSubscriptionPermissionChanged,e,t)}),e.on(A.SubscriptionStatusChanged,t=>{this.emit(L.TrackSubscriptionStatusChanged,e,t)}),e.on(A.Subscribed,t=>{this.emit(L.TrackSubscribed,t,e)}),e.on(A.Unsubscribed,t=>{this.emit(L.TrackUnsubscribed,t,e)}),e.on(A.SubscriptionFailed,t=>{this.emit(L.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]:P.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:P.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(L.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-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),te(o))),this.emit(L.TrackSubscriptionFailed,t);return}const l=e.kind==="video";let c;return l?c=new lS(e,t,r,s):c=new cS(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Za(c)&&Rt(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,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const l=P.kindFromProto(r.type);if(!l)return;o=new gS(l,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==P.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:te(c),newTrack:te(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),te(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(L.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case P.Kind.Audio:this.audioTrackPublications.delete(e);break;case P.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(L.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Rt(i.track)&&Za(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Z;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Z||(Z={}));const vS=4*1e3;class Kn extends Tt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=Z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=$,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=(a,o,l)=>y(this,void 0,void 0,function*(){var c;if(!rT())throw St()?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===Z.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(Z.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ka(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new yo(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,g,m)=>y(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const S=new AbortController;this.abortController=S,u==null||u();try{yield this.attemptConnection(m??a,o,l,S),this.abortController=void 0,f()}catch(x){if(this.regionUrlProvider&&x instanceof re&&x.reason!==X.Cancelled&&x.reason!==X.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(T){if(T instanceof re&&(T.status===401||T.reason===X.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(T);return}}k&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield d(f,g,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Qd(x)),g(x))}else{let k=rt.UNKNOWN_REASON;x instanceof re&&(k=Qd(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),g(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ja((f,g)=>{d(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,l,c,u,d)=>y(this,void 0,void 0,function*(){var h,f,g;const m=yield l.join(a,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},d.signal);let v=m.serverInfo;if(v||(v={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[S,x]=b;return"".concat(S,": ").concat(x)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(f=m.room)===null||f===void 0?void 0:f.sid,identity:(g=m.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new Wk("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,l,c)=>y(this,void 0,void 0,function*(){var u,d;this.state===Z.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(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ho),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new re("could not establish signal connection",X.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof re&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new re("Connection attempt aborted",X.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}We()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),We()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Z.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),l=0;l<a;l++)o[l]=arguments[l];return y(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,g;const m=yield c.disconnectLock.lock();try{if(c.state===Z.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===Z.Connecting||c.state===Z.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(d=c.abortController)===null||d===void 0||d.abort(),(f=(h=c.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new re("Client initiated disconnect",X.Cancelled)),c.connectFuture=void 0),!((g=c.engine)===null||g===void 0)&&g.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,rt.CLIENT_INITIATED),c.engine=void 0}finally{m()}}()})},this.onPageLeave=()=>y(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>y(this,void 0,void 0,function*(){const a=[],o=ct();if(o&&o.os==="iOS"){const l="livekit-dummy-audio-el";let c=document.getElementById(l);if(!c){c=document.createElement("audio"),c.id=l,c.autoplay=!0,c.hidden=!0;const u=Xa();u.enabled=!0;const d=new MediaStream([u]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,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(O.Disconnected,()=>{c==null||c.remove(),c=null})}a.push(c)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(l=>{var c;(c=l.track)===null||c===void 0||c.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.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 a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=a=>y(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);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:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(Z.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var l;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(l=this.sidToIdentity.get(o.sid))!==null&&l!==void 0?l:"");let c=this.remoteParticipants.get(o.identity);o.state===Dn.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],l={};a.forEach(c=>{if(l[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))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{l[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{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)}),a.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 l=Array.from(o.values());l.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(O.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const l=this.getRemoteParticipantBySid(o.participantSid);if(!l)return;const c=l.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=P.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,l.emit(L.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,c,c.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const l=o.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(a.trackSid));if(!o)return;const l=o.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const l=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(a,o,l)=>{this.emit(O.DataReceived,o.payload,a,l,o.topic),a==null||a.emit(L.DataReceived,o.payload,l)},this.handleSipDtmf=(a,o)=>{this.emit(O.SipDTMFReceived,o,a),a==null||a.emit(L.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const l=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=l==null?void 0:l.trackPublications.get(o.trackId),u=hT(o,this.transcriptionReceivedTimes);c==null||c.emit(A.TranscriptionReceived,u),l==null||l.emit(L.TranscriptionReceived,u,c),this.emit(O.TranscriptionReceived,u,l,c)},this.handleChatMessage=(a,o)=>{const l=fT(o);this.emit(O.ChatMessage,l,a)},this.handleMetrics=(a,o)=>{this.emit(O.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,l;const c=Pe.getInstance().previousDevices,u=yield Pe.getInstance().getDevices(void 0,!1),d=ct();if((d==null?void 0:d.name)==="Chrome"&&d.os!=="iOS")for(let f of u){const g=c.find(m=>m.deviceId===f.deviceId);g&&g.label!==""&&g.kind===f.kind&&g.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(O.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const g=vT(f),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(S=>S.kind===f),b=this.getActiveDevice(f);if(b===((o=c.filter(S=>S.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((l=v[0])===null||l===void 0?void 0:l.deviceId)!==b){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Xt()||f==="videoinput"||v.length>0&&!v.find(S=>S.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const l=this.getRemoteParticipantBySid(o.participantSid);l&&l.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(O.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(O.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(O.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(O.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(O.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>y(this,void 0,void 0,function*(){var o,l,c,u,d,h;(o=a.track)===null||o===void 0||o.on(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(A.Restarted,this.onLocalTrackRestarted),(d=(u=(c=a.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(O.LocalTrackPublished,a,this.localParticipant),gn(a.track)&&(yield a.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=nh(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(O.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,l;(o=a.track)===null||o===void 0||o.off(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(A.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),l=nh(a.source);l&&o&&o!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,o),this.emit(O.ActiveDeviceChanged,l,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(O.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(O.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(O.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(O.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},BT),e),this.log=Et((i=this.options.loggerName)!==null&&i!==void 0?i:ot.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},fh),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ph),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},UT),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Fe,this.localParticipant=new mS("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Jt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Jt(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Jt(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),We()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Kn.cleanupRegistry&&Kn.cleanupRegistry.register(this,()=>{a.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,i,r,s,a){return y(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});fo(u)>mh?(l=me.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof me?l=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=me.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,l)})}setE2EEEnabled(e){return y(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 CT(this.options.e2ee),this.e2eeManager.on($t.ParticipantEncryptionStatusChanged,(t,i)=>{mT(i)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on($t.EncryptionError,t=>this.emit(O.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 y(this,void 0,void 0,function*(){return this.state===Z.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(N.RoomUpdate,i),e(r.sid))};this.engine.on(N.RoomUpdate,i),this.once(O.Disconnected,()=>{this.engine.off(N.RoomUpdate,i),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 eS(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,i)=>{this.onTrackAdded(e,t,i)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Z.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(N.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Z.Connected)&&this.emit(O.Reconnected)}).on(N.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.Offline,()=>{this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(O.Reconnecting)}).on(N.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(N.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(L.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}).on(N.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(O.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 Pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===Z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ka(new URL(e))&&t){this.regionUrlProvider=new yo(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Z.Disconnected&&(this.regionUrl=i,yield fetch(Qa(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Qa(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return y(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new kt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new kt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new kt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new kt({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new kt({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new kt({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new kt({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>y(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Dr({reason:rt.CLIENT_INITIATED,action:Bn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new kt({scenario:{case:"subscriberBandwidth",value:mn(t)}});break;case"leave-full-reconnect":r=new kt({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,l,c,u,d,h,f,g;let m=!0,v=!1;const b=a?{exact:r}:r;if(i==="audioinput"){v=s.localParticipant.audioTrackPublications.size===0;const S=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===P.Source.Microphone);try{m=(yield Promise.all(x.map(k=>{var T;return(T=k.audioTrack)===null||T===void 0?void 0:T.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=S,k}}else if(i==="videoinput"){v=s.localParticipant.videoTrackPublications.size===0;const S=(l=s.getActiveDevice(i))!==null&&l!==void 0?l:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.videoTrackPublications.values()).filter(k=>k.source===P.Source.Camera);try{m=(yield Promise.all(x.map(k=>{var T;return(T=k.videoTrack)===null||T===void 0?void 0:T.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.videoCaptureDefaults.deviceId=S,k}}else if(i==="audiooutput"){if(!qa()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(c=yield Pe.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(g=s.options).audioOutput)!==null&&u!==void 0||(g.audioOutput={});const S=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(x=>x.setAudioOutput({deviceId:r})))}catch(x){throw s.options.audioOutput.deviceId=S,x}}return(v||i==="audiooutput")&&(s.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((f=s.options.audioOutput)===null||f===void 0?void 0:f.deviceId)||r),s.emit(O.ActiveDeviceChanged,i,r)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(L.AttributesChanged,this.onLocalAttributesChanged).on(L.TrackMuted,this.onLocalTrackMuted).on(L.TrackUnmuted,this.onLocalTrackUnmuted).on(L.LocalTrackPublished,this.onLocalTrackPublished).on(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(L.MediaDevicesError,this.onMediaDevicesError).on(L.AudioStreamAcquired,this.startAudio).on(L.ChatMessage,this.onLocalChatMessageSent).on(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Z.Connecting||this.state===Z.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,d)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,d);return}if(this.state===Z.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=tT(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const l=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),l.addSubscribedMediaTrack(e,o,t,i,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Z.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,a,o;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(a=r.track)===null||a===void 0||a.stop()):(o=r.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(L.AttributesChanged,this.onLocalAttributesChanged).off(L.TrackMuted,this.onLocalTrackMuted).off(L.TrackUnmuted,this.onLocalTrackUnmuted).off(L.LocalTrackPublished,this.onLocalTrackPublished).off(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(L.MediaDevicesError,this.onMediaDevicesError).off(L.AudioStreamAcquired,this.startAudio).off(L.ChatMessage,this.onLocalChatMessageSent).off(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),We()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Z.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return y(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Yr(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:l=>{s=l,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new rS(a,o,Yr(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:l=>{s=l,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new sS(a,o,Yr(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.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 i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return y(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=th())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ge(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(O.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=is.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new is(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,i),i.on(L.TrackPublished,r=>{this.emitWhenConnected(O.TrackPublished,r,i)}).on(L.TrackSubscribed,(r,s)=>{r.kind===P.Kind.Audio?(r.on(A.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(A.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===P.Kind.Video&&(r.on(A.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(A.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,r,s,i)}).on(L.TrackUnpublished,r=>{this.emit(O.TrackUnpublished,r,i)}).on(L.TrackUnsubscribed,(r,s)=>{this.emit(O.TrackUnsubscribed,r,s,i)}).on(L.TrackMuted,r=>{this.emitWhenConnected(O.TrackMuted,r,i)}).on(L.TrackUnmuted,r=>{this.emitWhenConnected(O.TrackUnmuted,r,i)}).on(L.ParticipantMetadataChanged,r=>{this.emitWhenConnected(O.ParticipantMetadataChanged,r,i)}).on(L.ParticipantNameChanged,r=>{this.emitWhenConnected(O.ParticipantNameChanged,r,i)}).on(L.AttributesChanged,r=>{this.emitWhenConnected(O.ParticipantAttributesChanged,r,i)}).on(L.ConnectionQualityChanged,r=>{this.emitWhenConnected(O.ConnectionQualityChanged,r,i)}).on(L.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,r,i)}).on(L.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,r,s,i)}).on(L.TrackSubscriptionFailed,(r,s)=>{this.emit(O.TrackSubscriptionFailed,r,i,s)}).on(L.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,r,s,i)}).on(L.Active,()=>{this.emitWhenConnected(O.ParticipantActive,i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),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&&pT(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=Ae.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,rt.STATE_MISMATCH))):e=0},vS)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ae.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===Z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Z.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return y(this,void 0,void 0,function*(){var t,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ar({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ue.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new un({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(Z.Connected),r.video){const a=new So(P.Kind.Video,new Un({source:Ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO,name:"video-dummy"}),new ts(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Jd(160*((t=s.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(a),this.localParticipant.emit(L.LocalTrackPublished,a)}if(r.audio){const a=new So(P.Kind.Audio,new Un({source:Ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO}),new Zr(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Xa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(L.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new un({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Dn.ACTIVE,tracks:[],joinedAt:ue.parse(Date.now())});const l=this.getOrCreateParticipant(o.identity,o);if(s.video){const c=Jd(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Un({source:Ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const c=Xa(),u=new Un({source:Ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}l.updateInfo(o)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const s=Ih(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}Kn.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Ih(n){return n.map(e=>{if(e)return Array.isArray(e)?Ih(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var dt;(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"})(dt||(dt={}));class tn extends Tt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=dt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Kn(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==dt.IDLE)throw Error("check is running already");this.setStatus(dt.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!==dt.SKIPPED&&this.setStatus(this.isSuccess()?dt.SUCCESS:dt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return y(this,void 0,void 0,function*(){return this.room.state===Z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return y(this,void 0,void 0,function*(){this.room&&this.room.state!==Z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(dt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Ge(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 bS extends tn{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new yo(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return y(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,l=1e6/a,c="A".repeat(a),u=Date.now();for(let g=0;g<l;g++)yield s.write(c);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Co=1e4;class yS extends tn{get description(){return"Connection via UDP vs TCP"}perform(){return y(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 i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Co/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Co/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return y(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 i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();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},d=setInterval(()=>y(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Co)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class kS extends tn{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield hS();if(yield eh(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class TS extends tn{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield dS();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return y(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,l;const c=document.createElement("canvas"),u=e.getSettings(),d=(a=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(l=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&l!==void 0?l:720;c.width=d,c.height=h;const f=c.getContext("2d");f.drawImage(i,0,0);const m=f.getImageData(0,0,c.width,c.height).data;let v=!0;for(let b=0;b<m.length;b+=4)if(m[b]!==0||m[b+1]!==0||m[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),i.remove()})}}class SS extends tn{get description(){return"Resuming connection after interruption"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const l=t.engine.client.onClose;if(l&&l(""),yield a,i){if(!r||t.state!==Z.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 CS extends tn{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new ro,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,a=!1,o=!1;for(let l of r.iceServers)for(let c of l.urls)c.startsWith("turn:")?(a=!0,o=!0):c.startsWith("turns:")&&(a=!0,o=!0,s=!0),c.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class xS extends tn{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const a=new RTCIceCandidate(r);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(wS(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),$.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function wS(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 _S extends tn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return y(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ro;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===Nu.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class cx extends Tt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:dt.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!==dt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return y(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(_S)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(xS)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(CS)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(SS)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(kS)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(TS)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(yS);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(bS)})}}const ES=/\{[^{}]+\}/g;function PS(){return Math.random().toString(36).slice(2,11)}function RS(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=Lh(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:f=i,Request:g=t,headers:m,params:v={},parseAs:b="json",querySerializer:S,bodySerializer:x=s??OS,body:k,...T}=d||{};h&&(e=Lh(h));let C=typeof r=="function"?r:Nh(r);S&&(C=typeof S=="function"?S:Nh({...typeof r=="object"?r:{},...S}));const _=k===void 0?void 0:x(k),R=_===void 0||_ instanceof FormData?{}:{"Content-Type":"application/json"},I={redirect:"follow",...o,...T,body:_,headers:NS(R,a,m,v.header)};let M,D,j=new t(AS(u,{baseUrl:e,params:v,querySerializer:C}),I);for(const z in T)z in j||(j[z]=T[z]);if(l.length){M=PS(),D=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:C,bodySerializer:x});for(const z of l)if(z&&typeof z=="object"&&typeof z.onRequest=="function"){const W=await z.onRequest({request:j,schemaPath:u,params:v,options:D,id:M});if(W){if(!(W instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");j=W}}}let V=await f(j);if(l.length)for(let z=l.length-1;z>=0;z--){const W=l[z];if(W&&typeof W=="object"&&typeof W.onResponse=="function"){const F=await W.onResponse({request:j,response:V,schemaPath:u,params:v,options:D,id:M});if(F){if(!(F instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");V=F}}}if(V.status===204||V.headers.get("Content-Length")==="0")return V.ok?{data:{},response:V}:{error:{},response:V};if(V.ok)return b==="stream"?{data:V.body,response:V}:{data:await V[b](),response:V};let q=await V.text();try{q=JSON.parse(q)}catch{}return{error:q,response:V}}return{GET(u,d){return c(u,{...d,method:"GET"})},PUT(u,d){return c(u,{...d,method:"PUT"})},POST(u,d){return c(u,{...d,method:"POST"})},DELETE(u,d){return c(u,{...d,method:"DELETE"})},OPTIONS(u,d){return c(u,{...d,method:"OPTIONS"})},HEAD(u,d){return c(u,{...d,method:"HEAD"})},PATCH(u,d){return c(u,{...d,method:"PATCH"})},TRACE(u,d){return c(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");l.push(d)}},eject(...u){for(const d of u){const h=l.indexOf(d);h!==-1&&l.splice(h,1)}}}}function rs(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 Oh(n,e,t){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)i.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const a=i.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(const a in e){const o=t.style==="deepObject"?`${n}[${a}]`:a;i.push(rs(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Ah(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}const i={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(const s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(rs(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Nh(n){return function(t){const i=[];if(t&&typeof t=="object")for(const r in t){const s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;i.push(Ah(r,s,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof s=="object"){i.push(Oh(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(rs(r,s,n))}}return i.join("&")}}function IS(n,e){let t=n;for(const i of n.match(ES)??[]){let r=i.substring(1,i.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const o=e[r];if(Array.isArray(o)){t=t.replace(i,Ah(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,Oh(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${rs(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function OS(n){return n instanceof FormData?n:JSON.stringify(n)}function AS(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=IS(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function NS(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const i=t instanceof Headers?t.entries():Object.entries(t);for(const[r,s]of i)if(s===null)e.delete(r);else if(Array.isArray(s))for(const a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Lh(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Mh="Onboardee-Session-Token",Dh="OnboardeeSessionToken";class Uh{constructor(e){this.client=RS({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const i=window.localStorage.getItem(Dh);i&&t.headers.set(Mh,i)}return t},onResponse({response:t}){const i=t.headers.get(Mh);return i&&window.localStorage&&window.localStorage.setItem(Dh,i),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,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i},...r&&{course_id:r}}}})}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 getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}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:{content:t.content||""}})}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,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...i&&{limit:i.toString()}}}})}async updateProductKnowledgeBlock(e,t,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i}}}})}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 listAdminUsers(e){const t={};return e!=null&&e.search&&(t.search=e.search),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(t).length>0?{query:t}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,t,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:t,signal:i})}async deletePlanAutosave(e){return await this.client.DELETE("/api/plans/{id}/autosave",{params:{path:{id:e}}})}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,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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:{content:t.content||""}})}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,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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 i={token:e};return t!=null&&t.productId&&(i.product_id=t.productId),t!=null&&t.startDate&&(i.start_date=t.startDate),t!=null&&t.endDate&&(i.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:i}})}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:i}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...i&&{user:encodeURIComponent(i)}}}})}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}}})}async getGraphemes(){return await this.client.GET("/api/graphemes")}async listVoices(){return await this.client.GET("/api/voices")}async generateVoiceSample(e,t){return await this.client.POST("/api/voices/generate-sample",{body:{product_id:t,voice_id:e},parseAs:"stream"})}getClient(){return this.client}}const Bh="https://app.coragents.ai";class ss extends Cs{constructor(e,t,i,r){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=i,this.api=r.api||new Uh({baseUrl:Bh}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new Kn(s)),this.captureScreen=r.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("volume-check"),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(O.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(O.TrackSubscribed,i=>{i.kind==="audio"&&(i.attach(),i.source===P.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(i.mediaStream)))}),this.room.on(O.LocalTrackPublished,i=>{i.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(i.audioTrack.mediaStream))}),this.room.on(O.ParticipantAttributesChanged,i=>{if(!i["lk.agent.state"])return;const r=i["lk.agent.state"];switch(r){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",r)}}),this.room.on(O.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),s=JSON.parse(r);switch(s.status||s.request||s.type){case"course_progress":typeof s.current_step=="number"&&typeof s.total_steps=="number"&&Array.isArray(s.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,s.current_step),totalSteps:Math.max(1,s.total_steps),stepNames:s.step_names});break;case"open_text_input":this.emit("textInputRequested");break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");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;case"transcript":this.emit("transcript",s.transcript,s.role);break;default:console.warn("[obi] unknown data received",s)}}catch(r){console.error("[obi] error parsing data",r)}}),this.room.localParticipant.registerRpcMethod("mic_check",async i=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async i=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let r=null,s=null;try{r=await this.captureScreen()}catch(a){r=null,a=a}if(!r||s)return console.error("[obi] error capturing screen",{error:s}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(a){return console.error("[obi] error sending screen capture",{error:a}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let i=0;i<9&&!(this.room.state===Z.Connected&&this.room.remoteParticipants.size>=1);i++)await new Promise(r=>setTimeout(r,1e3));if(!(this.room.state===Z.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 i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?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(i){i=i,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,i;e.handleMuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,i;e.handleUnmuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.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 i=e.context.sampleRate/2/e.frequencyBinCount,r=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(r);const s=[],a=50,o=5e3,l=8,c=Math.pow(o/a,1/l);for(let u=0;u<l;u++){const d=a*Math.pow(c,u),h=a*Math.pow(c,u+1),f=Math.floor(d/i),g=Math.floor(h/i),m=Math.min(g,r.length),v=Math.min(f,m);if(v<m){const b=r.slice(v,m).reduce((S,x)=>S+x,0)/(m-v)/255;s.push(b)}else s.push(0)}return s}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,i,r={}){const s=JSON.parse(e),a=new ss(t,s.planId,i,r);return a.state=s.state,a.speakingState=s.speakingState,a.identity=s.identity||null,a.isPaused=s.isPaused||!1,a.sessionUuid=s.sessionUuid||null,a.roomId=s.roomId||null,a.joinToken=s.joinToken||null,a.roomUrl=s.roomUrl||null,a.startedAt=s.startedAt||null,a}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,i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,i}}class as extends Cs{constructor(e,t,i={}){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=i.api||new Uh({baseUrl:i.apiBaseUrl||Bh}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new ss(r,s,a,o)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var t,i,r,s,a;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=((i=o.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=o.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((s=o.data)==null?void 0:s.plan_is_completed)||[],this.showWidget=((a=o.data)==null?void 0:a.show_widget)||!1,e.planUuid){let l=null;try{const c=await this.api.getPlanSDK(e.planUuid);if(c.error)throw new Error(`Plan not found: ${c.error}`);c.data&&(l=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&&(l=u.data)}catch(u){console.error("[obi] error getting plan via both endpoints",{planErr:c,sessionErr:u})}}l?(this.selectedPlan=l,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(i=>{this.session=null,console.error("[obi] error starting session",i)}),this.session}async resumeSession(e){var t,i;return this.state,(t=this.session)==null||t.state,(i=this.session)==null||i.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(r=>{console.error("[obi] error joining room",{error:r}),r instanceof Error&&r.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 i,r,s;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const a=this.plans.findIndex(o=>{var l;return o.uuid===((l=this.selectedPlan)==null?void 0:l.uuid)});a!==-1&&(this.planIsCompleted[a]=!0)}(s=(r=this.session)==null?void 0:r.removeAllListeners)==null||s.call(r),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,i,r={}){const s=JSON.parse(e);if(s.serialisedAt){const o=new Date(s.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)return null}else throw new Error("Client was not serialised, assuming it's dead.");const a=new as(t,i,r);return a.state=s.state,a.identity=s.identity||null,a.product=s.product||null,a.plans=s.plans||[],a.selectedPlan=s.selectedPlan||null,a.selectedPlanUuid=s.selectedPlanUuid||null,a.showWidget=s.showWidget||!1,s.session&&(a.session=ss.deserialise(s.session,t,i,{api:a.api})),a}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var i,r,s;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(s=this.session)==null?void 0:s.sessionUuid})}}var os,H,Fh,vn,jh,Vh,Gh,Wh,xo,wo,_o,zh,Ci={},Hh=[],LS=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,xi=Array.isArray;function Ot(n,e){for(var t in e)n[t]=e[t];return n}function Eo(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Po(n,e,t){var i,r,s,a={};for(s in e)s=="key"?i=e[s]:s=="ref"?r=e[s]:a[s]=e[s];if(arguments.length>2&&(a.children=arguments.length>3?os.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return cs(n,a,i,r,null)}function cs(n,e,t,i,r){var s={type:n,props:e,key:t,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++Fh,__i:-1,__u:0};return r==null&&H.vnode!=null&&H.vnode(s),s}function Me(n){return n.children}function At(n,e){this.props=n,this.context=e}function $n(n,e){if(e==null)return n.__?$n(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"?$n(n):null}function qh(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 qh(n)}}function Ro(n){(!n.__d&&(n.__d=!0)&&vn.push(n)&&!ls.__r++||jh!=H.debounceRendering)&&((jh=H.debounceRendering)||Vh)(ls)}function ls(){for(var n,e,t,i,r,s,a,o=1;vn.length;)vn.length>o&&vn.sort(Gh),n=vn.shift(),o=vn.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=Ot({},i)).__v=i.__v+1,H.vnode&&H.vnode(t),Io(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??$n(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,Jh(s,t,a),t.__e!=r&&qh(t)));ls.__r=0}function Kh(n,e,t,i,r,s,a,o,l,c,u){var d,h,f,g,m,v,b=i&&i.__k||Hh,S=e.length;for(l=MS(t,e,b,l,S),d=0;d<S;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?Ci:b[f.__i]||Ci,f.__i=d,v=Io(n,f,h,r,s,a,o,l,c,u),g=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Oo(h.ref,null,f),u.push(f.ref,f.__c||g,f)),m==null&&g!=null&&(m=g),4&f.__u||h.__k===f.__k?l=$h(f,l,n):typeof f.type=="function"&&v!==void 0?l=v:g&&(l=g.nextSibling),f.__u&=-7);return t.__e=m,l}function MS(n,e,t,i,r){var s,a,o,l,c,u=t.length,d=u,h=0;for(n.__k=new Array(r),s=0;s<r;s++)(a=e[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(l=s+h,(a=n.__k[s]=typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?cs(null,a,null,null,null):xi(a)?cs(Me,{children:a},null,null,null):a.constructor==null&&a.__b>0?cs(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=n,a.__b=n.__b+1,o=null,(c=a.__i=DS(a,t,l,d))!=-1&&(d--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(r>u?h--:r<u&&h++),typeof a.type!="function"&&(a.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,a.__u|=4))):n.__k[s]=null;if(d)for(s=0;s<u;s++)(o=t[s])!=null&&!(2&o.__u)&&(o.__e==i&&(i=$n(o)),Zh(o,o));return i}function $h(n,e,t){var i,r;if(typeof n.type=="function"){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,e=$h(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=$n(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function us(n,e){return e=e||[],n==null||typeof n=="boolean"||(xi(n)?n.some(function(t){us(t,e)}):e.push(n)),e}function DS(n,e,t,i){var r,s,a=n.key,o=n.type,l=e[t];if(l===null&&n.key==null||l&&a==l.key&&o==l.type&&!(2&l.__u))return t;if(i>(l!=null&&!(2&l.__u)?1:0))for(r=t-1,s=t+1;r>=0||s<e.length;){if(r>=0){if((l=e[r])&&!(2&l.__u)&&a==l.key&&o==l.type)return r;r--}if(s<e.length){if((l=e[s])&&!(2&l.__u)&&a==l.key&&o==l.type)return s;s++}}return-1}function Yh(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||LS.test(e)?t:t+"px"}function ds(n,e,t,i,r){var s;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof i=="string"&&(n.style.cssText=i=""),i)for(e in i)t&&e in t||Yh(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||Yh(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Wh,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+s]=t,t?i?t.u=i.u:(t.u=xo,n.addEventListener(e,s?_o:wo,s)):n.removeEventListener(e,s?_o:wo,s);else{if(r=="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 Xh(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=xo++;else if(e.t<t.u)return;return t(H.event?H.event(e):e)}}}function Io(n,e,t,i,r,s,a,o,l,c){var u,d,h,f,g,m,v,b,S,x,k,T,C,_,R,I,M,D=e.type;if(e.constructor!=null)return null;128&t.__u&&(l=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=H.__b)&&u(e);e:if(typeof D=="function")try{if(b=e.props,S="prototype"in D&&D.prototype.render,x=(u=D.contextType)&&i[u.__c],k=u?x?x.props.value:u.__:i,t.__c?v=(d=e.__c=t.__c).__=d.__E:(S?e.__c=d=new D(b,k):(e.__c=d=new At(b,k),d.constructor=D,d.render=BS),x&&x.sub(d),d.props=b,d.state||(d.state={}),d.context=k,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),S&&d.__s==null&&(d.__s=d.state),S&&D.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Ot({},d.__s)),Ot(d.__s,D.getDerivedStateFromProps(b,d.__s))),f=d.props,g=d.state,d.__v=e,h)S&&D.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),S&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(S&&D.getDerivedStateFromProps==null&&b!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,k),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,k)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(j){j&&(j.__=e)}),T=0;T<d._sb.length;T++)d.__h.push(d._sb[T]);d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,k),S&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,g,m)})}if(d.context=k,d.props=b,d.__P=n,d.__e=!1,C=H.__r,_=0,S){for(d.state=d.__s,d.__d=!1,C&&C(e),u=d.render(d.props,d.state,d.context),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[]}else do d.__d=!1,C&&C(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++_<25);d.state=d.__s,d.getChildContext!=null&&(i=Ot(Ot({},i),d.getChildContext())),S&&!h&&d.getSnapshotBeforeUpdate!=null&&(m=d.getSnapshotBeforeUpdate(f,g)),I=u,u!=null&&u.type===Me&&u.key==null&&(I=Qh(u.props.children)),o=Kh(n,xi(I)?I:[I],e,t,i,r,s,a,o,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),v&&(d.__E=d.__=null)}catch(j){if(e.__v=null,l||s!=null)if(j.then){for(e.__u|=l?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,e.__e=o}else for(M=s.length;M--;)Eo(s[M]);else e.__e=t.__e,e.__k=t.__k;H.__e(j,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=US(t.__e,e,t,i,r,s,a,l,c);return(u=H.diffed)&&u(e),128&e.__u?void 0:o}function Jh(n,e,t){for(var i=0;i<t.length;i++)Oo(t[i],t[++i],t[++i]);H.__c&&H.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){H.__e(s,r.__v)}})}function Qh(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:xi(n)?n.map(Qh):Ot({},n)}function US(n,e,t,i,r,s,a,o,l){var c,u,d,h,f,g,m,v=t.props,b=e.props,S=e.type;if(S=="svg"?r="http://www.w3.org/2000/svg":S=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((f=s[c])&&"setAttribute"in f==!!S&&(S?f.localName==S:f.nodeType==3)){n=f,s[c]=null;break}}if(n==null){if(S==null)return document.createTextNode(b);n=document.createElementNS(r,S,b.is&&b),o&&(H.__m&&H.__m(e,s),o=!1),s=null}if(S==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&os.call(n.childNodes),v=t.props||Ci,!o&&s!=null)for(v={},c=0;c<n.attributes.length;c++)v[(f=n.attributes[c]).name]=f.value;for(c in v)if(f=v[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=f;else if(!(c in b)){if(c=="value"&&"defaultValue"in b||c=="checked"&&"defaultChecked"in b)continue;ds(n,c,null,f,r)}}for(c in b)f=b[c],c=="children"?h=f:c=="dangerouslySetInnerHTML"?u=f:c=="value"?g=f:c=="checked"?m=f:o&&typeof f!="function"||v[c]===f||ds(n,c,f,v[c],r);if(u)o||d&&(u.__html==d.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(d&&(n.innerHTML=""),Kh(e.type=="template"?n.content:n,xi(h)?h:[h],e,t,i,S=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&$n(t,0),o,l),s!=null)for(c=s.length;c--;)Eo(s[c]);o||(c="value",S=="progress"&&g==null?n.removeAttribute("value"):g!=null&&(g!==n[c]||S=="progress"&&!g||S=="option"&&g!=v[c])&&ds(n,c,g,v[c],r),c="checked",m!=null&&m!=n[c]&&ds(n,c,m,v[c],r))}return n}function Oo(n,e,t){try{if(typeof n=="function"){var i=typeof n.__u=="function";i&&n.__u(),i&&e==null||(n.__u=n(e))}else n.current=e}catch(r){H.__e(r,t)}}function Zh(n,e,t){var i,r;if(H.unmount&&H.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||Oo(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){H.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&Zh(i[r],e,t||typeof n.type!="function");t||Eo(n.__e),n.__c=n.__=n.__e=void 0}function BS(n,e,t){return this.constructor(n,t)}function FS(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),H.__&&H.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Io(e,n=(!i&&t||e).__k=Po(Me,null,[n]),r||Ci,Ci,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?os.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),Jh(s,n,a)}function jS(n){function e(t){var i,r;return this.getChildContext||(i=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&i.forEach(function(a){a.__e=!0,Ro(a)})},this.sub=function(s){i.add(s);var a=s.componentWillUnmount;s.componentWillUnmount=function(){i&&i.delete(s),a&&a.call(s)}}),t.children}return e.__c="__cC"+zh++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}os=Hh.slice,H={__e:function(n,e,t,i){for(var r,s,a;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(n)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,i||{}),a=r.__d),a)return r.__E=r}catch(o){n=o}throw n}},Fh=0,At.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ot({},this.state),typeof n=="function"&&(n=n(Ot({},t),this.props)),n&&Ot(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Ro(this))},At.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Ro(this))},At.prototype.render=Me,vn=[],Vh=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Gh=function(n,e){return n.__v.__b-e.__v.__b},ls.__r=0,Wh=/(PointerCapture)$|Capture$/i,xo=0,wo=Xh(!1),_o=Xh(!0),zh=0;var VS=0;function p(n,e,t,i,r,s){e||(e={});var a,o,l=e;if("ref"in l)for(o in l={},e)o=="ref"?a=e[o]:l[o]=e[o];var c={type:n,props:l,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--VS,__i:-1,__u:0,__source:r,__self:s};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)l[o]===void 0&&(l[o]=a[o]);return H.vnode&&H.vnode(c),c}var bn,de,Ao,ef,wi=0,tf=[],ke=H,nf=ke.__b,rf=ke.__r,sf=ke.diffed,af=ke.__c,of=ke.unmount,cf=ke.__;function _i(n,e){ke.__h&&ke.__h(de,n,wi||e),wi=0;var t=de.__H||(de.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function Y(n){return wi=1,GS(df,n)}function GS(n,e,t){var i=_i(bn++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):df(void 0,e),function(o){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,o);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=de,!de.__f)){var r=function(o,l,c){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!s||s.call(this,o,l,c);var d=i.__c.props!==o;return u.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(d=!0)}}),s&&s.call(this,o,l,c)||d};de.__f=!0;var s=de.shouldComponentUpdate,a=de.componentWillUpdate;de.componentWillUpdate=function(o,l,c){if(this.__e){var u=s;s=void 0,r(o,l,c),s=u}a&&a.call(this,o,l,c)},de.shouldComponentUpdate=r}return i.__N||i.__}function ze(n,e){var t=_i(bn++,3);!ke.__s&&Mo(t.__H,e)&&(t.__=n,t.u=e,de.__H.__h.push(t))}function hs(n,e){var t=_i(bn++,4);!ke.__s&&Mo(t.__H,e)&&(t.__=n,t.u=e,de.__h.push(t))}function Ct(n){return wi=5,No(function(){return{current:n}},[])}function No(n,e){var t=_i(bn++,7);return Mo(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function WS(n,e){return wi=8,No(function(){return n},e)}function lf(n){var e=de.context[n.__c],t=_i(bn++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(de)),e.props.value):n.__}function zS(){for(var n;n=tf.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(fs),n.__H.__h.forEach(Lo),n.__H.__h=[]}catch(e){n.__H.__h=[],ke.__e(e,n.__v)}}ke.__b=function(n){de=null,nf&&nf(n)},ke.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),cf&&cf(n,e)},ke.__r=function(n){rf&&rf(n),bn=0;var e=(de=n.__c).__H;e&&(Ao===de?(e.__h=[],de.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(fs),e.__h.forEach(Lo),e.__h=[],bn=0)),Ao=de},ke.diffed=function(n){sf&&sf(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(tf.push(e)!==1&&ef===ke.requestAnimationFrame||((ef=ke.requestAnimationFrame)||HS)(zS)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Ao=de=null},ke.__c=function(n,e){e.some(function(t){try{t.__h.forEach(fs),t.__h=t.__h.filter(function(i){return!i.__||Lo(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],ke.__e(i,t.__v)}}),af&&af(n,e)},ke.unmount=function(n){of&&of(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{fs(i)}catch(r){e=r}}),t.__H=void 0,e&&ke.__e(e,t.__v))};var uf=typeof requestAnimationFrame=="function";function HS(n){var e,t=function(){clearTimeout(i),uf&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);uf&&(e=requestAnimationFrame(t))}function fs(n){var e=de,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),de=e}function Lo(n){var e=de;n.__c=n.__(),de=e}function Mo(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function df(n,e){return typeof e=="function"?e(n):e}function qS({size:n=24,color:e="#000"}){return p("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:[p("path",{d:"M18 6 6 18"}),p("path",{d:"m6 6 12 12"})]})}function hf({onClose:n}){return p("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:p(qS,{})})}function ff({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Ct(null),a=Ct(null);ze(()=>{const u=s.current;u&&(n&&!u.open?u.showModal():!n&&u.open&&(a.current="programmatic",u.close()))},[n]);const o=u=>{const d=s.current;u.target===d&&!r&&(a.current="user-initiated",d==null||d.close())},l=u=>{u.preventDefault(),a.current||(a.current="user-initiated");const d=a.current;a.current=null,t==null||t(d)},c=()=>{var u;a.current="user-initiated",(u=s.current)==null||u.close()};return ze(()=>{const u=s.current;if(u)return u.addEventListener("click",o),u.addEventListener("close",l),()=>{u.removeEventListener("click",o),u.removeEventListener("close",l)}},[t]),p("dialog",{ref:s,className:`modal-${i}`,children:[p(hf,{onClose:c}),p("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Do(n){const{children:e,className:t="",...i}=n;return p("div",{className:`${t} obi-panel`,...i,children:e})}function ps({className:n="",isActive:e=!1,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),p("div",{className:o,onMouseEnter:r,onMouseLeave:s,children:p("div",{className:`obi-pill pill ${n}`,onClick:i,children:a})})}function KS({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const l=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return p("div",{className:l,...o,children:p("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function $S({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const l=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return p("div",{className:l,...o,children:p("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function yn({type:n,size:e=24}){return p("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:YS(n)})}function YS(n){switch(n){case"pause":return p(Me,{children:[p("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),p("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return p(Me,{children:p("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 p(Me,{children:[p("path",{d:"M18 6 6 18"}),p("path",{d:"m6 6 12 12"})]});case"message":return p(Me,{children:p("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 p(Me,{children:[p("path",{d:"m14 10 7-7"}),p("path",{d:"M20 10h-6V4"}),p("path",{d:"m3 21 7-7"}),p("path",{d:"M4 14h6v6"})]});case"voice":return p(Me,{children:[p("path",{d:"M2 10v3"}),p("path",{d:"M6 6v11"}),p("path",{d:"M10 3v18"}),p("path",{d:"M14 8v7"}),p("path",{d:"M18 5v13"}),p("path",{d:"M22 10v3"})]});case"open":return p(Me,{children:[p("path",{d:"M12 7v14"}),p("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 Uo=jS(null);function XS({children:n}){const e=lf(Uo);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:i,setIsOpen:r,setAnimating:s,targetRef:a,trigger:o,onChange:l,delayMs:c}=e,u=Ct(null),d=pf(a,s),[h,f]=Y(!1);ze(()=>{t!==void 0&&t!==h&&(t?m():v()),f(t)},[t]),ze(()=>()=>{u.current&&clearTimeout(u.current)},[]);function g(){u.current&&(clearTimeout(u.current),u.current=null)}function m(){g(),c>0?u.current=setTimeout(()=>{l==null||l(!0),r(!0),u.current=null},c):(l==null||l(!0),r(!0))}function v(){g(),l==null||l(!1),r(!1)}const b=()=>{o==="click"&&(i?v():m())};function S(){o==="hover"&&m()}function x(){o==="hover"&&v()}return p("div",{ref:d,class:"target",onClick:b,onMouseEnter:S,onMouseLeave:x,children:n})}function JS({children:n}){const e=lf(Uo);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:i,setAnimating:r,targetRef:s,contentRef:a}=e,o=pf(a,r);return hs(()=>{if(t&&!i&&s.current&&a.current){const l=a.current;if(!l)return;const c=s.current;if(!c)return;const u=l.getBoundingClientRect(),d=c.getBoundingClientRect(),h=d.right-d.left;l.style.top=`${u.top-u.bottom-(8+e.offset)}px`,l.style.left=`${-(u.right-u.left-h)/2}px`}},[t,i]),t?p("div",{ref:o,class:"content",style:{opacity:i?0:1},children:n}):null}function He({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,l]=Y(!1),[c,u]=Y(!1),d=Ct(null),h=Ct(null),f={controlledOpen:e,isOpen:o,setIsOpen:l,animating:c,setAnimating:u,targetRef:d,contentRef:h,trigger:n,onChange:t,delayMs:r,offset:s};return p(Uo.Provider,{value:f,children:p("div",{class:`obi-popout ${a}`,children:i})})}He.Target=XS,He.Content=JS;function pf(n,e){const t=Ct(null),i=Ct(null),r=Ct(!0),s=WS(a=>{if(n.current=a,!a){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function o(){if(r.current){r.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}i.current=new ResizeObserver(o),i.current.observe(a,{box:"border-box"})},[]);return ze(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),s}function ht({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:p(yn,{type:"close",size:16}),pause:p(yn,{type:"pause",size:16}),play:p(yn,{type:"play",size:16}),message:p(yn,{type:"message",size:16}),minimize:p(yn,{type:"minimize",size:16}),voice:p(yn,{type:"voice",size:16}),open:p(yn,{type:"open",size:16})}[t],a={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=p("button",{class:`obi-button obi-round-button ${a} ${n}`,onClick:i?void 0:e,disabled:i,children:s});return r?p(He,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[p(He.Target,{children:o}),p(He.Content,{children:p("div",{className:"obi-round-button-title",children:r})})]}):o}const mf=8,ms=8,QS=50,ZS=.7,Yn=3;function gf({getBands:n,color:e="white"}){const t=Ct(null);return ze(()=>{if(!n)return;const i=setInterval(()=>{try{const r=n();if(!t.current)return;const s=t.current.querySelectorAll(".bar"),a=r&&r.length>0?r.slice(0,ms).map(o=>{const l=Math.abs(o);return Math.min(l/ZS*mf,mf)||Yn}):Array(ms).fill(Yn);for(;a.length<ms;)a.push(Yn);a.forEach((o,l)=>{if(o<Yn&&(o=Yn),s[l]){const c=o*2;s[l].style.height=`${c}px`,s[l].style.display=o>0?"block":"none"}})}catch(r){console.warn("Error updating equaliser:",r)}},QS);return()=>{clearInterval(i)}},[n]),p("div",{className:"obi-equaliser",ref:t,children:Array.from({length:ms},(i,r)=>p("div",{className:"column",children:p("div",{className:"bar",style:{height:`${Yn}px`,backgroundColor:e,display:"block"}})},r))})}function nn({className:n,children:e,onClick:t}){return t?p("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):p("div",{class:`obi-message ${n}`,children:e})}const eC=8;function vf({color:n="white"}){return p("div",{className:"obi-loading-dots",children:Array.from({length:eC},(e,t)=>p("div",{className:"column",children:[p("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),p("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function tC({onContinue:n,onWrapUp:e}){return p(Do,{className:"obi-exit-survey",children:p(iC,{onContinue:n,onWrapUp:()=>{e()}})})}function nC({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=Y("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return p(Do,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?p(rC,{onReasonSelect:s}):p(sC,{onReasonSelect:s,onClose:t})})}function iC({onContinue:n,onWrapUp:e}){return p("div",{className:"obi-exit-survey-container",children:[p("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),p("div",{className:"obi-exit-survey-options",children:[p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),p("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 rC({onReasonSelect:n}){return p("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[p("div",{className:"obi-exit-survey-header",children:p("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),p("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),p("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"}),p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function sC({onReasonSelect:n,onClose:e}){const[t,i]=Y("");return p("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[p("div",{className:"obi-exit-survey-header",children:[p(hf,{onClose:e}),p("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),p("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[p("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:r=>i(r.target.value)}),p("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 aC(n,e){for(var t in e)n[t]=e[t];return n}function bf(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var i in e)if(i!=="__source"&&n[i]!==e[i])return!0;return!1}function yf(n,e){this.props=n,this.context=e}(yf.prototype=new At).isPureReactComponent=!0,yf.prototype.shouldComponentUpdate=function(n,e){return bf(this.props,n)||bf(this.state,e)};var kf=H.__b;H.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),kf&&kf(n)};var oC=H.__e;H.__e=function(n,e,t,i){if(n.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),r.__c(n,e)}oC(n,e,t,i)};var Tf=H.unmount;function Sf(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),n.__c.__H=null),(n=aC({},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(i){return Sf(i,e,t)})),n}function Cf(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Cf(i,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function Bo(){this.__u=0,this.o=null,this.__b=null}function xf(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function gs(){this.i=null,this.l=null}H.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Tf&&Tf(n)},(Bo.prototype=new At).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=xf(i.__v),s=!1,a=function(){s||(s=!0,t.__R=null,r?r(o):o())};t.__R=a;var o=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=Cf(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),n.then(a,a)},Bo.prototype.componentWillUnmount=function(){this.o=[]},Bo.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Sf(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&Po(Me,null,n.fallback);return r&&(r.__u&=-33),[Po(Me,null,e.__a?null:n.children),r]};var wf=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]}};(gs.prototype=new At).__a=function(n){var e=this,t=xf(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),wf(e,n,i)):r()};t?t(s):s()}},gs.prototype.render=function(n){this.i=null,this.l=new Map;var e=us(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},gs.prototype.componentDidUpdate=gs.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){wf(n,t,e)})};var cC=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,lC=/^(?: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]/,uC=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,dC=/[A-Z0-9]/g,hC=typeof document<"u",fC=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};At.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(At.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var _f=H.event;function pC(){}function mC(){return this.cancelBubble}function gC(){return this.defaultPrevented}H.event=function(n){return _f&&(n=_f(n)),n.persist=pC,n.isPropagationStopped=mC,n.isDefaultPrevented=gC,n.nativeEvent=n};var vC={enumerable:!1,configurable:!0,get:function(){return this.class}},Ef=H.vnode;H.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,i=e.type,r={},s=i.indexOf("-")===-1;for(var a in t){var o=t[a];if(!(a==="value"&&"defaultValue"in t&&o==null||hC&&a==="children"&&i==="noscript"||a==="class"||a==="className")){var l=a.toLowerCase();a==="defaultValue"&&"value"in t&&t.value==null?a="value":a==="download"&&o===!0?o="":l==="translate"&&o==="no"?o=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?a="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||fC(t.type)?l==="onfocus"?a="onfocusin":l==="onblur"?a="onfocusout":uC.test(a)&&(a=l):l=a="oninput":s&&lC.test(a)?a=a.replace(dC,"-$&").toLowerCase():o===null&&(o=void 0),l==="oninput"&&r[a=l]&&(a="oninputCapture"),r[a]=o}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=us(t.children).forEach(function(c){c.props.selected=r.value.indexOf(c.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=us(t.children).forEach(function(c){c.props.selected=r.multiple?r.defaultValue.indexOf(c.props.value)!=-1:r.defaultValue==c.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",vC)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=cC,Ef&&Ef(n)};var Pf=H.__r;H.__r=function(n){Pf&&Pf(n),n.__c};var Rf=H.diffed;H.diffed=function(n){Rf&&Rf(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 bC(n){const{placeholder:e="Type your message...",value:t,defaultValue:i,onChange:r,onSend:s,onCancel:a,onExpand:o,isLoading:l=!1,disabled:c=!1,maxLength:u=500,children:d}=n,[h,f]=Y(t||i||""),[g,m]=Y((t||i||"").length>24),v=Ct(null);hs(()=>{g&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,S=T=>{const C=T.currentTarget.value;t===void 0&&f(C),r==null||r(C)},x=T=>{T.key==="Escape"&&(f(t||i||""),m(!1),a==null||a()),T.key==="Enter"&&!T.shiftKey&&b.trim()&&(T.preventDefault(),f(t||i||""),m(!1),k()),(b||"").length>=24&&!g&&(m(!0),o==null||o(!0))};ze(()=>{v.current&&v.current.focus()},[v.current]);const k=()=>{!b.trim()||l||c||(s==null||s(b.trim()),t===void 0&&f(""))};return p("div",{className:`obi-message-input ${g?"expanded":""}`,children:[p("div",{className:"container",children:p("textarea",{ref:v,className:"field",placeholder:e,value:b,onInput:S,onKeyDown:x,disabled:c||l,maxLength:u,rows:1})}),p("div",{className:"button-container",children:[g&&p("div",{children:d}),p("button",{className:"obi-button send",onClick:k,disabled:!b.trim()||l||c,type:"button",children:p("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:p("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 yC(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r}=n,s=Array.from({length:t},(l,c)=>({isCompleted:c<e,stepNumber:c+1})),a=i[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${a}`;return p("div",{class:`obi-course-progress ${r||""}`,children:[p("div",{class:"obi-course-progress-steps",children:s.map((l,c)=>p("div",{class:"obi-course-progress-container",children:p("div",{class:`obi-course-progress-step ${l.isCompleted?"completed":""}`})},c))}),p("div",{class:"obi-course-progress-description",children:o})]})}function If({className:n="",size:e=64}){return p("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:p("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 kC(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=Y(null),[a,o]=Y(n.isActive??n.defaultIsActive??!1),[l,c]=Y(!1),[u,d]=Y(n.cancelling??!1),[h,f]=Y(n.messaging??!1),[g,m]=Y(!1),[v,b]=Y(h),[S,x]=Y(!1);hs(()=>{n.messaging!==void 0&&f(n.messaging)},[n.messaging]);function k(){o(!0),c(!1),x(!0),n.messaging!==void 0&&f(n.messaging)}function T(){}function C(){r&&(clearTimeout(r),s(null))}function _(){s(setTimeout(()=>{o(n.defaultIsActive??!1),x(!1)},400))}function R(ae){var ft;m(!1),(ft=n.onMessage)==null||ft.call(n,ae)}function I(){var ae;f(!1),m(!1),o(!1),c(!0),(ae=n.onMinimize)==null||ae.call(n)}function M(){var ae;f(!1),d(!0),m(!1),(ae=n.onCancelClick)==null||ae.call(n)}function D(){var ae;t||((ae=n.onOpen)==null||ae.call(n))}function j(ae){var ft,np,ip,rp,sp,ap;switch(ae){case"need-help":(ft=n.onMessage)==null||ft.call(n,"I'm struggling, can you look at my screen and help me out."),(np=n.onOneClickAction)==null||np.call(n,"need-help");break;case"continue":(ip=n.onMessage)==null||ip.call(n,"Okay, let's continue."),(rp=n.onOneClickAction)==null||rp.call(n,"continue");break;case"say-again":(sp=n.onMessage)==null||sp.call(n,"Please say that again."),(ap=n.onOneClickAction)==null||ap.call(n,"say-again");break}}function V(ae){var ft;n.messaging===void 0&&((ft=n.onMessagingChange)==null||ft.call(n,ae),f(ae)),ae||m(!1)}const q=n.isActive??((a||t)&&!l&&!e),z=q&&t,W=q&&t&&!g,F=n.speakingStatus==="user-speaking",G=n.speakingStatus==="thinking",J=n.speakingStatus==="busy",se=q&&!t&&!u&&S,ge=q&&t&&i&&!F&&!u,Te=q&&t&&!ge&&!F&&h!==v&&!u,et=q&&t&&i&&F&&!u,qe=q&&t&&!i&&F&&!u,xe=q&&t&&!i&&J&&!u,Nt=h&&F,Ke=se||ge||et||qe||Te||u,rn=400,Sn=q&&t&&!g,sx=se?5:10;return hs(()=>{b(h)},[F]),!t&&!u?p(TC,{...n}):!t&&u?p(SC,{onOtherSelect:()=>{var ae;(ae=n.onCancelReasonOther)==null||ae.call(n)},onCancelReason:ae=>{var ft;o(n.defaultIsActive??!1),d(!1),(ft=n.onCancelReason)==null||ft.call(n,ae)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):p(Do,{className:`obi-widget-panel ${z?"expanded":""} ${g?"maximized":""} ${h?"messaging":""} ${J?"tool-usage":""}`,children:[p("div",{className:`obi-widget ${q?"active":""} ${t?"in-plan":""}`,onMouseEnter:C,onMouseLeave:_,children:[W&&p(ht,{type:"cancel",onClick:M,disabled:u,title:"Cancel session"}),W&&!i&&p(ht,{type:"pause",onClick:n.onPause,title:"Pause session"}),W&&i&&p(ht,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(He,{className:"obi-widget-popout",open:Ke,trigger:null,delayMs:rn,offset:sx,children:[p(He.Target,{children:[Nt&&p(bC,{value:n.message,onCancel:()=>V(!1),onSend:R,onExpand:m,onChange:n.onMessageChange,children:p("div",{className:"obi-widget-buttons",children:[p(ht,{type:"cancel",onClick:M,disabled:u,title:"Cancel session"}),!i&&p(ht,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&p(ht,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(ht,{type:h?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>V(!h),title:h?"Voice input":"Text input"}),p(ht,{type:"minimize",onClick:I,title:"Minimize widget"})]})}),!Nt&&p(ps,{className:q&&!t?"button":"",isActive:q,speakingStatus:n.speakingStatus,onClick:D,onMouseEnter:k,onMouseLeave:T,children:[q&&!t&&!xe&&p("span",{className:"obi-widget-pill-text",children:"Tutorials"}),q&&t&&xe&&p("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),q&&t&&!G&&!xe&&p(gf,{getBands:n.spectrum}),q&&G&&!xe&&p(vf,{})]})]}),p(He.Content,{children:p("div",{onMouseLeave:_,children:[se&&p(nn,{onClick:D,children:"Click to see all"}),ge&&p(nn,{children:"Session will pause shortly"}),Te&&p(nn,{children:["Switched to ",h?"chat":"voice"]}),et&&p(nn,{children:"Paused"}),qe&&p("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[p(nn,{onClick:()=>j("need-help"),children:"Need help"}),p(nn,{onClick:()=>j("continue"),children:"Continue"}),p(nn,{onClick:()=>j("say-again"),children:"Say again"})]}),u&&p(tC,{onContinue:()=>{var ae;(ae=n.onCancelAbort)==null||ae.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var ae;(ae=n.onCancel)==null||ae.call(n)}})]})})]}),W&&p(ht,{type:h?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>V(!h),title:h?"Voice input":"Text input"}),W&&p(ht,{type:"minimize",onClick:I,title:"Minimize widget"})]}),Sn&&n.courseProgress&&p("div",{className:`obi-course-progress-container ${h?"expanded":""}`,children:p(yC,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames})})]})}function TC(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=Y(null),[o,l]=Y(n.isActive??n.defaultIsActive??!1),[c,u]=Y(!1),[d,h]=Y(n.hovered??!1);function f(){var R;l(!0),u(!1),h(!0),(R=n.onHover)==null||R.call(n,!0)}function g(){}function m(){s&&(clearTimeout(s),a(null))}function v(){o&&a(setTimeout(()=>{var R;l(n.defaultIsActive??!1),h(!1),(R=n.onHover)==null||R.call(n,!1)},400))}function b(){l(!1),u(!0)}function S(){var R;(R=n.onOpen)==null||R.call(n)}const x=n.hovered??(d&&!c),k=n.isActive??(o&&!e&&!c),T=k&&x,C=`round-button ${k?"active":""}`;let _=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(_=`${t}/${i} completed`),p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:`obi-widget-out-of-plan ${x?"hover":""} ${k?"active":""}`,onMouseEnter:m,onMouseLeave:v,children:[p("div",{className:C,style:{width:"30px",height:"30px"}}),p(He,{className:"obi-widget-popout",open:T,trigger:null,delayMs:400,offset:5,children:[p(He.Target,{children:p($S,{className:k?"button":"",active:k,onClick:S,onMouseEnter:f,onMouseLeave:g,children:p("span",{className:"text",children:[p(If,{size:16}),_]})})}),p(He.Content,{children:p("div",{onMouseLeave:v,children:p(nn,{className:"message",onClick:S,children:"Click to see all"})})})]}),p(ht,{className:C,type:"minimize",onClick:b,title:"Minimize widget"})]})})}function SC(n){return p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:"obi-widget-out-of-plan",children:p(He,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[p(He.Target,{children:p(KS,{active:!1})}),p(He.Content,{children:p(nC,{onOtherSelect:()=>{var e;(e=n.onOtherSelect)==null||e.call(n)},onReasonSelect:(e,t)=>{var i;(i=n.onCancelReason)==null||i.call(n,e,t)},onClose:()=>{var e;(e=n.onClose)==null||e.call(n)}})})]})})})}function CC({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return p(ff,{open:n,onClose:t,preventOutsideClick:i,children:p("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function Xn({title:n="",subtitle:e="",agentName:t="Obi",buttonText:i="Continue",ignoreSpeakingState:r=!1,speakingState:s=null,actionDisabled:a=!1,href:o=null,centerVisual:l,description:c,button:u,onAction:d}){const[h,f]=Y(a),[g,m]=Y(!1),[v,b]=Y(s);return ze(()=>{!g&&!r&&(s==="listening"&&v!=="listening"&&h&&f(!1),s!=="listening"&&!h&&f(!0)),b(s)},[s,h,r]),ze(()=>{f(a)},[a]),p("div",{className:"tour-content",children:p("div",{className:"container",children:[p("div",{className:"header",children:[p("h1",{className:"title",children:n}),p("p",{className:"subtitle",children:e})]}),p("div",{className:"visual",style:{background:"var(--obi-color-tint)"},children:l}),p("div",{className:"description",children:c}),p("div",{className:"button-container",children:u||p(o?"a":"button",{className:`action-button ${h?"disabled":""}`,onClick:()=>{h||(f(!0),m(!0),d==null||d())},disabled:h,...o?{href:o,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:p("span",{className:"button-text",children:(()=>{switch(s){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return i}})()})})})]})})}function xC({logoUrl:n="",appName:e="App"}){const[t,i]=Y(!1),[r,s]=Y(!1),a=()=>{i(!0)},o=()=>{s(!0),i(!1)},l={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&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!n||t||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return p("div",{style:l.container,children:p("div",{style:l.logoContainer,children:[p("div",{style:l.backgroundPattern}),p("div",{style:l.logoWrapper,children:[n&&p("img",{style:l.appLogo,src:n,alt:`${e} logo`,onError:a,onLoad:o}),p("div",{style:l.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function wC({session:n,speakingState:e,onAction:t}){const i=n.appName?`Navigate to ${n.appName}`:"Navigate to app",r=n.appName?`Open ${n.appName}`:"Open app",s=n.appName?`Enjoy the tutorial in ${n.appName}`:"Enjoy the tutorial";return p(Xn,{title:i,subtitle:"Click the button below to open the app",agentName:n.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:n.url,description:s,centerVisual:p(xC,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}function _C({}){return p("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:p(ps,{isActive:!0,children:p("div",{className:"obi-static-voice-visual",children:[p("div",{className:"column",children:p("div",{className:"bar bar-1"})}),p("div",{className:"column",children:p("div",{className:"bar bar-2"})}),p("div",{className:"column",children:p("div",{className:"bar bar-3"})}),p("div",{className:"column",children:p("div",{className:"bar bar-4"})}),p("div",{className:"column",children:p("div",{className:"bar bar-5"})}),p("div",{className:"column",children:p("div",{className:"bar bar-6"})}),p("div",{className:"column",children:p("div",{className:"bar bar-7"})}),p("div",{className:"column",children:p("div",{className:"bar bar-8"})})]})})})}function EC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,buttonText:"Start now",agentName:n.agentName||"Obi",speakingState:e,centerVisual:p(_C,{}),onAction:t})}function PC(){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 p("div",{style:n.host,children:[p("style",{children:`
42
+ `},co}var lh;function NT(){if(lh)return lt;lh=1;var n=OT(),e=AT(),t=oo();return lt.grammar=t,lt.write=e,lt.parse=n.parse,lt.parseParams=n.parseParams,lt.parseFmtpConfig=n.parseFmtpConfig,lt.parsePayloads=n.parsePayloads,lt.parseRemoteCandidates=n.parseRemoteCandidates,lt.parseImageAttributes=n.parseImageAttributes,lt.parseSimulcastStreamList=n.parseSimulcastStreamList,lt}var Zt=NT();function lo(n,e,t){var i,r,s;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(r=t.callback)!=null&&r,l=t.maxWait,c=Date.now(),u=[];function d(){if(l!==void 0){var f=Date.now()-c;if(f+e>=l)return l-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(m,v){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,c=Date.now(),!a){var x=n.apply(g,f);o&&o(x),u.forEach(function(k){return(0,k.resolve)(x)}),u=[]}},d()),b){var S=n.apply(g,f);return o&&o(S),m(S)}u.push({resolve:m,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(g){return(0,g.reject)(f)}),u=[]},h}const LT=.7,MT=20,Hn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class uh extends Tt.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 i;super(),this.log=$,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=lo(r=>y(this,void 0,void 0,function*(){this.emit(Hn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),MT),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=Et((i=t.loggerName)!==null&&i!==void 0?i:ot.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.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 i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.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 y(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return y(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:r,nackMids:s}=DT(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=Zt.parse((t=e.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s.mid!=a.transceiver.mid)return!1;let o=0;if(s.rtp.some(c=>c.codec.toUpperCase()===a.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let l=!1;for(const c of s.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Zt.write(r)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Hn.NegotiationComplete),e.sdp&&Zt.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Hn.RTPVideoPayloadTypes,s.rtp)}))})}createAndSendOffer(e){return y(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 s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Zt.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{hh(s),s.type==="audio"?dh(s,[],[]):s.type==="video"&&this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let o=0;if(s.rtp.some(c=>c.codec.toUpperCase()===a.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(yi(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*LT);for(const c of s.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),yield this.setMungedSDP(i,Zt.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Zt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{hh(r),r.type==="audio"&&dh(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Zt.write(i)),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 _e("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 _e("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 y(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=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),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return y(this,void 0,void 0,function*(){if(t){const r=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:t})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Ua(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===zd))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var l;o.type==="video"&&((l=o.ext)===null||l===void 0||l.forEach(c=>{c.value>a&&(a=c.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:zd})}}}function dh(n,e,t){let i=0;n.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function DT(n){var e;const t=[],i=[],r=Zt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(l=>l.codec==="opus"?(s=l.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(l=>l.payload===s&&l.type==="nack")&&i.push(a.mid),a.fmtp.some(l=>l.payload===s?(l.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function hh(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 uo="vp8",UT={audioPreset:Va.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Wa.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:uo,backupCodec:!0},fh={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ph={deviceId:{ideal:"default"},resolution:bi.h720.resolution},BT={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Pk,disconnectOnPageLeave:!0,webAudioMix:!1},ho={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var pe;(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"})(pe||(pe={}));class FT{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=ho.peerConnectionTimeout,this.log=$,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(l=>l.getConnectionState());o.every(l=>l==="connected")?this.state=pe.CONNECTED:o.some(l=>l==="failed")?this.state=pe.FAILED:o.some(l=>l==="connecting")?this.state=pe.CONNECTING:o.every(l=>l==="closed")?this.state=pe.CLOSED:o.some(l=>l==="closed")?this.state=pe.CLOSING:o.every(l=>l==="new")&&(this.state=pe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(pe[a]," to ").concat(pe[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Et((r=i.loggerName)!==null&&r!==void 0?r:ot.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new uh(e,i),this.subscriber=new uh(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,at.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,at.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=s=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s)},this.state=pe.NEW,this.connectionLock=new Fe,this.remoteOfferLock=new Fe}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 y(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(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return y(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return y(this,void 0,void 0,function*(){t===at.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return y(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 y(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return y(this,void 0,void 0,function*(){return new Promise((t,i)=>y(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Hn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Hn.NegotiationComplete,()=>{clearTimeout(r),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),i(a)})}))})}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===at.PUBLISHER?this.publisher.getConnectedAddress():e===at.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 y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((l,c)=>y(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Ae.clearTimeout(d),c(new re("room connection has been cancelled",X.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Ae.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(new re("could not establish pc connection",X.InternalError))},a);for(;this.state!==pe.CONNECTED;)if(yield Ge(50),r!=null&&r.signal.aborted){c(new re("room connection has been cancelled",X.Cancelled));return}Ae.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}class me extends Error{constructor(e,t,i){super(t),this.code=e,this.message=gh(t,me.MAX_MESSAGE_BYTES),this.data=i?gh(i,me.MAX_DATA_BYTES):void 0}static fromProto(e){return new me(e.code,e.message,e.data)}toProto(){return new Ou({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new me(me.ErrorCode[e],me.ErrorMessage[e],t)}}me.MAX_MESSAGE_BYTES=256,me.MAX_DATA_BYTES=15360,me.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},me.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 mh=15360;function fo(n){return new TextEncoder().encode(n).length}function gh(n,e){if(fo(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}const po=2e3;function Qr(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const jT=1e3;class vh extends P{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=lo(()=>y(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>y(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(A.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Fe,this.pauseUpstreamLock=new Fe,this.processorLock=new Fe,this.restartLock=new Fe,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==P.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 y(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Vn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){const s=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&&(jn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{jn(r??e,s)}))})}waitForDimensions(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jT;return function*(){var i;if(e.kind===P.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ct())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ge(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield Ge(50)}throw new Pt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return y(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Jt(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Jt(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return y(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===P.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===P.Kind.Audio?"audioinput":"videoinput";return t?Pe.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return y(this,void 0,void 0,function*(){if(!this.sender)throw new Pt("unable to replace an unpublished track");let i,r;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return y(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Rk(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===P.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(c=>{Vn(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield l.applyConstraints(s),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l),this._constraints=e,this.emit(A.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{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?A.Muted:A.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hd()&&(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 y(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(A.UpstreamPaused,this);const i=ct();if((i==null?void 0:i.name)==="Safari"&&pn(i.version,"12.0")<0)throw new Da("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 y(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(A.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 y(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 y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),l={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(l),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(jn(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Vn(i._mediaStreamTrack,c),jn(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(A.TrackProcessorUpdate,i.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(A.TrackProcessorUpdate))}()})}}class Zr extends vh{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,P.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>y(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}a&&this.prevStats&&(this._currentBitrate=Qr(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===P.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 y(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 i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Jt(this._constraints.deviceId);return this.source===P.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return y(this,void 0,void 0,function*(){let t;if(e){const i=no({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return y(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){We()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},po)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!St()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(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(A.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return y(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 i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return y(this,void 0,void 0,function*(){const e=yield eh(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(A.AudioSilenceDetected)),e})}}function VT(n,e,t){switch(n.kind){case"audio":return new Zr(n,e,!1,void 0,t);case"video":return new ts(n,e,!1,t);default:throw new Pt("unsupported track type: ".concat(n.kind))}}const GT=Object.values(bi),WT=Object.values(Ga),zT=Object.values(Wa),HT=[bi.h180,bi.h360],qT=[Ga.h180,Ga.h360],KT=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;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)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),mo=["q","h","f"];function go(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,l=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!a&&!o&&!l||!e||!t)return[{}];a||(a=YT(n,e,t,c),$.debug("using video encoding",a));const u=a.maxFramerate,d=new ie(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(l&&yi(c)){const g=new es(l),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const v=ct();if(Xt()||St()||(v==null?void 0:v.name)==="Chrome"&&pn(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3;for(let S=0;S<g.spatial;S+=1)m.push({rid:mo[2-S],maxBitrate:a.maxBitrate/Math.pow(b,S),maxFramerate:d.encoding.maxFramerate});m[0].scalabilityMode=l}else m.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:l});return d.encoding.priority&&(m[0].priority=d.encoding.priority,m[0].networkPriority=d.encoding.priority),$.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(r=yh(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:bh(n,d):h=(s=yh(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:bh(n,d);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const m=Math.max(e,t);if(m>=960&&f)return vo(e,t,[g,f,d],u);if(m>=480)return vo(e,t,[g,d],u)}return vo(e,t,[d])}function $T(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&$.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(),l=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===P.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),go(n.source===P.Source.ScreenShare,l,c,t)}function YT(n,e,t,i){const r=XT(n,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const l=r[o];if(s=l.encoding,l.width>=a)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function XT(n,e,t){if(n)return zT;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?GT:WT}function bh(n,e){if(n)return KT(e);const{width:t,height:i}=e,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?HT:qT}function vo(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=mo.length)return;const o=Math.min(n,e),c={rid:mo[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(c.maxFramerate=u);const d=Gn()||a===0;s.encoding.priority&&d&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),St()&&Kd()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var l;o.maxFramerate!=s&&(a&&(a=!1,$.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),$.info('Setting framerate of encoding "'.concat((l=o.rid)!==null&&l!==void 0?l:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function yh(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:r}=t;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class es{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 JT(n){return n.source===P.Source.ScreenShare||n.constraints.height&&Jt(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const QT=5e3;class ts extends vh{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,P.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>y(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}const a=new Map(s.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((l,c)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=Qr(l,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new Fe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!We())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},po))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,l=qt(this.simulcastCodecs.values()),c;c=yield l.next(),t=c.done,!t;o=!0)s=c.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){i={error:u}}finally{try{!o&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,l=qt(this.simulcastCodecs.values()),c;c=yield l.next(),t=c.done,!t;o=!0){s=c.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!o&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===P.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 y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===P.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 y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ze.LOW;i<=Ze.HIGH;i+=1)t.push(new xa({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const d=no({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var l=!0,c=qt(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;l=!0){s=u.value,l=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!l&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return y(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,l,c,u,d;if(yield t.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=qt(r.simulcastCodecs.values()),g;g=yield f.next(),a=g.done,!a;h=!0)c=g.value,h=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){o={error:m}}finally{try{!h&&!a&&(l=f.return)&&(yield l.call(f))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return y(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 i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},QT))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a,o,l;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,i=qt(e);r=yield i.next(),s=r.done,!s;t=!0){l=r.value,t=!1;const u=l;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){c.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield kh(d.sender,d.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e){return y(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 kh(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hd()&&this.isInBackground&&this.source===P.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function kh(n,e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:l}=o;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:l,senderEncodings:e}));return}let c=!1;const u=ct();if((u==null?void 0:u.name)==="Chrome"&&pn(u==null?void 0:u.version,"133")>0&&l[0].scalabilityMode){const h=l[0],f=new es(h.scalabilityMode);let g=Ln.OFF;if(t.forEach(m=>{m.enabled&&(g===Ln.OFF||m.quality>g)&&(g=m.quality)}),g===Ln.OFF)h.active&&(h.active=!1,c=!0);else if(!h.active||f.spatial!==g+1){c=!0,h.active=!0;const m=new es(e[0].scalabilityMode);f.spatial=g+1,f.suffix=m.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-g),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else l.forEach((h,f)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const v=Th(m),b=t.find(S=>S.quality===v);b&&h.active!==b.enabled&&(c=!0,h.active=b.enabled,r.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),s),Gn()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))});c&&(o.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Th(n){switch(n){case"f":return Ze.HIGH;case"h":return Ze.MEDIUM;case"q":return Ze.LOW;default:return Ze.HIGH}}function Sh(n,e,t,i){if(!t)return[new dn({quality:Ze.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new es(r),a=[],o=s.suffix=="h"?1.5:2,l=s.suffix=="h"?2:3;for(let c=0;c<s.spatial;c+=1)a.push(new dn({quality:Math.min(Ze.HIGH,s.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(l,c)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const l=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let c=Th((a=r.rid)!==null&&a!==void 0?a:"");return new dn({quality:c,width:Math.ceil(n/l),height:Math.ceil(e/l),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ch="_lossy",xh="_reliable",ZT=2*1e3,bo="leave-reconnect";var ut;(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"})(ut||(ut={}));class eS extends Tt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ho.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=ut.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=$,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===xh)s.reliableDCSub=a;else if(a.label===Ch)s.lossyDCSub=a;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label),s.logContext),a.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>y(this,void 0,void 0,function*(){var r,s;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const l=Ve.fromBinary(new Uint8Array(o));((r=l.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,l.value.value.speakers):(((s=l.value)===null||s===void 0?void 0:s.case)==="user"&&nS(l,l.value.value),this.emit(N.DataPacketReceived,l))}finally{a()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?Q.LOSSY:Q.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=l=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(l,"ms. giving up"),this.logContext),this.emit(N.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===bo&&(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=Ae.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ut.Connected&&i();const s=()=>{this.off(N.Disconnected,a),i()},a=()=>{this.off(N.Restarted,s),r()};this.once(N.Restarted,s),this.once(N.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(N.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ce.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Mn.RR_SIGNAL_DISCONNECTED))},this.log=Et((t=e.loggerName)!==null&&t!==void 0?t:ot.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ro(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Fe,this.dataProcessLock=new Fe,this.dcBufferStatus=new Map([[Q.LOSSY,!0],[Q.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(N.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(N.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(N.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(N.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(N.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(N.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(N.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(N.SignalRequestResponse,i)}get logContext(){var e,t,i,r,s,a,o,l;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,pID:(l=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||l===void 0?void 0:l.sid}}join(e,t,i,r){return y(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout(()=>{this.emit(N.SignalConnected)},10),s}catch(s){if(s instanceof re&&s.reason===X.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,i,r);throw s}})}close(){return y(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 y(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=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.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 y(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Pt("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new re("publication of local track timed out, no response from server",X.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject: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 y(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 y(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==pe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new FT(r,e.subscriberPrimary,this.loggerOptions),this.emit(N.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,a)=>{this.client.sendIceCandidate(s,a)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,a,o)=>y(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),s===pe.CONNECTED){const u=this.pcState===ut.New;this.pcState=ut.Connected,u&&this.emit(N.Connected,e)}else s===pe.FAILED&&this.pcState===ut.Connected&&(this.pcState=ut.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Mn.RR_SUBSCRIBER_FAILED:Mn.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===ce.RECONNECTING,c=[pe.FAILED,pe.CLOSING,pe.CLOSED].includes(s);l&&c&&!this._isClosed&&this.emit(N.Offline)}),this.pcManager.onTrack=s=>{this.emit(N.MediaTrackAdded,s.track,s.streams[0],s.receiver)},tS((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>y(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=>y(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(N.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(N.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,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",Mn.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 Bn.DISCONNECT:this.emit(N.Disconnected,e==null?void 0:e.reason),this.close();break;case Bn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(bo);break;case Bn.RESUME:this.handleDisconnect(bo)}}}makeRTCConfiguration(e){var t;const i=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),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===mi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ch,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(xh,{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,i){return y(this,void 0,void 0,function*(){if(za())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Ha())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new _e("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(za())return this.createSimulcastTransceiverSender(e,t,i,r);if(Ha())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new _e("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),zn(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return y(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){$.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===mi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:pe.NEW)===pe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof _e?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof qn||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Mn.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 y(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new _e("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new qn;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof re&&a.reason===X.NotAllowed?new _e("could not reconnect, token might be expired"):new qn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(N.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ce.CONNECTED)throw new qn("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(N.Restarted)}catch(s){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return y(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new _e("could not reconnect, url or token not saved");if(!this.pcManager)throw new _e("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(N.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof re&&r.reason===X.NotAllowed?new _e("could not reconnect, token might be expired"):r instanceof re&&r.reason===X.LeaveRequest?r:new qn(s)}if(this.emit(N.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r)}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!==ce.CONNECTED)throw new qn("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 y(this,void 0,void 0,function*(){if(!this.pcManager)throw new _e("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ge(ZT),!this.pcManager)throw new _e("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ut.Connected}catch(e){throw this.pcState=ut.Disconnected,new re("could not establish PC connection, ".concat(e.message),X.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new Ve({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcResponse",value:new Iu({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,Q.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new Ve({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcAck",value:new Ru({requestId:t})}});yield this.sendDataPacket(i,Q.RELIABLE)})}sendDataPacket(e,t){return y(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const r=this.dataChannelForKind(t);r&&r.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>y(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const r=()=>i("Engine closed");for(this.once(N.Closing,r);!this.dcBufferStatus.get(e);)yield Ge(10);this.off(N.Closing,r),t()}}))}ensureDataTransportConnected(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new _e("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new re("".concat(o," connection not set"),X.InternalError);let l=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),l=!0),!l&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(l=!0),l&&i.negotiate();const c=i.dataChannelForKind(t,r);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Ge(50)}throw new re("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),X.InternalError)}()})}ensurePublisherConnected(e){return y(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==pe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return y(this,void 0,void 0,function*(){return new Promise((e,t)=>y(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ua("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(N.Closing,r),this.pcManager.publisher.once(Hn.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const l=o.codec.toLowerCase();uT(l)&&a.set(o.payload,l)}),this.emit(N.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Ua&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Mn.RR_UNKNOWN),t(s)}finally{this.off(N.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===Q.LOSSY)return this.lossyDCSub;if(e===Q.RELIABLE)return this.reliableDCSub}else{if(e===Q.LOSSY)return this.lossyDC;if(e===Q.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,l=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&l.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new $u({answer:s?Jr({sdp:s.sdp,type:s.type}):void 0,offer:a?Jr({sdp:a.sdp,type:a.type}):void 0,subscription:new Mr({trackSids:l,subscribe:!o,participantTracks:[]}),publishTracks:yT(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Yu({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(Q.LOSSY),at.PUBLISHER),t(this.dataChannelForKind(Q.RELIABLE),at.PUBLISHER),t(this.dataChannelForKind(Q.LOSSY,!0),at.SUBSCRIBER),t(this.dataChannelForKind(Q.RELIABLE,!0),at.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ae.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){We()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){We()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class qn extends Error{}function tS(n){return n!==void 0&&n>13}function nS(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class yo{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 Ka(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return y(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(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),$.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return y(this,void 0,void 0,function*(){const t=yield fetch("".concat(iS(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new re("Could not fetch region settings: ".concat(t.statusText),t.status===401?X.NotAllowed:X.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function iS(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class wh{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class rS extends wh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>y(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s=new Set;try{for(var a=!0,o=qt(this),l;l=yield o.next(),e=l.done,!e;a=!0){r=l.value,a=!1;const c=r;s.add(c)}}catch(c){t={error:c}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class sS extends wh{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Yr(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>y(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:t.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s="";try{for(var a=!0,o=qt(this),l;l=yield o.next(),e=l.done,!e;a=!0)r=l.value,a=!1,s+=r}catch(c){t={error:c}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return s})}}class _h{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return y(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 aS extends _h{}class oS extends _h{}class Eh extends P{constructor(e,t,i,r,s){super(e,i,s),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.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(A.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return y(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(),po)),kT()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(A.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class cS extends Eh{constructor(e,t,i,r,s,a){super(e,t,P.Kind.Audio,i,a),this.monitorReceiver=()=>y(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=Qr(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;St()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(St())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return y(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(qa(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&qa(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,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 i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(A.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(A.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,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 y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const ko=100;class lS extends Eh{constructor(e,t,i,r,s){super(e,t,P.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>y(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Qr(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=lo(()=>{this.updateDimensions()},ko),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Vn(this._mediaStreamTrack,t):jn(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 uS(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(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,l)=>Math.max(o,l.visibilityChangedAt||0),0),r=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,s=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!r||s;if(this.lastVisible!==a){if(!a&&Date.now()-i<ko){Ae.setTimeout(()=>{this.updateVisibility()},ko);return}this.lastVisible=a,this.emit(A.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,l=a.height()*s;o+l>i+r&&(i=o,r=l)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(A.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?$d():t||($d()>2?2:1)}}class uS{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:a}=i;s===this.element&&(this.isIntersecting=a,this.isPiP=Si(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Si(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Si(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??To(e),this.isPiP=We()&&Si(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=To(this.element),this.isPiP=Si(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Xd().observe(this.element),Yd().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=Xd())===null||e===void 0||e.unobserve(this.element),(t=Yd())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Si(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?To(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function To(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:l}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!o&&l!=="none"}class It extends Tt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=$e.NONE,this.log=$,this.handleMuted=()=>{this.emit(A.Muted)},this.handleUnmuted=()=>{this.emit(A.Unmuted)},this.log=Et((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:ot.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=P.Source.Unknown}setTrack(e){this.track&&(this.track.off(A.Muted,this.handleMuted),this.track.off(A.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(A.Muted,this.handleMuted),e.on(A.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),te(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==$e.NONE}get audioTrack(){if(Rt(this.track))return this.track}get videoTrack(){if(zn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=P.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===P.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={}))})(It||(It={}));class So extends It{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(A.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(A.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(A.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 y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Rt(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(st.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(st.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(st.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(st.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(st.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(st.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ns(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=ih(n);let a=s.audio,o=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),n.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},t=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},t=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const l=Zd(s,fh,ph),c=no(l),u=navigator.mediaDevices.getUserMedia(c);s.audio&&(Pe.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("audioinput"))),s.video&&(Pe.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>y(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?l.audio:l.video;(typeof g=="boolean"||!g)&&(g={});let m;const v=f?c.audio:c.video;typeof v!="boolean"&&(m=v);const b=h.getSettings().deviceId;m!=null&&m.deviceId&&Jt(m.deviceId)!==b?m.deviceId=b:m||(m={deviceId:b});const S=VT(h,m,e);return S.kind===P.Kind.Video?S.source=P.Source.Camera:S.kind===P.Kind.Audio&&(S.source=P.Source.Microphone),S.mediaStream=d,Rt(S)&&i?yield S.setProcessor(i):zn(S)&&r&&(yield S.setProcessor(r)),S})))}catch(d){if(!t)throw d;return ns(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function dS(n){return y(this,void 0,void 0,function*(){return(yield ns({audio:!1,video:n??!0}))[0]})}function hS(n){return y(this,void 0,void 0,function*(){return(yield ns({audio:n??!0,video:!1}))[0]})}var en;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(en||(en={}));function fS(n){switch(n){case pi.EXCELLENT:return en.Excellent;case pi.GOOD:return en.Good;case pi.POOR:return en.Poor;case pi.LOST:return en.Lost;default:return en.Unknown}}class Ph extends Tt.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===Lr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Dn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Lr.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=en.Unknown,this.log=$,this.log=Et((l=a==null?void 0:a.loggerName)!==null&&l!==void 0?l:ot.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}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 Ja,this.once(L.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(P.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(P.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(P.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===Dn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Dn.ACTIVE&&this.emit(L.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(L.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(L.ParticipantNameChanged,e)}_setAttributes(e){const t=TT(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(L.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const l=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(L.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(L.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=fS(e),t!==this._connectionQuality&&this.emit(L.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=>Rt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(A.Muted,()=>{this.emit(L.TrackMuted,e)}),e.on(A.Unmuted,()=>{this.emit(L.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case P.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case P.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function pS(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new qu({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}const Rh=15e3;class mS extends Ph{constructor(e,t,i,r,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=$e.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ja)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(l=>this.log.warn(l.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:l,message:c}=a,u=this.pendingSignalRequests.get(o);u&&(l!==wa.OK&&u.reject(new Vd(c,l)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,l=null,c=null;o.value.case==="payload"?l=o.value.value:o.value.case==="error"&&(c=me.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,l,c);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>pS(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),te(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),te(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),te(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>y(this,void 0,void 0,function*(){var o,l,c,u,d,h;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var g=!0,m=qt(b),v;v=yield m.next(),o=v.done,!o;g=!0){u=v.value,g=!1;const S=u;Zk(S)&&(this.log.debug("publish ".concat(S," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),te(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,S,f.options))}}catch(S){l={error:S}}finally{try{!g&&!o&&(c=m.return)&&(yield c.call(m))}finally{if(l)throw l.error}}}else a.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>y(this,void 0,void 0,function*(){if(a.source===P.Source.ScreenShare||a.source===P.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),te(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(gn(a)||Qt(a))try{if(We())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===P.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),te(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),te(a))),gn(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),te(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==$e.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,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.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 y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return y(this,arguments,void 0,function(t){var i=this;let{metadata:r,name:s,attributes:a}=t;return function*(){return new Promise((o,l)=>y(i,void 0,void 0,function*(){var c,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{l(g),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(g=>{let[m,v]=g;return this.attributes[m]===v||v===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),o();return}yield Ge(50)}l(new Vd("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(P.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(P.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(P.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(L.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?$e.GCM:$e.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,r){return y(this,void 0,void 0,function*(){var s,a;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 l;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 P.Source.Camera:l=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case P.Source.Microphone:l=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case P.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Pt(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(L.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const d of l)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),te(d))),c.push(this.publishTrack(d,r));[o]=yield Promise.all(c)}catch(c){throw l==null||l.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===P.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const l=this.getTrackPublication(P.Source.ScreenShareAudio);l&&l.track&&this.unpublishTrack(l.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return y(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(P.Source.Camera)||this.pendingPublishing.has(P.Source.Microphone))){this.pendingPublishing.add(P.Source.Camera),this.pendingPublishing.add(P.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(P.Source.Camera),this.pendingPublishing.delete(P.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const r=Zd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield ns(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Rt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=P.Source.Microphone,this.emit(L.AudioStreamAcquired)),zn(o)&&(this.cameraError=void 0,o.source=P.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return y(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Da("getDisplayMedia not supported");e.resolution===void 0&&!sT()&&(e.resolution=Wa.h1080fps30.resolution);const t=bT(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new Pt("no video track found");const s=new ts(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=P.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(L.AudioStreamAcquired);const o=new Zr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=P.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return y(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,l,c,u;gn(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),Wn(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case P.Source.Microphone:b="audioinput";break;case P.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Zr(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new ts(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Pt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),te(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(l=r==null?void 0:r.forceStereo)!==null&&l!==void 0?l:f;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),te(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=r.dtx)!==null&&c!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const m=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!aT()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),m.simulcast=!1),m.source&&(i.source=m.source);const v=new Promise((b,S)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ce.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:te(i)}));const x=()=>y(this,void 0,void 0,function*(){try{const k=yield this.publish(i,m,g);b(k)}catch(k){S(k)}});setTimeout(()=>{this.engine.off(N.SignalConnected,x),S(new Ba("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(N.SignalConnected,x),this.engine.on(N.Closing,()=>{this.engine.off(N.SignalConnected,x),S(new Ba("publishing rejected as engine closed",499))})}else try{const x=yield this.publish(i,m,g);b(x)}catch(x){S(x)}}catch(x){S(x)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),te(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>ST(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),te(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var r,s,a,o,l,c,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new Ba("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(T=>Wn(e)&&T.source===e.source)&&e.source!==P.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),te(e))),t.stopMicTrackOnMute&&Rt(e)&&(e.stopOnMute=!0),e.source===P.Source.ScreenShare&&Gn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!nT()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!iT()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=uo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(T=>t.videoCodec===Xr(T.mime))||(t.videoCodec=Xr(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(A.Muted,this.onTrackMuted),e.on(A.Unmuted,this.onTrackUnmuted),e.on(A.Ended,this.handleTrackEnded),e.on(A.UpstreamPaused,this.onTrackUpstreamPaused),e.on(A.UpstreamResumed,this.onTrackUpstreamResumed),e.on(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new ka({cid:e.mediaStreamTrack.id,name:t.name,type:P.kindToProto(e.kind),muted:e.isMuted,source:P.sourceToProto(e.source),disableDtx:!(!((r=t.dtx)!==null&&r!==void 0)||r),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let b;if(e.kind===P.Kind.Video){let T={width:0,height:0};try{T=yield e.waitForDimensions()}catch{const _=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:bi.h720.resolution;T={width:_.width,height:_.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{dims:T}))}v.width=T.width,v.height=T.height,Qt(e)&&(yi(m)&&(e.source===P.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),te(e))))),t.scalabilityMode=(l=t.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),v.simulcastCodecs=[new ya({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:uo}),t.backupCodec&&m!==t.backupCodec.codec&&v.encryption===$e.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new ya({codec:t.backupCodec.codec,cid:""})))),b=go(e.source===P.Source.ScreenShare,v.width,v.height,t),v.layers=Sh(v.width,v.height,b,yi(t.videoCodec))}else e.kind===P.Kind.Audio&&(b=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new _e("cannot publish track when not connected");const S=()=>y(this,void 0,void 0,function*(){var T,C,_;if(!this.engine.pcManager)throw new _e("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Qt(e)&&((T=t.degradationPreference)!==null&&T!==void 0||(t.degradationPreference=JT(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Gn()&&e.kind===P.Kind.Audio){let R;for(const I of this.engine.pcManager.publisher.getTransceivers())if(I.sender===e.sender){R=I;break}R&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:R,codec:"opus",maxbr:!((C=b[0])===null||C===void 0)&&C.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&yi(e.codec)&&(!((_=b[0])===null||_===void 0)&&_.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let x;if(this.enabledPublishVideoCodecs.length>0)x=(yield Promise.all([this.engine.addTrack(v),S()]))[0];else{x=yield this.engine.addTrack(v);let T;if(x.codecs.forEach(C=>{T===void 0&&(T=C.mimeType)}),T&&e.kind===P.Kind.Video){const C=Xr(T);C!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{codec:C})),t.videoCodec=C,b=go(e.source===P.Source.ScreenShare,v.width,v.height,t))}yield S()}const k=new So(e.kind,x,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return k.options=t,e.sid=x.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:x})),Qt(e)?e.startMonitor(this.engine.client):gn(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(L.LocalTrackPublished,k),k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==$e.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new Pt("track is not published");if(!Qt(e))throw new Pt("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=$T(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),te(e)));return}const l=e.addSimulcastTrack(t,o);if(!l)return;const c=new ka({cid:l.mediaStreamTrack.id,type:P.kindToProto(e.kind),muted:e.isMuted,source:P.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=Sh(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new _e("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,l,a,o),yield this.engine.negotiate()}),h=(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:h}))})}unpublishTrack(e,t){return y(this,void 0,void 0,function*(){var i,r;if(Wn(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),te(e))),yield c)}const s=this.getPublicationForTrack(e),a=s?te(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=s.track,e.off(A.Muted,this.onTrackMuted),e.off(A.Unmuted,this.onTrackUnmuted),e.off(A.Ended,this.handleTrackEnded),e.off(A.UpstreamPaused,this.onTrackUpstreamPaused),e.off(A.UpstreamResumed,this.onTrackUpstreamResumed),e.off(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const l=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<pe.FAILED&&l)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===l&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(l)&&(o=!0),Qt(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),a),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case P.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case P.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(L.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return y(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,a)=>y(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(l=>{l.track&&(t&&(l.options=Object.assign(Object.assign({},l.options),t)),o.push(l))}),yield Promise.all(o.map(l=>y(this,void 0,void 0,function*(){const c=l.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==P.Source.ScreenShare&&c.source!==P.Source.ScreenShareAudio&&(gn(c)||Qt(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:l.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,l.options,!0)}))),s()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?Q.RELIABLE:Q.LOSSY,a=r.destinationIdentities,o=r.topic,l=new Ve({kind:s,value:{case:"user",value:new _u({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(l,s)}()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new Ve({kind:Q.RELIABLE,value:{case:"sipDtmf",value:new Eu({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Q.RELIABLE)})}sendChatMessage(e,t){return y(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new Ve({value:{case:"chatMessage",value:new fa(Object.assign(Object.assign({},i),{timestamp:ue.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Q.RELIABLE),this.emit(L.ChatMessage,i),i})}editChatMessage(e,t){return y(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Ve({value:{case:"chatMessage",value:new fa(Object.assign(Object.assign({},i),{timestamp:ue.parse(i.timestamp),editTimestamp:ue.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Q.RELIABLE),this.emit(L.ChatMessage,i),i})}sendText(e,t){return y(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),l=new Array(o?o.length+1:1).fill(0),c=(d,h)=>{var f;l[h]=d;const g=l.reduce((m,v)=>m+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},u=yield this.streamText({streamId:r,totalSize:a,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((d,h)=>y(this,void 0,void 0,function*(){return this._sendFile(o[h],d,{topic:t.topic,mimeType:d.type,onProgress:f=>{c(f,h+1)}})})))),u.info})}streamText(e){return y(this,void 0,void 0,function*(){var t,i;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new ma({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:mn(s.timestamp),totalLength:mn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Bu({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"?pa.UPDATE:pa.CREATE})}}),o=e==null?void 0:e.destinationIdentities,l=new Ve({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,Q.RELIABLE);let c=0;const u=this,d=new WritableStream({write(g){return y(this,void 0,void 0,function*(){for(const m of gT(g,Rh)){yield u.engine.waitForBufferStatusLow(Q.RELIABLE);const v=new ga({content:m,streamId:r,chunkIndex:mn(c)}),b=new Ve({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,Q.RELIABLE),c+=1}})},close(){return y(this,void 0,void 0,function*(){const g=new va({streamId:r}),m=new Ve({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield u.engine.sendDataPacket(m,Q.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(N.Closing,h);const f=new aS(d,s,()=>this.engine.off(N.Closing,h));return f})}sendFile(e,t){return y(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return y(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:l}=yield a.read();if(o)break;yield s.write(l)}return yield s.close(),s.info})}streamBytes(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},u=new ma({totalLength:mn((a=c.size)!==null&&a!==void 0?a:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:mn(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Fu({name:c.name})}}),d=new Ve({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,Q.RELIABLE);let h=0;const f=new Fe,g=this.engine,m=this.log,v=new WritableStream({write(S){return y(this,void 0,void 0,function*(){const x=yield f.lock();let k=0;try{for(;k<S.byteLength;){const T=S.slice(k,k+Rh);yield g.waitForBufferStatusLow(Q.RELIABLE);const C=new Ve({destinationIdentities:l,value:{case:"streamChunk",value:new ga({content:T,streamId:o,chunkIndex:mn(h)})}});yield g.sendDataPacket(C,Q.RELIABLE),h+=1,k+=T.byteLength}}finally{x()}})},close(){return y(this,void 0,void 0,function*(){const S=new va({streamId:o}),x=new Ve({destinationIdentities:l,value:{case:"streamTrailer",value:S}});yield g.sendDataPacket(x,Q.RELIABLE)})},abort(S){m.error("Sink error:",S)}});return new oS(v,c)})}performRpc(e){return y(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:r,method:s,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>y(i,void 0,void 0,function*(){var d,h,f,g;if(fo(a)>mh){u(me.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||h===void 0)&&h.version&&pn((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){u(me.builtIn("UNSUPPORTED_SERVER"));return}const m=crypto.randomUUID();yield this.publishRpcRequest(r,m,s,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(m),u(me.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(b)},2e3);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(m),u(me.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(S,x)=>{clearTimeout(b),this.pendingAcks.has(m)&&(console.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(v)),x?u(x):c(S??"")},participantIdentity:r})}))}()})}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,i){const r=this.pendingResponses.get(e);r?(r.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=new Ve({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcRequest",value:new Pu({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,Q.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,me.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 i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),te(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(gn(r)||Qt(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return y(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[a]=s;return a.source===e});if(r)return r[1];yield Ge(20)}})}}class gS extends It{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ze.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(A.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Mr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Au({participantSid:"",trackSids:[this.trackSid]})]});this.emit(A.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?It.SubscriptionStatus.Unsubscribed:super.isSubscribed?It.SubscriptionStatus.Subscribed:It.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?It.PermissionStatus.Allowed:It.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,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(eo(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&eo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(A.VisibilityChanged,this.handleVisibilityChange),r.off(A.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(A.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(A.VisibilityChanged,this.handleVisibilityChange),e.on(A.Ended,this.handleEnded),this.emit(A.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(A.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?A.Muted:A.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(A.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(A.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===P.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 eo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Vu({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=Ze.HIGH,this.emit(A.UpdateSettings,e)}}class is extends Ph{static fromParticipantInfo(e,t,i){return new is(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Lr.STANDARD;super(t,i||"",r,s,a,o,l),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(A.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),te(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(A.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(A.SubscriptionPermissionChanged,t=>{this.emit(L.TrackSubscriptionPermissionChanged,e,t)}),e.on(A.SubscriptionStatusChanged,t=>{this.emit(L.TrackSubscriptionStatusChanged,e,t)}),e.on(A.Subscribed,t=>{this.emit(L.TrackSubscribed,t,e)}),e.on(A.Unsubscribed,t=>{this.emit(L.TrackUnsubscribed,t,e)}),e.on(A.SubscriptionFailed,t=>{this.emit(L.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]:P.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:P.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(L.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-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),te(o))),this.emit(L.TrackSubscriptionFailed,t);return}const l=e.kind==="video";let c;return l?c=new lS(e,t,r,s):c=new cS(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Za(c)&&Rt(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,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const l=P.kindFromProto(r.type);if(!l)return;o=new gS(l,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==P.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:te(c),newTrack:te(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),te(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(L.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case P.Kind.Audio:this.audioTrackPublications.delete(e);break;case P.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(L.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Rt(i.track)&&Za(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Z;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Z||(Z={}));const vS=4*1e3;class Kn extends Tt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=Z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=$,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=(a,o,l)=>y(this,void 0,void 0,function*(){var c;if(!rT())throw St()?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===Z.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(Z.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ka(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new yo(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,g,m)=>y(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const S=new AbortController;this.abortController=S,u==null||u();try{yield this.attemptConnection(m??a,o,l,S),this.abortController=void 0,f()}catch(x){if(this.regionUrlProvider&&x instanceof re&&x.reason!==X.Cancelled&&x.reason!==X.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(T){if(T instanceof re&&(T.status===401||T.reason===X.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(T);return}}k&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield d(f,g,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Qd(x)),g(x))}else{let k=rt.UNKNOWN_REASON;x instanceof re&&(k=Qd(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),g(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ja((f,g)=>{d(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,l,c,u,d)=>y(this,void 0,void 0,function*(){var h,f,g;const m=yield l.join(a,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},d.signal);let v=m.serverInfo;if(v||(v={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[S,x]=b;return"".concat(S,": ").concat(x)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(f=m.room)===null||f===void 0?void 0:f.sid,identity:(g=m.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new Wk("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,l,c)=>y(this,void 0,void 0,function*(){var u,d;this.state===Z.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(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ho),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new re("could not establish signal connection",X.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof re&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new re("Connection attempt aborted",X.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}We()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),We()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Z.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),l=0;l<a;l++)o[l]=arguments[l];return y(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,g;const m=yield c.disconnectLock.lock();try{if(c.state===Z.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===Z.Connecting||c.state===Z.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(d=c.abortController)===null||d===void 0||d.abort(),(f=(h=c.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new re("Client initiated disconnect",X.Cancelled)),c.connectFuture=void 0),!((g=c.engine)===null||g===void 0)&&g.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,rt.CLIENT_INITIATED),c.engine=void 0}finally{m()}}()})},this.onPageLeave=()=>y(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>y(this,void 0,void 0,function*(){const a=[],o=ct();if(o&&o.os==="iOS"){const l="livekit-dummy-audio-el";let c=document.getElementById(l);if(!c){c=document.createElement("audio"),c.id=l,c.autoplay=!0,c.hidden=!0;const u=Xa();u.enabled=!0;const d=new MediaStream([u]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,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(O.Disconnected,()=>{c==null||c.remove(),c=null})}a.push(c)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(l=>{var c;(c=l.track)===null||c===void 0||c.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.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 a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=a=>y(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);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:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(Z.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var l;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(l=this.sidToIdentity.get(o.sid))!==null&&l!==void 0?l:"");let c=this.remoteParticipants.get(o.identity);o.state===Dn.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],l={};a.forEach(c=>{if(l[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))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{l[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{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)}),a.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 l=Array.from(o.values());l.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(O.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const l=this.getRemoteParticipantBySid(o.participantSid);if(!l)return;const c=l.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=P.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,l.emit(L.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,c,c.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const l=o.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(a.trackSid));if(!o)return;const l=o.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const l=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(a,o,l)=>{this.emit(O.DataReceived,o.payload,a,l,o.topic),a==null||a.emit(L.DataReceived,o.payload,l)},this.handleSipDtmf=(a,o)=>{this.emit(O.SipDTMFReceived,o,a),a==null||a.emit(L.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const l=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=l==null?void 0:l.trackPublications.get(o.trackId),u=hT(o,this.transcriptionReceivedTimes);c==null||c.emit(A.TranscriptionReceived,u),l==null||l.emit(L.TranscriptionReceived,u,c),this.emit(O.TranscriptionReceived,u,l,c)},this.handleChatMessage=(a,o)=>{const l=fT(o);this.emit(O.ChatMessage,l,a)},this.handleMetrics=(a,o)=>{this.emit(O.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,l;const c=Pe.getInstance().previousDevices,u=yield Pe.getInstance().getDevices(void 0,!1),d=ct();if((d==null?void 0:d.name)==="Chrome"&&d.os!=="iOS")for(let f of u){const g=c.find(m=>m.deviceId===f.deviceId);g&&g.label!==""&&g.kind===f.kind&&g.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(O.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const g=vT(f),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(S=>S.kind===f),b=this.getActiveDevice(f);if(b===((o=c.filter(S=>S.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((l=v[0])===null||l===void 0?void 0:l.deviceId)!==b){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Xt()||f==="videoinput"||v.length>0&&!v.find(S=>S.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const l=this.getRemoteParticipantBySid(o.participantSid);l&&l.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(O.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(O.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(O.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(O.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(O.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>y(this,void 0,void 0,function*(){var o,l,c,u,d,h;(o=a.track)===null||o===void 0||o.on(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(A.Restarted,this.onLocalTrackRestarted),(d=(u=(c=a.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(O.LocalTrackPublished,a,this.localParticipant),gn(a.track)&&(yield a.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=nh(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(O.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,l;(o=a.track)===null||o===void 0||o.off(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(A.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),l=nh(a.source);l&&o&&o!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,o),this.emit(O.ActiveDeviceChanged,l,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(O.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(O.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(O.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(O.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},BT),e),this.log=Et((i=this.options.loggerName)!==null&&i!==void 0?i:ot.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},fh),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ph),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},UT),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Fe,this.localParticipant=new mS("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Jt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Jt(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Jt(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),We()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Kn.cleanupRegistry&&Kn.cleanupRegistry.register(this,()=>{a.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,i,r,s,a){return y(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});fo(u)>mh?(l=me.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof me?l=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=me.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,l)})}setE2EEEnabled(e){return y(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 CT(this.options.e2ee),this.e2eeManager.on($t.ParticipantEncryptionStatusChanged,(t,i)=>{mT(i)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on($t.EncryptionError,t=>this.emit(O.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 y(this,void 0,void 0,function*(){return this.state===Z.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(N.RoomUpdate,i),e(r.sid))};this.engine.on(N.RoomUpdate,i),this.once(O.Disconnected,()=>{this.engine.off(N.RoomUpdate,i),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 eS(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,i)=>{this.onTrackAdded(e,t,i)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Z.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(N.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Z.Connected)&&this.emit(O.Reconnected)}).on(N.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.Offline,()=>{this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(O.Reconnecting)}).on(N.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(N.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(L.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}).on(N.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(O.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 Pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===Z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ka(new URL(e))&&t){this.regionUrlProvider=new yo(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Z.Disconnected&&(this.regionUrl=i,yield fetch(Qa(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Qa(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return y(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new kt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new kt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new kt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new kt({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new kt({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new kt({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new kt({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>y(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Dr({reason:rt.CLIENT_INITIATED,action:Bn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new kt({scenario:{case:"subscriberBandwidth",value:mn(t)}});break;case"leave-full-reconnect":r=new kt({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,l,c,u,d,h,f,g;let m=!0,v=!1;const b=a?{exact:r}:r;if(i==="audioinput"){v=s.localParticipant.audioTrackPublications.size===0;const S=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===P.Source.Microphone);try{m=(yield Promise.all(x.map(k=>{var T;return(T=k.audioTrack)===null||T===void 0?void 0:T.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=S,k}}else if(i==="videoinput"){v=s.localParticipant.videoTrackPublications.size===0;const S=(l=s.getActiveDevice(i))!==null&&l!==void 0?l:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.videoTrackPublications.values()).filter(k=>k.source===P.Source.Camera);try{m=(yield Promise.all(x.map(k=>{var T;return(T=k.videoTrack)===null||T===void 0?void 0:T.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.videoCaptureDefaults.deviceId=S,k}}else if(i==="audiooutput"){if(!qa()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(c=yield Pe.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(g=s.options).audioOutput)!==null&&u!==void 0||(g.audioOutput={});const S=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(x=>x.setAudioOutput({deviceId:r})))}catch(x){throw s.options.audioOutput.deviceId=S,x}}return(v||i==="audiooutput")&&(s.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((f=s.options.audioOutput)===null||f===void 0?void 0:f.deviceId)||r),s.emit(O.ActiveDeviceChanged,i,r)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(L.AttributesChanged,this.onLocalAttributesChanged).on(L.TrackMuted,this.onLocalTrackMuted).on(L.TrackUnmuted,this.onLocalTrackUnmuted).on(L.LocalTrackPublished,this.onLocalTrackPublished).on(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(L.MediaDevicesError,this.onMediaDevicesError).on(L.AudioStreamAcquired,this.startAudio).on(L.ChatMessage,this.onLocalChatMessageSent).on(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Z.Connecting||this.state===Z.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,d)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,d);return}if(this.state===Z.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=tT(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const l=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),l.addSubscribedMediaTrack(e,o,t,i,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Z.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,a,o;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(a=r.track)===null||a===void 0||a.stop()):(o=r.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(L.AttributesChanged,this.onLocalAttributesChanged).off(L.TrackMuted,this.onLocalTrackMuted).off(L.TrackUnmuted,this.onLocalTrackUnmuted).off(L.LocalTrackPublished,this.onLocalTrackPublished).off(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(L.MediaDevicesError,this.onMediaDevicesError).off(L.AudioStreamAcquired,this.startAudio).off(L.ChatMessage,this.onLocalChatMessageSent).off(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),We()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Z.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return y(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Yr(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:l=>{s=l,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new rS(a,o,Yr(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:l=>{s=l,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new sS(a,o,Yr(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.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 i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return y(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=th())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ge(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(O.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=is.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new is(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,i),i.on(L.TrackPublished,r=>{this.emitWhenConnected(O.TrackPublished,r,i)}).on(L.TrackSubscribed,(r,s)=>{r.kind===P.Kind.Audio?(r.on(A.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(A.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===P.Kind.Video&&(r.on(A.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(A.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,r,s,i)}).on(L.TrackUnpublished,r=>{this.emit(O.TrackUnpublished,r,i)}).on(L.TrackUnsubscribed,(r,s)=>{this.emit(O.TrackUnsubscribed,r,s,i)}).on(L.TrackMuted,r=>{this.emitWhenConnected(O.TrackMuted,r,i)}).on(L.TrackUnmuted,r=>{this.emitWhenConnected(O.TrackUnmuted,r,i)}).on(L.ParticipantMetadataChanged,r=>{this.emitWhenConnected(O.ParticipantMetadataChanged,r,i)}).on(L.ParticipantNameChanged,r=>{this.emitWhenConnected(O.ParticipantNameChanged,r,i)}).on(L.AttributesChanged,r=>{this.emitWhenConnected(O.ParticipantAttributesChanged,r,i)}).on(L.ConnectionQualityChanged,r=>{this.emitWhenConnected(O.ConnectionQualityChanged,r,i)}).on(L.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,r,i)}).on(L.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,r,s,i)}).on(L.TrackSubscriptionFailed,(r,s)=>{this.emit(O.TrackSubscriptionFailed,r,i,s)}).on(L.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,r,s,i)}).on(L.Active,()=>{this.emitWhenConnected(O.ParticipantActive,i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),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&&pT(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=Ae.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,rt.STATE_MISMATCH))):e=0},vS)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ae.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===Z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Z.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return y(this,void 0,void 0,function*(){var t,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ar({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ue.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new un({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(Z.Connected),r.video){const a=new So(P.Kind.Video,new Un({source:Ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO,name:"video-dummy"}),new ts(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Jd(160*((t=s.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(a),this.localParticipant.emit(L.LocalTrackPublished,a)}if(r.audio){const a=new So(P.Kind.Audio,new Un({source:Ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO}),new Zr(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Xa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(L.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new un({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Dn.ACTIVE,tracks:[],joinedAt:ue.parse(Date.now())});const l=this.getOrCreateParticipant(o.identity,o);if(s.video){const c=Jd(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Un({source:Ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const c=Xa(),u=new Un({source:Ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:it.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}l.updateInfo(o)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const s=Ih(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}Kn.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Ih(n){return n.map(e=>{if(e)return Array.isArray(e)?Ih(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var dt;(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"})(dt||(dt={}));class tn extends Tt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=dt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Kn(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==dt.IDLE)throw Error("check is running already");this.setStatus(dt.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!==dt.SKIPPED&&this.setStatus(this.isSuccess()?dt.SUCCESS:dt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return y(this,void 0,void 0,function*(){return this.room.state===Z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return y(this,void 0,void 0,function*(){this.room&&this.room.state!==Z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(dt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Ge(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 bS extends tn{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new yo(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return y(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,l=1e6/a,c="A".repeat(a),u=Date.now();for(let g=0;g<l;g++)yield s.write(c);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Co=1e4;class yS extends tn{get description(){return"Connection via UDP vs TCP"}perform(){return y(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 i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Co/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Co/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return y(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 i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();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},d=setInterval(()=>y(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Co)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class kS extends tn{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield hS();if(yield eh(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class TS extends tn{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield dS();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return y(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,l;const c=document.createElement("canvas"),u=e.getSettings(),d=(a=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(l=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&l!==void 0?l:720;c.width=d,c.height=h;const f=c.getContext("2d");f.drawImage(i,0,0);const m=f.getImageData(0,0,c.width,c.height).data;let v=!0;for(let b=0;b<m.length;b+=4)if(m[b]!==0||m[b+1]!==0||m[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),i.remove()})}}class SS extends tn{get description(){return"Resuming connection after interruption"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const l=t.engine.client.onClose;if(l&&l(""),yield a,i){if(!r||t.state!==Z.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 CS extends tn{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new ro,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,a=!1,o=!1;for(let l of r.iceServers)for(let c of l.urls)c.startsWith("turn:")?(a=!0,o=!0):c.startsWith("turns:")&&(a=!0,o=!0,s=!0),c.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class xS extends tn{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const a=new RTCIceCandidate(r);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(wS(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),$.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function wS(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 _S extends tn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return y(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ro;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===Nu.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class cx extends Tt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:dt.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!==dt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return y(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(_S)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(xS)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(CS)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(SS)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(kS)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(TS)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(yS);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(bS)})}}const ES=/\{[^{}]+\}/g;function PS(){return Math.random().toString(36).slice(2,11)}function RS(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=Lh(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:f=i,Request:g=t,headers:m,params:v={},parseAs:b="json",querySerializer:S,bodySerializer:x=s??OS,body:k,...T}=d||{};h&&(e=Lh(h));let C=typeof r=="function"?r:Nh(r);S&&(C=typeof S=="function"?S:Nh({...typeof r=="object"?r:{},...S}));const _=k===void 0?void 0:x(k),R=_===void 0||_ instanceof FormData?{}:{"Content-Type":"application/json"},I={redirect:"follow",...o,...T,body:_,headers:NS(R,a,m,v.header)};let M,D,j=new t(AS(u,{baseUrl:e,params:v,querySerializer:C}),I);for(const z in T)z in j||(j[z]=T[z]);if(l.length){M=PS(),D=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:C,bodySerializer:x});for(const z of l)if(z&&typeof z=="object"&&typeof z.onRequest=="function"){const W=await z.onRequest({request:j,schemaPath:u,params:v,options:D,id:M});if(W){if(!(W instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");j=W}}}let V=await f(j);if(l.length)for(let z=l.length-1;z>=0;z--){const W=l[z];if(W&&typeof W=="object"&&typeof W.onResponse=="function"){const F=await W.onResponse({request:j,response:V,schemaPath:u,params:v,options:D,id:M});if(F){if(!(F instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");V=F}}}if(V.status===204||V.headers.get("Content-Length")==="0")return V.ok?{data:{},response:V}:{error:{},response:V};if(V.ok)return b==="stream"?{data:V.body,response:V}:{data:await V[b](),response:V};let q=await V.text();try{q=JSON.parse(q)}catch{}return{error:q,response:V}}return{GET(u,d){return c(u,{...d,method:"GET"})},PUT(u,d){return c(u,{...d,method:"PUT"})},POST(u,d){return c(u,{...d,method:"POST"})},DELETE(u,d){return c(u,{...d,method:"DELETE"})},OPTIONS(u,d){return c(u,{...d,method:"OPTIONS"})},HEAD(u,d){return c(u,{...d,method:"HEAD"})},PATCH(u,d){return c(u,{...d,method:"PATCH"})},TRACE(u,d){return c(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");l.push(d)}},eject(...u){for(const d of u){const h=l.indexOf(d);h!==-1&&l.splice(h,1)}}}}function rs(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 Oh(n,e,t){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)i.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const a=i.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(const a in e){const o=t.style==="deepObject"?`${n}[${a}]`:a;i.push(rs(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Ah(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}const i={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(const s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(rs(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Nh(n){return function(t){const i=[];if(t&&typeof t=="object")for(const r in t){const s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;i.push(Ah(r,s,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof s=="object"){i.push(Oh(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(rs(r,s,n))}}return i.join("&")}}function IS(n,e){let t=n;for(const i of n.match(ES)??[]){let r=i.substring(1,i.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const o=e[r];if(Array.isArray(o)){t=t.replace(i,Ah(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,Oh(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${rs(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function OS(n){return n instanceof FormData?n:JSON.stringify(n)}function AS(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=IS(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function NS(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const i=t instanceof Headers?t.entries():Object.entries(t);for(const[r,s]of i)if(s===null)e.delete(r);else if(Array.isArray(s))for(const a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Lh(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Mh="Onboardee-Session-Token",Dh="OnboardeeSessionToken";class Uh{constructor(e){this.client=RS({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const i=window.localStorage.getItem(Dh);i&&t.headers.set(Mh,i)}return t},onResponse({response:t}){const i=t.headers.get(Mh);return i&&window.localStorage&&window.localStorage.setItem(Dh,i),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,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i},...r&&{course_id:r}}}})}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 getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}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:{content:t.content||""}})}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,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...i&&{limit:i.toString()}}}})}async updateProductKnowledgeBlock(e,t,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i}}}})}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 listAdminUsers(e){const t={};return e!=null&&e.search&&(t.search=e.search),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(t).length>0?{query:t}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,t,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:t,signal:i})}async deletePlanAutosave(e){return await this.client.DELETE("/api/plans/{id}/autosave",{params:{path:{id:e}}})}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,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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:{content:t.content||""}})}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,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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 i={token:e};return t!=null&&t.productId&&(i.product_id=t.productId),t!=null&&t.startDate&&(i.start_date=t.startDate),t!=null&&t.endDate&&(i.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:i}})}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:i}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...i&&{user:encodeURIComponent(i)}}}})}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}}})}async getGraphemes(){return await this.client.GET("/api/graphemes")}async listVoices(){return await this.client.GET("/api/voices")}async generateVoiceSample(e,t){return await this.client.POST("/api/voices/generate-sample",{body:{product_id:t,voice_id:e},parseAs:"stream"})}getClient(){return this.client}}const Bh="https://app.coragents.ai";class ss extends Cs{constructor(e,t,i,r){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=i,this.api=r.api||new Uh({baseUrl:Bh}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new Kn(s)),this.captureScreen=r.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("volume-check"),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(O.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(O.TrackSubscribed,i=>{i.kind==="audio"&&(i.attach(),i.source===P.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(i.mediaStream)))}),this.room.on(O.LocalTrackPublished,i=>{i.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(i.audioTrack.mediaStream))}),this.room.on(O.ParticipantAttributesChanged,i=>{if(!i["lk.agent.state"])return;const r=i["lk.agent.state"];switch(r){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",r)}}),this.room.on(O.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),s=JSON.parse(r);switch(s.status||s.request||s.type){case"course_progress":typeof s.current_step=="number"&&typeof s.total_steps=="number"&&Array.isArray(s.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,s.current_step),totalSteps:Math.max(1,s.total_steps),stepNames:s.step_names});break;case"open_text_input":this.emit("textInputRequested");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;case"transcript":this.emit("transcript",s.transcript,s.role);break;default:console.warn("[obi] unknown data received",s)}}catch(r){console.error("[obi] error parsing data",r)}}),this.room.localParticipant.registerRpcMethod("mic_check",async i=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async i=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let r=null,s=null;try{r=await this.captureScreen()}catch(a){r=null,a=a}if(!r||s)return console.error("[obi] error capturing screen",{error:s}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(a){return console.error("[obi] error sending screen capture",{error:a}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let i=0;i<9&&!(this.room.state===Z.Connected&&this.room.remoteParticipants.size>=1);i++)await new Promise(r=>setTimeout(r,1e3));if(!(this.room.state===Z.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 i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?this.speakingState="speaking":this.speakingState="listening"}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),this.say("Yes, I can hear you.")}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(i){i=i,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),e?this.say("Okay, I've shared my microphone with you."):this.say("I'm sorry, I wasn't able to share my microphone with you."),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,i;e.handleMuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,i;e.handleUnmuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.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 i=e.context.sampleRate/2/e.frequencyBinCount,r=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(r);const s=[],a=50,o=5e3,l=8,c=Math.pow(o/a,1/l);for(let u=0;u<l;u++){const d=a*Math.pow(c,u),h=a*Math.pow(c,u+1),f=Math.floor(d/i),g=Math.floor(h/i),m=Math.min(g,r.length),v=Math.min(f,m);if(v<m){const b=r.slice(v,m).reduce((S,x)=>S+x,0)/(m-v)/255;s.push(b)}else s.push(0)}return s}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,i,r={}){const s=JSON.parse(e),a=new ss(t,s.planId,i,r);return a.state=s.state,a.speakingState=s.speakingState,a.identity=s.identity||null,a.isPaused=s.isPaused||!1,a.sessionUuid=s.sessionUuid||null,a.roomId=s.roomId||null,a.joinToken=s.joinToken||null,a.roomUrl=s.roomUrl||null,a.startedAt=s.startedAt||null,a}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,i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,i}}class as extends Cs{constructor(e,t,i={}){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=i.api||new Uh({baseUrl:i.apiBaseUrl||Bh}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new ss(r,s,a,o)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var t,i,r,s,a;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=((i=o.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=o.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((s=o.data)==null?void 0:s.plan_is_completed)||[],this.showWidget=((a=o.data)==null?void 0:a.show_widget)||!1,e.planUuid){let l=null;try{const c=await this.api.getPlanSDK(e.planUuid);if(c.error)throw new Error(`Plan not found: ${c.error}`);c.data&&(l=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&&(l=u.data)}catch(u){console.error("[obi] error getting plan via both endpoints",{planErr:c,sessionErr:u})}}l?(this.selectedPlan=l,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(i=>{this.session=null,console.error("[obi] error starting session",i)}),this.session}async resumeSession(e){var t,i;return this.state,(t=this.session)==null||t.state,(i=this.session)==null||i.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(r=>{console.error("[obi] error joining room",{error:r}),r instanceof Error&&r.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 i,r,s;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const a=this.plans.findIndex(o=>{var l;return o.uuid===((l=this.selectedPlan)==null?void 0:l.uuid)});a!==-1&&(this.planIsCompleted[a]=!0)}(s=(r=this.session)==null?void 0:r.removeAllListeners)==null||s.call(r),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,i,r={}){const s=JSON.parse(e);if(s.serialisedAt){const o=new Date(s.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)return null}else throw new Error("Client was not serialised, assuming it's dead.");const a=new as(t,i,r);return a.state=s.state,a.identity=s.identity||null,a.product=s.product||null,a.plans=s.plans||[],a.selectedPlan=s.selectedPlan||null,a.selectedPlanUuid=s.selectedPlanUuid||null,a.showWidget=s.showWidget||!1,s.session&&(a.session=ss.deserialise(s.session,t,i,{api:a.api})),a}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var i,r,s;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(s=this.session)==null?void 0:s.sessionUuid})}}var os,H,Fh,vn,jh,Vh,Gh,Wh,xo,wo,_o,zh,Ci={},Hh=[],LS=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,xi=Array.isArray;function Ot(n,e){for(var t in e)n[t]=e[t];return n}function Eo(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Po(n,e,t){var i,r,s,a={};for(s in e)s=="key"?i=e[s]:s=="ref"?r=e[s]:a[s]=e[s];if(arguments.length>2&&(a.children=arguments.length>3?os.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return cs(n,a,i,r,null)}function cs(n,e,t,i,r){var s={type:n,props:e,key:t,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++Fh,__i:-1,__u:0};return r==null&&H.vnode!=null&&H.vnode(s),s}function Me(n){return n.children}function At(n,e){this.props=n,this.context=e}function $n(n,e){if(e==null)return n.__?$n(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"?$n(n):null}function qh(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 qh(n)}}function Ro(n){(!n.__d&&(n.__d=!0)&&vn.push(n)&&!ls.__r++||jh!=H.debounceRendering)&&((jh=H.debounceRendering)||Vh)(ls)}function ls(){for(var n,e,t,i,r,s,a,o=1;vn.length;)vn.length>o&&vn.sort(Gh),n=vn.shift(),o=vn.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=Ot({},i)).__v=i.__v+1,H.vnode&&H.vnode(t),Io(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??$n(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,Jh(s,t,a),t.__e!=r&&qh(t)));ls.__r=0}function Kh(n,e,t,i,r,s,a,o,l,c,u){var d,h,f,g,m,v,b=i&&i.__k||Hh,S=e.length;for(l=MS(t,e,b,l,S),d=0;d<S;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?Ci:b[f.__i]||Ci,f.__i=d,v=Io(n,f,h,r,s,a,o,l,c,u),g=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Oo(h.ref,null,f),u.push(f.ref,f.__c||g,f)),m==null&&g!=null&&(m=g),4&f.__u||h.__k===f.__k?l=$h(f,l,n):typeof f.type=="function"&&v!==void 0?l=v:g&&(l=g.nextSibling),f.__u&=-7);return t.__e=m,l}function MS(n,e,t,i,r){var s,a,o,l,c,u=t.length,d=u,h=0;for(n.__k=new Array(r),s=0;s<r;s++)(a=e[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(l=s+h,(a=n.__k[s]=typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?cs(null,a,null,null,null):xi(a)?cs(Me,{children:a},null,null,null):a.constructor==null&&a.__b>0?cs(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=n,a.__b=n.__b+1,o=null,(c=a.__i=DS(a,t,l,d))!=-1&&(d--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(r>u?h--:r<u&&h++),typeof a.type!="function"&&(a.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,a.__u|=4))):n.__k[s]=null;if(d)for(s=0;s<u;s++)(o=t[s])!=null&&!(2&o.__u)&&(o.__e==i&&(i=$n(o)),Zh(o,o));return i}function $h(n,e,t){var i,r;if(typeof n.type=="function"){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,e=$h(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=$n(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function us(n,e){return e=e||[],n==null||typeof n=="boolean"||(xi(n)?n.some(function(t){us(t,e)}):e.push(n)),e}function DS(n,e,t,i){var r,s,a=n.key,o=n.type,l=e[t];if(l===null&&n.key==null||l&&a==l.key&&o==l.type&&!(2&l.__u))return t;if(i>(l!=null&&!(2&l.__u)?1:0))for(r=t-1,s=t+1;r>=0||s<e.length;){if(r>=0){if((l=e[r])&&!(2&l.__u)&&a==l.key&&o==l.type)return r;r--}if(s<e.length){if((l=e[s])&&!(2&l.__u)&&a==l.key&&o==l.type)return s;s++}}return-1}function Yh(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||LS.test(e)?t:t+"px"}function ds(n,e,t,i,r){var s;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof i=="string"&&(n.style.cssText=i=""),i)for(e in i)t&&e in t||Yh(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||Yh(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Wh,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+s]=t,t?i?t.u=i.u:(t.u=xo,n.addEventListener(e,s?_o:wo,s)):n.removeEventListener(e,s?_o:wo,s);else{if(r=="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 Xh(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=xo++;else if(e.t<t.u)return;return t(H.event?H.event(e):e)}}}function Io(n,e,t,i,r,s,a,o,l,c){var u,d,h,f,g,m,v,b,S,x,k,T,C,_,R,I,M,D=e.type;if(e.constructor!=null)return null;128&t.__u&&(l=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=H.__b)&&u(e);e:if(typeof D=="function")try{if(b=e.props,S="prototype"in D&&D.prototype.render,x=(u=D.contextType)&&i[u.__c],k=u?x?x.props.value:u.__:i,t.__c?v=(d=e.__c=t.__c).__=d.__E:(S?e.__c=d=new D(b,k):(e.__c=d=new At(b,k),d.constructor=D,d.render=BS),x&&x.sub(d),d.props=b,d.state||(d.state={}),d.context=k,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),S&&d.__s==null&&(d.__s=d.state),S&&D.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Ot({},d.__s)),Ot(d.__s,D.getDerivedStateFromProps(b,d.__s))),f=d.props,g=d.state,d.__v=e,h)S&&D.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),S&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(S&&D.getDerivedStateFromProps==null&&b!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,k),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,k)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(j){j&&(j.__=e)}),T=0;T<d._sb.length;T++)d.__h.push(d._sb[T]);d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,k),S&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,g,m)})}if(d.context=k,d.props=b,d.__P=n,d.__e=!1,C=H.__r,_=0,S){for(d.state=d.__s,d.__d=!1,C&&C(e),u=d.render(d.props,d.state,d.context),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[]}else do d.__d=!1,C&&C(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++_<25);d.state=d.__s,d.getChildContext!=null&&(i=Ot(Ot({},i),d.getChildContext())),S&&!h&&d.getSnapshotBeforeUpdate!=null&&(m=d.getSnapshotBeforeUpdate(f,g)),I=u,u!=null&&u.type===Me&&u.key==null&&(I=Qh(u.props.children)),o=Kh(n,xi(I)?I:[I],e,t,i,r,s,a,o,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),v&&(d.__E=d.__=null)}catch(j){if(e.__v=null,l||s!=null)if(j.then){for(e.__u|=l?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,e.__e=o}else for(M=s.length;M--;)Eo(s[M]);else e.__e=t.__e,e.__k=t.__k;H.__e(j,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=US(t.__e,e,t,i,r,s,a,l,c);return(u=H.diffed)&&u(e),128&e.__u?void 0:o}function Jh(n,e,t){for(var i=0;i<t.length;i++)Oo(t[i],t[++i],t[++i]);H.__c&&H.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){H.__e(s,r.__v)}})}function Qh(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:xi(n)?n.map(Qh):Ot({},n)}function US(n,e,t,i,r,s,a,o,l){var c,u,d,h,f,g,m,v=t.props,b=e.props,S=e.type;if(S=="svg"?r="http://www.w3.org/2000/svg":S=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((f=s[c])&&"setAttribute"in f==!!S&&(S?f.localName==S:f.nodeType==3)){n=f,s[c]=null;break}}if(n==null){if(S==null)return document.createTextNode(b);n=document.createElementNS(r,S,b.is&&b),o&&(H.__m&&H.__m(e,s),o=!1),s=null}if(S==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&os.call(n.childNodes),v=t.props||Ci,!o&&s!=null)for(v={},c=0;c<n.attributes.length;c++)v[(f=n.attributes[c]).name]=f.value;for(c in v)if(f=v[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=f;else if(!(c in b)){if(c=="value"&&"defaultValue"in b||c=="checked"&&"defaultChecked"in b)continue;ds(n,c,null,f,r)}}for(c in b)f=b[c],c=="children"?h=f:c=="dangerouslySetInnerHTML"?u=f:c=="value"?g=f:c=="checked"?m=f:o&&typeof f!="function"||v[c]===f||ds(n,c,f,v[c],r);if(u)o||d&&(u.__html==d.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(d&&(n.innerHTML=""),Kh(e.type=="template"?n.content:n,xi(h)?h:[h],e,t,i,S=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&$n(t,0),o,l),s!=null)for(c=s.length;c--;)Eo(s[c]);o||(c="value",S=="progress"&&g==null?n.removeAttribute("value"):g!=null&&(g!==n[c]||S=="progress"&&!g||S=="option"&&g!=v[c])&&ds(n,c,g,v[c],r),c="checked",m!=null&&m!=n[c]&&ds(n,c,m,v[c],r))}return n}function Oo(n,e,t){try{if(typeof n=="function"){var i=typeof n.__u=="function";i&&n.__u(),i&&e==null||(n.__u=n(e))}else n.current=e}catch(r){H.__e(r,t)}}function Zh(n,e,t){var i,r;if(H.unmount&&H.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||Oo(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){H.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&Zh(i[r],e,t||typeof n.type!="function");t||Eo(n.__e),n.__c=n.__=n.__e=void 0}function BS(n,e,t){return this.constructor(n,t)}function FS(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),H.__&&H.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Io(e,n=(!i&&t||e).__k=Po(Me,null,[n]),r||Ci,Ci,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?os.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),Jh(s,n,a)}function jS(n){function e(t){var i,r;return this.getChildContext||(i=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&i.forEach(function(a){a.__e=!0,Ro(a)})},this.sub=function(s){i.add(s);var a=s.componentWillUnmount;s.componentWillUnmount=function(){i&&i.delete(s),a&&a.call(s)}}),t.children}return e.__c="__cC"+zh++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}os=Hh.slice,H={__e:function(n,e,t,i){for(var r,s,a;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(n)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,i||{}),a=r.__d),a)return r.__E=r}catch(o){n=o}throw n}},Fh=0,At.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ot({},this.state),typeof n=="function"&&(n=n(Ot({},t),this.props)),n&&Ot(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Ro(this))},At.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Ro(this))},At.prototype.render=Me,vn=[],Vh=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Gh=function(n,e){return n.__v.__b-e.__v.__b},ls.__r=0,Wh=/(PointerCapture)$|Capture$/i,xo=0,wo=Xh(!1),_o=Xh(!0),zh=0;var VS=0;function p(n,e,t,i,r,s){e||(e={});var a,o,l=e;if("ref"in l)for(o in l={},e)o=="ref"?a=e[o]:l[o]=e[o];var c={type:n,props:l,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--VS,__i:-1,__u:0,__source:r,__self:s};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)l[o]===void 0&&(l[o]=a[o]);return H.vnode&&H.vnode(c),c}var bn,de,Ao,ef,wi=0,tf=[],ke=H,nf=ke.__b,rf=ke.__r,sf=ke.diffed,af=ke.__c,of=ke.unmount,cf=ke.__;function _i(n,e){ke.__h&&ke.__h(de,n,wi||e),wi=0;var t=de.__H||(de.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function Y(n){return wi=1,GS(df,n)}function GS(n,e,t){var i=_i(bn++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):df(void 0,e),function(o){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,o);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=de,!de.__f)){var r=function(o,l,c){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!s||s.call(this,o,l,c);var d=i.__c.props!==o;return u.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(d=!0)}}),s&&s.call(this,o,l,c)||d};de.__f=!0;var s=de.shouldComponentUpdate,a=de.componentWillUpdate;de.componentWillUpdate=function(o,l,c){if(this.__e){var u=s;s=void 0,r(o,l,c),s=u}a&&a.call(this,o,l,c)},de.shouldComponentUpdate=r}return i.__N||i.__}function ze(n,e){var t=_i(bn++,3);!ke.__s&&Mo(t.__H,e)&&(t.__=n,t.u=e,de.__H.__h.push(t))}function hs(n,e){var t=_i(bn++,4);!ke.__s&&Mo(t.__H,e)&&(t.__=n,t.u=e,de.__h.push(t))}function Ct(n){return wi=5,No(function(){return{current:n}},[])}function No(n,e){var t=_i(bn++,7);return Mo(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function WS(n,e){return wi=8,No(function(){return n},e)}function lf(n){var e=de.context[n.__c],t=_i(bn++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(de)),e.props.value):n.__}function zS(){for(var n;n=tf.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(fs),n.__H.__h.forEach(Lo),n.__H.__h=[]}catch(e){n.__H.__h=[],ke.__e(e,n.__v)}}ke.__b=function(n){de=null,nf&&nf(n)},ke.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),cf&&cf(n,e)},ke.__r=function(n){rf&&rf(n),bn=0;var e=(de=n.__c).__H;e&&(Ao===de?(e.__h=[],de.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(fs),e.__h.forEach(Lo),e.__h=[],bn=0)),Ao=de},ke.diffed=function(n){sf&&sf(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(tf.push(e)!==1&&ef===ke.requestAnimationFrame||((ef=ke.requestAnimationFrame)||HS)(zS)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Ao=de=null},ke.__c=function(n,e){e.some(function(t){try{t.__h.forEach(fs),t.__h=t.__h.filter(function(i){return!i.__||Lo(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],ke.__e(i,t.__v)}}),af&&af(n,e)},ke.unmount=function(n){of&&of(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{fs(i)}catch(r){e=r}}),t.__H=void 0,e&&ke.__e(e,t.__v))};var uf=typeof requestAnimationFrame=="function";function HS(n){var e,t=function(){clearTimeout(i),uf&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);uf&&(e=requestAnimationFrame(t))}function fs(n){var e=de,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),de=e}function Lo(n){var e=de;n.__c=n.__(),de=e}function Mo(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function df(n,e){return typeof e=="function"?e(n):e}function qS({size:n=24,color:e="#000"}){return p("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:[p("path",{d:"M18 6 6 18"}),p("path",{d:"m6 6 12 12"})]})}function hf({onClose:n}){return p("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:p(qS,{})})}function ff({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Ct(null),a=Ct(null);ze(()=>{const u=s.current;u&&(n&&!u.open?u.showModal():!n&&u.open&&(a.current="programmatic",u.close()))},[n]);const o=u=>{const d=s.current;u.target===d&&!r&&(a.current="user-initiated",d==null||d.close())},l=u=>{u.preventDefault(),a.current||(a.current="user-initiated");const d=a.current;a.current=null,t==null||t(d)},c=()=>{var u;a.current="user-initiated",(u=s.current)==null||u.close()};return ze(()=>{const u=s.current;if(u)return u.addEventListener("click",o),u.addEventListener("close",l),()=>{u.removeEventListener("click",o),u.removeEventListener("close",l)}},[t]),p("dialog",{ref:s,className:`modal-${i}`,children:[p(hf,{onClose:c}),p("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Do(n){const{children:e,className:t="",...i}=n;return p("div",{className:`${t} obi-panel`,...i,children:e})}function ps({className:n="",isActive:e=!1,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),p("div",{className:o,onMouseEnter:r,onMouseLeave:s,children:p("div",{className:`obi-pill pill ${n}`,onClick:i,children:a})})}function KS({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const l=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return p("div",{className:l,...o,children:p("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function $S({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const l=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return p("div",{className:l,...o,children:p("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function yn({type:n,size:e=24}){return p("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:YS(n)})}function YS(n){switch(n){case"pause":return p(Me,{children:[p("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),p("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return p(Me,{children:p("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 p(Me,{children:[p("path",{d:"M18 6 6 18"}),p("path",{d:"m6 6 12 12"})]});case"message":return p(Me,{children:p("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 p(Me,{children:[p("path",{d:"m14 10 7-7"}),p("path",{d:"M20 10h-6V4"}),p("path",{d:"m3 21 7-7"}),p("path",{d:"M4 14h6v6"})]});case"voice":return p(Me,{children:[p("path",{d:"M2 10v3"}),p("path",{d:"M6 6v11"}),p("path",{d:"M10 3v18"}),p("path",{d:"M14 8v7"}),p("path",{d:"M18 5v13"}),p("path",{d:"M22 10v3"})]});case"open":return p(Me,{children:[p("path",{d:"M12 7v14"}),p("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 Uo=jS(null);function XS({children:n}){const e=lf(Uo);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:i,setIsOpen:r,setAnimating:s,targetRef:a,trigger:o,onChange:l,delayMs:c}=e,u=Ct(null),d=pf(a,s),[h,f]=Y(!1);ze(()=>{t!==void 0&&t!==h&&(t?m():v()),f(t)},[t]),ze(()=>()=>{u.current&&clearTimeout(u.current)},[]);function g(){u.current&&(clearTimeout(u.current),u.current=null)}function m(){g(),c>0?u.current=setTimeout(()=>{l==null||l(!0),r(!0),u.current=null},c):(l==null||l(!0),r(!0))}function v(){g(),l==null||l(!1),r(!1)}const b=()=>{o==="click"&&(i?v():m())};function S(){o==="hover"&&m()}function x(){o==="hover"&&v()}return p("div",{ref:d,class:"target",onClick:b,onMouseEnter:S,onMouseLeave:x,children:n})}function JS({children:n}){const e=lf(Uo);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:i,setAnimating:r,targetRef:s,contentRef:a}=e,o=pf(a,r);return hs(()=>{if(t&&!i&&s.current&&a.current){const l=a.current;if(!l)return;const c=s.current;if(!c)return;const u=l.getBoundingClientRect(),d=c.getBoundingClientRect(),h=d.right-d.left;l.style.top=`${u.top-u.bottom-(8+e.offset)}px`,l.style.left=`${-(u.right-u.left-h)/2}px`}},[t,i]),t?p("div",{ref:o,class:"content",style:{opacity:i?0:1},children:n}):null}function He({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,l]=Y(!1),[c,u]=Y(!1),d=Ct(null),h=Ct(null),f={controlledOpen:e,isOpen:o,setIsOpen:l,animating:c,setAnimating:u,targetRef:d,contentRef:h,trigger:n,onChange:t,delayMs:r,offset:s};return p(Uo.Provider,{value:f,children:p("div",{class:`obi-popout ${a}`,children:i})})}He.Target=XS,He.Content=JS;function pf(n,e){const t=Ct(null),i=Ct(null),r=Ct(!0),s=WS(a=>{if(n.current=a,!a){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function o(){if(r.current){r.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}i.current=new ResizeObserver(o),i.current.observe(a,{box:"border-box"})},[]);return ze(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),s}function ht({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:p(yn,{type:"close",size:16}),pause:p(yn,{type:"pause",size:16}),play:p(yn,{type:"play",size:16}),message:p(yn,{type:"message",size:16}),minimize:p(yn,{type:"minimize",size:16}),voice:p(yn,{type:"voice",size:16}),open:p(yn,{type:"open",size:16})}[t],a={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=p("button",{class:`obi-button obi-round-button ${a} ${n}`,onClick:i?void 0:e,disabled:i,children:s});return r?p(He,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[p(He.Target,{children:o}),p(He.Content,{children:p("div",{className:"obi-round-button-title",children:r})})]}):o}const mf=8,ms=8,QS=50,ZS=.7,Yn=3;function gf({getBands:n,color:e="white"}){const t=Ct(null);return ze(()=>{if(!n)return;const i=setInterval(()=>{try{const r=n();if(!t.current)return;const s=t.current.querySelectorAll(".bar"),a=r&&r.length>0?r.slice(0,ms).map(o=>{const l=Math.abs(o);return Math.min(l/ZS*mf,mf)||Yn}):Array(ms).fill(Yn);for(;a.length<ms;)a.push(Yn);a.forEach((o,l)=>{if(o<Yn&&(o=Yn),s[l]){const c=o*2;s[l].style.height=`${c}px`,s[l].style.display=o>0?"block":"none"}})}catch(r){console.warn("Error updating equaliser:",r)}},QS);return()=>{clearInterval(i)}},[n]),p("div",{className:"obi-equaliser",ref:t,children:Array.from({length:ms},(i,r)=>p("div",{className:"column",children:p("div",{className:"bar",style:{height:`${Yn}px`,backgroundColor:e,display:"block"}})},r))})}function nn({className:n,children:e,onClick:t}){return t?p("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):p("div",{class:`obi-message ${n}`,children:e})}const eC=8;function vf({color:n="white"}){return p("div",{className:"obi-loading-dots",children:Array.from({length:eC},(e,t)=>p("div",{className:"column",children:[p("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),p("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function tC({onContinue:n,onWrapUp:e}){return p(Do,{className:"obi-exit-survey",children:p(iC,{onContinue:n,onWrapUp:()=>{e()}})})}function nC({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=Y("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return p(Do,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?p(rC,{onReasonSelect:s}):p(sC,{onReasonSelect:s,onClose:t})})}function iC({onContinue:n,onWrapUp:e}){return p("div",{className:"obi-exit-survey-container",children:[p("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),p("div",{className:"obi-exit-survey-options",children:[p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),p("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 rC({onReasonSelect:n}){return p("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[p("div",{className:"obi-exit-survey-header",children:p("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),p("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),p("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"}),p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),p("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function sC({onReasonSelect:n,onClose:e}){const[t,i]=Y("");return p("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[p("div",{className:"obi-exit-survey-header",children:[p(hf,{onClose:e}),p("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),p("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[p("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:r=>i(r.target.value)}),p("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 aC(n,e){for(var t in e)n[t]=e[t];return n}function bf(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var i in e)if(i!=="__source"&&n[i]!==e[i])return!0;return!1}function yf(n,e){this.props=n,this.context=e}(yf.prototype=new At).isPureReactComponent=!0,yf.prototype.shouldComponentUpdate=function(n,e){return bf(this.props,n)||bf(this.state,e)};var kf=H.__b;H.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),kf&&kf(n)};var oC=H.__e;H.__e=function(n,e,t,i){if(n.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),r.__c(n,e)}oC(n,e,t,i)};var Tf=H.unmount;function Sf(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),n.__c.__H=null),(n=aC({},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(i){return Sf(i,e,t)})),n}function Cf(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Cf(i,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function Bo(){this.__u=0,this.o=null,this.__b=null}function xf(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function gs(){this.i=null,this.l=null}H.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Tf&&Tf(n)},(Bo.prototype=new At).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=xf(i.__v),s=!1,a=function(){s||(s=!0,t.__R=null,r?r(o):o())};t.__R=a;var o=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=Cf(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),n.then(a,a)},Bo.prototype.componentWillUnmount=function(){this.o=[]},Bo.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Sf(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&Po(Me,null,n.fallback);return r&&(r.__u&=-33),[Po(Me,null,e.__a?null:n.children),r]};var wf=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]}};(gs.prototype=new At).__a=function(n){var e=this,t=xf(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),wf(e,n,i)):r()};t?t(s):s()}},gs.prototype.render=function(n){this.i=null,this.l=new Map;var e=us(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},gs.prototype.componentDidUpdate=gs.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){wf(n,t,e)})};var cC=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,lC=/^(?: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]/,uC=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,dC=/[A-Z0-9]/g,hC=typeof document<"u",fC=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};At.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(At.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var _f=H.event;function pC(){}function mC(){return this.cancelBubble}function gC(){return this.defaultPrevented}H.event=function(n){return _f&&(n=_f(n)),n.persist=pC,n.isPropagationStopped=mC,n.isDefaultPrevented=gC,n.nativeEvent=n};var vC={enumerable:!1,configurable:!0,get:function(){return this.class}},Ef=H.vnode;H.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,i=e.type,r={},s=i.indexOf("-")===-1;for(var a in t){var o=t[a];if(!(a==="value"&&"defaultValue"in t&&o==null||hC&&a==="children"&&i==="noscript"||a==="class"||a==="className")){var l=a.toLowerCase();a==="defaultValue"&&"value"in t&&t.value==null?a="value":a==="download"&&o===!0?o="":l==="translate"&&o==="no"?o=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?a="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||fC(t.type)?l==="onfocus"?a="onfocusin":l==="onblur"?a="onfocusout":uC.test(a)&&(a=l):l=a="oninput":s&&lC.test(a)?a=a.replace(dC,"-$&").toLowerCase():o===null&&(o=void 0),l==="oninput"&&r[a=l]&&(a="oninputCapture"),r[a]=o}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=us(t.children).forEach(function(c){c.props.selected=r.value.indexOf(c.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=us(t.children).forEach(function(c){c.props.selected=r.multiple?r.defaultValue.indexOf(c.props.value)!=-1:r.defaultValue==c.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",vC)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=cC,Ef&&Ef(n)};var Pf=H.__r;H.__r=function(n){Pf&&Pf(n),n.__c};var Rf=H.diffed;H.diffed=function(n){Rf&&Rf(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 bC(n){const{placeholder:e="Type your message...",value:t,defaultValue:i,onChange:r,onSend:s,onCancel:a,onExpand:o,isLoading:l=!1,disabled:c=!1,maxLength:u=500,children:d}=n,[h,f]=Y(t||i||""),[g,m]=Y((t||i||"").length>24),v=Ct(null);hs(()=>{g&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,S=T=>{const C=T.currentTarget.value;t===void 0&&f(C),r==null||r(C)},x=T=>{T.key==="Escape"&&(f(t||i||""),m(!1),a==null||a()),T.key==="Enter"&&!T.shiftKey&&b.trim()&&(T.preventDefault(),f(t||i||""),m(!1),k()),(b||"").length>=24&&!g&&(m(!0),o==null||o(!0))};ze(()=>{v.current&&v.current.focus()},[v.current]);const k=()=>{!b.trim()||l||c||(s==null||s(b.trim()),t===void 0&&f(""))};return p("div",{className:`obi-message-input ${g?"expanded":""}`,children:[p("div",{className:"container",children:p("textarea",{ref:v,className:"field",placeholder:e,value:b,onInput:S,onKeyDown:x,disabled:c||l,maxLength:u,rows:1})}),p("div",{className:"button-container",children:[g&&p("div",{children:d}),p("button",{className:"obi-button send",onClick:k,disabled:!b.trim()||l||c,type:"button",children:p("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:p("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 yC(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r}=n,s=Array.from({length:t},(l,c)=>({isCompleted:c<e,stepNumber:c+1})),a=i[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${a}`;return p("div",{class:`obi-course-progress ${r||""}`,children:[p("div",{class:"obi-course-progress-steps",children:s.map((l,c)=>p("div",{class:"obi-course-progress-container",children:p("div",{class:`obi-course-progress-step ${l.isCompleted?"completed":""}`})},c))}),p("div",{class:"obi-course-progress-description",children:o})]})}function If({className:n="",size:e=64}){return p("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:p("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 kC(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=Y(null),[a,o]=Y(n.isActive??n.defaultIsActive??!1),[l,c]=Y(!1),[u,d]=Y(n.cancelling??!1),[h,f]=Y(n.messaging??!1),[g,m]=Y(!1),[v,b]=Y(h),[S,x]=Y(!1);hs(()=>{n.messaging!==void 0&&f(n.messaging)},[n.messaging]);function k(){o(!0),c(!1),x(!0),n.messaging!==void 0&&f(n.messaging)}function T(){}function C(){r&&(clearTimeout(r),s(null))}function _(){s(setTimeout(()=>{o(n.defaultIsActive??!1),x(!1)},400))}function R(ae){var ft;m(!1),(ft=n.onMessage)==null||ft.call(n,ae)}function I(){var ae;f(!1),m(!1),o(!1),c(!0),(ae=n.onMinimize)==null||ae.call(n)}function M(){var ae;f(!1),d(!0),m(!1),(ae=n.onCancelClick)==null||ae.call(n)}function D(){var ae;t||((ae=n.onOpen)==null||ae.call(n))}function j(ae){var ft,np,ip,rp,sp,ap;switch(ae){case"need-help":(ft=n.onMessage)==null||ft.call(n,"I'm struggling, can you look at my screen and help me out."),(np=n.onOneClickAction)==null||np.call(n,"need-help");break;case"continue":(ip=n.onMessage)==null||ip.call(n,"Okay, let's continue."),(rp=n.onOneClickAction)==null||rp.call(n,"continue");break;case"say-again":(sp=n.onMessage)==null||sp.call(n,"Please say that again."),(ap=n.onOneClickAction)==null||ap.call(n,"say-again");break}}function V(ae){var ft;n.messaging===void 0&&((ft=n.onMessagingChange)==null||ft.call(n,ae),f(ae)),ae||m(!1)}const q=n.isActive??((a||t)&&!l&&!e),z=q&&t,W=q&&t&&!g,F=n.speakingStatus==="user-speaking",G=n.speakingStatus==="thinking",J=n.speakingStatus==="busy",se=q&&!t&&!u&&S,ge=q&&t&&i&&!F&&!u,Te=q&&t&&!ge&&!F&&h!==v&&!u,et=q&&t&&i&&F&&!u,qe=q&&t&&!i&&F&&!u,xe=q&&t&&!i&&J&&!u,Nt=h&&F,Ke=se||ge||et||qe||Te||u,rn=400,Sn=q&&t&&!g,sx=se?5:10;return hs(()=>{b(h)},[F]),!t&&!u?p(TC,{...n}):!t&&u?p(SC,{onOtherSelect:()=>{var ae;(ae=n.onCancelReasonOther)==null||ae.call(n)},onCancelReason:ae=>{var ft;o(n.defaultIsActive??!1),d(!1),(ft=n.onCancelReason)==null||ft.call(n,ae)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):p(Do,{className:`obi-widget-panel ${z?"expanded":""} ${g?"maximized":""} ${h?"messaging":""} ${J?"tool-usage":""}`,children:[p("div",{className:`obi-widget ${q?"active":""} ${t?"in-plan":""}`,onMouseEnter:C,onMouseLeave:_,children:[W&&p(ht,{type:"cancel",onClick:M,disabled:u,title:"Cancel session"}),W&&!i&&p(ht,{type:"pause",onClick:n.onPause,title:"Pause session"}),W&&i&&p(ht,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(He,{className:"obi-widget-popout",open:Ke,trigger:null,delayMs:rn,offset:sx,children:[p(He.Target,{children:[Nt&&p(bC,{value:n.message,onCancel:()=>V(!1),onSend:R,onExpand:m,onChange:n.onMessageChange,children:p("div",{className:"obi-widget-buttons",children:[p(ht,{type:"cancel",onClick:M,disabled:u,title:"Cancel session"}),!i&&p(ht,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&p(ht,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(ht,{type:h?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>V(!h),title:h?"Voice input":"Text input"}),p(ht,{type:"minimize",onClick:I,title:"Minimize widget"})]})}),!Nt&&p(ps,{className:q&&!t?"button":"",isActive:q,speakingStatus:n.speakingStatus,onClick:D,onMouseEnter:k,onMouseLeave:T,children:[q&&!t&&!xe&&p("span",{className:"obi-widget-pill-text",children:"Tutorials"}),q&&t&&xe&&p("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),q&&t&&!G&&!xe&&p(gf,{getBands:n.spectrum}),q&&G&&!xe&&p(vf,{})]})]}),p(He.Content,{children:p("div",{onMouseLeave:_,children:[se&&p(nn,{onClick:D,children:"Click to see all"}),ge&&p(nn,{children:"Session will pause shortly"}),Te&&p(nn,{children:["Switched to ",h?"chat":"voice"]}),et&&p(nn,{children:"Paused"}),qe&&p("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[p(nn,{onClick:()=>j("need-help"),children:"Need help"}),p(nn,{onClick:()=>j("continue"),children:"Continue"}),p(nn,{onClick:()=>j("say-again"),children:"Say again"})]}),u&&p(tC,{onContinue:()=>{var ae;(ae=n.onCancelAbort)==null||ae.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var ae;(ae=n.onCancel)==null||ae.call(n)}})]})})]}),W&&p(ht,{type:h?"voice":"message",disabled:n.messaging!==void 0,onClick:()=>V(!h),title:h?"Voice input":"Text input"}),W&&p(ht,{type:"minimize",onClick:I,title:"Minimize widget"})]}),Sn&&n.courseProgress&&p("div",{className:`obi-course-progress-container ${h?"expanded":""}`,children:p(yC,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames})})]})}function TC(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=Y(null),[o,l]=Y(n.isActive??n.defaultIsActive??!1),[c,u]=Y(!1),[d,h]=Y(n.hovered??!1);function f(){var R;l(!0),u(!1),h(!0),(R=n.onHover)==null||R.call(n,!0)}function g(){}function m(){s&&(clearTimeout(s),a(null))}function v(){o&&a(setTimeout(()=>{var R;l(n.defaultIsActive??!1),h(!1),(R=n.onHover)==null||R.call(n,!1)},400))}function b(){l(!1),u(!0)}function S(){var R;(R=n.onOpen)==null||R.call(n)}const x=n.hovered??(d&&!c),k=n.isActive??(o&&!e&&!c),T=k&&x,C=`round-button ${k?"active":""}`;let _=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(_=`${t}/${i} completed`),p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:`obi-widget-out-of-plan ${x?"hover":""} ${k?"active":""}`,onMouseEnter:m,onMouseLeave:v,children:[p("div",{className:C,style:{width:"30px",height:"30px"}}),p(He,{className:"obi-widget-popout",open:T,trigger:null,delayMs:400,offset:5,children:[p(He.Target,{children:p($S,{className:k?"button":"",active:k,onClick:S,onMouseEnter:f,onMouseLeave:g,children:p("span",{className:"text",children:[p(If,{size:16}),_]})})}),p(He.Content,{children:p("div",{onMouseLeave:v,children:p(nn,{className:"message",onClick:S,children:"Click to see all"})})})]}),p(ht,{className:C,type:"minimize",onClick:b,title:"Minimize widget"})]})})}function SC(n){return p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:"obi-widget-out-of-plan",children:p(He,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[p(He.Target,{children:p(KS,{active:!1})}),p(He.Content,{children:p(nC,{onOtherSelect:()=>{var e;(e=n.onOtherSelect)==null||e.call(n)},onReasonSelect:(e,t)=>{var i;(i=n.onCancelReason)==null||i.call(n,e,t)},onClose:()=>{var e;(e=n.onClose)==null||e.call(n)}})})]})})})}function CC({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return p(ff,{open:n,onClose:t,preventOutsideClick:i,children:p("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function Xn({title:n="",subtitle:e="",agentName:t="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:s=!1,href:a=null,centerVisual:o,description:l,button:c,onAction:u}){const[d,h]=Y(s),[f,g]=Y(!1),[m,v]=Y(r);return ze(()=>{f||(r==="listening"&&m!=="listening"&&d&&h(!1),r!=="listening"&&!d&&h(!0)),v(r)},[r,d]),ze(()=>{h(s)},[s]),p("div",{className:"tour-content",children:p("div",{className:"container",children:[p("div",{className:"header",children:[p("h1",{className:"title",children:n}),p("p",{className:"subtitle",children:e})]}),p("div",{className:"visual",style:{background:"var(--obi-color-tint)"},children:o}),p("div",{className:"description",children:l}),p("div",{className:"button-container",children:c||p(a?"a":"button",{className:`action-button ${d?"disabled":""}`,onClick:()=>{d||(h(!0),g(!0),u==null||u())},disabled:d,...a?{href:a,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:p("span",{className:"button-text",children:(()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return i}})()})})})]})})}function xC({logoUrl:n="",appName:e="App"}){const[t,i]=Y(!1),[r,s]=Y(!1),a=()=>{i(!0)},o=()=>{s(!0),i(!1)},l={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&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!n||t||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return p("div",{style:l.container,children:p("div",{style:l.logoContainer,children:[p("div",{style:l.backgroundPattern}),p("div",{style:l.logoWrapper,children:[n&&p("img",{style:l.appLogo,src:n,alt:`${e} logo`,onError:a,onLoad:o}),p("div",{style:l.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function wC({session:n,speakingState:e,onAction:t}){const i=n.appName?`Navigate to ${n.appName}`:"Navigate to app",r=n.appName?`Open ${n.appName}`:"Open app",s=n.appName?`Enjoy the tutorial in ${n.appName}`:"Enjoy the tutorial";return p(Xn,{title:i,subtitle:"Click the button below to open the app",agentName:n.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:n.url,description:s,centerVisual:p(xC,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}function _C({}){return p("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:p(ps,{isActive:!0,children:p("div",{className:"obi-static-voice-visual",children:[p("div",{className:"column",children:p("div",{className:"bar bar-1"})}),p("div",{className:"column",children:p("div",{className:"bar bar-2"})}),p("div",{className:"column",children:p("div",{className:"bar bar-3"})}),p("div",{className:"column",children:p("div",{className:"bar bar-4"})}),p("div",{className:"column",children:p("div",{className:"bar bar-5"})}),p("div",{className:"column",children:p("div",{className:"bar bar-6"})}),p("div",{className:"column",children:p("div",{className:"bar bar-7"})}),p("div",{className:"column",children:p("div",{className:"bar bar-8"})})]})})})}function EC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,buttonText:"Start now",agentName:n.agentName||"Obi",speakingState:e,centerVisual:p(_C,{}),onAction:t})}function PC(){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 p("div",{style:n.host,children:[p("style",{children:`
43
43
  @keyframes pointToAllow {
44
44
  0%, 100% { transform: translate(0, 0); }
45
45
  50% { transform: translate(2px, -1px); }
46
46
  }
47
- `}),p("div",{style:n.container,children:[p("div",{style:n.permissionDialog,children:p("div",{style:n.permissionContent,children:[p("div",{style:n.permissionContentTop,children:[p("div",{style:n.micIconContainer,children:p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:n.micIcon,children:[p("path",{d:"M12 19v3"}),p("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),p("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]})}),p("div",{style:n.permissionText,children:"Use your microphone"})]}),p("button",{style:n.allowButton,children:"Allow"})]})}),p("div",{style:n.cursorPointer,children:p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:n.cursorSvg,children:[p("path",{d:"M12.586 12.586 19 19"}),p("path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.579a.5.5 0 0 0 .063-.947z"})]})})]})]})}function RC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:"Connect your microphone",subtitle:"Watch for the prompt in your browser",agentName:n.agentName||"Obi",buttonText:"Continue",speakingState:e,actionDisabled:!0,description:`${n.agentName||"Obi"} will guide you through the tutorial by talking with you.`,centerVisual:p(PC,{}),onAction:t})}function IC({}){return p("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:p(ps,{isActive:!0,children:p(vf,{})})})}function OC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:"Can you hear me?",subtitle:`Make sure your sound is on so you can hear ${n.agentName||"Obi"}`,agentName:n.agentName||"Obi",ignoreSpeakingState:!0,speakingState:e,actionDisabled:!1,description:`${n.agentName||"Obi"} will guide you through the tutorial by talking with you.`,centerVisual:p(IC,{}),onAction:t})}function AC(){const n={container:{display:"flex",justifyContent:"center",alignItems:"center"},skeletonContainer:{display:"flex",flexDirection:"column",flexShrink:0,gap:"10px",alignItems:"center",padding:"20px",margin:"0 auto",background:"white",borderRadius:"12px",border:"0.569px solid #E4E4E7",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",height:"234px",width:"344px"},headerSection:{display:"flex",position:"relative",gap:"16px",alignItems:"center",alignSelf:"stretch"},avatar:{position:"relative",background:"#F4F4F5",borderRadius:"50%",height:"55px",width:"55px",flexShrink:0,overflow:"hidden"},textLines:{display:"flex",position:"relative",flexDirection:"column",gap:"10px",alignItems:"flex-start",alignSelf:"stretch",width:"100%"},textLine:{position:"relative",borderRadius:"2px",background:"#F4F4F5",height:"18px",alignSelf:"stretch",overflow:"hidden"},contentSection:{display:"flex",position:"relative",flexDirection:"column",flexShrink:0,gap:"16px",justifyContent:"center",alignItems:"flex-start",alignSelf:"stretch",height:"62px"},contentBlock:{position:"relative",alignSelf:"stretch",borderRadius:"2px",background:"#F4F4F5",flex:"1 0 0",overflow:"hidden"},shimmer:{position:"absolute",top:0,left:"-150px",height:"100%",width:"150px",background:"linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.6), transparent)",animation:"skeleton-loading 2s infinite"}};return p("div",{style:n.container,children:[p("style",{children:`
47
+ `}),p("div",{style:n.container,children:[p("div",{style:n.permissionDialog,children:p("div",{style:n.permissionContent,children:[p("div",{style:n.permissionContentTop,children:[p("div",{style:n.micIconContainer,children:p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:n.micIcon,children:[p("path",{d:"M12 19v3"}),p("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),p("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]})}),p("div",{style:n.permissionText,children:"Use your microphone"})]}),p("button",{style:n.allowButton,children:"Allow"})]})}),p("div",{style:n.cursorPointer,children:p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:n.cursorSvg,children:[p("path",{d:"M12.586 12.586 19 19"}),p("path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.579a.5.5 0 0 0 .063-.947z"})]})})]})]})}function RC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:"Connect your microphone",subtitle:"Watch for the prompt in your browser",agentName:n.agentName||"Obi",buttonText:"Continue",speakingState:e,actionDisabled:!0,description:`${n.agentName||"Obi"} will guide you through the tutorial by talking with you.`,centerVisual:p(PC,{}),onAction:t})}function IC({}){return p("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:p(ps,{isActive:!0,children:p(vf,{})})})}function OC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:"Can you hear me?",subtitle:`Make sure your sound is on so you can hear ${n.agentName||"Obi"}`,agentName:n.agentName||"Obi",speakingState:e,actionDisabled:!1,description:`${n.agentName||"Obi"} will guide you through the tutorial by talking with you.`,centerVisual:p(IC,{}),onAction:t})}function AC(){const n={container:{display:"flex",justifyContent:"center",alignItems:"center"},skeletonContainer:{display:"flex",flexDirection:"column",flexShrink:0,gap:"10px",alignItems:"center",padding:"20px",margin:"0 auto",background:"white",borderRadius:"12px",border:"0.569px solid #E4E4E7",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",height:"234px",width:"344px"},headerSection:{display:"flex",position:"relative",gap:"16px",alignItems:"center",alignSelf:"stretch"},avatar:{position:"relative",background:"#F4F4F5",borderRadius:"50%",height:"55px",width:"55px",flexShrink:0,overflow:"hidden"},textLines:{display:"flex",position:"relative",flexDirection:"column",gap:"10px",alignItems:"flex-start",alignSelf:"stretch",width:"100%"},textLine:{position:"relative",borderRadius:"2px",background:"#F4F4F5",height:"18px",alignSelf:"stretch",overflow:"hidden"},contentSection:{display:"flex",position:"relative",flexDirection:"column",flexShrink:0,gap:"16px",justifyContent:"center",alignItems:"flex-start",alignSelf:"stretch",height:"62px"},contentBlock:{position:"relative",alignSelf:"stretch",borderRadius:"2px",background:"#F4F4F5",flex:"1 0 0",overflow:"hidden"},shimmer:{position:"absolute",top:0,left:"-150px",height:"100%",width:"150px",background:"linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.6), transparent)",animation:"skeleton-loading 2s infinite"}};return p("div",{style:n.container,children:[p("style",{children:`
48
48
  @keyframes skeleton-loading {
49
49
  0% { transform: translateX(-150px); }
50
50
  50% { transform: translateX(344px); }
@@ -52,4 +52,4 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
52
52
  }
53
53
  `}),p("article",{style:n.skeletonContainer,role:"status","aria-label":"Loading content",children:[p("section",{style:n.headerSection,children:[p("div",{style:n.avatar,role:"img","aria-label":"Loading avatar",children:p("div",{style:n.shimmer})}),p("div",{style:n.textLines,children:[p("div",{style:n.textLine,role:"presentation","aria-label":"Loading text line 1",children:p("div",{style:n.shimmer})}),p("div",{style:n.textLine,role:"presentation","aria-label":"Loading text line 2",children:p("div",{style:n.shimmer})})]})]}),p("section",{style:n.contentSection,children:p("div",{style:n.contentBlock,role:"presentation","aria-label":"Loading card content",children:p("div",{style:n.shimmer})})})]})]})}function NC({}){const n={host:{display:"block"},shareContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"grid",placeItems:"center",overflow:"hidden",position:"relative",backgroundColor:"var(--obi-color-tint)"},controlsRow:{zIndex:10,gridRowStart:1,gridColumnStart:1,display:"flex",alignSelf:"flex-start",marginTop:"36px",alignItems:"center",gap:"8px"},monitorIconContainer:{display:"flex",height:"40px",width:"40px",aspectRatio:"1",alignItems:"center",justifyContent:"center",gap:"8px",borderRadius:"2px",border:"1px solid #E4E4E7",background:"#F8FAFC",padding:"8px"},monitorIcon:{width:"24px",height:"24px",color:"#111827"},tabSelector:{display:"flex",width:"260px",height:"40px",padding:"4px",alignItems:"center",borderRadius:"2px",background:"#E4E4E7"},tabButton:e=>({display:"flex",flex:1,alignSelf:"stretch",alignItems:"center",justifyContent:"center",gap:"10px",borderRadius:"2px",padding:"6px 12px",border:"none",cursor:"pointer",fontFamily:"'Satoshi', sans-serif",fontSize:"14px",fontWeight:500,opacity:e?1:.4,background:e?"white":"#F8FAFC",boxShadow:e?"0 1px 2px 0 rgba(0, 0, 0, 0.05)":"none"}),skeletonContainer:{marginTop:"104px",gridColumnStart:1,gridRowStart:1,alignSelf:"center"}};return p("div",{style:n.host,children:p("div",{style:n.shareContainer,children:[p("div",{style:n.controlsRow,children:[p("div",{style:n.monitorIconContainer,children:p("svg",{style:n.monitorIcon,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[p("rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",ry:"2"}),p("line",{x1:"8",x2:"16",y1:"21",y2:"21"}),p("line",{x1:"12",x2:"12",y1:"17",y2:"21"})]})}),p("div",{style:n.tabSelector,children:[p("button",{style:n.tabButton(!1),children:"Tab"}),p("button",{style:n.tabButton(!0),children:"Window"})]})]}),p("div",{style:n.skeletonContainer,children:p(AC,{})})]})})}function LC({session:n,speakingState:e,onAction:t}){return p(Xn,{title:"Connect your screen",subtitle:"Watch for the prompt in your browser",agentName:n.agentName||"Obi",buttonText:"Share screen",speakingState:e,description:`${n.agentName||"Obi"} will guide you through ${n.appName||"the app"} by watching your screen.`,centerVisual:p(NC,{}),actionDisabled:!0,onAction:t})}function MC({spectrum:n}){return p("div",{style:{borderRadius:"15px",boxShadow:"0 0 20px 2px var(--obi-color-primary)",backgroundColor:"var(--obi-color-primary)",transform:"scale(1.6)"},children:p(ps,{isActive:!0,children:p(gf,{getBands:n})})})}function DC({session:n,speakingState:e,spectrum:t,onAction:i}){return p(Xn,{title:"Overview",subtitle:`${n.agentName||"Obi"} will start your tutorial in a moment`,agentName:n.agentName||"Obi",speakingState:e,description:`Get ready to explore ${n.appName||"the app"} with ${n.agentName||"Obi"}.`,centerVisual:p(MC,{spectrum:t}),actionDisabled:!0,onAction:i})}function UC({id:n,name:e,description:t,duration:i=10,order:r=0,selected:s=!1,completed:a=!1,onClick:o}){return p("div",{className:`course-container ${s?"selected":""}`,onClick:()=>{o==null||o({id:n,name:e,description:t,duration:i,order:r})},children:[p("div",{className:"header-row",children:[p("h2",{className:"course-title",children:e}),a&&p("span",{className:"duration",children:"Completed"})]}),t&&p("p",{className:"course-description",children:t})]})}function BC({courses:n=[],selectedCourseId:e=null,loading:t=!1,error:i="",onCourseSelect:r}){const[s,a]=Y(""),o=u=>{const d=u.currentTarget;a(d.value)},l=u=>{r==null||r(u)};if(t)return p("div",{className:"loading",children:"Loading..."});if(i)return p("div",{className:"error",children:i});if(!n||n.length===0)return p("div",{className:"empty",children:"No courses available"});const c=n.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())||(u.description||"").toLowerCase().includes(s.toLowerCase()));return p("div",{className:"tour-select",children:[p("div",{className:"controls",children:[p("div",{className:"tabs",children:p("button",{className:"tab active",children:"All"})}),p("div",{className:"filter",children:[p("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:p("path",{d:"M10.0417 8.75002H9.42087L9.20004 8.53502C9.96921 7.63585 10.4417 6.47502 10.4417 5.20835C10.4417 2.56085 8.32254 0.441681 5.67504 0.441681C3.02754 0.441681 0.908374 2.56085 0.908374 5.20835C0.908374 7.85585 3.02754 9.97502 5.67504 9.97502C6.94171 9.97502 8.10254 9.50252 9.00171 8.73335L9.22671 8.95418V9.57502L13.2167 13.5592L14.375 12.4008L10.0417 8.75002ZM5.67504 8.75002C3.72754 8.75002 2.15837 7.18085 2.15837 5.20835C2.15837 3.23585 3.72754 1.66668 5.67504 1.66668C7.62254 1.66668 9.19171 3.23585 9.19171 5.20835C9.19171 7.18085 7.62254 8.75002 5.67504 8.75002Z",fill:"#6B7280"})}),p("input",{type:"text",placeholder:"Search...",value:s,onInput:o})]})]}),p("div",{className:"course-grid",children:c.sort((u,d)=>(u.order||0)-(d.order||0)).map(u=>{const d=u.id===e;return p(UC,{id:u.id,name:u.name,description:u.description||"",duration:u.duration,order:u.order||0,completed:u.completed,selected:d,onClick:l},u.id)})})]})}function FC({open:n,courses:e=[],loading:t=!1,error:i="",title:r="AI Onboarding Assistant",productName:s,onClose:a,onCourseSelect:o,onCourseHighlight:l}){const[c,u]=Y(null),d=f=>{u(f),l==null||l(f)},h=()=>{c&&o&&o(c)};return p(ff,{open:n,onClose:a,size:"large",preventOutsideClick:!0,children:p("div",{className:"tour-select-modal-container",children:[p("div",{className:"header",children:[p("div",{className:"icon",style:{color:"white"},children:p(If,{})}),p("div",{className:"title-section",children:t?p(Me,{children:[p("div",{className:"skeleton skeleton-title"}),p("div",{className:"skeleton skeleton-subtitle"})]}):p(Me,{children:[p("h1",{children:r}),p("p",{className:"subtitle",children:["Start a tutorial and learn how to use ",s," through an interactive conversation."]})]})})]}),p("div",{className:"course-list-wrapper",children:p(BC,{courses:e,selectedCourseId:(c==null?void 0:c.id)||"",loading:t,error:i,onCourseSelect:d})}),p("div",{className:"footer",children:[p("button",{className:"obi-button footer-button",onClick:h,disabled:!c,children:[p("span",{children:"Get started"}),p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",children:p("path",{d:"M3.83325 8.00065H13.1666M13.1666 8.00065L8.49992 3.33398M13.1666 8.00065L8.49992 12.6673",stroke:c?"#FAFAFA":"#999","stroke-width":"1.33","stroke-linecap":"round","stroke-linejoin":"round"})})]}),p("p",{className:"footer-text",children:"Sessions are securely recorded for quality improvement purposes."})]})]})})}function jC({session:n,sessionState:e,speakingState:t,spectrum:i,onStart:r,onContinue:s,onShareMicrophone:a,onShareScreen:o,onModalChange:l}){const[c,u]=Y(null);function d(f){c!==f&&(l==null||l(f),u(f))}function h(){e==="connecting"||e==="connected"||!e?r==null||r():e==="volume-check"||e==="mic-check"?s==null||s():e==="mic-share"?a==null||a():e==="screen-share"&&(o==null||o())}return No(()=>{switch(e){case null:case"connecting":case"connected":return d("session-start"),p(EC,{session:n,speakingState:t,onAction:h});case"volume-check":return d("voice-guidance"),p(OC,{session:n,speakingState:t,onAction:h});case"mic-check":return d("overview"),p(DC,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-share":return d("share-mic"),p(RC,{session:n,speakingState:t,onAction:h});case"screen-share":return d("share-screen"),p(LC,{session:n,speakingState:t,onAction:h});case"navigate":return d("navigate"),p(wC,{session:n,speakingState:t,onAction:h});default:return null}},[e,t,r,s,a,o])}function VC(n){const{session:e,sessionState:t,speakingState:i,spectrum:r,onClose:s,onStart:a,onContinue:o,onShareMicrophone:l,onShareScreen:c,onModalChange:u}=n,[d,h]=Y(null);function f(v){u==null||u(v),h(v)}function g(v){s(v,d),h(null)}const m=(n.open??!0)&&(!t||t==="connecting"||t==="connected"||t==="volume-check"||t==="mic-check"||t==="mic-share"||t==="screen-share"||t==="navigate");return p(CC,{open:m,onClose:g,preventOutsideClick:!0,children:()=>p(jC,{session:e,sessionState:t,speakingState:i,spectrum:r,onStart:a,onContinue:o,onShareMicrophone:l,onShareScreen:c,onModalChange:f})})}const GC={identify:()=>{},track:()=>{},page:()=>{},reset:()=>{}};function Ei(){return GC}const WC=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Of="9.23.0",Jn=globalThis;function zC(n,e,t=Jn){const i=t.__SENTRY__=t.__SENTRY__||{},r=i[Of]=i[Of]||{};return r[n]||(r[n]=e())}const HC="Sentry Logger ",Af=["debug","info","warn","error","log","assert","trace"],Nf={};function qC(n){if(!("console"in Jn))return n();const e=Jn.console,t={},i=Object.keys(Nf);i.forEach(r=>{const s=Nf[r];t[r]=e[r],e[r]=s});try{return n()}finally{i.forEach(r=>{e[r]=t[r]})}}function KC(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return WC?Af.forEach(t=>{e[t]=(...i)=>{n&&qC(()=>{Jn.console[t](`${HC}[${t}]:`,...i)})}}):Af.forEach(t=>{e[t]=()=>{}}),e}zC("logger",KC);const Lf=1e3;function $C(){return Date.now()/Lf}function YC(){const{performance:n}=Jn;if(!(n!=null&&n.now))return $C;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/Lf}YC();const Mf=50,Qn="?",Df=/\(error: (.*)\)/,Uf=/captureMessage|captureException/;function XC(...n){const e=n.sort((t,i)=>t[0]-i[0]).map(t=>t[1]);return(t,i=0,r=0)=>{const s=[],a=t.split(`
54
54
  `);for(let o=i;o<a.length;o++){const l=a[o];if(l.length>1024)continue;const c=Df.test(l)?l.replace(Df,"$1"):l;if(!c.match(/\S*Error: /)){for(const u of e){const d=u(c);if(d){s.push(d);break}}if(s.length>=Mf+r)break}}return JC(s.slice(r))}}function JC(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(vs(e).function||"")&&e.pop(),e.reverse(),Uf.test(vs(e).function||"")&&(e.pop(),Uf.test(vs(e).function||"")&&e.pop()),e.slice(0,Mf).map(t=>({...t,filename:t.filename||vs(e).filename,function:t.function||Qn}))}function vs(n){return n[n.length-1]||{}}var Bf;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(Bf||(Bf={})),Jn._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const QC=30,ZC=50;function Fo(n,e,t,i){const r={filename:n,function:e==="<anonymous>"?Qn:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}const e1=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,t1=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,n1=/\((\S*)(?::(\d+))(?::(\d+))\)/,i1=n=>{const e=e1.exec(n);if(e){const[,i,r,s]=e;return Fo(i,Qn,+r,+s)}const t=t1.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=n1.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=Ff(t[1]||Qn,t[2]);return Fo(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},r1=[QC,i1],s1=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,a1=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;XC(...[r1,[ZC,n=>{const e=s1.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=a1.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let t=e[3],i=e[1]||Qn;return[i,t]=Ff(i,t),Fo(t,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const Ff=(n,e)=>{const t=n.indexOf("safari-extension")!==-1,i=n.indexOf("safari-web-extension")!==-1;return t||i?[n.indexOf("@")!==-1?n.split("@")[0]:Qn,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function o1(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(u){try{c(i.next(u))}catch(d){a(d)}}function l(u){try{c(i.throw(u))}catch(d){a(d)}}function c(u){u.done?s(u.value):r(u.value).then(o,l)}c((i=i.apply(n,e||[])).next())})}function c1(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(c){return function(u){return l([c,u])}}function l(c){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(i=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(u){c=[6,u],r=0}finally{i=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var jf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Pi=typeof Uint8Array>"u"?[]:new Uint8Array(256),bs=0;bs<jf.length;bs++)Pi[jf.charCodeAt(bs)]=bs;for(var l1=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,l;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var c=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(c)?c:new Uint8Array(c);for(i=0;i<t;i+=4)s=Pi[n.charCodeAt(i)],a=Pi[n.charCodeAt(i+1)],o=Pi[n.charCodeAt(i+2)],l=Pi[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|l&63;return c},u1=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},d1=function(n){for(var e=n.length,t=[],i=0;i<e;i+=4)t.push(n[i+3]<<24|n[i+2]<<16|n[i+1]<<8|n[i]);return t},kn=5,jo=6+5,Vo=2,h1=jo-kn,Vf=65536>>kn,f1=1<<kn,Go=f1-1,p1=1024>>kn,m1=Vf+p1,g1=m1,v1=32,b1=g1+v1,y1=65536>>jo,k1=1<<h1,T1=k1-1,Gf=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},S1=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},C1=function(n,e){var t=l1(n),i=Array.isArray(t)?d1(t):new Uint32Array(t),r=Array.isArray(t)?u1(t):new Uint16Array(t),s=24,a=Gf(r,s/2,i[4]/2),o=i[5]===2?Gf(r,(s+i[4])/2):S1(i,Math.ceil((s+i[4])/4));return new x1(i[0],i[1],i[2],i[3],a,o)},x1=function(){function n(e,t,i,r,s,a){this.initialValue=e,this.errorValue=t,this.highStart=i,this.highValueIndex=r,this.index=s,this.data=a}return n.prototype.get=function(e){var t;if(e>=0){if(e<55296||e>56319&&e<=65535)return t=this.index[e>>kn],t=(t<<Vo)+(e&Go),this.data[t];if(e<=65535)return t=this.index[Vf+(e-55296>>kn)],t=(t<<Vo)+(e&Go),this.data[t];if(e<this.highStart)return t=b1-y1+(e>>jo),t=this.index[t],t+=e>>kn&T1,t=this.index[t],t=(t<<Vo)+(e&Go),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),Wf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w1=typeof Uint8Array>"u"?[]:new Uint8Array(256),ys=0;ys<Wf.length;ys++)w1[Wf.charCodeAt(ys)]=ys;var zf=null;function _1(n){return o1(this,void 0,void 0,function(){var e;return c1(this,function(t){switch(t.label){case 0:return zf!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw new Error("Invalid graphemes response");zf=C1(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}for(var Hf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",E1=typeof Uint8Array>"u"?[]:new Uint8Array(256),ks=0;ks<Hf.length;ks++)E1[Hf.charCodeAt(ks)]=ks;function P1(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(u){try{c(i.next(u))}catch(d){a(d)}}function l(u){try{c(i.throw(u))}catch(d){a(d)}}function c(u){u.done?s(u.value):r(u.value).then(o,l)}c((i=i.apply(n,e||[])).next())})}function R1(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(c){return function(u){return l([c,u])}}function l(c){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(i=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(u){c=[6,u],r=0}finally{i=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var qf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ri=typeof Uint8Array>"u"?[]:new Uint8Array(256),Ts=0;Ts<qf.length;Ts++)Ri[qf.charCodeAt(Ts)]=Ts;for(var I1=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,l;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var c=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(c)?c:new Uint8Array(c);for(i=0;i<t;i+=4)s=Ri[n.charCodeAt(i)],a=Ri[n.charCodeAt(i+1)],o=Ri[n.charCodeAt(i+2)],l=Ri[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|l&63;return c},O1=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},A1=function(n){for(var e=n.length,t=[],i=0;i<e;i+=4)t.push(n[i+3]<<24|n[i+2]<<16|n[i+1]<<8|n[i]);return t},Tn=5,Wo=6+5,zo=2,N1=Wo-Tn,Kf=65536>>Tn,L1=1<<Tn,Ho=L1-1,M1=1024>>Tn,D1=Kf+M1,U1=D1,B1=32,F1=U1+B1,j1=65536>>Wo,V1=1<<N1,G1=V1-1,$f=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},W1=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},z1=function(n,e){var t=I1(n),i=Array.isArray(t)?A1(t):new Uint32Array(t),r=Array.isArray(t)?O1(t):new Uint16Array(t),s=24,a=$f(r,s/2,i[4]/2),o=i[5]===2?$f(r,(s+i[4])/2):W1(i,Math.ceil((s+i[4])/4));return new H1(i[0],i[1],i[2],i[3],a,o)},H1=function(){function n(e,t,i,r,s,a){this.initialValue=e,this.errorValue=t,this.highStart=i,this.highValueIndex=r,this.index=s,this.data=a}return n.prototype.get=function(e){var t;if(e>=0){if(e<55296||e>56319&&e<=65535)return t=this.index[e>>Tn],t=(t<<zo)+(e&Ho),this.data[t];if(e<=65535)return t=this.index[Kf+(e-55296>>Tn)],t=(t<<zo)+(e&Ho),this.data[t];if(e<this.highStart)return t=F1-j1+(e>>Wo),t=this.index[t],t+=e>>Tn&G1,t=this.index[t],t=(t<<zo)+(e&Ho),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),Yf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",q1=typeof Uint8Array>"u"?[]:new Uint8Array(256),Ss=0;Ss<Yf.length;Ss++)q1[Yf.charCodeAt(Ss)]=Ss;var Xf=null;function K1(n){return P1(this,void 0,void 0,function(){var e;return R1(this,function(t){switch(t.label){case 0:return Xf!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw console.error("invalid graphemes response",e),new Error("Invalid graphemes response");Xf=z1(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}const $1=`:root,:host{--obi-modal-padding: 48px 48px 32px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 12px;--obi-modal-shadow: 0px 1px 2px rgba(0, 0, 0, .05);--obi-modal-xsmall-width: 320px;--obi-modal-xsmall-height: 240px;--obi-modal-small-width: 480px;--obi-modal-small-height: 400px;--obi-modal-medium-width: 640px;--obi-modal-medium-height: 545px;--obi-modal-large-width: 1200px;--obi-modal-large-height: 700px;--obi-font-family: "Satoshi", sans-serif;--obi-color-primary: #9500FF;--obi-color-primary-50: color-mix(in srgb, var(--obi-color-primary) 50%, white 50%);--obi-color-primary-30: color-mix(in srgb, var(--obi-color-primary) 30%, white 70%);--obi-color-tint: color-mix(in srgb, var(--obi-color-primary) 5%, white 95%);--obi-color-text: #18181B;--obi-course-color-selected: var(--obi-color-primary-50);--obi-course-color-tint: var(--obi-color-tint);--obi-course-progress-step-completed: #B3B3B3;--obi-course-progress-step-incomplete: #D9D9D9;--obi-course-progress-text-color: #757575;font-family:var(--obi-font-family);color:var(--obi-color-text)}.obi-button{font-family:var(--obi-font-family);color:var(--obi-color-text)}dialog{margin:auto;padding:0;border:none;border-radius:var(--obi-modal-border-radius);box-shadow:var(--obi-modal-shadow);background:var(--obi-modal-background-color);box-sizing:border-box}dialog>.modal-content{padding:var(--obi-modal-padding);box-sizing:border-box}dialog,dialog.modal-medium,dialog>.modal-content,dialog.modal-medium>.modal-content{width:var(--obi-modal-medium-width);min-height:var(--obi-modal-medium-height)}dialog.modal-xsmall,dialog.modal-xsmall>.modal-content{width:var(--obi-modal-xsmall-width);min-height:var(--obi-modal-xsmall-height)}dialog.modal-small,dialog.modal-small>.modal-content{width:var(--obi-modal-small-width);min-height:var(--obi-modal-small-height)}dialog.modal-large,dialog.modal-large>.modal-content{width:var(--obi-modal-large-width);min-height:var(--obi-modal-large-height)}dialog::backdrop{background:rgba(0,0,0,.5)}.tour-content{display:block;width:100%;height:100%}.tour-content .container{box-sizing:border-box;display:flex;flex-direction:column;align-items:center;padding:0;width:100%;height:100%}.tour-content .header{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:100%}.tour-content .title{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:700;font-size:32px;line-height:90%;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0}.tour-content .subtitle{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b;margin:0}.tour-content .visual{width:480px;height:240px;margin-top:24px;border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative}.tour-content .description{width:100%;min-height:48px;margin:24px 0 0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b}.tour-content .button-container{display:flex;margin-top:24px;flex-direction:column;align-items:center;gap:16px;width:100%}.tour-content .action-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;min-width:200px;height:40px;background:#303030;border:1px solid #303030;border-radius:4px;cursor:pointer;text-decoration:none}.tour-content .action-button.disabled{opacity:.6;cursor:not-allowed}.tour-content .button-text{height:16px;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{flex:1;display:flex;flex-direction:column}.obi-close-button{position:absolute;top:24px;right:24px;width:24px;height:24px;cursor:pointer;border:none;background:none;padding:0;display:flex;align-items:center;justify-content:center;z-index:1}.obi-panel{box-sizing:border-box;padding:24px;background-color:#fff;box-shadow:0 16px 32px -4px #0000001f,0 4px 8px -2px #00000014,inset 0 1px #fff9;border-radius:12px}.obi-pill.container{width:96px;height:30px;display:flex;align-items:center;justify-content:center}.obi-pill.container .pill{display:flex;align-items:center;justify-content:center;width:48px;height:6px;opacity:.7;border-radius:3px;background-color:var(--obi-color-primary);transition:width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill.container .pill.button{cursor:pointer}.obi-pill.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill.container.active .pill{width:96px;height:30px;border-radius:15px;opacity:1}.obi-pill.container.busy,.obi-pill.container.busy .pill{width:220px}.obi-pill2.container{display:flex;align-items:center;justify-content:center}.obi-pill2.container .pill{display:flex;align-items:center;justify-content:center;min-width:48px;max-width:48px;height:6px;opacity:.7;border-radius:3px;border:1px solid #FFFFFF1F;background-color:var(--obi-color-primary);transform:translateY(0);overflow:hidden;white-space:nowrap;flex:0 0 auto;box-sizing:border-box;padding-left:0;padding-right:0;transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill2.container .pill.button{cursor:pointer}.obi-pill2.container:not(.active){transition:height 0s linear .15s;height:6px}.obi-pill2.container:not(.active) .pill{transform:translateY(12px);transition:transform 0s linear .15s,max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill2.container.active{transition:none;height:30px}.obi-pill2.container.active .pill{transition:transform 0s,max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out;max-width:1000px;height:30px;border-radius:15px;opacity:1;padding-left:14px;padding-right:14px}.obi-pill2.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill2.container:not(.active) .pill .text{opacity:0;animation:none}.obi-pill-up.container{display:flex;align-items:flex-end;justify-content:center}.obi-pill-up.container .pill{display:flex;align-items:center;justify-content:center;min-width:48px;max-width:48px;height:6px;opacity:.7;border-radius:3px;border:1px solid #FFFFFF1F;background-color:var(--obi-color-primary);overflow:hidden;white-space:nowrap;flex:0 0 auto;box-sizing:border-box;padding-left:0;padding-right:0;transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill-up.container .pill.button{cursor:pointer}.obi-pill-up.container:not(.active){transition:height 0s linear .15s;height:6px}.obi-pill-up.container:not(.active) .pill{transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill-up.container.active{transition:none;height:30px}.obi-pill-up.container.active .pill{transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out;max-width:1000px;height:30px;border-radius:15px;opacity:1;padding-left:14px;padding-right:14px}.obi-pill-up.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill-up.container:not(.active) .pill .text{opacity:0;animation:none}.obi-popout{position:relative;display:inline-block}.obi-popout .obi-popout-target{cursor:pointer;display:inline-block}.obi-popout .content{position:absolute;background-color:#fff0;z-index:100;animation:popout-appear .15s ease-out}@keyframes popout-appear{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.obi-round-button-popout{z-index:600}.obi-round-button{flex:0 0 auto;display:flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:50%;padding:0;box-sizing:border-box;background-color:#fff;border:1px solid #D9D9D9;box-shadow:none}.obi-round-button:hover{cursor:pointer}.obi-round-button:disabled{box-shadow:none;background-color:#f0f0f0;color:#999;cursor:not-allowed!important;pointer-events:none}.obi-round-button-title{padding:8px 16px;border-radius:12px;background-color:#fff;color:#000;font-size:14px;font-weight:400;white-space:nowrap;box-shadow:0 4px 12px #00000026,0 2px 4px #0000001a;border:1px solid rgba(0,0,0,.08);z-index:5000;pointer-events:none;-webkit-user-select:none;user-select:none;position:relative}.obi-round-button-title:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-top:6px solid white;filter:drop-shadow(0 2px 2px rgba(0,0,0,.1))}.obi-equaliser{display:flex;align-items:center;gap:2px;height:32px}.obi-equaliser .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-equaliser .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1}.obi-message{display:inline-flex;align-items:center;justify-content:center;padding:0 15px;text-wrap:nowrap;font-size:16px;font-weight:400;height:30px;box-sizing:border-box;background-color:#fff;border-radius:15px;border:1px solid #D9D9D9}.obi-message.clickable{box-shadow:0 4px 6px #0000001a;cursor:pointer}.obi-loading-dots{display:flex;align-items:center;gap:2px;height:32px}.obi-loading-dots .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-loading-dots .dot{width:3px;height:3px;border-radius:2px;position:relative;z-index:2}.obi-loading-dots .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1;height:0px;animation:bounce .9s ease-in-out infinite}@keyframes bounce{0%,60%,to{height:0px}30%{height:16px}}.obi-exit-survey{position:relative;width:320px;margin:0 auto;-webkit-backdrop-filter:none;backdrop-filter:none;background:white;z-index:9999}.obi-exit-survey-container{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-header{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-title{width:272px;height:22px;margin:0;font-family:Satoshi,sans-serif;font-size:16px;font-weight:600;line-height:140%;text-align:center;color:#1e1e1e;flex:none;align-self:stretch}.obi-exit-survey-subtitle{width:272px;height:20px;margin:0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;text-align:center;color:#757575;flex:none;align-self:stretch}.obi-exit-survey-options{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-options textarea{height:80px;resize:none;outline:none}.obi-exit-survey-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;width:272px;height:44px;border-radius:12px;cursor:pointer;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-button:hover{transform:translateY(-1px);box-shadow:0 4px 8px #0000001a}.obi-exit-survey-button:active{transform:translateY(0)}.obi-exit-survey-button-continue{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-button-continue:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-button-wrap-up{background:#303030;border:1px solid rgba(217,217,217);color:#fff;font-weight:500}.obi-exit-survey-button-wrap-up:hover{background:#404040;border-color:#d9d9d9}.obi-exit-survey-reason-button{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-reason-button:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-reason-button-secondary{display:flex;flex-direction:row;justify-content:center;align-items:center;padding:4px 6px;gap:8px;width:272px;height:28px;border-radius:4px;cursor:pointer;border:none;background:transparent;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;color:#5a5a5a;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-reason-button-secondary:hover{background:rgba(0,0,0,.05);color:#3a3a3a}.obi-message-input{display:inline-block;position:relative}.obi-message-input .container{width:212px;height:30px;box-sizing:border-box;background:#FFFFFF;border:1px solid var(--obi-color-primary-30);border-radius:15px;display:flex;align-items:center;flex:none;order:2;flex-grow:0;transition:height .3s ease,border-radius .3s ease;animation:expandMessageInput .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .container{height:auto;min-height:140px;border-radius:15px;align-items:flex-start;padding:8px 0;animation:expandMessageInputWide .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input .field{flex:1 1 0;border:none;background:transparent;outline:none;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:18px;color:#000;padding:4px 3px 0 16px;height:100%;box-sizing:border-box;min-width:0;resize:none;overflow:hidden;scrollbar-width:none;transition:padding .3s ease;animation:fadeInInputField .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .field{height:auto;min-height:120px;padding:4px 16px;overflow-y:auto;line-height:18px}.obi-message-input .field::placeholder{color:#999}.obi-message-input .field:disabled{cursor:not-allowed;opacity:.6}.obi-message-input .send{position:absolute;bottom:3px;right:4px;flex-shrink:0;width:24px;height:24px;background:var(--obi-color-primary);border:none;border-radius:9999px;display:flex;justify-content:center;align-items:center;cursor:pointer;transition:all .3s ease;color:#fff}.obi-message-input.expanded .send{width:28px;height:28px;position:relative;top:0;bottom:0;margin-right:0}.obi-message-input.expanded .button-container{display:flex;justify-content:space-between;align-items:center;width:100%;margin-top:8px}.obi-message-input .send:disabled{background:#CCCCCC;cursor:not-allowed;transform:none}.obi-message-input .container:focus-within{border-color:var(--obi-color-primary);box-shadow:0 0 0 2px #9008ff1a}@keyframes expandMessageInput{0%{width:32px}to{width:212px}}@keyframes expandMessageInputWide{0%{width:212px}to{width:340px}}@keyframes fadeInInputField{0%{opacity:0}60%{opacity:0}to{opacity:1}}.obi-course-progress{display:flex;flex-direction:column;justify-content:center;align-items:flex-start;gap:6px;width:100%;min-width:0;height:24px;flex:none;order:1;align-self:stretch;flex-grow:0}.obi-course-progress-steps{display:flex;flex-direction:row;align-items:center;justify-content:space-between;padding:0;gap:2px;width:100%;height:6px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-container{display:flex;flex-direction:column;justify-content:center;align-items:stretch;padding:2px 0;height:6px;flex:1;min-width:0}.obi-course-progress-step{width:100%;height:2px;background:var(--obi-course-progress-step-incomplete);border-radius:24px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-step.completed{background:var(--obi-course-progress-step-completed)}.obi-course-progress-description{width:100%;height:14px;font-family:var(--obi-font-family);font-style:normal;font-weight:500;font-size:14px;line-height:100%;color:var(--obi-course-progress-text-color);flex:none;order:1;flex-grow:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.obi-widget-popout{z-index:400}.obi-widget-panel{display:flex;flex-direction:column;gap:8px;align-items:center;justify-content:center;min-width:222px;width:min-content;padding:12px;box-sizing:border-box;border-radius:27px;background:white;transition:background .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel:not(.messaging){width:256px}.obi-widget-panel.tool-usage{width:384px}.obi-widget-panel:not(.expanded){background:transparent;border:none;box-shadow:none;transition:background .1s ease-out .1s,border .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel.maximized{transform:translateY(-110px)}.obi-widget-panel .obi-widget{display:flex;align-items:center;min-width:192px;padding-left:58px;box-sizing:border-box;gap:4px}.obi-widget-panel .obi-widget.active.in-plan{padding-left:0}.obi-widget-panel .obi-widget.active.in-plan .obi-round-button{animation:fade-in-button .2s ease-out .15s both}.obi-widget-panel .obi-widget.active .obi-equaliser{animation:fade-in-equaliser .2s ease-out .15s both}@keyframes fade-in-button{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes fade-in-equaliser{0%{opacity:0}to{opacity:1}}.obi-widget-panel .obi-course-progress-container{display:none;width:100%;max-height:0;opacity:0;transform:translateY(-10px);overflow:hidden;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel:hover .obi-course-progress-container{display:block;max-width:22 0px;animation:expand-course-progress .3s ease-in-out forwards}.obi-widget-panel:hover .obi-course-progress-container.expanded{max-width:330px}@keyframes expand-course-progress{0%{max-height:0;opacity:0;transform:translateY(-10px)}to{max-height:40px;opacity:1;transform:translateY(0)}}.obi-widget-pill-text{font-size:16px;font-weight:400;color:#fff;opacity:0;animation:fade-in-pill-text .3s ease-in-out forwards}@keyframes fade-in-pill-text{0%{opacity:0}40%{opacity:0}to{opacity:1}}.obi-widget-buttons{display:flex;flex-direction:row;gap:4px}.obi-widget-out-of-plan{display:flex;align-items:center;gap:0}.obi-widget-out-of-plan .text{font-size:16px;color:#fff;display:inline-flex;align-items:center;gap:8px;animation:fade-in-pill-text .3s ease-in-out forwards}.obi-widget-out-of-plan .round-button{display:none;animation:fade-in-button .2s ease-out .15s both}.obi-widget-out-of-plan .message{display:none}.obi-widget-out-of-plan.active{gap:0}.obi-widget-out-of-plan.active:hover,.obi-widget-out-of-plan.active.hover{gap:4px}.obi-widget-out-of-plan.active:hover .round-button,.obi-widget-out-of-plan.active:hover .message,.obi-widget-out-of-plan.active.hover .round-button,.obi-widget-out-of-plan.active.hover .message{display:flex}.obi-static-voice-visual{display:flex;align-items:center;gap:2px;height:32px}.obi-static-voice-visual .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-static-voice-visual .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;background-color:#fff;border-radius:2px;z-index:1}.obi-static-voice-visual .bar-1{height:2px}.obi-static-voice-visual .bar-2{height:6px}.obi-static-voice-visual .bar-3{height:10px}.obi-static-voice-visual .bar-4,.obi-static-voice-visual .bar-5{height:16px}.obi-static-voice-visual .bar-6{height:10px}.obi-static-voice-visual .bar-7{height:6px}.obi-static-voice-visual .bar-8{height:2px}.tour-select{display:block;font-family:Inter,sans-serif}.course-container{display:flex;padding:20px;align-items:flex-start;gap:8px;height:180px;border-radius:6px;border:1px solid rgba(0,0,0,.6);background:#fff;cursor:pointer;transition:all .2s;flex-direction:column;box-sizing:border-box;overflow:hidden}.course-container:hover{background-color:#f9fafb;border-color:#d1d5db;box-shadow:0 1px 2px #0000000d}.course-container:active{transform:scale(.98)}.course-container.selected{border-radius:6px;border:1px solid var(--obi-course-color-selected);background:var(--obi-course-color-tint)}.course-container.selected:hover{background:var(--obi-course-color-tint)}.header-row{display:flex;justify-content:space-between;align-items:flex-start;align-self:stretch;flex-shrink:0;text-align:left}.course-title{color:#000;font-family:Inter,sans-serif;font-size:20px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.2px;margin:0}.duration{display:flex;padding:4px 12px;justify-content:center;align-items:center;gap:8px;border-radius:9999px;background:var(--obi-course-color-tint);color:#000;font-family:Inter,sans-serif;font-size:14px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.14px;flex-shrink:0}.course-container.selected .duration{background:#fff}.course-description{flex:1 0 0;color:#0009;font-family:Inter,sans-serif;font-size:16px;font-style:normal;font-weight:400;line-height:140%;letter-spacing:-.16px;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;text-align:left}.course-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;padding:0;flex:1 0 0;align-self:stretch;min-height:364px}.controls{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.tabs{display:flex;gap:10px}.tab{display:flex;padding:6px 12px;justify-content:center;align-items:center;align-self:stretch;border:none;background:none;cursor:pointer;font-family:Inter,sans-serif;font-size:16px;font-weight:500;color:#0006;border-bottom:2px solid transparent;transition:all .2s}.tab.active{color:#000;border-bottom:2px solid var(--obi-color-primary)}.tab:hover{color:#000}.filter{position:relative;display:flex;align-items:center;width:336px;height:40px}.filter input{color:var(--obi-color-text);caret-color:var(--obi-color-text);padding:8px 12px 8px 36px;border-radius:6px;border:1px solid rgba(0,0,0,.1);background:#fff;font-family:Inter,sans-serif;font-size:14px;line-height:20px;width:100%;height:100%;box-sizing:border-box;outline:none}.filter input:focus{outline:1px solid var(--obi-color-primary);outline-offset:-1px}.filter input::placeholder{color:#0006}.filter svg{position:absolute;left:12px;pointer-events:none}@media (max-width: 767px){.course-grid{grid-template-columns:1fr}}.loading,.error,.empty{display:flex;justify-content:center;align-items:center;margin-top:16px}.error{color:#ef4444}.tour-select-modal-container{display:flex;flex-direction:column;align-items:center;gap:24px;flex:1 0 0;align-self:stretch;font-family:Satoshi,sans-serif;color:#000;text-align:center;max-width:1200px;width:100%;min-height:600px;box-sizing:border-box}.course-list-wrapper{flex:1;overflow-y:auto;width:100%;min-height:0;max-height:424px;padding-right:3px;box-sizing:border-box}.course-list-wrapper::-webkit-scrollbar{width:3px}.course-list-wrapper::-webkit-scrollbar-track{background:transparent}.course-list-wrapper::-webkit-scrollbar-thumb{background-color:#000;border-radius:2px;min-height:20px}.course-list-wrapper::-webkit-scrollbar-thumb:hover{background-color:#333}.header{display:flex;align-items:flex-start;gap:16px;width:100%;text-align:left}.icon{display:flex;width:56px;height:56px;padding:12px;justify-content:center;align-items:center;border-radius:12px;border:1px solid var(--obi-color-primary);background:var(--obi-color-primary);box-sizing:border-box}.icon img{width:32px;height:32px;color:#fff;fill:#fff}.title-section{align-self:stretch;flex:1}.tour-select-modal-container h1{color:#18181b;font-family:Satoshi;font-size:32px;font-style:normal;font-weight:700;line-height:90%;letter-spacing:-.96px;margin:0 0 8px}.subtitle{color:#18181b;font-family:Satoshi;font-size:20px;font-style:normal;font-weight:500;line-height:90%;letter-spacing:-.6px;margin:0}.footer{display:flex;width:360px;flex-direction:column;align-items:center;gap:12px}.footer-button{display:flex;height:48px;padding:16px;justify-content:center;align-items:center;gap:8px;align-self:stretch;border-radius:6px;background:#18181b;border:none;cursor:pointer;color:#fafafa;font-family:Satoshi;font-weight:500;transition:opacity .2s ease}.footer-button:disabled{opacity:.5;cursor:not-allowed}.footer-button:not(:disabled){opacity:1}.footer-button:not(:disabled):hover{background:#27272a}.footer-text{color:#18181b;font-family:Satoshi;font-size:12px;font-style:normal;font-weight:400;line-height:100%;letter-spacing:-.12px;margin:0;text-align:center}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%);background-size:200% 100%;animation:loading 1.5s infinite;border-radius:4px}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.skeleton-title{height:32px;width:60%;margin-bottom:12px}.skeleton-subtitle{height:20px;width:80%}
55
- `;function Y1(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function X1(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(i=>{try{const r=Y1(i);return r.test(t)||r.test(n)}catch(r){return console.warn(`Invalid URL pattern: ${i}`,r),!1}})}function qo(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return X1(e,n)}function J1(n){var R,I,M,D,j,V,q,z,W;const[e,t]=Y(!1),[i,r]=Y(!1),[s,a]=Y(!1),[o,l]=Y(null),c=Q1(n.sdk,u,n.shadowHost,l,a);function u(F){var G;(G=c.client)!=null&&G.session||t(F)}if(!c.client)return null;const d=c.client.planIsCompleted.filter(Boolean).length===c.client.plans.length,h=Z1((R=c.client.product)==null?void 0:R.widget_url_blacklist),f=d?c.completedWidgetDisplay||((I=c.client.product)==null?void 0:I.completed_widget_display):c.widgetDisplay||((M=c.client.product)==null?void 0:M.widget_display),g=c.widgetPosition||((D=c.client.product)==null?void 0:D.widget_position);let m=c.isActive;((V=(j=c.client)==null?void 0:j.product)==null?void 0:V.name)==="Canibuild"&&(m=!0);const v=c.client.session,b=!!v,S=b&&!e;let x;switch(v==null?void 0:v.speakingState){case"listening":x="user-speaking";break;case"speaking":x="agent-speaking";break;case"thinking":x="thinking";break;case"busy":x="busy";break}const k=v==null?void 0:v.isPaused,T=b||c.client.state==="ready"&&m&&!h&&(f!=="invisible"||c.client.selectedPlan),C=()=>{var F,G,J,se,ge,Te;return{name:(F=c.client.selectedPlan)==null?void 0:F.name,description:(G=c.client.selectedPlan)==null?void 0:G.description,appName:(J=c.client.product)==null?void 0:J.name,appLogoUrl:((se=c.client.product)==null?void 0:se.logo_url)||"",url:(ge=c.client.product)==null?void 0:ge.url,agentName:((Te=c.client.product)==null?void 0:Te.agent_name)||"Obi"}},_=g==="bottom-right"?{position:"fixed",right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",left:"50%",transform:"translateX(-50%)",width:"max-content"};return S?_.top="calc(100vh - 100px)":_.bottom="20px",p("div",{children:[e&&p(FC,{open:e,courses:c.client.plans.map((F,G)=>{var J,se;return{id:F.uuid,name:F.name,description:F.description||"",duration:F.duration||0,completed:((se=(J=c.client)==null?void 0:J.planIsCompleted)==null?void 0:se[G])||!1}}),loading:!1,title:((q=c.client.product)==null?void 0:q.assistant_subtitle)||void 0,productName:((z=c.client.product)==null?void 0:z.name)||"",onCourseHighlight:F=>{F&&Ei().track("course-selected",{courseName:F.name,courseUuid:F.id})},onCourseSelect:F=>{const G=c.client.plans.find(J=>J.uuid===F.id)||null;G&&(G==null?void 0:G.uuid)!==c.client.selectedPlanUuid&&(c.client.selectPlan(G),t(!1),r(!0),Ei().track("course-get-started",{courseName:F.name,courseUuid:F.id}))},onClose:F=>{F==="user-initiated"&&c.client.selectPlan(null),t(!1)}}),T&&p(Me,{children:[p("div",{style:_,children:p(kC,{inPlan:b,isActive:i?!1:void 0,defaultIsActive:f!=="minimized",isPaused:k,messaging:(v==null?void 0:v.isMicShared)===!1||s?!0:void 0,speakingStatus:x,spectrum:()=>(v==null?void 0:v.audioSpectrum())||null,courseProgress:o,onOpen:()=>{t(!0)},onCancelClick:()=>{},onCancelAbort:()=>{},onCancel:()=>{var F;(F=c.client.session)==null||F.stop()},onCancelReason:(F,G)=>{},onPause:()=>{var F,G;(G=(F=c.client.session)==null?void 0:F.pause)==null||G.call(F)},onUnpause:()=>{var F,G;(G=(F=c.client.session)==null?void 0:F.unpause)==null||G.call(F)},onMessagingChange:F=>{var G,J,se,ge;F?(J=(G=c.client.session)==null?void 0:G.muteMicrophone)==null||J.call(G):(ge=(se=c.client.session)==null?void 0:se.unmuteMicrophone)==null||ge.call(se)},onMessageChange:F=>{Ei().track("chat-input-provided",{message:F,length:F.length})},onMessage:F=>{c.say(F),Ei().track("chat-message-sent",{message:F,length:F.length})},onHover:F=>{},onOneClickAction:F=>{},onMinimize:()=>{},agentName:((W=c.client.product)==null?void 0:W.agent_name)||"Obi",completedTutorials:c.client.planIsCompleted.filter(Boolean).length,totalTutorials:c.client.plans.length})}),!!c.client.selectedPlan&&p(VC,{open:!0,session:C(),sessionState:(v==null?void 0:v.state)||null,speakingState:(v==null?void 0:v.speakingState)||null,spectrum:()=>(v==null?void 0:v.audioSpectrum())||null,onModalChange:F=>{},onClose:(F,G)=>{var J,se;F==="user-initiated"&&(((J=c.client.session)==null?void 0:J.state)==="mic-share"?(se=c.client.session)==null||se.shareMicrophoneFailed():c.client.stopSession()),r(!1)},onStart:()=>{c.client.selectedPlanUuid&&c.startSession()},onContinue:()=>{v==null||v.continue()},onShareMicrophone:()=>{v==null||v.shareMicrophone()}})]})]})}function Q1(n,e,t,i,r){const[s,a]=Y(0),[o,l]=Y(null);return ze(()=>{n.on("showMenu",c=>{e(c)}),n.on("configUpdated",()=>{a(c=>c+1)})},[n]),ze(()=>{n.client&&(n.client.session&&l(n.client.session),n.client.on("sessionStarted",c=>{l(c),r==null||r(!1),a(u=>u+1)}),n.client.on("sessionStopped",()=>{l(null),r==null||r(!1),a(c=>c+1)}),n.client.on("sessionShutdown",()=>{a(c=>c+1)}),n.client.on("sessionResumed",()=>{a(c=>c+1)}),n.client.on("stateChanged",()=>{var c;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((c=n.client.product)==null?void 0:c.primary_color)||"#9500FF"),a(u=>u+1)}),n.client.on("planSelected",()=>{a(c=>c+1)}))},[n,n.client]),ze(()=>{if(!o)return;o.on("stateChanged",()=>{a(u=>u+1)}),o.on("speakingStateChanged",()=>{a(u=>u+1)}),o.on("paused",()=>{a(u=>u+1)}),o.on("unpaused",()=>{a(u=>u+1)}),o.on("micCheckComplete",u=>{}),o.on("transcript",(u,d)=>{}),o.on&&o.on("textInputRequested",()=>{r==null||r(!0),a(u=>u+1)});const c=u=>{i(u)};return o.on&&o.on("courseProgress",c),()=>{o.off&&o.off("courseProgress",c),o.off&&o.off("textInputRequested")}},[o]),n}function Z1(n){const[e,t]=Y(()=>qo(n));return ze(()=>{t(qo(n))},[n]),ze(()=>{ex();const i=()=>{t(qo(n))};return window.addEventListener("locationchange",i),window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("locationchange",i),window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[n]),e}function ex(){const n=window;if(n.__obi_history_patched)return;const{pushState:e,replaceState:t}=window.history,i=r=>function(...s){const a=r.apply(this,s);return window.dispatchEvent(new Event("locationchange")),a};window.history.pushState=i(e),window.history.replaceState=i(t),n.__obi_history_patched=!0}function tx(n){if(document.querySelector("obi-widget"))return;nx();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",t.appendChild(i);const r=new CSSStyleSheet;r.replaceSync($1),t.adoptedStyleSheets=[r],FS(p(J1,{sdk:n,shadowHost:e}),i),console.log("[obi-sdk] widget mounted")}function nx(){Jf("https://fonts.cdnfonts.com/css/satoshi"),Jf("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function Jf(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const Qf="49206C6F7665204F6269_session",Zf="obi-url-params";class ix extends Cs{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.dispatchCommand=(t,i)=>{var r,s,a,o,l;switch(this.commandLog.push({commandType:t,args:i}),t){case"update":this.updateConfig(i);break;case"startSession":if(!(i!=null&&i.planUuid)){console.warn("[obi] startSession command requires a planUuid",i);return}const c=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",i);return}this.updateActive(!0),(a=(s=this.client)==null?void 0:s.selectPlan)==null||a.call(s,c);break;case"stopSession":(l=(o=this.client)==null?void 0:o.stopSession)==null||l.call(o);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:t,args:i})}},e&&this.createClient(e),this.parsePassiveParams()}async createClient(e){if(this.client){this.client.appToken!==e&&console.warn("[obi] client already exists with different app token");return}let t=null;const i=this.load();if(i)try{t=as.deserialise(i,e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)}),t&&(this._resumed=!0)}catch(r){console.error("[obi] error loading cached client",r)}t||(t=new as(e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",r=>{var s,a,o,l,c,u,d,h,f;r==="ready"&&this.updateConfig({isActive:(s=this.client)==null?void 0:s.showWidget,primaryColour:((o=(a=this.client)==null?void 0:a.product)==null?void 0:o.primary_color)||"#9500FF",widgetDisplay:((l=window==null?void 0:window.obiWidgetConfig)==null?void 0:l.widgetDisplay)||((u=(c=this.client)==null?void 0:c.product)==null?void 0:u.widget_display)||"regular",completedWidgetDisplay:((d=window==null?void 0:window.obiWidgetConfig)==null?void 0:d.completedWidgetDisplay)||((f=(h=this.client)==null?void 0:h.product)==null?void 0:f.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{this.save(),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{localStorage.removeItem("obi-client"),this.passivePlanUuid=null}),this.client.on("sessionShutdown",r=>{r==="invalid-room"&&localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(r,s)=>{}),this.client.session&&this.client.resumeSession(r=>{r.on("stateChanged",s=>{s!=="disconnecting"&&s!=="disconnected"&&s!=="error"&&s!=="connecting"&&this.save()}),r.on("paused",()=>{this.save()}),r.on("unpaused",()=>{this.save()})})}async initialise(e={}){this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised"),this.dispatchCommandQueue()}).catch(t=>{console.error("[obi] error initialising client",t),this.emit("error",t)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),this.updateWidgetDisplay(e.widgetDisplay),this.updateCompletedWidgetDisplay(e.completedWidgetDisplay),this.updateWidgetPosition(e.widgetPosition),await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var t;e===void 0||e==((t=this.client)==null?void 0:t.appToken)||(this.passivePlanUuid,await this.createClient(e),this.client&&await this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised")}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}updateWidgetDisplay(e){e===void 0||e==this.widgetDisplay||(this.widgetDisplay=e)}updateCompletedWidgetDisplay(e){e===void 0||e==this.completedWidgetDisplay||(this.completedWidgetDisplay=e)}updateWidgetPosition(e){e===void 0||e==this.widgetPosition||(this.widgetPosition=e)}async updateIdentity(e){var i;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;let t=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:t,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised")}).catch(r=>{console.error("[obi] error initialising client",r),this.emit("error",r)}),e!=null&&e.email&&Ei().identify((e==null?void 0:e.email)||"",t)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var t,i,r;await((r=(i=(t=this.client)==null?void 0:t.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(){await this.client.startSession(this.client.selectedPlanUuid,e=>{e.on("stateChanged",t=>{t!=="disconnecting"&&t!=="disconnected"&&t!=="error"&&t!=="connecting"&&this.save()})})}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(t=>{try{this.dispatchCommand(t[0],t[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(Zf)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((s,a)=>{e[a]=s});const t=e[Qf];if(!t)return null;const i=new URL(window.location.href);i.searchParams.delete(Qf),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Zf),this.passivePlanUuid=t}mountWidget(){tx(this)}async captureScreen(){try{await _1(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await K1(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.css_line_breaks))}catch(e){throw console.error("[obi] error initialising unicode trie",e),e}try{return(await Hb(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var e;localStorage.setItem("obi-client",((e=this.client)==null?void 0:e.serialise())||"")}load(){return localStorage.getItem("obi-client")}}async function ep(n,e){let t;try{t=window}catch{console.warn("[obi] no window object found"),t={}}return rx({appToken:n,window:t,init:e})}async function rx({appToken:n,window:e,init:t}){var s,a;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}t&&t(),n||(n=(s=e==null?void 0:e.obiWidgetConfig)==null?void 0:s.apiKey);let i;try{i=((a=e.ObiSDK)==null?void 0:a.q)||[]}catch{i=[]}const r=new ix(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function tp(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{ep(void 0,tp)}):ep(void 0,tp)})();
55
+ `;function Y1(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function X1(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(i=>{try{const r=Y1(i);return r.test(t)||r.test(n)}catch(r){return console.warn(`Invalid URL pattern: ${i}`,r),!1}})}function qo(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return X1(e,n)}function J1(n){var R,I,M,D,j,V,q,z,W;const[e,t]=Y(!1),[i,r]=Y(!1),[s,a]=Y(!1),[o,l]=Y(null),c=Q1(n.sdk,u,n.shadowHost,l,a);function u(F){var G;(G=c.client)!=null&&G.session||t(F)}if(!c.client)return null;const d=c.client.planIsCompleted.filter(Boolean).length===c.client.plans.length,h=Z1((R=c.client.product)==null?void 0:R.widget_url_blacklist),f=d?c.completedWidgetDisplay||((I=c.client.product)==null?void 0:I.completed_widget_display):c.widgetDisplay||((M=c.client.product)==null?void 0:M.widget_display),g=c.widgetPosition||((D=c.client.product)==null?void 0:D.widget_position);let m=c.isActive;((V=(j=c.client)==null?void 0:j.product)==null?void 0:V.name)==="Canibuild"&&(m=!0);const v=c.client.session,b=!!v,S=b&&!e;let x;switch(v==null?void 0:v.speakingState){case"listening":x="user-speaking";break;case"speaking":x="agent-speaking";break;case"thinking":x="thinking";break;case"busy":x="busy";break}const k=v==null?void 0:v.isPaused,T=b||c.client.state==="ready"&&m&&!h&&(f!=="invisible"||c.client.selectedPlan),C=()=>{var F,G,J,se,ge,Te;return{name:(F=c.client.selectedPlan)==null?void 0:F.name,description:(G=c.client.selectedPlan)==null?void 0:G.description,appName:(J=c.client.product)==null?void 0:J.name,appLogoUrl:((se=c.client.product)==null?void 0:se.logo_url)||"",url:(ge=c.client.product)==null?void 0:ge.url,agentName:((Te=c.client.product)==null?void 0:Te.agent_name)||"Obi"}},_=g==="bottom-right"?{position:"fixed",right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",left:"50%",transform:"translateX(-50%)",width:"max-content"};return S?_.top="calc(100vh - 100px)":_.bottom="20px",p("div",{children:[e&&p(FC,{open:e,courses:c.client.plans.map((F,G)=>{var J,se;return{id:F.uuid,name:F.name,description:F.description||"",duration:F.duration||0,completed:((se=(J=c.client)==null?void 0:J.planIsCompleted)==null?void 0:se[G])||!1}}),loading:!1,title:((q=c.client.product)==null?void 0:q.assistant_subtitle)||void 0,productName:((z=c.client.product)==null?void 0:z.name)||"",onCourseHighlight:F=>{F&&Ei().track("course-selected",{courseName:F.name,courseUuid:F.id})},onCourseSelect:F=>{const G=c.client.plans.find(J=>J.uuid===F.id)||null;G&&(G==null?void 0:G.uuid)!==c.client.selectedPlanUuid&&(c.client.selectPlan(G),t(!1),r(!0),Ei().track("course-get-started",{courseName:F.name,courseUuid:F.id}))},onClose:F=>{F==="user-initiated"&&c.client.selectPlan(null),t(!1)}}),T&&p(Me,{children:[p("div",{style:_,children:p(kC,{inPlan:b,isActive:i?!1:void 0,defaultIsActive:f!=="minimized",isPaused:k,messaging:(v==null?void 0:v.isMicShared)===!1||s?!0:void 0,speakingStatus:x,spectrum:()=>(v==null?void 0:v.audioSpectrum())||null,courseProgress:o,onOpen:()=>{t(!0)},onCancelClick:()=>{},onCancelAbort:()=>{},onCancel:()=>{var F;(F=c.client.session)==null||F.stop()},onCancelReason:(F,G)=>{},onPause:()=>{var F,G;(G=(F=c.client.session)==null?void 0:F.pause)==null||G.call(F)},onUnpause:()=>{var F,G;(G=(F=c.client.session)==null?void 0:F.unpause)==null||G.call(F)},onMessagingChange:F=>{var G,J,se,ge;F?(J=(G=c.client.session)==null?void 0:G.muteMicrophone)==null||J.call(G):(ge=(se=c.client.session)==null?void 0:se.unmuteMicrophone)==null||ge.call(se)},onMessageChange:F=>{Ei().track("chat-input-provided",{message:F,length:F.length})},onMessage:F=>{c.say(F),Ei().track("chat-message-sent",{message:F,length:F.length})},onHover:F=>{},onOneClickAction:F=>{},onMinimize:()=>{},agentName:((W=c.client.product)==null?void 0:W.agent_name)||"Obi",completedTutorials:c.client.planIsCompleted.filter(Boolean).length,totalTutorials:c.client.plans.length})}),!!c.client.selectedPlan&&p(VC,{open:!0,session:C(),sessionState:(v==null?void 0:v.state)||null,speakingState:(v==null?void 0:v.speakingState)||null,spectrum:()=>(v==null?void 0:v.audioSpectrum())||null,onModalChange:F=>{},onClose:(F,G)=>{var J,se;F==="user-initiated"&&(((J=c.client.session)==null?void 0:J.state)==="mic-share"?(se=c.client.session)==null||se.shareMicrophoneFailed():c.client.stopSession()),r(!1)},onStart:()=>{c.client.selectedPlanUuid&&c.startSession()},onContinue:()=>{v==null||v.continue()},onShareMicrophone:()=>{v==null||v.shareMicrophone()}})]})]})}function Q1(n,e,t,i,r){const[s,a]=Y(0),[o,l]=Y(null);return ze(()=>{n.on("showMenu",c=>{e(c)}),n.on("configUpdated",()=>{a(c=>c+1)})},[n]),ze(()=>{n.client&&(n.client.session&&l(n.client.session),n.client.on("sessionStarted",c=>{l(c),r==null||r(!1),a(u=>u+1)}),n.client.on("sessionStopped",()=>{l(null),r==null||r(!1),a(c=>c+1)}),n.client.on("sessionShutdown",()=>{a(c=>c+1)}),n.client.on("sessionResumed",()=>{a(c=>c+1)}),n.client.on("stateChanged",()=>{var c;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((c=n.client.product)==null?void 0:c.primary_color)||"#9500FF"),a(u=>u+1)}),n.client.on("planSelected",()=>{a(c=>c+1)}))},[n,n.client]),ze(()=>{if(!o)return;o.on("stateChanged",()=>{a(u=>u+1)}),o.on("speakingStateChanged",()=>{a(u=>u+1)}),o.on("paused",()=>{a(u=>u+1)}),o.on("unpaused",()=>{a(u=>u+1)}),o.on("micCheckComplete",u=>{}),o.on("transcript",(u,d)=>{}),o.on&&o.on("textInputRequested",()=>{r==null||r(!0),a(u=>u+1)});const c=u=>{i(u)};return o.on&&o.on("courseProgress",c),()=>{o.off&&o.off("courseProgress",c),o.off&&o.off("textInputRequested")}},[o]),n}function Z1(n){const[e,t]=Y(()=>qo(n));return ze(()=>{t(qo(n))},[n]),ze(()=>{ex();const i=()=>{t(qo(n))};return window.addEventListener("locationchange",i),window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("locationchange",i),window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[n]),e}function ex(){const n=window;if(n.__obi_history_patched)return;const{pushState:e,replaceState:t}=window.history,i=r=>function(...s){const a=r.apply(this,s);return window.dispatchEvent(new Event("locationchange")),a};window.history.pushState=i(e),window.history.replaceState=i(t),n.__obi_history_patched=!0}function tx(n){if(document.querySelector("obi-widget"))return;nx();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",t.appendChild(i);const r=new CSSStyleSheet;r.replaceSync($1),t.adoptedStyleSheets=[r],FS(p(J1,{sdk:n,shadowHost:e}),i),console.log("[obi-sdk] widget mounted")}function nx(){Jf("https://fonts.cdnfonts.com/css/satoshi"),Jf("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function Jf(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const Qf="49206C6F7665204F6269_session",Zf="obi-url-params";class ix extends Cs{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.dispatchCommand=(t,i)=>{var r,s,a,o,l;switch(this.commandLog.push({commandType:t,args:i}),t){case"update":this.updateConfig(i);break;case"startSession":if(!(i!=null&&i.planUuid)){console.warn("[obi] startSession command requires a planUuid",i);return}const c=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",i);return}this.updateActive(!0),(a=(s=this.client)==null?void 0:s.selectPlan)==null||a.call(s,c);break;case"stopSession":(l=(o=this.client)==null?void 0:o.stopSession)==null||l.call(o);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:t,args:i})}},e&&this.createClient(e),this.parsePassiveParams()}async createClient(e){if(this.client){this.client.appToken!==e&&console.warn("[obi] client already exists with different app token");return}let t=null;const i=this.load();if(i)try{t=as.deserialise(i,e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),t&&(this._resumed=!0)}catch(r){console.error("[obi] error loading cached client",r)}t||(t=new as(e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",r=>{var s,a,o,l,c,u,d,h,f;r==="ready"&&this.updateConfig({isActive:(s=this.client)==null?void 0:s.showWidget,primaryColour:((o=(a=this.client)==null?void 0:a.product)==null?void 0:o.primary_color)||"#9500FF",widgetDisplay:((l=window==null?void 0:window.obiWidgetConfig)==null?void 0:l.widgetDisplay)||((u=(c=this.client)==null?void 0:c.product)==null?void 0:u.widget_display)||"regular",completedWidgetDisplay:((d=window==null?void 0:window.obiWidgetConfig)==null?void 0:d.completedWidgetDisplay)||((f=(h=this.client)==null?void 0:h.product)==null?void 0:f.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{this.save(),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{localStorage.removeItem("obi-client"),this.passivePlanUuid=null}),this.client.on("sessionShutdown",r=>{r==="invalid-room"&&localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(r,s)=>{}),this.client.session&&this.client.resumeSession(r=>{r.on("stateChanged",s=>{s!=="disconnecting"&&s!=="disconnected"&&s!=="error"&&s!=="connecting"&&this.save()}),r.on("paused",()=>{this.save()}),r.on("unpaused",()=>{this.save()})})}async initialise(e={}){this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised"),this.dispatchCommandQueue()}).catch(t=>{console.error("[obi] error initialising client",t),this.emit("error",t)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),this.updateWidgetDisplay(e.widgetDisplay),this.updateCompletedWidgetDisplay(e.completedWidgetDisplay),this.updateWidgetPosition(e.widgetPosition),await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var t;e===void 0||e==((t=this.client)==null?void 0:t.appToken)||(this.passivePlanUuid,await this.createClient(e),this.client&&await this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised")}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}updateWidgetDisplay(e){e===void 0||e==this.widgetDisplay||(this.widgetDisplay=e)}updateCompletedWidgetDisplay(e){e===void 0||e==this.completedWidgetDisplay||(this.completedWidgetDisplay=e)}updateWidgetPosition(e){e===void 0||e==this.widgetPosition||(this.widgetPosition=e)}async updateIdentity(e){var i;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;let t=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:t,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised")}).catch(r=>{console.error("[obi] error initialising client",r),this.emit("error",r)}),e!=null&&e.email&&Ei().identify((e==null?void 0:e.email)||"",t)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var t,i,r;await((r=(i=(t=this.client)==null?void 0:t.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(){await this.client.startSession(this.client.selectedPlanUuid,e=>{e.on("stateChanged",t=>{t!=="disconnecting"&&t!=="disconnected"&&t!=="error"&&t!=="connecting"&&this.save()})})}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(t=>{try{this.dispatchCommand(t[0],t[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(Zf)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((s,a)=>{e[a]=s});const t=e[Qf];if(!t)return null;const i=new URL(window.location.href);i.searchParams.delete(Qf),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Zf),this.passivePlanUuid=t}mountWidget(){tx(this)}async captureScreen(){try{await _1(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await K1(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.css_line_breaks))}catch(e){throw console.error("[obi] error initialising unicode trie",e),e}try{return(await Hb(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var e;localStorage.setItem("obi-client",((e=this.client)==null?void 0:e.serialise())||"")}load(){return localStorage.getItem("obi-client")}}async function ep(n,e){let t;try{t=window}catch{console.warn("[obi] no window object found"),t={}}return rx({appToken:n,window:t,init:e})}async function rx({appToken:n,window:e,init:t}){var s,a;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}t&&t(),n||(n=(s=e==null?void 0:e.obiWidgetConfig)==null?void 0:s.apiKey);let i;try{i=((a=e.ObiSDK)==null?void 0:a.q)||[]}catch{i=[]}const r=new ix(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function tp(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{ep(void 0,tp)}):ep(void 0,tp)})();