obi-sdk 0.19.31 → 0.19.33

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,8 +39,8 @@ 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 Rs(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 Ps(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 vS=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ro,shimAddIceCandidateNullOrEmpty:Rs,shimConnectionState:Eo,shimMaxMessageSize:_s,shimParameterlessSetLocalDescription:Ps,shimRTCIceCandidate:xs,shimRTCIceCandidateRelayProtocol:_o,shimSendThrowTypeError:Es});function bS(){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=uh,i=fS(n),r={browserDetails:i,commonShim:vS,extractVersion:ws,disableLog:dS,disableWarnings:hS,sdp:gS};switch(i.browser){case"chrome":if(!Ch||!Co||!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=Ch,Rs(n,i),Ps(n),mh(n,i),gh(n),Co(n,i),vh(n),kh(n,i),bh(n),yh(n),Sh(n,i),xs(n),_o(n),Eo(n),_s(n,i),Es(n),Ro(n,i);break;case"firefox":if(!Lh||!wo||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=Lh,Rs(n,i),Ps(n),wh(n,i),wo(n,i),xh(n),Rh(n),_h(n),Eh(n),Ph(n),Ih(n),Oh(n),Ah(n),Nh(n),xs(n),Eo(n),_s(n,i),Es(n);break;case"safari":if(!Hh||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=Hh,Rs(n,i),Ps(n),jh(n),Gh(n),Uh(n),Mh(n),Dh(n),Vh(n),Bh(n),zh(n),xs(n),_o(n),_s(n,i),Es(n),Ro(n,i);break;default:t("Unsupported browser!");break}return r}bS({window:typeof window>"u"?void 0:window});const yS=10,Is="lk_e2ee",TS={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:yS,keyringSize:16};var yn;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(yn||(yn={}));var Kh;(function(n){n.KeyRatcheted="keyRatcheted"})(Kh||(Kh={}));var Tn;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(Tn||(Tn={}));var $h;(function(n){n.Error="cryptorError"})($h||($h={}));function kS(){return SS()||Po()}function Po(){return typeof window.RTCRtpScriptTransform<"u"}function SS(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class v_ extends Vt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,r)=>{ne.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},TS),e),this.on(yn.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(yn.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(yn.RatchetRequest,e,t)}}class kn extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var re;(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"})(re||(re={}));class he extends kn{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=re[t]}}class Io extends kn{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class $t extends kn{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class CS extends kn{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Me extends kn{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Oo extends kn{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Ao extends kn{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Yh extends kn{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:yo[t]}}var Os;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Os||(Os={})),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}(Os||(Os={}));var Xh;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Xh||(Xh={}));var A;(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"})(A||(A={}));var U;(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"})(U||(U={}));var M;(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"})(M||(M={}));var L;(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"})(L||(L={}));function wS(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const xS=/version\/(\d+(\.?_?\d+)+)/i;let No;function wt(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(No===void 0||e){const i=_S.find(r=>{let{test:s}=r;return s.test(t)});No=i==null?void 0:i.describe(t)}return No}const _S=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:As(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Lo(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:As(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Lo(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:As(xS,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Lo(n)}}}];function As(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 Lo(n){return n.includes("mac os")?As(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var ES="2.13.0";const RS=ES,PS=16;class He{}He.setTimeout=function(){return setTimeout(...arguments)},He.setInterval=function(){return setInterval(...arguments)},He.clearTimeout=function(){return clearTimeout(...arguments)},He.clearInterval=function(){return clearInterval(...arguments)};const IS=5e3,Yi=[];var mt;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(mt||(mt={}));class I extends Vt.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=I.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ne,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),IS):this.handleAppVisibilityChanged()},this.log=Kt((r=i.loggerName)!==null&&r!==void 0?r:Ct.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=I.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ce(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===I.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===I.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Yi.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Yi.splice(Yi.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),di(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?L.AudioPlaybackStarted:L.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?L.AudioPlaybackFailed:L.VideoPlaybackFailed,s):s.name==="AbortError"?ne.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):ne.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(L.ElementAttached,e),e}detach(e){try{if(e){hi(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(L.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{hi(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(L.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=Kt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Yi.forEach(i=>{i.parentElement||(t=!1)}),t&&Yi.push(e)}}handleAppVisibilityChanged(){return y(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===I.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){ct()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ct()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function di(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)),(!Sn()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Sn()||fi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function hi(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 yt.AUDIO;case e.Video:return yt.VIDEO;default:return yt.DATA}}n.kindToProto=r;function s(c){switch(c){case yt.AUDIO:return e.Audio;case yt.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(c){switch(c){case t.Camera:return Ne.CAMERA;case t.Microphone:return Ne.MICROPHONE;case t.ScreenShare:return Ne.SCREEN_SHARE;case t.ScreenShareAudio:return Ne.SCREEN_SHARE_AUDIO;default:return Ne.UNKNOWN}}n.sourceToProto=a;function o(c){switch(c){case Ne.CAMERA:return t.Camera;case Ne.MICROPHONE:return t.Microphone;case Ne.SCREEN_SHARE:return t.ScreenShare;case Ne.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function l(c){switch(c){case ho.ACTIVE:return i.Active;case ho.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=l})(I||(I={}));class de{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 OS=["vp8","h264"],AS=["vp8","h264","vp9","av1"];function NS(n){return!!OS.find(e=>e===n)}var Jh;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Jh||(Jh={}));var Mo;(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}})(Mo||(Mo={}));const Xi={h90:new de(160,90,9e4,20),h180:new de(320,180,16e4,20),h216:new de(384,216,18e4,20),h360:new de(640,360,45e4,20),h540:new de(960,540,8e5,25),h720:new de(1280,720,17e5,30),h1080:new de(1920,1080,3e6,30),h1440:new de(2560,1440,5e6,30),h2160:new de(3840,2160,8e6,30)},Do={h120:new de(160,120,7e4,20),h180:new de(240,180,125e3,20),h240:new de(320,240,14e4,20),h360:new de(480,360,33e4,20),h480:new de(640,480,5e5,20),h540:new de(720,540,6e5,25),h720:new de(960,720,13e5,30),h1080:new de(1440,1080,23e5,30),h1440:new de(1920,1440,38e5,30)},Uo={h360fps3:new de(640,360,2e5,3,"medium"),h360fps15:new de(640,360,4e5,15,"medium"),h720fps5:new de(1280,720,8e5,5,"medium"),h720fps15:new de(1280,720,15e5,15,"medium"),h720fps30:new de(1280,720,2e6,30,"medium"),h1080fps15:new de(1920,1080,25e5,15,"medium"),h1080fps30:new de(1920,1080,5e6,30,"medium"),original:new de(0,0,7e6,30,"medium")},LS="|",Qh="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function MS(n){const e=n.split(LS);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function ot(n){return y(this,void 0,void 0,function*(){return new Promise(e=>He.setTimeout(e,n))})}function Bo(){return"addTransceiver"in RTCPeerConnection.prototype}function Fo(){return"addTrack"in RTCPeerConnection.prototype}function DS(){if(!("getCapabilities"in RTCRtpSender)||Sn())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 US(){if(!("getCapabilities"in RTCRtpSender)||fi())return!1;if(Sn()){const t=wt();if(t!=null&&t.version&&Bn(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 Ji(n){return n==="av1"||n==="vp9"}function jo(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function BS(){return typeof RTCPeerConnection>"u"?!1:Bo()||Fo()}function fi(){var n;return((n=wt())===null||n===void 0?void 0:n.name)==="Firefox"}function Sn(){var n;return((n=wt())===null||n===void 0?void 0:n.name)==="Safari"}function FS(){const n=wt();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Zh(){var n,e;return ct()?(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 jS(){const n=wt(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Bn(e,n.osVersion)>=0?!0:n.name==="Safari"&&Bn(e,n.version)>=0}function ct(){return typeof document<"u"}function Gt(){return navigator.product=="ReactNative"}function Vo(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function ef(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function tf(){if(!Gt())return;let n=ef();if(n)return n.platform}function nf(){if(ct())return window.devicePixelRatio;if(Gt()){let n=ef();if(n)return n.devicePixelRatio}return 1}function Bn(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 VS(n){for(const e of n)e.target.handleResize(e)}function GS(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Go=null;const rf=()=>(Go||(Go=new ResizeObserver(VS)),Go);let zo=null;const sf=()=>(zo||(zo=new IntersectionObserver(GS,{root:null,rootMargin:"0px"})),zo);function zS(){var n;const e=new Ak({sdk:Gd.JS,protocol:PS,version:RS});return Gt()&&(e.os=(n=tf())!==null&&n!==void 0?n:""),e}function af(){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 Qi;function Ho(){if(!Qi){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(),[Qi]=i.stream.getAudioTracks(),!Qi)throw Error("Could not get empty media stream audio track");Qi.enabled=!1}return Qi.clone()}class Wo{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 HS(n){return AS.includes(n)}function Cn(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 WS(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function qo(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function qS(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 KS(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 of(n){switch(n.reason){case re.LeaveRequest:return n.context;case re.Cancelled:return Tt.CLIENT_INITIATED;case re.NotAllowed:return Tt.USER_REJECTED;case re.ServerUnreachable:return Tt.JOIN_FAILURE;default:return Tt.UNKNOWN_REASON}}function Ns(n){return n!==void 0?Number(n):void 0}function Fn(n){return n!==void 0?BigInt(n):void 0}function pi(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Yt(n){return!!n&&n.kind==I.Kind.Audio}function mi(n){return!!n&&n.kind==I.Kind.Video}function wn(n){return pi(n)&&mi(n)}function jn(n){return pi(n)&&Yt(n)}function Ko(n){return!!n&&!n.isLocal}function $S(n){return!!n&&!n.isLocal}function $o(n){return Ko(n)&&mi(n)}function YS(n){return n.isLocal}function XS(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 cf(n,e,t){var i,r,s,a;const{optionsWithoutProcessor:o,audioProcessor:l,videoProcessor:c}=hf(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&&(Yo(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&&(Yo(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 Yo(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Xo(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":Yo(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 lf(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=uf();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 ot(t),r.getByteTimeDomainData(a);const l=a.some(c=>c!==128&&c!==0);return i.close(),!l}return!1}()})}function uf(){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 JS(n){return n==="audioinput"?I.Source.Microphone:n==="videoinput"?I.Source.Camera:I.Source.Unknown}function df(n){return n===I.Source.Microphone?"audioinput":n===I.Source.Camera?"videoinput":void 0}function QS(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,Sn()?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 Ls(n){return n.split("/")[1].toLowerCase()}function ZS(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new vo({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ce(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?ce(n.track):{})}}function eC(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function tC(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 hf(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:wS(e)}}function nC(n){switch(n){case Ne.CAMERA:return I.Source.Camera;case Ne.MICROPHONE:return I.Source.Microphone;case Ne.SCREEN_SHARE:return I.Source.ScreenShare;case Ne.SCREEN_SHARE_AUDIO:return I.Source.ScreenShareAudio;default:return I.Source.Unknown}}class iC extends Vt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,r;const{kind:s,data:a}=t.data;switch(s){case"error":ne.error(a.error.message),this.emit(Tn.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(Tn.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(Tn.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(yn.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{ne.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Tn.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!kS())throw new Io("tried to setup end-to-end encryption on an unsupported browser");if(ne.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:aS.getLevel()}};this.worker&&(ne.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ne.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ne.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(M.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(A.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==ut.NONE,r.identity)),e.on(A.ConnectionStateChanged,i=>{i===ae.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==ut.NONE,r.identity)})})}).on(A.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(A.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(A.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(U.LocalTrackPublished,i=>y(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(yn.SetKey,i=>this.postKey(i)).on(yn.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"?Ls(i.mimeType):void 0)}}setupE2EESender(e,t){if(!pi(e)||!t){t||ne.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(Po()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Is 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[Is]=!0}})}handleSender(e,t,i){var r;if(!(Is 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(Po()){ne.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{ne.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[Is]=!0}}}const Jo="default";class Be{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Be),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=Be.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){ne.debug("awaiting getUserMedia promise");try{t?yield Be.userMediaPromiseMap.get(t):yield Promise.all(Be.userMediaPromiseMap.values())}catch{ne.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Sn()&&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!==Jo)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===Jo);if(!s){ne.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==Jo&&o.groupId===(i??s.groupId));if(!a){ne.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?Be.userMediaPromiseMap.has(e):Be.userMediaPromiseMap.size>0}}Be.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Be.userMediaPromiseMap=new Map;var Zi;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Zi||(Zi={}));class rC{constructor(){this.pendingTasks=new Map,this.taskMutex=new rt,this.nextTaskIndex=0}run(e){return y(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Zi.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Zi.RUNNING,yield e()}finally{t.status=Zi.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 sC(n,e){const t=new URL(WS(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),ff(t,"rtc")}function aC(n){const e=new URL(qo(n));return ff(e,"validate")}function oC(n){return n.endsWith("/")?n:"".concat(n,"/")}function ff(n,e){return n.pathname="".concat(oC(n.pathname)).concat(e),n.toString()}const cC=["syncState","trickle","offer","answer","simulate","leave"];function lC(n){const e=cC.indexOf(n.case)>=0;return ne.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ge;(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"})(ge||(ge={}));class Qo{get currentState(){return this.state}get isDisconnected(){return this.state===ge.DISCONNECTING||this.state===ge.DISCONNECTED}get isEstablishingConnection(){return this.state===ge.CONNECTING||this.state===ge.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=ge.DISCONNECTED,this.log=ne,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=Kt((i=t.loggerName)!==null&&i!==void 0?i:Ct.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new rC,this.queuedRequests=[],this.closingLock=new rt,this.connectionLock=new rt,this.state=ge.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=ge.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=ge.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=zS(),a=uC(t,s,i),o=sC(e,a),l=aC(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 he("room connection has been cancelled (signal)",re.Cancelled))}),f=setTimeout(()=>{this.close(),u(new he("room connection has timed out (signal)",re.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!==ge.CONNECTED){this.state=ge.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(l);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();u(new he(b,re.NotAllowed,v.status))}else u(new he("Encountered unknown websocket error during connection: ".concat(m.toString()),re.InternalError,v.status))}catch(v){u(new he(v instanceof Error?v.message:"server was not reachable",re.ServerUnreachable))}return}this.handleWSError(m)}),this.ws.onmessage=m=>y(this,void 0,void 0,function*(){var v,b,C;let x;if(typeof m.data=="string"){const T=JSON.parse(m.data);x=$d.fromJson(T,{ignoreUnknownFields:!0})}else if(m.data instanceof ArrayBuffer)x=$d.fromBinary(new Uint8Array(m.data));else{this.log.error("could not decode websocket message: ".concat(typeof m.data),this.logContext);return}if(this.state!==ge.CONNECTED){let T=!1;if(((v=x.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=ge.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===ge.RECONNECTING&&x.message.case!=="leave"?(this.state=ge.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),T=!0)):this.isEstablishingConnection&&x.message.case==="leave"?u(new he("Received leave request while trying to (re)connect",re.LeaveRequest,void 0,x.message.value.reason)):i.reconnect||u(new he("did not receive join response, got ".concat((C=x.message)===null||C===void 0?void 0:C.case," instead"),re.InternalError)),!T)return}this.signalLatency&&(yield ot(this.signalLatency)),this.handleSignalResponse(x)}),this.ws.onclose=m=>{this.isEstablishingConnection&&u(new he("Websocket got closed during a (re)connection attempt",re.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=ge.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,ot(250)])),e.ws=void 0}}finally{t&&(e.state=ge.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ms(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Ms(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 mo({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new go({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 Qd({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 Jd({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new th({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Te.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new rh({timestamp:Te.parse(Date.now()),rtt:Te.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Xd({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ts({reason:Tt.CLIENT_INITIATED,action:li.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&&!lC(t)&&i.state===ge.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 ot(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 Mk({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=pf(r.value);this.onAnswer&&this.onAnswer(a)}else if(r.case==="offer"){const a=pf(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===ge.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=He.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&&He.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=He.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&He.clearInterval(this.pingInterval)}}function pf(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 Ms(n){return new Dn({sdp:n.sdp,type:n.type})}function uC(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",Gt()?"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 xt={},Zo={},ec={exports:{}},mf;function tc(){if(mf)return ec.exports;mf=1;var n=ec.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")})}),ec.exports}var gf;function dC(){return gf||(gf=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=tc(),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}})})}}(Zo)),Zo}var nc,vf;function hC(){if(vf)return nc;vf=1;var n=tc(),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 nc=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
- `},nc}var bf;function fC(){if(bf)return xt;bf=1;var n=dC(),e=hC(),t=tc();return xt.grammar=t,xt.write=e,xt.parse=n.parse,xt.parseParams=n.parseParams,xt.parseFmtpConfig=n.parseFmtpConfig,xt.parsePayloads=n.parsePayloads,xt.parseRemoteCandidates=n.parseRemoteCandidates,xt.parseImageAttributes=n.parseImageAttributes,xt.parseSimulcastStreamList=n.parseSimulcastStreamList,xt}var xn=fC();function ic(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(T){return(0,T.resolve)(x)}),u=[]}},d()),b){var C=n.apply(g,f);return o&&o(C),m(C)}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 pC=.7,mC=20,gi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class yf extends Vt.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=ne,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ic(r=>y(this,void 0,void 0,function*(){this.emit(gi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),mC),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=Kt((i=t.loggerName)!==null&&i!==void 0?i:Ct.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}=gC(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=xn.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=xn.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(gi.NegotiationComplete),e.sdp&&xn.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(gi.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=xn.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{kf(s),s.type==="audio"?Tf(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||(Ji(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*pC);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,xn.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=xn.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{kf(r),r.type==="audio"&&Tf(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,xn.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 Me("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 Me("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 Oo(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Qh))){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:Qh})}}}function Tf(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 gC(n){var e;const t=[],i=[],r=xn.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 kf(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 rc="vp8",vC={audioPreset:Mo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Uo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:rc,backupCodec:!0},Sf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Cf={deviceId:{ideal:"default"},resolution:Xi.h720.resolution},bC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new cS,disconnectOnPageLeave:!0,webAudioMix:!1},sc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var xe;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(xe||(xe={}));class yC{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=sc.peerConnectionTimeout,this.log=ne,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(l=>l.getConnectionState());o.every(l=>l==="connected")?this.state=xe.CONNECTED:o.some(l=>l==="failed")?this.state=xe.FAILED:o.some(l=>l==="connecting")?this.state=xe.CONNECTING:o.every(l=>l==="closed")?this.state=xe.CLOSED:o.some(l=>l==="closed")?this.state=xe.CLOSING:o.every(l=>l==="new")&&(this.state=xe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(xe[a]," to ").concat(xe[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Kt((r=i.loggerName)!==null&&r!==void 0?r:Ct.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new yf(e,i),this.subscriber=new yf(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,St.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,St.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=xe.NEW,this.connectionLock=new rt,this.remoteOfferLock=new rt}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===St.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(gi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(gi.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===St.PUBLISHER?this.publisher.getConnectedAddress():e===St.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),He.clearTimeout(d),c(new he("room connection has been cancelled",re.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=He.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(new he("could not establish pc connection",re.InternalError))},a);for(;this.state!==xe.CONNECTED;)if(yield ot(50),r!=null&&r.signal.aborted){c(new he("room connection has been cancelled",re.Cancelled));return}He.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}class _e extends Error{constructor(e,t,i){super(t),this.code=e,this.message=xf(t,_e.MAX_MESSAGE_BYTES),this.data=i?xf(i,_e.MAX_DATA_BYTES):void 0}static fromProto(e){return new _e(e.code,e.message,e.data)}toProto(){return new Fd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new _e(_e.ErrorCode[e],_e.ErrorMessage[e],t)}}_e.MAX_MESSAGE_BYTES=256,_e.MAX_DATA_BYTES=15360,_e.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},_e.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 wf=15360;function ac(n){return new TextEncoder().encode(n).length}function xf(n,e){if(ac(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 oc=2e3;function Ds(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 TC=1e3;class _f extends I{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=ic(()=>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(L.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new rt,this.pauseUpstreamLock=new rt,this.processorLock=new rt,this.restartLock=new rt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==I.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=>{hi(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&&(di(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=>{di(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]:TC;return function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=wt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield ot(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield ot(50)}throw new $t("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===Cn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Cn(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===I.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===I.Kind.Audio?"audioinput":"videoinput";return t?Be.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 $t("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=lS(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===I.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(c=>{hi(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(L.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?L.Muted:L.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),Zh()&&(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(L.UpstreamPaused,this);const i=wt();if((i==null?void 0:i.name)==="Safari"&&Bn(i.version,"12.0")<0)throw new Io("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(L.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(di(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&&(hi(i._mediaStreamTrack,c),di(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(L.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(L.TrackProcessorUpdate))}()})}}class Us extends _f{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,I.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=Ds(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,kt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,kt.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===I.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!==Cn(this._constraints.deviceId);return this.source===I.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=Xo({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(){ct()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},oc)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Gt()&&!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(L.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 lf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(L.AudioSilenceDetected)),e})}}function kC(n,e,t){switch(n.kind){case"audio":return new Us(n,e,!1,void 0,t);case"video":return new Fs(n,e,!1,t);default:throw new $t("unsupported track type: ".concat(n.kind))}}const SC=Object.values(Xi),CC=Object.values(Do),wC=Object.values(Uo),xC=[Xi.h180,Xi.h360],_C=[Do.h180,Do.h360],EC=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new de(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)}),cc=["q","h","f"];function lc(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=PC(n,e,t,c),ne.debug("using video encoding",a));const u=a.maxFramerate,d=new de(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(l&&Ji(c)){const g=new Bs(l),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const v=wt();if(Sn()||Gt()||(v==null?void 0:v.name)==="Chrome"&&Bn(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3;for(let C=0;C<g.spatial;C+=1)m.push({rid:cc[2-C],maxBitrate:a.maxBitrate/Math.pow(b,C),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),ne.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(r=Rf(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Ef(n,d):h=(s=Rf(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Ef(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 uc(e,t,[g,f,d],u);if(m>=480)return uc(e,t,[g,d],u)}return uc(e,t,[d])}function RC(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ne.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===I.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),lc(n.source===I.Source.ScreenShare,l,c,t)}function PC(n,e,t,i){const r=IC(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 IC(n,e,t){if(n)return wC;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?SC:CC}function Ef(n,e){if(n)return EC(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)?xC:_C}function uc(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=cc.length)return;const o=Math.min(n,e),c={rid:cc[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=fi()||a===0;s.encoding.priority&&d&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),Gt()&&tf()==="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,ne.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ne.info('Setting framerate of encoding "'.concat((l=o.rid)!==null&&l!==void 0?l:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Rf(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 Bs{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 OC(n){return n.source===I.Source.ScreenShare||n.constraints.height&&Cn(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const AC=5e3;class Fs extends _f{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,I.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+=Ds(l,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new rt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ct())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()},oc))}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=bn(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=bn(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===I.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===I.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=mt.LOW;i<=mt.HIGH;i+=1)t.push(new bo({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=Xo({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var l=!0,c=bn(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=bn(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)},AC))}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=bn(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 Pf(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 Pf(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),Zh()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Pf(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=wt();if((u==null?void 0:u.name)==="Chrome"&&Bn(u==null?void 0:u.version,"133")>0&&l[0].scalabilityMode){const h=l[0],f=new Bs(h.scalabilityMode);let g=si.OFF;if(t.forEach(m=>{m.enabled&&(g===si.OFF||m.quality>g)&&(g=m.quality)}),g===si.OFF)h.active&&(h.active=!1,c=!0);else if(!h.active||f.spatial!==g+1){c=!0,h.active=!0;const m=new Bs(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=If(m),b=t.find(C=>C.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),fi()&&(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 If(n){switch(n){case"f":return mt.HIGH;case"h":return mt.MEDIUM;case"q":return mt.LOW;default:return mt.HIGH}}function Of(n,e,t,i){if(!t)return[new Mn({quality:mt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new Bs(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 Mn({quality:Math.min(mt.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=If((a=r.rid)!==null&&a!==void 0?a:"");return new Mn({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 Af="_lossy",Nf="_reliable",NC=2*1e3,dc="leave-reconnect";var _t;(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"})(_t||(_t={}));class LC extends Vt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=sc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=_t.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=ne,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===Nf)s.reliableDCSub=a;else if(a.label===Af)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=at.fromBinary(new Uint8Array(o));((r=l.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(M.ActiveSpeakersUpdate,l.value.value.speakers):(((s=l.value)===null||s===void 0?void 0:s.case)==="user"&&DC(l,l.value.value),this.emit(M.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?se.LOSSY:se.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(M.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===dc&&(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=He.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===_t.Connected&&i();const s=()=>{this.off(M.Disconnected,a),i()},a=()=>{this.off(M.Restarted,s),r()};this.once(M.Restarted,s),this.once(M.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(M.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ge.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ai.RR_SIGNAL_DISCONNECTED))},this.log=Kt((t=e.loggerName)!==null&&t!==void 0?t:Ct.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Qo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new rt,this.dataProcessLock=new rt,this.dcBufferStatus=new Map([[se.LOSSY,!0],[se.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(M.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(M.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(M.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(M.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(M.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(M.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(M.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(M.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(M.SignalConnected)},10),s}catch(s){if(s instanceof he&&s.reason===re.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(M.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 $t("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 he("publication of local track timed out, no response from server",re.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!==xe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new yC(r,e.subscriberPrimary,this.loggerOptions),this.emit(M.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===xe.CONNECTED){const u=this.pcState===_t.New;this.pcState=_t.Connected,u&&this.emit(M.Connected,e)}else s===xe.FAILED&&this.pcState===_t.Connected&&(this.pcState=_t.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ai.RR_SUBSCRIBER_FAILED:ai.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===ge.RECONNECTING,c=[xe.FAILED,xe.CLOSING,xe.CLOSED].includes(s);l&&c&&!this._isClosed&&this.emit(M.Offline)}),this.pcManager.onTrack=s=>{this.emit(M.MediaTrackAdded,s.track,s.streams[0],s.receiver)},MC((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(M.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(M.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(M.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(M.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(M.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ai.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 li.DISCONNECT:this.emit(M.Disconnected,e==null?void 0:e.reason),this.close();break;case li.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(dc);break;case li.RESUME:this.handleDisconnect(dc)}}}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===Ki.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(Af,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Nf,{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(Bo())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Fo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Me("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(Bo())return this.createSimulcastTransceiverSender(e,t,i,r);if(Fo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Me("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Me("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),mi(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 Me("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 Me("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){ne.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ki.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:xe.NEW)===xe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Me?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof vi||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ai.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(M.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 Me("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(M.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 vi;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof he&&a.reason===re.NotAllowed?new Me("could not reconnect, token might be expired"):new vi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(M.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ge.CONNECTED)throw new vi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(M.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 Me("could not reconnect, url or token not saved");if(!this.pcManager)throw new Me("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(M.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 he&&r.reason===re.NotAllowed?new Me("could not reconnect, token might be expired"):r instanceof he&&r.reason===re.LeaveRequest?r:new vi(s)}if(this.emit(M.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!==ge.CONNECTED)throw new vi("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(M.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Me("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=_t.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ot(NC),!this.pcManager)throw new Me("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=_t.Connected}catch(e){throw this.pcState=_t.Disconnected,new he("could not establish PC connection, ".concat(e.message),re.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new at({destinationIdentities:[e],kind:se.RELIABLE,value:{case:"rpcResponse",value:new Bd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,se.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new at({destinationIdentities:[e],kind:se.RELIABLE,value:{case:"rpcAck",value:new Ud({requestId:t})}});yield this.sendDataPacket(i,se.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(M.Closing,r);!this.dcBufferStatus.get(e);)yield ot(10);this.off(M.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 Me("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new he("".concat(o," connection not set"),re.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 ot(50)}throw new he("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),re.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!==xe.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 Oo("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(M.Closing,r),this.pcManager.publisher.once(gi.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const l=o.codec.toLowerCase();HS(l)&&a.set(o.payload,l)}),this.emit(M.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Oo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ai.RR_UNKNOWN),t(s)}finally{this.off(M.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===se.LOSSY)return this.lossyDCSub;if(e===se.RELIABLE)return this.reliableDCSub}else{if(e===se.LOSSY)return this.lossyDC;if(e===se.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 nh({answer:s?Ms({sdp:s.sdp,type:s.type}):void 0,offer:a?Ms({sdp:a.sdp,type:a.type}):void 0,subscription:new ys({trackSids:l,subscribe:!o,participantTracks:[]}),publishTracks:ZS(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 ih({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(se.LOSSY),St.PUBLISHER),t(this.dataChannelForKind(se.RELIABLE),St.PUBLISHER),t(this.dataChannelForKind(se.LOSSY,!0),St.SUBSCRIBER),t(this.dataChannelForKind(se.RELIABLE,!0),St.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&He.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ct()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){ct()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class vi extends Error{}function MC(n){return n!==void 0&&n>13}function DC(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 hc{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 Vo(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),ne.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(UC(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 he("Could not fetch region settings: ".concat(t.statusText),t.status===401?re.NotAllowed:re.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function UC(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Lf{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class BC extends Lf{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=bn(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 FC extends Lf{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ns(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=bn(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 Mf{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 jC extends Mf{}class VC extends Mf{}class Df extends I{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?L.Muted:L.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(L.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(),oc)),eC()&&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(L.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class GC extends Df{constructor(e,t,i,r,s,a){super(e,t,I.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=Ds(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;Gt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Gt())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(jo(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&jo(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(L.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(L.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 fc=100;class zC extends Df{constructor(e,t,i,r,s){super(e,t,I.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=Ds(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=ic(()=>{this.updateDimensions()},fc),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?hi(this._mediaStreamTrack,t):di(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new HC(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<fc){He.setTimeout(()=>{this.updateVisibility()},fc);return}this.lastVisible=a,this.emit(L.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(L.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?nf():t||(nf()>2?2:1)}}class HC{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=er(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=er(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=er(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??pc(e),this.isPiP=ct()&&er(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=pc(this.element),this.isPiP=er(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,sf().observe(this.element),rf().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=sf())===null||e===void 0||e.unobserve(this.element),(t=rf())===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 er(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?pc(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function pc(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 Xt extends Vt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=ut.NONE,this.log=ne,this.handleMuted=()=>{this.emit(L.Muted)},this.handleUnmuted=()=>{this.emit(L.Unmuted)},this.log=Kt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Ct.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=I.Source.Unknown}setTrack(e){this.track&&(this.track.off(L.Muted,this.handleMuted),this.track.off(L.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(L.Muted,this.handleMuted),e.on(L.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ce(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==ut.NONE}get audioTrack(){if(Yt(this.track))return this.track}get videoTrack(){if(mi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=I.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===I.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={}))})(Xt||(Xt={}));class mc extends Xt{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(L.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(L.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(L.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(Yt(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(kt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(kt.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(kt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(kt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(kt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(kt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function js(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=hf(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=cf(s,Sf,Cf),c=Xo(l),u=navigator.mediaDevices.getUserMedia(c);s.audio&&(Be.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Be.userMediaPromiseMap.delete("audioinput"))),s.video&&(Be.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Be.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&&Cn(m.deviceId)!==b?m.deviceId=b:m||(m={deviceId:b});const C=kC(h,m,e);return C.kind===I.Kind.Video?C.source=I.Source.Camera:C.kind===I.Kind.Audio&&(C.source=I.Source.Microphone),C.mediaStream=d,Yt(C)&&i?yield C.setProcessor(i):mi(C)&&r&&(yield C.setProcessor(r)),C})))}catch(d){if(!t)throw d;return js(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function WC(n){return y(this,void 0,void 0,function*(){return(yield js({audio:!1,video:n??!0}))[0]})}function qC(n){return y(this,void 0,void 0,function*(){return(yield js({audio:n??!0,video:!1}))[0]})}var _n;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(_n||(_n={}));function KC(n){switch(n){case qi.EXCELLENT:return _n.Excellent;case qi.GOOD:return _n.Good;case qi.POOR:return _n.Poor;case qi.LOST:return _n.Lost;default:return _n.Unknown}}class Uf extends Vt.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===bs.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===oi.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]:bs.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=_n.Unknown,this.log=ne,this.log=Kt((l=a==null?void 0:a.loggerName)!==null&&l!==void 0?l:Ct.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 Wo,this.once(U.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(I.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(I.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(I.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===oi.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==oi.ACTIVE&&this.emit(U.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(U.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(U.ParticipantNameChanged,e)}_setAttributes(e){const t=tC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(U.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(U.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(U.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=KC(e),t!==this._connectionQuality&&this.emit(U.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=>Yt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(L.Muted,()=>{this.emit(U.TrackMuted,e)}),e.on(L.Unmuted,()=>{this.emit(U.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case I.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case I.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function $C(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 eh({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 Bf=15e3;class YC extends Uf{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=ut.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Wo)},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!==yo.OK&&u.reject(new Yh(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=_e.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=>$C(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),ce(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ce(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ce(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=bn(b),v;v=yield m.next(),o=v.done,!o;g=!0){u=v.value,g=!1;const C=u;NS(C)&&(this.log.debug("publish ".concat(C," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ce(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,C,f.options))}}catch(C){l={error:C}}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===I.Source.ScreenShare||a.source===I.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ce(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(jn(a)||wn(a))try{if(ct())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===I.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),ce(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),ce(a))),jn(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),ce(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!==ut.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(M.RemoteMute,(t,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(M.Connected,this.handleReconnected).on(M.SignalRestarted,this.handleReconnected).on(M.SignalResumed,this.handleReconnected).on(M.Restarting,this.handleReconnecting).on(M.Resuming,this.handleReconnecting).on(M.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(M.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(M.Disconnected,this.handleDisconnected).on(M.SignalRequestResponse,this.handleSignalRequestResponse).on(M.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 ot(50)}l(new Yh("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(I.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(I.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(I.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(U.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?ut.GCM:ut.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 I.Source.Camera:l=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case I.Source.Microphone:l=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case I.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new $t(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(U.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),ce(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===I.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const l=this.getTrackPublication(I.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(I.Source.Camera)||this.pendingPublishing.has(I.Source.Microphone))){this.pendingPublishing.add(I.Source.Camera),this.pendingPublishing.add(I.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(I.Source.Camera),this.pendingPublishing.delete(I.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const r=cf(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 js(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Yt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=I.Source.Microphone,this.emit(U.AudioStreamAcquired)),mi(o)&&(this.cameraError=void 0,o.source=I.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 Io("getDisplayMedia not supported");e.resolution===void 0&&!FS()&&(e.resolution=Uo.h1080fps30.resolution);const t=QS(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new $t("no video track found");const s=new Fs(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=I.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(U.AudioStreamAcquired);const o=new Us(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=I.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;jn(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),pi(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 I.Source.Microphone:b="audioinput";break;case I.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 Us(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Fs(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new $t("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),ce(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),ce(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);!jS()&&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,C)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ge.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ce(i)}));const x=()=>y(this,void 0,void 0,function*(){try{const T=yield this.publish(i,m,g);b(T)}catch(T){C(T)}});setTimeout(()=>{this.engine.off(M.SignalConnected,x),C(new Ao("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(M.SignalConnected,x),this.engine.on(M.Closing,()=>{this.engine.off(M.SignalConnected,x),C(new Ao("publishing rejected as engine closed",499))})}else try{const x=yield this.publish(i,m,g);b(x)}catch(x){C(x)}}catch(x){C(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),ce(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>nC(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ce(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 Ao("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(S=>pi(e)&&S.source===e.source)&&e.source!==I.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ce(e))),t.stopMicTrackOnMute&&Yt(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&fi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!DS()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!US()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=rc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(S=>t.videoCodec===Ls(S.mime))||(t.videoCodec=Ls(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(L.Muted,this.onTrackMuted),e.on(L.Unmuted,this.onTrackUnmuted),e.on(L.Ended,this.handleTrackEnded),e.on(L.UpstreamPaused,this.onTrackUpstreamPaused),e.on(L.UpstreamResumed,this.onTrackUpstreamResumed),e.on(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new po({cid:e.mediaStreamTrack.id,name:t.name,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.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===I.Kind.Video){let S={width:0,height:0};try{S=yield e.waitForDimensions()}catch{const E=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Xi.h720.resolution;S={width:E.width,height:E.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ce(e)),{dims:S}))}v.width=S.width,v.height=S.height,wn(e)&&(Ji(m)&&(e.source===I.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),ce(e))))),t.scalabilityMode=(l=t.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),v.simulcastCodecs=[new fo({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:rc}),t.backupCodec&&m!==t.backupCodec.codec&&v.encryption===ut.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new fo({codec:t.backupCodec.codec,cid:""})))),b=lc(e.source===I.Source.ScreenShare,v.width,v.height,t),v.layers=Of(v.width,v.height,b,Ji(t.videoCodec))}else e.kind===I.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 Me("cannot publish track when not connected");const C=()=>y(this,void 0,void 0,function*(){var S,w,E;if(!this.engine.pcManager)throw new Me("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),wn(e)&&((S=t.degradationPreference)!==null&&S!==void 0||(t.degradationPreference=OC(e)),e.setDegradationPreference(t.degradationPreference)),b)if(fi()&&e.kind===I.Kind.Audio){let P;for(const O of this.engine.pcManager.publisher.getTransceivers())if(O.sender===e.sender){P=O;break}P&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:P,codec:"opus",maxbr:!((w=b[0])===null||w===void 0)&&w.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Ji(e.codec)&&(!((E=b[0])===null||E===void 0)&&E.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),C()]))[0];else{x=yield this.engine.addTrack(v);let S;if(x.codecs.forEach(w=>{S===void 0&&(S=w.mimeType)}),S&&e.kind===I.Kind.Video){const w=Ls(S);w!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ce(e)),{codec:w})),t.videoCodec=w,b=lc(e.source===I.Source.ScreenShare,v.width,v.height,t))}yield C()}const T=new mc(e.kind,x,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return T.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})),wn(e)?e.startMonitor(this.engine.client):jn(e)&&e.startMonitor(),this.addTrackPublication(T),this.emit(U.LocalTrackPublished,T),T})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==ut.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new $t("track is not published");if(!wn(e))throw new $t("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=RC(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),ce(e)));return}const l=e.addSimulcastTrack(t,o);if(!l)return;const c=new po({cid:l.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=Of(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Me("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(pi(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ce(e))),yield c)}const s=this.getPublicationForTrack(e),a=s?ce(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(L.Muted,this.onTrackMuted),e.off(L.Unmuted,this.onTrackUnmuted),e.off(L.Ended,this.handleTrackEnded),e.off(L.UpstreamPaused,this.onTrackUpstreamPaused),e.off(L.UpstreamResumed,this.onTrackUpstreamResumed),e.off(L.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<xe.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),wn(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 I.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case I.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(U.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!==I.Source.ScreenShare&&c.source!==I.Source.ScreenShareAudio&&(jn(c)||wn(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?se.RELIABLE:se.LOSSY,a=r.destinationIdentities,o=r.topic,l=new at({kind:s,value:{case:"user",value:new Ld({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 at({kind:se.RELIABLE,value:{case:"sipDtmf",value:new Md({code:e,digit:t})}});yield this.engine.sendDataPacket(i,se.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 at({value:{case:"chatMessage",value:new ao(Object.assign(Object.assign({},i),{timestamp:Te.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,se.RELIABLE),this.emit(U.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 at({value:{case:"chatMessage",value:new ao(Object.assign(Object.assign({},i),{timestamp:Te.parse(i.timestamp),editTimestamp:Te.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,se.RELIABLE),this.emit(U.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 co({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Fn(s.timestamp),totalLength:Fn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new qd({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"?oo.UPDATE:oo.CREATE})}}),o=e==null?void 0:e.destinationIdentities,l=new at({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,se.RELIABLE);let c=0;const u=this,d=new WritableStream({write(g){return y(this,void 0,void 0,function*(){for(const m of XS(g,Bf)){yield u.engine.waitForBufferStatusLow(se.RELIABLE);const v=new lo({content:m,streamId:r,chunkIndex:Fn(c)}),b=new at({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,se.RELIABLE),c+=1}})},close(){return y(this,void 0,void 0,function*(){const g=new uo({streamId:r}),m=new at({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield u.engine.sendDataPacket(m,se.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(M.Closing,h);const f=new jC(d,s,()=>this.engine.off(M.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 co({totalLength:Fn((a=c.size)!==null&&a!==void 0?a:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:Fn(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Kd({name:c.name})}}),d=new at({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,se.RELIABLE);let h=0;const f=new rt,g=this.engine,m=this.log,v=new WritableStream({write(C){return y(this,void 0,void 0,function*(){const x=yield f.lock();let T=0;try{for(;T<C.byteLength;){const S=C.slice(T,T+Bf);yield g.waitForBufferStatusLow(se.RELIABLE);const w=new at({destinationIdentities:l,value:{case:"streamChunk",value:new lo({content:S,streamId:o,chunkIndex:Fn(h)})}});yield g.sendDataPacket(w,se.RELIABLE),h+=1,T+=S.byteLength}}finally{x()}})},close(){return y(this,void 0,void 0,function*(){const C=new uo({streamId:o}),x=new at({destinationIdentities:l,value:{case:"streamTrailer",value:C}});yield g.sendDataPacket(x,se.RELIABLE)})},abort(C){m.error("Sink error:",C)}});return new VC(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(ac(a)>wf){u(_e.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&&Bn((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(_e.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(_e.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(_e.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(C,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(C??"")},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 at({destinationIdentities:[e],kind:se.RELIABLE,value:{case:"rpcRequest",value:new Dd({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,se.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,_e.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),ce(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?(jn(r)||wn(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 ot(20)}})}}class XC extends Xt{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=mt.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(L.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 ys({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new jd({participantSid:"",trackSids:[this.trackSid]})]});this.emit(L.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Xt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Xt.SubscriptionStatus.Subscribed:Xt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Xt.PermissionStatus.Allowed:Xt.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||($o(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&$o(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(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(L.VisibilityChanged,this.handleVisibilityChange),r.off(L.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(L.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(L.VisibilityChanged,this.handleVisibilityChange),e.on(L.Ended,this.handleEnded),this.emit(L.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(L.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?L.Muted:L.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(L.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(L.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===I.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 $o(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Yd({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=mt.HIGH,this.emit(L.UpdateSettings,e)}}class Vs extends Uf{static fromParticipantInfo(e,t,i){return new Vs(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]:bs.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(L.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ce(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(L.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(L.SubscriptionPermissionChanged,t=>{this.emit(U.TrackSubscriptionPermissionChanged,e,t)}),e.on(L.SubscriptionStatusChanged,t=>{this.emit(U.TrackSubscriptionStatusChanged,e,t)}),e.on(L.Subscribed,t=>{this.emit(U.TrackSubscribed,t,e)}),e.on(L.Unsubscribed,t=>{this.emit(U.TrackUnsubscribed,t,e)}),e.on(L.SubscriptionFailed,t=>{this.emit(U.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]:I.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]:I.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(U.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),ce(o))),this.emit(U.TrackSubscriptionFailed,t);return}const l=e.kind==="video";let c;return l?c=new zC(e,t,r,s):c=new GC(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)&&Ko(c)&&Yt(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=I.kindFromProto(r.type);if(!l)return;o=new XC(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!==I.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:ce(c),newTrack:ce(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),ce(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(U.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 I.Kind.Audio:this.audioTrackPublications.delete(e);break;case I.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(U.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Yt(i.track)&&Ko(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 ae;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ae||(ae={}));const JC=4*1e3;class bi extends Vt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=ae.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ne,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(!BS())throw Gt()?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===ae.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(ae.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Vo(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new hc(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 C=new AbortController;this.abortController=C,u==null||u();try{yield this.attemptConnection(m??a,o,l,C),this.abortController=void 0,f()}catch(x){if(this.regionUrlProvider&&x instanceof he&&x.reason!==re.Cancelled&&x.reason!==re.NotAllowed){let T=null;try{T=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(S){if(S instanceof he&&(S.status===401||S.reason===re.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(S);return}}T&&!(!((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(T),this.logContext),this.recreateEngine(),yield d(f,g,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,of(x)),g(x))}else{let T=Tt.UNKNOWN_REASON;x instanceof he&&(T=of(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),g(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Wo((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[C,x]=b;return"".concat(C,": ").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 CS("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===ae.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({},sc),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(A.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new he("could not establish signal connection",re.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof he&&(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 he("Connection attempt aborted",re.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}ct()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ct()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ae.Connected),this.emit(A.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===ae.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===ae.Connecting||c.state===ae.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 he("Client initiated disconnect",re.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,Tt.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=wt();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=Ho();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(A.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(ae.Reconnecting)&&this.emit(A.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(ae.Connected),this.emit(A.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===oi.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(A.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(A.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=I.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,l.emit(U.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(A.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(A.DataReceived,o.payload,a,l,o.topic),a==null||a.emit(U.DataReceived,o.payload,l)},this.handleSipDtmf=(a,o)=>{this.emit(A.SipDTMFReceived,o,a),a==null||a.emit(U.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=qS(o,this.transcriptionReceivedTimes);c==null||c.emit(L.TranscriptionReceived,u),l==null||l.emit(U.TranscriptionReceived,u,c),this.emit(A.TranscriptionReceived,u,l,c)},this.handleChatMessage=(a,o)=>{const l=KS(o);this.emit(A.ChatMessage,l,a)},this.handleMetrics=(a,o)=>{this.emit(A.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(A.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(A.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(A.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(A.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,l;const c=Be.getInstance().previousDevices,u=yield Be.getInstance().getDevices(void 0,!1),d=wt();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(A.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const g=JS(f),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(C=>C.kind===f),b=this.getActiveDevice(f);if(b===((o=c.filter(C=>C.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"&&!Sn()||f==="videoinput"||v.length>0&&!v.find(C=>C.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(A.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(A.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(A.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(A.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(A.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(A.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(A.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(A.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(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(L.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(A.LocalTrackPublished,a,this.localParticipant),jn(a.track)&&(yield a.track.checkForSilence())&&this.emit(A.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=df(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(A.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,l;(o=a.track)===null||o===void 0||o.off(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(L.Restarted,this.onLocalTrackRestarted),this.emit(A.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),l=df(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(A.ActiveDeviceChanged,l,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(A.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(A.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(A.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(A.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},bC),e),this.log=Kt((i=this.options.loggerName)!==null&&i!==void 0?i:Ct.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Sf),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Cf),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},vC),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new rt,this.localParticipant=new YC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Cn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Cn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Cn(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),ct()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),bi.cleanupRegistry&&bi.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,_e.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,_e.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});ac(u)>wf?(l=_e.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof _e?l=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=_e.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 iC(this.options.e2ee),this.e2eeManager.on(Tn.ParticipantEncryptionStatusChanged,(t,i)=>{YS(i)&&(this.isE2EEEnabled=t),this.emit(A.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(Tn.EncryptionError,t=>this.emit(A.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===ae.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(M.RoomUpdate,i),e(r.sid))};this.engine.on(M.RoomUpdate,i),this.once(A.Disconnected,()=>{this.engine.off(M.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 LC(this.options),this.engine.on(M.ParticipantUpdate,this.handleParticipantUpdates).on(M.RoomUpdate,this.handleRoomUpdate).on(M.SpeakersChanged,this.handleSpeakersChanged).on(M.StreamStateChanged,this.handleStreamStateUpdate).on(M.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(M.SubscriptionError,this.handleSubscriptionError).on(M.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(M.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(M.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(M.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(M.DataPacketReceived,this.handleDataPacket).on(M.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ae.SignalReconnecting)&&this.emit(A.SignalReconnecting)}).on(M.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ae.Connected)&&this.emit(A.Reconnected)}).on(M.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ae.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(M.Restarting,this.handleRestarting).on(M.SignalRestarted,this.handleSignalRestarted).on(M.Offline,()=>{this.setAndEmitConnectionState(ae.Reconnecting)&&this.emit(A.Reconnecting)}).on(M.DCBufferStatusChanged,(e,t)=>{this.emit(A.DCBufferStatusChanged,e,t)}).on(M.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(U.LocalTrackSubscribed,t),this.emitWhenConnected(A.LocalTrackSubscribed,t,this.localParticipant)}).on(M.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(A.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 Be.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ae.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Vo(new URL(e))&&t){this.regionUrlProvider=new hc(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ae.Disconnected&&(this.regionUrl=i,yield fetch(qo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(qo(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 jt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new jt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new jt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new jt({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 jt({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 jt({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 jt({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 Ts({reason:Tt.CLIENT_INITIATED,action:li.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new jt({scenario:{case:"subscriberBandwidth",value:Fn(t)}});break;case"leave-full-reconnect":r=new jt({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 C=(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(T=>T.source===I.Source.Microphone);try{m=(yield Promise.all(x.map(T=>{var S;return(S=T.audioTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(T=>T===!0)}catch(T){throw s.options.audioCaptureDefaults.deviceId=C,T}}else if(i==="videoinput"){v=s.localParticipant.videoTrackPublications.size===0;const C=(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(T=>T.source===I.Source.Camera);try{m=(yield Promise.all(x.map(T=>{var S;return(S=T.videoTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(T=>T===!0)}catch(T){throw s.options.videoCaptureDefaults.deviceId=C,T}}else if(i==="audiooutput"){if(!jo()&&!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 Be.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(g=s.options).audioOutput)!==null&&u!==void 0||(g.audioOutput={});const C=(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=C,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(A.ActiveDeviceChanged,i,r)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(U.AttributesChanged,this.onLocalAttributesChanged).on(U.TrackMuted,this.onLocalTrackMuted).on(U.TrackUnmuted,this.onLocalTrackUnmuted).on(U.LocalTrackPublished,this.onLocalTrackPublished).on(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(U.MediaDevicesError,this.onMediaDevicesError).on(U.AudioStreamAcquired,this.startAudio).on(U.ChatMessage,this.onLocalChatMessageSent).on(U.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===ae.Connecting||this.state===ae.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(A.Reconnected,u),this.off(A.Connected,u),this.off(A.Disconnected,d)};this.once(A.Reconnected,u),this.once(A.Connected,u),this.once(A.Disconnected,d);return}if(this.state===ae.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=MS(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!==ae.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(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(U.AttributesChanged,this.onLocalAttributesChanged).off(U.TrackMuted,this.onLocalTrackMuted).off(U.TrackUnmuted,this.onLocalTrackUnmuted).off(U.LocalTrackPublished,this.onLocalTrackPublished).off(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(U.MediaDevicesError,this.onMediaDevicesError).off(U.AudioStreamAcquired,this.startAudio).off(U.ChatMessage,this.onLocalChatMessageSent).off(U.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),ct()&&(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(ae.Disconnected),this.emit(A.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(A.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:Ns(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 BC(a,o,Ns(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 FC(a,o,Ns(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=uf())!==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(),ot(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(A.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=Vs.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Vs(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(A.ParticipantConnected,i),i.on(U.TrackPublished,r=>{this.emitWhenConnected(A.TrackPublished,r,i)}).on(U.TrackSubscribed,(r,s)=>{r.kind===I.Kind.Audio?(r.on(L.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(L.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===I.Kind.Video&&(r.on(L.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(L.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(A.TrackSubscribed,r,s,i)}).on(U.TrackUnpublished,r=>{this.emit(A.TrackUnpublished,r,i)}).on(U.TrackUnsubscribed,(r,s)=>{this.emit(A.TrackUnsubscribed,r,s,i)}).on(U.TrackMuted,r=>{this.emitWhenConnected(A.TrackMuted,r,i)}).on(U.TrackUnmuted,r=>{this.emitWhenConnected(A.TrackUnmuted,r,i)}).on(U.ParticipantMetadataChanged,r=>{this.emitWhenConnected(A.ParticipantMetadataChanged,r,i)}).on(U.ParticipantNameChanged,r=>{this.emitWhenConnected(A.ParticipantNameChanged,r,i)}).on(U.AttributesChanged,r=>{this.emitWhenConnected(A.ParticipantAttributesChanged,r,i)}).on(U.ConnectionQualityChanged,r=>{this.emitWhenConnected(A.ConnectionQualityChanged,r,i)}).on(U.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(A.ParticipantPermissionsChanged,r,i)}).on(U.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(A.TrackSubscriptionStatusChanged,r,s,i)}).on(U.TrackSubscriptionFailed,(r,s)=>{this.emit(A.TrackSubscriptionFailed,r,i,s)}).on(U.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(A.TrackSubscriptionPermissionChanged,r,s,i)}).on(U.Active,()=>{this.emitWhenConnected(A.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&&$S(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=He.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,Tt.STATE_MISMATCH))):e=0},JC)}clearConnectionReconcile(){this.connectionReconcileInterval&&He.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(A.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===ae.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ae.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 gs({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Te.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ln({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(A.SignalConnected),this.emit(A.Connected),this.setAndEmitConnectionState(ae.Connected),r.video){const a=new mc(I.Kind.Video,new ci({source:Ne.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:yt.AUDIO,name:"video-dummy"}),new Fs(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:af(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(U.LocalTrackPublished,a)}if(r.audio){const a=new mc(I.Kind.Audio,new ci({source:Ne.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:yt.AUDIO}),new Us(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ho(),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(U.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Ln({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:oi.ACTIVE,tracks:[],joinedAt:Te.parse(Date.now())});const l=this.getOrCreateParticipant(o.identity,o);if(s.video){const c=af(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new ci({source:Ne.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:yt.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const c=Ho(),u=new ci({source:Ne.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:yt.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!==A.ActiveSpeakersChanged&&e!==A.TranscriptionReceived){const s=Ff(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)}}bi.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Ff(n){return n.map(e=>{if(e)return Array.isArray(e)?Ff(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Et;(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"})(Et||(Et={}));class En extends Vt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Et.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new bi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==Et.IDLE)throw Error("check is running already");this.setStatus(Et.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!==Et.SKIPPED&&this.setStatus(this.isSuccess()?Et.SUCCESS:Et.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===ae.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!==ae.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Et.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(A.Reconnecting,()=>{t=!0}),this.room.once(A.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 ot(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 QC extends En{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new hc(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 gc=1e4;class ZC extends En{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/(gc/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(gc/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,gc)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class e1 extends En{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield qC();if(yield lf(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 t1 extends En{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield WC();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 n1 extends En{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(A.SignalReconnecting,o).on(A.Reconnecting,o).on(A.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!==ae.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 i1 extends En{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new Qo,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 r1 extends En{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(A.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&&(s1(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(),ne.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 s1(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 a1 extends En{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 Qo;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)===Vd.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 b_ extends Vt.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:Et.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!==Et.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(a1)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(r1)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(i1)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(n1)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(e1)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(t1)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(ZC);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(QC)})}}const o1=/\{[^{}]+\}/g;function c1(){return Math.random().toString(36).slice(2,11)}function l1(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=zf(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:C,bodySerializer:x=s??d1,body:T,...S}=d||{};h&&(e=zf(h));let w=typeof r=="function"?r:Gf(r);C&&(w=typeof C=="function"?C:Gf({...typeof r=="object"?r:{},...C}));const E=T===void 0?void 0:x(T),P=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},O={redirect:"follow",...o,...S,body:E,headers:f1(P,a,m,v.header)};let B,N,H=new t(h1(u,{baseUrl:e,params:v,querySerializer:w}),O);for(const Y in S)Y in H||(H[Y]=S[Y]);if(l.length){B=c1(),N=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:w,bodySerializer:x});for(const Y of l)if(Y&&typeof Y=="object"&&typeof Y.onRequest=="function"){const q=await Y.onRequest({request:H,schemaPath:u,params:v,options:N,id:B});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");H=q}}}let W=await f(H);if(l.length)for(let Y=l.length-1;Y>=0;Y--){const q=l[Y];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const fe=await q.onResponse({request:H,response:W,schemaPath:u,params:v,options:N,id:B});if(fe){if(!(fe instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");W=fe}}}if(W.status===204||W.headers.get("Content-Length")==="0")return W.ok?{data:{},response:W}:{error:{},response:W};if(W.ok)return b==="stream"?{data:W.body,response:W}:{data:await W[b](),response:W};let J=await W.text();try{J=JSON.parse(J)}catch{}return{error:J,response:W}}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 Gs(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 jf(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(Gs(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Vf(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(Gs(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Gf(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(Vf(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(jf(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(Gs(r,s,n))}}return i.join("&")}}function u1(n,e){let t=n;for(const i of n.match(o1)??[]){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,Vf(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,jf(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${Gs(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function d1(n){return n instanceof FormData?n:JSON.stringify(n)}function h1(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=u1(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function f1(...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 zf(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Hf="Onboardee-Session-Token",Wf="OnboardeeSessionToken";class qf{constructor(e){this.client=l1({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const i=window.localStorage.getItem(Wf);i&&t.headers.set(Hf,i)}return t},onResponse({response:t}){const i=t.headers.get(Hf);return i&&window.localStorage&&window.localStorage.setItem(Wf,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 listUsers(){return await this.client.GET("/api/users")}async createUser(e){return await this.client.POST("/api/users",{body:e})}async updateUser(e,t){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:t})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}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 listAudiences(e){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)}}})}async createAudience(e,t){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:t})}async getAudience(e,t){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async updateAudience(e,t,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}},body:i})}async deleteAudience(e,t){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async replaceAudiencePlans(e,t,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:t}},body:{plans:i}})}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 listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,t){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async bulkUpdateProductPronunciationRules(e,t){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async deleteProductPronunciationRule(e,t){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:t}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:t})}async updateProductExternalKnowledge(e,t,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}},body:i})}async deleteProductExternalKnowledge(e,t){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}}})}async refreshProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:t}}})}async listExternalKnowledgePages(e,t){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId: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 duplicatePlan(e){return await this.client.POST("/api/plans/{id}/duplicate",{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 listPlanFAQs(e,t=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(t)}}})}async listPlanDraftFAQs(e){return await this.client.GET("/api/plans/{id}/draft-faqs",{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 listRevisionFAQs(e,t){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...t!==void 0&&{include_drafts:t.toString()}}}})}async createRevisionFAQ(e,t){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:t})}async updateFAQ(e,t){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:t})}async deleteFAQ(e){return await this.client.DELETE("/api/faqs/{id}",{params:{path:{id:e}}})}async promoteFAQ(e){return await this.client.POST("/api/faqs/{id}/promote",{params:{path:{id:e}}})}async promoteFAQs(e){return await this.client.POST("/api/faqs/promote",{body:{faq_ids:e}})}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"})}async getFeatureFlags(e){return await this.client.GET("/api/features",{params:e?{query:e}:void 0})}getClient(){return this.client}}const Kf="https://app.coragents.ai";class zs extends ga{constructor(e,t,i,r){super(),this.state=null,this.isPaused=!1,this.isAudioTrackPublished=!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.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.appToken=e,this.planId=t,this.clientType=i,this.api=r.api||new qf({baseUrl:Kf}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new bi(s)),this.captureScreen=r.captureScreen||null}async start(e){this.planId,e==null||e.roomId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const i=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId,...(e==null?void 0:e.roomId)&&{room_id:e.roomId}})).data;if(!(i!=null&&i.url)||!(i!=null&&i.token)||!(i!=null&&i.room)||!(i!=null&&i.session_uuid))throw new Error("Invalid room info");this.sessionUuid=i==null?void 0:i.session_uuid,this.roomId=i==null?void 0:i.room,this.joinToken=i==null?void 0:i.token,this.roomUrl=i==null?void 0:i.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("volume-check"),this.planId,this.sessionUuid}catch(t){console.error("[obi] error starting session",{error:t}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(A.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(A.TrackSubscribed,i=>{if(i.kind==="audio"&&(i.attach(),i.source===I.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=s}}),this.room.on(A.LocalTrackPublished,i=>{if(i.kind==="audio"){this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=s}}),this.room.on(A.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(A.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"in_progress":this.setState("in-progress");break;case"shutdown":this.shutdown("server-sent");break;case"mute_microphone":this.muteMicrophone();break;case"unmute_microphone":this.unmuteMicrophone();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===ae.Connected&&this.room.remoteParticipants.size>=1);i++)await new Promise(r=>setTimeout(r,1e3));if(!(this.room.state===ae.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 publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const c=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",c),!1}console.log("[obi] requesting audio track via getUserMedia"),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});const t=this.publishedAudioStream.getAudioTracks().map(c=>{var u,d;return{id:c.id,label:c.label,enabled:c.enabled,muted:c.muted,readyState:c.readyState,constraints:(u=c.getConstraints)==null?void 0:u.call(c),settings:(d=c.getSettings)==null?void 0:d.call(c)}});console.log("[obi] getUserMedia resolved",t);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const c=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",c),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},s=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,s);const a=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:I.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,s,a.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:o,context:l}=this.createFFT(this.publishedAudioStream);this.userAnalyser=o,this.userAudioContext=l,this.isAudioTrackPublished=!0,e=!0}catch(t){if(console.error("[obi] failed to publish audio track",t),this.isAudioTrackPublished=!1,this.publishedAudioStream){try{this.publishedAudioStream.getTracks().forEach(i=>i.stop())}catch(i){console.warn("[obi] error stopping tracks during cleanup",i)}this.publishedAudioStream=null}this.publishedAudioTrack=null}return e}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){if(this.sessionUuid,this.publishedAudioTrack&&this.isAudioTrackPublished)try{console.log("[obi] unpublishing audio track",this.publishedAudioTrack.id,this.room.localParticipant.identity),this.room.localParticipant.unpublishTrack(this.publishedAudioTrack)}catch(i){console.warn("[obi] failed to unpublish audio track",i)}if(this.publishedAudioStream)try{const i=this.publishedAudioStream.getAudioTracks().length;console.log("[obi] stopping published audio stream tracks",i),this.publishedAudioStream.getTracks().forEach(r=>r.stop())}catch(i){console.warn("[obi] error stopping published audio tracks",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null),this.isAudioTrackPublished=!1,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.frequencyDataBuffer=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}agentAudioSpectrum(){return this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):null}normaliseSpectrum(e){const i=e.context.sampleRate/2/e.frequencyBinCount;(!this.frequencyDataBuffer||this.frequencyDataBuffer.length!==e.frequencyBinCount)&&(this.frequencyDataBuffer=new Uint8Array(new ArrayBuffer(e.frequencyBinCount))),e.getByteFrequencyData(this.frequencyDataBuffer);const r=[],s=50,a=5e3,o=8,l=Math.pow(a/s,1/o);for(let c=0;c<o;c++){const u=s*Math.pow(l,c),d=s*Math.pow(l,c+1),h=Math.floor(u/i),f=Math.floor(d/i),g=Math.min(f,this.frequencyDataBuffer.length),m=Math.min(h,g);if(m<g){let v=0;for(let C=m;C<g;C++)v+=this.frequencyDataBuffer[C];const b=v/(g-m)/255;r.push(b)}else r.push(0)}return r}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 zs(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,{analyser:i,context:t}}}class Hs extends ga{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 qf({baseUrl:i.apiBaseUrl||Kf}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new zs(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,i){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(i).then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,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),a=new Hs(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=zs.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 Ws,X,$f,Vn,Yf,Xf,Jf,Qf,vc,bc,yc,Zf,tr={},ep=[],p1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,nr=Array.isArray;function Jt(n,e){for(var t in e)n[t]=e[t];return n}function Tc(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function kc(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?Ws.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return qs(n,a,i,r,null)}function qs(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??++$f,__i:-1,__u:0};return r==null&&X.vnode!=null&&X.vnode(s),s}function $e(n){return n.children}function Qt(n,e){this.props=n,this.context=e}function yi(n,e){if(e==null)return n.__?yi(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"?yi(n):null}function tp(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 tp(n)}}function Sc(n){(!n.__d&&(n.__d=!0)&&Vn.push(n)&&!Ks.__r++||Yf!=X.debounceRendering)&&((Yf=X.debounceRendering)||Xf)(Ks)}function Ks(){for(var n,e,t,i,r,s,a,o=1;Vn.length;)Vn.length>o&&Vn.sort(Jf),n=Vn.shift(),o=Vn.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=Jt({},i)).__v=i.__v+1,X.vnode&&X.vnode(t),Cc(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??yi(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,ap(s,t,a),t.__e!=r&&tp(t)));Ks.__r=0}function np(n,e,t,i,r,s,a,o,l,c,u){var d,h,f,g,m,v,b=i&&i.__k||ep,C=e.length;for(l=m1(t,e,b,l,C),d=0;d<C;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?tr:b[f.__i]||tr,f.__i=d,v=Cc(n,f,h,r,s,a,o,l,c,u),g=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&wc(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=ip(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 m1(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?qs(null,a,null,null,null):nr(a)?qs($e,{children:a},null,null,null):a.constructor==null&&a.__b>0?qs(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=g1(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=yi(o)),cp(o,o));return i}function ip(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=ip(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=yi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function $s(n,e){return e=e||[],n==null||typeof n=="boolean"||(nr(n)?n.some(function(t){$s(t,e)}):e.push(n)),e}function g1(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 rp(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||p1.test(e)?t:t+"px"}function Ys(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||rp(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||rp(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Qf,"$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=vc,n.addEventListener(e,s?yc:bc,s)):n.removeEventListener(e,s?yc:bc,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 sp(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=vc++;else if(e.t<t.u)return;return t(X.event?X.event(e):e)}}}function Cc(n,e,t,i,r,s,a,o,l,c){var u,d,h,f,g,m,v,b,C,x,T,S,w,E,P,O,B,N=e.type;if(e.constructor!=null)return null;128&t.__u&&(l=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=X.__b)&&u(e);e:if(typeof N=="function")try{if(b=e.props,C="prototype"in N&&N.prototype.render,x=(u=N.contextType)&&i[u.__c],T=u?x?x.props.value:u.__:i,t.__c?v=(d=e.__c=t.__c).__=d.__E:(C?e.__c=d=new N(b,T):(e.__c=d=new Qt(b,T),d.constructor=N,d.render=b1),x&&x.sub(d),d.props=b,d.state||(d.state={}),d.context=T,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&N.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Jt({},d.__s)),Jt(d.__s,N.getDerivedStateFromProps(b,d.__s))),f=d.props,g=d.state,d.__v=e,h)C&&N.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&N.getDerivedStateFromProps==null&&b!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,T),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,T)===!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(H){H&&(H.__=e)}),S=0;S<d._sb.length;S++)d.__h.push(d._sb[S]);d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,T),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,g,m)})}if(d.context=T,d.props=b,d.__P=n,d.__e=!1,w=X.__r,E=0,C){for(d.state=d.__s,d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),P=0;P<d._sb.length;P++)d.__h.push(d._sb[P]);d._sb=[]}else do d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++E<25);d.state=d.__s,d.getChildContext!=null&&(i=Jt(Jt({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(m=d.getSnapshotBeforeUpdate(f,g)),O=u,u!=null&&u.type===$e&&u.key==null&&(O=op(u.props.children)),o=np(n,nr(O)?O:[O],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(H){if(e.__v=null,l||s!=null)if(H.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(B=s.length;B--;)Tc(s[B]);else e.__e=t.__e,e.__k=t.__k;X.__e(H,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=v1(t.__e,e,t,i,r,s,a,l,c);return(u=X.diffed)&&u(e),128&e.__u?void 0:o}function ap(n,e,t){for(var i=0;i<t.length;i++)wc(t[i],t[++i],t[++i]);X.__c&&X.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){X.__e(s,r.__v)}})}function op(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:nr(n)?n.map(op):Jt({},n)}function v1(n,e,t,i,r,s,a,o,l){var c,u,d,h,f,g,m,v=t.props,b=e.props,C=e.type;if(C=="svg"?r="http://www.w3.org/2000/svg":C=="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==!!C&&(C?f.localName==C:f.nodeType==3)){n=f,s[c]=null;break}}if(n==null){if(C==null)return document.createTextNode(b);n=document.createElementNS(r,C,b.is&&b),o&&(X.__m&&X.__m(e,s),o=!1),s=null}if(C==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&Ws.call(n.childNodes),v=t.props||tr,!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;Ys(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||Ys(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=""),np(e.type=="template"?n.content:n,nr(h)?h:[h],e,t,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&yi(t,0),o,l),s!=null)for(c=s.length;c--;)Tc(s[c]);o||(c="value",C=="progress"&&g==null?n.removeAttribute("value"):g!=null&&(g!==n[c]||C=="progress"&&!g||C=="option"&&g!=v[c])&&Ys(n,c,g,v[c],r),c="checked",m!=null&&m!=n[c]&&Ys(n,c,m,v[c],r))}return n}function wc(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){X.__e(r,t)}}function cp(n,e,t){var i,r;if(X.unmount&&X.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||wc(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){X.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&cp(i[r],e,t||typeof n.type!="function");t||Tc(n.__e),n.__c=n.__=n.__e=void 0}function b1(n,e,t){return this.constructor(n,t)}function y1(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),X.__&&X.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Cc(e,n=(!i&&t||e).__k=kc($e,null,[n]),r||tr,tr,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?Ws.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),ap(s,n,a)}function T1(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,Sc(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"+Zf++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}Ws=ep.slice,X={__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}},$f=0,Qt.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Jt({},this.state),typeof n=="function"&&(n=n(Jt({},t),this.props)),n&&Jt(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Sc(this))},Qt.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Sc(this))},Qt.prototype.render=$e,Vn=[],Xf=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Jf=function(n,e){return n.__v.__b-e.__v.__b},Ks.__r=0,Qf=/(PointerCapture)$|Capture$/i,vc=0,bc=sp(!1),yc=sp(!0),Zf=0;var k1=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:--k1,__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 X.vnode&&X.vnode(c),c}var Gn,ke,xc,lp,ir=0,up=[],Oe=X,dp=Oe.__b,hp=Oe.__r,fp=Oe.diffed,pp=Oe.__c,mp=Oe.unmount,gp=Oe.__;function rr(n,e){Oe.__h&&Oe.__h(ke,n,ir||e),ir=0;var t=ke.__H||(ke.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function ee(n){return ir=1,S1(yp,n)}function S1(n,e,t){var i=rr(Gn++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):yp(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=ke,!ke.__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};ke.__f=!0;var s=ke.shouldComponentUpdate,a=ke.componentWillUpdate;ke.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)},ke.shouldComponentUpdate=r}return i.__N||i.__}function Je(n,e){var t=rr(Gn++,3);!Oe.__s&&Rc(t.__H,e)&&(t.__=n,t.u=e,ke.__H.__h.push(t))}function _c(n,e){var t=rr(Gn++,4);!Oe.__s&&Rc(t.__H,e)&&(t.__=n,t.u=e,ke.__h.push(t))}function Rt(n){return ir=5,Xs(function(){return{current:n}},[])}function Xs(n,e){var t=rr(Gn++,7);return Rc(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function C1(n,e){return ir=8,Xs(function(){return n},e)}function vp(n){var e=ke.context[n.__c],t=rr(Gn++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(ke)),e.props.value):n.__}function w1(){for(var n;n=up.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(Js),n.__H.__h.forEach(Ec),n.__H.__h=[]}catch(e){n.__H.__h=[],Oe.__e(e,n.__v)}}Oe.__b=function(n){ke=null,dp&&dp(n)},Oe.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),gp&&gp(n,e)},Oe.__r=function(n){hp&&hp(n),Gn=0;var e=(ke=n.__c).__H;e&&(xc===ke?(e.__h=[],ke.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(Js),e.__h.forEach(Ec),e.__h=[],Gn=0)),xc=ke},Oe.diffed=function(n){fp&&fp(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(up.push(e)!==1&&lp===Oe.requestAnimationFrame||((lp=Oe.requestAnimationFrame)||x1)(w1)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),xc=ke=null},Oe.__c=function(n,e){e.some(function(t){try{t.__h.forEach(Js),t.__h=t.__h.filter(function(i){return!i.__||Ec(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],Oe.__e(i,t.__v)}}),pp&&pp(n,e)},Oe.unmount=function(n){mp&&mp(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{Js(i)}catch(r){e=r}}),t.__H=void 0,e&&Oe.__e(e,t.__v))};var bp=typeof requestAnimationFrame=="function";function x1(n){var e,t=function(){clearTimeout(i),bp&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);bp&&(e=requestAnimationFrame(t))}function Js(n){var e=ke,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),ke=e}function Ec(n){var e=ke;n.__c=n.__(),ke=e}function Rc(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function yp(n,e){return typeof e=="function"?e(n):e}function _1({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 Tp({onClose:n}){return p("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:p(_1,{})})}function kp({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Rt(null),a=Rt(null);Je(()=>{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 Je(()=>{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(Tp,{onClose:c}),p("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Pc({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 E1({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 R1({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})})}const Sp=8,Qs=8,P1=100,I1=.7,Ti=3;function Cp({getBands:n,color:e="white"}){const t=Rt(null);return Je(()=>{if(!n)return;let i=0,r;const s=a=>{try{if(a-i>=P1){const o=n();if(t.current){const l=t.current.querySelectorAll(".bar"),c=o&&o.length>0?o.slice(0,Qs).map(u=>{const d=Math.abs(u);return Math.min(d/I1*Sp,Sp)||Ti}):Array(Qs).fill(Ti);for(;c.length<Qs;)c.push(Ti);c.forEach((u,d)=>{if(u<Ti&&(u=Ti),l[d]){const h=u*2;l[d].style.height=`${h}px`,l[d].style.display=u>0?"block":"none"}})}i=a}r=requestAnimationFrame(s)}catch(o){console.warn("Error updating equaliser:",o),r=requestAnimationFrame(s)}};return r=requestAnimationFrame(s),()=>{cancelAnimationFrame(r)}},[n]),p("div",{className:"obi-equaliser",ref:t,children:Array.from({length:Qs},(i,r)=>p("div",{className:"column",children:p("div",{className:"bar",style:{height:`${Ti}px`,backgroundColor:e,display:"block"}})},r))})}function O1(n){const{spectrum:e}=n;return p(Pc,{isActive:!0,children:p(Cp,{getBands:e})})}function Ic(n){const{children:e,className:t="",...i}=n;return p("div",{className:`${t} obi-panel`,...i,children:e})}function zn({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:A1(n)})}function A1(n){switch(n){case"pause":return p($e,{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($e,{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($e,{children:[p("path",{d:"M18 6 6 18"}),p("path",{d:"m6 6 12 12"})]});case"message":return p($e,{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($e,{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($e,{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($e,{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 Oc=T1(null);function N1({children:n}){const e=vp(Oc);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=Rt(null),d=wp(a,s),[h,f]=ee(!1);Je(()=>{t!==void 0&&t!==h&&(t?m():v()),f(t)},[t]),Je(()=>()=>{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 C(){o==="hover"&&m()}function x(){o==="hover"&&v()}return p("div",{ref:d,class:"target",onClick:b,onMouseEnter:C,onMouseLeave:x,children:n})}function L1({children:n}){const e=vp(Oc);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=wp(a,r);return _c(()=>{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 lt({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,l]=ee(!1),[c,u]=ee(!1),d=Rt(null),h=Rt(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(Oc.Provider,{value:f,children:p("div",{class:`obi-popout ${a}`,children:i})})}lt.Target=N1,lt.Content=L1;function wp(n,e){const t=Rt(null),i=Rt(null),r=Rt(!0),s=C1(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 Je(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),s}function Pt({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:p(zn,{type:"close",size:16}),pause:p(zn,{type:"pause",size:16}),play:p(zn,{type:"play",size:16}),message:p(zn,{type:"message",size:16}),minimize:p(zn,{type:"minimize",size:16}),voice:p(zn,{type:"voice",size:16}),open:p(zn,{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(lt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[p(lt.Target,{children:o}),p(lt.Content,{children:p("div",{className:"obi-round-button-title",children:r})})]}):o}function Rn({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 M1=8;function D1({color:n="white"}){return p("div",{className:"obi-loading-dots",children:Array.from({length:M1},(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 U1({onContinue:n,onWrapUp:e}){return p(Ic,{className:"obi-exit-survey",children:p(F1,{onContinue:n,onWrapUp:()=>{e()}})})}function B1({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=ee("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return p(Ic,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?p(j1,{onReasonSelect:s}):p(V1,{onReasonSelect:s,onClose:t})})}function F1({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 j1({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 V1({onReasonSelect:n,onClose:e}){const[t,i]=ee("");return p("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[p("div",{className:"obi-exit-survey-header",children:[p(Tp,{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 G1(n,e){for(var t in e)n[t]=e[t];return n}function xp(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 _p(n,e){this.props=n,this.context=e}(_p.prototype=new Qt).isPureReactComponent=!0,_p.prototype.shouldComponentUpdate=function(n,e){return xp(this.props,n)||xp(this.state,e)};var Ep=X.__b;X.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Ep&&Ep(n)};var z1=X.__e;X.__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)}z1(n,e,t,i)};var Rp=X.unmount;function Pp(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=G1({},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 Pp(i,e,t)})),n}function Ip(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Ip(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 Ac(){this.__u=0,this.o=null,this.__b=null}function Op(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Zs(){this.i=null,this.l=null}X.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Rp&&Rp(n)},(Ac.prototype=new Qt).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=Op(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]=Ip(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)},Ac.prototype.componentWillUnmount=function(){this.o=[]},Ac.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]=Pp(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&kc($e,null,n.fallback);return r&&(r.__u&=-33),[kc($e,null,e.__a?null:n.children),r]};var Ap=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]}};(Zs.prototype=new Qt).__a=function(n){var e=this,t=Op(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Ap(e,n,i)):r()};t?t(s):s()}},Zs.prototype.render=function(n){this.i=null,this.l=new Map;var e=$s(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},Zs.prototype.componentDidUpdate=Zs.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Ap(n,t,e)})};var H1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,W1=/^(?: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]/,q1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,K1=/[A-Z0-9]/g,$1=typeof document<"u",Y1=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};Qt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(Qt.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var Np=X.event;function X1(){}function J1(){return this.cancelBubble}function Q1(){return this.defaultPrevented}X.event=function(n){return Np&&(n=Np(n)),n.persist=X1,n.isPropagationStopped=J1,n.isDefaultPrevented=Q1,n.nativeEvent=n};var Z1={enumerable:!1,configurable:!0,get:function(){return this.class}},Lp=X.vnode;X.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||$1&&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"||Y1(t.type)?l==="onfocus"?a="onfocusin":l==="onblur"?a="onfocusout":q1.test(a)&&(a=l):l=a="oninput":s&&W1.test(a)?a=a.replace(K1,"-$&").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=$s(t.children).forEach(function(c){c.props.selected=r.value.indexOf(c.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=$s(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",Z1)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=H1,Lp&&Lp(n)};var Mp=X.__r;X.__r=function(n){Mp&&Mp(n),n.__c};var Dp=X.diffed;X.diffed=function(n){Dp&&Dp(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 ew(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]=ee(t||i||""),[g,m]=ee((t||i||"").length>24),v=Rt(null);_c(()=>{g&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,C=S=>{const w=S.currentTarget.value;t===void 0&&f(w),r==null||r(w)},x=S=>{S.key==="Escape"&&(f(t||i||""),m(!1),a==null||a()),S.key==="Enter"&&!S.shiftKey&&b.trim()&&(S.preventDefault(),f(t||i||""),m(!1),T()),(b||"").length>=24&&!g&&(m(!0),o==null||o(!0))};Je(()=>{v.current&&v.current.focus()},[v.current]);const T=()=>{!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:C,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:T,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 tw(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r,onStepClick:s}=n,[a,o]=ee(null),l=Array.from({length:t},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),c=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(a!==null){const d=i[a]&&i[a].trim().length>0?i[a]:`Step ${a+1}`;return`${a+1}/${t} \u2022 ${d}`}return`${e}/${t} \u2022 ${c}`})();return p("div",{class:`obi-course-progress ${r||""}`,children:[p("div",{class:"obi-course-progress-steps",children:l.map((d,h)=>{const f=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,g=d.isCompleted?"completed":"future";function m(){s&&s(h,f)}function v(b){s&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),m())}return p("div",{class:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>o(h),onMouseLeave:()=>o(null),onClick:s?m:void 0,onKeyDown:s?v:void 0,role:s?"button":void 0,tabIndex:s?0:void 0,children:p("div",{class:`obi-course-progress-step ${g}`,"aria-label":f})},h)})}),p("div",{class:"obi-course-progress-description",children:u})]})}function Up({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 nw(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=ee(null),[a,o]=ee(n.isActive??n.defaultIsActive??!1),[l,c]=ee(!1),[u,d]=ee(n.cancelling??!1),[h,f]=ee(n.messaging??!1),[g,m]=ee(!1),[v,b]=ee(h),[C,x]=ee(!1);function T(){o(!0),c(!1),x(!0)}function S(){}function w(){r&&(clearTimeout(r),s(null))}function E(){s(setTimeout(()=>{o(n.defaultIsActive??!1),x(!1)},400))}function P(ie){var Fe;m(!1),(Fe=n.onMessage)==null||Fe.call(n,ie)}function O(){var ie;f(!1),m(!1),o(!1),c(!0),(ie=n.onMinimize)==null||ie.call(n)}function B(){var ie;f(!1),d(!0),m(!1),(ie=n.onCancelClick)==null||ie.call(n)}function N(){var ie;t||((ie=n.onOpen)==null||ie.call(n))}function H(ie){var Fe,tt,en,xi,tn,qn;switch(ie){case"need-help":(Fe=n.onMessage)==null||Fe.call(n,"I'm struggling, can you look at my screen and help me out."),(tt=n.onOneClickAction)==null||tt.call(n,"need-help");break;case"continue":(en=n.onMessage)==null||en.call(n,"Okay, let's continue."),(xi=n.onOneClickAction)==null||xi.call(n,"continue");break;case"say-again":(tn=n.onMessage)==null||tn.call(n,"Please say that again."),(qn=n.onOneClickAction)==null||qn.call(n,"say-again");break}}function W(ie){var Fe,tt;n.messaging===void 0?((Fe=n.onMessagingChange)==null||Fe.call(n,ie),f(ie)):((tt=n.onMessagingChange)==null||tt.call(n,!n.messaging),f(!n.messaging)),ie||m(!1)}const J=n.isActive??((a||t)&&!l&&!e),Y=J&&t,q=J&&t&&!g,fe=n.speakingStatus==="user-speaking",ve=n.speakingStatus==="thinking",be=n.speakingStatus==="busy",V=J&&!t&&!u&&C,z=J&&t&&i&&!fe&&!u,Q=J&&t&&!z&&!fe&&h!==v&&!u,K=J&&t&&i&&fe&&!u,Se=J&&t&&!i&&fe&&!u,$=J&&t&&!i&&be&&!u,pe=n.messaging!==void 0?n.messaging:h,De=pe&&fe,Ot=V||z||K||Se||Q||u,At=400,la=!!n.courseProgress,ua=V?5:10;return _c(()=>{b(h)},[fe]),!t&&!u?p(iw,{...n}):!t&&u?p(rw,{onOtherSelect:()=>{var ie;(ie=n.onCancelReasonOther)==null||ie.call(n)},onCancelReason:ie=>{var Fe;o(n.defaultIsActive??!1),d(!1),(Fe=n.onCancelReason)==null||Fe.call(n,ie)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):p(Ic,{className:`obi-widget-panel ${Y?"expanded":""} ${g?"maximized":""} ${pe?"messaging":""} ${be?"tool-usage":""}`,children:[p("div",{className:`obi-widget ${J?"active":""} ${t?"in-plan":""}`,onMouseEnter:w,onMouseLeave:E,children:[q&&p(Pt,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),q&&!i&&p(Pt,{type:"pause",onClick:n.onPause,title:"Pause session"}),q&&i&&p(Pt,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(lt,{className:"obi-widget-popout",open:Ot,trigger:null,delayMs:At,offset:ua,children:[p(lt.Target,{children:[De&&p(ew,{value:n.message,onCancel:()=>W(!1),onSend:P,onExpand:m,onChange:n.onMessageChange,children:p("div",{className:"obi-widget-buttons",children:[p(Pt,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),!i&&p(Pt,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&p(Pt,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(Pt,{type:pe?"voice":"message",onClick:()=>W(!pe),title:pe?"Voice input":"Text input"}),p(Pt,{type:"minimize",onClick:O,title:"Minimize widget"})]})}),!De&&p(Pc,{className:J&&!t?"button":"",isActive:J,speakingStatus:n.speakingStatus,onClick:N,onMouseEnter:T,onMouseLeave:S,children:[J&&!t&&!$&&p("span",{className:"obi-widget-pill-text",children:"Tutorials"}),J&&t&&$&&p("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),J&&t&&!ve&&!$&&p(Cp,{getBands:n.spectrum}),J&&ve&&!$&&p(D1,{})]})]}),p(lt.Content,{children:p("div",{onMouseLeave:E,children:[V&&p(Rn,{onClick:N,children:"Click to see all"}),z&&p(Rn,{children:"Session will pause shortly"}),Q&&p(Rn,{children:["Switched to ",pe?"chat":"voice"]}),K&&p(Rn,{children:"Paused"}),Se&&p("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[p(Rn,{onClick:()=>H("need-help"),children:"Need help"}),p(Rn,{onClick:()=>H("continue"),children:"Continue"}),p(Rn,{onClick:()=>H("say-again"),children:"Say again"})]}),u&&p(U1,{onContinue:()=>{var ie;(ie=n.onCancelAbort)==null||ie.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var ie;(ie=n.onCancel)==null||ie.call(n)}})]})})]}),q&&p(Pt,{type:pe?"voice":"message",onClick:()=>W(!pe),title:pe?"Voice input":"Text input"}),q&&p(Pt,{type:"minimize",onClick:O,title:"Minimize widget"})]}),la&&n.courseProgress&&p("div",{className:`obi-widget-course-progress ${pe?"expanded":""}`,children:p(tw,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames,onStepClick:(ie,Fe)=>{var en;const tt=`Can we please jump to the steps related to: ${Fe}`;(en=n.onMessage)==null||en.call(n,tt)}})})]})}function iw(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=ee(null),[o,l]=ee(n.isActive??n.defaultIsActive??!1),[c,u]=ee(!1),[d,h]=ee(n.hovered??!1);function f(){var P;l(!0),u(!1),h(!0),(P=n.onHover)==null||P.call(n,!0)}function g(){}function m(){s&&(clearTimeout(s),a(null))}function v(){o&&a(setTimeout(()=>{var P;l(n.defaultIsActive??!1),h(!1),(P=n.onHover)==null||P.call(n,!1)},400))}function b(){l(!1),u(!0)}function C(){var P;(P=n.onOpen)==null||P.call(n)}const x=n.hovered??(d&&!c),T=n.isActive??(o&&!e&&!c),S=T&&x,w=`round-button ${T?"active":""}`;let E=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(E=`${t}/${i} completed`),p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:`obi-widget-out-of-plan ${x?"hover":""} ${T?"active":""}`,onMouseEnter:m,onMouseLeave:v,children:[p("div",{className:w,style:{width:"30px",height:"30px"}}),p(lt,{className:"obi-widget-popout",open:S,trigger:null,delayMs:400,offset:5,children:[p(lt.Target,{children:p(R1,{className:T?"button":"",active:T,onClick:C,onMouseEnter:f,onMouseLeave:g,children:p("span",{className:"text",children:[p(Up,{size:16}),E]})})}),p(lt.Content,{children:p("div",{onMouseLeave:v,children:p(Rn,{className:"message",onClick:C,children:"Click to see all"})})})]}),p(Pt,{className:w,type:"minimize",onClick:b,title:"Minimize widget"})]})})}function rw(n){return p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:"obi-widget-out-of-plan",children:p(lt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[p(lt.Target,{children:p(E1,{active:!1})}),p(lt.Content,{children:p(B1,{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 sw({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return p(kp,{open:n,onClose:t,preventOutsideClick:i,size:"medium",children:p("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function ki({title:n="",agentName:e="Obi",buttonText:t="Continue",speakingState:i=null,actionDisabled:r=!1,footer:s,href:a=null,glow:o=!1,centerVisual:l,description:c,button:u,onAction:d}){const[h,f]=ee(r),[g,m]=ee(!1),[v,b]=ee(i);return Je(()=>{g||(i==="listening"&&v!=="listening"&&h&&f(!1),i!=="listening"&&!h&&f(!0)),b(i)},[i,h]),Je(()=>{f(r)},[r]),p("div",{className:"tour-content",children:p("div",{className:"container",children:[p("div",{className:`visual ${o?"glow":""}`,children:l}),p("div",{className:"header",children:[p("h1",{className:"title",children:n}),p("div",{className:"description",children:c})]}),p("div",{className:"button-container",children:u||p(a?"a":"button",{className:`action-button ${h?"disabled":""}`,onClick:()=>{h||(f(!0),m(!0),d==null||d())},disabled:h,...a?{href:a,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:p("span",{className:"button-text",children:(()=>{switch(i){case"thinking":return"Loading...";case"speaking":return`${e} is speaking`;default:return t}})()})})}),s&&p("div",{className:"footer",children:s})]})})}function aw({logoUrl:n="",appName:e="App"}){const[t,i]=ee(!1),[r,s]=ee(!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 ow({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(ki,{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(aw,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}const{entries:Bp,setPrototypeOf:Fp,isFrozen:cw,getPrototypeOf:lw,getOwnPropertyDescriptor:uw}=Object;let{freeze:Qe,seal:gt,create:jp}=Object,{apply:Nc,construct:Lc}=typeof Reflect<"u"&&Reflect;Qe||(Qe=function(n){return n}),gt||(gt=function(n){return n}),Nc||(Nc=function(n,e,t){return n.apply(e,t)}),Lc||(Lc=function(n,e){return new n(...e)});const ea=et(Array.prototype.forEach),dw=et(Array.prototype.lastIndexOf),Vp=et(Array.prototype.pop),sr=et(Array.prototype.push),hw=et(Array.prototype.splice),ta=et(String.prototype.toLowerCase),Mc=et(String.prototype.toString),Gp=et(String.prototype.match),ar=et(String.prototype.replace),fw=et(String.prototype.indexOf),pw=et(String.prototype.trim),It=et(Object.prototype.hasOwnProperty),Ze=et(RegExp.prototype.test),or=mw(TypeError);function et(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Nc(n,e,i)}}function mw(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Lc(n,t)}}function Z(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ta;Fp&&Fp(n,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const s=t(r);s!==r&&(cw(e)||(e[i]=s),r=s)}n[r]=!0}return n}function gw(n){for(let e=0;e<n.length;e++)It(n,e)||(n[e]=null);return n}function Zt(n){const e=jp(null);for(const[t,i]of Bp(n))It(n,t)&&(Array.isArray(i)?e[t]=gw(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=Zt(i):e[t]=i);return e}function cr(n,e){for(;n!==null;){const i=uw(n,e);if(i){if(i.get)return et(i.get);if(typeof i.value=="function")return et(i.value)}n=lw(n)}function t(){return null}return t}const zp=Qe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Dc=Qe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Uc=Qe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),vw=Qe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Bc=Qe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),bw=Qe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hp=Qe(["#text"]),Wp=Qe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Fc=Qe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),qp=Qe(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),na=Qe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),yw=gt(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Tw=gt(/<%[\w\W]*|[\w\W]*%>/gm),kw=gt(/\$\{[\w\W]*/gm),Sw=gt(/^data-[\-\w.\u00B7-\uFFFF]+$/),Cw=gt(/^aria-[\-\w]+$/),Kp=gt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ww=gt(/^(?:\w+script|data):/i),xw=gt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),$p=gt(/^html$/i),_w=gt(/^[a-z][.\w]*(-[.\w]+)+$/i);var Yp=Object.freeze({__proto__:null,ARIA_ATTR:Cw,ATTR_WHITESPACE:xw,CUSTOM_ELEMENT:_w,DATA_ATTR:Sw,DOCTYPE_NAME:$p,ERB_EXPR:Tw,IS_ALLOWED_URI:Kp,IS_SCRIPT_OR_DATA:ww,MUSTACHE_EXPR:yw,TMPLIT_EXPR:kw});const lr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ew=function(){return typeof window>"u"?null:window},Rw=function(n,e){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let t=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(t=e.getAttribute(i));const r="dompurify"+(t?"#"+t:"");try{return n.createPolicy(r,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Xp=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Jp(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ew();const e=k=>Jp(k);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==lr.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n;const i=t,r=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:o,Element:l,NodeFilter:c,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=n,g=l.prototype,m=cr(g,"cloneNode"),v=cr(g,"remove"),b=cr(g,"nextSibling"),C=cr(g,"childNodes"),x=cr(g,"parentNode");if(typeof a=="function"){const k=t.createElement("template");k.content&&k.content.ownerDocument&&(t=k.content.ownerDocument)}let T,S="";const{implementation:w,createNodeIterator:E,createDocumentFragment:P,getElementsByTagName:O}=t,{importNode:B}=i;let N=Xp();e.isSupported=typeof Bp=="function"&&typeof x=="function"&&w&&w.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:H,ERB_EXPR:W,TMPLIT_EXPR:J,DATA_ATTR:Y,ARIA_ATTR:q,IS_SCRIPT_OR_DATA:fe,ATTR_WHITESPACE:ve,CUSTOM_ELEMENT:be}=Yp;let{IS_ALLOWED_URI:V}=Yp,z=null;const Q=Z({},[...zp,...Dc,...Uc,...Bc,...Hp]);let K=null;const Se=Z({},[...Wp,...Fc,...qp,...na]);let $=Object.seal(jp(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),pe=null,De=null,Ot=!0,At=!0,la=!1,ua=!0,ie=!1,Fe=!0,tt=!1,en=!1,xi=!1,tn=!1,qn=!1,da=!1,wm=!0,xm=!1;const o_="user-content-";let $c=!0,hr=!1,_i={},Ei=null;const _m=Z({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Em=null;const Rm=Z({},["audio","video","img","source","image","track"]);let Yc=null;const Pm=Z({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ha="http://www.w3.org/1998/Math/MathML",fa="http://www.w3.org/2000/svg",nn="http://www.w3.org/1999/xhtml";let Ri=nn,Xc=!1,Jc=null;const c_=Z({},[ha,fa,nn],Mc);let pa=Z({},["mi","mo","mn","ms","mtext"]),ma=Z({},["annotation-xml"]);const l_=Z({},["title","style","font","a","script"]);let fr=null;const u_=["application/xhtml+xml","text/html"],d_="text/html";let je=null,Pi=null;const h_=t.createElement("form"),Im=function(k){return k instanceof RegExp||k instanceof Function},Qc=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Pi&&Pi===k)){if((!k||typeof k!="object")&&(k={}),k=Zt(k),fr=u_.indexOf(k.PARSER_MEDIA_TYPE)===-1?d_:k.PARSER_MEDIA_TYPE,je=fr==="application/xhtml+xml"?Mc:ta,z=It(k,"ALLOWED_TAGS")?Z({},k.ALLOWED_TAGS,je):Q,K=It(k,"ALLOWED_ATTR")?Z({},k.ALLOWED_ATTR,je):Se,Jc=It(k,"ALLOWED_NAMESPACES")?Z({},k.ALLOWED_NAMESPACES,Mc):c_,Yc=It(k,"ADD_URI_SAFE_ATTR")?Z(Zt(Pm),k.ADD_URI_SAFE_ATTR,je):Pm,Em=It(k,"ADD_DATA_URI_TAGS")?Z(Zt(Rm),k.ADD_DATA_URI_TAGS,je):Rm,Ei=It(k,"FORBID_CONTENTS")?Z({},k.FORBID_CONTENTS,je):_m,pe=It(k,"FORBID_TAGS")?Z({},k.FORBID_TAGS,je):Zt({}),De=It(k,"FORBID_ATTR")?Z({},k.FORBID_ATTR,je):Zt({}),_i=It(k,"USE_PROFILES")?k.USE_PROFILES:!1,Ot=k.ALLOW_ARIA_ATTR!==!1,At=k.ALLOW_DATA_ATTR!==!1,la=k.ALLOW_UNKNOWN_PROTOCOLS||!1,ua=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ie=k.SAFE_FOR_TEMPLATES||!1,Fe=k.SAFE_FOR_XML!==!1,tt=k.WHOLE_DOCUMENT||!1,tn=k.RETURN_DOM||!1,qn=k.RETURN_DOM_FRAGMENT||!1,da=k.RETURN_TRUSTED_TYPE||!1,xi=k.FORCE_BODY||!1,wm=k.SANITIZE_DOM!==!1,xm=k.SANITIZE_NAMED_PROPS||!1,$c=k.KEEP_CONTENT!==!1,hr=k.IN_PLACE||!1,V=k.ALLOWED_URI_REGEXP||Kp,Ri=k.NAMESPACE||nn,pa=k.MATHML_TEXT_INTEGRATION_POINTS||pa,ma=k.HTML_INTEGRATION_POINTS||ma,$=k.CUSTOM_ELEMENT_HANDLING||{},k.CUSTOM_ELEMENT_HANDLING&&Im(k.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&($.tagNameCheck=k.CUSTOM_ELEMENT_HANDLING.tagNameCheck),k.CUSTOM_ELEMENT_HANDLING&&Im(k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&($.attributeNameCheck=k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),k.CUSTOM_ELEMENT_HANDLING&&typeof k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&($.allowCustomizedBuiltInElements=k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ie&&(At=!1),qn&&(tn=!0),_i&&(z=Z({},Hp),K=[],_i.html===!0&&(Z(z,zp),Z(K,Wp)),_i.svg===!0&&(Z(z,Dc),Z(K,Fc),Z(K,na)),_i.svgFilters===!0&&(Z(z,Uc),Z(K,Fc),Z(K,na)),_i.mathMl===!0&&(Z(z,Bc),Z(K,qp),Z(K,na))),k.ADD_TAGS&&(z===Q&&(z=Zt(z)),Z(z,k.ADD_TAGS,je)),k.ADD_ATTR&&(K===Se&&(K=Zt(K)),Z(K,k.ADD_ATTR,je)),k.ADD_URI_SAFE_ATTR&&Z(Yc,k.ADD_URI_SAFE_ATTR,je),k.FORBID_CONTENTS&&(Ei===_m&&(Ei=Zt(Ei)),Z(Ei,k.FORBID_CONTENTS,je)),$c&&(z["#text"]=!0),tt&&Z(z,["html","head","body"]),z.table&&(Z(z,["tbody"]),delete pe.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw or('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw or('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=k.TRUSTED_TYPES_POLICY,S=T.createHTML("")}else T===void 0&&(T=Rw(f,r)),T!==null&&typeof S=="string"&&(S=T.createHTML(""));Qe&&Qe(k),Pi=k}},Om=Z({},[...Dc,...Uc,...vw]),Am=Z({},[...Bc,...bw]),f_=function(k){let G=x(k);(!G||!G.tagName)&&(G={namespaceURI:Ri,tagName:"template"});const D=ta(k.tagName),ue=ta(G.tagName);return Jc[k.namespaceURI]?k.namespaceURI===fa?G.namespaceURI===nn?D==="svg":G.namespaceURI===ha?D==="svg"&&(ue==="annotation-xml"||pa[ue]):!!Om[D]:k.namespaceURI===ha?G.namespaceURI===nn?D==="math":G.namespaceURI===fa?D==="math"&&ma[ue]:!!Am[D]:k.namespaceURI===nn?G.namespaceURI===fa&&!ma[ue]||G.namespaceURI===ha&&!pa[ue]?!1:!Am[D]&&(l_[D]||!Om[D]):!!(fr==="application/xhtml+xml"&&Jc[k.namespaceURI]):!1},Kn=function(k){sr(e.removed,{element:k});try{x(k).removeChild(k)}catch{v(k)}},Ii=function(k,G){try{sr(e.removed,{attribute:G.getAttributeNode(k),from:G})}catch{sr(e.removed,{attribute:null,from:G})}if(G.removeAttribute(k),k==="is")if(tn||qn)try{Kn(G)}catch{}else try{G.setAttribute(k,"")}catch{}},Nm=function(k){let G=null,D=null;if(xi)k="<remove></remove>"+k;else{const Ee=Gp(k,/^[\r\n\t ]+/);D=Ee&&Ee[0]}fr==="application/xhtml+xml"&&Ri===nn&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const ue=T?T.createHTML(k):k;if(Ri===nn)try{G=new h().parseFromString(ue,fr)}catch{}if(!G||!G.documentElement){G=w.createDocument(Ri,"template",null);try{G.documentElement.innerHTML=Xc?S:ue}catch{}}const We=G.body||G.documentElement;return k&&D&&We.insertBefore(t.createTextNode(D),We.childNodes[0]||null),Ri===nn?O.call(G,tt?"html":"body")[0]:tt?G.documentElement:We},Lm=function(k){return E.call(k.ownerDocument||k,k,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Zc=function(k){return k instanceof d&&(typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||!(k.attributes instanceof u)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function")},Mm=function(k){return typeof o=="function"&&k instanceof o};function rn(k,G,D){ea(k,ue=>{ue.call(e,G,D,Pi)})}const Dm=function(k){let G=null;if(rn(N.beforeSanitizeElements,k,null),Zc(k))return Kn(k),!0;const D=je(k.nodeName);if(rn(N.uponSanitizeElement,k,{tagName:D,allowedTags:z}),Fe&&k.hasChildNodes()&&!Mm(k.firstElementChild)&&Ze(/<[/\w!]/g,k.innerHTML)&&Ze(/<[/\w!]/g,k.textContent)||k.nodeType===lr.progressingInstruction||Fe&&k.nodeType===lr.comment&&Ze(/<[/\w]/g,k.data))return Kn(k),!0;if(!z[D]||pe[D]){if(!pe[D]&&Bm(D)&&($.tagNameCheck instanceof RegExp&&Ze($.tagNameCheck,D)||$.tagNameCheck instanceof Function&&$.tagNameCheck(D)))return!1;if($c&&!Ei[D]){const ue=x(k)||k.parentNode,We=C(k)||k.childNodes;if(We&&ue){const Ee=We.length;for(let sn=Ee-1;sn>=0;--sn){const Nt=m(We[sn],!0);Nt.__removalCount=(k.__removalCount||0)+1,ue.insertBefore(Nt,b(k))}}}return Kn(k),!0}return k instanceof l&&!f_(k)||(D==="noscript"||D==="noembed"||D==="noframes")&&Ze(/<\/no(script|embed|frames)/i,k.innerHTML)?(Kn(k),!0):(ie&&k.nodeType===lr.text&&(G=k.textContent,ea([H,W,J],ue=>{G=ar(G,ue," ")}),k.textContent!==G&&(sr(e.removed,{element:k.cloneNode()}),k.textContent=G)),rn(N.afterSanitizeElements,k,null),!1)},Um=function(k,G,D){if(wm&&(G==="id"||G==="name")&&(D in t||D in h_))return!1;if(!(At&&!De[G]&&Ze(Y,G))&&!(Ot&&Ze(q,G))){if(!K[G]||De[G]){if(!(Bm(k)&&($.tagNameCheck instanceof RegExp&&Ze($.tagNameCheck,k)||$.tagNameCheck instanceof Function&&$.tagNameCheck(k))&&($.attributeNameCheck instanceof RegExp&&Ze($.attributeNameCheck,G)||$.attributeNameCheck instanceof Function&&$.attributeNameCheck(G))||G==="is"&&$.allowCustomizedBuiltInElements&&($.tagNameCheck instanceof RegExp&&Ze($.tagNameCheck,D)||$.tagNameCheck instanceof Function&&$.tagNameCheck(D))))return!1}else if(!Yc[G]&&!Ze(V,ar(D,ve,""))&&!((G==="src"||G==="xlink:href"||G==="href")&&k!=="script"&&fw(D,"data:")===0&&Em[k])&&!(la&&!Ze(fe,ar(D,ve,"")))&&D)return!1}return!0},Bm=function(k){return k!=="annotation-xml"&&Gp(k,be)},Fm=function(k){rn(N.beforeSanitizeAttributes,k,null);const{attributes:G}=k;if(!G||Zc(k))return;const D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0};let ue=G.length;for(;ue--;){const We=G[ue],{name:Ee,namespaceURI:sn,value:Nt}=We,zt=je(Ee),el=Nt;let Ye=Ee==="value"?el:pw(el);if(D.attrName=zt,D.attrValue=Ye,D.keepAttr=!0,D.forceKeepAttr=void 0,rn(N.uponSanitizeAttribute,k,D),Ye=D.attrValue,xm&&(zt==="id"||zt==="name")&&(Ii(Ee,k),Ye=o_+Ye),Fe&&Ze(/((--!?|])>)|<\/(style|title)/i,Ye)){Ii(Ee,k);continue}if(D.forceKeepAttr)continue;if(!D.keepAttr){Ii(Ee,k);continue}if(!ua&&Ze(/\/>/i,Ye)){Ii(Ee,k);continue}ie&&ea([H,W,J],m_=>{Ye=ar(Ye,m_," ")});const jm=je(k.nodeName);if(!Um(jm,zt,Ye)){Ii(Ee,k);continue}if(T&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!sn)switch(f.getAttributeType(jm,zt)){case"TrustedHTML":{Ye=T.createHTML(Ye);break}case"TrustedScriptURL":{Ye=T.createScriptURL(Ye);break}}if(Ye!==el)try{sn?k.setAttributeNS(sn,Ee,Ye):k.setAttribute(Ee,Ye),Zc(k)?Kn(k):Vp(e.removed)}catch{Ii(Ee,k)}}rn(N.afterSanitizeAttributes,k,null)},p_=function k(G){let D=null;const ue=Lm(G);for(rn(N.beforeSanitizeShadowDOM,G,null);D=ue.nextNode();)rn(N.uponSanitizeShadowNode,D,null),Dm(D),Fm(D),D.content instanceof s&&k(D.content);rn(N.afterSanitizeShadowDOM,G,null)};return e.sanitize=function(k){let G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},D=null,ue=null,We=null,Ee=null;if(Xc=!k,Xc&&(k="<!-->"),typeof k!="string"&&!Mm(k))if(typeof k.toString=="function"){if(k=k.toString(),typeof k!="string")throw or("dirty is not a string, aborting")}else throw or("toString is not a function");if(!e.isSupported)return k;if(en||Qc(G),e.removed=[],typeof k=="string"&&(hr=!1),hr){if(k.nodeName){const zt=je(k.nodeName);if(!z[zt]||pe[zt])throw or("root node is forbidden and cannot be sanitized in-place")}}else if(k instanceof o)D=Nm("<!---->"),ue=D.ownerDocument.importNode(k,!0),ue.nodeType===lr.element&&ue.nodeName==="BODY"||ue.nodeName==="HTML"?D=ue:D.appendChild(ue);else{if(!tn&&!ie&&!tt&&k.indexOf("<")===-1)return T&&da?T.createHTML(k):k;if(D=Nm(k),!D)return tn?null:da?S:""}D&&xi&&Kn(D.firstChild);const sn=Lm(hr?k:D);for(;We=sn.nextNode();)Dm(We),Fm(We),We.content instanceof s&&p_(We.content);if(hr)return k;if(tn){if(qn)for(Ee=P.call(D.ownerDocument);D.firstChild;)Ee.appendChild(D.firstChild);else Ee=D;return(K.shadowroot||K.shadowrootmode)&&(Ee=B.call(i,Ee,!0)),Ee}let Nt=tt?D.outerHTML:D.innerHTML;return tt&&z["!doctype"]&&D.ownerDocument&&D.ownerDocument.doctype&&D.ownerDocument.doctype.name&&Ze($p,D.ownerDocument.doctype.name)&&(Nt="<!DOCTYPE "+D.ownerDocument.doctype.name+`>
43
- `+Nt),ie&&ea([H,W,J],zt=>{Nt=ar(Nt,zt," ")}),T&&da?T.createHTML(Nt):Nt},e.setConfig=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Qc(k),en=!0},e.clearConfig=function(){Pi=null,en=!1},e.isValidAttribute=function(k,G,D){Pi||Qc({});const ue=je(k),We=je(G);return Um(ue,We,D)},e.addHook=function(k,G){typeof G=="function"&&sr(N[k],G)},e.removeHook=function(k,G){if(G!==void 0){const D=dw(N[k],G);return D===-1?void 0:hw(N[k],D,1)[0]}return Vp(N[k])},e.removeHooks=function(k){N[k]=[]},e.removeAllHooks=function(){N=Xp()},e}var Pw=Jp();function Iw({}){return p("div",{className:"obi-static-voice",children:[p("div",{className:"obi-static-voice-visual-title",children:"AI Guided Tutorial"}),p("div",{style:{transform:"scale(1.25) translateY(-4px)"},children:p(Pc,{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 Ow({session:n,speakingState:e,onAction:t}){const i="Sessions are securely recorded for quality improvement purposes.",r=Xs(()=>{var l;const o=(l=n.legalFooter)==null?void 0:l.trim();return o?Pw.sanitize(o):null},[n.legalFooter]),s=Rt(null);Je(()=>{if(!r)return;const o=s.current;o&&o.querySelectorAll("a").forEach(l=>{l.setAttribute("target","_blank");const c=(l.getAttribute("rel")||"").split(/\s+/);c.includes("noopener")||c.push("noopener"),c.includes("noreferrer")||c.push("noreferrer"),l.setAttribute("rel",c.filter(Boolean).join(" "))})},[r]);const a=r?p("span",{ref:s,dangerouslySetInnerHTML:{__html:r}}):i;return p(ki,{title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,footer:a,buttonText:"Get started",agentName:n.agentName||"Obi",speakingState:e,centerVisual:p(Iw,{}),onAction:t})}function Aw(){const n={host:{display:"block",position:"relative",width:"100%",height:"161px"},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
+ `},nc}var bf;function fC(){if(bf)return xt;bf=1;var n=dC(),e=hC(),t=tc();return xt.grammar=t,xt.write=e,xt.parse=n.parse,xt.parseParams=n.parseParams,xt.parseFmtpConfig=n.parseFmtpConfig,xt.parsePayloads=n.parsePayloads,xt.parseRemoteCandidates=n.parseRemoteCandidates,xt.parseImageAttributes=n.parseImageAttributes,xt.parseSimulcastStreamList=n.parseSimulcastStreamList,xt}var xn=fC();function ic(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(T){return(0,T.resolve)(x)}),u=[]}},d()),b){var C=n.apply(g,f);return o&&o(C),m(C)}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 pC=.7,mC=20,gi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class yf extends Vt.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=ne,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ic(r=>y(this,void 0,void 0,function*(){this.emit(gi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),mC),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=Kt((i=t.loggerName)!==null&&i!==void 0?i:Ct.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}=gC(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=xn.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=xn.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(gi.NegotiationComplete),e.sdp&&xn.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(gi.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=xn.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{kf(s),s.type==="audio"?Tf(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||(Ji(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*pC);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,xn.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=xn.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{kf(r),r.type==="audio"&&Tf(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,xn.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 Me("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 Me("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 Oo(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Qh))){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:Qh})}}}function Tf(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 gC(n){var e;const t=[],i=[],r=xn.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 kf(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 rc="vp8",vC={audioPreset:Mo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Uo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:rc,backupCodec:!0},Sf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Cf={deviceId:{ideal:"default"},resolution:Xi.h720.resolution},bC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new cS,disconnectOnPageLeave:!0,webAudioMix:!1},sc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var xe;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(xe||(xe={}));class yC{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=sc.peerConnectionTimeout,this.log=ne,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(l=>l.getConnectionState());o.every(l=>l==="connected")?this.state=xe.CONNECTED:o.some(l=>l==="failed")?this.state=xe.FAILED:o.some(l=>l==="connecting")?this.state=xe.CONNECTING:o.every(l=>l==="closed")?this.state=xe.CLOSED:o.some(l=>l==="closed")?this.state=xe.CLOSING:o.every(l=>l==="new")&&(this.state=xe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(xe[a]," to ").concat(xe[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Kt((r=i.loggerName)!==null&&r!==void 0?r:Ct.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new yf(e,i),this.subscriber=new yf(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,St.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,St.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=xe.NEW,this.connectionLock=new rt,this.remoteOfferLock=new rt}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===St.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(gi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(gi.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===St.PUBLISHER?this.publisher.getConnectedAddress():e===St.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),He.clearTimeout(d),c(new he("room connection has been cancelled",re.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=He.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(new he("could not establish pc connection",re.InternalError))},a);for(;this.state!==xe.CONNECTED;)if(yield ot(50),r!=null&&r.signal.aborted){c(new he("room connection has been cancelled",re.Cancelled));return}He.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}class _e extends Error{constructor(e,t,i){super(t),this.code=e,this.message=xf(t,_e.MAX_MESSAGE_BYTES),this.data=i?xf(i,_e.MAX_DATA_BYTES):void 0}static fromProto(e){return new _e(e.code,e.message,e.data)}toProto(){return new Fd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new _e(_e.ErrorCode[e],_e.ErrorMessage[e],t)}}_e.MAX_MESSAGE_BYTES=256,_e.MAX_DATA_BYTES=15360,_e.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},_e.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 wf=15360;function ac(n){return new TextEncoder().encode(n).length}function xf(n,e){if(ac(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 oc=2e3;function Ds(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 TC=1e3;class _f extends I{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=ic(()=>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(L.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new rt,this.pauseUpstreamLock=new rt,this.processorLock=new rt,this.restartLock=new rt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==I.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=>{hi(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&&(di(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=>{di(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]:TC;return function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=wt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield ot(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield ot(50)}throw new $t("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===Cn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Cn(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===I.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===I.Kind.Audio?"audioinput":"videoinput";return t?Be.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 $t("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=lS(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===I.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(c=>{hi(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(L.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?L.Muted:L.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),Zh()&&(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(L.UpstreamPaused,this);const i=wt();if((i==null?void 0:i.name)==="Safari"&&Bn(i.version,"12.0")<0)throw new Io("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(L.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(di(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&&(hi(i._mediaStreamTrack,c),di(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(L.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(L.TrackProcessorUpdate))}()})}}class Us extends _f{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,I.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=Ds(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,kt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,kt.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===I.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!==Cn(this._constraints.deviceId);return this.source===I.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=Xo({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(){ct()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},oc)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Gt()&&!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(L.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 lf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(L.AudioSilenceDetected)),e})}}function kC(n,e,t){switch(n.kind){case"audio":return new Us(n,e,!1,void 0,t);case"video":return new Fs(n,e,!1,t);default:throw new $t("unsupported track type: ".concat(n.kind))}}const SC=Object.values(Xi),CC=Object.values(Do),wC=Object.values(Uo),xC=[Xi.h180,Xi.h360],_C=[Do.h180,Do.h360],EC=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new de(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)}),cc=["q","h","f"];function lc(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=PC(n,e,t,c),ne.debug("using video encoding",a));const u=a.maxFramerate,d=new de(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(l&&Ji(c)){const g=new Bs(l),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const v=wt();if(Sn()||Gt()||(v==null?void 0:v.name)==="Chrome"&&Bn(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3;for(let C=0;C<g.spatial;C+=1)m.push({rid:cc[2-C],maxBitrate:a.maxBitrate/Math.pow(b,C),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),ne.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(r=Rf(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Ef(n,d):h=(s=Rf(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Ef(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 uc(e,t,[g,f,d],u);if(m>=480)return uc(e,t,[g,d],u)}return uc(e,t,[d])}function RC(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ne.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===I.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),lc(n.source===I.Source.ScreenShare,l,c,t)}function PC(n,e,t,i){const r=IC(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 IC(n,e,t){if(n)return wC;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?SC:CC}function Ef(n,e){if(n)return EC(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)?xC:_C}function uc(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=cc.length)return;const o=Math.min(n,e),c={rid:cc[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=fi()||a===0;s.encoding.priority&&d&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),Gt()&&tf()==="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,ne.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ne.info('Setting framerate of encoding "'.concat((l=o.rid)!==null&&l!==void 0?l:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Rf(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 Bs{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 OC(n){return n.source===I.Source.ScreenShare||n.constraints.height&&Cn(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const AC=5e3;class Fs extends _f{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,I.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+=Ds(l,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new rt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ct())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()},oc))}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=bn(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=bn(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===I.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===I.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=mt.LOW;i<=mt.HIGH;i+=1)t.push(new bo({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=Xo({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var l=!0,c=bn(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=bn(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)},AC))}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=bn(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 Pf(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 Pf(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),Zh()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Pf(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=wt();if((u==null?void 0:u.name)==="Chrome"&&Bn(u==null?void 0:u.version,"133")>0&&l[0].scalabilityMode){const h=l[0],f=new Bs(h.scalabilityMode);let g=si.OFF;if(t.forEach(m=>{m.enabled&&(g===si.OFF||m.quality>g)&&(g=m.quality)}),g===si.OFF)h.active&&(h.active=!1,c=!0);else if(!h.active||f.spatial!==g+1){c=!0,h.active=!0;const m=new Bs(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=If(m),b=t.find(C=>C.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),fi()&&(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 If(n){switch(n){case"f":return mt.HIGH;case"h":return mt.MEDIUM;case"q":return mt.LOW;default:return mt.HIGH}}function Of(n,e,t,i){if(!t)return[new Mn({quality:mt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new Bs(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 Mn({quality:Math.min(mt.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=If((a=r.rid)!==null&&a!==void 0?a:"");return new Mn({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 Af="_lossy",Nf="_reliable",NC=2*1e3,dc="leave-reconnect";var _t;(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"})(_t||(_t={}));class LC extends Vt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=sc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=_t.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=ne,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===Nf)s.reliableDCSub=a;else if(a.label===Af)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=at.fromBinary(new Uint8Array(o));((r=l.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(M.ActiveSpeakersUpdate,l.value.value.speakers):(((s=l.value)===null||s===void 0?void 0:s.case)==="user"&&DC(l,l.value.value),this.emit(M.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?se.LOSSY:se.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(M.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===dc&&(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=He.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===_t.Connected&&i();const s=()=>{this.off(M.Disconnected,a),i()},a=()=>{this.off(M.Restarted,s),r()};this.once(M.Restarted,s),this.once(M.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(M.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ge.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ai.RR_SIGNAL_DISCONNECTED))},this.log=Kt((t=e.loggerName)!==null&&t!==void 0?t:Ct.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Qo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new rt,this.dataProcessLock=new rt,this.dcBufferStatus=new Map([[se.LOSSY,!0],[se.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(M.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(M.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(M.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(M.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(M.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(M.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(M.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(M.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(M.SignalConnected)},10),s}catch(s){if(s instanceof he&&s.reason===re.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(M.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 $t("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 he("publication of local track timed out, no response from server",re.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!==xe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new yC(r,e.subscriberPrimary,this.loggerOptions),this.emit(M.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===xe.CONNECTED){const u=this.pcState===_t.New;this.pcState=_t.Connected,u&&this.emit(M.Connected,e)}else s===xe.FAILED&&this.pcState===_t.Connected&&(this.pcState=_t.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ai.RR_SUBSCRIBER_FAILED:ai.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===ge.RECONNECTING,c=[xe.FAILED,xe.CLOSING,xe.CLOSED].includes(s);l&&c&&!this._isClosed&&this.emit(M.Offline)}),this.pcManager.onTrack=s=>{this.emit(M.MediaTrackAdded,s.track,s.streams[0],s.receiver)},MC((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(M.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(M.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(M.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(M.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(M.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ai.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 li.DISCONNECT:this.emit(M.Disconnected,e==null?void 0:e.reason),this.close();break;case li.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(dc);break;case li.RESUME:this.handleDisconnect(dc)}}}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===Ki.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(Af,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Nf,{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(Bo())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Fo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Me("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(Bo())return this.createSimulcastTransceiverSender(e,t,i,r);if(Fo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Me("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Me("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),mi(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 Me("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 Me("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){ne.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ki.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:xe.NEW)===xe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Me?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof vi||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ai.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(M.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 Me("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(M.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 vi;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof he&&a.reason===re.NotAllowed?new Me("could not reconnect, token might be expired"):new vi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(M.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ge.CONNECTED)throw new vi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(M.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 Me("could not reconnect, url or token not saved");if(!this.pcManager)throw new Me("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(M.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 he&&r.reason===re.NotAllowed?new Me("could not reconnect, token might be expired"):r instanceof he&&r.reason===re.LeaveRequest?r:new vi(s)}if(this.emit(M.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!==ge.CONNECTED)throw new vi("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(M.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Me("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=_t.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ot(NC),!this.pcManager)throw new Me("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=_t.Connected}catch(e){throw this.pcState=_t.Disconnected,new he("could not establish PC connection, ".concat(e.message),re.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new at({destinationIdentities:[e],kind:se.RELIABLE,value:{case:"rpcResponse",value:new Bd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,se.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new at({destinationIdentities:[e],kind:se.RELIABLE,value:{case:"rpcAck",value:new Ud({requestId:t})}});yield this.sendDataPacket(i,se.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(M.Closing,r);!this.dcBufferStatus.get(e);)yield ot(10);this.off(M.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 Me("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new he("".concat(o," connection not set"),re.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 ot(50)}throw new he("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),re.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!==xe.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 Oo("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(M.Closing,r),this.pcManager.publisher.once(gi.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const l=o.codec.toLowerCase();HS(l)&&a.set(o.payload,l)}),this.emit(M.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Oo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ai.RR_UNKNOWN),t(s)}finally{this.off(M.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===se.LOSSY)return this.lossyDCSub;if(e===se.RELIABLE)return this.reliableDCSub}else{if(e===se.LOSSY)return this.lossyDC;if(e===se.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 nh({answer:s?Ms({sdp:s.sdp,type:s.type}):void 0,offer:a?Ms({sdp:a.sdp,type:a.type}):void 0,subscription:new ys({trackSids:l,subscribe:!o,participantTracks:[]}),publishTracks:ZS(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 ih({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(se.LOSSY),St.PUBLISHER),t(this.dataChannelForKind(se.RELIABLE),St.PUBLISHER),t(this.dataChannelForKind(se.LOSSY,!0),St.SUBSCRIBER),t(this.dataChannelForKind(se.RELIABLE,!0),St.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&He.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ct()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){ct()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class vi extends Error{}function MC(n){return n!==void 0&&n>13}function DC(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 hc{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 Vo(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),ne.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(UC(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 he("Could not fetch region settings: ".concat(t.statusText),t.status===401?re.NotAllowed:re.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function UC(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Lf{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class BC extends Lf{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=bn(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 FC extends Lf{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ns(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=bn(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 Mf{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 jC extends Mf{}class VC extends Mf{}class Df extends I{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?L.Muted:L.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(L.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(),oc)),eC()&&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(L.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class GC extends Df{constructor(e,t,i,r,s,a){super(e,t,I.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=Ds(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;Gt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Gt())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(jo(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&jo(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(L.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(L.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 fc=100;class zC extends Df{constructor(e,t,i,r,s){super(e,t,I.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=Ds(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=ic(()=>{this.updateDimensions()},fc),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?hi(this._mediaStreamTrack,t):di(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new HC(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<fc){He.setTimeout(()=>{this.updateVisibility()},fc);return}this.lastVisible=a,this.emit(L.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(L.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?nf():t||(nf()>2?2:1)}}class HC{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=er(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=er(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=er(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??pc(e),this.isPiP=ct()&&er(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=pc(this.element),this.isPiP=er(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,sf().observe(this.element),rf().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=sf())===null||e===void 0||e.unobserve(this.element),(t=rf())===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 er(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?pc(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function pc(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 Xt extends Vt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=ut.NONE,this.log=ne,this.handleMuted=()=>{this.emit(L.Muted)},this.handleUnmuted=()=>{this.emit(L.Unmuted)},this.log=Kt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Ct.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=I.Source.Unknown}setTrack(e){this.track&&(this.track.off(L.Muted,this.handleMuted),this.track.off(L.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(L.Muted,this.handleMuted),e.on(L.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ce(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==ut.NONE}get audioTrack(){if(Yt(this.track))return this.track}get videoTrack(){if(mi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=I.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===I.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={}))})(Xt||(Xt={}));class mc extends Xt{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(L.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(L.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(L.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(Yt(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(kt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(kt.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(kt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(kt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(kt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(kt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function js(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=hf(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=cf(s,Sf,Cf),c=Xo(l),u=navigator.mediaDevices.getUserMedia(c);s.audio&&(Be.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Be.userMediaPromiseMap.delete("audioinput"))),s.video&&(Be.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Be.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&&Cn(m.deviceId)!==b?m.deviceId=b:m||(m={deviceId:b});const C=kC(h,m,e);return C.kind===I.Kind.Video?C.source=I.Source.Camera:C.kind===I.Kind.Audio&&(C.source=I.Source.Microphone),C.mediaStream=d,Yt(C)&&i?yield C.setProcessor(i):mi(C)&&r&&(yield C.setProcessor(r)),C})))}catch(d){if(!t)throw d;return js(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function WC(n){return y(this,void 0,void 0,function*(){return(yield js({audio:!1,video:n??!0}))[0]})}function qC(n){return y(this,void 0,void 0,function*(){return(yield js({audio:n??!0,video:!1}))[0]})}var _n;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(_n||(_n={}));function KC(n){switch(n){case qi.EXCELLENT:return _n.Excellent;case qi.GOOD:return _n.Good;case qi.POOR:return _n.Poor;case qi.LOST:return _n.Lost;default:return _n.Unknown}}class Uf extends Vt.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===bs.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===oi.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]:bs.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=_n.Unknown,this.log=ne,this.log=Kt((l=a==null?void 0:a.loggerName)!==null&&l!==void 0?l:Ct.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 Wo,this.once(U.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(I.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(I.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(I.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===oi.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==oi.ACTIVE&&this.emit(U.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(U.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(U.ParticipantNameChanged,e)}_setAttributes(e){const t=tC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(U.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(U.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(U.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=KC(e),t!==this._connectionQuality&&this.emit(U.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=>Yt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(L.Muted,()=>{this.emit(U.TrackMuted,e)}),e.on(L.Unmuted,()=>{this.emit(U.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case I.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case I.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function $C(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 eh({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 Bf=15e3;class YC extends Uf{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=ut.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Wo)},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!==yo.OK&&u.reject(new Yh(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=_e.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=>$C(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),ce(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ce(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ce(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=bn(b),v;v=yield m.next(),o=v.done,!o;g=!0){u=v.value,g=!1;const C=u;NS(C)&&(this.log.debug("publish ".concat(C," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ce(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,C,f.options))}}catch(C){l={error:C}}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===I.Source.ScreenShare||a.source===I.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ce(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(jn(a)||wn(a))try{if(ct())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===I.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),ce(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),ce(a))),jn(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),ce(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!==ut.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(M.RemoteMute,(t,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(M.Connected,this.handleReconnected).on(M.SignalRestarted,this.handleReconnected).on(M.SignalResumed,this.handleReconnected).on(M.Restarting,this.handleReconnecting).on(M.Resuming,this.handleReconnecting).on(M.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(M.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(M.Disconnected,this.handleDisconnected).on(M.SignalRequestResponse,this.handleSignalRequestResponse).on(M.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 ot(50)}l(new Yh("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(I.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(I.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(I.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(U.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?ut.GCM:ut.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 I.Source.Camera:l=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case I.Source.Microphone:l=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case I.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new $t(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(U.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),ce(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===I.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const l=this.getTrackPublication(I.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(I.Source.Camera)||this.pendingPublishing.has(I.Source.Microphone))){this.pendingPublishing.add(I.Source.Camera),this.pendingPublishing.add(I.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(I.Source.Camera),this.pendingPublishing.delete(I.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const r=cf(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 js(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Yt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=I.Source.Microphone,this.emit(U.AudioStreamAcquired)),mi(o)&&(this.cameraError=void 0,o.source=I.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 Io("getDisplayMedia not supported");e.resolution===void 0&&!FS()&&(e.resolution=Uo.h1080fps30.resolution);const t=QS(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new $t("no video track found");const s=new Fs(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=I.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(U.AudioStreamAcquired);const o=new Us(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=I.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;jn(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),pi(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 I.Source.Microphone:b="audioinput";break;case I.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 Us(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Fs(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new $t("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),ce(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),ce(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);!jS()&&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,C)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ge.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ce(i)}));const x=()=>y(this,void 0,void 0,function*(){try{const T=yield this.publish(i,m,g);b(T)}catch(T){C(T)}});setTimeout(()=>{this.engine.off(M.SignalConnected,x),C(new Ao("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(M.SignalConnected,x),this.engine.on(M.Closing,()=>{this.engine.off(M.SignalConnected,x),C(new Ao("publishing rejected as engine closed",499))})}else try{const x=yield this.publish(i,m,g);b(x)}catch(x){C(x)}}catch(x){C(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),ce(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>nC(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ce(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 Ao("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(S=>pi(e)&&S.source===e.source)&&e.source!==I.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ce(e))),t.stopMicTrackOnMute&&Yt(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&fi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!DS()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!US()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=rc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(S=>t.videoCodec===Ls(S.mime))||(t.videoCodec=Ls(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(L.Muted,this.onTrackMuted),e.on(L.Unmuted,this.onTrackUnmuted),e.on(L.Ended,this.handleTrackEnded),e.on(L.UpstreamPaused,this.onTrackUpstreamPaused),e.on(L.UpstreamResumed,this.onTrackUpstreamResumed),e.on(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new po({cid:e.mediaStreamTrack.id,name:t.name,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.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===I.Kind.Video){let S={width:0,height:0};try{S=yield e.waitForDimensions()}catch{const E=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Xi.h720.resolution;S={width:E.width,height:E.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ce(e)),{dims:S}))}v.width=S.width,v.height=S.height,wn(e)&&(Ji(m)&&(e.source===I.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),ce(e))))),t.scalabilityMode=(l=t.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),v.simulcastCodecs=[new fo({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:rc}),t.backupCodec&&m!==t.backupCodec.codec&&v.encryption===ut.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new fo({codec:t.backupCodec.codec,cid:""})))),b=lc(e.source===I.Source.ScreenShare,v.width,v.height,t),v.layers=Of(v.width,v.height,b,Ji(t.videoCodec))}else e.kind===I.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 Me("cannot publish track when not connected");const C=()=>y(this,void 0,void 0,function*(){var S,w,E;if(!this.engine.pcManager)throw new Me("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),wn(e)&&((S=t.degradationPreference)!==null&&S!==void 0||(t.degradationPreference=OC(e)),e.setDegradationPreference(t.degradationPreference)),b)if(fi()&&e.kind===I.Kind.Audio){let P;for(const O of this.engine.pcManager.publisher.getTransceivers())if(O.sender===e.sender){P=O;break}P&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:P,codec:"opus",maxbr:!((w=b[0])===null||w===void 0)&&w.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Ji(e.codec)&&(!((E=b[0])===null||E===void 0)&&E.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),C()]))[0];else{x=yield this.engine.addTrack(v);let S;if(x.codecs.forEach(w=>{S===void 0&&(S=w.mimeType)}),S&&e.kind===I.Kind.Video){const w=Ls(S);w!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ce(e)),{codec:w})),t.videoCodec=w,b=lc(e.source===I.Source.ScreenShare,v.width,v.height,t))}yield C()}const T=new mc(e.kind,x,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return T.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})),wn(e)?e.startMonitor(this.engine.client):jn(e)&&e.startMonitor(),this.addTrackPublication(T),this.emit(U.LocalTrackPublished,T),T})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==ut.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new $t("track is not published");if(!wn(e))throw new $t("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=RC(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),ce(e)));return}const l=e.addSimulcastTrack(t,o);if(!l)return;const c=new po({cid:l.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=Of(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Me("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(pi(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ce(e))),yield c)}const s=this.getPublicationForTrack(e),a=s?ce(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(L.Muted,this.onTrackMuted),e.off(L.Unmuted,this.onTrackUnmuted),e.off(L.Ended,this.handleTrackEnded),e.off(L.UpstreamPaused,this.onTrackUpstreamPaused),e.off(L.UpstreamResumed,this.onTrackUpstreamResumed),e.off(L.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<xe.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),wn(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 I.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case I.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(U.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!==I.Source.ScreenShare&&c.source!==I.Source.ScreenShareAudio&&(jn(c)||wn(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?se.RELIABLE:se.LOSSY,a=r.destinationIdentities,o=r.topic,l=new at({kind:s,value:{case:"user",value:new Ld({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 at({kind:se.RELIABLE,value:{case:"sipDtmf",value:new Md({code:e,digit:t})}});yield this.engine.sendDataPacket(i,se.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 at({value:{case:"chatMessage",value:new ao(Object.assign(Object.assign({},i),{timestamp:Te.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,se.RELIABLE),this.emit(U.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 at({value:{case:"chatMessage",value:new ao(Object.assign(Object.assign({},i),{timestamp:Te.parse(i.timestamp),editTimestamp:Te.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,se.RELIABLE),this.emit(U.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 co({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Fn(s.timestamp),totalLength:Fn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new qd({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"?oo.UPDATE:oo.CREATE})}}),o=e==null?void 0:e.destinationIdentities,l=new at({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,se.RELIABLE);let c=0;const u=this,d=new WritableStream({write(g){return y(this,void 0,void 0,function*(){for(const m of XS(g,Bf)){yield u.engine.waitForBufferStatusLow(se.RELIABLE);const v=new lo({content:m,streamId:r,chunkIndex:Fn(c)}),b=new at({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,se.RELIABLE),c+=1}})},close(){return y(this,void 0,void 0,function*(){const g=new uo({streamId:r}),m=new at({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield u.engine.sendDataPacket(m,se.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(M.Closing,h);const f=new jC(d,s,()=>this.engine.off(M.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 co({totalLength:Fn((a=c.size)!==null&&a!==void 0?a:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:Fn(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Kd({name:c.name})}}),d=new at({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,se.RELIABLE);let h=0;const f=new rt,g=this.engine,m=this.log,v=new WritableStream({write(C){return y(this,void 0,void 0,function*(){const x=yield f.lock();let T=0;try{for(;T<C.byteLength;){const S=C.slice(T,T+Bf);yield g.waitForBufferStatusLow(se.RELIABLE);const w=new at({destinationIdentities:l,value:{case:"streamChunk",value:new lo({content:S,streamId:o,chunkIndex:Fn(h)})}});yield g.sendDataPacket(w,se.RELIABLE),h+=1,T+=S.byteLength}}finally{x()}})},close(){return y(this,void 0,void 0,function*(){const C=new uo({streamId:o}),x=new at({destinationIdentities:l,value:{case:"streamTrailer",value:C}});yield g.sendDataPacket(x,se.RELIABLE)})},abort(C){m.error("Sink error:",C)}});return new VC(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(ac(a)>wf){u(_e.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&&Bn((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(_e.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(_e.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(_e.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(C,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(C??"")},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 at({destinationIdentities:[e],kind:se.RELIABLE,value:{case:"rpcRequest",value:new Dd({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,se.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,_e.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),ce(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?(jn(r)||wn(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 ot(20)}})}}class XC extends Xt{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=mt.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(L.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 ys({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new jd({participantSid:"",trackSids:[this.trackSid]})]});this.emit(L.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Xt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Xt.SubscriptionStatus.Subscribed:Xt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Xt.PermissionStatus.Allowed:Xt.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||($o(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&$o(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(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(L.VisibilityChanged,this.handleVisibilityChange),r.off(L.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(L.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(L.VisibilityChanged,this.handleVisibilityChange),e.on(L.Ended,this.handleEnded),this.emit(L.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(L.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?L.Muted:L.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(L.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(L.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===I.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 $o(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Yd({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=mt.HIGH,this.emit(L.UpdateSettings,e)}}class Vs extends Uf{static fromParticipantInfo(e,t,i){return new Vs(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]:bs.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(L.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ce(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(L.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(L.SubscriptionPermissionChanged,t=>{this.emit(U.TrackSubscriptionPermissionChanged,e,t)}),e.on(L.SubscriptionStatusChanged,t=>{this.emit(U.TrackSubscriptionStatusChanged,e,t)}),e.on(L.Subscribed,t=>{this.emit(U.TrackSubscribed,t,e)}),e.on(L.Unsubscribed,t=>{this.emit(U.TrackUnsubscribed,t,e)}),e.on(L.SubscriptionFailed,t=>{this.emit(U.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]:I.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]:I.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(U.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),ce(o))),this.emit(U.TrackSubscriptionFailed,t);return}const l=e.kind==="video";let c;return l?c=new zC(e,t,r,s):c=new GC(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)&&Ko(c)&&Yt(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=I.kindFromProto(r.type);if(!l)return;o=new XC(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!==I.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:ce(c),newTrack:ce(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),ce(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(U.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 I.Kind.Audio:this.audioTrackPublications.delete(e);break;case I.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(U.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Yt(i.track)&&Ko(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 ae;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ae||(ae={}));const JC=4*1e3;class bi extends Vt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=ae.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ne,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(!BS())throw Gt()?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===ae.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(ae.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Vo(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new hc(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 C=new AbortController;this.abortController=C,u==null||u();try{yield this.attemptConnection(m??a,o,l,C),this.abortController=void 0,f()}catch(x){if(this.regionUrlProvider&&x instanceof he&&x.reason!==re.Cancelled&&x.reason!==re.NotAllowed){let T=null;try{T=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(S){if(S instanceof he&&(S.status===401||S.reason===re.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(S);return}}T&&!(!((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(T),this.logContext),this.recreateEngine(),yield d(f,g,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,of(x)),g(x))}else{let T=Tt.UNKNOWN_REASON;x instanceof he&&(T=of(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),g(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Wo((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[C,x]=b;return"".concat(C,": ").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 CS("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===ae.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({},sc),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(A.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new he("could not establish signal connection",re.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof he&&(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 he("Connection attempt aborted",re.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}ct()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ct()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ae.Connected),this.emit(A.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===ae.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===ae.Connecting||c.state===ae.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 he("Client initiated disconnect",re.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,Tt.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=wt();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=Ho();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(A.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(ae.Reconnecting)&&this.emit(A.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(ae.Connected),this.emit(A.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===oi.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(A.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(A.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=I.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,l.emit(U.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(A.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(A.DataReceived,o.payload,a,l,o.topic),a==null||a.emit(U.DataReceived,o.payload,l)},this.handleSipDtmf=(a,o)=>{this.emit(A.SipDTMFReceived,o,a),a==null||a.emit(U.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=qS(o,this.transcriptionReceivedTimes);c==null||c.emit(L.TranscriptionReceived,u),l==null||l.emit(U.TranscriptionReceived,u,c),this.emit(A.TranscriptionReceived,u,l,c)},this.handleChatMessage=(a,o)=>{const l=KS(o);this.emit(A.ChatMessage,l,a)},this.handleMetrics=(a,o)=>{this.emit(A.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(A.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(A.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(A.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(A.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,l;const c=Be.getInstance().previousDevices,u=yield Be.getInstance().getDevices(void 0,!1),d=wt();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(A.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const g=JS(f),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(C=>C.kind===f),b=this.getActiveDevice(f);if(b===((o=c.filter(C=>C.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"&&!Sn()||f==="videoinput"||v.length>0&&!v.find(C=>C.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(A.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(A.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(A.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(A.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(A.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(A.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(A.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(A.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(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(L.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(A.LocalTrackPublished,a,this.localParticipant),jn(a.track)&&(yield a.track.checkForSilence())&&this.emit(A.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=df(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(A.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,l;(o=a.track)===null||o===void 0||o.off(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(L.Restarted,this.onLocalTrackRestarted),this.emit(A.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),l=df(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(A.ActiveDeviceChanged,l,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(A.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(A.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(A.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(A.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},bC),e),this.log=Kt((i=this.options.loggerName)!==null&&i!==void 0?i:Ct.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Sf),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Cf),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},vC),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new rt,this.localParticipant=new YC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Cn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Cn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Cn(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),ct()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),bi.cleanupRegistry&&bi.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,_e.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,_e.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});ac(u)>wf?(l=_e.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof _e?l=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=_e.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 iC(this.options.e2ee),this.e2eeManager.on(Tn.ParticipantEncryptionStatusChanged,(t,i)=>{YS(i)&&(this.isE2EEEnabled=t),this.emit(A.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(Tn.EncryptionError,t=>this.emit(A.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===ae.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(M.RoomUpdate,i),e(r.sid))};this.engine.on(M.RoomUpdate,i),this.once(A.Disconnected,()=>{this.engine.off(M.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 LC(this.options),this.engine.on(M.ParticipantUpdate,this.handleParticipantUpdates).on(M.RoomUpdate,this.handleRoomUpdate).on(M.SpeakersChanged,this.handleSpeakersChanged).on(M.StreamStateChanged,this.handleStreamStateUpdate).on(M.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(M.SubscriptionError,this.handleSubscriptionError).on(M.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(M.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(M.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(M.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(M.DataPacketReceived,this.handleDataPacket).on(M.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ae.SignalReconnecting)&&this.emit(A.SignalReconnecting)}).on(M.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ae.Connected)&&this.emit(A.Reconnected)}).on(M.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ae.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(M.Restarting,this.handleRestarting).on(M.SignalRestarted,this.handleSignalRestarted).on(M.Offline,()=>{this.setAndEmitConnectionState(ae.Reconnecting)&&this.emit(A.Reconnecting)}).on(M.DCBufferStatusChanged,(e,t)=>{this.emit(A.DCBufferStatusChanged,e,t)}).on(M.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(U.LocalTrackSubscribed,t),this.emitWhenConnected(A.LocalTrackSubscribed,t,this.localParticipant)}).on(M.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(A.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 Be.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ae.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Vo(new URL(e))&&t){this.regionUrlProvider=new hc(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ae.Disconnected&&(this.regionUrl=i,yield fetch(qo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(qo(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 jt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new jt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new jt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new jt({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 jt({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 jt({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 jt({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 Ts({reason:Tt.CLIENT_INITIATED,action:li.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new jt({scenario:{case:"subscriberBandwidth",value:Fn(t)}});break;case"leave-full-reconnect":r=new jt({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 C=(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(T=>T.source===I.Source.Microphone);try{m=(yield Promise.all(x.map(T=>{var S;return(S=T.audioTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(T=>T===!0)}catch(T){throw s.options.audioCaptureDefaults.deviceId=C,T}}else if(i==="videoinput"){v=s.localParticipant.videoTrackPublications.size===0;const C=(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(T=>T.source===I.Source.Camera);try{m=(yield Promise.all(x.map(T=>{var S;return(S=T.videoTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(T=>T===!0)}catch(T){throw s.options.videoCaptureDefaults.deviceId=C,T}}else if(i==="audiooutput"){if(!jo()&&!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 Be.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(g=s.options).audioOutput)!==null&&u!==void 0||(g.audioOutput={});const C=(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=C,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(A.ActiveDeviceChanged,i,r)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(U.AttributesChanged,this.onLocalAttributesChanged).on(U.TrackMuted,this.onLocalTrackMuted).on(U.TrackUnmuted,this.onLocalTrackUnmuted).on(U.LocalTrackPublished,this.onLocalTrackPublished).on(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(U.MediaDevicesError,this.onMediaDevicesError).on(U.AudioStreamAcquired,this.startAudio).on(U.ChatMessage,this.onLocalChatMessageSent).on(U.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===ae.Connecting||this.state===ae.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(A.Reconnected,u),this.off(A.Connected,u),this.off(A.Disconnected,d)};this.once(A.Reconnected,u),this.once(A.Connected,u),this.once(A.Disconnected,d);return}if(this.state===ae.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=MS(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!==ae.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(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(U.AttributesChanged,this.onLocalAttributesChanged).off(U.TrackMuted,this.onLocalTrackMuted).off(U.TrackUnmuted,this.onLocalTrackUnmuted).off(U.LocalTrackPublished,this.onLocalTrackPublished).off(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(U.MediaDevicesError,this.onMediaDevicesError).off(U.AudioStreamAcquired,this.startAudio).off(U.ChatMessage,this.onLocalChatMessageSent).off(U.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),ct()&&(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(ae.Disconnected),this.emit(A.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(A.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:Ns(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 BC(a,o,Ns(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 FC(a,o,Ns(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=uf())!==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(),ot(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(A.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=Vs.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Vs(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(A.ParticipantConnected,i),i.on(U.TrackPublished,r=>{this.emitWhenConnected(A.TrackPublished,r,i)}).on(U.TrackSubscribed,(r,s)=>{r.kind===I.Kind.Audio?(r.on(L.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(L.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===I.Kind.Video&&(r.on(L.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(L.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(A.TrackSubscribed,r,s,i)}).on(U.TrackUnpublished,r=>{this.emit(A.TrackUnpublished,r,i)}).on(U.TrackUnsubscribed,(r,s)=>{this.emit(A.TrackUnsubscribed,r,s,i)}).on(U.TrackMuted,r=>{this.emitWhenConnected(A.TrackMuted,r,i)}).on(U.TrackUnmuted,r=>{this.emitWhenConnected(A.TrackUnmuted,r,i)}).on(U.ParticipantMetadataChanged,r=>{this.emitWhenConnected(A.ParticipantMetadataChanged,r,i)}).on(U.ParticipantNameChanged,r=>{this.emitWhenConnected(A.ParticipantNameChanged,r,i)}).on(U.AttributesChanged,r=>{this.emitWhenConnected(A.ParticipantAttributesChanged,r,i)}).on(U.ConnectionQualityChanged,r=>{this.emitWhenConnected(A.ConnectionQualityChanged,r,i)}).on(U.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(A.ParticipantPermissionsChanged,r,i)}).on(U.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(A.TrackSubscriptionStatusChanged,r,s,i)}).on(U.TrackSubscriptionFailed,(r,s)=>{this.emit(A.TrackSubscriptionFailed,r,i,s)}).on(U.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(A.TrackSubscriptionPermissionChanged,r,s,i)}).on(U.Active,()=>{this.emitWhenConnected(A.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&&$S(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=He.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,Tt.STATE_MISMATCH))):e=0},JC)}clearConnectionReconcile(){this.connectionReconcileInterval&&He.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(A.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===ae.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ae.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 gs({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Te.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ln({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(A.SignalConnected),this.emit(A.Connected),this.setAndEmitConnectionState(ae.Connected),r.video){const a=new mc(I.Kind.Video,new ci({source:Ne.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:yt.AUDIO,name:"video-dummy"}),new Fs(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:af(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(U.LocalTrackPublished,a)}if(r.audio){const a=new mc(I.Kind.Audio,new ci({source:Ne.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:yt.AUDIO}),new Us(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ho(),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(U.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Ln({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:oi.ACTIVE,tracks:[],joinedAt:Te.parse(Date.now())});const l=this.getOrCreateParticipant(o.identity,o);if(s.video){const c=af(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new ci({source:Ne.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:yt.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const c=Ho(),u=new ci({source:Ne.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:yt.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!==A.ActiveSpeakersChanged&&e!==A.TranscriptionReceived){const s=Ff(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)}}bi.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Ff(n){return n.map(e=>{if(e)return Array.isArray(e)?Ff(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Et;(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"})(Et||(Et={}));class En extends Vt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Et.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new bi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==Et.IDLE)throw Error("check is running already");this.setStatus(Et.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!==Et.SKIPPED&&this.setStatus(this.isSuccess()?Et.SUCCESS:Et.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===ae.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!==ae.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Et.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(A.Reconnecting,()=>{t=!0}),this.room.once(A.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 ot(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 QC extends En{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new hc(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 gc=1e4;class ZC extends En{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/(gc/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(gc/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,gc)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class e1 extends En{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield qC();if(yield lf(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 t1 extends En{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield WC();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 n1 extends En{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(A.SignalReconnecting,o).on(A.Reconnecting,o).on(A.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!==ae.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 i1 extends En{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new Qo,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 r1 extends En{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(A.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&&(s1(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(),ne.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 s1(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 a1 extends En{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 Qo;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)===Vd.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 b_ extends Vt.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:Et.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!==Et.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(a1)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(r1)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(i1)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(n1)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(e1)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(t1)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(ZC);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(QC)})}}const o1=/\{[^{}]+\}/g;function c1(){return Math.random().toString(36).slice(2,11)}function l1(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=zf(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:C,bodySerializer:x=s??d1,body:T,...S}=d||{};h&&(e=zf(h));let w=typeof r=="function"?r:Gf(r);C&&(w=typeof C=="function"?C:Gf({...typeof r=="object"?r:{},...C}));const E=T===void 0?void 0:x(T),P=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},O={redirect:"follow",...o,...S,body:E,headers:f1(P,a,m,v.header)};let B,N,H=new t(h1(u,{baseUrl:e,params:v,querySerializer:w}),O);for(const Y in S)Y in H||(H[Y]=S[Y]);if(l.length){B=c1(),N=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:w,bodySerializer:x});for(const Y of l)if(Y&&typeof Y=="object"&&typeof Y.onRequest=="function"){const q=await Y.onRequest({request:H,schemaPath:u,params:v,options:N,id:B});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");H=q}}}let W=await f(H);if(l.length)for(let Y=l.length-1;Y>=0;Y--){const q=l[Y];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const fe=await q.onResponse({request:H,response:W,schemaPath:u,params:v,options:N,id:B});if(fe){if(!(fe instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");W=fe}}}if(W.status===204||W.headers.get("Content-Length")==="0")return W.ok?{data:{},response:W}:{error:{},response:W};if(W.ok)return b==="stream"?{data:W.body,response:W}:{data:await W[b](),response:W};let J=await W.text();try{J=JSON.parse(J)}catch{}return{error:J,response:W}}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 Gs(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 jf(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(Gs(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Vf(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(Gs(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Gf(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(Vf(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(jf(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(Gs(r,s,n))}}return i.join("&")}}function u1(n,e){let t=n;for(const i of n.match(o1)??[]){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,Vf(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,jf(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${Gs(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function d1(n){return n instanceof FormData?n:JSON.stringify(n)}function h1(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=u1(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function f1(...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 zf(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Hf="Onboardee-Session-Token",Wf="OnboardeeSessionToken";class qf{constructor(e){this.client=l1({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const i=window.localStorage.getItem(Wf);i&&t.headers.set(Hf,i)}return t},onResponse({response:t}){const i=t.headers.get(Hf);return i&&window.localStorage&&window.localStorage.setItem(Wf,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 listUsers(){return await this.client.GET("/api/users")}async createUser(e){return await this.client.POST("/api/users",{body:e})}async updateUser(e,t){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:t})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}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 listAudiences(e){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)}}})}async createAudience(e,t){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:t})}async getAudience(e,t){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async updateAudience(e,t,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}},body:i})}async deleteAudience(e,t){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async replaceAudiencePlans(e,t,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:t}},body:{plans:i}})}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 listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,t){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async bulkUpdateProductPronunciationRules(e,t){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async deleteProductPronunciationRule(e,t){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:t}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:t})}async updateProductExternalKnowledge(e,t,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}},body:i})}async deleteProductExternalKnowledge(e,t){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}}})}async refreshProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:t}}})}async listExternalKnowledgePages(e,t){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId: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 duplicatePlan(e){return await this.client.POST("/api/plans/{id}/duplicate",{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 listPlanFAQs(e,t=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(t)}}})}async listPlanDraftFAQs(e){return await this.client.GET("/api/plans/{id}/draft-faqs",{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 listRevisionFAQs(e,t){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...t!==void 0&&{include_drafts:t.toString()}}}})}async createRevisionFAQ(e,t){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:t})}async updateFAQ(e,t){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:t})}async deleteFAQ(e){return await this.client.DELETE("/api/faqs/{id}",{params:{path:{id:e}}})}async promoteFAQ(e){return await this.client.POST("/api/faqs/{id}/promote",{params:{path:{id:e}}})}async promoteFAQs(e){return await this.client.POST("/api/faqs/promote",{body:{faq_ids:e}})}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"})}async getFeatureFlags(e){return await this.client.GET("/api/features",{params:e?{query:e}:void 0})}getClient(){return this.client}}const Kf="https://app.coragents.ai";class zs extends ga{constructor(e,t,i,r){super(),this.state=null,this.isPaused=!1,this.isAudioTrackPublished=!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.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.appToken=e,this.planId=t,this.clientType=i,this.api=r.api||new qf({baseUrl:Kf}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new bi(s)),this.captureScreen=r.captureScreen||null}async start(e){this.planId,e==null||e.roomId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const i=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId,...(e==null?void 0:e.roomId)&&{room_id:e.roomId}})).data;if(!(i!=null&&i.url)||!(i!=null&&i.token)||!(i!=null&&i.room)||!(i!=null&&i.session_uuid))throw new Error("Invalid room info");this.sessionUuid=i==null?void 0:i.session_uuid,this.roomId=i==null?void 0:i.room,this.joinToken=i==null?void 0:i.token,this.roomUrl=i==null?void 0:i.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("volume-check"),this.planId,this.sessionUuid}catch(t){console.error("[obi] error starting session",{error:t}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(A.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(A.TrackSubscribed,i=>{if(i.kind==="audio"&&(i.attach(),i.source===I.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=s}}),this.room.on(A.LocalTrackPublished,i=>{if(i.kind==="audio"){this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=s}}),this.room.on(A.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(A.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"in_progress":this.setState("in-progress");break;case"shutdown":this.shutdown("server-sent");break;case"mute_microphone":this.muteMicrophone();break;case"unmute_microphone":this.unmuteMicrophone();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===ae.Connected&&this.room.remoteParticipants.size>=1);i++)await new Promise(r=>setTimeout(r,1e3));if(!(this.room.state===ae.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 publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const c=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",c),!1}console.log("[obi] requesting audio track via getUserMedia"),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});const t=this.publishedAudioStream.getAudioTracks().map(c=>{var u,d;return{id:c.id,label:c.label,enabled:c.enabled,muted:c.muted,readyState:c.readyState,constraints:(u=c.getConstraints)==null?void 0:u.call(c),settings:(d=c.getSettings)==null?void 0:d.call(c)}});console.log("[obi] getUserMedia resolved",t);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const c=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",c),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},s=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,s);const a=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:I.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,s,a.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:o,context:l}=this.createFFT(this.publishedAudioStream);this.userAnalyser=o,this.userAudioContext=l,this.isAudioTrackPublished=!0,e=!0}catch(t){if(console.error("[obi] failed to publish audio track",t),this.isAudioTrackPublished=!1,this.publishedAudioStream){try{this.publishedAudioStream.getTracks().forEach(i=>i.stop())}catch(i){console.warn("[obi] error stopping tracks during cleanup",i)}this.publishedAudioStream=null}this.publishedAudioTrack=null}return e}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){if(this.sessionUuid,this.publishedAudioTrack&&this.isAudioTrackPublished)try{console.log("[obi] unpublishing audio track",this.publishedAudioTrack.id,this.room.localParticipant.identity),this.room.localParticipant.unpublishTrack(this.publishedAudioTrack)}catch(i){console.warn("[obi] failed to unpublish audio track",i)}if(this.publishedAudioStream)try{const i=this.publishedAudioStream.getAudioTracks().length;console.log("[obi] stopping published audio stream tracks",i),this.publishedAudioStream.getTracks().forEach(r=>r.stop())}catch(i){console.warn("[obi] error stopping published audio tracks",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null),this.isAudioTrackPublished=!1,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.frequencyDataBuffer=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}agentAudioSpectrum(){return this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):null}normaliseSpectrum(e){const i=e.context.sampleRate/2/e.frequencyBinCount;(!this.frequencyDataBuffer||this.frequencyDataBuffer.length!==e.frequencyBinCount)&&(this.frequencyDataBuffer=new Uint8Array(new ArrayBuffer(e.frequencyBinCount))),e.getByteFrequencyData(this.frequencyDataBuffer);const r=[],s=50,a=5e3,o=8,l=Math.pow(a/s,1/o);for(let c=0;c<o;c++){const u=s*Math.pow(l,c),d=s*Math.pow(l,c+1),h=Math.floor(u/i),f=Math.floor(d/i),g=Math.min(f,this.frequencyDataBuffer.length),m=Math.min(h,g);if(m<g){let v=0;for(let C=m;C<g;C++)v+=this.frequencyDataBuffer[C];const b=v/(g-m)/255;r.push(b)}else r.push(0)}return r}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 zs(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,{analyser:i,context:t}}}class Hs extends ga{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 qf({baseUrl:i.apiBaseUrl||Kf}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new zs(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,i){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(i).then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,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),a=new Hs(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=zs.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 Ws,X,$f,Vn,Yf,Xf,Jf,Qf,vc,bc,yc,Zf,tr={},ep=[],p1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,nr=Array.isArray;function Jt(n,e){for(var t in e)n[t]=e[t];return n}function Tc(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function kc(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?Ws.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return qs(n,a,i,r,null)}function qs(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??++$f,__i:-1,__u:0};return r==null&&X.vnode!=null&&X.vnode(s),s}function $e(n){return n.children}function Qt(n,e){this.props=n,this.context=e}function yi(n,e){if(e==null)return n.__?yi(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"?yi(n):null}function tp(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 tp(n)}}function Sc(n){(!n.__d&&(n.__d=!0)&&Vn.push(n)&&!Ks.__r++||Yf!=X.debounceRendering)&&((Yf=X.debounceRendering)||Xf)(Ks)}function Ks(){for(var n,e,t,i,r,s,a,o=1;Vn.length;)Vn.length>o&&Vn.sort(Jf),n=Vn.shift(),o=Vn.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=Jt({},i)).__v=i.__v+1,X.vnode&&X.vnode(t),Cc(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??yi(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,ap(s,t,a),t.__e!=r&&tp(t)));Ks.__r=0}function np(n,e,t,i,r,s,a,o,l,c,u){var d,h,f,g,m,v,b=i&&i.__k||ep,C=e.length;for(l=m1(t,e,b,l,C),d=0;d<C;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?tr:b[f.__i]||tr,f.__i=d,v=Cc(n,f,h,r,s,a,o,l,c,u),g=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&wc(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=ip(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 m1(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?qs(null,a,null,null,null):nr(a)?qs($e,{children:a},null,null,null):a.constructor==null&&a.__b>0?qs(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=g1(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=yi(o)),cp(o,o));return i}function ip(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=ip(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=yi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function $s(n,e){return e=e||[],n==null||typeof n=="boolean"||(nr(n)?n.some(function(t){$s(t,e)}):e.push(n)),e}function g1(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 rp(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||p1.test(e)?t:t+"px"}function Ys(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||rp(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||rp(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Qf,"$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=vc,n.addEventListener(e,s?yc:bc,s)):n.removeEventListener(e,s?yc:bc,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 sp(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=vc++;else if(e.t<t.u)return;return t(X.event?X.event(e):e)}}}function Cc(n,e,t,i,r,s,a,o,l,c){var u,d,h,f,g,m,v,b,C,x,T,S,w,E,P,O,B,N=e.type;if(e.constructor!=null)return null;128&t.__u&&(l=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=X.__b)&&u(e);e:if(typeof N=="function")try{if(b=e.props,C="prototype"in N&&N.prototype.render,x=(u=N.contextType)&&i[u.__c],T=u?x?x.props.value:u.__:i,t.__c?v=(d=e.__c=t.__c).__=d.__E:(C?e.__c=d=new N(b,T):(e.__c=d=new Qt(b,T),d.constructor=N,d.render=b1),x&&x.sub(d),d.props=b,d.state||(d.state={}),d.context=T,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&N.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Jt({},d.__s)),Jt(d.__s,N.getDerivedStateFromProps(b,d.__s))),f=d.props,g=d.state,d.__v=e,h)C&&N.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&N.getDerivedStateFromProps==null&&b!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,T),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,T)===!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(H){H&&(H.__=e)}),S=0;S<d._sb.length;S++)d.__h.push(d._sb[S]);d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,T),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,g,m)})}if(d.context=T,d.props=b,d.__P=n,d.__e=!1,w=X.__r,E=0,C){for(d.state=d.__s,d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),P=0;P<d._sb.length;P++)d.__h.push(d._sb[P]);d._sb=[]}else do d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++E<25);d.state=d.__s,d.getChildContext!=null&&(i=Jt(Jt({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(m=d.getSnapshotBeforeUpdate(f,g)),O=u,u!=null&&u.type===$e&&u.key==null&&(O=op(u.props.children)),o=np(n,nr(O)?O:[O],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(H){if(e.__v=null,l||s!=null)if(H.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(B=s.length;B--;)Tc(s[B]);else e.__e=t.__e,e.__k=t.__k;X.__e(H,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=v1(t.__e,e,t,i,r,s,a,l,c);return(u=X.diffed)&&u(e),128&e.__u?void 0:o}function ap(n,e,t){for(var i=0;i<t.length;i++)wc(t[i],t[++i],t[++i]);X.__c&&X.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){X.__e(s,r.__v)}})}function op(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:nr(n)?n.map(op):Jt({},n)}function v1(n,e,t,i,r,s,a,o,l){var c,u,d,h,f,g,m,v=t.props,b=e.props,C=e.type;if(C=="svg"?r="http://www.w3.org/2000/svg":C=="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==!!C&&(C?f.localName==C:f.nodeType==3)){n=f,s[c]=null;break}}if(n==null){if(C==null)return document.createTextNode(b);n=document.createElementNS(r,C,b.is&&b),o&&(X.__m&&X.__m(e,s),o=!1),s=null}if(C==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&Ws.call(n.childNodes),v=t.props||tr,!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;Ys(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||Ys(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=""),np(e.type=="template"?n.content:n,nr(h)?h:[h],e,t,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&yi(t,0),o,l),s!=null)for(c=s.length;c--;)Tc(s[c]);o||(c="value",C=="progress"&&g==null?n.removeAttribute("value"):g!=null&&(g!==n[c]||C=="progress"&&!g||C=="option"&&g!=v[c])&&Ys(n,c,g,v[c],r),c="checked",m!=null&&m!=n[c]&&Ys(n,c,m,v[c],r))}return n}function wc(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){X.__e(r,t)}}function cp(n,e,t){var i,r;if(X.unmount&&X.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||wc(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){X.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&cp(i[r],e,t||typeof n.type!="function");t||Tc(n.__e),n.__c=n.__=n.__e=void 0}function b1(n,e,t){return this.constructor(n,t)}function y1(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),X.__&&X.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Cc(e,n=(!i&&t||e).__k=kc($e,null,[n]),r||tr,tr,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?Ws.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),ap(s,n,a)}function T1(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,Sc(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"+Zf++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}Ws=ep.slice,X={__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}},$f=0,Qt.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Jt({},this.state),typeof n=="function"&&(n=n(Jt({},t),this.props)),n&&Jt(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Sc(this))},Qt.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Sc(this))},Qt.prototype.render=$e,Vn=[],Xf=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Jf=function(n,e){return n.__v.__b-e.__v.__b},Ks.__r=0,Qf=/(PointerCapture)$|Capture$/i,vc=0,bc=sp(!1),yc=sp(!0),Zf=0;var k1=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:--k1,__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 X.vnode&&X.vnode(c),c}var Gn,ke,xc,lp,ir=0,up=[],Oe=X,dp=Oe.__b,hp=Oe.__r,fp=Oe.diffed,pp=Oe.__c,mp=Oe.unmount,gp=Oe.__;function rr(n,e){Oe.__h&&Oe.__h(ke,n,ir||e),ir=0;var t=ke.__H||(ke.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function ee(n){return ir=1,S1(yp,n)}function S1(n,e,t){var i=rr(Gn++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):yp(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=ke,!ke.__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};ke.__f=!0;var s=ke.shouldComponentUpdate,a=ke.componentWillUpdate;ke.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)},ke.shouldComponentUpdate=r}return i.__N||i.__}function Je(n,e){var t=rr(Gn++,3);!Oe.__s&&Rc(t.__H,e)&&(t.__=n,t.u=e,ke.__H.__h.push(t))}function _c(n,e){var t=rr(Gn++,4);!Oe.__s&&Rc(t.__H,e)&&(t.__=n,t.u=e,ke.__h.push(t))}function Rt(n){return ir=5,Xs(function(){return{current:n}},[])}function Xs(n,e){var t=rr(Gn++,7);return Rc(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function C1(n,e){return ir=8,Xs(function(){return n},e)}function vp(n){var e=ke.context[n.__c],t=rr(Gn++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(ke)),e.props.value):n.__}function w1(){for(var n;n=up.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(Js),n.__H.__h.forEach(Ec),n.__H.__h=[]}catch(e){n.__H.__h=[],Oe.__e(e,n.__v)}}Oe.__b=function(n){ke=null,dp&&dp(n)},Oe.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),gp&&gp(n,e)},Oe.__r=function(n){hp&&hp(n),Gn=0;var e=(ke=n.__c).__H;e&&(xc===ke?(e.__h=[],ke.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(Js),e.__h.forEach(Ec),e.__h=[],Gn=0)),xc=ke},Oe.diffed=function(n){fp&&fp(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(up.push(e)!==1&&lp===Oe.requestAnimationFrame||((lp=Oe.requestAnimationFrame)||x1)(w1)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),xc=ke=null},Oe.__c=function(n,e){e.some(function(t){try{t.__h.forEach(Js),t.__h=t.__h.filter(function(i){return!i.__||Ec(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],Oe.__e(i,t.__v)}}),pp&&pp(n,e)},Oe.unmount=function(n){mp&&mp(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{Js(i)}catch(r){e=r}}),t.__H=void 0,e&&Oe.__e(e,t.__v))};var bp=typeof requestAnimationFrame=="function";function x1(n){var e,t=function(){clearTimeout(i),bp&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);bp&&(e=requestAnimationFrame(t))}function Js(n){var e=ke,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),ke=e}function Ec(n){var e=ke;n.__c=n.__(),ke=e}function Rc(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function yp(n,e){return typeof e=="function"?e(n):e}function _1({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 Tp({onClose:n}){return p("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:p(_1,{})})}function kp({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Rt(null),a=Rt(null);Je(()=>{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 Je(()=>{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(Tp,{onClose:c}),p("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Pc({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 E1({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 R1({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})})}const Sp=8,Qs=8,P1=100,I1=.7,Ti=3;function Cp({getBands:n,color:e="white"}){const t=Rt(null);return Je(()=>{if(!n)return;let i=0,r;const s=a=>{try{if(a-i>=P1){const o=n();if(t.current){const l=t.current.querySelectorAll(".bar"),c=o&&o.length>0?o.slice(0,Qs).map(u=>{const d=Math.abs(u);return Math.min(d/I1*Sp,Sp)||Ti}):Array(Qs).fill(Ti);for(;c.length<Qs;)c.push(Ti);c.forEach((u,d)=>{if(u<Ti&&(u=Ti),l[d]){const h=u*2;l[d].style.height=`${h}px`,l[d].style.display=u>0?"block":"none"}})}i=a}r=requestAnimationFrame(s)}catch(o){console.warn("Error updating equaliser:",o),r=requestAnimationFrame(s)}};return r=requestAnimationFrame(s),()=>{cancelAnimationFrame(r)}},[n]),p("div",{className:"obi-equaliser",ref:t,children:Array.from({length:Qs},(i,r)=>p("div",{className:"column",children:p("div",{className:"bar",style:{height:`${Ti}px`,backgroundColor:e,display:"block"}})},r))})}function O1(n){const{spectrum:e}=n;return p(Pc,{isActive:!0,children:p(Cp,{getBands:e})})}function Ic(n){const{children:e,className:t="",...i}=n;return p("div",{className:`${t} obi-panel`,...i,children:e})}function zn({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:A1(n)})}function A1(n){switch(n){case"pause":return p($e,{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($e,{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($e,{children:[p("path",{d:"M18 6 6 18"}),p("path",{d:"m6 6 12 12"})]});case"message":return p($e,{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($e,{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($e,{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($e,{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 Oc=T1(null);function N1({children:n}){const e=vp(Oc);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=Rt(null),d=wp(a,s),[h,f]=ee(!1);Je(()=>{t!==void 0&&t!==h&&(t?m():v()),f(t)},[t]),Je(()=>()=>{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 C(){o==="hover"&&m()}function x(){o==="hover"&&v()}return p("div",{ref:d,class:"target",onClick:b,onMouseEnter:C,onMouseLeave:x,children:n})}function L1({children:n}){const e=vp(Oc);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=wp(a,r);return _c(()=>{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 lt({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,l]=ee(!1),[c,u]=ee(!1),d=Rt(null),h=Rt(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(Oc.Provider,{value:f,children:p("div",{class:`obi-popout ${a}`,children:i})})}lt.Target=N1,lt.Content=L1;function wp(n,e){const t=Rt(null),i=Rt(null),r=Rt(!0),s=C1(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 Je(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),s}function Pt({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:p(zn,{type:"close",size:16}),pause:p(zn,{type:"pause",size:16}),play:p(zn,{type:"play",size:16}),message:p(zn,{type:"message",size:16}),minimize:p(zn,{type:"minimize",size:16}),voice:p(zn,{type:"voice",size:16}),open:p(zn,{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(lt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[p(lt.Target,{children:o}),p(lt.Content,{children:p("div",{className:"obi-round-button-title",children:r})})]}):o}function Rn({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 M1=8;function D1({color:n="white"}){return p("div",{className:"obi-loading-dots",children:Array.from({length:M1},(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 U1({onContinue:n,onWrapUp:e}){return p(Ic,{className:"obi-exit-survey",children:p(F1,{onContinue:n,onWrapUp:()=>{e()}})})}function B1({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=ee("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return p(Ic,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?p(j1,{onReasonSelect:s}):p(V1,{onReasonSelect:s,onClose:t})})}function F1({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 j1({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 V1({onReasonSelect:n,onClose:e}){const[t,i]=ee("");return p("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[p("div",{className:"obi-exit-survey-header",children:[p(Tp,{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 G1(n,e){for(var t in e)n[t]=e[t];return n}function xp(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 _p(n,e){this.props=n,this.context=e}(_p.prototype=new Qt).isPureReactComponent=!0,_p.prototype.shouldComponentUpdate=function(n,e){return xp(this.props,n)||xp(this.state,e)};var Ep=X.__b;X.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Ep&&Ep(n)};var z1=X.__e;X.__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)}z1(n,e,t,i)};var Rp=X.unmount;function Pp(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=G1({},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 Pp(i,e,t)})),n}function Ip(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Ip(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 Ac(){this.__u=0,this.o=null,this.__b=null}function Op(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Zs(){this.i=null,this.l=null}X.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Rp&&Rp(n)},(Ac.prototype=new Qt).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=Op(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]=Ip(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)},Ac.prototype.componentWillUnmount=function(){this.o=[]},Ac.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]=Pp(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&kc($e,null,n.fallback);return r&&(r.__u&=-33),[kc($e,null,e.__a?null:n.children),r]};var Ap=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]}};(Zs.prototype=new Qt).__a=function(n){var e=this,t=Op(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Ap(e,n,i)):r()};t?t(s):s()}},Zs.prototype.render=function(n){this.i=null,this.l=new Map;var e=$s(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},Zs.prototype.componentDidUpdate=Zs.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Ap(n,t,e)})};var H1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,W1=/^(?: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]/,q1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,K1=/[A-Z0-9]/g,$1=typeof document<"u",Y1=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};Qt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(Qt.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var Np=X.event;function X1(){}function J1(){return this.cancelBubble}function Q1(){return this.defaultPrevented}X.event=function(n){return Np&&(n=Np(n)),n.persist=X1,n.isPropagationStopped=J1,n.isDefaultPrevented=Q1,n.nativeEvent=n};var Z1={enumerable:!1,configurable:!0,get:function(){return this.class}},Lp=X.vnode;X.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||$1&&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"||Y1(t.type)?l==="onfocus"?a="onfocusin":l==="onblur"?a="onfocusout":q1.test(a)&&(a=l):l=a="oninput":s&&W1.test(a)?a=a.replace(K1,"-$&").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=$s(t.children).forEach(function(c){c.props.selected=r.value.indexOf(c.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=$s(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",Z1)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=H1,Lp&&Lp(n)};var Mp=X.__r;X.__r=function(n){Mp&&Mp(n),n.__c};var Dp=X.diffed;X.diffed=function(n){Dp&&Dp(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 ew(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]=ee(t||i||""),[g,m]=ee((t||i||"").length>24),v=Rt(null);_c(()=>{g&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,C=S=>{const w=S.currentTarget.value;t===void 0&&f(w),r==null||r(w)},x=S=>{S.key==="Escape"&&(f(t||i||""),m(!1),a==null||a()),S.key==="Enter"&&!S.shiftKey&&b.trim()&&(S.preventDefault(),f(t||i||""),m(!1),T()),(b||"").length>=24&&!g&&(m(!0),o==null||o(!0))};Je(()=>{v.current&&v.current.focus()},[v.current]);const T=()=>{!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:C,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:T,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 tw(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r,onStepClick:s}=n,[a,o]=ee(null),l=Array.from({length:t},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),c=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(a!==null){const d=i[a]&&i[a].trim().length>0?i[a]:`Step ${a+1}`;return`${a+1}/${t} \u2022 ${d}`}return`${e}/${t} \u2022 ${c}`})();return p("div",{class:`obi-course-progress ${r||""}`,children:[p("div",{class:"obi-course-progress-steps",children:l.map((d,h)=>{const f=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,g=d.isCompleted?"completed":"future";function m(){s&&s(h,f)}function v(b){s&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),m())}return p("div",{class:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>o(h),onMouseLeave:()=>o(null),onClick:s?m:void 0,onKeyDown:s?v:void 0,role:s?"button":void 0,tabIndex:s?0:void 0,children:p("div",{class:`obi-course-progress-step ${g}`,"aria-label":f})},h)})}),p("div",{class:"obi-course-progress-description",children:u})]})}function Up({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 nw(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=ee(null),[a,o]=ee(n.isActive??n.defaultIsActive??!1),[l,c]=ee(!1),[u,d]=ee(n.cancelling??!1),[h,f]=ee(n.messaging??!1),[g,m]=ee(!1),[v,b]=ee(h),[C,x]=ee(!1);function T(){o(!0),c(!1),x(!0)}function S(){}function w(){r&&(clearTimeout(r),s(null))}function E(){s(setTimeout(()=>{o(n.defaultIsActive??!1),x(!1)},400))}function P(ie){var Fe;m(!1),(Fe=n.onMessage)==null||Fe.call(n,ie)}function O(){var ie;f(!1),m(!1),o(!1),c(!0),(ie=n.onMinimize)==null||ie.call(n)}function B(){var ie;f(!1),d(!0),m(!1),(ie=n.onCancelClick)==null||ie.call(n)}function N(){var ie;t||((ie=n.onOpen)==null||ie.call(n))}function H(ie){var Fe,tt,en,xi,tn,qn;switch(ie){case"need-help":(Fe=n.onMessage)==null||Fe.call(n,"I'm struggling, can you look at my screen and help me out."),(tt=n.onOneClickAction)==null||tt.call(n,"need-help");break;case"continue":(en=n.onMessage)==null||en.call(n,"Okay, let's continue."),(xi=n.onOneClickAction)==null||xi.call(n,"continue");break;case"say-again":(tn=n.onMessage)==null||tn.call(n,"Please say that again."),(qn=n.onOneClickAction)==null||qn.call(n,"say-again");break}}function W(ie){var Fe,tt;n.messaging===void 0?((Fe=n.onMessagingChange)==null||Fe.call(n,ie),f(ie)):((tt=n.onMessagingChange)==null||tt.call(n,!n.messaging),f(!n.messaging)),ie||m(!1)}const J=n.isActive??((a||t)&&!l&&!e),Y=J&&t,q=J&&t&&!g,fe=n.speakingStatus==="user-speaking",ve=n.speakingStatus==="thinking",be=n.speakingStatus==="busy",V=J&&!t&&!u&&C,z=J&&t&&i&&!fe&&!u,Q=J&&t&&!z&&!fe&&h!==v&&!u,K=J&&t&&i&&fe&&!u,Se=J&&t&&!i&&fe&&!u,$=J&&t&&!i&&be&&!u,pe=n.messaging!==void 0?n.messaging:h,De=pe&&fe,Ot=V||z||K||Se||Q||u,At=400,la=!!n.courseProgress,ua=V?5:10;return _c(()=>{b(h)},[fe]),!t&&!u?p(iw,{...n}):!t&&u?p(rw,{onOtherSelect:()=>{var ie;(ie=n.onCancelReasonOther)==null||ie.call(n)},onCancelReason:ie=>{var Fe;o(n.defaultIsActive??!1),d(!1),(Fe=n.onCancelReason)==null||Fe.call(n,ie)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):p(Ic,{className:`obi-widget-panel ${Y?"expanded":""} ${g?"maximized":""} ${pe?"messaging":""} ${be?"tool-usage":""}`,children:[p("div",{className:`obi-widget ${J?"active":""} ${t?"in-plan":""}`,onMouseEnter:w,onMouseLeave:E,children:[q&&p(Pt,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),q&&!i&&p(Pt,{type:"pause",onClick:n.onPause,title:"Pause session"}),q&&i&&p(Pt,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(lt,{className:"obi-widget-popout",open:Ot,trigger:null,delayMs:At,offset:ua,children:[p(lt.Target,{children:[De&&p(ew,{value:n.message,onCancel:()=>W(!1),onSend:P,onExpand:m,onChange:n.onMessageChange,children:p("div",{className:"obi-widget-buttons",children:[p(Pt,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),!i&&p(Pt,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&p(Pt,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),p(Pt,{type:pe?"voice":"message",onClick:()=>W(!pe),title:pe?"Voice input":"Text input"}),p(Pt,{type:"minimize",onClick:O,title:"Minimize widget"})]})}),!De&&p(Pc,{className:J&&!t?"button":"",isActive:J,speakingStatus:n.speakingStatus,onClick:N,onMouseEnter:T,onMouseLeave:S,children:[J&&!t&&!$&&p("span",{className:"obi-widget-pill-text",children:"Tutorials"}),J&&t&&$&&p("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),J&&t&&!ve&&!$&&p(Cp,{getBands:n.spectrum}),J&&ve&&!$&&p(D1,{})]})]}),p(lt.Content,{children:p("div",{onMouseLeave:E,children:[V&&p(Rn,{onClick:N,children:"Click to see all"}),z&&p(Rn,{children:"Session will pause shortly"}),Q&&p(Rn,{children:["Switched to ",pe?"chat":"voice"]}),K&&p(Rn,{children:"Paused"}),Se&&p("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[p(Rn,{onClick:()=>H("need-help"),children:"Need help"}),p(Rn,{onClick:()=>H("continue"),children:"Continue"}),p(Rn,{onClick:()=>H("say-again"),children:"Say again"})]}),u&&p(U1,{onContinue:()=>{var ie;(ie=n.onCancelAbort)==null||ie.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var ie;(ie=n.onCancel)==null||ie.call(n)}})]})})]}),q&&p(Pt,{type:pe?"voice":"message",onClick:()=>W(!pe),title:pe?"Voice input":"Text input"}),q&&p(Pt,{type:"minimize",onClick:O,title:"Minimize widget"})]}),la&&n.courseProgress&&p("div",{className:`obi-widget-course-progress ${pe?"expanded":""}`,children:p(tw,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames,onStepClick:(ie,Fe)=>{var en;const tt=`Can we please jump to the steps related to: ${Fe}`;(en=n.onMessage)==null||en.call(n,tt)}})})]})}function iw(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=ee(null),[o,l]=ee(n.isActive??n.defaultIsActive??!1),[c,u]=ee(!1),[d,h]=ee(n.hovered??!1);function f(){var P;l(!0),u(!1),h(!0),(P=n.onHover)==null||P.call(n,!0)}function g(){}function m(){s&&(clearTimeout(s),a(null))}function v(){o&&a(setTimeout(()=>{var P;l(n.defaultIsActive??!1),h(!1),(P=n.onHover)==null||P.call(n,!1)},400))}function b(){l(!1),u(!0)}function C(){var P;(P=n.onOpen)==null||P.call(n)}const x=n.hovered??(d&&!c),T=n.isActive??(o&&!e&&!c),S=T&&x,w=`round-button ${T?"active":""}`;let E=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(E=`${t}/${i} completed`),p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:`obi-widget-out-of-plan ${x?"hover":""} ${T?"active":""}`,onMouseEnter:m,onMouseLeave:v,children:[p("div",{className:w,style:{width:"30px",height:"30px"}}),p(lt,{className:"obi-widget-popout",open:S,trigger:null,delayMs:400,offset:5,children:[p(lt.Target,{children:p(R1,{className:T?"button":"",active:T,onClick:C,onMouseEnter:f,onMouseLeave:g,children:p("span",{className:"text",children:[p(Up,{size:16}),E]})})}),p(lt.Content,{children:p("div",{onMouseLeave:v,children:p(Rn,{className:"message",onClick:C,children:"Click to see all"})})})]}),p(Pt,{className:w,type:"minimize",onClick:b,title:"Minimize widget"})]})})}function rw(n){return p("div",{className:"obi-widget-out-of-plan-container",children:p("div",{className:"obi-widget-out-of-plan",children:p(lt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[p(lt.Target,{children:p(E1,{active:!1})}),p(lt.Content,{children:p(B1,{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 sw({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return p(kp,{open:n,onClose:t,preventOutsideClick:i,size:"medium",children:p("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function ki({title:n="",agentName:e="Obi",buttonText:t="Continue",speakingState:i=null,actionDisabled:r=!1,footer:s,href:a=null,glow:o=!1,centerVisual:l,description:c,button:u,onAction:d}){const[h,f]=ee(r),[g,m]=ee(!1),[v,b]=ee(i);return Je(()=>{g||(i==="listening"&&v!=="listening"&&h&&f(!1),i!=="listening"&&!h&&f(!0)),b(i)},[i,h]),Je(()=>{f(r)},[r]),p("div",{className:"tour-content",children:p("div",{className:"container",children:[p("div",{className:`visual ${o?"glow":""}`,children:l}),p("div",{className:"header",children:[p("h1",{className:"title",children:n}),p("div",{className:"description",children:c})]}),p("div",{className:"button-container",children:u||p(a?"a":"button",{className:`action-button ${h?"disabled":""}`,onClick:()=>{h||(f(!0),m(!0),d==null||d())},disabled:h,...a?{href:a,target:"_blank",rel:"noopener noreferrer"}:{type:"button"},children:p("span",{className:"button-text",children:(()=>{switch(i){case"thinking":return"Loading...";case"speaking":return`${e} is speaking`;default:return t}})()})})}),s&&p("div",{className:"tour-footer",children:s})]})})}function aw({logoUrl:n="",appName:e="App"}){const[t,i]=ee(!1),[r,s]=ee(!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 ow({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(ki,{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(aw,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}const{entries:Bp,setPrototypeOf:Fp,isFrozen:cw,getPrototypeOf:lw,getOwnPropertyDescriptor:uw}=Object;let{freeze:Qe,seal:gt,create:jp}=Object,{apply:Nc,construct:Lc}=typeof Reflect<"u"&&Reflect;Qe||(Qe=function(n){return n}),gt||(gt=function(n){return n}),Nc||(Nc=function(n,e,t){return n.apply(e,t)}),Lc||(Lc=function(n,e){return new n(...e)});const ea=et(Array.prototype.forEach),dw=et(Array.prototype.lastIndexOf),Vp=et(Array.prototype.pop),sr=et(Array.prototype.push),hw=et(Array.prototype.splice),ta=et(String.prototype.toLowerCase),Mc=et(String.prototype.toString),Gp=et(String.prototype.match),ar=et(String.prototype.replace),fw=et(String.prototype.indexOf),pw=et(String.prototype.trim),It=et(Object.prototype.hasOwnProperty),Ze=et(RegExp.prototype.test),or=mw(TypeError);function et(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Nc(n,e,i)}}function mw(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Lc(n,t)}}function Z(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ta;Fp&&Fp(n,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const s=t(r);s!==r&&(cw(e)||(e[i]=s),r=s)}n[r]=!0}return n}function gw(n){for(let e=0;e<n.length;e++)It(n,e)||(n[e]=null);return n}function Zt(n){const e=jp(null);for(const[t,i]of Bp(n))It(n,t)&&(Array.isArray(i)?e[t]=gw(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=Zt(i):e[t]=i);return e}function cr(n,e){for(;n!==null;){const i=uw(n,e);if(i){if(i.get)return et(i.get);if(typeof i.value=="function")return et(i.value)}n=lw(n)}function t(){return null}return t}const zp=Qe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Dc=Qe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Uc=Qe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),vw=Qe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Bc=Qe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),bw=Qe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hp=Qe(["#text"]),Wp=Qe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Fc=Qe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),qp=Qe(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),na=Qe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),yw=gt(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Tw=gt(/<%[\w\W]*|[\w\W]*%>/gm),kw=gt(/\$\{[\w\W]*/gm),Sw=gt(/^data-[\-\w.\u00B7-\uFFFF]+$/),Cw=gt(/^aria-[\-\w]+$/),Kp=gt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ww=gt(/^(?:\w+script|data):/i),xw=gt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),$p=gt(/^html$/i),_w=gt(/^[a-z][.\w]*(-[.\w]+)+$/i);var Yp=Object.freeze({__proto__:null,ARIA_ATTR:Cw,ATTR_WHITESPACE:xw,CUSTOM_ELEMENT:_w,DATA_ATTR:Sw,DOCTYPE_NAME:$p,ERB_EXPR:Tw,IS_ALLOWED_URI:Kp,IS_SCRIPT_OR_DATA:ww,MUSTACHE_EXPR:yw,TMPLIT_EXPR:kw});const lr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ew=function(){return typeof window>"u"?null:window},Rw=function(n,e){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let t=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(t=e.getAttribute(i));const r="dompurify"+(t?"#"+t:"");try{return n.createPolicy(r,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Xp=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Jp(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ew();const e=k=>Jp(k);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==lr.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n;const i=t,r=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:o,Element:l,NodeFilter:c,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=n,g=l.prototype,m=cr(g,"cloneNode"),v=cr(g,"remove"),b=cr(g,"nextSibling"),C=cr(g,"childNodes"),x=cr(g,"parentNode");if(typeof a=="function"){const k=t.createElement("template");k.content&&k.content.ownerDocument&&(t=k.content.ownerDocument)}let T,S="";const{implementation:w,createNodeIterator:E,createDocumentFragment:P,getElementsByTagName:O}=t,{importNode:B}=i;let N=Xp();e.isSupported=typeof Bp=="function"&&typeof x=="function"&&w&&w.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:H,ERB_EXPR:W,TMPLIT_EXPR:J,DATA_ATTR:Y,ARIA_ATTR:q,IS_SCRIPT_OR_DATA:fe,ATTR_WHITESPACE:ve,CUSTOM_ELEMENT:be}=Yp;let{IS_ALLOWED_URI:V}=Yp,z=null;const Q=Z({},[...zp,...Dc,...Uc,...Bc,...Hp]);let K=null;const Se=Z({},[...Wp,...Fc,...qp,...na]);let $=Object.seal(jp(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),pe=null,De=null,Ot=!0,At=!0,la=!1,ua=!0,ie=!1,Fe=!0,tt=!1,en=!1,xi=!1,tn=!1,qn=!1,da=!1,wm=!0,xm=!1;const o_="user-content-";let $c=!0,hr=!1,_i={},Ei=null;const _m=Z({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Em=null;const Rm=Z({},["audio","video","img","source","image","track"]);let Yc=null;const Pm=Z({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ha="http://www.w3.org/1998/Math/MathML",fa="http://www.w3.org/2000/svg",nn="http://www.w3.org/1999/xhtml";let Ri=nn,Xc=!1,Jc=null;const c_=Z({},[ha,fa,nn],Mc);let pa=Z({},["mi","mo","mn","ms","mtext"]),ma=Z({},["annotation-xml"]);const l_=Z({},["title","style","font","a","script"]);let fr=null;const u_=["application/xhtml+xml","text/html"],d_="text/html";let je=null,Pi=null;const h_=t.createElement("form"),Im=function(k){return k instanceof RegExp||k instanceof Function},Qc=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Pi&&Pi===k)){if((!k||typeof k!="object")&&(k={}),k=Zt(k),fr=u_.indexOf(k.PARSER_MEDIA_TYPE)===-1?d_:k.PARSER_MEDIA_TYPE,je=fr==="application/xhtml+xml"?Mc:ta,z=It(k,"ALLOWED_TAGS")?Z({},k.ALLOWED_TAGS,je):Q,K=It(k,"ALLOWED_ATTR")?Z({},k.ALLOWED_ATTR,je):Se,Jc=It(k,"ALLOWED_NAMESPACES")?Z({},k.ALLOWED_NAMESPACES,Mc):c_,Yc=It(k,"ADD_URI_SAFE_ATTR")?Z(Zt(Pm),k.ADD_URI_SAFE_ATTR,je):Pm,Em=It(k,"ADD_DATA_URI_TAGS")?Z(Zt(Rm),k.ADD_DATA_URI_TAGS,je):Rm,Ei=It(k,"FORBID_CONTENTS")?Z({},k.FORBID_CONTENTS,je):_m,pe=It(k,"FORBID_TAGS")?Z({},k.FORBID_TAGS,je):Zt({}),De=It(k,"FORBID_ATTR")?Z({},k.FORBID_ATTR,je):Zt({}),_i=It(k,"USE_PROFILES")?k.USE_PROFILES:!1,Ot=k.ALLOW_ARIA_ATTR!==!1,At=k.ALLOW_DATA_ATTR!==!1,la=k.ALLOW_UNKNOWN_PROTOCOLS||!1,ua=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ie=k.SAFE_FOR_TEMPLATES||!1,Fe=k.SAFE_FOR_XML!==!1,tt=k.WHOLE_DOCUMENT||!1,tn=k.RETURN_DOM||!1,qn=k.RETURN_DOM_FRAGMENT||!1,da=k.RETURN_TRUSTED_TYPE||!1,xi=k.FORCE_BODY||!1,wm=k.SANITIZE_DOM!==!1,xm=k.SANITIZE_NAMED_PROPS||!1,$c=k.KEEP_CONTENT!==!1,hr=k.IN_PLACE||!1,V=k.ALLOWED_URI_REGEXP||Kp,Ri=k.NAMESPACE||nn,pa=k.MATHML_TEXT_INTEGRATION_POINTS||pa,ma=k.HTML_INTEGRATION_POINTS||ma,$=k.CUSTOM_ELEMENT_HANDLING||{},k.CUSTOM_ELEMENT_HANDLING&&Im(k.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&($.tagNameCheck=k.CUSTOM_ELEMENT_HANDLING.tagNameCheck),k.CUSTOM_ELEMENT_HANDLING&&Im(k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&($.attributeNameCheck=k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),k.CUSTOM_ELEMENT_HANDLING&&typeof k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&($.allowCustomizedBuiltInElements=k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ie&&(At=!1),qn&&(tn=!0),_i&&(z=Z({},Hp),K=[],_i.html===!0&&(Z(z,zp),Z(K,Wp)),_i.svg===!0&&(Z(z,Dc),Z(K,Fc),Z(K,na)),_i.svgFilters===!0&&(Z(z,Uc),Z(K,Fc),Z(K,na)),_i.mathMl===!0&&(Z(z,Bc),Z(K,qp),Z(K,na))),k.ADD_TAGS&&(z===Q&&(z=Zt(z)),Z(z,k.ADD_TAGS,je)),k.ADD_ATTR&&(K===Se&&(K=Zt(K)),Z(K,k.ADD_ATTR,je)),k.ADD_URI_SAFE_ATTR&&Z(Yc,k.ADD_URI_SAFE_ATTR,je),k.FORBID_CONTENTS&&(Ei===_m&&(Ei=Zt(Ei)),Z(Ei,k.FORBID_CONTENTS,je)),$c&&(z["#text"]=!0),tt&&Z(z,["html","head","body"]),z.table&&(Z(z,["tbody"]),delete pe.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw or('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw or('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=k.TRUSTED_TYPES_POLICY,S=T.createHTML("")}else T===void 0&&(T=Rw(f,r)),T!==null&&typeof S=="string"&&(S=T.createHTML(""));Qe&&Qe(k),Pi=k}},Om=Z({},[...Dc,...Uc,...vw]),Am=Z({},[...Bc,...bw]),f_=function(k){let G=x(k);(!G||!G.tagName)&&(G={namespaceURI:Ri,tagName:"template"});const D=ta(k.tagName),ue=ta(G.tagName);return Jc[k.namespaceURI]?k.namespaceURI===fa?G.namespaceURI===nn?D==="svg":G.namespaceURI===ha?D==="svg"&&(ue==="annotation-xml"||pa[ue]):!!Om[D]:k.namespaceURI===ha?G.namespaceURI===nn?D==="math":G.namespaceURI===fa?D==="math"&&ma[ue]:!!Am[D]:k.namespaceURI===nn?G.namespaceURI===fa&&!ma[ue]||G.namespaceURI===ha&&!pa[ue]?!1:!Am[D]&&(l_[D]||!Om[D]):!!(fr==="application/xhtml+xml"&&Jc[k.namespaceURI]):!1},Kn=function(k){sr(e.removed,{element:k});try{x(k).removeChild(k)}catch{v(k)}},Ii=function(k,G){try{sr(e.removed,{attribute:G.getAttributeNode(k),from:G})}catch{sr(e.removed,{attribute:null,from:G})}if(G.removeAttribute(k),k==="is")if(tn||qn)try{Kn(G)}catch{}else try{G.setAttribute(k,"")}catch{}},Nm=function(k){let G=null,D=null;if(xi)k="<remove></remove>"+k;else{const Ee=Gp(k,/^[\r\n\t ]+/);D=Ee&&Ee[0]}fr==="application/xhtml+xml"&&Ri===nn&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const ue=T?T.createHTML(k):k;if(Ri===nn)try{G=new h().parseFromString(ue,fr)}catch{}if(!G||!G.documentElement){G=w.createDocument(Ri,"template",null);try{G.documentElement.innerHTML=Xc?S:ue}catch{}}const We=G.body||G.documentElement;return k&&D&&We.insertBefore(t.createTextNode(D),We.childNodes[0]||null),Ri===nn?O.call(G,tt?"html":"body")[0]:tt?G.documentElement:We},Lm=function(k){return E.call(k.ownerDocument||k,k,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Zc=function(k){return k instanceof d&&(typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||!(k.attributes instanceof u)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function")},Mm=function(k){return typeof o=="function"&&k instanceof o};function rn(k,G,D){ea(k,ue=>{ue.call(e,G,D,Pi)})}const Dm=function(k){let G=null;if(rn(N.beforeSanitizeElements,k,null),Zc(k))return Kn(k),!0;const D=je(k.nodeName);if(rn(N.uponSanitizeElement,k,{tagName:D,allowedTags:z}),Fe&&k.hasChildNodes()&&!Mm(k.firstElementChild)&&Ze(/<[/\w!]/g,k.innerHTML)&&Ze(/<[/\w!]/g,k.textContent)||k.nodeType===lr.progressingInstruction||Fe&&k.nodeType===lr.comment&&Ze(/<[/\w]/g,k.data))return Kn(k),!0;if(!z[D]||pe[D]){if(!pe[D]&&Bm(D)&&($.tagNameCheck instanceof RegExp&&Ze($.tagNameCheck,D)||$.tagNameCheck instanceof Function&&$.tagNameCheck(D)))return!1;if($c&&!Ei[D]){const ue=x(k)||k.parentNode,We=C(k)||k.childNodes;if(We&&ue){const Ee=We.length;for(let sn=Ee-1;sn>=0;--sn){const Nt=m(We[sn],!0);Nt.__removalCount=(k.__removalCount||0)+1,ue.insertBefore(Nt,b(k))}}}return Kn(k),!0}return k instanceof l&&!f_(k)||(D==="noscript"||D==="noembed"||D==="noframes")&&Ze(/<\/no(script|embed|frames)/i,k.innerHTML)?(Kn(k),!0):(ie&&k.nodeType===lr.text&&(G=k.textContent,ea([H,W,J],ue=>{G=ar(G,ue," ")}),k.textContent!==G&&(sr(e.removed,{element:k.cloneNode()}),k.textContent=G)),rn(N.afterSanitizeElements,k,null),!1)},Um=function(k,G,D){if(wm&&(G==="id"||G==="name")&&(D in t||D in h_))return!1;if(!(At&&!De[G]&&Ze(Y,G))&&!(Ot&&Ze(q,G))){if(!K[G]||De[G]){if(!(Bm(k)&&($.tagNameCheck instanceof RegExp&&Ze($.tagNameCheck,k)||$.tagNameCheck instanceof Function&&$.tagNameCheck(k))&&($.attributeNameCheck instanceof RegExp&&Ze($.attributeNameCheck,G)||$.attributeNameCheck instanceof Function&&$.attributeNameCheck(G))||G==="is"&&$.allowCustomizedBuiltInElements&&($.tagNameCheck instanceof RegExp&&Ze($.tagNameCheck,D)||$.tagNameCheck instanceof Function&&$.tagNameCheck(D))))return!1}else if(!Yc[G]&&!Ze(V,ar(D,ve,""))&&!((G==="src"||G==="xlink:href"||G==="href")&&k!=="script"&&fw(D,"data:")===0&&Em[k])&&!(la&&!Ze(fe,ar(D,ve,"")))&&D)return!1}return!0},Bm=function(k){return k!=="annotation-xml"&&Gp(k,be)},Fm=function(k){rn(N.beforeSanitizeAttributes,k,null);const{attributes:G}=k;if(!G||Zc(k))return;const D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0};let ue=G.length;for(;ue--;){const We=G[ue],{name:Ee,namespaceURI:sn,value:Nt}=We,zt=je(Ee),el=Nt;let Ye=Ee==="value"?el:pw(el);if(D.attrName=zt,D.attrValue=Ye,D.keepAttr=!0,D.forceKeepAttr=void 0,rn(N.uponSanitizeAttribute,k,D),Ye=D.attrValue,xm&&(zt==="id"||zt==="name")&&(Ii(Ee,k),Ye=o_+Ye),Fe&&Ze(/((--!?|])>)|<\/(style|title)/i,Ye)){Ii(Ee,k);continue}if(D.forceKeepAttr)continue;if(!D.keepAttr){Ii(Ee,k);continue}if(!ua&&Ze(/\/>/i,Ye)){Ii(Ee,k);continue}ie&&ea([H,W,J],m_=>{Ye=ar(Ye,m_," ")});const jm=je(k.nodeName);if(!Um(jm,zt,Ye)){Ii(Ee,k);continue}if(T&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!sn)switch(f.getAttributeType(jm,zt)){case"TrustedHTML":{Ye=T.createHTML(Ye);break}case"TrustedScriptURL":{Ye=T.createScriptURL(Ye);break}}if(Ye!==el)try{sn?k.setAttributeNS(sn,Ee,Ye):k.setAttribute(Ee,Ye),Zc(k)?Kn(k):Vp(e.removed)}catch{Ii(Ee,k)}}rn(N.afterSanitizeAttributes,k,null)},p_=function k(G){let D=null;const ue=Lm(G);for(rn(N.beforeSanitizeShadowDOM,G,null);D=ue.nextNode();)rn(N.uponSanitizeShadowNode,D,null),Dm(D),Fm(D),D.content instanceof s&&k(D.content);rn(N.afterSanitizeShadowDOM,G,null)};return e.sanitize=function(k){let G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},D=null,ue=null,We=null,Ee=null;if(Xc=!k,Xc&&(k="<!-->"),typeof k!="string"&&!Mm(k))if(typeof k.toString=="function"){if(k=k.toString(),typeof k!="string")throw or("dirty is not a string, aborting")}else throw or("toString is not a function");if(!e.isSupported)return k;if(en||Qc(G),e.removed=[],typeof k=="string"&&(hr=!1),hr){if(k.nodeName){const zt=je(k.nodeName);if(!z[zt]||pe[zt])throw or("root node is forbidden and cannot be sanitized in-place")}}else if(k instanceof o)D=Nm("<!---->"),ue=D.ownerDocument.importNode(k,!0),ue.nodeType===lr.element&&ue.nodeName==="BODY"||ue.nodeName==="HTML"?D=ue:D.appendChild(ue);else{if(!tn&&!ie&&!tt&&k.indexOf("<")===-1)return T&&da?T.createHTML(k):k;if(D=Nm(k),!D)return tn?null:da?S:""}D&&xi&&Kn(D.firstChild);const sn=Lm(hr?k:D);for(;We=sn.nextNode();)Dm(We),Fm(We),We.content instanceof s&&p_(We.content);if(hr)return k;if(tn){if(qn)for(Ee=P.call(D.ownerDocument);D.firstChild;)Ee.appendChild(D.firstChild);else Ee=D;return(K.shadowroot||K.shadowrootmode)&&(Ee=B.call(i,Ee,!0)),Ee}let Nt=tt?D.outerHTML:D.innerHTML;return tt&&z["!doctype"]&&D.ownerDocument&&D.ownerDocument.doctype&&D.ownerDocument.doctype.name&&Ze($p,D.ownerDocument.doctype.name)&&(Nt="<!DOCTYPE "+D.ownerDocument.doctype.name+`>
43
+ `+Nt),ie&&ea([H,W,J],zt=>{Nt=ar(Nt,zt," ")}),T&&da?T.createHTML(Nt):Nt},e.setConfig=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Qc(k),en=!0},e.clearConfig=function(){Pi=null,en=!1},e.isValidAttribute=function(k,G,D){Pi||Qc({});const ue=je(k),We=je(G);return Um(ue,We,D)},e.addHook=function(k,G){typeof G=="function"&&sr(N[k],G)},e.removeHook=function(k,G){if(G!==void 0){const D=dw(N[k],G);return D===-1?void 0:hw(N[k],D,1)[0]}return Vp(N[k])},e.removeHooks=function(k){N[k]=[]},e.removeAllHooks=function(){N=Xp()},e}var Pw=Jp();function Iw({}){return p("div",{className:"obi-static-voice",children:[p("div",{className:"obi-static-voice-visual-title",children:"AI Guided Tutorial"}),p("div",{style:{transform:"scale(1.25) translateY(-4px)"},children:p(Pc,{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 Ow({session:n,speakingState:e,onAction:t}){const i="Sessions are securely recorded for quality improvement purposes.",r=Xs(()=>{var l;const o=(l=n.legalFooter)==null?void 0:l.trim();return o?Pw.sanitize(o):null},[n.legalFooter]),s=Rt(null);Je(()=>{if(!r)return;const o=s.current;o&&o.querySelectorAll("a").forEach(l=>{l.setAttribute("target","_blank");const c=(l.getAttribute("rel")||"").split(/\s+/);c.includes("noopener")||c.push("noopener"),c.includes("noreferrer")||c.push("noreferrer"),l.setAttribute("rel",c.filter(Boolean).join(" ")),l.style.color="black"})},[r]);const a=r?p("span",{ref:s,dangerouslySetInnerHTML:{__html:r}}):i;return p(ki,{title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,footer:a,buttonText:"Get started",agentName:n.agentName||"Obi",speakingState:e,centerVisual:p(Iw,{}),onAction:t})}function Aw(){const n={host:{display:"block",position:"relative",width:"100%",height:"161px"},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:`
44
44
  @keyframes pointToAllow {
45
45
  0%, 100% { transform: translate(0, 0); }
46
46
  50% { transform: translate(2px, -1px); }
@@ -52,5 +52,5 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
52
52
  100% { transform: translateX(344px); }
53
53
  }
54
54
  `}),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 Dw({}){const n={host:{display:"block",height:"161px"},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:"'Inter', 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(Mw,{})})]})})}function Uw({session:n,speakingState:e,onAction:t}){return p(ki,{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(Dw,{}),actionDisabled:!0,onAction:t})}function Bw({session:n,speakingState:e,spectrum:t,onAction:i}){return p(ki,{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(Qp,{spectrum:t}),actionDisabled:!0,onAction:i})}function Fw({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 jw({courses:n=[],selectedCourseId:e=null,loading:t=!1,error:i="",onCourseSelect:r}){const[s,a]=ee(""),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(Fw,{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 Vw({open:n,courses:e=[],loading:t=!1,error:i="",title:r="AI Coach",productName:s,onClose:a,onCourseSelect:o,onCourseHighlight:l}){const[c,u]=ee(null),d=f=>{u(f),l==null||l(f)},h=()=>{c&&o&&o(c)};return p(kp,{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(Up,{})}),p("div",{className:"title-section",children:t?p($e,{children:[p("div",{className:"skeleton skeleton-title"}),p("div",{className:"skeleton skeleton-subtitle"})]}):p($e,{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(jw,{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 Gw({session:n,sessionState:e,speakingState:t,spectrum:i,onStart:r,onContinue:s,onShareMicrophone:a,onShareScreen:o,onModalChange:l}){const[c,u]=ee(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 Xs(()=>{switch(e){case null:case"connecting":case"connected":return d("session-start"),p(Ow,{session:n,speakingState:t,onAction:h});case"volume-check":return d("voice-guidance"),p(Lw,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-check":return d("overview"),p(Bw,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-share":return d("share-mic"),p(Nw,{session:n,speakingState:t,onAction:h});case"screen-share":return d("share-screen"),p(Uw,{session:n,speakingState:t,onAction:h});case"navigate":return d("navigate"),p(ow,{session:n,speakingState:t,onAction:h});default:return null}},[e,t,r,s,a,o])}function zw(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]=ee(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(sw,{open:m,onClose:g,preventOutsideClick:!0,children:()=>p(Gw,{session:e,sessionState:t,speakingState:i,spectrum:r,onStart:a,onContinue:o,onShareMicrophone:l,onShareScreen:c,onModalChange:f})})}const Hw={identify:()=>{},track:()=>{},page:()=>{},reset:()=>{}};function Si(){return Hw}const Ww=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Zp="9.23.0",Ci=globalThis;function qw(n,e,t=Ci){const i=t.__SENTRY__=t.__SENTRY__||{},r=i[Zp]=i[Zp]||{};return r[n]||(r[n]=e())}const Kw="Sentry Logger ",em=["debug","info","warn","error","log","assert","trace"],tm={};function $w(n){if(!("console"in Ci))return n();const e=Ci.console,t={},i=Object.keys(tm);i.forEach(r=>{const s=tm[r];t[r]=e[r],e[r]=s});try{return n()}finally{i.forEach(r=>{e[r]=t[r]})}}function Yw(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return Ww?em.forEach(t=>{e[t]=(...i)=>{n&&$w(()=>{Ci.console[t](`${Kw}[${t}]:`,...i)})}}):em.forEach(t=>{e[t]=()=>{}}),e}qw("logger",Yw);const nm=1e3;function Xw(){return Date.now()/nm}function Jw(){const{performance:n}=Ci;if(!(n!=null&&n.now))return Xw;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/nm}Jw();const im=50,wi="?",rm=/\(error: (.*)\)/,sm=/captureMessage|captureException/;function Qw(...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(`
55
- `);for(let o=i;o<a.length;o++){const l=a[o];if(l.length>1024)continue;const c=rm.test(l)?l.replace(rm,"$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>=im+r)break}}return Zw(s.slice(r))}}function Zw(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(ia(e).function||"")&&e.pop(),e.reverse(),sm.test(ia(e).function||"")&&(e.pop(),sm.test(ia(e).function||"")&&e.pop()),e.slice(0,im).map(t=>({...t,filename:t.filename||ia(e).filename,function:t.function||wi}))}function ia(n){return n[n.length-1]||{}}var am;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(am||(am={})),Ci._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const ex=30,tx=50;function jc(n,e,t,i){const r={filename:n,function:e==="<anonymous>"?wi:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}const nx=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ix=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,rx=/\((\S*)(?::(\d+))(?::(\d+))\)/,sx=n=>{const e=nx.exec(n);if(e){const[,i,r,s]=e;return jc(i,wi,+r,+s)}const t=ix.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=rx.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=om(t[1]||wi,t[2]);return jc(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},ax=[ex,sx],ox=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,cx=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;Qw(...[ax,[tx,n=>{const e=ox.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=cx.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]||wi;return[i,t]=om(i,t),jc(t,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const om=(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]:wi,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function lx(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 ux(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 cm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ur=typeof Uint8Array>"u"?[]:new Uint8Array(256),ra=0;ra<cm.length;ra++)ur[cm.charCodeAt(ra)]=ra;for(var dx=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=ur[n.charCodeAt(i)],a=ur[n.charCodeAt(i+1)],o=ur[n.charCodeAt(i+2)],l=ur[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},hx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},fx=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},Hn=5,Vc=6+5,Gc=2,px=Vc-Hn,lm=65536>>Hn,mx=1<<Hn,zc=mx-1,gx=1024>>Hn,vx=lm+gx,bx=vx,yx=32,Tx=bx+yx,kx=65536>>Vc,Sx=1<<px,Cx=Sx-1,um=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},wx=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},xx=function(n,e){var t=dx(n),i=Array.isArray(t)?fx(t):new Uint32Array(t),r=Array.isArray(t)?hx(t):new Uint16Array(t),s=24,a=um(r,s/2,i[4]/2),o=i[5]===2?um(r,(s+i[4])/2):wx(i,Math.ceil((s+i[4])/4));return new _x(i[0],i[1],i[2],i[3],a,o)},_x=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>>Hn],t=(t<<Gc)+(e&zc),this.data[t];if(e<=65535)return t=this.index[lm+(e-55296>>Hn)],t=(t<<Gc)+(e&zc),this.data[t];if(e<this.highStart)return t=Tx-kx+(e>>Vc),t=this.index[t],t+=e>>Hn&Cx,t=this.index[t],t=(t<<Gc)+(e&zc),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),dm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ex=typeof Uint8Array>"u"?[]:new Uint8Array(256),sa=0;sa<dm.length;sa++)Ex[dm.charCodeAt(sa)]=sa;var hm=null;function Rx(n){return lx(this,void 0,void 0,function(){var e;return ux(this,function(t){switch(t.label){case 0:return hm!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw new Error("Invalid graphemes response");hm=xx(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}for(var fm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Px=typeof Uint8Array>"u"?[]:new Uint8Array(256),aa=0;aa<fm.length;aa++)Px[fm.charCodeAt(aa)]=aa;function Ix(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 Ox(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 pm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dr=typeof Uint8Array>"u"?[]:new Uint8Array(256),oa=0;oa<pm.length;oa++)dr[pm.charCodeAt(oa)]=oa;for(var Ax=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=dr[n.charCodeAt(i)],a=dr[n.charCodeAt(i+1)],o=dr[n.charCodeAt(i+2)],l=dr[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},Nx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},Lx=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},Wn=5,Hc=6+5,Wc=2,Mx=Hc-Wn,mm=65536>>Wn,Dx=1<<Wn,qc=Dx-1,Ux=1024>>Wn,Bx=mm+Ux,Fx=Bx,jx=32,Vx=Fx+jx,Gx=65536>>Hc,zx=1<<Mx,Hx=zx-1,gm=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Wx=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},qx=function(n,e){var t=Ax(n),i=Array.isArray(t)?Lx(t):new Uint32Array(t),r=Array.isArray(t)?Nx(t):new Uint16Array(t),s=24,a=gm(r,s/2,i[4]/2),o=i[5]===2?gm(r,(s+i[4])/2):Wx(i,Math.ceil((s+i[4])/4));return new Kx(i[0],i[1],i[2],i[3],a,o)},Kx=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>>Wn],t=(t<<Wc)+(e&qc),this.data[t];if(e<=65535)return t=this.index[mm+(e-55296>>Wn)],t=(t<<Wc)+(e&qc),this.data[t];if(e<this.highStart)return t=Vx-Gx+(e>>Hc),t=this.index[t],t+=e>>Wn&Hx,t=this.index[t],t=(t<<Wc)+(e&qc),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),vm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$x=typeof Uint8Array>"u"?[]:new Uint8Array(256),ca=0;ca<vm.length;ca++)$x[vm.charCodeAt(ca)]=ca;var bm=null;function Yx(n){return Ix(this,void 0,void 0,function(){var e;return Ox(this,function(t){switch(t.label){case 0:return bm!==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");bm=qx(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}const Xx=`:root,:host{--obi-modal-padding: 32px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 24px;--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: 372px;--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);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:block;flex-grow:1;flex-direction:column;align-items:center;padding:0;width:100%;margin-bottom:16px}.tour-content .title{width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:700;font-size:24px;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0 0 12px}.tour-content .subtitle{width:100%;font-family:Inter,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{flex-grow:0;flex-shrink:0;display:flex;align-items:center;justify-content:center;position:relative;margin-bottom:24px}.tour-content .visual.glow{width:390px;border-radius:15px;background-color:var(--obi-color-tint)}.tour-content .description{width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:400;font-size:16px;color:#757575!important;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b}.tour-content .button-container{flex-grow:0;display:flex;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;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:Inter,sans-serif;font-style:normal;font-weight:500;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{height:100%;flex:1;display:flex;flex-direction:column}.footer{height:24px;display:flex;align-items:center;justify-content:flex-end;font-family:Inter,sans-serif;font-size:8px;font-weight:200;margin-top:8px}.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-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-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-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-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-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:14px;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:6px 0;height:100%;flex:1;min-width:0;cursor:pointer}.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;cursor:pointer}.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-course-progress .obi-widget-popout,.obi-course-progress .obi-widget-popout .content{z-index:800}.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-widget-course-progress{display:block;width:100%;max-width:220px;max-height:40px;opacity:1;transform:translateY(0);overflow:visible;position:relative;z-index:800;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel .obi-widget-course-progress.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{height:96px;display:flex;flex-direction:column;align-items:center;justify-content:center}.obi-static-voice-visual-title{font-family:Inter,sans-serif;font-style:normal;font-weight:600;font-size:14px;color:var(--obi-color-primary);background-color:var(--obi-color-tint);padding:8px 12px;border-radius:20px;margin-bottom:24px}.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
+ `);for(let o=i;o<a.length;o++){const l=a[o];if(l.length>1024)continue;const c=rm.test(l)?l.replace(rm,"$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>=im+r)break}}return Zw(s.slice(r))}}function Zw(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(ia(e).function||"")&&e.pop(),e.reverse(),sm.test(ia(e).function||"")&&(e.pop(),sm.test(ia(e).function||"")&&e.pop()),e.slice(0,im).map(t=>({...t,filename:t.filename||ia(e).filename,function:t.function||wi}))}function ia(n){return n[n.length-1]||{}}var am;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(am||(am={})),Ci._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const ex=30,tx=50;function jc(n,e,t,i){const r={filename:n,function:e==="<anonymous>"?wi:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}const nx=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ix=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,rx=/\((\S*)(?::(\d+))(?::(\d+))\)/,sx=n=>{const e=nx.exec(n);if(e){const[,i,r,s]=e;return jc(i,wi,+r,+s)}const t=ix.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=rx.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=om(t[1]||wi,t[2]);return jc(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},ax=[ex,sx],ox=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,cx=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;Qw(...[ax,[tx,n=>{const e=ox.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=cx.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]||wi;return[i,t]=om(i,t),jc(t,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const om=(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]:wi,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function lx(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 ux(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 cm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ur=typeof Uint8Array>"u"?[]:new Uint8Array(256),ra=0;ra<cm.length;ra++)ur[cm.charCodeAt(ra)]=ra;for(var dx=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=ur[n.charCodeAt(i)],a=ur[n.charCodeAt(i+1)],o=ur[n.charCodeAt(i+2)],l=ur[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},hx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},fx=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},Hn=5,Vc=6+5,Gc=2,px=Vc-Hn,lm=65536>>Hn,mx=1<<Hn,zc=mx-1,gx=1024>>Hn,vx=lm+gx,bx=vx,yx=32,Tx=bx+yx,kx=65536>>Vc,Sx=1<<px,Cx=Sx-1,um=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},wx=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},xx=function(n,e){var t=dx(n),i=Array.isArray(t)?fx(t):new Uint32Array(t),r=Array.isArray(t)?hx(t):new Uint16Array(t),s=24,a=um(r,s/2,i[4]/2),o=i[5]===2?um(r,(s+i[4])/2):wx(i,Math.ceil((s+i[4])/4));return new _x(i[0],i[1],i[2],i[3],a,o)},_x=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>>Hn],t=(t<<Gc)+(e&zc),this.data[t];if(e<=65535)return t=this.index[lm+(e-55296>>Hn)],t=(t<<Gc)+(e&zc),this.data[t];if(e<this.highStart)return t=Tx-kx+(e>>Vc),t=this.index[t],t+=e>>Hn&Cx,t=this.index[t],t=(t<<Gc)+(e&zc),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),dm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ex=typeof Uint8Array>"u"?[]:new Uint8Array(256),sa=0;sa<dm.length;sa++)Ex[dm.charCodeAt(sa)]=sa;var hm=null;function Rx(n){return lx(this,void 0,void 0,function(){var e;return ux(this,function(t){switch(t.label){case 0:return hm!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw new Error("Invalid graphemes response");hm=xx(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}for(var fm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Px=typeof Uint8Array>"u"?[]:new Uint8Array(256),aa=0;aa<fm.length;aa++)Px[fm.charCodeAt(aa)]=aa;function Ix(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 Ox(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 pm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dr=typeof Uint8Array>"u"?[]:new Uint8Array(256),oa=0;oa<pm.length;oa++)dr[pm.charCodeAt(oa)]=oa;for(var Ax=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=dr[n.charCodeAt(i)],a=dr[n.charCodeAt(i+1)],o=dr[n.charCodeAt(i+2)],l=dr[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},Nx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},Lx=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},Wn=5,Hc=6+5,Wc=2,Mx=Hc-Wn,mm=65536>>Wn,Dx=1<<Wn,qc=Dx-1,Ux=1024>>Wn,Bx=mm+Ux,Fx=Bx,jx=32,Vx=Fx+jx,Gx=65536>>Hc,zx=1<<Mx,Hx=zx-1,gm=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Wx=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},qx=function(n,e){var t=Ax(n),i=Array.isArray(t)?Lx(t):new Uint32Array(t),r=Array.isArray(t)?Nx(t):new Uint16Array(t),s=24,a=gm(r,s/2,i[4]/2),o=i[5]===2?gm(r,(s+i[4])/2):Wx(i,Math.ceil((s+i[4])/4));return new Kx(i[0],i[1],i[2],i[3],a,o)},Kx=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>>Wn],t=(t<<Wc)+(e&qc),this.data[t];if(e<=65535)return t=this.index[mm+(e-55296>>Wn)],t=(t<<Wc)+(e&qc),this.data[t];if(e<this.highStart)return t=Vx-Gx+(e>>Hc),t=this.index[t],t+=e>>Wn&Hx,t=this.index[t],t=(t<<Wc)+(e&qc),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),vm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$x=typeof Uint8Array>"u"?[]:new Uint8Array(256),ca=0;ca<vm.length;ca++)$x[vm.charCodeAt(ca)]=ca;var bm=null;function Yx(n){return Ix(this,void 0,void 0,function(){var e;return Ox(this,function(t){switch(t.label){case 0:return bm!==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");bm=qx(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}const Xx=`:root,:host{--obi-modal-padding: 32px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 24px;--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: 372px;--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:block;flex-grow:1;flex-direction:column;align-items:center;padding:0;width:100%;margin-bottom:16px}.tour-content .title{width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:700;font-size:24px;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0 0 12px}.tour-content .subtitle{width:100%;font-family:Inter,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{flex-grow:0;flex-shrink:0;display:flex;align-items:center;justify-content:center;position:relative;margin-bottom:24px}.tour-content .visual.glow{width:390px;border-radius:15px;background-color:var(--obi-color-tint)}.tour-content .description{width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:400;font-size:16px;color:#757575!important;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b}.tour-content .button-container{flex-grow:0;display:flex;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;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:Inter,sans-serif;font-style:normal;font-weight:500;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{height:100%;flex:1;display:flex;flex-direction:column}.tour-footer{width:100%!important;text-align:center;min-height:24px;display:flex;align-items:flex-end;justify-content:center;font-family:Inter,sans-serif;font-size:8px;font-weight:200;margin-top:8px}.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-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-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-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-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-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:14px;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:6px 0;height:100%;flex:1;min-width:0;cursor:pointer}.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;cursor:pointer}.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-course-progress .obi-widget-popout,.obi-course-progress .obi-widget-popout .content{z-index:800}.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-widget-course-progress{display:block;width:100%;max-width:220px;max-height:40px;opacity:1;transform:translateY(0);overflow:visible;position:relative;z-index:800;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel .obi-widget-course-progress.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{height:96px;display:flex;flex-direction:column;align-items:center;justify-content:center}.obi-static-voice-visual-title{font-family:Inter,sans-serif;font-style:normal;font-weight:600;font-size:14px;color:var(--obi-color-primary);background-color:var(--obi-color-tint);padding:8px 12px;border-radius:20px;margin-bottom:24px}.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%}
56
56
  `;function Jx(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function Qx(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(i=>{try{const r=Jx(i);return r.test(t)||r.test(n)}catch(r){return console.warn(`Invalid URL pattern: ${i}`,r),!1}})}function Kc(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return Qx(e,n)}function Zx(n){var O,B,N,H,W,J,Y,q,fe,ve,be;const[e,t]=ee(!1),[i,r]=ee(!1),[s,a]=ee(!1),[o,l]=ee(null),c=e_(n.sdk,u,n.shadowHost,l,a);function u(V){var z;(z=c.client)!=null&&z.session||(V?P():t(!1))}if(!c.client)return null;const d=c.client.planIsCompleted.filter(Boolean).length===c.client.plans.length,h=t_((O=c.client.product)==null?void 0:O.widget_url_blacklist),f=d?c.completedWidgetDisplay||((B=c.client.product)==null?void 0:B.completed_widget_display):c.widgetDisplay||((N=c.client.product)==null?void 0:N.widget_display),g=c.widgetPosition||((H=c.client.product)==null?void 0:H.widget_position);let m=c.isActive;((J=(W=c.client)==null?void 0:W.product)==null?void 0:J.name)==="Canibuild"&&(m=!0);const v=c.client.session,b=!!v,C=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 T=v==null?void 0:v.isPaused,S=b||c.client.state==="ready"&&m&&!h&&(f!=="invisible"||c.client.selectedPlan),w=()=>{var V,z,Q,K,Se,$,pe;return{name:(V=c.client.selectedPlan)==null?void 0:V.name,description:(z=c.client.selectedPlan)==null?void 0:z.description,appName:(Q=c.client.product)==null?void 0:Q.name,appLogoUrl:((K=c.client.product)==null?void 0:K.logo_url)||"",url:(Se=c.client.product)==null?void 0:Se.url,agentName:(($=c.client.product)==null?void 0:$.agent_name)||"Obi",legalFooter:((pe=c.client.product)==null?void 0:pe.legal_footer_text)||void 0}},E=g==="bottom-right"?{position:"fixed",right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",left:"50%",transform:"translateX(-50%)",width:"max-content"};C?E.top="calc(100vh - 100px)":E.bottom="20px";const P=()=>{const V=c.client;if(!V)return;const z=V.plans||[];if(z.length===1){const[Q]=z;V.selectedPlanUuid!==Q.uuid&&(V.selectPlan(Q),Si().track("course-get-started",{courseName:Q.name,courseUuid:Q.uuid})),t(!1),r(!0);return}t(!0)};return p("div",{children:[e&&p(Vw,{open:e,courses:c.client.plans.map((V,z)=>{var Q,K;return{id:V.uuid,name:V.name,description:V.description||"",duration:V.duration||0,completed:((K=(Q=c.client)==null?void 0:Q.planIsCompleted)==null?void 0:K[z])||!1}}),loading:!1,title:((Y=c.client.product)==null?void 0:Y.assistant_subtitle)||void 0,productName:((q=c.client.product)==null?void 0:q.name)||"",onCourseHighlight:V=>{V&&Si().track("course-selected",{courseName:V.name,courseUuid:V.id})},onCourseSelect:V=>{const z=c.client.plans.find(Q=>Q.uuid===V.id)||null;z&&(z==null?void 0:z.uuid)!==c.client.selectedPlanUuid&&(c.client.selectPlan(z),t(!1),r(!0),Si().track("course-get-started",{courseName:V.name,courseUuid:V.id}))},onClose:V=>{V==="user-initiated"&&c.client.selectPlan(null),t(!1)}}),S&&p($e,{children:[p("div",{style:E,children:p(nw,{inPlan:b,isActive:i?!1:void 0,defaultIsActive:f!=="minimized",isPaused:T,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:P,onCancelClick:()=>{},onCancelAbort:()=>{},onCancel:()=>{var V;(V=c.client.session)==null||V.stop()},onCancelReason:(V,z)=>{},onPause:()=>{var V,z;(z=(V=c.client.session)==null?void 0:V.pause)==null||z.call(V)},onUnpause:()=>{var V,z;(z=(V=c.client.session)==null?void 0:V.unpause)==null||z.call(V)},onMessagingChange:V=>{var z,Q,K,Se;a(!1),V?(Q=(z=c.client.session)==null?void 0:z.muteMicrophone)==null||Q.call(z):(Se=(K=c.client.session)==null?void 0:K.unmuteMicrophone)==null||Se.call(K)},onMessageChange:V=>{Si().track("chat-input-provided",{message:V,length:V.length})},onMessage:V=>{c.say(V),a(!1),Si().track("chat-message-sent",{message:V,length:V.length})},onHover:V=>{},onOneClickAction:V=>{a(!1)},onMinimize:()=>{},agentName:((fe=c.client.product)==null?void 0:fe.agent_name)||"Obi",completedTutorials:((ve=c.client.product)==null?void 0:ve.widget_show_progress)===!1?void 0:c.client.planIsCompleted.filter(Boolean).length,totalTutorials:((be=c.client.product)==null?void 0:be.widget_show_progress)===!1?void 0:c.client.plans.length})}),!!c.client.selectedPlan&&p(zw,{open:!0,session:w(),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:V=>{},onClose:(V,z)=>{var Q,K;V==="user-initiated"&&(((Q=c.client.session)==null?void 0:Q.state)==="mic-share"?(K=c.client.session)==null||K.shareMicrophoneFailed():c.client.stopSession()),r(!1)},onStart:()=>{c.client.selectedPlanUuid&&c.startSession()},onContinue:()=>{v==null||v.continue()},onShareMicrophone:()=>{v==null||v.shareMicrophone()}})]})]})}function e_(n,e,t,i,r){const[s,a]=ee(0),[o,l]=ee(null);return Je(()=>{n.on("showMenu",c=>{e(c)}),n.on("configUpdated",()=>{a(c=>c+1)})},[n]),Je(()=>{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]),Je(()=>{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 t_(n){const[e,t]=ee(()=>Kc(n));return Je(()=>{t(Kc(n))},[n]),Je(()=>{n_();const i=()=>{t(Kc(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 n_(){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 i_(n){if(document.querySelector("obi-widget"))return;r_();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(Xx),t.adoptedStyleSheets=[r],y1(p(Zx,{sdk:n,shadowHost:e}),i),console.log("[obi-sdk] widget mounted")}function r_(){ym("https://fonts.cdnfonts.com/css/satoshi"),ym("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function ym(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const Tm="49206C6F7665204F6269_session",km="obi-url-params";class s_ extends ga{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=Hs.deserialise(i,e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)}),t?this._resumed=!0:localStorage.removeItem("obi-client")}catch(r){console.error("[obi] error loading cached client",r)}t||(t=new Hs(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,g;r==="ready"&&this.updateConfig({isActive:((s=window==null?void 0:window.obiWidgetConfig)==null?void 0:s.isActive)??((a=this.client)==null?void 0:a.showWidget),primaryColour:((l=(o=this.client)==null?void 0:o.product)==null?void 0:l.primary_color)||"#9500FF",widgetDisplay:((c=window==null?void 0:window.obiWidgetConfig)==null?void 0:c.widgetDisplay)||((d=(u=this.client)==null?void 0:u.product)==null?void 0:d.widget_display)||"regular",completedWidgetDisplay:((h=window==null?void 0:window.obiWidgetConfig)==null?void 0:h.completedWidgetDisplay)||((g=(f=this.client)==null?void 0:f.product)==null?void 0:g.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={}){var t;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((t=window==null?void 0:window.obiWidgetConfig)==null?void 0:t.user)||void 0}).then(()=>{this.emit("initialised"),this.dispatchCommandQueue()}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}):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,r;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;(r=this.client)==null||r.identity;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(s=>{console.error("[obi] error initialising client",s),this.emit("error",s)}),e!=null&&e.email&&Si().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(km)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((s,a)=>{e[a]=s});const t=e[Tm];if(!t)return null;const i=new URL(window.location.href);i.searchParams.delete(Tm),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(km),this.passivePlanUuid=t}mountWidget(){i_(this)}async captureScreen(){try{await Rx(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await Yx(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 xT(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var t;const e=((t=this.client)==null?void 0:t.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}}async function Sm(n,e){let t;try{t=window}catch{console.warn("[obi] no window object found"),t={}}return a_({appToken:n,window:t,init:e})}async function a_({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 s_(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function Cm(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Sm(void 0,Cm)}):Sm(void 0,Cm)})();